Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Tests: Genjutsu's new modes, their gate and graphs

Adarsh9b817ddc7d17
diff --git a/scripts/eval/cases/genjutsu.json b/scripts/eval/cases/genjutsu.json
index 591f9ab0..864ee3b0 100644
--- a/scripts/eval/cases/genjutsu.json
+++ b/scripts/eval/cases/genjutsu.json
@@ -333,6 +333,321 @@
"requestId": "{{requestId}}"
}
}
+ },
+ {
+ "id": "genjutsu/group",
+ "title": "Group swap: two characters, each taking over the person named",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-group-swap"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/duo.mp4",
+ "images": ["local/genjutsu/character.png", "local/genjutsu/character2.png"]
+ },
+ "metrics": ["temporal", "identity", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "character",
+ "references": ["{{inputs.images.0}}", "{{inputs.images.1}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "quality": "720p",
+ "character": {
+ "people": [
+ {
+ "role": "the person on the left"
+ },
+ {
+ "role": "the person on the right"
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/group-one-by-one",
+ "title": "Group swap, one by one: a pass for each person",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-group-swap"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/duo.mp4",
+ "images": ["local/genjutsu/character.png", "local/genjutsu/character2.png"]
+ },
+ "metrics": ["temporal", "identity", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "character",
+ "references": ["{{inputs.images.0}}", "{{inputs.images.1}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "quality": "720p",
+ "character": {
+ "people": [
+ {
+ "role": "the person on the left"
+ },
+ {
+ "role": "the person on the right"
+ }
+ ],
+ "onePerPerson": true
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/scene-change",
+ "title": "Scene edit: the coat becomes a crimson velvet tailored blazer",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-scene-edit"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/street.mp4",
+ "images": ["local/genjutsu/object.png"]
+ },
+ "metrics": ["temporal", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "swap",
+ "target": "type",
+ "references": ["{{inputs.images.0}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "quality": "720p",
+ "object": {
+ "action": "change",
+ "target": "coat",
+ "becomes": "a crimson velvet tailored blazer"
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/scene-remove",
+ "title": "Scene edit: the handbag is removed and the boulevard continues",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-scene-edit"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/street.mp4"
+ },
+ "metrics": ["temporal", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "swap",
+ "target": "type",
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "quality": "720p",
+ "object": {
+ "action": "remove",
+ "target": "handbag"
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/scene-background",
+ "title": "Scene edit: the people on an Amalfi cliff terrace at golden hour",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-scene-edit"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/dance.mp4"
+ },
+ "metrics": ["temporal", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "swap",
+ "target": "type",
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "quality": "720p",
+ "object": {
+ "action": "background",
+ "target": "the people",
+ "becomes": "an Amalfi cliff terrace at golden hour, the sea below"
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/picture",
+ "title": "From picture: the character in the clip's first-frame pose, in the picture's setting (the first frame)",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-from-picture"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/dance.mp4",
+ "images": ["local/genjutsu/character.png"]
+ },
+ "metrics": ["clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "picture",
+ "references": ["{{inputs.images.0}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "picture": {
+ "stage": "frame"
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/picture-golden-halo",
+ "title": "From picture with the Golden halo light (the first frame)",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-from-picture"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/dance.mp4",
+ "images": ["local/genjutsu/character.png"]
+ },
+ "metrics": ["clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "picture",
+ "references": ["{{inputs.images.0}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "picture": {
+ "stage": "frame",
+ "light": {
+ "look": "golden-halo"
+ }
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/fix-faces",
+ "title": "Fix faces: small faces redrawn to match the character photo",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-h3-fix-faces"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/duo.mp4",
+ "images": ["local/genjutsu/character.png"]
+ },
+ "metrics": ["temporal", "identity", "clip"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "finish",
+ "references": ["{{inputs.images.0}}"],
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "finish": {
+ "tool": "faces",
+ "faceStyle": "mouth"
+ }
+ }
+ }
+ },
+ {
+ "id": "genjutsu/fix-colours",
+ "title": "Fix colours: the soft film finish",
+ "engines": ["open"],
+ "models": {
+ "open": ["oss-fix-colours"]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4"
+ },
+ "metrics": ["temporal"],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "modelId": "{{modelId}}",
+ "source": "{{source:inputs.video}}",
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}",
+ "mode": "finish",
+ "range": {
+ "start": 0,
+ "end": 6
+ },
+ "finish": {
+ "tool": "colours",
+ "finish": "soft"
+ }
+ }
+ }
}
]
}
diff --git a/tests/assist-polish.test.ts b/tests/assist-polish.test.ts
index 137d9557..170b8a79 100644
--- a/tests/assist-polish.test.ts
+++ b/tests/assist-polish.test.ts
@@ -37,9 +37,10 @@ describe("the 390 px sweep visits dynamic routes", () => {
for (const p of patterns) expect(byPattern[p]?.length, p).toBeGreaterThan(0);
expect(urls.filter((u) => /\[/.test(u))).toEqual([]);
expect(urls).toEqual(expect.arrayContaining(["/cinema/c1", "/cinema/does-not-exist", "/canvas/v1", "/canvas/does-not-exist", "/assist/projects/p1", "/apps/does-not-exist"]));
- // Dialogs a query opens: a skill's Run form.
- expect(querySamples({ recipeSkill: "lamp" })).toEqual(["/assist/skills?run=lamp", "/assist/skills?run=does-not-exist"]);
- expect(querySamples()).toEqual(["/assist/skills?run=does-not-exist"]);
+ // Dialogs and tabs a query opens: a skill's Run form, Genjutsu's From picture and Finish tabs.
+ const genjutsu = ["/genjutsu?mode=picture", "/genjutsu?mode=finish"];
+ expect(querySamples({ recipeSkill: "lamp" })).toEqual(["/assist/skills?run=lamp", "/assist/skills?run=does-not-exist", ...genjutsu]);
+ expect(querySamples()).toEqual(["/assist/skills?run=does-not-exist", ...genjutsu]);
});
it("gives a route added later (another branch's /faceless/[id]/[episode]) a not-found sample by itself", () => {
diff --git a/tests/comfy-dbs.test.ts b/tests/comfy-dbs.test.ts
index 899ed63f..01fb9eb7 100644
--- a/tests/comfy-dbs.test.ts
+++ b/tests/comfy-dbs.test.ts
@@ -304,7 +304,7 @@ describe("licences, as information", () => {
expect(entry.notes).toMatch(/NC variants included; whether that reaches the weights or their outputs is unresolved/);
// Still information: the workflow's licence row reads Apache-2.0, nothing is flagged or hidden for it.
expect(licenceInfo(workflowLicence(entry)).class).toBe("commercial");
- expect(ATTRIBUTIONS.filter((a) => a.licence === "MIT").map((a) => a.text)).toEqual([
+ expect(ATTRIBUTIONS.filter((a) => a.licence === "MIT" && a.for === "Dialogue, music and effects separation").map((a) => a.text)).toEqual([
"BS-RoFormer, copyright (c) 2023 Phil Wang",
"Music-Source-Separation-Training, copyright (c) 2024 Roman Solovyev (ZFTurbo)",
"TIGER / Look2Hear, copyright (c) 2026 Kai Li",
diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.ts
index b6ad70ee..c0117068 100644
--- a/tests/comfy-library-4.test.ts
+++ b/tests/comfy-library-4.test.ts
@@ -156,6 +156,17 @@ describe("round-4 ComfyUI workflows", () => {
"any-angle-3d",
"any-angle-shot",
"video-regenerate-h3",
+ // Genjutsu's Openjutsu modes: their packs aren't on the validation server yet; each opens only after its /prompt
+ // check and a real render (workflows/comfyui/gpu-tested.json, src/server/genjutsu-live.ts).
+ "video-group-swap-h3",
+ "video-group-swap-h3-one-by-one",
+ "video-scene-edit-h3",
+ "image-from-picture-prepare",
+ "video-scene-describe",
+ "video-from-picture-solar",
+ "video-from-picture-h3",
+ "video-fix-faces-h3",
+ "video-fix-colours",
]);
for (const w of manifest.workflows) for (const o of w.outputs) if (o.role) expect(ROLES, `${w.id} ${o.role}`).toContain(o.role);
});
diff --git a/tests/comfy-openjutsu-modes.test.ts b/tests/comfy-openjutsu-modes.test.ts
new file mode 100644
index 00000000..6e6c208b
--- /dev/null
+++ b/tests/comfy-openjutsu-modes.test.ts
@@ -0,0 +1,99 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import type { ComfyWorkflow, Manifest } from "@/lib/comfy";
+import { getModel } from "@/lib/catalog";
+import { ATTRIBUTIONS, nodePack } from "@/lib/licences";
+import { OPENJUTSU_WORKFLOWS } from "@/lib/openjutsu-graphs";
+import { resolveWorkflowId } from "@/lib/comfy-variants";
+
+// Genjutsu's Openjutsu modes in the ComfyUI library: nine graphs with pinned weights, their node packs pinned the same in
+// packs.json and install-comfyui.sh (opt-in), both patches, and the licences the About page and CREDITS.md read.
+const ROOT = process.cwd();
+const dir = path.join(ROOT, "workflows/comfyui");
+const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8")) as Manifest;
+const packs = JSON.parse(fs.readFileSync(path.join(dir, "packs.json"), "utf8")) as Record<string, { repo: string; commit: string }>;
+const install = fs.readFileSync(path.join(ROOT, "scripts/comfy/install-comfyui.sh"), "utf8");
+const credits = fs.readFileSync(path.join(ROOT, "CREDITS.md"), "utf8");
+const pins = JSON.parse(fs.readFileSync(path.join(dir, "model-pins.json"), "utf8")) as Record<string, { revision: string }>;
+const entry = (id: string) => manifest.workflows.find((w) => w.id === id)!;
+const graph = (id: string) => JSON.parse(fs.readFileSync(path.join(dir, `${id}.json`), "utf8")) as ComfyWorkflow;
+const IDS = Object.values(OPENJUTSU_WORKFLOWS);
+
+const PINS: Record<string, [string, string]> = {
+ "ComfyUI-MiniMaxH3-Context-Loop": ["OJ_CONTEXT_LOOP_REF", "43afeffcc570beb5f7382593e79e4b211c7e02f6"],
+ "ComfyUI-Fantastic-MiniMaxH3-PromptBuilder": ["OJ_PROMPT_BUILDER_REF", "22e719fe89336c628383363182a4da3cb58d4f9b"],
+ "comfyui-h3-oneclick-swap": ["OJ_ONECLICK_SWAP_REF", "e44a56e92920000e675d14be484aea0d7498d63e"],
+ "comfyui-image-detail-contrast": ["OJ_DETAIL_CONTRAST_REF", "485a5e246424ce012b998862b45f06d21e8d63b2"],
+ Orion4D_FXMax: ["OJ_ORION_FXMAX_REF", "7048e8423ad7d1a6a52119d0d4870c2b7fc2885f"],
+ SolarRenderer: ["OJ_SOLAR_REF", "0ca4f5e45b062cc9e9aee506de46aabdc22e4c3d"],
+};
+
+describe("the Openjutsu graphs in the library", () => {
+ it("are all in the manifest, not validated yet, with every weight pinned to a revision and sized", () => {
+ for (const id of IDS) {
+ const w = entry(id);
+ expect(w, id).toBeDefined();
+ expect(w.validated, id).toBe(false);
+ for (const m of w.models) {
+ // At a revision in its address, or pinned to one in model-pins.json.
+ const pinned = /^https:\/\/huggingface\.co\/[^/]+\/[^/]+\/resolve\/[0-9a-f]{40}\//.test(m.url ?? "") || /^[0-9a-f]{40}$/.test(pins[m.url ?? ""]?.revision ?? "");
+ expect(pinned, `${id} ${m.file}`).toBe(true);
+ expect(m.sizeGb, `${id} ${m.file}`).toBeGreaterThan(0);
+ }
+ }
+ // Fuobe's remaps: the NVFP4 H3 text encoder, BFL's Klein file, the rank-64 Solar pair, largest_face.
+ const files = (id: string) => entry(id).models.map((m) => m.file);
+ expect(files(OPENJUTSU_WORKFLOWS.group)).toContain("qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors");
+ expect(files(OPENJUTSU_WORKFLOWS.group)).toContain("minimax_h3_DMAD_4step_full_lora_avg_rank_39_bf16.safetensors");
+ expect(files(OPENJUTSU_WORKFLOWS.prepare)).toContain("flux3-image-klein-int8-convrot.safetensors");
+ expect(files(OPENJUTSU_WORKFLOWS.solar)).toEqual(expect.arrayContaining(["solarrenderer_4step_lora_rank64.safetensors", "solarrenderer_control_lora_rank64.safetensors"]));
+ for (const id of IDS) expect(JSON.stringify(graph(id)), id).not.toMatch(/int4_convrot|flux3_image_klein_sd|"select":"largest"/);
+ });
+
+ it("every media loader is bound", () => {
+ for (const id of IDS) {
+ const w = entry(id);
+ const loaders = Object.entries(graph(id)).filter(([, n]) => n.class_type === "LoadImage" || n.class_type === "VHS_LoadVideo").map(([k]) => k);
+ const bound = new Set(Object.values(w.bindings).flatMap((b) => (b ?? []).map((x) => x.node)));
+ for (const k of loaders) expect(bound.has(k), `${id} ${k}`).toBe(true);
+ }
+ });
+
+ it("the models Genjutsu runs point at them, one by one and the H3 renderer as variants", () => {
+ expect(getModel("oss-h3-group-swap")!.routes[0].endpoint).toBe(OPENJUTSU_WORKFLOWS.group);
+ expect(getModel("oss-from-picture")!.routes[0].endpoint).toBe(OPENJUTSU_WORKFLOWS.solar);
+ const has = () => true;
+ const r = (endpoint: string, extra: Record<string, unknown>) => resolveWorkflowId(endpoint, { op: "x", clips: 0, images: 0, audio2: false, extra, has });
+ expect(r(OPENJUTSU_WORKFLOWS.group, { openjutsu: { onePerPerson: true } })).toBe(OPENJUTSU_WORKFLOWS.groupOneByOne);
+ expect(r(OPENJUTSU_WORKFLOWS.group, { openjutsu: {} })).toBe(OPENJUTSU_WORKFLOWS.group);
+ expect(r(OPENJUTSU_WORKFLOWS.solar, { openjutsu: { renderer: "h3" } })).toBe(OPENJUTSU_WORKFLOWS.h3);
+ });
+
+ it("name their packs, pinned the same in packs.json and install-comfyui.sh (opt-in), with both patches", () => {
+ for (const [name, [variable, sha]] of Object.entries(PINS)) {
+ expect(packs[name]?.commit, name).toBe(sha);
+ expect(install, name).toContain(`${variable}="\${${variable}:-${sha}}"`);
+ }
+ expect(install).toMatch(/OPENJUTSU_MODES:-0\}" = "1"/);
+ expect(install).toContain("git -c core.longpaths=true clone");
+ for (const p of ["solarrenderer-long-clips.patch", "h3-oneclick-swap-wording.patch"]) {
+ expect(fs.existsSync(path.join(ROOT, "scripts/comfy/patches", p)), p).toBe(true);
+ expect(install, p).toContain(`patches/${p}`);
+ }
+ const wording = fs.readFileSync(path.join(ROOT, "scripts/comfy/patches/h3-oneclick-swap-wording.patch"), "utf8");
+ expect(wording).toMatch(/^\+.*at the original speed in one continuous take/m);
+ expect(wording).not.toMatch(/^\+.*(without adding|do not enter|no part of the original|not replaced)/m);
+ // The websocket reconnect fix only serves upstream's proxy: not installed.
+ expect(install).not.toMatch(/websocket-reconnect/);
+ // Patches keep their bytes (upstream files use CRLF).
+ expect(fs.readFileSync(path.join(ROOT, ".gitattributes"), "utf8")).toContain("scripts/comfy/patches/*.patch -text");
+ });
+
+ it("their packs and the graphs' source are credited", () => {
+ for (const id of IDS) for (const n of entry(id).customNodes) expect(nodePack(n.name), `${id} ${n.name}`).toBeDefined();
+ expect(ATTRIBUTIONS.some((a) => a.url === "https://github.com/D3voz/openjutsu" && a.licence === "MIT")).toBe(true);
+ expect(credits).toContain("D3voz");
+ expect(credits).toContain("SolarRenderer");
+ });
+});
diff --git a/tests/e2e/_routes.mjs b/tests/e2e/_routes.mjs
index f614989a..4be8aadd 100644
--- a/tests/e2e/_routes.mjs
+++ b/tests/e2e/_routes.mjs
@@ -74,5 +74,6 @@ export function dynamicSamples(root, ids = {}) {
* /assist/skills?run=…); an unknown one is visited too (the form says so in the dialog).
*/
export function querySamples(ids = {}) {
- return [ids.recipeSkill && `/assist/skills?run=${ids.recipeSkill}`, "/assist/skills?run=does-not-exist"].filter(Boolean);
+ // Genjutsu's From picture and Finish tabs (a visitor lands on Motion transfer until they open).
+ return [ids.recipeSkill && `/assist/skills?run=${ids.recipeSkill}`, "/assist/skills?run=does-not-exist", "/genjutsu?mode=picture", "/genjutsu?mode=finish"].filter(Boolean);
}
diff --git a/tests/e2e/genjutsu-openjutsu.mjs b/tests/e2e/genjutsu-openjutsu.mjs
new file mode 100644
index 00000000..b62165cb
--- /dev/null
+++ b/tests/e2e/genjutsu-openjutsu.mjs
@@ -0,0 +1,126 @@
+// Genjutsu's Openjutsu modes, browser check. As the owner (a studio without a password): the From picture and Finish
+// tabs show and every tab is 44 px tall; Character swap with four characters shows Who becomes who, and a tap on the
+// part's first frame writes where that person stands; From picture's two-step header with step 2 locked until a frame
+// is used; Finish's tool switch; nothing scrolls sideways at 390 px. With --guest (a studio with a password and public
+// sign-up, nothing open yet): only the five existing tabs, ?mode=picture and ?mode=finish land on Motion transfer, and
+// nothing scrolls sideways at 390 or 1440 px.
+// Usage: node tests/e2e/genjutsu-openjutsu.mjs [appUrl] [--guest] [--shots <dir>] (app running in demo mode). Exits 1 on a failed check.
+import fs from "node:fs";
+import path from "node:path";
+import { launch, root } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");
+const guest = argv.includes("--guest");
+const shots = argv.includes("--shots") ? argv[argv.indexOf("--shots") + 1] : undefined;
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+const EXISTING = ["Motion transfer", "Character swap", "Object swap", "Restyle", "Insert"];
+
+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) => `gj1.${Buffer.from(JSON.stringify(o)).toString("base64url")}`;
+
+const browser = await launch();
+try {
+ for (const [width, height] of [
+ [390, 844],
+ [1440, 900],
+ ]) {
+ const context = await browser.newContext({ viewport: { width, height }, ...(width < 500 ? { isMobile: true, hasTouch: true } : {}) });
+ await context.addInitScript(() => {
+ try {
+ localStorage.setItem("fuobe.engine", "open");
+ } catch {}
+ });
+ const page = await context.newPage();
+ const shot = async (name) => shots && (await page.screenshot({ path: path.join(shots, `${name}-${width}.png`), fullPage: true }));
+ const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ const tabs = async () => (await page.getByRole("tablist", { name: "Genjutsu modes" }).getByRole("tab").allInnerTexts()).map((t) => t.replace(/\s*Only you$/, "").trim());
+ 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(1500);
+ };
+ const selected = () => page.evaluate(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.replace(/Only you$/, ""));
+
+ if (guest) {
+ await open("/genjutsu");
+ check(`${width}: a guest sees the five existing tabs only`, JSON.stringify(await tabs()) === JSON.stringify(EXISTING), JSON.stringify(await tabs()));
+ check(`${width}: no "Only you" for a guest`, !(await page.evaluate(() => document.body.innerText.includes("Only you"))));
+ check(`${width}: /genjutsu fits the screen`, (await sideways()) <= 0);
+ await shot("guest-genjutsu");
+ for (const m of ["picture", "finish"]) {
+ await open(`/genjutsu?mode=${m}`);
+ check(`${width}: ?mode=${m} lands on Motion transfer for a guest`, (await selected()) === "Motion transfer", String(await selected()));
+ }
+ await page.goto(`${app}/character-swap`, { waitUntil: "load", timeout: 120_000 });
+ await page.waitForTimeout(1500);
+ check(`${width}: /character-swap fits the screen`, (await sideways()) <= 0);
+ await shot("guest-character-swap");
+ } else {
+ const clip = await upload("scripts/eval/fixtures/walk-6s.mp4", "video/mp4", "walk.mp4");
+ const pics = [];
+ for (let i = 0; i < 4; i++) pics.push(await upload("scripts/eval/fixtures/character/drawn-face-2.png", "image/png", `c${i}.png`));
+ await open("/genjutsu");
+ const t = await tabs();
+ check(`${width}: the owner sees From picture and Finish`, t.includes("From picture") && t.includes("Finish"), JSON.stringify(t));
+ const heights = await page.evaluate(() => [...document.querySelectorAll('[role="tablist"][aria-label="Genjutsu modes"] [role="tab"]')].map((b) => Math.round(b.getBoundingClientRect().height)));
+ check(`${width}: every mode tab is 44 px tall`, heights.every((h) => h >= 44), JSON.stringify(heights));
+
+ // Character swap with four characters on your GPU: Who becomes who, and a tap writes the words.
+ await open(`/genjutsu?video=${encodeURIComponent(clip)}&setup=${code({ m: "character", e: "open", r: pics })}`);
+ const rows = page.getByRole("textbox", { name: /Character \d replaces/ });
+ await rows.first().waitFor({ timeout: 120_000 }).catch(() => {});
+ check(`${width}: four characters, one "Replaces…" row each`, (await rows.count()) === 4, String(await rows.count()));
+ check(`${width}: four characters fit the screen`, (await sideways()) <= 0);
+ await shot("owner-group-swap");
+ const tap = page.getByRole("button", { name: "Tap them" }).first();
+ await page.waitForFunction(() => [...document.querySelectorAll("button")].some((b) => b.textContent?.includes("Tap them") && !b.disabled), null, { timeout: 60_000 }).catch(() => {});
+ if (await tap.isEnabled()) {
+ await tap.click();
+ const stage = page.getByRole("button", { name: /Tap the person character 1 replaces/ });
+ await stage.scrollIntoViewIfNeeded();
+ const box = await stage.boundingBox();
+ if (box) await page.mouse.click(box.x + box.width * 0.15, box.y + box.height * 0.5);
+ check(`${width}: a tap on the left writes "the person on the left"`, (await rows.first().inputValue()) === "the person on the left", await rows.first().inputValue());
+ } else check(`${width}: "Tap them" opens the part's first frame`, false, "the frame didn't load");
+
+ // From picture: two steps, the first one first.
+ await open(`/genjutsu?mode=picture&video=${encodeURIComponent(clip)}&image=${encodeURIComponent(pics[0])}`);
+ const steps = page.getByRole("list", { name: "Steps" });
+ await steps.waitFor({ timeout: 60_000 }).catch(() => {});
+ check(`${width}: From picture's step 1 is current`, (await steps.locator('[aria-current="step"]').innerText().catch(() => "")) === "1 First frame");
+ check(`${width}: Generate makes the first frame first`, await page.getByRole("button", { name: "Make the first frame" }).isVisible().catch(() => false));
+ check(`${width}: the 17 looks and your own words`, (await page.getByRole("radiogroup", { name: "Light" }).getByRole("radio").count().catch(() => 0)) === 19);
+ check(`${width}: From picture fits the screen`, (await sideways()) <= 0);
+ await shot("owner-from-picture");
+
+ // Finish: the two tools.
+ await open(`/genjutsu?mode=finish&tool=faces&video=${encodeURIComponent(clip)}`);
+ const tool = page.getByRole("radiogroup", { name: "Tool" });
+ await tool.waitFor({ timeout: 60_000 }).catch(() => {});
+ check(`${width}: Finish: Fix faces · Fix colours`, (await tool.getByRole("radio").allInnerTexts().catch(() => [])).join("|") === "Fix faces|Fix colours");
+ check(`${width}: Finish fits the screen`, (await sideways()) <= 0);
+ await shot("owner-finish");
+ }
+ await context.close();
+ }
+} finally {
+ await browser.close();
+}
+if (failures.length) {
+ console.log(`\n${failures.length} failed`);
+ process.exit(1);
+}
+console.log("\nall good");
diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.ts
index 24f43c1c..40c8e238 100644
--- a/tests/eval-harness.test.ts
+++ b/tests/eval-harness.test.ts
@@ -349,10 +349,26 @@ describe("the runner on the demo provider", () => {
type Plan = { jobs: { case: string; variant: string; model: string; skip?: string }[] };
const dry = async (args: string[]) => JSON.parse((await cli(["run", ...args, "--dry-run", "--json"])).stdout) as Plan;
setSetting("falKey", "fal-test-key");
+ // Group swap, Scene edit, From picture and Finish run on your GPU only: on the cloud their jobs say so and skip.
+ const cloud = (p: Plan) => {
+ const gpu = p.jobs.filter((j) => j.skip === "runs on open only");
+ expect(gpu.map((j) => j.case)).toEqual([
+ "genjutsu/group",
+ "genjutsu/group-one-by-one",
+ "genjutsu/scene-change",
+ "genjutsu/scene-remove",
+ "genjutsu/scene-background",
+ "genjutsu/picture",
+ "genjutsu/picture-golden-halo",
+ "genjutsu/fix-faces",
+ "genjutsu/fix-colours",
+ ]);
+ return p.jobs.filter((j) => !gpu.includes(j));
+ };
try {
// With fal connected, each mode runs its own partner on fal.
const g = await dry(["--suite", "genjutsu", "--engine", "cloud", "--variants", "partner", "--allow-fixtures"]);
- expect(g.jobs.map((j) => [j.case, j.model, j.skip ?? null])).toEqual([
+ expect(cloud(g).map((j) => [j.case, j.model, j.skip ?? null])).toEqual([
["genjutsu/move", "kling-motion-control", null],
// A case with no partner of its own runs its own models (the -lite tiers, the Original without its first frame).
["genjutsu/move-lite", "fuobe-genjutsu-motion-lite", null],
@@ -366,7 +382,7 @@ describe("the runner on the demo provider", () => {
]);
// The Originals on the cloud: their hosted open halves on fal.
const o = await dry(["--suite", "genjutsu", "--engine", "cloud", "--variants", "original", "--allow-fixtures"]);
- expect(o.jobs.map((j) => [j.case, j.model, j.skip ?? null])).toEqual([
+ expect(cloud(o).map((j) => [j.case, j.model, j.skip ?? null])).toEqual([
["genjutsu/move", "fuobe-genjutsu-motion", null],
["genjutsu/move-lite", "fuobe-genjutsu-motion-lite", null],
["genjutsu/character", "fuobe-character-swap", null],
diff --git a/tests/genjutsu-api.test.ts b/tests/genjutsu-api.test.ts
index 1b3aa10b..1d39870e 100644
--- a/tests/genjutsu-api.test.ts
+++ b/tests/genjutsu-api.test.ts
@@ -182,7 +182,8 @@ describe("Genjutsu: estimates", () => {
};
expect(await say(body({ references: [], source: { url: clip, ...src } }))).toBe("Add a picture of your character");
expect(await say(body({ source: { url: clip, ...src }, range: { start: 0, end: 3 } }))).toMatch(/between 4 and 30 seconds/);
- expect(await say(body({ mode: "swap", target: "paint", engine: "open", source: { url: clip, ...src } }))).toMatch(/name what to swap/);
+ // Painting on your GPU is Scene edit's (the owner sees it before it opens to everyone).
+ expect(await say(body({ mode: "swap", target: "paint", engine: "open", source: { url: clip, ...src } }))).toBe("Paint over what changes");
expect(await say(body({ mode: "swap", modelId: "kling-o3", source: { url: clip, ...src, duration: 10 }, range: { start: 0, end: 10 } }))).toMatch(/Say what to swap/);
expect(await say(body({ mode: "restyle", references: [], source: { url: clip, ...src } }))).toBe("Pick a look");
// Character swap: a part of 5–15 s, a click only on the open engine.
diff --git a/tests/genjutsu-live.test.ts b/tests/genjutsu-live.test.ts
new file mode 100644
index 00000000..8dca7ded
--- /dev/null
+++ b/tests/genjutsu-live.test.ts
@@ -0,0 +1,56 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { GENJUTSU_FEATURE_KEYS, GENJUTSU_FEATURES } from "@/lib/catalog/genjutsu";
+import { genjutsuLive } from "@/server/genjutsu-live";
+
+// Genjutsu's Openjutsu features open to everyone one by one: each needs its workflows accepted by ComfyUI AND a real render
+// recorded as passed (workflows/comfyui/gpu-tested.json). The manifest flag alone never opens one.
+const ROOT = process.cwd();
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-live-"));
+const write = (name: string, v: unknown) => {
+ const f = path.join(dir, name);
+ fs.writeFileSync(f, typeof v === "string" ? v : JSON.stringify(v));
+ return f;
+};
+const all = [...new Set(Object.values(GENJUTSU_FEATURES).flatMap((f) => f.workflows))];
+
+describe("Genjutsu's live gate", () => {
+ it("needs both: workflows validated and a passed render", () => {
+ const validated = write("m-ok.json", { workflows: all.map((id) => ({ id, validated: true })) });
+ const notValidated = write("m-no.json", { workflows: all.map((id) => ({ id, validated: false })) });
+ const passed = write("r-ok.json", { features: Object.fromEntries(GENJUTSU_FEATURE_KEYS.map((k) => [k, { passed: true }])) });
+ const none = write("r-none.json", { features: {} });
+ expect(Object.values(genjutsuLive(validated, none)).some(Boolean)).toBe(false);
+ expect(Object.values(genjutsuLive(notValidated, passed)).some(Boolean)).toBe(false);
+ expect(Object.values(genjutsuLive(validated, passed)).every(Boolean)).toBe(true);
+ // One feature at a time.
+ const one = write("r-one.json", { features: { "finish-colours": { passed: true, date: "2026-11-03" }, "finish-faces": { passed: false } } });
+ const live = genjutsuLive(validated, one);
+ expect(live["finish-colours"]).toBe(true);
+ expect(live["finish-faces"]).toBe(false);
+ expect(live.picture).toBe(false);
+ // From picture needs all three of its workflows.
+ const partly = write("m-part.json", { workflows: all.map((id) => ({ id, validated: id !== "video-scene-describe" })) });
+ expect(genjutsuLive(partly, passed).picture).toBe(false);
+ expect(genjutsuLive(partly, passed)["finish-colours"]).toBe(true);
+ });
+
+ it("a missing file, a missing entry or bad JSON opens nothing", () => {
+ const validated = write("m2.json", { workflows: all.map((id) => ({ id, validated: true })) });
+ expect(Object.values(genjutsuLive(validated, path.join(dir, "missing.json"))).some(Boolean)).toBe(false);
+ expect(Object.values(genjutsuLive(path.join(dir, "missing.json"), write("r2.json", { features: { picture: { passed: true } } }))).some(Boolean)).toBe(false);
+ expect(Object.values(genjutsuLive(validated, write("bad.json", "{not json"))).some(Boolean)).toBe(false);
+ });
+
+ it("the committed record opens nothing yet, and the page passes the gate to the studio", () => {
+ expect(JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/gpu-tested.json"), "utf8"))).toEqual({ features: {} });
+ expect(Object.values(genjutsuLive()).some(Boolean)).toBe(false);
+ const page = fs.readFileSync(path.join(ROOT, "src/app/(studio)/genjutsu/page.tsx"), "utf8");
+ expect(page).toMatch(/<GenjutsuStudio examples=\{studioExamples\("genjutsu"\)\} 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-openjutsu-access.test.ts b/tests/genjutsu-openjutsu-access.test.ts
new file mode 100644
index 00000000..e995f1f1
--- /dev/null
+++ b/tests/genjutsu-openjutsu-access.test.ts
@@ -0,0 +1,174 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.setConfig({ testTimeout: 60_000 });
+
+/**
+ * Genjutsu's Openjutsu modes under the owner's public sign-up rules: until a feature has passed its GPU test, a guest's or
+ * an account's price check for it is refused in words (the tab isn't shown to them either); runs and From picture's
+ * describer stay the owner's on this server, as every Genjutsu run.
+ */
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-oj-access-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_PUBLIC_SIGNUP;
+delete process.env.FUOBE_ALLOWED_ORIGINS;
+
+const auth = await import("@/server/auth");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const estimateRoute = await import("@/app/api/genjutsu/estimate/route");
+const sceneRoute = await import("@/app/api/genjutsu/scene/route");
+const { estimateGenjutsu, NOT_HERE } = await import("@/server/genjutsu");
+const generationsRoute = await import("@/app/api/generations/route");
+const { directRunFeatures } = await import("@/lib/catalog/genjutsu");
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+const req = (url: string, init: { method?: string; cookie?: string } = {}) => {
+ const method = init.method ?? "GET";
+ const headers: Record<string, string> = {};
+ if (init.cookie) headers.cookie = `${auth.SESSION_COOKIE}=${init.cookie}`;
+ return new NextRequest(`http://localhost:3000${url}`, { method, headers, ...(method !== "GET" && { body: "{}" }) });
+};
+const call = (url: string, body: unknown, cookie?: string) =>
+ new Request(`http://localhost:3000${url}`, { method: "POST", headers: { "Content-Type": "application/json", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) }, body: JSON.stringify(body) });
+
+let clip = "";
+let n = 0;
+beforeAll(() => {
+ auth.setPassword("install password");
+ setSetting("demoMode", "on");
+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "duo.mp4" }).url;
+});
+afterEach(() => {
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+});
+
+const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };
+const bodies = () => [
+ { engine: "open", mode: "finish", finish: { tool: "colours" }, source: { url: clip, ...src }, range: { start: 0, end: 12 } },
+ { engine: "open", mode: "picture", picture: { stage: "frame" }, references: [clip], source: { url: clip, ...src }, range: { start: 0, end: 6 } },
+ { engine: "open", mode: "swap", target: "type", object: { action: "remove", target: "the handbag" }, source: { url: clip, ...src }, range: { start: 0, end: 6 } },
+ { engine: "open", mode: "character", modelId: "oss-h3-group-swap", references: [clip, clip], source: { url: clip, ...src }, range: { start: 0, end: 6 } },
+];
+
+describe("Genjutsu's Openjutsu features before they open", () => {
+ it("a guest's and an account's price check is refused in words; the owner's goes through", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const cookie = auth.createSession(auth.createAccount(`oj${++n}@example.com`, "long enough").id).value;
+ for (const b of bodies()) {
+ expect(passed(proxy(req("/api/genjutsu/estimate", { method: "POST" }))), b.mode).toBe(true);
+ for (const who of [undefined, cookie]) {
+ const r = await estimateRoute.POST(call("/api/genjutsu/estimate", b, who));
+ expect(r.status, `${b.mode} ${who ? "account" : "guest"}`).toBe(422);
+ expect((await r.json()).error).toBe(NOT_HERE);
+ }
+ await expect(estimateGenjutsu(b as never, { owner: false })).rejects.toThrow(NOT_HERE);
+ // The owner sees and prices every feature.
+ const owner = await estimateGenjutsu(b as never, { owner: true }).catch((e: Error) => e);
+ expect(owner instanceof Error ? owner.message : "", b.mode).not.toBe(NOT_HERE);
+ }
+ });
+
+ it("a visitor's existing Genjutsu modes are as before", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const r = await estimateRoute.POST(call("/api/genjutsu/estimate", { engine: "open", mode: "motion", references: [clip], source: { url: clip, ...src }, range: { start: 0, end: 6 } }));
+ expect((await r.json()).error ?? "").not.toBe(NOT_HERE);
+ });
+
+ it("the new makers' models sent straight to /api/generations run for the owner only", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const cookie = auth.createSession(auth.createAccount(`oj${++n}@example.com`, "long enough").id).value;
+ const owner = auth.createSession().value;
+ const runs = [
+ { feature: "genjutsu", modelId: "oss-h3-group-swap", op: "group-swap", inputs: { video: clip, images: [clip] } },
+ { feature: "genjutsu", modelId: "oss-h3-scene-edit", op: "scene-edit", inputs: { video: clip }, params: { extra: { openjutsu: { action: "remove" } } } },
+ { feature: "genjutsu", modelId: "oss-from-picture-frame", op: "picture-frame", inputs: { video: clip, images: [clip] } },
+ { feature: "genjutsu", modelId: "oss-scene-describe", op: "describe-video", inputs: { video: clip } },
+ { feature: "genjutsu", modelId: "oss-from-picture", op: "picture-video", inputs: { video: clip, images: [clip] } },
+ { feature: "genjutsu", modelId: "oss-h3-fix-faces", op: "face-fix-video", inputs: { video: clip, images: [clip] } },
+ { feature: "genjutsu", modelId: "oss-fix-colours", op: "tone-video", inputs: { video: clip } },
+ ];
+ const send = (body: unknown, who?: string, preview = false) =>
+ generationsRoute.POST(
+ new Request(`http://localhost:3000/api/generations${preview ? "?preview=1" : ""}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", host: "localhost:3000", ...(who && { cookie: `${auth.SESSION_COOKIE}=${who}` }) },
+ body: JSON.stringify(body),
+ }),
+ );
+ for (const b of runs) {
+ for (const [who, preview] of [[cookie, false], [cookie, true], [undefined, true]] as const) {
+ const r = await send(b, who, preview);
+ expect(r.status, `${b.modelId} ${who ? "account" : "guest"}${preview ? " price check" : ""}`).toBe(403);
+ const j = await r.json();
+ expect(j.code).toBe("own-gpu-tool");
+ expect(j.error).toBe(access.OWN_GPU_TOOL_MESSAGE);
+ }
+ // The owner's request isn't refused by the gate (it may still fail later: no ComfyUI here).
+ const r = await send(b, owner, true);
+ expect(((await r.json()) as { code?: string }).code ?? "", b.modelId).not.toBe("own-gpu-tool");
+ }
+ });
+
+ it("a direct run needs every feature it uses", () => {
+ expect(directRunFeatures("oss-h3-group-swap", { onePerPerson: true })).toEqual(["group-swap", "group-swap-one-by-one"]);
+ expect(directRunFeatures("oss-h3-scene-edit", { action: "background" })).toEqual(["object-background"]);
+ expect(directRunFeatures("oss-h3-scene-edit", {})).toEqual(["object-change"]);
+ expect(directRunFeatures("oss-from-picture-frame", { light: "Soft window light", ownPerson: true })).toEqual(["picture", "picture-light", "picture-own-person"]);
+ expect(directRunFeatures("oss-from-picture", { renderer: "h3" })).toEqual(["picture", "picture-h3-renderer"]);
+ expect(directRunFeatures("minimax-h3-i2v")).toBeNull();
+ });
+
+ it("an approved first frame is found however many frames came after it", async () => {
+ const { db } = await import("@/server/db");
+ const { describeScene } = await import("@/server/genjutsu");
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'genjutsu-step', 'oss-from-picture-frame', 'open', 'comfyui', 'picture-frame', 'image', 'succeeded', '{}', ?, ?, ?)",
+ );
+ const t = Date.now() - 86_400_000;
+ db().transaction(() => {
+ add.run("old-frame", JSON.stringify([{ url: "/api/files/old-frame.png", kind: "image" }]), t, t);
+ for (let i = 0; i < 520; i++) add.run(`frame-${i}`, JSON.stringify([{ url: `/api/files/frame-${i}.png`, kind: "image" }]), t + 1000 + i, t + 1000 + i);
+ })();
+ const say = (frame: string) => {
+ try {
+ describeScene({ engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, frame } as never);
+ return "";
+ } catch (e) {
+ return (e as Error).message;
+ }
+ };
+ expect(say("/api/files/old-frame.png")).not.toBe("Make and pick the first frame first");
+ expect(say("/api/files/never-made.png")).toBe("Make and pick the first frame first");
+ });
+
+ it("From picture's describer is the owner's, like every Genjutsu run", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const cookie = auth.createSession(auth.createAccount(`oj${++n}@example.com`, "long enough").id).value;
+ for (const who of [undefined, cookie]) {
+ for (const p of ["/api/genjutsu", "/api/genjutsu/scene"]) {
+ const r = proxy(req(p, { method: "POST", cookie: who }));
+ expect(r.status, `${p} ${who ? "account" : "guest"}`).toBe(403);
+ expect((await r.json()).code).toBe("own-gpu-tool");
+ }
+ }
+ expect(access.isPriceCheck("POST", "/api/genjutsu/scene", "")).toBe(false);
+ // Behind the proxy the route refuses a visitor too.
+ const r = await sceneRoute.POST(call("/api/genjutsu/scene", { engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, ownPerson: true }));
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toBe(NOT_HERE);
+ });
+});
diff --git a/tests/genjutsu-openjutsu-comfy.test.ts b/tests/genjutsu-openjutsu-comfy.test.ts
new file mode 100644
index 00000000..7e6d6772
--- /dev/null
+++ b/tests/genjutsu-openjutsu-comfy.test.ts
@@ -0,0 +1,134 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { getMaker, planGenjutsu } from "@/lib/catalog/genjutsu";
+import { danglingLinks, OPENJUTSU_WORKFLOWS as W } from "@/lib/openjutsu-graphs";
+import type { GenInput, Operation } from "@/lib/catalog/types";
+import type { MediaInfo } from "@/lib/media-probe";
+
+// The comfyui provider driving Genjutsu's Openjutsu graphs: the media bound, the settings written by title, the pictures
+// a request leaves out taken out with their branches, and a Context Loop job's run folder deleted once it ends.
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-oj-comfy-"));
+process.env.FUOBE_DATA_DIR = tmp;
+process.env.COMFYUI_URL = "http://comfy.test:8188";
+const { prepareWorkflow, deleteRunFolder } = await import("@/server/providers/comfyui");
+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
+
+const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 1308, height: 736, fps: 24, frames: 144 };
+const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>
+ prepareWorkflow(id, { video: "part.mp4", ...input } as GenInput, { generationId: "gen42", op, upload: async (_d, _t, name) => `up_${name}`, media: (n) => (n === "part.mp4" ? clip : undefined) });
+type Wf = Record<string, { class_type: string; inputs: Record<string, unknown>; _meta?: { title?: string } }>;
+const titled = (wf: Wf, t: string) => Object.values(wf).find((n) => n._meta?.title === t);
+
+describe("Genjutsu's Openjutsu graphs through the provider", () => {
+ it("Group swap: two characters bound, the other pictures gone, the roles, quality and the job's own run name", async () => {
+ const { manifest, workflow } = await prepare(
+ W.group,
+ { images: ["a.png", "b.png"], seed: 11, extra: { openjutsu: { pictures: 2, roles: ["the person on the left", "the person on the right"], quality: "720p", edge: "tight" } } },
+ "group-swap",
+ );
+ const wf = workflow as Wf;
+ expect(manifest.id).toBe(W.group);
+ expect(titled(wf, "Picture 1")!.inputs.image).toBe("a.png");
+ expect(titled(wf, "Picture 2")!.inputs.image).toBe("b.png");
+ expect(titled(wf, "Picture 3")).toBeUndefined();
+ expect(titled(wf, "Source video (people get replaced)")!.inputs.video).toBe("part.mp4");
+ expect(titled(wf, "Swap Plan (roles, seed, size)")!.inputs).toMatchObject({ roles: "the person on the left\nthe person on the right", resolution: "736p", seed: 11 });
+ expect(Object.values(wf).find((n) => n.class_type === "MiniMaxH3ChainPlanModern")!.inputs.run_name).toBe("fuobe_gen42");
+ expect(danglingLinks(workflow)).toEqual([]);
+ });
+
+ it("one by one runs its own graph; a character missing is refused in words", async () => {
+ const { manifest } = await prepare(W.group, { images: ["a.png", "b.png"], extra: { openjutsu: { pictures: 2, onePerPerson: true } } }, "group-swap");
+ expect(manifest.id).toBe(W.groupOneByOne);
+ await expect(prepare(W.group, { images: ["a.png"], extra: { openjutsu: { pictures: 2 } } }, "group-swap")).rejects.toThrow();
+ });
+
+ it("Scene edit: remove takes no picture; background flips the mask", async () => {
+ const r = (await prepare(W.scene, { extra: { openjutsu: { action: "remove", target: "the handbag" } } }, "scene-edit")).workflow as Wf;
+ expect(titled(r, "Picture 1")).toBeUndefined();
+ expect(titled(r, "Object Swap Plan (what to change)")!.inputs).toMatchObject({ mode: "remove", target: "the handbag" });
+ const b = (await prepare(W.scene, { images: ["place.png"], extra: { openjutsu: { action: "background", target: "the people", becomes: "an Amalfi terrace", picture: true } } }, "scene-edit")).workflow as Wf;
+ expect(titled(b, "Picture 1")!.inputs.image).toBe("place.png");
+ expect(titled(b, "Grow mask")!.inputs.flip_input).toBe(true);
+ });
+
+ it("From picture: the first frame at the part's start, the clip's own person without a picture; the video from the approved frame", async () => {
+ const f = (await prepare(W.prepare, { images: ["me.png"], startTime: 2, extra: { openjutsu: { light: "" } } }, "picture-frame")).workflow as Wf;
+ expect(f["1"].inputs).toMatchObject({ video: "part.mp4", skip_first_frames: 48 });
+ expect(f["4"].inputs.image).toBe("me.png");
+ const own = (await prepare(W.prepare, { startTime: 0, extra: { openjutsu: { light: "Light the new photo with a warm golden glow.", ownPerson: true } } }, "picture-frame")).workflow as Wf;
+ expect(own["4"]).toBeUndefined();
+ const v = await prepare(W.solar, { images: ["frame.png"], extra: { openjutsu: { seconds: 6, quality: "480p", scene: "She turns." } } }, "picture-video");
+ expect((v.workflow as Wf)["20"].inputs.image).toBe("frame.png");
+ expect((v.workflow as Wf)["56"].inputs).toMatchObject({ length: 141 });
+ expect((await prepare(W.solar, { images: ["frame.png"], extra: { openjutsu: { seconds: 6, renderer: "h3" } } }, "picture-video")).manifest.id).toBe(W.h3);
+ const d = (await prepare(W.describe, { images: ["frame.png"], startTime: 1, extra: { openjutsu: { seconds: 6 } } }, "describe-video")).workflow as Wf;
+ expect(d["1"].inputs).toMatchObject({ skip_first_frames: 24, frame_load_cap: 141 });
+ });
+
+ it("Finish: faces with the photo, colours with its finish", async () => {
+ const faces = (await prepare(W.faces, { images: ["face.png"], extra: { openjutsu: { faceStyle: "photo", chunkSeconds: 10 } } }, "face-fix-video")).workflow as Wf;
+ expect(titled(faces, "Picture 1")!.inputs.image).toBe("face.png");
+ expect(titled(faces, "Face Fix Chunks")!.inputs.chunk_seconds).toBe(10);
+ const colours = (await prepare(W.colours, { extra: { openjutsu: { finish: "off", soften: 0 } } }, "tone-video")).workflow as Wf;
+ expect(Object.values(colours).map((n) => n.class_type).sort()).toEqual(["VHS_BatchManager", "VHS_LoadVideo", "VHS_VideoCombine"]);
+ });
+
+ it("Fix colours goes through in passes; Fix faces refuses a clip bigger than the server can hold", async () => {
+ // Fix colours: every pass holds about 1.5 GB of frames (three copies), whatever the clip's length.
+ const p = await prepare(W.colours, { extra: { openjutsu: { finish: "soft" } } }, "tone-video");
+ const wf = p.workflow as Wf;
+ const [managerId, manager] = Object.entries(wf).find(([, n]) => n.class_type === "VHS_BatchManager")!;
+ expect(manager.inputs.frames_per_batch).toBe(Math.floor((1.5 * 2 ** 30) / (12 * 1308 * 736 * 3)));
+ expect(manager.inputs.job).toBe("gen42");
+ for (const n of Object.values(wf)) if (n.class_type === "VHS_LoadVideo" || n.class_type === "VHS_VideoCombine") expect(n.inputs.meta_batch).toEqual([managerId, 0]);
+ expect(p.meta).toMatchObject({ metaBatch: true });
+ // Fix faces holds the whole clip twice: on a 16 GB server, 1080p for 30 s is refused in words.
+ const big: MediaInfo = { ...clip, duration: 30, videoDuration: 30, width: 1920, height: 1080, frames: 720 };
+ await expect(
+ prepareWorkflow(W.faces, { video: "big.mp4", images: ["face.png"], extra: { openjutsu: {} } } as GenInput, {
+ generationId: "gen43",
+ op: "face-fix-video",
+ upload: async (_d, _t, name) => `up_${name}`,
+ media: (n) => (n === "big.mp4" ? big : undefined),
+ serverRam: async () => 16 * 2 ** 30,
+ }),
+ ).rejects.toThrow(/Fix faces holds the whole clip in memory/);
+ });
+
+ it("a planned Group swap is what the graph is given (after its part is fitted)", async () => {
+ const p = planGenjutsu({
+ engine: "open",
+ mode: "character",
+ maker: getMaker("oss-h3-group-swap", "open")!,
+ title: "Genjutsu",
+ source: { url: "/api/files/c.mp4", duration: 10, fps: 30, width: 1920, height: 1080, hasAudio: true },
+ range: { start: 0, end: 6 },
+ quality: "480p",
+ references: ["/api/files/a.png", "/api/files/b.png"],
+ character: { people: [{ role: "the dancer" }, { role: "" }] },
+ });
+ const s = p.steps.find((x) => x.key === "swap")!.request;
+ const { workflow } = await prepare(W.group, { images: ["a.png", "b.png"], extra: s.params!.extra as Record<string, unknown> }, s.op!);
+ expect(titled(workflow as Wf, "Swap Plan (roles, seed, size)")!.inputs).toMatchObject({ roles: "the dancer\nthe person with the second most screen time", resolution: "480p" });
+ });
+
+ it("a Context Loop job's run folder is deleted through the pack's own routes (preview, then delete with its snapshot)", async () => {
+ const calls: { url: string; body: unknown }[] = [];
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;
+ calls.push({ url: String(url), body });
+ if (String(url).endsWith("/delete-preview")) return new Response(JSON.stringify({ ok: true, snapshot: "a".repeat(64) }), { status: 200 });
+ return new Response(JSON.stringify({ ok: true }), { status: 200 });
+ });
+ try {
+ expect(await deleteRunFolder("fuobe_gen42")).toBe(true);
+ } finally {
+ fetchMock.mockRestore();
+ }
+ expect(calls.map((c) => c.url.replace("http://comfy.test:8188", ""))).toEqual(["/minimax_h3_context_loop/run-folder/delete-preview", "/minimax_h3_context_loop/run-folder/delete"]);
+ expect(calls[1].body).toEqual({ run_name: "fuobe_gen42", snapshot: "a".repeat(64), confirmation: "fuobe_gen42" });
+ });
+});
diff --git a/tests/genjutsu-openjutsu.test.ts b/tests/genjutsu-openjutsu.test.ts
new file mode 100644
index 00000000..e6a01163
--- /dev/null
+++ b/tests/genjutsu-openjutsu.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from "vitest";
+import {
+ chooseMaker,
+ decodeSetup,
+ encodeSetup,
+ fitSize,
+ GENJUTSU_FEATURES,
+ GENJUTSU_MODES,
+ genjutsuProblem,
+ getMaker,
+ makersFor,
+ modeOpen,
+ ORIGINALS,
+ planGenjutsu,
+ requestFeatures,
+ type GenjutsuPlanInput,
+ type Maker,
+} from "@/lib/catalog/genjutsu";
+import { roleFromPin } from "@/lib/catalog/character-swap";
+
+// Genjutsu's Openjutsu modes in the catalog: Group swap (2–4 characters), Scene edit (change / remove / new background),
+// From picture (first frame, then the video) and Finish (Fix faces, Fix colours), each behind its own gate.
+const ref = "/api/files/hero.png";
+const none = () => false;
+const open = (id: string) => getMaker(id, "open")!;
+const source = { url: "/api/files/clip.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true };
+const oj = (o: Partial<GenjutsuPlanInput> & { maker: Maker }) =>
+ planGenjutsu({ engine: "open", mode: "character", title: "Genjutsu", source, range: { start: 2, end: 8 }, quality: "720p", references: [ref, "/api/files/two.png"], ...o });
+const step = (p: ReturnType<typeof planGenjutsu>, key: string) => {
+ const s = p.steps.find((x) => x.key === key);
+ if (!s) throw new Error(`no step ${key} in ${p.steps.map((x) => x.key).join(", ")}`);
+ return s;
+};
+
+describe("Genjutsu: the Openjutsu modes", () => {
+ it("two new tabs; each opens with its features (the owner sees all), and visitors see nothing new until then", () => {
+ expect(GENJUTSU_MODES.map((m) => m.id)).toEqual(["motion", "character", "swap", "restyle", "insert", "picture", "finish"]);
+ expect(GENJUTSU_MODES.filter((m) => modeOpen(m.id, none)).map((m) => m.id)).toEqual(["motion", "character", "swap", "restyle", "insert"]);
+ expect(modeOpen("finish", (f) => f === "finish-colours")).toBe(true);
+ expect(modeOpen("picture", (f) => f === "picture-light")).toBe(false);
+ for (const mode of ["character", "swap", "picture", "finish"] as const) {
+ for (const m of makersFor("open", mode, mode === "swap" || mode === "character" ? "type" : undefined, none)) expect(m.features, m.id).toBeUndefined();
+ }
+ expect(Object.keys(GENJUTSU_FEATURES)).toHaveLength(11);
+ });
+
+ it("two characters or more move the swap to Group swap on your GPU (Recast in the cloud); one stays Fuobe's", () => {
+ expect(chooseMaker({ engine: "open", mode: "character", refs: 1 })).toMatchObject({ maker: { id: ORIGINALS.character } });
+ expect(chooseMaker({ engine: "open", mode: "character", refs: 2 })).toMatchObject({ maker: { id: "oss-h3-group-swap" } });
+ expect(chooseMaker({ engine: "open", mode: "character", refs: 4, target: "click" })).toMatchObject({ maker: { id: "oss-h3-group-swap" } });
+ expect(chooseMaker({ engine: "cloud", mode: "character", refs: 3 })).toMatchObject({ maker: { id: "h3-max-recast" } });
+ expect(chooseMaker({ engine: "open", mode: "character", refs: 1, modelId: "oss-h3-group-swap" })).toMatchObject({ maker: { id: "oss-h3-group-swap" } });
+ // Before it opens, a visitor keeps the one-person swap.
+ expect(chooseMaker({ engine: "open", mode: "character", refs: 2, open: none })).toMatchObject({ maker: { id: ORIGINALS.character } });
+ });
+
+ it("Remove it and New background are Scene edit's; Finish picks by tool", () => {
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "type" })).toMatchObject({ maker: { id: ORIGINALS.swapLite } });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "type", action: "remove" })).toMatchObject({ maker: { id: "oss-h3-scene-edit" } });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "type", action: "background" })).toMatchObject({ maker: { id: "oss-h3-scene-edit" } });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "type", action: "remove" })).toEqual({ problem: "Remove it and New background run on your GPU" });
+ expect(chooseMaker({ engine: "open", mode: "finish", tool: "faces" })).toMatchObject({ maker: { id: "oss-h3-fix-faces" } });
+ expect(chooseMaker({ engine: "open", mode: "finish", tool: "colours" })).toMatchObject({ maker: { id: "oss-fix-colours" } });
+ expect(chooseMaker({ engine: "open", mode: "picture" })).toMatchObject({ maker: { id: "oss-from-picture" } });
+ expect(chooseMaker({ engine: "cloud", mode: "picture" })).toEqual({ problem: expect.stringMatching(/Nothing on this engine/) });
+ });
+
+ it("checks in words", () => {
+ const c = (m: Maker, o: Partial<Parameters<typeof genjutsuProblem>[0]> = {}) => genjutsuProblem({ mode: m.modes[0], maker: m, source, range: { start: 0, end: 6 }, references: 1, ...o });
+ expect(c(open("oss-h3-group-swap"), { references: 5 })).toBe("Up to four characters");
+ expect(c(open("oss-h3-group-swap"), { references: 1, character: { onePerPerson: true } })).toBe("Add a second character");
+ expect(c(open("oss-h3-group-swap"), { references: 3, character: { onePerPerson: true } })).toBe("One by one takes two characters");
+ expect(c(open("oss-h3-group-swap"), { range: { start: 0, end: 1.5 } })).toBe("Pick a part between 2 and 15 seconds");
+ expect(c(open("oss-h3-group-swap"), { range: { start: 0, end: 16 } })).toBe("Pick a part between 2 and 15 seconds");
+ expect(c(open("oss-h3-scene-edit"), { references: 0, object: { action: "change" } })).toBe("Name what changes");
+ expect(c(open("oss-h3-scene-edit"), { references: 0, object: { action: "remove" } })).toBe("Name what goes");
+ expect(c(open("oss-h3-scene-edit"), { references: 0, object: { action: "background" } })).toBeNull();
+ expect(c(open("oss-h3-scene-edit"), { references: 0, target: "paint", object: { action: "change" } })).toBe("Paint over what changes");
+ expect(c(open("oss-from-picture"), { picture: { stage: "frame", ownPerson: true }, references: 0 })).toBe("Pick a light, or turn off Keep the clip's own person");
+ expect(c(open("oss-from-picture"), { picture: { stage: "frame" }, references: 0 })).toBe("Add a picture of your character");
+ expect(c(open("oss-from-picture"), { picture: { stage: "video" } })).toBe("Make and pick the first frame first");
+ expect(c(open("oss-h3-fix-faces"), { references: 0 })).toBe("Add the character photo");
+ expect(c(open("oss-fix-colours"), { references: 0, range: { start: 0, end: 19 } })).toBeNull();
+ expect(c(open("oss-h3-fix-faces"), { range: { start: 0, end: 10 }, source: { ...source, duration: 40 } })).toBeNull();
+ // Fix faces holds the whole part in memory: 10 s at most.
+ expect(c(open("oss-h3-fix-faces"), { range: { start: 0, end: 20 }, source: { ...source, duration: 40 } })).toBe("Pick up to 10 seconds of the video");
+ });
+
+ it("which features a request needs", () => {
+ expect(requestFeatures({ mode: "character", maker: open("oss-h3-group-swap"), character: { onePerPerson: true } })).toEqual(["group-swap", "group-swap-one-by-one"]);
+ expect(requestFeatures({ mode: "swap", maker: open("oss-h3-scene-edit"), object: { action: "background" } })).toEqual(["object-background"]);
+ expect(requestFeatures({ mode: "picture", maker: open("oss-from-picture"), picture: { stage: "frame", light: { look: "golden-halo" }, ownPerson: true } })).toEqual(["picture", "picture-light", "picture-own-person"]);
+ expect(requestFeatures({ mode: "motion", maker: getMaker(ORIGINALS.motionLite, "cloud")! })).toEqual([]);
+ });
+
+ it("plans: the part fitted at 24 fps and the quality's short edge, then one job with its settings", () => {
+ const g = oj({ maker: open("oss-h3-group-swap"), character: { people: [{ role: "the person on the left" }], onePerPerson: true, hats: true, mouthsFollowSound: false, edge: "loose" }, seed: 7 });
+ expect(step(g, "part").request).toMatchObject({ modelId: "oss-fit-clip", op: "trim", params: { startTime: 2, endTime: 8, fps: 24, extra: { width: 1308, height: 736 } } });
+ const swap = step(g, "swap");
+ expect(swap.request).toMatchObject({ modelId: "oss-h3-group-swap", op: "group-swap", feature: "genjutsu", inputs: { images: [ref, "/api/files/two.png"] }, params: { seed: 7, resolution: "720p" } });
+ expect(swap.request.params?.extra?.openjutsu).toMatchObject({ pictures: 2, roles: ["the person on the left", ""], hats: true, mouthsFollowSound: false, edge: "loose", onePerPerson: true, seed: 7 });
+ expect(swap.chain).toEqual([{ slot: "video" }]);
+ expect(g.final).toBe("swap");
+
+ const e = oj({ mode: "swap", maker: open("oss-h3-scene-edit"), references: [ref], object: { action: "remove", target: "the handbag" }, quality: "480p" });
+ expect(step(e, "part").request.params?.extra).toEqual({ width: 854, height: 480 });
+ expect(step(e, "edit").request).toMatchObject({ op: "scene-edit", params: { extra: { openjutsu: { action: "remove", target: "the handbag", picture: false } } } });
+ expect(step(e, "edit").request.inputs).toBeUndefined();
+ const bg = oj({ mode: "swap", maker: open("oss-h3-scene-edit"), references: [ref], object: { action: "background", becomes: "an Amalfi terrace" } });
+ expect(step(bg, "edit").request.params?.extra?.openjutsu).toMatchObject({ action: "background", target: "the people", becomes: "an Amalfi terrace", picture: true });
+
+ const frame = oj({ mode: "picture", maker: open("oss-from-picture"), references: [ref], picture: { stage: "frame", light: { look: "golden-halo" } } });
+ expect(frame.steps.map((s) => s.key)).toEqual(["frame"]);
+ expect(step(frame, "frame").request).toMatchObject({ modelId: "oss-from-picture-frame", op: "picture-frame", feature: "genjutsu-step", inputs: { video: source.url, images: [ref] }, params: { startTime: 2 } });
+ expect(String((step(frame, "frame").request.params?.extra?.openjutsu as { light: string }).light)).toMatch(/warm golden glow/);
+ const video = oj({ mode: "picture", maker: open("oss-from-picture"), references: [ref], picture: { stage: "video", frame: "/api/files/frame.png", scene: "She turns." } });
+ expect(step(video, "video").request).toMatchObject({ op: "picture-video", inputs: { images: ["/api/files/frame.png"] }, params: { extra: { openjutsu: { seconds: 6, scene: "She turns." } } } });
+ expect(() => oj({ mode: "picture", maker: open("oss-from-picture"), picture: { stage: "video" } })).toThrow(/first frame/);
+
+ const colours = oj({ mode: "finish", maker: open("oss-fix-colours"), references: [], range: { start: 0, end: 20 }, finish: { tool: "colours", finish: "rich" } });
+ expect(colours.steps.map((s) => s.key)).toEqual(["fix"]);
+ expect(step(colours, "fix").request).toMatchObject({ op: "tone-video", inputs: { video: source.url }, params: { extra: { openjutsu: { finish: "rich" } } } });
+ const faces = oj({ mode: "finish", maker: open("oss-h3-fix-faces"), references: [ref], range: { start: 0, end: 10 }, finish: { tool: "faces", faceStyle: "photo" } });
+ expect(faces.steps.map((s) => s.key)).toEqual(["part", "fix"]);
+ expect(step(faces, "fix").request).toMatchObject({ op: "face-fix-video", inputs: { images: [ref] }, params: { extra: { openjutsu: { faceStyle: "photo", chunkSeconds: 6.5 } } } });
+ expect(fitSize(640, 360, 736)).toEqual({ width: 640, height: 360 });
+ });
+
+ it("setup codes carry the new settings; a code naming what isn't open opens without it", () => {
+ const code = encodeSetup({ mode: "character", engine: "open", model: "oss-h3-group-swap", character: { people: [{ role: "the dancer", pin: { x: 0.25, y: 0.5 } }, { role: "" }], onePerPerson: true, edge: "tight" } });
+ expect(decodeSetup(code)).toMatchObject({ mode: "character", model: "oss-h3-group-swap", character: { people: [{ role: "the dancer", pin: { x: 0.25, y: 0.5 } }, { role: "" }], onePerPerson: true, edge: "tight" } });
+ const visitor = decodeSetup(code, none)!;
+ expect(visitor.model).toBeUndefined();
+ expect(visitor.character?.onePerPerson).toBeUndefined();
+ const pic = encodeSetup({ mode: "picture", picture: { light: { look: "venetian-blinds" }, ownPerson: true, keepCrop: true } });
+ expect(decodeSetup(pic)).toMatchObject({ mode: "picture", picture: { light: { look: "venetian-blinds" }, ownPerson: true, keepCrop: true } });
+ expect(decodeSetup(pic, none)!.mode).toBe("motion");
+ const obj = encodeSetup({ mode: "swap", object: { action: "background", target: "the people", becomes: "a rooftop at dusk" } });
+ expect(decodeSetup(obj)?.object).toEqual({ action: "background", target: "the people", becomes: "a rooftop at dusk" });
+ expect(decodeSetup(obj, none)?.object).toBeUndefined();
+ const fin = encodeSetup({ mode: "finish", finish: { tool: "colours", finish: "filmic", strength: 0.5 } });
+ expect(decodeSetup(fin)).toMatchObject({ mode: "finish", finish: { tool: "colours", finish: "filmic", strength: 0.5 } });
+ expect(decodeSetup(fin, (f) => f === "finish-faces")?.finish).toBeUndefined();
+ });
+
+ it("Who becomes who: a tap writes where the person stands", () => {
+ expect(roleFromPin({ x: 0.1, y: 0.5 })).toBe("the person on the left");
+ expect(roleFromPin({ x: 0.5, y: 0.8 })).toBe("the person in the centre in front");
+ expect(roleFromPin({ x: 0.9, y: 0.1 })).toBe("the person on the right at the back");
+ });
+});
diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.ts
index d660fecb..5fb88e21 100644
--- a/tests/genjutsu.test.ts
+++ b/tests/genjutsu.test.ts
@@ -78,7 +78,9 @@ describe("Genjutsu: which model runs", () => {
expect(sources("cloud", "insert", "type")).toMatchObject({ "kling-o3": "partner", "kling-4": "partner" });
expect(sources("cloud", "swap", "paint")).toEqual({ [ORIGINALS.swapLite]: "original", "wan-22-vace-inpaint": "open" });
expect(sources("cloud", "restyle")).toEqual({ [ORIGINALS.restyle]: "original", "gemini-omni-flash": "partner", "kling-o3-4k-edit": "partner", "happy-horse-video-edit": "partner" });
- expect(sources("open", "character", "type")).toEqual({ [ORIGINALS.character]: "original", "oss-h3-character-swap-relay": "open" });
+ expect(sources("open", "character", "type")).toEqual({ [ORIGINALS.character]: "original", "oss-h3-character-swap-relay": "open", "oss-h3-group-swap": "open" });
+ // A visitor before Group swap has opened: as before.
+ expect(Object.keys(Object.fromEntries(makersFor("open", "character", "type", () => false).map((m) => [m.id, m.source])))).toEqual([ORIGINALS.character, "oss-h3-character-swap-relay"]);
// A picked partner runs.
expect(chooseMaker({ engine: "cloud", mode: "character", modelId: "h3-max-recast" })).toMatchObject({ maker: { id: "h3-max-recast" } });
});
@@ -103,19 +105,23 @@ describe("Genjutsu: which model runs", () => {
it("refuses in words what an engine can't do", () => {
expect(chooseMaker({ engine: "cloud", mode: "character", target: "click" })).toEqual({ problem: CLOUD_CLICK_PROBLEM });
expect(chooseMaker({ engine: "open", mode: "character", target: "click" })).toMatchObject({ maker: { id: ORIGINALS.character, engine: "open" } });
- expect(chooseMaker({ engine: "open", mode: "swap", target: "paint" })).toEqual({ problem: expect.stringMatching(/name what to swap/) });
+ // Painting on your GPU is Scene edit's (the owner, or once it has opened); before that, words only.
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "paint", open: () => false })).toEqual({ problem: expect.stringMatching(/name what to swap/) });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "paint" })).toMatchObject({ maker: { id: "oss-h3-scene-edit" } });
expect(chooseMaker({ engine: "open", mode: "insert", target: "type" })).toEqual({ problem: expect.stringMatching(/paint where it goes/) });
expect(chooseMaker({ engine: "cloud", mode: "character", target: "paint" })).toEqual({ problem: expect.stringMatching(/doesn't take paint/) });
});
it("every maker is a catalog model that does its mode's operation on its engine", () => {
- const ops = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v" } as const;
+ const ops = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v", picture: "picture-video", finish: "tone-video" } as const;
+ const opOf = (m: Maker, mode: keyof typeof ops) =>
+ m.group ? "group-swap" : m.actions ? "scene-edit" : m.review ? "picture-video" : m.tool === "faces" ? "face-fix-video" : m.tool === "colours" ? "tone-video" : ops[mode];
for (const m of MAKERS) {
const model = getModel(m.id);
expect(model, m.id).toBeDefined();
expect(model!.engines ?? [model!.engine], m.id).toContain(m.engine);
const providers = m.engine === "open" ? ["comfyui"] : ["fal", "replicate"];
- for (const mode of m.modes) expect(model!.routes.some((r) => r.op === ops[mode] && providers.includes(r.provider)), `${m.id} ${m.engine} ${mode}`).toBe(true);
+ for (const mode of m.modes) expect(model!.routes.some((r) => r.op === opOf(m, mode) && providers.includes(r.provider)), `${m.id} ${m.engine} ${mode}`).toBe(true);
}
// The Originals are one model on both engines.
for (const id of Object.values(ORIGINALS)) expect(getModel(id)?.engines).toEqual(["open", "cloud"]);
diff --git a/tests/openjutsu-graphs.test.ts b/tests/openjutsu-graphs.test.ts
new file mode 100644
index 00000000..65a8fd16
--- /dev/null
+++ b/tests/openjutsu-graphs.test.ts
@@ -0,0 +1,219 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import type { ComfyWorkflow } from "@/lib/comfy";
+import {
+ canvasSize,
+ clampCanvas,
+ danglingLinks,
+ describeScene,
+ detailFor,
+ faceChunkCount,
+ FRAME_RELIGHT_PROMPT,
+ LIGHT_LOOKS,
+ lightWords,
+ nodeByTitle,
+ openjutsuGraph,
+ openjutsuLeftOut,
+ OPENJUTSU_WORKFLOWS as W,
+ paintKeyframe,
+ pictureFrames,
+ pictureVideo,
+ preparePicture,
+ pruneColor,
+ pruneFace,
+ pruneGroupSwap,
+ pruneSceneEdit,
+ RELIGHT_PROMPT,
+ rolesText,
+ runName,
+ toneFor,
+} from "@/lib/openjutsu-graphs";
+
+// The Openjutsu graphs Genjutsu sends (Fuobe's copies of D3voz's graphs, as built into workflows/comfyui), with each
+// request's settings written by node title.
+const graph = (id: string) => JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui", `${id}.json`), "utf8")) as ComfyWorkflow;
+const byTitle = (g: ComfyWorkflow, t: string) => g[nodeByTitle(g, t)];
+const titles = (g: ComfyWorkflow) => Object.values(g).map((n) => n._meta?.title ?? "");
+const group = { pictures: 2, roles: ["the person on the left", ""], resolution: "736p", motion: 512 as const, hatFix: false, noLipSync: false, edge: "normal" as const, seed: 9, run: "fuobe_g1" };
+
+describe("Group swap's graphs", () => {
+ it("drop the pictures not sent (their shrink and describer too) and leave no dangling link", () => {
+ for (const n of [1, 2, 3, 4]) {
+ const g = pruneGroupSwap(graph(W.group), { ...group, pictures: n, roles: [] });
+ expect(Object.values(g).filter((x) => x.class_type === "LoadImage").length).toBe(n);
+ expect(danglingLinks(g)).toEqual([]);
+ for (let k = n + 1; k <= 4; k++) expect(titles(g)).not.toContain(`Describe picture ${k}`);
+ }
+ expect(() => pruneGroupSwap(graph(W.group), { ...group, pictures: 5 })).toThrow(/1–4/);
+ // One by one takes exactly two.
+ expect(danglingLinks(pruneGroupSwap(graph(W.groupOneByOne), group))).toEqual([]);
+ });
+
+ it("roles: one line per character, the empty ones named by screen time; none at all lets the describer name them", () => {
+ expect(rolesText(["the person on the left", ""], 2)).toBe("the person on the left\nthe person with the second most screen time");
+ expect(rolesText(["", ""], 2)).toBe("");
+ expect(rolesText(["the dancer"], 1)).toBe("the dancer");
+ const plan = byTitle(pruneGroupSwap(graph(W.group), group), "Swap Plan (roles, seed, size)").inputs;
+ expect(plan).toMatchObject({ roles: "the person on the left\nthe person with the second most screen time", seed: 9, resolution: "736p", clip_seconds: 6 });
+ });
+
+ it("hats off and mouths following the sound take their nodes out; each job has its own run name", () => {
+ const g = pruneGroupSwap(graph(W.group), group);
+ expect(titles(g).some((t) => /\bhats?\b/i.test(t))).toBe(false);
+ expect(titles(g)).not.toContain("No lip-sync in the prompt");
+ expect(titles(g)).not.toContain("Mute the clip audio H3 hears");
+ const withAll = pruneGroupSwap(graph(W.group), { ...group, hatFix: true, noLipSync: true });
+ expect(titles(withAll)).toContain("SAM 3.1 track hats");
+ expect(titles(withAll)).toContain("No lip-sync in the prompt");
+ const plan = Object.values(g).find((n) => n.class_type === "MiniMaxH3ChainPlanModern")!;
+ expect(plan.inputs.run_name).toBe("fuobe_g1");
+ expect(runName("abc-12_x/..")).toBe("fuobe_abc-12_x");
+ expect(runName("a")).not.toBe(runName("b"));
+ });
+
+ it("edge and motion detail", () => {
+ const g = pruneGroupSwap(graph(W.group), { ...group, edge: "loose", motion: 768 });
+ expect(Object.values(g).filter((n) => n.class_type === "GrowMaskWithBlur" && / grow mask /.test(n._meta?.title ?? "")).every((n) => n.inputs.expand === 60)).toBe(true);
+ expect(Object.values(g).filter((n) => /motion reference/i.test(n._meta?.title ?? "") && n.class_type === "ImageScaleToMaxDimension").every((n) => n.inputs.largest_size === 768)).toBe(true);
+ });
+});
+
+describe("Scene edit's graph", () => {
+ const base = { target: "her coat", becomes: "a crimson velvet tailored blazer", picture: true, biggestOnly: false, keepShape: false, edge: "normal" as const, motion: 512 as const, resolution: "736p", seed: 3, run: "fuobe_g2" };
+ it("change with a picture keeps the picture; without the outline the grey reference video goes", () => {
+ const g = pruneSceneEdit(graph(W.scene), { ...base, action: "change" });
+ expect(titles(g)).toContain("Picture 1");
+ const ref = byTitle(g, "Reference Conditioning").inputs;
+ expect(ref["ref_images.ref_image_0"]).toBeDefined();
+ expect(ref["ref_videos.ref_video_0"]).toBeUndefined();
+ expect(byTitle(g, "Object Swap Plan (what to change)").inputs).toMatchObject({ mode: "change", target: "her coat", change_to: "a crimson velvet tailored blazer", seed: 3 });
+ expect(byTitle(g, "SAM: what to change").inputs.text).toBe("her coat");
+ expect(danglingLinks(g)).toEqual([]);
+ expect(byTitle(pruneSceneEdit(graph(W.scene), { ...base, action: "change", keepShape: true }), "Reference Conditioning").inputs["ref_videos.ref_video_0"]).toBeDefined();
+ });
+
+ it("remove drops the picture; background flips the grown mask; the margins are the object ones", () => {
+ const r = pruneSceneEdit(graph(W.scene), { ...base, action: "remove" });
+ expect(titles(r)).not.toContain("Picture 1");
+ expect(danglingLinks(r)).toEqual([]);
+ const b = pruneSceneEdit(graph(W.scene), { ...base, action: "background", target: "the people", edge: "loose" });
+ expect(byTitle(b, "Grow mask").inputs).toMatchObject({ flip_input: true, expand: 40 });
+ expect(danglingLinks(b)).toEqual([]);
+ });
+
+ it("a painted keyframe is run-length encoded at <= 256 px and follows the tracked area", () => {
+ const w = 512;
+ const h = 288;
+ const data = new Uint8Array(w * h * 4);
+ for (let y = 100; y < 150; y++) for (let x = 200; x < 300; x++) data[(y * w + x) * 4] = 255;
+ const k = paintKeyframe({ width: w, height: h, data });
+ expect([k.width, k.height]).toEqual([256, 144]);
+ expect(k.runs.length % 2).toBe(0);
+ expect(k.runs.length).toBeGreaterThan(0);
+ const g = pruneSceneEdit(graph(W.scene), { ...base, action: "change", paint: [k] });
+ expect(g.object_paint.class_type).toBe("H3PaintedEditArea");
+ expect(byTitle(g, "Grow mask").inputs.mask).toEqual(["object_paint_clip", 0]);
+ expect(danglingLinks(g)).toEqual([]);
+ });
+});
+
+describe("From picture's graphs", () => {
+ it("the first frame: the clip's shape at 768 px, the seed, the positive request", () => {
+ const g = preparePicture(graph(W.prepare), { width: 1920, height: 1080, seed: 5, light: "", ownPerson: false, keepCrop: false });
+ expect([g["3"].inputs.width, g["3"].inputs.height]).toEqual(canvasSize(1920, 1080, "768p"));
+ expect(g["19"].inputs.seed).toBe(5);
+ expect(String(g["6"].inputs.value)).toMatch(/^Show the character from <image 1> in exactly the pose/);
+ expect(danglingLinks(g)).toEqual([]);
+ });
+
+ it("a light makes it one pass (the character only, at 3 MP); the clip's own person is relit, keeping the crop at denoise 0.9", () => {
+ const light = lightWords({ look: "golden-halo" });
+ const lit = preparePicture(graph(W.prepare), { width: 1280, height: 720, seed: 1, light, ownPerson: false, keepCrop: false, adjust: "arms crossed" });
+ expect(String(lit["6"].inputs.value)).toContain("Arms crossed.");
+ expect(String(lit["6"].inputs.value)).toContain(light);
+ expect(lit["15"].inputs["images.image1"]).toBeUndefined();
+ expect(lit.relight_latent.class_type).toBe("EmptyFlux2LatentImage");
+ expect(danglingLinks(lit)).toEqual([]);
+ const own = preparePicture(graph(W.prepare), { width: 1280, height: 720, seed: 1, light, ownPerson: true, keepCrop: true });
+ expect(own["4"]).toBeUndefined();
+ expect(own["19"].inputs.denoise).toBe(0.9);
+ expect(own.relight_start.class_type).toBe("VAEEncode");
+ expect(String(own["6"].inputs.value)).toContain(FRAME_RELIGHT_PROMPT.replace(" {look}", ""));
+ expect(danglingLinks(own)).toEqual([]);
+ expect(preparePicture(graph(W.prepare), { width: 1280, height: 720, seed: 1, light, ownPerson: true, keepCrop: false })["19"].inputs.denoise).toBe(1);
+ expect(() => preparePicture(graph(W.prepare), { width: 1280, height: 720, seed: 1, light: "", ownPerson: true, keepCrop: false })).toThrow(/light/);
+ });
+
+ it("17 looks with plain names; own words travel as a sentence", () => {
+ expect(LIGHT_LOOKS).toHaveLength(17);
+ expect(new Set(LIGHT_LOOKS.map((l) => l.id)).size).toBe(17);
+ expect(LIGHT_LOOKS.map((l) => l.name)).not.toContain("Magenta club · mostly the background");
+ expect(lightWords({ words: "soft pearl light from a high window." })).toBe("Light the new photo this way: soft pearl light from a high window.");
+ expect(lightWords(undefined)).toBe("");
+ });
+
+ it("what happens: the part's frames, and pass 1 alone for the clip's own person", () => {
+ const g = describeScene(graph(W.describe), { frames: pictureFrames(6), ownPerson: false });
+ expect(g["1"].inputs.frame_load_cap).toBe(141);
+ const own = describeScene(graph(W.describe), { frames: 141, ownPerson: true });
+ expect(own["74"]).toBeUndefined();
+ expect(own["79"].inputs.source).toEqual(["73", 0]);
+ expect(danglingLinks(own)).toEqual([]);
+ });
+
+ it("the video: frames on H3's grid, the canvas clamped at 2048, the description opening the shot", () => {
+ expect([pictureFrames(6), pictureFrames(5.9), pictureFrames(15)]).toEqual([141, 141, 345]);
+ expect(clampCanvas([2624, 1088])).toEqual([2048, 832]);
+ const g = pictureVideo(graph(W.solar), { renderer: "solar", seconds: 6, width: 1920, height: 1080, quality: "720p", motion: 0, seed: 4, description: "The character turns to camera." });
+ expect(g["56"].inputs).toMatchObject({ length: 141 });
+ expect(Math.max(Number(g["56"].inputs.width), Number(g["56"].inputs.height))).toBeLessThanOrEqual(2048);
+ expect(String(g["56"].inputs.prompt)).toContain("[Shot 1] The shot begins from <Video 2>. The character turns to camera. ");
+ expect(g["60"].inputs.steps).toBe(4);
+ expect(g["65"].inputs.seed).toBe(4);
+ expect(pictureVideo(graph(W.h3), { renderer: "h3", seconds: 6, width: 1280, height: 720, quality: "480p", motion: 512, seed: 4 })["60"].inputs.steps).toBe(6);
+ expect(() => pictureVideo(graph(W.solar), { renderer: "solar", seconds: 0.5, width: 1280, height: 720, quality: "480p", motion: 0, seed: 1 })).toThrow();
+ });
+});
+
+describe("Finish's graphs", () => {
+ it("Fix faces: match the photo drops the blurred face; largest_face; sections", () => {
+ const photo = pruneFace(graph(W.faces), { style: "photo", seed: 2, chunkSeconds: 4 });
+ expect(titles(photo)).not.toContain("Blurred face (follow the mouth)");
+ expect(byTitle(photo, "Reference Conditioning").inputs["ref_videos.ref_video_0"]).toBeUndefined();
+ expect(byTitle(photo, "Face Fix Chunks").inputs.chunk_seconds).toBe(4);
+ expect(Object.values(photo).filter((n) => n.class_type === "H3FaceTrackCrop").every((n) => n.inputs.select === "largest_face")).toBe(true);
+ expect(danglingLinks(photo)).toEqual([]);
+ const mouth = pruneFace(graph(W.faces), { style: "mouth", seed: 2, chunkSeconds: 6.5 });
+ expect(titles(mouth)).toContain("Blurred face (follow the mouth)");
+ expect([faceChunkCount(5.8, 6.5), faceChunkCount(6, 6.5), faceChunkCount(17, 6.5)]).toEqual([1, 2, 4]);
+ });
+
+ it("Fix colours: a step turned off goes; the tone travels in raw_settings", () => {
+ const off = pruneColor(graph(W.colours), { detail: null, tone: null });
+ expect(Object.values(off).map((n) => n.class_type).sort()).toEqual(["VHS_BatchManager", "VHS_LoadVideo", "VHS_VideoCombine"]);
+ expect(danglingLinks(off)).toEqual([]);
+ const soft = pruneColor(graph(W.colours), { detail: detailFor(0.33), tone: toneFor("soft", 0.4) });
+ expect(byTitle(soft, "Detail contrast").inputs.detail_contrast).toBeCloseTo(-0.198, 3);
+ expect(JSON.parse(String(byTitle(soft, "Tone mapper").inputs.raw_settings)).settings).toMatchObject({ mode: "Reinhard", strength: 0.2 });
+ expect(toneFor("rich", 0.1)).toMatchObject({ mode: "Filmic Strong", strength: 0.35 });
+ expect(detailFor(0)).toBeNull();
+ });
+});
+
+describe("the provider's branch", () => {
+ it("one settings object per workflow; the pictures left out", () => {
+ const g = openjutsuGraph(W.group, graph(W.group), { pictures: 2, roles: ["a", "b"], quality: "720p", seed: 1 }, { generationId: "gen1" });
+ expect(byTitle(g, "Swap Plan (roles, seed, size)").inputs.resolution).toBe("736p");
+ expect(openjutsuLeftOut(W.group, { pictures: 2 })).toEqual(["image3", "image4"]);
+ expect(openjutsuLeftOut(W.scene, { action: "remove", picture: true })).toEqual(["image"]);
+ expect(openjutsuLeftOut(W.prepare, { ownPerson: true })).toEqual(["image"]);
+ expect(() => openjutsuGraph(W.prepare, graph(W.prepare), {}, { generationId: "g" })).toThrow(/size/);
+ });
+
+ it("no image or video prompt names what isn't wanted (Fuobe's rule)", () => {
+ const NEG = /\b(do not|don't|never|no other|without|not replaced)\b/i;
+ const prompts: string[] = [RELIGHT_PROMPT, ...LIGHT_LOOKS.map((l) => l.light), String(graph(W.prepare)["6"].inputs.value), String(graph(W.solar)["56"].inputs.prompt), String(graph(W.h3)["56"].inputs.prompt)];
+ for (const p of prompts) expect(p, p.slice(0, 60)).not.toMatch(NEG);
+ });
+});