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: an example under each mode, with Use this example
Adarshbdb99e93cdfd
diff --git a/public/examples/genjutsu-character/1/in-clip.384.webp b/public/examples/genjutsu-character/1/in-clip.384.webpnew file mode 100644index 00000000..483caeb8Binary files /dev/null and b/public/examples/genjutsu-character/1/in-clip.384.webp differdiff --git a/public/examples/genjutsu-character/1/in-clip.jpg b/public/examples/genjutsu-character/1/in-clip.jpgnew file mode 100644index 00000000..1fb432d3Binary files /dev/null and b/public/examples/genjutsu-character/1/in-clip.jpg differdiff --git a/public/examples/genjutsu-character/1/in-photo1.384.webp b/public/examples/genjutsu-character/1/in-photo1.384.webpnew file mode 100644index 00000000..edc55f38Binary files /dev/null and b/public/examples/genjutsu-character/1/in-photo1.384.webp differdiff --git a/public/examples/genjutsu-character/1/in-photo1.jpg b/public/examples/genjutsu-character/1/in-photo1.jpgnew file mode 100644index 00000000..58cfe351Binary files /dev/null and b/public/examples/genjutsu-character/1/in-photo1.jpg differdiff --git a/public/examples/genjutsu-character/1/in-photo2.384.webp b/public/examples/genjutsu-character/1/in-photo2.384.webpnew file mode 100644index 00000000..cc73a511Binary files /dev/null and b/public/examples/genjutsu-character/1/in-photo2.384.webp differdiff --git a/public/examples/genjutsu-character/1/in-photo2.jpg b/public/examples/genjutsu-character/1/in-photo2.jpgnew file mode 100644index 00000000..b54d5539Binary files /dev/null and b/public/examples/genjutsu-character/1/in-photo2.jpg differdiff --git a/public/examples/genjutsu-character/1/show.mp4 b/public/examples/genjutsu-character/1/show.mp4new file mode 100644index 00000000..3d1932f4Binary files /dev/null and b/public/examples/genjutsu-character/1/show.mp4 differdiff --git a/public/examples/genjutsu-character/1/show.peak.webp b/public/examples/genjutsu-character/1/show.peak.webpnew file mode 100644index 00000000..e411a140Binary files /dev/null and b/public/examples/genjutsu-character/1/show.peak.webp differdiff --git a/public/examples/genjutsu-character/1/show.poster.webp b/public/examples/genjutsu-character/1/show.poster.webpnew file mode 100644index 00000000..ce8571f3Binary files /dev/null and b/public/examples/genjutsu-character/1/show.poster.webp differdiff --git a/public/examples/genjutsu-finish/1/in-clip.384.webp b/public/examples/genjutsu-finish/1/in-clip.384.webpnew file mode 100644index 00000000..4529bb27Binary files /dev/null and b/public/examples/genjutsu-finish/1/in-clip.384.webp differdiff --git a/public/examples/genjutsu-finish/1/in-clip.jpg b/public/examples/genjutsu-finish/1/in-clip.jpgnew file mode 100644index 00000000..a99840b9Binary files /dev/null and b/public/examples/genjutsu-finish/1/in-clip.jpg differdiff --git a/public/examples/genjutsu-finish/1/show.mp4 b/public/examples/genjutsu-finish/1/show.mp4new file mode 100644index 00000000..242b5199Binary files /dev/null and b/public/examples/genjutsu-finish/1/show.mp4 differdiff --git a/public/examples/genjutsu-finish/1/show.peak.webp b/public/examples/genjutsu-finish/1/show.peak.webpnew file mode 100644index 00000000..633bfbc7Binary files /dev/null and b/public/examples/genjutsu-finish/1/show.peak.webp differdiff --git a/public/examples/genjutsu-finish/1/show.poster.webp b/public/examples/genjutsu-finish/1/show.poster.webpnew file mode 100644index 00000000..8378097eBinary files /dev/null and b/public/examples/genjutsu-finish/1/show.poster.webp differdiff --git a/scripts/examples/publish-examples.mjs b/scripts/examples/publish-examples.mjsindex bf01aefe..38d15901 100644--- a/scripts/examples/publish-examples.mjs+++ b/scripts/examples/publish-examples.mjs@@ -13,6 +13,12 @@* frame-in the same from a clip's first frame ("at": "last" for its last)* mask-in a painted area: a black-and-white PNG, as it is* still-out a picture shown as an output: JPEG q84, 960 px at most, plus its poster (<name>.512.webp)+ * clip-show a before → after loop shown as an output (a Genjutsu mode's example): "before" (the clip that went in)+ * and "after" (the result) baked into one muted H.264 mp4, 1024×768, 24 fps, 1.2 MB at most, as "layout":+ * "inset" (the result fills the frame, the clip plays in a rounded window bottom-left) or "wipe" (the clip+ * for 1 s, then a thin line sweeps left to right over 1.4 s and leaves the result). Plus its first frame+ * (<name>.poster.webp, 1024 px, so the loop starts with no jump) and the result near its end+ * (<name>.peak.webp, 512 px: where a card rests, and what reduced motion shows)* A published file is never replaced or removed (a run may name it): a copy whose file exists with other bytes stops* the script. A new version gets a new path. A file a run reads sits under /examples/ or /samples/ only: a still from* elsewhere in public/ (a preset's before/after, which its own script rewrites) is copied in first.@@ -93,9 +99,93 @@ async function make(job, dry) {const jpg = await sharp(fs.readFileSync(from)).resize({ width: 960, height: 960, fit: "inside", withoutEnlargement: true }).toColorspace("srgb").jpeg({ quality: 84, mozjpeg: true }).toBuffer();return [put(to, jpg, dry), put(withExt(to, ".512.webp"), await poster(jpg), dry)];}+ if (op === "clip-show") return clipShow(job, dry);throw new Error(`${to}: unknown op ${op}`);}+const SHOW = { w: 1024, h: 768, fps: 24, maxBytes: 1_200_000 };++/** A clip's frame count and length (ffprobe). */+function probe(file) {+ const out = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).toString().trim();+ return Number(out);+}++/** The rounded window's alpha (white inside) and its frame (white at 85 %), as PNGs for ffmpeg. */+async function insetMasks(dir, w, h, r, border) {+ const mask = path.join(dir, "mask.png");+ const frame = path.join(dir, "frame.png");+ const svg = (W, H, R, fill) => Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect width="${W}" height="${H}" fill="black" fill-opacity="0"/><rect width="${W}" height="${H}" rx="${R}" ry="${R}" fill="${fill}"/></svg>`);+ await sharp({ create: { width: w, height: h, channels: 3, background: "#000" } }).composite([{ input: svg(w, h, r, "#fff") }]).greyscale().png().toFile(mask);+ await sharp(svg(w + 2 * border, h + 2 * border, r + border, "rgba(255,255,255,0.85)")).png().toFile(frame);+ return { mask, frame };+}++/** The before → after loop, encoded until it fits; then its poster and its resting still. */+async function clipShow(job, dry) {+ const { to, before, after, layout } = job;+ if (layout !== "inset" && layout !== "wipe") throw new Error(`${to}: clip-show takes layout "inset" or "wipe"`);+ const frames = Math.min(probe(before), probe(after));+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-example-show-"));+ const { w, h, fps } = SHOW;+ const norm = (i, W, H) => `[${i}:v]fps=${fps},scale=${W}:${H}:flags=lanczos,setsar=1,format=yuv420p,trim=end_frame=${frames},setpts=PTS-STARTPTS`;+ let inputs;+ let graph;+ if (layout === "inset") {+ // The source at 30 %, 24 px from the bottom-left corners, 12 px round, a 2 px white frame.+ const iw = 308;+ const ih = 230;+ const b = 2;+ const x = 24;+ const y = h - 24 - ih;+ const { mask, frame } = await insetMasks(dir, iw, ih, 12, b);+ inputs = ["-i", after, "-i", before, "-loop", "1", "-i", mask, "-loop", "1", "-i", frame];+ graph = [+ `${norm(0, w, h)}[A]`,+ `${norm(1, iw, ih)}[B]`,+ `[2:v]format=gray,scale=${iw}:${ih}[M]`,+ `[B][M]alphamerge[BM]`,+ `[A][3:v]overlay=${x - b}:${y - b}:shortest=1[A1]`,+ `[A1][BM]overlay=${x}:${y}:shortest=1,format=yuv420p[out]`,+ ].join(";");+ } else {+ // 0–1 s the source; 1–2.4 s a line sweeps (ease in-out) and leaves the result on its left; then the result.+ const p = "clip((t-1)/1.4\,0\,1)";+ const X = `(${w}*if(lt(${p}\,0.5)\,2*${p}*${p}\,1-pow(-2*${p}+2\,2)/2))`;+ const d = (frames / fps).toFixed(4);+ inputs = ["-i", before, "-i", after];+ graph = [+ `${norm(0, w, h)}[A]`,+ `${norm(1, w, h)}[B]`,+ `color=black:s=${w}x${h}:r=${fps}:d=${d}[m0]`,+ `color=white:s=${w}x${h}:r=${fps}:d=${d}[m1]`,+ `[m0][m1]overlay=x='${X}-${w}':y=0:eval=frame,format=gray[M]`,+ `[B][M]alphamerge[BM]`,+ `[A][BM]overlay=0:0:shortest=1[W]`,+ `[email protected]:s=8x${h}:r=${fps}:d=${d}[S]`,+ `color=white:s=2x${h}:r=${fps}:d=${d}[L]`,+ `[W][S]overlay=x='${X}-4':y=0:eval=frame:enable='between(t\,1\,2.4)'[W1]`,+ `[W1][L]overlay=x='${X}-1':y=0:eval=frame:enable='between(t\,1\,2.4)',format=yuv420p[out]`,+ ].join(";");+ }+ const mp4 = path.join(dir, "show.mp4");+ let data;+ for (const crf of [24, 26, 28, 30, 32]) {+ execFileSync("ffmpeg", ["-v", "error", "-y", ...inputs, "-filter_complex", graph, "-map", "[out]", "-frames:v", String(frames), "-an", "-c:v", "libx264", "-profile:v", "high", "-preset", "slow", "-crf", String(crf), "-pix_fmt", "yuv420p", "-r", String(fps), "-movflags", "+faststart", "-map_metadata", "-1", "-threads", "1", mp4]);+ data = fs.readFileSync(mp4);+ if (data.length <= SHOW.maxBytes) break;+ }+ if (data.length > SHOW.maxBytes) throw new Error(`${to}: the loop is ${data.length} bytes, over ${SHOW.maxBytes}`);+ const first = frameOf(mp4);+ const posterWebp = await fitting((q) => sharp(first).webp({ quality: q }).toBuffer(), [78, 70, 62, 54], 90_000);+ const peakPng = path.join(dir, "peak.png");+ execFileSync("ffmpeg", ["-v", "error", "-y", "-ss", ((frames / fps) - 0.45).toFixed(3), "-i", mp4, "-frames:v", "1", peakPng]);+ const peakWebp = await fitting((q) => sharp(fs.readFileSync(peakPng)).resize({ width: 512 }).webp({ quality: q }).toBuffer(), [78, 70, 62], 40_000);+ fs.rmSync(dir, { recursive: true, force: true });+ console.log(`${to}: ${frames} frames, ${(data.length / 1e6).toFixed(2)} MB`);+ return [put(to, data, dry), put(withExt(to, ".poster.webp"), posterWebp, dry), put(withExt(to, ".peak.webp"), peakWebp, dry)];+}+/** An input's inset copy, where there is one. */function thumbFor(pub) {const own = withExt(pub, ".384.webp");@@ -104,6 +194,9 @@ function thumbFor(pub) {/** An output's poster, where there is one. */function posterFor(pub) {+ // A clip-show loop's first frame.+ const first = withExt(pub, ".poster.webp");+ if (first !== pub && fs.existsSync(abs(first))) return first;const ba = /^\/previews\/presets\/ba\/960\/(.+)$/.exec(pub);if (ba) return `/previews/presets/ba/512/${ba[1]}`;const own = withExt(pub, ".512.webp");diff --git a/src/app/(studio)/genjutsu/page.tsx b/src/app/(studio)/genjutsu/page.tsxindex 01856516..204d1564 100644--- a/src/app/(studio)/genjutsu/page.tsx+++ b/src/app/(studio)/genjutsu/page.tsx@@ -1,11 +1,11 @@import type { Metadata } from "next";import { GenjutsuStudio } from "@/components/genjutsu/genjutsu-studio";-import { exampleRow } from "@/lib/examples/catalog";+import { exampleRow, genjutsuExamples } from "@/lib/examples/catalog";import { genjutsuLive } from "@/server/genjutsu-live";export const metadata: Metadata = { title: "Genjutsu" };export default function Page() {// Which Openjutsu modes are open to everyone (two committed files, read as the page is built; the owner sees them all).- return <GenjutsuStudio examples={exampleRow("tool:genjutsu")} live={genjutsuLive()} />;+ return <GenjutsuStudio examples={exampleRow("tool:genjutsu")} modeExamples={genjutsuExamples()} live={genjutsuLive()} />;}diff --git a/src/components/av/tool-shell.tsx b/src/components/av/tool-shell.tsxindex cf7a19c0..055698fa 100644--- a/src/components/av/tool-shell.tsx+++ b/src/components/av/tool-shell.tsx@@ -76,9 +76,9 @@ export function ToolHero({ title, subtitle, children }: { title: string; subtitl}/** A titled card section (setup steps, review, results). */-export function Panel({ title, aside, children, className }: { title?: React.ReactNode; aside?: React.ReactNode; children: React.ReactNode; className?: string }) {+export function Panel({ title, aside, children, className, id }: { title?: React.ReactNode; aside?: React.ReactNode; children: React.ReactNode; className?: string; id?: string }) {return (- <section className={cn("rounded-2xl border bg-background p-3 shadow-soft sm:p-4", className)}>+ <section id={id} className={cn("rounded-2xl border bg-background p-3 shadow-soft sm:p-4", className)}>{(title || aside) && (<div className="mb-3 flex min-w-0 items-center gap-2">{title && <h3 className="min-w-0 truncate text-[13px] font-semibold">{title}</h3>}diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 6e59a740..45ac4d84 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -80,6 +80,9 @@ import { FinishFields, FrameCompare, LightPicker, More, OnlyYou, PERSON_COLOURS,import { LookPicker, type LookSource } from "./look-picker";import { SetupCode } from "./setup-code";import { useClipCuts } from "./use-cuts";+import { ModeExample, ModeExampleRow } from "./mode-example";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { exampleFor, MARKED_NOTE, partLimits, sameRecipe, toRecipe, type GenjutsuExampleCard, type ModeExamples } from "@/lib/examples/genjutsu";/** The upload box's line: the mode's own window (Character swap: 5–15 s of one shot). */const limits = (mode: GenjutsuMode) =>@@ -115,9 +118,10 @@ const seedOf = (s: string): number | undefined => (s.trim() === "" ? undefined :* and your references, say what changes, see the price (or "Free" on your ComfyUI), get the result with a before /* after wipe. Fuobe's Originals run by default on both engines; open weights and partners are labelled alternatives.* Setups copy and paste as a short code. The plan: src/lib/catalog/genjutsu.ts; the server: src/server/genjutsu.ts.- * examples: "More to try" (exampleRow(), from the page), under the clip drop until there is a run of one's own.+ * examples: "More to try" (exampleRow(), from the page), under the clip drop until there is a run of one's own; and each+ * mode's own example under its title (modeExamples: a before → after loop, and Use this example, which loads its recipe).*/-export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData | null; live?: Partial<Record<GenjutsuFeature, boolean>> }) {+export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: ExampleRowData | null; modeExamples?: ModeExamples; 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();@@ -164,6 +168,13 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |const [describing, setDescribing] = useState(false);const [finish, setFinish] = useState<FinishOptions>({ tool: "colours" });const [tapFor, setTapFor] = useState<number | null>(null);+ // A mode's example in the form: which one, the part's length it asks for until a clip is in, and its words that came+ // from its own clip (a note under those fields).+ const [exampleIn, setExampleIn] = useState<string | null>(null);+ const [pendingLength, setPendingLength] = useState<number | null>(null);+ const [marked, setMarked] = useState<{ subject?: boolean; target?: boolean }>({});+ const [askReplace, setAskReplace] = useState<GenjutsuExampleCard | null>(null);+ const [dropRing, setDropRing] = useState(false);const runMutation = useGenjutsuRun();const sceneMutation = useDescribeScene();const guard = useSubmitGuard();@@ -246,6 +257,8 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |const partCuts = isCharacter && range ? cutsInPart(cuts ?? undefined, { start: range.startTime, end: range.endTime }) : [];const cut = cutWarning(partCuts);const seedNumber = seedOf(seed);+ // Modes with no seed field of their own show one once a seed is set (an example's or a pasted setup's).+ const seedShown = !isCharacter && !fresh && seed.trim() !== "";// Character swap's H3 makers take H3's two qualities; the other makers (Recast, P-Video…) Genjutsu's own.// A size this engine can't make worth it (your GPU's 4K) is asked as 2K, as the picker shows it.const askedQuality = isCharacter && maker?.h3 ? (qualityOff(engine, charQuality) ? "2K" : charQuality) : quality;@@ -364,7 +377,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |}const pictureStage: "frame" | "video" = frameUrl ? "video" : "frame";- const apply = (s: GenjutsuSetup) => {+ const apply = (s: GenjutsuSetup, example?: GenjutsuExampleCard) => {// Through setMode: the URL's ?mode= follows (a reload keeps the pasted mode).setMode(s.mode);const e = s.engine && engineMode === "both" ? s.engine : engine;@@ -396,9 +409,29 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |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." });+ // gj2 and examples: the seed, the part's length and the sound too (an example with no seed: a new one each time).+ if (s.seed !== undefined || example) setSeed(s.seed !== undefined ? String(s.seed) : "");+ if (s.originalSound) setOriginalSound(s.originalSound);+ if (s.length !== undefined) partLength(s.length, s.mode, s.model);+ if (!example) toast("Setup pasted", { description: clip ? "Check the references and press Generate." : "Add a clip to run it on." });};+ /** The part becomes this long from where it starts (the clip's end at most, and the mode's longest part). */+ const partLength = (length: number, m: GenjutsuMode, model?: string) => {+ const most = partLimits(m, model).max;+ if (!range || !duration) return setPendingLength(length);+ setPendingLength(null);+ const end = Math.min(duration, range.startTime + Math.min(length, most));+ setRange({ ...range, endTime: Math.round(end * 1000) / 1000 });+ if (duration - range.startTime < length - 0.05) toast(`Your clip is ${Math.round((duration - range.startTime) * 10) / 10} s from there. The example used ${Math.round(length * 10) / 10} s.`, { id: "gj-example-length" });+ };+ // A clip added after an example: its part takes the example's length once the clip is read.+ if (pendingLength !== null && range && duration) {+ setPendingLength(null);+ const end = Math.min(duration, range.startTime + pendingLength);+ if (Math.abs(range.endTime - end) > 0.001) setRange({ ...range, endTime: Math.round(end * 1000) / 1000 });+ }+// Hand-offs: ?mode=swap, ?video=/api/files/…, ?image=/api/files/… (a reference), ?setup=gj1.…. Read as they change, so// "Use in Genjutsu" on a result in this page's own feed (a link to /genjutsu?video=…) loads that clip too. Each value// is applied once; ?image and ?setup leave the URL then (a reload doesn't paste them over what you changed).@@ -431,6 +464,13 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |if (s) apply(s);else toast.error("That setup code didn't read — ask for it again");}+ // ?example=<id>: its mode, with the example in view (nothing is loaded until Use this example).+ const ex = fresh("example");+ const exMode = ex ? GENJUTSU_MODES.find((g) => modeExamples?.[g.id]?.some((c) => c.id === ex))?.id : undefined;+ if (exMode && modeOpen(exMode, open)) {+ setModeState(exMode);+ requestAnimationFrame(() => document.querySelector("[data-mode-example]")?.scrollIntoView({ block: "center" }));+ }const video = fresh("video");if (video?.startsWith("/api/files/")) {clearMarks();@@ -528,6 +568,13 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |const soundEngine = maker?.engine ?? engine;const soundLiveNow = useSoundLive(ORIGINAL_SOUND_FEATURE);const originalSound = originalSoundOn(soundAsked ?? originalSoundDefault({ replacesPerson: isCharacter, engine: soundEngine, live: soundLiveNow }), soundEngine);+ // The whole setup, as the header copies it (gj2: with the seed, the part's length and the sound) and as an example compares.+ const partNow = range ? Math.round((range.endTime - range.startTime) * 1000) / 1000 : (pendingLength ?? undefined);+ const fullSetup: GenjutsuSetup = { ...setup, ...(seedNumber !== undefined && !seedProblem(seedNumber) ? { seed: seedNumber } : {}), ...(partNow ? { length: partNow } : {}), originalSound };+ // This mode's example for this viewer (none: no card), and whether the form still holds it.+ const example = exampleFor(modeExamples, mode, open);+ const exampleInUse = !!example && exampleIn === example.id && sameRecipe(toRecipe(fullSetup), example.load.recipe);+ const exampleOnlyYou = !!example && owner && !example.load.needs.every((f) => !!live?.[f]);const body: GenjutsuBody | null =uploaded && maker && !problem && !refs.some((r) => r.uploading) && !custom.some((r) => r.uploading)? {@@ -547,7 +594,8 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |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 } : {}),+ // A seed field shows for every mode once a seed is set (an example's, a pasted setup's): what shows, runs.+ ...(!isCharacter && seedNumber !== undefined && (fresh || seedShown) ? { seed: seedNumber } : {}),...(sceneEdit ? { object: { ...objectEdit, action } } : {}),...(mode === "picture" ? { picture: { ...picture, stage: pictureStage, ...(frameUrl ? { frame: frameUrl } : {}), ...(scene.trim() ? { scene: scene.trim() } : {}) } } : {}),...(mode === "finish" ? { finish } : {}),@@ -640,12 +688,72 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |setTapFor(null);};+ /** Use this example: the form's own words and seed are replaced only after a yes. */+ const ownWords = !!(prompt.trim() || subject.trim() || objectEdit.target?.trim() || objectEdit.becomes?.trim() || character.description?.trim() || picture.adjust?.trim() || words.trim() || seed.trim());+ const pickExample = (card: GenjutsuExampleCard) => (ownWords && !exampleInUse ? setAskReplace(card) : loadExample(card));+ const loadExample = (card: GenjutsuExampleCard) => {+ const snap = { mode, engine, tier, quality, charQuality, targets, subject, prompts, lookChoice, look, custom, words, picked, character, action, objectEdit, picture, finish, seed, range, soundAsked, pendingLength, marked, exampleIn, points, paint };+ const r = card.load.recipe;+ apply(r, card);+ // The example's own clicks and paint never come with it; the viewer's no longer fit the new settings either.+ setPoints([]);+ setPaint(null);+ setMarked({ subject: !!r.subject, target: !!r.object?.target });+ setExampleIn(card.id);+ toast("Example loaded", {+ id: "gj-example",+ description: clip ? "Check your photos, then Generate." : "Add your clip, then Generate.",+ duration: 10_000,+ action: {+ label: "Undo",+ onClick: () => {+ setMode(snap.mode);+ if (snap.engine !== engine && engineMode === "both") setEngine(snap.engine);+ setTier(snap.tier);+ setQuality(snap.quality);+ setCharQuality(snap.charQuality);+ setTargets(snap.targets);+ setSubject(snap.subject);+ setPrompts(snap.prompts);+ setLookSource(snap.lookChoice);+ setLook(snap.look);+ setCustom(snap.custom);+ setWords(snap.words);+ setPicked(snap.picked);+ setCharacter(snap.character);+ setAction(snap.action);+ setObjectEdit(snap.objectEdit);+ setPicture(snap.picture);+ setFinish(snap.finish);+ setSeed(snap.seed);+ if (snap.range) setRange(snap.range);+ setOriginalSound(snap.soundAsked);+ setPendingLength(snap.pendingLength);+ setMarked(snap.marked);+ setExampleIn(snap.exampleIn);+ setPoints(snap.points);+ setPaint(snap.paint);+ },+ },+ });+ // Next: the clip (no clip yet), else the first thing still missing, else Generate.+ requestAnimationFrame(() => {+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const target = document.getElementById(clip ? (refs.length ? "gj-generate" : "gj-refs") : "gj-clip-drop") ?? document.getElementById("gj-generate");+ target?.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });+ if (!clip) {+ setDropRing(true);+ setTimeout(() => setDropRing(false), 2000);+ }+ });+ };+const modeInfo = getMode(mode);const hint = modeHint(mode, open);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} fadeKey={mode} header={<SetupCode setup={setup} onPaste={apply} />} wide selfHostedOnly>+ <ToolShell title="Genjutsu" tabs={tabs} fadeKey={mode} header={<SetupCode setup={fullSetup} onPaste={(s) => apply(s)} />} wide selfHostedOnly>{!clip && (<ToolHero title={modeInfo.label} subtitle={`${hint}${visitor ? "" : " Free on your own ComfyUI."}`}>{isCharacter && (@@ -656,7 +764,10 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |{visitor && <SelfHostNote className="mt-3 max-w-xl">Genjutsu isn't available here.</SelfHostNote>}</ToolHero>)}- <div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>+ {!clip && example && (+ <ModeExample key={example.id} card={example} owner={!visitor} canUse={!visitor} inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} className="mt-6" />+ )}+ <div id="gj-clip-drop" className={cn("mx-auto scroll-mt-24 rounded-2xl transition-shadow", clip ? "pt-4" : "mt-8 max-w-[640px]", dropRing && "ring-2 ring-primary ring-offset-4 ring-offset-background")}>{!clip ? (<ClipDropaccept={GENJUTSU.accept}@@ -805,6 +916,8 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |{showRefs && (<Panel+ id="gj-refs"+ className="scroll-mt-24"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>}>@@ -834,6 +947,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |<Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)]">{mode === "picture" && <PictureSteps stage={pictureStage} />}+ {example && !visitor && <ModeExampleRow key={example.id} card={example} owner canUse inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} />}<p className="text-[13px] text-pretty text-muted-foreground">{hint}</p>{mode === "finish" && <FinishFields value={finish} onChange={setFinish} open={open} ownerOnly={ownerOnly} seed={seed} onSeed={setSeed} />}@@ -929,6 +1043,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |onSeed={setSeed}/>)}+ {sceneEdit && marked.target && objectEdit.target && <p className="-mt-2 text-[12px] text-muted-foreground">{MARKED_NOTE}</p>}{group && (<WhoBecomesWho@@ -952,6 +1067,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |placeholder={maker?.people ? "e.g. “the presenter”" : "e.g. “the red car”, “her jacket”"}className="text-[13px]"/>+ {marked.subject && subject.trim() && <p className="text-[12px] text-muted-foreground">{MARKED_NOTE}</p>}</Field>)}@@ -1037,6 +1153,12 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |</Field>)}+ {seedShown && (+ <Field label="Seed" htmlFor="gj-any-seed" hint="Blank: a new one each time">+ <Input id="gj-any-seed" inputMode="numeric" value={seed} onChange={(e) => setSeed(e.target.value.replace(/[^0-9]/g, "").slice(0, 15))} className="h-11 text-[13px]" />+ </Field>+ )}+{clip?.info?.hasAudio !== false && mode !== "picture" && <OriginalSoundPicker engine={soundEngine} value={originalSound} onChange={setOriginalSound} />}<div className="space-y-3 border-t pt-3">@@ -1058,7 +1180,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |</>)}</div>- <Button className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending || visitor || describing}>+ <Button id="gj-generate" 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>@@ -1126,6 +1248,25 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |<Suspense fallback={null}><UrlParams onChange={setParams} /></Suspense>+ <AlertDialog open={!!askReplace} onOpenChange={(o) => !o && setAskReplace(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Replace your settings with the example's?</AlertDialogTitle>+ <AlertDialogDescription>Your words and settings change to the example's. Your clip and photos stay.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep mine</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => {+ if (askReplace) loadExample(askReplace);+ setAskReplace(null);+ }}+ >+ Replace+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></ToolShell>);}diff --git a/src/components/genjutsu/mode-example.tsx b/src/components/genjutsu/mode-example.tsxnew file mode 100644index 00000000..25e43fae--- /dev/null+++ b/src/components/genjutsu/mode-example.tsx@@ -0,0 +1,302 @@+"use client";++import { Check, Copy, Pause, Play, Sparkles } from "lucide-react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { copyText } from "@/lib/clipboard";+import { encodeSetup, getMaker } from "@/lib/catalog/genjutsu";+import type { GenjutsuExampleCard } from "@/lib/examples/genjutsu";+import { cn } from "@/lib/utils";+import { OnlyYou } from "./openjutsu-panels";++/**+ * A Genjutsu mode's example, under the mode's title: one muted before → after loop (the clip that went in, then what+ * came out), what went in, the settings it used, and "Use this example", which puts those settings into the form and+ * keeps the viewer's own clip and photos. Visitors, who can't run Genjutsu here, copy its setup instead.+ *+ * Loading: a still in a fixed 4:3 box first (nothing moves when the clip arrives). The clip downloads only once the+ * card is at least half in view, and not at all with Save-Data or reduced motion (then the finished result shows as a+ * still with a Play button). Leaving the mode drops the download. No analytics of any kind.+ */++/** Where the clip that went in sits in an inset loop (clip-show: 308×230 at 24 px from the corner of 1024×768). */+const INSET = { left: `${(24 / 1024) * 100}%`, top: `${((768 - 24 - 230) / 768) * 100}%` };+/** The wipe's line reaches the middle at 1.7 s: before that the frame is mostly the clip that went in. */+const WIPE_MIDDLE = 1.7;++const reducedMotion = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;+const saveData = () => typeof navigator !== "undefined" && !!(navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData;++/** Reduced motion can change while the page is open. */+function watchStill(change: () => void) {+ const q = window.matchMedia("(prefers-reduced-motion: reduce)");+ q.addEventListener("change", change);+ return () => q.removeEventListener("change", change);+}++/** A small label on the picture (not read out: the card's caption says what it is). */+function Pill({ children, className, style }: { children: React.ReactNode; className?: string; style?: React.CSSProperties }) {+ return (+ <span aria-hidden className={cn("pointer-events-none absolute rounded-full bg-black/55 px-2 py-0.5 text-[12px] font-semibold text-white", className)} style={style}>+ {children}+ </span>+ );+}++/** The loop: the still first, the clip once it is in view (or Play is pressed). */+function Loop({ card }: { card: GenjutsuExampleCard }) {+ const box = useRef<HTMLDivElement>(null);+ const video = useRef<HTMLVideoElement>(null);+ const [inView, setInView] = useState(false);+ // null: plays by itself when it can; true / false: the viewer pressed Pause or Play.+ const [chosen, setChosen] = useState<boolean | null>(null);+ // Reduced motion or Save-Data: the finished result as a still, and the clip only on Play (false while the page hydrates).+ const still = useSyncExternalStore(watchStill, () => reducedMotion() || saveData(), () => false);+ const [late, setLate] = useState(false);+ const out = card.output;+ const rest = out.rest?.src;++ useEffect(() => {+ const el = box.current;+ if (!el || typeof IntersectionObserver === "undefined") return;+ const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { rootMargin: "200px 0px", threshold: 0.5 });+ io.observe(el);+ return () => io.disconnect();+ }, []);++ const wanted = chosen ?? (!still && inView);+ // The clip is fetched once it is first wanted, and kept while the mode stays (a scroll back plays at once).+ const [loaded, setLoaded] = useState(false);+ if (wanted && !loaded) setLoaded(true);++ useEffect(() => {+ const v = video.current;+ if (!v || !loaded) return;+ const hidden = () => document.visibilityState === "hidden";+ const sync = () => {+ if (wanted && inView && !hidden()) void v.play().catch(() => {});+ else v.pause();+ };+ sync();+ document.addEventListener("visibilitychange", sync);+ return () => document.removeEventListener("visibilitychange", sync);+ }, [loaded, wanted, inView]);++ // The mode changes (this card leaves): its download stops.+ useEffect(() => {+ const v = video.current;+ if (!v || !loaded) return;+ return () => {+ v.pause();+ v.removeAttribute("src");+ v.load();+ };+ }, [loaded]);++ // The wipe's single label follows the line: "Before" until the result has most of the frame.+ useEffect(() => {+ const v = video.current;+ if (!v || !loaded || card.load.layout !== "wipe") return;+ const tick = () => setLate(v.currentTime >= WIPE_MIDDLE);+ v.addEventListener("timeupdate", tick);+ return () => v.removeEventListener("timeupdate", tick);+ }, [loaded, card.load.layout]);++ const playing = loaded && wanted;+ // Before the clip: the reduced-motion still is the finished result; otherwise the loop's first frame.+ const poster = still && rest ? rest : (out.poster ?? rest);+ const showsResult = still && !loaded ? true : late;+ return (+ <div ref={box} className="relative aspect-[4/3] w-full overflow-hidden bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {poster && <img src={poster} alt="" decoding="async" fetchPriority="low" className="absolute inset-0 size-full object-cover" draggable={false} />}+ {loaded && (+ <video+ ref={video}+ src={out.src}+ poster={out.poster}+ muted+ loop+ playsInline+ preload="auto"+ aria-label={card.caption}+ className="absolute inset-0 size-full object-cover"+ data-example-video=""+ />+ )}+ {card.load.layout === "inset" ? (+ <>+ <Pill className="top-2 right-2">After</Pill>+ <Pill style={{ left: `calc(${INSET.left} + 6px)`, top: `calc(${INSET.top} + 6px)` }} className="bg-black/60 text-[11px]">+ Before+ </Pill>+ </>+ ) : (+ <Pill className="top-2 left-2">{showsResult ? "After" : "Before"}</Pill>+ )}+ <button+ type="button"+ onClick={() => setChosen(!playing)}+ aria-label={playing ? "Pause the example" : "Play the example"}+ className="absolute right-2 bottom-2 grid size-11 place-items-center rounded-full bg-black/55 text-white outline-none hover:bg-black/70 focus-visible:ring-2 focus-visible:ring-white"+ >+ {playing ? <Pause className="size-4" /> : <Play className="size-4 translate-x-px" />}+ </button>+ </div>+ );+}++/** Copies the example's setup as a link (a visitor pastes it into Genjutsu on their own Fuobe). */+async function copySetup(card: GenjutsuExampleCard) {+ const link = `${window.location.origin}/genjutsu?setup=${encodeSetup(card.load.recipe)}`;+ if (await copyText(link)) toast("Setup copied", { description: "Paste it in Genjutsu on your own Fuobe." });+ else toast.error("Couldn't copy — your browser blocked the clipboard");+}++export interface ModeExampleProps {+ card: GenjutsuExampleCard;+ /** The owner (or a studio of one's own): Use this example, the model's name, and Only you where it applies. */+ owner: boolean;+ /** Genjutsu runs here: Use this example (else Copy its setup only). */+ canUse: boolean;+ /** The form still holds this example's settings. */+ inUse: boolean;+ /** Some of its features are open only to the owner (the Only you mark). */+ onlyYou?: boolean;+ onUse: () => void;+ className?: string;+}++/** The example card: the loop on the left (on top on a phone), what it is and what it used beside it. */+export function ModeExample({ card, owner, canUse, inUse, onlyYou, onUse, className }: ModeExampleProps) {+ const r = card.load.recipe;+ const model = owner ? getMaker(r.model, r.engine)?.label : undefined;+ const settings = [...(model ? [model] : []), ...(card.chips ?? [])];+ const titleId = `gj-example-${card.id.replace(/\W/g, "-")}`;+ return (+ <figure+ aria-labelledby={titleId}+ data-mode-example={card.id}+ className={cn(+ "mx-auto grid w-full max-w-[960px] grid-cols-1 overflow-hidden rounded-2xl border bg-background text-left shadow-soft md:grid-cols-[minmax(0,1fr)_352px]",+ inUse && "ring-2 ring-primary ring-offset-2 ring-offset-background",+ className,+ )}+ >+ <Loop card={card} />+ <figcaption className="flex min-w-0 flex-col gap-3 p-4 md:p-5">+ <div>+ <p className="flex items-center gap-1.5 text-[11px] font-semibold text-muted-foreground">+ <span className="tracking-wider uppercase">Example</span>+ {onlyYou && <OnlyYou />}+ </p>+ <h3 id={titleId} className="mt-1 text-[16px] leading-snug font-semibold text-balance">+ {card.caption}+ </h3>+ {card.words && <p className="mt-1.5 text-[13px] leading-relaxed text-pretty text-muted-foreground">{card.words}</p>}+ </div>+ <div>+ <p className="text-[12px] font-medium">What went in</p>+ <div className="mt-1.5 flex items-center gap-2">+ {card.inputs.map((i) => (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ key={i.slot}+ src={i.media.thumb ?? i.media.src}+ alt={i.label ?? ""}+ loading="lazy"+ decoding="async"+ className={cn("h-12 shrink-0 rounded-md bg-muted object-cover", i.slot === "clip" ? "w-16" : "w-9")}+ />+ ))}+ <span className="min-w-0 text-[13px] text-muted-foreground">{card.load.went}</span>+ </div>+ </div>+ {/* The settings: open beside the loop on a wide screen, behind a tap on a phone. */}+ <div className="hidden md:block">+ <p className="text-[12px] font-medium">Settings it used</p>+ <Settings items={settings} />+ </div>+ <details className="group md:hidden">+ <summary className="flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">+ <span className="inline-block transition-transform group-open:rotate-90" aria-hidden>+ ›+ </span>+ Settings it used+ </summary>+ <Settings items={settings} />+ </details>+ {/* One 44 px row for every viewer: the card keeps its height when the owner's page switches at hydration. */}+ <div className="mt-auto flex gap-2 pt-1">+ {canUse ? (+ <>+ <Button className="h-11 min-w-0 flex-1 rounded-full" onClick={onUse} disabled={inUse} data-use-example="">+ {inUse ? <Check className="size-4" /> : <Sparkles className="size-4" />}+ {inUse ? "In use" : "Use this example"}+ </Button>+ <Button variant="outline" className="size-11 shrink-0 rounded-full p-0" onClick={() => void copySetup(card)} aria-label="Copy its setup" title="Copy its setup">+ <Copy className="size-4" />+ </Button>+ </>+ ) : (+ <Button variant="outline" className="h-11 w-full rounded-full" onClick={() => void copySetup(card)}>+ <Copy className="size-4" /> Copy its setup+ </Button>+ )}+ </div>+ </figcaption>+ </figure>+ );+}++function Settings({ items }: { items: string[] }) {+ return (+ <ul className="mt-1.5 flex flex-wrap gap-1.5" aria-label="Settings it used">+ {items.map((s) => (+ <li key={s} className="rounded-full border px-2 py-0.5 text-[12px] text-muted-foreground">+ {s}+ </li>+ ))}+ </ul>+ );+}++/** With a clip loaded: one line in the side panel, and the full card in a dialog. */+export function ModeExampleRow(props: ModeExampleProps) {+ const { card, inUse, onUse } = props;+ const [open, setOpen] = useState(false);+ const still = card.output.rest?.src ?? card.output.poster;+ return (+ <div className="flex items-center gap-2.5 rounded-xl border p-2" data-mode-example-row={card.id}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {still && <img src={still} alt="" loading="lazy" decoding="async" className="h-12 w-16 shrink-0 rounded-md bg-muted object-cover" />}+ <p className="min-w-0 flex-1 text-[13px] leading-snug">+ <span className="text-muted-foreground">{inUse ? "Example in use: " : "Example: "}</span>+ {card.caption}+ </p>+ {!inUse && (+ <Button variant="outline" className="h-11 shrink-0 rounded-full px-4" onClick={() => setOpen(true)}>+ See it+ </Button>+ )}+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-h-[90dvh] overflow-y-auto p-0 sm:max-w-[min(92vw,960px)]">+ <DialogHeader className="sr-only">+ <DialogTitle>{card.caption}</DialogTitle>+ <DialogDescription>An example of this mode, and the settings it used.</DialogDescription>+ </DialogHeader>+ <ModeExample+ {...props}+ className="rounded-none border-0 shadow-none"+ onUse={() => {+ setOpen(false);+ onUse();+ }}+ />+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/components/genjutsu/setup-code.tsx b/src/components/genjutsu/setup-code.tsxindex 2d2afdc6..51bbf4ea 100644--- a/src/components/genjutsu/setup-code.tsx+++ b/src/components/genjutsu/setup-code.tsx@@ -11,7 +11,7 @@ import { decodeSetup, encodeSetup, type GenjutsuSetup } from "@/lib/catalog/genj/*** Higgsfield's "share a setup by code", done locally: Copy setup puts a link with the settings as a short code- * (/genjutsu?setup=gj1.…) on the clipboard; Paste setup reads a code or such a link back. The clip itself isn't in+ * (/genjutsu?setup=gj2.…) on the clipboard; Paste setup reads a code or such a link back. The clip itself isn't in* it; reference images are files of this install.*/export function SetupCode({ setup, onPaste }: { setup: GenjutsuSetup; onPaste: (s: GenjutsuSetup) => void }) {@@ -24,7 +24,7 @@ export function SetupCode({ setup, onPaste }: { setup: GenjutsuSetup; onPaste: (};const paste = () => {const s = decodeSetup(text);- if (!s) return void toast.error("That isn't a Genjutsu setup code (they start with gj1.)");+ if (!s) return void toast.error("That isn't a Genjutsu setup code (they start with gj1. or gj2.)");onPaste(s);setOpen(false);setText("");@@ -53,7 +53,7 @@ export function SetupCode({ setup, onPaste }: { setup: GenjutsuSetup; onPaste: (<label htmlFor="gj-setup-code" className="block text-[13px] font-medium">Paste a setup code or link</label>- <Input id="gj-setup-code" value={text} onChange={(e) => setText(e.target.value)} placeholder="gj1.… or a /genjutsu?setup= link" className="h-8 text-[13px]" autoFocus />+ <Input id="gj-setup-code" value={text} onChange={(e) => setText(e.target.value)} placeholder="gj2.… or a /genjutsu?setup= link" className="h-8 text-[13px]" autoFocus /><div className="flex justify-end"><Button type="submit" size="sm" className="rounded-full" disabled={!text.trim()}>Use this setupdiff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex e90d8649..a8a780ca 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -2041,8 +2041,18 @@ export interface GenjutsuSetup {/** From picture's settings (not the frame or the words: they belong to a run). */picture?: Omit<PictureOptions, "frame" | "scene" | "stage">;finish?: FinishOptions;+ /** The run's seed (blank in the form: a new one each time). */+ seed?: number;+ /** How long the part is, in seconds (it starts where the part of the clip starts). */+ length?: number;+ /** What of the clip's sound goes back. */+ originalSound?: OriginalSound;}+/** The longest part a setup names: Finish's whole clip. */+export const SETUP_MAX_LENGTH = 60;+const SOUNDS: readonly OriginalSound[] = ["everything", "music-effects", "dialogue", "lower-music"];+const MODES = new Set<string>(GENJUTSU_MODES.map((m) => m.id));const QUALITIES = new Set<string>(["480p", "720p", "768p", "1080p", "2K", "4K"]);const FILE = /^\/api\/files\/[\w./-]{1,200}$/;@@ -2170,7 +2180,10 @@ export function cleanFinish(v: unknown): FinishOptions | undefined {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). */+/**+ * A setup as a short code ("gj2." + base64url JSON with short keys; empty fields left out). gj2 adds the seed, the+ * part's length and the original sound to gj1's fields, so a pasted code makes the same run; gj1 codes still read.+ */export function encodeSetup(s: GenjutsuSetup): string {const look = s.look && (s.look.kind === "custom" ? { k: "c", i: s.look.images, w: s.look.words || undefined } : { k: s.look.kind === "preset" ? "p" : "s", id: s.look.id });const o = {@@ -2188,10 +2201,16 @@ export function encodeSetup(s: GenjutsuSetup): string {o: s.object && cleanObject(s.object),i: s.picture && cleanPicture(s.picture),f: s.finish && cleanFinish(s.finish),+ sd: s.seed !== undefined && !seedProblem(s.seed) ? s.seed : undefined,+ pl: lengthOf(s.length),+ os: s.originalSound,};- return `gj1.${toBase64Url(JSON.stringify(o))}`;+ return `gj2.${toBase64Url(JSON.stringify(o))}`;}+/** A part's length as a code keeps it: 3 decimals, 1 to 60 s. */+const lengthOf = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) && v >= 1 && v <= SETUP_MAX_LENGTH ? Math.round(v * 1000) / 1000 : undefined);+/*** 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).@@ -2203,7 +2222,7 @@ export function decodeSetup(input: string, open: FeatureCheck = ALL_FEATURES): G// A link: its ?setup= (a malformed %-escape is not a code either).const fromLink = /[?&]setup=([^&#\s]+)/.exec(code);if (fromLink) code = decodeURIComponent(fromLink[1]);- if (!code.startsWith("gj1.")) return null;+ if (!/^gj[12]\./.test(code)) return null;o = JSON.parse(fromBase64Url(code.slice(4).replace(/\s+/g, ""))) as Record<string, unknown>;} catch {return null;@@ -2252,6 +2271,11 @@ export function decodeSetup(input: string, open: FeatureCheck = ALL_FEATURES): G}const finish = mode === "finish" ? cleanFinish(o.f) : undefined;if (finish && open(finish.tool === "faces" ? "finish-faces" : "finish-colours")) out.finish = finish;+ if (typeof o.sd === "number" && !seedProblem(o.sd)) out.seed = o.sd;+ const length = lengthOf(o.pl);+ if (length !== undefined) out.length = length;+ const sound = oneOf(o.os, SOUNDS);+ if (sound) out.originalSound = sound;return out;}diff --git a/src/lib/examples/catalog.ts b/src/lib/examples/catalog.tsindex db98b085..4914d556 100644--- a/src/lib/examples/catalog.ts+++ b/src/lib/examples/catalog.ts@@ -21,6 +21,8 @@ import {UPSCALE_STUDIO,VIDEO_STUDIO,} from "@/lib/studios";+import { getMaker, GENJUTSU_MODES, requestFeatures, type GenjutsuMode } from "@/lib/catalog/genjutsu";+import { exampleSettings, genjutsuSurface, recipeProblem, type GenjutsuExampleCard, type ModeExamples } from "./genjutsu";import { EXAMPLE_MEDIA, type ExampleMediaFile } from "./media.generated";import plan from "./plan.json";import {@@ -34,6 +36,8 @@ import {type ExampleRequest,type ExampleRowData,type ExampleSurface,+ type GenjutsuExampleLoad,+ type GenjutsuRecipe,} from "./types";/** One row of plan.json. */@@ -44,8 +48,16 @@ export interface PlanRow {rank: number;caption: string;words?: string;- /** "draft" (the default): the composer's own path. "look": a sheet to look at. */- load?: "draft" | "look";+ /** "draft" (the default): the composer's own path. "look": a sheet to look at. "genjutsu": a Genjutsu mode's example. */+ load?: "draft" | "look" | "genjutsu";+ /** A Genjutsu mode's example (load "genjutsu"): its loop's layout, what went in, the recipe, and the example's own inputs. */+ genjutsu?: {+ layout: GenjutsuExampleLoad["layout"];+ went: string;+ recipe: GenjutsuRecipe;+ /** The fields about the example's own clip and photos (who is who): never on the card, used by the tests' exact remake. */+ own?: Record<string, unknown>;+ };presetId?: string;modelId?: string;/** App settings, option key → choice value. */@@ -174,7 +186,7 @@ function outputMedia(row: PlanRow): ExampleMedia {return { src: `/previews/presets/ba/960/${id}-after.jpg?v=${v}`, kind: "image", poster: `/previews/presets/ba/512/${id}-after.jpg?v=${v}`, w: 960, h: 720 };}const f = EXAMPLE_MEDIA[out] ?? fail(row, `its output ${out} isn't a published example file`);- return { src: versioned(out, f), kind: mediaKind(f.type), ...(f.poster && { poster: f.poster }), ...(f.w && { w: f.w, h: f.h }) };+ return { src: versioned(out, f), kind: mediaKind(f.type), ...(f.poster && { poster: f.poster }), ...(f.w && { w: f.w, h: f.h }), ...(row.rest && { rest: restOf(row, row.rest) }) };}/** The request a row runs: its preset, model, words, settings and files, in a past run's shape. */@@ -222,14 +234,15 @@ function buildCard(row: PlanRow): ExampleCard {if (slots && !def) fail(row, `${row.surface} has no ${slot} slot`);const media = inputMedia(row, path);if (def && def.accept !== media.kind) fail(row, `${slot} takes ${def.accept}, not ${media.kind}`);- inputs.push({ slot, ...(def?.label && { label: def.label }), media });+ const label = row.load === "genjutsu" ? (GENJUTSU_INPUT_LABEL[slot.replace(/\d+$/, "")] ?? fail(row, `a Genjutsu example's inputs are clip, photo1… (not ${slot})`)) : def?.label;+ inputs.push({ slot, ...(label && { label }), media });}// An inpaint's picture with its painted area tinted shows what went in; the plain picture and the black-and-white// area it was made from stay out of the card (the request still has them).const shown = inputs.some((i) => i.slot === "sketch") ? inputs.filter((i) => i.slot !== "image" && i.slot !== "mask") : inputs;if (row.modelId && !getModel(row.modelId)) fail(row, `names model ${row.modelId}, which isn't in the catalog`);- const load: ExampleCard["load"] = row.load === "look" ? { via: "look" } : { via: "draft", request: requestOf(row, preset) };- const chips = chipsOf(row, preset);+ const load: ExampleCard["load"] = row.load === "genjutsu" ? genjutsuLoad(row) : row.load === "look" ? { via: "look" } : { via: "draft", request: requestOf(row, preset) };+ const chips = load.via === "genjutsu" ? exampleSettings(load.recipe) : chipsOf(row, preset);return {id: row.id,caption: row.caption,@@ -241,6 +254,26 @@ function buildCard(row: PlanRow): ExampleCard {};}+/** What a Genjutsu example's inputs are called on its card ("What went in"). */+const GENJUTSU_INPUT_LABEL: Record<string, string> = { clip: "Clip", photo: "Photo", look: "Look", product: "Product" };++/** A Genjutsu mode's example: its surface names the mode, and its recipe passes the same checks a pasted setup does. */+function genjutsuLoad(row: PlanRow): GenjutsuExampleLoad {+ const [kind, name] = splitSurface(row.surface);+ const [tool, mode] = name.split("/");+ if (kind !== "tool" || tool !== "genjutsu" || !GENJUTSU_MODES.some((m) => m.id === mode)) fail(row, "a Genjutsu example's surface is tool:genjutsu/<mode>");+ const g = row.genjutsu ?? fail(row, "a Genjutsu example needs its recipe (genjutsu: { layout, went, recipe })");+ if (g.layout !== "inset" && g.layout !== "wipe") fail(row, `its layout ${g.layout} is neither inset nor wipe`);+ if (!g.went.trim() || g.went.length > 60) fail(row, "what went in is 1 to 60 characters");+ const problem = recipeProblem(g.recipe, mode as GenjutsuMode);+ if (problem) fail(row, problem);+ const r = g.recipe;+ const maker = getMaker(r.model, r.engine)!;+ const needs = requestFeatures({ mode: r.mode, maker, character: r.character, object: r.object, picture: r.picture ? { ...r.picture, stage: "frame" } : undefined, finish: r.finish });+ if (!row.output.endsWith(".mp4")) fail(row, "a Genjutsu example shows a clip (clip-show)");+ return { via: "genjutsu", layout: g.layout, went: g.went, recipe: r, needs };+}+/** Every example, by surface, ranked. */function buildAll(): { bySurface: Map<string, ExampleCard[]>; byId: Map<string, { card: ExampleCard; surface: ExampleSurface }> } {const bySurface = new Map<string, { rank: number; card: ExampleCard }[]>();@@ -328,6 +361,16 @@ export function exampleRow(surface: ExampleSurface): ExampleRowData | null {return borrowed.length ? { heading: MORE_HEADING, cards: borrowed, surface } : null;}+/** Each Genjutsu mode's examples, best first (the page picks the one a viewer may see: exampleFor in ./genjutsu). */+export function genjutsuExamples(): ModeExamples {+ const out: ModeExamples = {};+ for (const m of GENJUTSU_MODES) {+ const cards = (ALL.bySurface.get(genjutsuSurface(m.id)) ?? []) as GenjutsuExampleCard[];+ if (cards.length) out[m.id] = cards;+ }+ return out;+}+/** The surface of a camera motion's or effect's page in the Video studio (/video?preset=<id>). */export const presetSurface = (id: string): ExampleSurface => (id.startsWith("app-") ? `app:${id}` : `preset:${id}`);diff --git a/src/lib/examples/genjutsu.ts b/src/lib/examples/genjutsu.tsnew file mode 100644index 00000000..9a834138--- /dev/null+++ b/src/lib/examples/genjutsu.ts@@ -0,0 +1,145 @@+/**+ * A Genjutsu mode's example (its card under the mode's title): which one a viewer sees, the settings it shows, and the+ * rules that make "Use this example" exact. The recipe is a setup (src/lib/catalog/genjutsu.ts) with the seed, the part's+ * length and the original sound, and none of the fields that describe the example's own clip or photos: those are the+ * viewer's to give. Client-safe: the catalog (catalog.ts) checks every row with these same rules when it is built.+ */+import { CHARACTER_SWAP } from "@/lib/catalog/character-swap";+import {+ ALL_FEATURES,+ decodeSetup,+ encodeSetup,+ GENJUTSU,+ getMaker,+ lookName,+ modeOpen,+ OPENJUTSU_LIMITS,+ SCENE_ACTIONS,+ type FeatureCheck,+ type GenjutsuMode,+ type GenjutsuSetup,+} from "@/lib/catalog/genjutsu";+import { originalSoundLabel } from "@/lib/av/original-sound";+import type { ExampleCard, ExampleSurface, GenjutsuExampleLoad, GenjutsuRecipe } from "./types";++/** The surface a mode's examples belong to: "tool:genjutsu/<mode>" (its id: "genjutsu-<mode>.<n>"). */+export const genjutsuSurface = (mode: GenjutsuMode): ExampleSurface => `tool:genjutsu/${mode}`;++/** A Genjutsu example card (its load is always "genjutsu"). */+export type GenjutsuExampleCard = ExampleCard & { load: GenjutsuExampleLoad };++/** Each mode's examples, best first. */+export type ModeExamples = Partial<Record<GenjutsuMode, GenjutsuExampleCard[]>>;++/**+ * Fields that describe the example's own clip or photos, never part of a recipe (cleared when it loads): the character+ * photo's description, who is who in the clip (roles, pins, the person's place or number, the words naming them).+ */+export const OWN_CHARACTER_FIELDS = ["description", "people", "who", "index", "subject"] as const;++/**+ * Words that came from the example's clip but often still fit the viewer's ("the dress"): loaded, with a note under the+ * field. Object swap's words naming what is swapped, and Scene edit's target.+ */+export const MARKED_NOTE = "From the example. Change it to fit your clip.";++/** The part a mode takes, in seconds (a model's own part where it has one). */+export function partLimits(mode: GenjutsuMode, model?: string): { min: number; max: number } {+ const own = getMaker(model)?.part;+ if (own) return own;+ if (mode === "character") return { min: CHARACTER_SWAP.minSeconds, max: CHARACTER_SWAP.maxSeconds };+ if (mode === "picture") return { min: OPENJUTSU_LIMITS.minSeconds, max: OPENJUTSU_LIMITS.maxSeconds };+ if (mode === "finish") return { min: 1, max: OPENJUTSU_LIMITS.coloursMaxSeconds };+ return { min: GENJUTSU.minSeconds, max: GENJUTSU.maxSeconds };+}++/** JSON with its keys in order: two setups with the same fields compare equal. */+function canonical(v: unknown): string {+ if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;+ if (v && typeof v === "object")+ return `{${Object.keys(v)+ .filter((k) => (v as Record<string, unknown>)[k] !== undefined)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${canonical((v as Record<string, unknown>)[k])}`)+ .join(",")}}`;+ return JSON.stringify(v);+}++/**+ * A form's setup as a recipe: its references and the fields about its own clip and photos left out, and the quality+ * left out where the model has none to pick (Finish keeps the clip's size). What "Use this example" compares with.+ */+export function toRecipe(s: GenjutsuSetup & { length?: number }): Omit<GenjutsuRecipe, "length"> & { length?: number } {+ const { references: _refs, ...rest } = s;+ void _refs;+ const out: Omit<GenjutsuRecipe, "length"> & { length?: number } = { ...rest };+ if (out.character) {+ const c: Record<string, unknown> = { ...out.character };+ for (const k of OWN_CHARACTER_FIELDS) delete c[k];+ if (Object.keys(c).length) out.character = c as GenjutsuSetup["character"];+ else delete out.character;+ }+ const maker = getMaker(s.model, s.engine);+ if (maker && !maker.qualities && !maker.h3) delete out.quality;+ if (s.mode === "finish") delete out.quality;+ if (out.object && !out.object.target) delete out.object.target;+ return out;+}++/** Whether two recipes run the same (the same fields, after a setup code's own checks). */+export function sameRecipe(a: Omit<GenjutsuRecipe, "length"> & { length?: number }, b: Omit<GenjutsuRecipe, "length"> & { length?: number }): boolean {+ const norm = (r: typeof a) => {+ const back = decodeSetup(encodeSetup(r)) ?? { mode: r.mode };+ // The part's length to the trimmer's 2 decimals: a part set from the example reads back as such.+ if (back.length !== undefined) back.length = Math.round(back.length * 100) / 100;+ return canonical(toRecipe(back));+ };+ return norm(a) === norm(b);+}++/** Why a row's recipe can't be an example (null: it can). The catalog fails the build on one. */+export function recipeProblem(r: GenjutsuRecipe, mode: GenjutsuMode): string | null {+ if (r.mode !== mode) return `its recipe runs ${r.mode}, not ${mode}`;+ if ((r as GenjutsuSetup).references) return "a recipe never names files: the viewer's own photos go in";+ for (const k of OWN_CHARACTER_FIELDS) if (r.character && k in r.character) return `character.${k} describes the example's own clip or photo`;+ const maker = getMaker(r.model, r.engine);+ if (!maker) return `its model ${r.model ?? "(none)"} isn't a Genjutsu model on the ${r.engine ?? "?"} engine`;+ if (!maker.modes.includes(r.mode)) return `${maker.id} doesn't run ${r.mode}`;+ const { min, max } = partLimits(r.mode, r.model);+ if (!(r.length >= min && r.length <= max)) return `its part (${r.length} s) is outside ${min}–${max} s`;+ // Every field survives a setup code: nothing a viewer loads is dropped or changed on the way.+ const back = decodeSetup(encodeSetup(r), ALL_FEATURES);+ if (!back || canonical(back) !== canonical(r)) return `its recipe doesn't survive a setup code (${canonical(back)})`;+ return null;+}++const seconds = (n: number) => `${Math.round(n * 10) / 10} s`;+const FINISH_LABEL: Record<string, string> = { soft: "Soft film", filmic: "Filmic", rich: "Rich", off: "Off" };++/** "Settings it used", as the form labels them (no model names: the owner's card adds the model). */+export function exampleSettings(r: GenjutsuRecipe): string[] {+ const out: string[] = [];+ const maker = getMaker(r.model, r.engine);+ // The tool's own name is a model's too: the finish says which one it was.+ if (r.mode === "finish" && r.finish) {+ if (r.finish.tool === "colours") {+ out.push(`Finish: ${FINISH_LABEL[r.finish.finish ?? "soft"]}`);+ out.push(`Strength ${Math.round((r.finish.strength ?? 0.4) * 100)}%`);+ out.push(`Soften detail ${Math.round((r.finish.soften ?? 0.33) * 100)}%`);+ }+ }+ if (r.object) out.push(SCENE_ACTIONS.find((a) => a.id === r.object!.action)!.label);+ if (r.look) out.push(`Look: ${lookName(r.look)}`);+ if (r.tier) out.push(r.tier === "high" ? "High" : "Standard");+ if (r.quality && maker && (maker.qualities || maker.h3)) out.push(r.quality);+ if (r.seed !== undefined) out.push(`Seed ${r.seed}`);+ out.push(`Part ${seconds(r.length)}`);+ if (r.originalSound) out.push(`Sound: ${originalSoundLabel(r.originalSound)}`);+ return out;+}++/** The example a viewer sees for a mode: the best one whose mode and features are open to them (none: no card). */+export function exampleFor(examples: ModeExamples | undefined, mode: GenjutsuMode, open: FeatureCheck): GenjutsuExampleCard | undefined {+ if (!modeOpen(mode, open)) return undefined;+ return examples?.[mode]?.find((c) => c.load.needs.every(open));+}diff --git a/src/lib/examples/media.generated.ts b/src/lib/examples/media.generated.tsindex 841fe993..4e0b3f7d 100644--- a/src/lib/examples/media.generated.ts+++ b/src/lib/examples/media.generated.ts@@ -6141,6 +6141,134 @@ export const EXAMPLE_MEDIA: Record<string, ExampleMediaFile> = {"w": 512,"h": 384},+ "/examples/genjutsu-character/1/in-clip.384.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 20494,+ "sha256": "7330bccee37efff3bb27bbc6f4b19af7398ef161ed6d157357d7dfcb3c581025",+ "v": "7330bcce",+ "w": 384,+ "h": 288+ },+ "/examples/genjutsu-character/1/in-clip.jpg": {+ "role": "in",+ "type": "image/jpeg",+ "bytes": 130131,+ "sha256": "a58db65b7b8fc4dce9dc4d43543f5a898a7eea187c7cb9007101babea48ec021",+ "v": "a58db65b",+ "w": 1024,+ "h": 768,+ "thumb": "/examples/genjutsu-character/1/in-clip.384.webp?v=7330bcce"+ },+ "/examples/genjutsu-character/1/in-photo1.384.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 4976,+ "sha256": "cf0b29f874fa35dda2b5d75a9511c98f20fd0a6d94b15398b70856f091029086",+ "v": "cf0b29f8",+ "w": 288,+ "h": 384+ },+ "/examples/genjutsu-character/1/in-photo1.jpg": {+ "role": "in",+ "type": "image/jpeg",+ "bytes": 123959,+ "sha256": "3fdc4cab67154768eb713fd54326513a255cc24952928273fa68f77307a77e03",+ "v": "3fdc4cab",+ "w": 960,+ "h": 1280,+ "thumb": "/examples/genjutsu-character/1/in-photo1.384.webp?v=cf0b29f8"+ },+ "/examples/genjutsu-character/1/in-photo2.384.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 4618,+ "sha256": "d199b904def0bb29a9c51de463133cf46aac892af9054b643723a600f40046a5",+ "v": "d199b904",+ "w": 288,+ "h": 384+ },+ "/examples/genjutsu-character/1/in-photo2.jpg": {+ "role": "in",+ "type": "image/jpeg",+ "bytes": 103273,+ "sha256": "ece6a208a4ab17f1c254b922ff53a1d356ee9761ba6a4e4ac448a0048aafa3ea",+ "v": "ece6a208",+ "w": 960,+ "h": 1280,+ "thumb": "/examples/genjutsu-character/1/in-photo2.384.webp?v=d199b904"+ },+ "/examples/genjutsu-character/1/show.mp4": {+ "role": "show",+ "type": "video/mp4",+ "bytes": 1109131,+ "sha256": "6d2fb1db6121dae6bf41f8a99bae62432b446750211f863aedc3d565f0cb858a",+ "v": "6d2fb1db",+ "poster": "/examples/genjutsu-character/1/show.poster.webp?v=6639a27c"+ },+ "/examples/genjutsu-character/1/show.peak.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 32068,+ "sha256": "a0a5bb65804309a65094690c2741a0915f4c0bffd940b35ba34518a702a0d0f1",+ "v": "a0a5bb65",+ "w": 512,+ "h": 384+ },+ "/examples/genjutsu-character/1/show.poster.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 73134,+ "sha256": "6639a27ce3efd0d00863b3bd03be3b39b32132233b1889d3bc7840516bc2de03",+ "v": "6639a27c",+ "w": 1024,+ "h": 768+ },+ "/examples/genjutsu-finish/1/in-clip.384.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 22564,+ "sha256": "1d9631ed9ec00dd0ea869293e218cfef72a1ea78a3019a8ba7c6cd830aec6859",+ "v": "1d9631ed",+ "w": 384,+ "h": 288+ },+ "/examples/genjutsu-finish/1/in-clip.jpg": {+ "role": "in",+ "type": "image/jpeg",+ "bytes": 132258,+ "sha256": "052a0f08de9d10ba1c7db6adf383d2a0db0d11ec9eeb3ce001b49e6a5a0e3d08",+ "v": "052a0f08",+ "w": 1024,+ "h": 768,+ "thumb": "/examples/genjutsu-finish/1/in-clip.384.webp?v=1d9631ed"+ },+ "/examples/genjutsu-finish/1/show.mp4": {+ "role": "show",+ "type": "video/mp4",+ "bytes": 929162,+ "sha256": "5fcb43976934bb5380a9f8ce6b1a7a9dbd672ba795e6d0dbcde4c4bc82358543",+ "v": "5fcb4397",+ "poster": "/examples/genjutsu-finish/1/show.poster.webp?v=e86785a4"+ },+ "/examples/genjutsu-finish/1/show.peak.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 20826,+ "sha256": "72772e4cacbb0938f7647cb7546375ff3ff18a8e4248b43c6fb9865a126c4202",+ "v": "72772e4c",+ "w": 512,+ "h": 384+ },+ "/examples/genjutsu-finish/1/show.poster.webp": {+ "role": "show",+ "type": "image/webp",+ "bytes": 77530,+ "sha256": "e86785a43477f83144837904306d04ffcfb0872469ab09109a00eb2e47fce8e9",+ "v": "e86785a4",+ "w": 1024,+ "h": 768+ },"/examples/image/1/out.512.webp": {"role": "show","type": "image/webp",diff --git a/src/lib/examples/plan.json b/src/lib/examples/plan.jsonindex 3845ee32..b1e3f180 100644--- a/src/lib/examples/plan.json+++ b/src/lib/examples/plan.json@@ -4705,5 +4705,81 @@"image": "/examples/app-upscale/1/in-image.jpg"},"output": "ba:app-upscale"+ },+ {+ "id": "genjutsu-character.1",+ "surface": "tool:genjutsu/character",+ "rank": 1,+ "caption": "Two people swapped in one take",+ "words": "A couple on sunny stone steps becomes two new people. The kiss on the cheek, the laugh and the light stay as filmed.",+ "load": "genjutsu",+ "genjutsu": {+ "layout": "inset",+ "went": "A 5 s clip and two photos",+ "recipe": {+ "mode": "character",+ "engine": "open",+ "model": "oss-h3-group-swap",+ "quality": "720p",+ "target": "type",+ "seed": 7,+ "length": 5.166,+ "originalSound": "everything"+ },+ "own": {+ "character": {+ "people": [+ {+ "role": "the woman on the left"+ },+ {+ "role": "the man on the right"+ }+ ]+ }+ }+ },+ "inputs": {+ "clip": "/examples/genjutsu-character/1/in-clip.jpg",+ "photo1": "/examples/genjutsu-character/1/in-photo1.jpg",+ "photo2": "/examples/genjutsu-character/1/in-photo2.jpg"+ },+ "output": "/examples/genjutsu-character/1/show.mp4",+ "rest": {+ "src": "/examples/genjutsu-character/1/show.peak.webp",+ "at": 4.717,+ "from": 0+ }+ },+ {+ "id": "genjutsu-finish.1",+ "surface": "tool:genjutsu/finish",+ "rank": 1,+ "caption": "A soft film finish at golden hour",+ "words": "The same take with a soft film finish: gentler contrast and smoother detail. Every frame and move stays as filmed.",+ "load": "genjutsu",+ "genjutsu": {+ "layout": "wipe",+ "went": "A 5 s clip",+ "recipe": {+ "mode": "finish",+ "engine": "open",+ "model": "oss-fix-colours",+ "finish": {+ "tool": "colours"+ },+ "length": 5.166,+ "originalSound": "everything"+ }+ },+ "inputs": {+ "clip": "/examples/genjutsu-finish/1/in-clip.jpg"+ },+ "output": "/examples/genjutsu-finish/1/show.mp4",+ "rest": {+ "src": "/examples/genjutsu-finish/1/show.peak.webp",+ "at": 4.717,+ "from": 0+ }}]diff --git a/src/lib/examples/types.ts b/src/lib/examples/types.tsindex 913c0429..28c5672f 100644--- a/src/lib/examples/types.ts+++ b/src/lib/examples/types.ts@@ -3,6 +3,7 @@* picture, a clip, a recording, words) and what came out; one tap puts its own files, words and settings into the* page's composer. Client-safe types: the catalog that builds them is server only (catalog.ts).*/+import type { GenjutsuFeature, GenjutsuSetup } from "@/lib/catalog/genjutsu";import type { GenerationRequest } from "@/lib/catalog/types";/** Where an example shows: an app, a camera motion or effect, a studio, a hub mode, a tool of its own, or a studio of the suite. */@@ -43,7 +44,28 @@ export type ExampleLoad =/** Every studio composer: the request goes into the draft. */| { via: "draft"; request: ExampleRequest }/** Look only: the card opens a sheet with what went in and what came out, or (a tile from another page) its page. */- | { via: "look"; href?: string };+ | { via: "look"; href?: string }+ /** A Genjutsu mode's example: its recipe goes into the Genjutsu form; the viewer's own clip and photos stay. */+ | GenjutsuExampleLoad;++/**+ * A Genjutsu mode's example (src/lib/examples/genjutsu.ts): one before → after loop, what went in, and the recipe that+ * made it. The recipe is a setup with the seed, the part's length and the sound, and none of the fields that point at+ * the example's own clip or photos (who is who, clicked points, the character's description).+ */+export interface GenjutsuExampleLoad {+ via: "genjutsu";+ /** "inset": the result fills the frame, the source plays in a corner window. "wipe": the source, then a line wipes to the result. */+ layout: "inset" | "wipe";+ /** What went in, in words ("A 5 s clip and two photos"). */+ went: string;+ recipe: GenjutsuRecipe;+ /** The features a viewer needs open to see it (src/server/genjutsu-live.ts); the owner sees every one. */+ needs: GenjutsuFeature[];+}++/** A Genjutsu setup as an example's recipe: the part's length is always in it, the example's own files never. */+export type GenjutsuRecipe = Omit<GenjutsuSetup, "references"> & { length: number };export interface ExampleInput {/** The composer slot it fills: image, image2, endImage, mask, video, audio… */diff --git a/tests/e2e/genjutsu-examples.mjs b/tests/e2e/genjutsu-examples.mjsnew file mode 100644index 00000000..cd18080b--- /dev/null+++ b/tests/e2e/genjutsu-examples.mjs@@ -0,0 +1,280 @@+// Genjutsu's mode examples, browser check at 390 and 1440 px, light and dark. Each mode tab: the selected mode's example+// card shows when the mode has one for this viewer (one card at most, none for a mode without one); its loop downloads+// only once the card is half in view and plays muted; nothing moves when it arrives; the pause button, the actions and+// the settings toggle are 44 px; switching modes drops the loop. Reduced motion: the finished result as a still, no+// download until Play. Visitors (--viewer guest | account: a studio with a password and public sign-up) see the video,+// the settings and Copy its setup, and no Use this example, no model names, no "Only you". The owner: Use this example+// with no clip marks the card "In use" (the form's setup equals the recipe), Undo puts the form back, and with a clip+// and the example's kind of photos the estimate's request body equals the run that made the example+// (tests/fixtures/genjutsu-examples/<id>.json; the clip, photos and who-is-who are the test's own).+// Usage: node tests/e2e/genjutsu-examples.mjs [appUrl] [--viewer owner|guest|account] [--shots <dir>] Exits 1 on a failed check.+import fs from "node:fs";+import path from "node:path";+import { launch, root, ENGINE } from "./_browser.mjs";++const argv = process.argv.slice(2);+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);+const app = (argv.find((a, i) => !a.startsWith("--") && !["--viewer", "--shots"].includes(argv[i - 1])) ?? "http://localhost:4001").replace(/\/$/, "");+const viewer = flag("--viewer") ?? "owner";+const shots = flag("--shots");+if (shots) fs.mkdirSync(shots, { recursive: true });+const visitor = viewer !== "owner";++const failures = [];+const check = (label, ok, extra = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(84)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};++const MODES = { motion: "Motion transfer", character: "Character swap", swap: "Object swap", restyle: "Restyle", insert: "Insert", picture: "From picture", finish: "Finish" };+// The examples in src/lib/examples/plan.json (load "genjutsu") and the features each needs open (requestFeatures).+const readJson = (p) => JSON.parse(fs.readFileSync(path.join(root, p), "utf8"));+const NEEDS = { "genjutsu-character.1": ["group-swap"], "genjutsu-finish.1": ["finish-colours"] };+const FEATURE_WORKFLOWS = { "group-swap": ["video-group-swap-h3"], "finish-colours": ["video-fix-colours"] };+const validated = new Set(readJson("workflows/comfyui/manifest.json").workflows.filter((w) => w.validated === true).map((w) => w.id));+const passed = readJson("workflows/comfyui/gpu-tested.json").features ?? {};+const live = (k) => passed[k]?.passed === true && FEATURE_WORKFLOWS[k].every((id) => validated.has(id));+const rows = readJson("src/lib/examples/plan.json").filter((r) => r.load === "genjutsu");+/** mode → the example this viewer should see (the best ranked whose features are open). */+const expected = {};+for (const r of [...rows].sort((a, b) => a.rank - b.rank)) {+ const mode = r.surface.replace("tool:genjutsu/", "");+ if (expected[mode]) continue;+ if (!visitor || (NEEDS[r.id] ?? []).every(live)) expected[mode] = r;+}++async function upload(file, type, name) {+ const form = new FormData();+ form.append("file", new Blob([fs.readFileSync(path.join(root, file))], { type }), name);+ const res = await fetch(`${app}/api/uploads`, { method: "POST", body: form });+ if (!res.ok) throw new Error(`upload failed: ${res.status}`);+ return (await res.json()).url;+}+const code = (o) => `gj2.${Buffer.from(JSON.stringify(o)).toString("base64url")}`;++const browser = await launch();+try {+ for (const scheme of ["light", "dark"]) {+ for (const [width, height] of [+ [390, 844],+ [1440, 900],+ ]) {+ const tag = `${viewer} ${width} ${scheme}`;+ const context = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, ...(width < 500 ? { isMobile: true, hasTouch: true } : {}) });+ await context.addInitScript(() => {+ try {+ localStorage.setItem("fuobe.engine", "open");+ } catch {}+ });+ if (viewer === "account") {+ const email = `gj-example-${Date.now()}-${width}-${scheme}@example.com`;+ const res = await context.request.post(`${app}/api/auth/signup`, { data: { email, password: "example-pass-1" } });+ check(`${tag}: an account signs up`, res.ok(), String(res.status()));+ }+ const page = await context.newPage();+ const mp4s = [];+ const runs = [];+ page.on("request", (r) => {+ if (/\/examples\/genjutsu-[a-z]+\/\d+\/show\.mp4/.test(r.url())) mp4s.push(r.url());+ if (r.method() === "POST" && r.url().endsWith("/api/genjutsu")) runs.push(r.url());+ });+ const shot = async (name) => shots && (await page.screenshot({ path: path.join(shots, `${viewer}-${name}-${width}-${scheme}.png`) }));+ const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ const open = async (url) => {+ await page.goto(`${app}${url}`, { waitUntil: "load", timeout: 180_000 });+ await page.getByRole("tablist", { name: "Genjutsu modes" }).waitFor({ timeout: 120_000 });+ await page.waitForTimeout(1200);+ };+ const cards = () => page.locator("[data-mode-example]");+ const card = () => cards().first();+ const box = (sel) => page.evaluate((s) => {+ const r = document.querySelector(s)?.getBoundingClientRect();+ return r ? [Math.round(r.x), Math.round(r.y + window.scrollY), Math.round(r.width), Math.round(r.height)].join(",") : null;+ }, sel);+ const playing = () =>+ page.evaluate(async () => {+ const v = document.querySelector("[data-example-video]");+ if (!v) return false;+ const t = v.currentTime;+ await new Promise((r) => setTimeout(r, 700));+ return !v.paused && v.muted && v.loop && v.currentTime !== t;+ });++ // Every open mode: a card where this viewer has an example, none elsewhere, one at most.+ await open("/genjutsu?mode=motion");+ check(`${tag}: no loop downloaded on a mode without an example`, expected.motion ? true : mp4s.length === 0, String(mp4s.length));+ const tabNames = (await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab").allInnerTexts()).map((t) => t.replace(/\s*Only you$/, "").trim());+ for (const [id, label] of Object.entries(MODES)) {+ if (!tabNames.includes(label)) continue;+ await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab", { name: new RegExp(`^${label}`) }).click();+ await page.waitForTimeout(500);+ const want = expected[id];+ const n = await cards().count();+ check(`${tag}: ${label} shows ${want ? `its example (${want.id})` : "no example card"}`, want ? n === 1 && (await card().getAttribute("data-mode-example")) === want.id : n === 0, `cards ${n}`);+ }++ for (const [id, row] of Object.entries(expected)) {+ const label = MODES[id];+ mp4s.length = 0;+ // The card off screen first (scrolled to the bottom): no download until it is half in view.+ await open(`/genjutsu?mode=${id}`);+ const shifts = await page.evaluate(() => {+ window.__shift = 0;+ new PerformanceObserver((l) => l.getEntries().forEach((e) => !e.hadRecentInput && (window.__shift += e.value))).observe({ type: "layout-shift", buffered: true });+ return true;+ });+ const c = card();+ await c.waitFor({ timeout: 30_000 });+ const before = await box("[data-mode-example]");+ const drop = await box("#gj-clip-drop");+ await c.scrollIntoViewIfNeeded();+ await page.waitForFunction(() => !!document.querySelector("[data-example-video]"), null, { timeout: 20_000 }).catch(() => {});+ await page.waitForTimeout(1500);+ check(`${tag} ${label}: the loop plays muted once in view`, await playing());+ check(`${tag} ${label}: one download of its loop`, mp4s.length >= 1 && mp4s.every((u) => u.includes(row.output)), JSON.stringify(mp4s.map((u) => u.replace(app, ""))));+ check(`${tag} ${label}: nothing moves when the loop arrives`, before === (await box("[data-mode-example]")) && drop === (await box("#gj-clip-drop")), `${before} / ${await box("[data-mode-example]")}`);+ if (ENGINE === "chromium" && shifts) {+ const cls = await page.evaluate(() => window.__shift);+ check(`${tag} ${label}: no layout shift (CLS ${cls.toFixed(3)})`, cls < 0.02);+ }+ const loopBox = await c.locator("[data-example-video]").boundingBox();+ check(`${tag} ${label}: the loop is 4:3 and at least 358 px wide`, !!loopBox && loopBox.width >= 340 && Math.abs(loopBox.width / loopBox.height - 4 / 3) < 0.02, loopBox ? `${Math.round(loopBox.width)}×${Math.round(loopBox.height)}` : "none");+ if (width >= 1440) {+ const side = await c.locator("figcaption").boundingBox();+ // 960 px with its 1 px border: the loop takes what the 352 px column leaves.+ check(`${tag} ${label}: 960 px card, a 352 px column beside the loop`, Math.round((await c.boundingBox()).width) === 960 && Math.round(side.width) === 352 && Math.round(loopBox.width) === 606, `${Math.round((await c.boundingBox()).width)} / ${Math.round(side.width)} / ${Math.round(loopBox.width)}`);+ }+ const sizes = await c.evaluate((el) => [...el.querySelectorAll("button, summary")].filter((b) => b.getClientRects().length).map((b) => `${b.getAttribute("aria-label") ?? b.textContent?.trim()}:${Math.round(b.getBoundingClientRect().width)}x${Math.round(b.getBoundingClientRect().height)}`));+ check(`${tag} ${label}: every target is 44 px or more`, sizes.every((s) => s.split(":").pop().split("x").every((d) => Number(d) >= 44) || /summary/.test(s)), JSON.stringify(sizes));+ const summary = c.locator("summary");+ if (await summary.isVisible()) check(`${tag} ${label}: "Settings it used" is a 44 px toggle`, ((await summary.boundingBox())?.height ?? 0) >= 44);+ // Pause and play.+ await c.getByRole("button", { name: "Pause the example" }).click();+ check(`${tag} ${label}: Pause stops the loop`, !(await playing()));+ await c.getByRole("button", { name: "Play the example" }).click();+ check(`${tag} ${label}: Play starts it again`, await playing());+ const text = await c.innerText();+ check(`${tag} ${label}: "EXAMPLE", the title and "What went in"`, /example/i.test(text) && text.includes(row.caption) && text.includes("What went in") && row.caption.length <= 40);+ check(`${tag} ${label}: no test words or file paths`, !/\b(test|pass(ed)?|owner|validated|oss-|\/api\/)/i.test(text), text.replace(/\s+/g, " ").slice(0, 160));+ if (visitor) {+ check(`${tag} ${label}: a visitor has no Use this example`, (await c.locator("[data-use-example]").count()) === 0);+ check(`${tag} ${label}: a visitor can copy its setup`, await c.getByRole("button", { name: /Copy its setup/ }).isVisible());+ check(`${tag} ${label}: no model names and no "Only you" for a visitor`, !/Group swap|Colour finish|Only you|MiniMax|H3/.test(text));+ } else {+ check(`${tag} ${label}: the owner has Use this example`, await c.locator("[data-use-example]").isVisible());+ }+ check(`${tag} ${label}: fits the screen`, (await sideways()) <= 0);+ await shot(`${id}`);+ // Leaving the mode drops the loop.+ await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab", { name: /^Motion transfer/ }).click();+ await page.waitForTimeout(400);+ check(`${tag} ${label}: leaving the mode removes its loop`, (await page.locator("[data-example-video]").count()) === 0 && (await cards().count()) === (expected.motion ? 1 : 0));++ // The owner: Use this example with no clip puts the exact recipe in the form ("In use"), and Undo takes it out.+ if (!visitor && scheme === "light") {+ await open(`/genjutsu?mode=${id}`);+ await card().locator("[data-use-example]").click();+ await page.waitForTimeout(600);+ const used = card().locator("[data-use-example]");+ check(`${tag} ${label}: Use this example fills the form exactly ("In use")`, (await used.innerText()).includes("In use"), await used.innerText());+ check(`${tag} ${label}: it runs nothing (no run request)`, runs.length === 0);+ const undo = page.getByRole("button", { name: "Undo" });+ if (await undo.isVisible().catch(() => false)) {+ await undo.click();+ await page.waitForTimeout(500);+ check(`${tag} ${label}: Undo puts the form back`, (await card().locator("[data-use-example]").innerText()).includes("Use this example"));+ } else check(`${tag} ${label}: the toast offers Undo`, false);+ }+ }+ await context.close();++ // Reduced motion: the result as a still, the loop only on Play.+ if (scheme === "light") {+ const first = Object.entries(expected)[0];+ if (first) {+ const [id, row] = first;+ const rc = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce", ...(width < 500 ? { isMobile: true, hasTouch: true } : {}) });+ if (viewer === "account") await rc.request.post(`${app}/api/auth/signup`, { data: { email: `gj-example-rm-${Date.now()}-${width}@example.com`, password: "example-pass-1" } });+ const p = await rc.newPage();+ const got = [];+ p.on("request", (r) => r.url().includes("/show.mp4") && got.push(r.url()));+ await p.goto(`${app}/genjutsu?mode=${id}`, { waitUntil: "load", timeout: 180_000 });+ const c = p.locator("[data-mode-example]").first();+ await c.waitFor({ timeout: 60_000 });+ await c.scrollIntoViewIfNeeded();+ await p.waitForTimeout(2000);+ const still = await c.locator("img").first().getAttribute("src");+ check(`${tag} reduced motion: the finished result as a still`, !!still && still.includes(row.rest.src) && (await c.locator("[data-example-video]").count()) === 0, String(still));+ check(`${tag} reduced motion: no download before Play`, got.length === 0, String(got.length));+ await c.getByRole("button", { name: "Play the example" }).click();+ await p.waitForTimeout(1500);+ check(`${tag} reduced motion: Play loads and plays it`, got.length >= 1 && (await p.evaluate(() => !document.querySelector("[data-example-video]")?.paused)));+ await rc.close();+ }+ }+ }+ }++ // The owner with a clip: the estimate's body equals the run that made each example.+ if (!visitor) {+ const clip = await upload("scripts/eval/fixtures/walk-6s.mp4", "video/mp4", "walk.mp4");+ const pics = [await upload("scripts/eval/fixtures/character/drawn-face-2.png", "image/png", "p1.png"), await upload("scripts/eval/fixtures/character/drawn-face-2.png", "image/png", "p2.png")];+ for (const width of [390, 1440]) {+ for (const row of Object.values(expected)) {+ const fixture = readJson(`tests/fixtures/genjutsu-examples/${row.id}.json`).body;+ const mode = row.genjutsu.recipe.mode;+ const context = await browser.newContext({ viewport: { width, height: 900 }, ...(width < 500 ? { isMobile: true, hasTouch: true } : {}) });+ await context.addInitScript(() => {+ try {+ localStorage.setItem("fuobe.engine", "open");+ } catch {}+ });+ const page = await context.newPage();+ const bodies = [];+ const runs = [];+ page.on("request", (r) => {+ if (r.method() !== "POST") return;+ if (r.url().endsWith("/api/genjutsu/estimate")) bodies.push(JSON.parse(r.postData() ?? "{}"));+ else if (r.url().endsWith("/api/genjutsu")) runs.push(r.url());+ });+ const refs = fixture.references.length ? { r: pics.slice(0, fixture.references.length) } : {};+ await page.goto(`${app}/genjutsu?video=${encodeURIComponent(clip)}&setup=${code({ m: mode, e: "open", ...refs })}`, { waitUntil: "load", timeout: 180_000 });+ const rowEl = page.locator("[data-mode-example-row]");+ await rowEl.waitFor({ timeout: 120_000 }).catch(() => {});+ check(`owner ${width} ${row.id}: with a clip, one "Example:" row in the side panel`, (await rowEl.count()) === 1 && (await page.locator("[data-mode-example]").count()) === 0);+ await rowEl.getByRole("button", { name: "See it" }).click();+ const dialog = page.getByRole("dialog");+ await dialog.waitFor({ timeout: 10_000 });+ await dialog.locator("[data-use-example]").click();+ await page.waitForTimeout(800);+ // Who is who in the example's own clip is the viewer's to give: the test gives the example's.+ const people = row.genjutsu.own?.character?.people ?? [];+ for (let i = 0; i < people.length; i++) {+ const field = page.getByRole("textbox", { name: `Character ${i + 1} replaces` });+ check(`owner ${width} ${row.id}: who becomes who is asked again (empty)`, (await field.inputValue()) === "");+ await field.fill(people[i].role);+ }+ await page.waitForTimeout(1500);+ const last = bodies.at(-1);+ const strip = (b) => {+ // The clip, its first frame's size and the photos are the viewer's own (the test's here).+ const rest = Object.fromEntries(Object.entries(b ?? {}).filter(([k]) => !["source", "references", "requestId", "frame"].includes(k)));+ // Finish keeps the clip's size: its quality plays no part in the run (tests/genjutsu-examples.test.ts).+ if (rest.mode === "finish") delete rest.quality;+ return JSON.stringify(Object.keys(rest).sort().reduce((o, k) => ((o[k] = rest[k]), o), {}));+ };+ check(`owner ${width} ${row.id}: the form's request equals the run that made it`, !!last && strip(last) === strip(fixture), `\n form: ${strip(last)}\n run: ${strip(fixture)}`);+ check(`owner ${width} ${row.id}: the photos are the viewer's own`, !!last && JSON.stringify(last.references) === JSON.stringify(refs.r ?? []));+ check(`owner ${width} ${row.id}: Use this example ran nothing`, runs.length === 0);+ await context.close();+ }+ }+ }+} finally {+ await browser.close();+}+if (failures.length) {+ console.log(`\n${failures.length} failed`);+ process.exit(1);+}+console.log("\nall passed");diff --git a/tests/examples-catalog.test.ts b/tests/examples-catalog.test.tsindex d77a42f0..3df13218 100644--- a/tests/examples-catalog.test.ts+++ b/tests/examples-catalog.test.ts@@ -5,6 +5,7 @@ import { getModel, getPreset, MODELS } from "@/lib/catalog";import type { StudioConfig } from "@/components/studio/studio-context";import { HOME_CAPTION_MAX } from "@/lib/home-showcase";import { HUB_MODES, type HubKind } from "@/lib/hubs";+import { GENJUTSU_MODES } from "@/lib/catalog/genjutsu";import { appStudio, EDIT_STUDIO, IMAGE_STUDIO, INPAINT_STUDIO, UPSCALE_STUDIO, VIDEO_STUDIO } from "@/lib/studios";import { EXAMPLE_MEDIA } from "@/lib/examples/media.generated";import { EXAMPLE_CAPTION_MAX, EXAMPLE_WORDS_MAX, EXAMPLES_HEADING, MORE_HEADING, exampleFits, type ExampleCard, type ExampleMedia } from "@/lib/examples/types";@@ -38,6 +39,9 @@ function pageExists(surface: string): boolean {if (!(hub in HUB_MODES)) return false;return !mode || HUB_MODES[hub as HubKind].some((m) => m.id === mode);}+ // A Genjutsu mode's examples: the Genjutsu page, on that mode (?mode=).+ const genjutsu = /^genjutsu\/([a-z]+)$/.exec(name);+ if (kind === "tool" && genjutsu) return GENJUTSU_MODES.some((m) => m.id === genjutsu[1]);return fs.existsSync(path.join(root, "src", "app", "(studio)", ...name.split("/"), "page.tsx"));}diff --git a/tests/fixtures/genjutsu-examples/genjutsu-character.1.json b/tests/fixtures/genjutsu-examples/genjutsu-character.1.jsonnew file mode 100644index 00000000..4f1b40ad--- /dev/null+++ b/tests/fixtures/genjutsu-examples/genjutsu-character.1.json@@ -0,0 +1,16 @@+{+ "id": "genjutsu-character.1",+ "note": "The request body of the run that made this example (file addresses replaced by neutral ones).",+ "body": {+ "engine": "open",+ "mode": "character",+ "modelId": "oss-h3-group-swap",+ "quality": "720p",+ "target": "type",+ "references": ["/api/files/example-photo1.png", "/api/files/example-photo2.png"],+ "source": { "url": "/api/files/example-clip.mp4", "name": "clip.mp4", "duration": 5.166, "fps": 24, "width": 1024, "height": 768, "hasAudio": true },+ "range": { "start": 0, "end": 5.166 },+ "seed": 7,+ "character": { "people": [{ "role": "the woman on the left" }, { "role": "the man on the right" }] }+ }+}diff --git a/tests/fixtures/genjutsu-examples/genjutsu-finish.1.json b/tests/fixtures/genjutsu-examples/genjutsu-finish.1.jsonnew file mode 100644index 00000000..4d788323--- /dev/null+++ b/tests/fixtures/genjutsu-examples/genjutsu-finish.1.json@@ -0,0 +1,13 @@+{+ "id": "genjutsu-finish.1",+ "note": "The request body of the run that made this example (file addresses replaced by neutral ones).",+ "body": {+ "engine": "open",+ "mode": "finish",+ "modelId": "oss-fix-colours",+ "references": [],+ "source": { "url": "/api/files/example-clip.mp4", "name": "clip.mp4", "duration": 5.166, "fps": 24, "width": 1024, "height": 768, "hasAudio": true },+ "range": { "start": 0, "end": 5.166 },+ "finish": { "tool": "colours" }+ }+}diff --git a/tests/genjutsu-examples.test.ts b/tests/genjutsu-examples.test.tsnew file mode 100644index 00000000..89a263f0--- /dev/null+++ b/tests/genjutsu-examples.test.ts@@ -0,0 +1,195 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it, vi } from "vitest";+import {+ ALL_FEATURES,+ decodeSetup,+ encodeSetup,+ GENJUTSU_MODES,+ getMaker,+ modeOpen,+ planGenjutsu,+ type GenjutsuMode,+ type GenjutsuPlanInput,+ type GenjutsuSetup,+} from "@/lib/catalog/genjutsu";+import { exampleFor, exampleSettings, recipeProblem, sameRecipe, toRecipe } from "@/lib/examples/genjutsu";+import type { GenjutsuRecipe } from "@/lib/examples/types";+import { genjutsuLive } from "@/server/genjutsu-live";+import plan from "@/lib/examples/plan.json";++// Each Genjutsu mode's example: one card per mode, its recipe exact (a setup code keeps every field, and the recipe plus+// the example's own inputs plans the same run as the one that made it), the fields about the example's own clip and+// photos never in a recipe, and a viewer sees only an example whose mode and model are open to them.++// home-showcase.ts (which the catalog's fallback rows borrow from) imports next/cache.+vi.mock("next/cache", () => ({ cacheLife: () => {} }));+const { genjutsuExamples } = await import("@/lib/examples/catalog");++type Row = { id: string; surface: string; load?: string; genjutsu?: { recipe: GenjutsuRecipe; own?: { character?: Record<string, unknown> } } };+const rows = (plan as Row[]).filter((r) => r.load === "genjutsu");+const examples = genjutsuExamples();+const none = () => false;++/** A run's request body, as the form sends it (src/components/genjutsu/genjutsu-studio.tsx). */+interface Body {+ engine: "open" | "cloud";+ mode: GenjutsuMode;+ modelId: string;+ tier?: "standard" | "high";+ quality?: string;+ target?: GenjutsuPlanInput["target"];+ references: string[];+ source: GenjutsuPlanInput["source"] & { name?: string };+ range: { start: number; end: number };+ seed?: number;+ character?: GenjutsuPlanInput["character"];+ object?: GenjutsuPlanInput["object"];+ finish?: GenjutsuPlanInput["finish"];+ originalSound?: GenjutsuPlanInput["originalSound"];+}++/** The run a body plans: every step's request, as the server would queue it. */+const planOf = (b: Body) =>+ planGenjutsu({+ engine: b.engine,+ mode: b.mode,+ maker: getMaker(b.modelId, b.engine)!,+ title: "Genjutsu",+ source: b.source,+ range: b.range,+ // A body with no quality (a Finish run) plans with the form's default.+ quality: b.quality ?? "720p",+ references: b.references,+ ...(b.target && { target: b.target }),+ ...(b.seed !== undefined && { seed: b.seed }),+ ...(b.character && { character: b.character }),+ ...(b.object && { object: b.object }),+ ...(b.finish && { finish: b.finish }),+ ...(b.originalSound && { originalSound: b.originalSound }),+ });++/** "Use this example" on the example's own clip and photos, with who-is-who given again: the body the form sends. */+function remake(recipe: GenjutsuRecipe, own: { character?: Record<string, unknown> } | undefined, run: Body, quality = "720p"): Body {+ return {+ engine: recipe.engine ?? "open",+ mode: recipe.mode,+ modelId: recipe.model!,+ ...(recipe.tier && { tier: recipe.tier }),+ // A recipe with no quality keeps the form's own (Finish keeps the clip's size).+ quality: recipe.quality ?? quality,+ ...(recipe.target && { target: recipe.target }),+ references: run.references,+ source: run.source,+ range: { start: 0, end: Math.min(run.source.duration ?? recipe.length, recipe.length) },+ ...(recipe.seed !== undefined && { seed: recipe.seed }),+ ...((recipe.character || own?.character) && { character: { ...recipe.character, ...own?.character } }),+ ...(recipe.object && { object: recipe.object }),+ ...(recipe.finish && { finish: recipe.finish }),+ ...(recipe.originalSound && recipe.originalSound !== "everything" && { originalSound: recipe.originalSound }),+ };+}++describe("Genjutsu mode examples", () => {+ it("each example sits on a real mode, one card list per mode, best first", () => {+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) {+ const mode = r.surface.replace("tool:genjutsu/", "");+ expect(GENJUTSU_MODES.map((m) => m.id), r.id).toContain(mode);+ expect(examples[mode as GenjutsuMode]?.some((c) => c.id === r.id), r.id).toBe(true);+ }+ });++ it("every recipe survives a gj2 setup code with nothing dropped, and gj1 codes still read", () => {+ for (const r of rows) {+ const recipe = r.genjutsu!.recipe;+ expect(recipeProblem(recipe, recipe.mode), r.id).toBeNull();+ const code = encodeSetup(recipe);+ expect(code).toMatch(/^gj2\./);+ expect(decodeSetup(code, ALL_FEATURES), r.id).toEqual(recipe);+ expect(sameRecipe(toRecipe(decodeSetup(code)!), recipe), r.id).toBe(true);+ }+ const gj1 = `gj1.${Buffer.from(JSON.stringify({ m: "finish", e: "open", f: { tool: "colours" } })).toString("base64url")}`;+ expect(decodeSetup(gj1)).toMatchObject({ mode: "finish", engine: "open", finish: { tool: "colours" } });+ });++ it("gj2 keeps the seed, the part's length and the sound, and drops what is out of range", () => {+ const s: GenjutsuSetup = { mode: "character", engine: "open", model: "oss-h3-group-swap", quality: "720p", target: "type", seed: 123456, length: 5.1666, originalSound: "music-effects" };+ expect(decodeSetup(encodeSetup(s))).toMatchObject({ seed: 123456, length: 5.167, originalSound: "music-effects" });+ const bad = `gj2.${Buffer.from(JSON.stringify({ m: "finish", sd: -4, pl: 600, os: "loud" })).toString("base64url")}`;+ const back = decodeSetup(bad)!;+ expect(back.seed).toBeUndefined();+ expect(back.length).toBeUndefined();+ expect(back.originalSound).toBeUndefined();+ });++ it("a recipe never names the example's files or who is who in its clip", () => {+ const base: GenjutsuRecipe = { mode: "character", engine: "open", model: "oss-h3-group-swap", quality: "720p", target: "type", length: 5 };+ expect(recipeProblem(base, "character")).toBeNull();+ expect(recipeProblem({ ...base, references: ["/api/files/a.png"] } as GenjutsuRecipe, "character")).toMatch(/files/);+ for (const k of ["description", "people", "who", "index", "subject"]) expect(recipeProblem({ ...base, character: { [k]: k === "index" ? 1 : "x" } } as GenjutsuRecipe, "character"), k).toMatch(new RegExp(`character\\.${k}`));+ expect(recipeProblem(base, "finish")).toMatch(/runs character/);+ expect(recipeProblem({ ...base, length: 40 }, "character")).toMatch(/outside/);+ // The form's own clip and photos fall out of a setup before it is compared with an example.+ expect(toRecipe({ ...base, references: ["/api/files/mine.png"], character: { people: [{ role: "the man" }] } as GenjutsuSetup["character"] })).toEqual(base);+ });++ it("the recipe plus the example's own clip and photos plans the same run as the one that made it", () => {+ const dir = path.join(process.cwd(), "tests", "fixtures", "genjutsu-examples");+ for (const r of rows) {+ const file = path.join(dir, `${r.id}.json`);+ expect(fs.existsSync(file), `${r.id}: its run's fixture`).toBe(true);+ const run = (JSON.parse(fs.readFileSync(file, "utf8")) as { body: Body }).body;+ const again = remake(r.genjutsu!.recipe, r.genjutsu!.own, run);+ expect(again.modelId, r.id).toBe(run.modelId);+ expect(again.range, r.id).toEqual(run.range);+ expect(planOf(again), r.id).toEqual(planOf(run));+ // A recipe with no quality of its own: the form's quality changes nothing in the run.+ if (!r.genjutsu!.recipe.quality) for (const q of ["480p", "1080p", "4K"]) expect(planOf(remake(r.genjutsu!.recipe, r.genjutsu!.own, run, q)), `${r.id} ${q}`).toEqual(planOf(run));+ }+ });++ it("the settings list names no model, no file and no test words", () => {+ for (const r of rows) {+ const list = exampleSettings(r.genjutsu!.recipe).join(" | ");+ expect(list, r.id).not.toMatch(/oss-|fuobe-|H3|Wan|test|pass|owner|\/api\//i);+ expect(list, r.id).toMatch(/Part \d/);+ }+ expect(exampleSettings({ mode: "finish", engine: "open", model: "oss-fix-colours", finish: { tool: "colours" }, length: 5.166, originalSound: "everything" })).toEqual([+ "Finish: Soft film",+ "Strength 40%",+ "Soften detail 33%",+ "Part 5.2 s",+ "Sound: Everything",+ ]);+ });++ it("a viewer sees an example only where its mode and its model are open to them; the owner sees every one", () => {+ for (const m of GENJUTSU_MODES) {+ const cards = examples[m.id] ?? [];+ // The owner: the best example of every mode that has one.+ expect(exampleFor(examples, m.id, ALL_FEATURES)?.id, m.id).toBe(cards[0]?.id);+ // Nothing open: only the five first modes show, and only an example that needs nothing.+ const closed = exampleFor(examples, m.id, none);+ if (closed) expect(closed.load.needs, m.id).toEqual([]);+ if (!modeOpen(m.id, none)) expect(closed, m.id).toBeUndefined();+ }+ for (const r of rows) {+ const card = Object.values(examples)+ .flat()+ .find((c) => c!.id === r.id)!;+ const mode = card.load.recipe.mode;+ // Each feature it needs closes it on its own.+ for (const f of card.load.needs) expect(exampleFor(examples, mode, (g) => g !== f)?.id === r.id, `${r.id} without ${f}`).toBe(false);+ // The committed gate (src/server/genjutsu-live.ts): what a visitor sees today.+ const live = genjutsuLive();+ const visitor = exampleFor(examples, mode, (f) => !!live[f]);+ if (card.load.needs.every((f) => live[f])) expect(visitor?.id, r.id).toBe(r.id);+ else expect(visitor?.id === r.id, r.id).toBe(false);+ }+ });++ it("only modes with an example show a card (no empty card)", () => {+ for (const m of GENJUTSU_MODES) if (!examples[m.id]) expect(exampleFor(examples, m.id, ALL_FEATURES)).toBeUndefined();+ });+});diff --git a/tests/genjutsu-live.test.ts b/tests/genjutsu-live.test.tsindex 97718d0f..104a29d0 100644--- a/tests/genjutsu-live.test.ts+++ b/tests/genjutsu-live.test.ts@@ -49,7 +49,7 @@ describe("Genjutsu's live gate", () => {expect(Object.keys(record.features).sort()).toEqual(["finish-colours", "group-swap"]);expect(Object.entries(genjutsuLive()).filter(([, on]) => on).map(([k]) => k).sort()).toEqual(["finish-colours", "group-swap"]);const page = fs.readFileSync(path.join(ROOT, "src/app/(studio)/genjutsu/page.tsx"), "utf8");- expect(page).toMatch(/<GenjutsuStudio examples=\{exampleRow\("tool:genjutsu"\)\} live=\{genjutsuLive\(\)\} \/>/);+ expect(page).toMatch(/<GenjutsuStudio examples=\{exampleRow\("tool:genjutsu"\)\} modeExamples=\{genjutsuExamples\(\)\} live=\{genjutsuLive\(\)\} \/>/);// The studio shows a feature when it is live or the viewer is the owner.const studio = fs.readFileSync(path.join(ROOT, "src/components/genjutsu/genjutsu-studio.tsx"), "utf8");expect(studio).toContain("const open: FeatureCheck = useCallback((f) => owner || !!live?.[f], [owner, live]);");diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.tsindex 5fb88e21..0d150561 100644--- a/tests/genjutsu.test.ts+++ b/tests/genjutsu.test.ts@@ -534,7 +534,7 @@ describe("Genjutsu: setup codes", () => {character: { who: "index" as const, index: 2, subject: "man in red", anchor: false, description: "a ronin", speech: "other" as const, lora: "v1" as const, windowFrames: 158 },};const code = encodeSetup(setup);- expect(code).toMatch(/^gj1\.[A-Za-z0-9_-]+$/);+ expect(code).toMatch(/^gj2\.[A-Za-z0-9_-]+$/);expect(decodeSetup(code)).toEqual(setup);expect(decodeSetup(` http://localhost:3000/genjutsu?setup=${code} `)).toEqual(setup);expect(decodeSetup(encodeSetup({ mode: "character", character: { dialogue: "secret words", who: "largest" } as never }))?.character).toEqual({ who: "largest" });