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.

Merge Character swap in 2K: 1080p / 2K / 4K in Genjutsu and Sharpen in Character Swap Studio

Adarsh995aada45f90
diff --cc docs/research/new-models-7.md
index dcd98e77,f66ef178..c46e5cd2
--- a/docs/research/new-models-7.md
+++ b/docs/research/new-models-7.md
@@@ -876,6 -876,8 +876,8 @@@ Browser checks: at 1440 px and 390 px w
What can't be verified here: GPU runs; whether σ 0.8 keeps the swapped identity; how the mask edge looks at 2K; any fal call. Add eval cases (scripts/eval) that compare identity (face similarity to the character) and background difference against the source, so a GPU run can decide the default σ.
-**Corrections from building it (n7-4-character-swap-2k, 2026-11-01).** (1) The segment's FFV1 master keeps only the take's last frames (`masterKeep`, the next segment's history), so the regenerate reads the take's own video, not the master. (2) fal's H3 resolution enum is 480P, 768P, 2K and 4K: there is no 1080P, so the cloud offers 2K and 4K (Genjutsu's 1080p on the cloud stays the 768P swap). (3) Both engines join the film at no more than 2048 px a side (the open engine's 24 fps copy and fit graph, fal merge-videos), so "capped at the source" means capped at that size: a 1080p clip sharpens at 1080p on your GPU, and the cloud's 4K adds nothing to such a film. (4) The regenerate keeps a 16:9 (or 9:16) centre of the take, so the composite lays two layers through the mask: the 768p swap over the part of the footage its canvas covers, then the regenerate over the centre its draft kept; a character reaching past that centre keeps the 768p swap there rather than the original person. (5) The composite decodes four streams as float32, so it runs in windows of at most 3 s, joined packet by packet. (6) Main's copy polish (157e5ba2, 2026-11-01) removed the old not-available Finish panel; the backplate card is back for the owner only.
++**Corrections from building it (2026-11-01).** (1) The segment's FFV1 master keeps only the take's last frames (`masterKeep`, the next segment's history), so the regenerate reads the take's own video, not the master. (2) fal's H3 resolution enum is 480P, 768P, 2K and 4K: there is no 1080P, so the cloud offers 2K and 4K (Genjutsu's 1080p on the cloud stays the 768P swap). (3) Both engines join the film at no more than 2048 px a side (the open engine's 24 fps copy and fit graph, fal merge-videos), so "capped at the source" means capped at that size: a 1080p clip sharpens at 1080p on your GPU, and the cloud's 4K adds nothing to such a film. (4) The regenerate keeps a 16:9 (or 9:16) centre of the take, so the composite lays two layers through the mask: the 768p swap over the part of the footage its canvas covers, then the regenerate over the centre its draft kept; a character reaching past that centre keeps the 768p swap there rather than the original person. (5) The composite decodes four streams as float32, so it runs in windows of at most 3 s, joined packet by packet. (6) Main's copy polish (157e5ba2, 2026-11-01) removed the old not-available Finish panel; the backplate card is back for the owner only.
+
### 5.6 N7-5 · Fly path in Cinema's 3D scene, and the camera-path library
_Priority P0 · effort large · depends on none · key `n7-5-fly-path` · research §3.3, §3.6, §3.7, §3.9, §3.10, §3.11_
diff --cc scripts/comfy/build-library.mjs
index 4bc3a58b,77fe5d6b..83f60787
--- a/scripts/comfy/build-library.mjs
+++ b/scripts/comfy/build-library.mjs
@@@ -156,6 -156,8 +156,8 @@@ export const BINDING_KEYS = new Set(
'preset',
// Open-H3 Regenerate (n7-3): the pack's output size and draft size (its combo strings) and the refine's start noise
'resolution', 'draftSize', 'startSigma',
- // Character swap in 2K (n7-4): the mask composite's window starts, the two layers' places and the mask's soft edge
++ // Character swap in 2K: the mask composite's window starts, the two layers' places and the mask's soft edge
+ 'takeStart', 'maskStart', 'takeX', 'takeY', 'regionWidth', 'regionHeight', 'regenWidth', 'regenHeight', 'regenX', 'regenY', 'trimX', 'trimY', 'feather',
// Clean up voice (ComfyUI-RE-USE): the RE-USE file, the rate it runs at, room tone, level and the music & effects bed's level
'reuseModel', 'rate', 'roomToneDb', 'level', 'bedDb',
// Blockout to film: a near = dark depth pass (Blender's mist) inverted before VACE reads it
diff --cc scripts/comfy/library.spec.mjs
index c0c58609,7029fe0f..12f861e1
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@@ -4725,6 -4725,41 +4725,41 @@@ export const SPEC =
'length, which CreateVideo muxes back at 24 fps. Measured by the pack\'s author: about 3 min per 5 s at 2K on a 72 GB RTX PRO 5000 (9.5 min with dense attention); 22 s on a B200 (NVIDIA); ' +
'a community run reached about 1080p on 32 GB with a lossy LoRA. The packs were tested by their author on ComfyUI 0.42.0.',
},
- // ---- Character swap in 2K (package n7-4-character-swap-2k; docs/research/new-models-7.md §2.10 rows 4-5): only the swapped
++ // ---- Character swap in 2K (docs/research/new-models-7.md §2.10 rows 4-5): only the swapped
+ // character comes from the regenerate, over the original footage, with the footage's own sound.
+ {
+ id: 'video-composite-mask',
+ title: 'Put only the swapped character back over the original footage: the 768p swap, then the regenerated one, each through the approved mask (grown, feathered), with the footage\'s sound (core nodes, no model)',
+ capability: 'composite',
+ handBuilt: 'hand-built/video-composite-mask.json',
+ bindings: {
+ video: [b('source', 'file')], video2: [b('regen', 'file')], video3: [b('take', 'file')], mask: [b('mask', 'file')],
+ startTime: [b('source_slice', 'start_time')], windowStart: [b('regen_slice', 'start_time')], takeStart: [b('take_slice', 'start_time')], maskStart: [b('mask_slice', 'start_time')],
+ duration: [b('source_slice', 'duration'), b('regen_slice', 'duration'), b('take_slice', 'duration'), b('mask_slice', 'duration')],
+ canvasWidth: [b('take_scaled', 'width'), b('take_mask_img', 'width')], canvasHeight: [b('take_scaled', 'height'), b('take_mask_img', 'height')],
+ takeX: [b('base', 'x')], takeY: [b('base', 'y')],
+ regionWidth: [b('regen_mask_img', 'width')], regionHeight: [b('regen_mask_img', 'height')],
+ regenWidth: [b('regen_scaled', 'width'), b('regen_trim', 'width')], regenHeight: [b('regen_scaled', 'height'), b('regen_trim', 'height')],
+ trimX: [b('regen_trim', 'x')], trimY: [b('regen_trim', 'y')],
+ regenX: [b('composite', 'x')], regenY: [b('composite', 'y')],
+ maskGrow: [b('take_grow', 'expand'), b('regen_grow', 'expand')],
+ feather: [b('take_feather', 'left'), b('take_feather', 'top'), b('take_feather', 'right'), b('take_feather', 'bottom'), b('regen_feather', 'left'), b('regen_feather', 'top'), b('regen_feather', 'right'), b('regen_feather', 'bottom')],
+ filenamePrefix: [b('save', 'filename_prefix')],
+ },
+ outputs: [{ node: 'save', kind: 'video' }],
+ defaults: { startTime: 0, windowStart: 0, takeStart: 0, maskStart: 0, duration: 3, canvasWidth: 320, canvasHeight: 180, takeX: 0, takeY: 0, regionWidth: 316, regionHeight: 180, regenWidth: 316, regenHeight: 179, trimX: 0, trimY: 0, regenX: 2, regenY: 0, maskGrow: 8, feather: 12 },
+ vramGb: 0,
+ license: 'n/a (no model; ComfyUI core)',
+ notes:
+ 'Character Swap Studio\'s Sharpen and Genjutsu\'s Character swap at 1080p / 2K / 4K on your GPU: a swap was redrawn by video-regenerate-h3, and only the character goes back over the footage, so the background and the sound stay as filmed. ' +
+ 'video = the footage at 24 fps and the film\'s size (the studio\'s 24 fps copy, or Genjutsu\'s part fitted by video-fit-clip), video3 = the 768p swap (H3\'s canvas), video2 = its regenerate, mask = the approved whole-shot mask from video-mask-h3-relay (H3\'s canvas, white = the person). ' +
+ 'Each LoadVideo goes through a Video Slice of the same duration (one composite window of at most 3 s, because every stream is decoded as float32, about 25 MB a frame at 1080p) from its own start (startTime, takeStart, windowStart, maskStart). ' +
+ 'Two layers, each through the mask scaled to it, grown (maskGrow) and feathered (feather): first the swap stretched back over the region of the footage its canvas covers (canvasWidth x canvasHeight at takeX, takeY), ' +
+ 'then the regenerate over the centre region its 16:9 / 9:16 draft kept (regionWidth x regionHeight; the mask is centre-cropped to it), less the rows its finish trims at 1080p and 4K (1080 of 1088, 2160 of 2176; the columns for a tall clip): ' +
+ 'the regenerate is laid over regenWidth x regenHeight at regenX, regenY and the mask cut to the same rows (CropMask at trimX, trimY), so a character reaching past that region keeps the 768p swap there rather than the original person. ' +
+ 'Fuobe works the regions out from the film\'s size and H3\'s canvas. CreateVideo takes the footage\'s own sound and rate (a silent clip stays silent). ' +
+ 'Run end to end on ComfyUI 0.41.0 (CPU): a 320x180 24 fps clip with sound, a 224x128 swap, a 384x216 regenerate and a 224x128 box mask, a 1.5 s window from 0.5 s: 36 frames and 1.5 s of AAC, the regenerate only inside the feathered box; the same with a silent clip gives video only.',
+ },
{
id: 'video-sdr-to-hdr-exr',
title: 'SDR to HDR as OpenEXR frames (scene-linear Rec.2020, half float) plus a 10-bit HLG preview (core, no model)',
diff --cc scripts/eval/cases/character-2k.json
index 00000000,ccb2eb2b..52ce4e6a
mode 000000,100644..100644
--- a/scripts/eval/cases/character-2k.json
+++ b/scripts/eval/cases/character-2k.json
@@@ -1,0 -1,377 +1,377 @@@
+ {
+ "$schema": "./case.schema.json",
+ "suite": "character-2k",
+ "title": "Fuobe Character swap in 2K · the regenerate's start noise",
- "description": "The Character swap at 1080p / 2K / 4K (package n7-4-character-swap-2k, src/lib/catalog/sharpen.ts) on Genjutsu's route (POST /api/genjutsu), on your clip and character in local/genjutsu/: person.mp4 (5–15 s, one continuous shot, at least 1080p, the person visible in its first frame) and character.png (a consenting person or a drawn character). On your GPU the 768p swap is redrawn by Open-H3 Regenerate and only the character is composited back over the footage; each case tries one start noise (character.sharpenSigma: 0.7, 0.8 or the release's 0.909) against the 768p swap. In the cloud fal's H3 makes 2K itself (no start noise), for reference. Scores: identity (the face against the character picture: does the redraw keep who they are?), background (the frame's outer ring against the source clip: does the background stay as filmed?) and temporal (flicker). Needs a GPU ComfyUI with OPEN_H3_REGEN=1 and H3_RELAY=1 for the open cases.",
++ "description": "The Character swap at 1080p / 2K / 4K (src/lib/catalog/sharpen.ts) on Genjutsu's route (POST /api/genjutsu), on your clip and character in local/genjutsu/: person.mp4 (5–15 s, one continuous shot, at least 1080p, the person visible in its first frame) and character.png (a consenting person or a drawn character). On your GPU the 768p swap is redrawn by Open-H3 Regenerate and only the character is composited back over the footage; each case tries one start noise (character.sharpenSigma: 0.7, 0.8 or the release's 0.909) against the 768p swap. In the cloud fal's H3 makes 2K itself (no start noise), for reference. Scores: identity (the face against the character picture: does the redraw keep who they are?), background (the frame's outer ring against the source clip: does the background stay as filmed?) and temporal (flicker). Needs a GPU ComfyUI with OPEN_H3_REGEN=1 and H3_RELAY=1 for the open cases.",
+ "original": [
+ "fuobe-character-swap"
+ ],
+ "kind": "video",
+ "decides": "The default start noise of the Character swap's 2K finish on your GPU (SHARPEN_SIGMA in src/lib/catalog/sharpen.ts, now 0.8). In one open run on at least 3 clips, the sigma whose identity is highest within 0.01 of the 768p swap's, with bgDiff within 0.002 of the best, becomes the default in a reviewed change; a tie keeps 0.8. A sigma whose identity falls more than 0.03 below the 768p swap is never the default.",
+ "targets": {
+ "open": {
+ "models": [
+ "fuobe-character-swap"
+ ]
+ },
+ "cloud": {
+ "models": [
+ "fuobe-character-swap"
+ ]
+ },
+ "demo": {
+ "models": [
+ "fuobe-character-swap"
+ ]
+ }
+ },
+ "defaults": {
+ "seeds": [
+ 1001,
+ 2002
+ ],
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "timeoutSeconds": 3600,
+ "candidate": "original"
+ },
+ "variants": {
+ "original": {
+ "description": "The Character swap as Genjutsu runs it"
+ }
+ },
+ "cases": [
+ {
+ "id": "character-2k/768p",
+ "title": "The 768p swap alone: the baseline every finish is compared with",
+ "models": {
+ "open": [
+ "fuobe-character-swap"
+ ],
+ "cloud": [
+ "fuobe-character-swap"
+ ],
+ "demo": [
+ "fuobe-character-swap"
+ ]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4",
+ "images": [
+ "local/genjutsu/character.png"
+ ]
+ },
+ "demoInputs": {
+ "video": "fixtures/walk-6s.mp4",
+ "images": [
+ "fixtures/character/drawn-face-2.png"
+ ]
+ },
+ "prompts": [
+ {
+ "id": "direction",
+ "text": "keep the walk and the timing; the character wears the same clothes as in the picture"
+ }
+ ],
+ "references": "local/genjutsu/character.png",
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "mode": "character",
+ "modelId": "{{modelId}}",
+ "prompt": "{{prompt}}",
+ "references": [
+ "{{inputs.images.0}}"
+ ],
+ "source": "{{source:inputs.video}}",
+ "range": {
+ "start": 0,
+ "end": 5
+ },
+ "quality": "768p",
+ "character": {
+ "who": "largest"
+ },
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}"
+ }
+ }
+ },
+ {
+ "id": "character-2k/sigma-07",
+ "title": "2K on your GPU at start noise 0.7 (Close: stays nearest the swap)",
+ "models": {
+ "open": [
+ "fuobe-character-swap"
+ ],
+ "cloud": [
+ "fuobe-character-swap"
+ ],
+ "demo": [
+ "fuobe-character-swap"
+ ]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4",
+ "images": [
+ "local/genjutsu/character.png"
+ ]
+ },
+ "demoInputs": {
+ "video": "fixtures/walk-6s.mp4",
+ "images": [
+ "fixtures/character/drawn-face-2.png"
+ ]
+ },
+ "prompts": [
+ {
+ "id": "direction",
+ "text": "keep the walk and the timing; the character wears the same clothes as in the picture"
+ }
+ ],
+ "references": "local/genjutsu/character.png",
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "mode": "character",
+ "modelId": "{{modelId}}",
+ "prompt": "{{prompt}}",
+ "references": [
+ "{{inputs.images.0}}"
+ ],
+ "source": "{{source:inputs.video}}",
+ "range": {
+ "start": 0,
+ "end": 5
+ },
+ "quality": "2K",
+ "character": {
+ "who": "largest",
+ "sharpenSigma": 0.7
+ },
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}"
+ }
+ },
+ "engines": [
+ "open",
+ "demo"
+ ]
+ },
+ {
+ "id": "character-2k/sigma-08",
+ "title": "2K on your GPU at start noise 0.8 (the default)",
+ "models": {
+ "open": [
+ "fuobe-character-swap"
+ ],
+ "cloud": [
+ "fuobe-character-swap"
+ ],
+ "demo": [
+ "fuobe-character-swap"
+ ]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4",
+ "images": [
+ "local/genjutsu/character.png"
+ ]
+ },
+ "demoInputs": {
+ "video": "fixtures/walk-6s.mp4",
+ "images": [
+ "fixtures/character/drawn-face-2.png"
+ ]
+ },
+ "prompts": [
+ {
+ "id": "direction",
+ "text": "keep the walk and the timing; the character wears the same clothes as in the picture"
+ }
+ ],
+ "references": "local/genjutsu/character.png",
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "mode": "character",
+ "modelId": "{{modelId}}",
+ "prompt": "{{prompt}}",
+ "references": [
+ "{{inputs.images.0}}"
+ ],
+ "source": "{{source:inputs.video}}",
+ "range": {
+ "start": 0,
+ "end": 5
+ },
+ "quality": "2K",
+ "character": {
+ "who": "largest",
+ "sharpenSigma": 0.8
+ },
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}"
+ }
+ },
+ "engines": [
+ "open",
+ "demo"
+ ]
+ },
+ {
+ "id": "character-2k/sigma-0909",
+ "title": "2K on your GPU at the release's start noise 0.909 (redraws the most; a face can drift)",
+ "models": {
+ "open": [
+ "fuobe-character-swap"
+ ],
+ "cloud": [
+ "fuobe-character-swap"
+ ],
+ "demo": [
+ "fuobe-character-swap"
+ ]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4",
+ "images": [
+ "local/genjutsu/character.png"
+ ]
+ },
+ "demoInputs": {
+ "video": "fixtures/walk-6s.mp4",
+ "images": [
+ "fixtures/character/drawn-face-2.png"
+ ]
+ },
+ "prompts": [
+ {
+ "id": "direction",
+ "text": "keep the walk and the timing; the character wears the same clothes as in the picture"
+ }
+ ],
+ "references": "local/genjutsu/character.png",
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "mode": "character",
+ "modelId": "{{modelId}}",
+ "prompt": "{{prompt}}",
+ "references": [
+ "{{inputs.images.0}}"
+ ],
+ "source": "{{source:inputs.video}}",
+ "range": {
+ "start": 0,
+ "end": 5
+ },
+ "quality": "2K",
+ "character": {
+ "who": "largest",
+ "sharpenSigma": 0.909
+ },
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}"
+ }
+ },
+ "engines": [
+ "open",
+ "demo"
+ ]
+ },
+ {
+ "id": "character-2k/cloud-2k",
+ "title": "2K in the cloud: fal's H3 makes it from a 768P base (the whole frame is redrawn)",
+ "models": {
+ "open": [
+ "fuobe-character-swap"
+ ],
+ "cloud": [
+ "fuobe-character-swap"
+ ],
+ "demo": [
+ "fuobe-character-swap"
+ ]
+ },
+ "inputs": {
+ "video": "local/genjutsu/person.mp4",
+ "images": [
+ "local/genjutsu/character.png"
+ ]
+ },
+ "demoInputs": {
+ "video": "fixtures/walk-6s.mp4",
+ "images": [
+ "fixtures/character/drawn-face-2.png"
+ ]
+ },
+ "prompts": [
+ {
+ "id": "direction",
+ "text": "keep the walk and the timing; the character wears the same clothes as in the picture"
+ }
+ ],
+ "references": "local/genjutsu/character.png",
+ "metrics": [
+ "identity",
+ "background",
+ "temporal"
+ ],
+ "submit": {
+ "route": "/api/genjutsu",
+ "body": {
+ "engine": "{{engine}}",
+ "mode": "character",
+ "modelId": "{{modelId}}",
+ "prompt": "{{prompt}}",
+ "references": [
+ "{{inputs.images.0}}"
+ ],
+ "source": "{{source:inputs.video}}",
+ "range": {
+ "start": 0,
+ "end": 5
+ },
+ "quality": "2K",
+ "character": {
+ "who": "largest"
+ },
+ "seed": "{{seed}}",
+ "requestId": "{{requestId}}"
+ }
+ },
+ "engines": [
+ "cloud"
+ ],
+ "note": "The cloud has no composite: expect a higher bgDiff than your GPU's cases"
+ }
+ ]
+ }
diff --cc src/components/swap-studio/stage-review.tsx
index 3d99ed3e,c9344185..7ade817b
--- a/src/components/swap-studio/stage-review.tsx
+++ b/src/components/swap-studio/stage-review.tsx
@@@ -8,8 -8,24 +8,24 @@@ import { Button } from "@/components/ui
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Panel } from "@/components/av/tool-shell";
import { Segmented } from "@/components/faceless/controls";
- import { characterLicenceLine } from "@/lib/catalog/character-swap";
- import { assemblyPieces, assemblyTakes, currentSegments, DECISION_LABELS, jobState, secondsLabel, SWAP_STUDIO, WORKERS_NOTE, type Decision, type SwapTake } from "@/lib/catalog/swap-studio";
+ import { Segmented as SizePicker } from "@/components/shorts/ui";
+ import { characterLicenceLine, h3Canvas } from "@/lib/catalog/character-swap";
-import { defaultSharpenTier, filmSize, gpuMinutes, joinNote, SHARPEN_COPY, sharpenOptions, type SharpenTier } from "@/lib/catalog/sharpen";
++import { defaultSharpenTier, filmSize, gpuMinutes, joinNote, SHARPEN_COPY, sharpenOffered, sharpenOptions, type SharpenTier } from "@/lib/catalog/sharpen";
+ import {
+ assemblyPieces,
+ assemblyTakes,
+ chosenTakes,
+ currentSegments,
+ DECISION_LABELS,
+ jobState,
+ secondsLabel,
+ SWAP_STUDIO,
+ usedFinish,
+ WORKERS_NOTE,
+ type Decision,
+ type GenSummary,
+ type SwapTake,
+ } from "@/lib/catalog/swap-studio";
import { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
import { downloadHref } from "@/lib/library";
import { cn } from "@/lib/utils";
@@@ -245,6 -386,8 +386,8 @@@ export function AssembleStage({ id, pro
</div>
</Panel>
- <FinishPanel id={id} project={project} clip={clip} gens={gens} estimate={estimate} />
++ {sharpenOffered(project.engine) && <FinishPanel id={id} project={project} clip={clip} gens={gens} estimate={estimate} />}
+
<Panel title="Where it runs">
<ul className="space-y-1.5 text-[12px] leading-snug text-pretty text-muted-foreground">
{project.engine === "open" && <li>{WORKERS_NOTE}</li>}
diff --cc src/lib/catalog/character-swap.ts
index 223eb124,7c5d8f91..b8de8470
--- a/src/lib/catalog/character-swap.ts
+++ b/src/lib/catalog/character-swap.ts
@@@ -10,6 -10,7 +10,8 @@@
* Pure module: limits, prompts, the H3 window plan, who to swap, the anchor's prompt and models, licences as data.
* The prompts follow Openjutsu's (MIT, Comfy Org 2026) and Akatz Labs' anchor brief (MIT, Akatz Labs 2026).
*/
++import { REGEN_OFFERED } from "./regenerate";
+ import { isSharpenTier, type SharpenTier } from "./sharpen";
import type { Engine, LoraRef, PixelPoint } from "./types";
export const CHARACTER_SWAP = {
@@@ -162,6 -170,17 +171,20 @@@ export function characterQuality(q: str
return q === "480p" ? "480p" : "768p";
}
+ /** The finishing size a quality asks for (1080p, 2K, 4K), or null for H3's own 480p / 768p. */
+ export function characterFinish(q: string | undefined): SharpenTier | null {
+ return isSharpenTier(q) ? q : null;
+ }
+
-/** The qualities each engine offers: your GPU regenerates 1080p, 2K and 4K; fal's H3 makes 2K and 4K (no 1080P). */
++/**
++ * The qualities each engine offers: your GPU regenerates 1080p, 2K and 4K with Open-H3 Regenerate (only while it is
++ * offered: REGEN_OFFERED); fal's H3 makes 2K and 4K (no 1080P).
++ */
+ export const CHARACTER_QUALITIES: Record<Engine, CharacterChoice[]> = {
- open: ["480p", "768p", "1080p", "2K", "4K"],
++ open: ["480p", "768p", ...(REGEN_OFFERED ? (["1080p", "2K", "4K"] as const) : [])],
+ cloud: ["480p", "768p", "2K", "4K"],
+ };
+
/** What the unpatched h3_character_swap pack's PrepareVideo takes: the strings "480" / "768" (the patched one: integers). */
export const packResolution = (q: string | undefined, patched = false): string | number => {
const v = characterQuality(q) === "480p" ? "480" : "768";
diff --cc src/lib/catalog/models.ts
index 2e8a7a7a,399e6e39..9f74060a
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@@ -7,7 -7,8 +7,8 @@@ import { loraEntry, loraRef } from "./l
import { ANGLES_LORA, MOSAIC_SCALE, MOSAIC_TARGET, SPEAK_GRAPH, SPEAK_LORA, SPEAK_PROMPT } from "./open-tools";
import { CINEMA_CROP, SOUL_ASPECTS, SOUL_TIERS } from "./soul";
import { RESTORE, offlineRestorePrompt } from "./restore";
-import { REGEN_COPY, REGEN_DEFAULT_TIER, REGEN_MODEL, REGEN_TIERS, REGEN_WORKFLOW } from "./regenerate";
+import { REGEN_COPY, REGEN_DEFAULT_TIER, REGEN_MODEL, REGEN_OFFERED, REGEN_TIERS, REGEN_WORKFLOW } from "./regenerate";
+ import { COMPOSITE_MODEL, COMPOSITE_WORKFLOW } from "./sharpen";
import { denoiseFor, EVOLUTION, EVOLUTION_DEFAULT_RESOLUTION, EVOLUTION_RESOLUTIONS, INTENSITIES, type Intensity } from "./evolution";
import { LAST_FRAME_CHAIN, type ModelDef, type ModelOptions, type ModelRoute, type Operation } from "./types";
@@@ -1148,6 -1148,19 +1149,19 @@@ const open: ModelDef[] =
options: { keepsNamed: true, matteOutputs: ["matte"] },
hidden: true,
}),
- // Character swap in 2K (n7-4): only the swapped character goes back over the footage, from the 768p swap and its
++ // Character swap in 2K: only the swapped character goes back over the footage, from the 768p swap and its
+ // regenerate, through the person's mask (src/lib/catalog/sharpen.ts). Run by Character Swap Studio and Genjutsu.
+ o({
+ id: COMPOSITE_MODEL,
+ name: "Character over the footage",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "video",
+ tagline: "Puts only the swapped character back over the original footage, with its own sound · CPU",
+ routes: [comfy("composite", COMPOSITE_WORKFLOW, "the swap, then its regenerate, each through the person's mask (grown, feathered); a few seconds a pass")],
+ options: {},
+ hidden: true,
+ }),
o({
id: "oss-qwen-relight",
name: "Qwen-Image-Edit Relight",
diff --cc src/lib/catalog/sharpen.ts
index 00000000,b734ac3c..f697c721
mode 000000,100644..100644
--- a/src/lib/catalog/sharpen.ts
+++ b/src/lib/catalog/sharpen.ts
@@@ -1,0 -1,437 +1,443 @@@
+ /**
+ * Character swap in 2K (docs/research/new-models-7.md §2.10 rows 4-5, §2.11): a swap comes back at H3's 768p, and
+ * "Sharpen" (Character Swap Studio's Finish) or a 1080p / 2K / 4K quality (Genjutsu's Character swap) makes it sharper
+ * without touching the background or the sound.
+ *
+ * Your GPU: the 768p swap is redrawn by Open-H3 Regenerate (video-regenerate-h3, start sigma 0.8: it stays closer to the
+ * draft), at most the size the footage is kept at, in 15 s windows; then video-composite-mask puts only the character
+ * back over the original footage (the swap first, then the regenerate, each through the person's mask, grown and
+ * feathered), with the footage's own sound, in short composite windows joined packet by packet.
+ * The cloud: nobody hosts a regenerate after the fact, so the swap is made again on fal's MiniMax H3 at 2K or 4K (the
+ * same hosted model asked for a size it offers, with the same words, LoRA, references and seed): a new version beside
+ * the first one, for approval. The whole frame is redrawn there.
+ *
+ * Pure: the tiers and what each engine makes of them, the cap at the size the film is joined at, the composite's
+ * geometry, the windows, the copy, and the steps on your GPU.
+ */
-import { REGEN_MODEL, REGEN_WINDOW_SECONDS, RERENDER } from "./regenerate";
++import { REGEN_MODEL, REGEN_OFFERED, REGEN_WINDOW_SECONDS, RERENDER } from "./regenerate";
+ import type { PlanStep } from "./shorts";
+ import type { ChainSlot, Engine, GenerationRequest } from "./types";
+
+ export const SHARPEN_TIERS = ["1080p", "2K", "4K"] as const;
+ export type SharpenTier = (typeof SHARPEN_TIERS)[number];
+ export const isSharpenTier = (v: unknown): v is SharpenTier => typeof v === "string" && (SHARPEN_TIERS as readonly string[]).includes(v);
+
+ /** Open-H3 Regenerate's tier for each (Upscale → Video names them by the shorter edge). */
+ export const SHARPEN_REGEN_TIER: Record<SharpenTier, "1080p" | "1440p" | "2160p"> = { "1080p": "1080p", "2K": "1440p", "4K": "2160p" };
+ /** The shorter edge each tier is made at. */
+ export const SHARPEN_SHORT_EDGE: Record<SharpenTier, number> = { "1080p": 1080, "2K": 1440, "4K": 2160 };
+ /** fal's MiniMax H3 resolutions: 480P and 768P are made natively, 2K and 4K from a 768P base (no 1080P). */
+ export const CLOUD_TIERS: readonly SharpenTier[] = ["2K", "4K"];
+
+ /** The regenerate's start noise for a swap (rdh: 0.8 "stays closer to the draft"; the release's 0.909 can drift a face). */
+ export const SHARPEN_SIGMA = 0.8;
+ /** The start noises an evaluation may try (Close 0.7 … the release's 0.909). */
+ export const SHARPEN_SIGMA_RANGE = { min: 0.5, max: 0.909 } as const;
+ const sigmaOf = (v: number | undefined) => (v !== undefined && v >= SHARPEN_SIGMA_RANGE.min && v <= SHARPEN_SIGMA_RANGE.max ? v : SHARPEN_SIGMA);
+
+ /** fal's price per second of the LoRA route (the Character swap's), by resolution. */
+ export const SWAP_PER_SECOND: Record<"480P" | "768P" | "2K" | "4K", number> = { "480P": 0.0625, "768P": 0.075, ...RERENDER["fuobe-character-swap"].perSecond };
+
++/** Whether an engine sharpens: the cloud always; your GPU only while Open-H3 Regenerate is offered (REGEN_OFFERED). */
++export const sharpenOffered = (engine: Engine): boolean => engine === "cloud" || REGEN_OFFERED;
++/** Why your GPU doesn't sharpen while Open-H3 Regenerate isn't offered. */
++export const OPEN_SHARPEN_OFF = "Sharpen isn't available on your GPU. Make the project in the cloud to sharpen its takes";
++
+ /** The mask composite (core nodes): the hidden model and its graph. */
+ export const COMPOSITE_MODEL = "oss-composite-mask";
+ export const COMPOSITE_WORKFLOW = "video-composite-mask";
+ /** One composite pass decodes four streams as float32 (about 25 MB a frame each at 1080p): 3 s keeps it near 12 GB. */
+ export const COMPOSITE_WINDOW_SECONDS = 3;
+ /** Both engines join the film at most this many pixels a side (the fit graph's limit; fal merge-videos' 2048). */
+ export const FILM_MAX = 2048;
+ const FPS = 24;
+
+ /** The pace the open engine's regenerate was measured at (about 3 minutes per 5 s at 2K on a 72 GB GPU). */
+ export const REGEN_MINUTES_PER_5S = 3;
+
+ export const SHARPEN_COPY = {
+ title: "Sharpen to 1080p / 2K / 4K",
+ /** Your GPU: only the character is redrawn, at the size picked. */
+ card: (tier: string) =>
+ `Redraws each chosen take at ${tier} with Open-H3 Regenerate, then puts only your character back over the original footage. The background and the sound stay as filmed. Faces can change slightly; compare before you keep it.`,
+ /** The cloud: a new render of the take (no regenerate is hosted). */
+ cardCloud: (tier: string) =>
+ `Makes each chosen take again at ${tier} on MiniMax H3, with the same words, references and seed, as a new version beside the first. The whole frame is redrawn, so compare before you keep it.`,
+ /** The model each engine sharpens with, for the takes line. */
+ model: (engine: Engine, tier: string) => (engine === "open" ? `Open-H3 Regenerate at ${tier}` : `MiniMax H3 at ${tier}`),
+ /** Genjutsu's Quality hint for a finishing size. */
+ hint: "2K and 4K redraw the 768p swap at the higher size.",
+ hintOpen: "1080p and 2K redraw the 768p swap at the higher size.",
+ /** Your GPU's limit, in Genjutsu's Quality hint. */
+ joinOpen: `Your GPU joins the clip at up to ${FILM_MAX} px a side, so 2K needs a clip larger than 1080p.`,
+ /** fal's 4K made in pieces: merge-videos joins them at up to 2048 px a side. */
+ joinCloud4k: `A part over 15 s is made in pieces, and the pieces are joined at up to ${FILM_MAX} px a side`,
+ /** The version beside a take, and its switch. */
+ version: (tier: string) => `${tier} version`,
+ pick: (tier: string) => `Use the ${tier} version`,
+ usingIt: (tier: string) => `The assembly uses the ${tier} version`,
+ noMask: "Sharpen puts your character back through the shot's mask: approve a mask in Who to swap and make the take with it",
+ small: "This clip is filmed below 1080p, so the 768p takes already match it",
+ noSize: "Couldn't read this clip's size, so it can't be sharpened: save it as an MP4 (H.264) and add it again",
+ none: "Choose a take for every swapped segment first",
+ } as const;
+
+ /**
+ * The film's frame: the size every piece is joined at, on even numbers. Your GPU: the clip's own, at most 2048 px a side
+ * (the studio's 24 fps copy, swap-studio.ts normalizedSize). The cloud: the same, and a small clip scaled up towards
+ * 512 px on its short side (fal merge-videos, swap-studio.ts cloudFilmSize).
+ */
+ export function filmSize(width?: number, height?: number, engine: Engine = "open"): { width: number; height: number } | null {
+ if (!width || !height) return null;
+ if (engine === "cloud") {
+ const scale = Math.min(FILM_MAX / Math.max(width, height), Math.max(1, 512 / Math.min(width, height)));
+ const even = (n: number) => Math.max(2, Math.round((n * scale) / 2) * 2);
+ return { width: even(width), height: even(height) };
+ }
+ const k = Math.min(1, FILM_MAX / width, FILM_MAX / height);
+ const even = (n: number) => Math.max(2, Math.floor((n * k) / 2) * 2);
+ return { width: even(width), height: even(height) };
+ }
+
+ export interface SharpenOption {
+ tier: SharpenTier;
+ available: boolean;
+ /** Why it can't be picked, in words. */
+ reason?: string;
+ }
+
+ const sizeWords = (f: { width: number; height: number }) => `${f.width}×${f.height}`;
+ const below = (tier: SharpenTier): SharpenTier | null => SHARPEN_TIERS[SHARPEN_TIERS.indexOf(tier) - 1] ?? null;
+
+ /**
+ * The part of the film your GPU redraws the character in: the centre the regenerate's 16:9 / 9:16 draft keeps of H3's
+ * canvas (compositeGeometry's region). Without the canvas, the film's own shape stands in for it (H3's canvas is the
+ * clip's shape on a 32 px grid).
+ */
+ export function redrawnRegion(film: { width: number; height: number }, canvas?: { width: number; height: number }): { width: number; height: number } {
+ const { region } = compositeGeometry(film, canvas ?? film);
+ return { width: region.width, height: region.height };
+ }
+
+ /** The longest shorter side that part can have: the draft's 1.75 shape inside a film of at most 2048 px a side. */
+ const REGION_MAX_SHORT = Math.floor((FILM_MAX * 768) / 1344);
+
+ /**
+ * The tiers your GPU can never make worth it, whatever the clip: the part redrawn is at most 2048 × 1170, so 4K adds
+ * nothing over 2K. With the reason, in words.
+ */
+ export const OPEN_TIER_OFF: Partial<Record<SharpenTier, string>> = Object.fromEntries(
+ SHARPEN_TIERS.filter((t) => below(t) && REGION_MAX_SHORT <= SHARPEN_SHORT_EDGE[below(t)!]).map((t) => [
+ t,
+ `Your GPU joins the clip at up to ${FILM_MAX} px a side, so ${t} adds nothing over ${below(t)}`,
+ ]),
+ );
+
+ /**
+ * What each tier does for a film of this size on an engine. The cloud redraws the whole frame and offers what fal makes
+ * (2K, 4K) where the join keeps it. Your GPU redraws only the character, inside the part of the frame the regenerate
+ * keeps (`canvas`: H3's canvas the swap was made at): 1080p is its base size, and a larger size is offered when that
+ * part is taller than the size below it (so it adds detail the smaller one can't).
+ */
+ export function sharpenOptions(engine: Engine, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenOption[] {
+ const short = film ? Math.min(film.width, film.height) : 0;
+ const region = film ? redrawnRegion(film, canvas) : null;
+ const regionShort = region ? Math.min(region.width, region.height) : 0;
+ return SHARPEN_TIERS.map((tier) => {
++ if (!sharpenOffered(engine)) return { tier, available: false, reason: OPEN_SHARPEN_OFF };
+ if (engine === "cloud" && !CLOUD_TIERS.includes(tier)) return { tier, available: false, reason: "The cloud makes 2K or 4K" };
+ if (engine === "open" && OPEN_TIER_OFF[tier]) return { tier, available: false, reason: OPEN_TIER_OFF[tier] };
+ if (!film) return { tier, available: engine === "cloud" && tier === "2K", ...(engine === "cloud" && tier === "2K" ? {} : { reason: SHARPEN_COPY.noSize }) };
+ if (short < SHARPEN_SHORT_EDGE["1080p"]) return { tier, available: false, reason: SHARPEN_COPY.small };
+ if (engine === "cloud") {
+ // The cloud's 2K is the smallest it makes: always worth it over 768p, joined at the film's size.
+ if (tier === "2K" || SHARPEN_SHORT_EDGE[tier] <= short) return { tier, available: true };
+ return { tier, available: false, reason: `Joined at ${sizeWords(film)}, so ${tier} adds nothing to the film` };
+ }
+ const lower = below(tier);
+ if (!lower || regionShort > SHARPEN_SHORT_EDGE[lower]) return { tier, available: true };
+ return {
+ tier,
+ available: false,
+ reason: `Your character is redrawn in a ${sizeWords(region!)} part of the frame (the clip is joined at up to ${FILM_MAX} px a side), so ${tier} adds nothing over ${lower}`,
+ };
+ });
+ }
+
+ /** The tier made when `asked` is picked: the largest available one not above it (null: none is). */
+ export function sharpenTierFor(engine: Engine, asked: SharpenTier, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenTier | null {
+ const ok = sharpenOptions(engine, film, canvas).filter((o) => o.available).map((o) => o.tier);
+ const at = SHARPEN_TIERS.indexOf(asked);
+ return [...ok].reverse().find((t) => SHARPEN_TIERS.indexOf(t) <= at) ?? null;
+ }
+
+ /**
+ * The tier picked first. The cloud: 2K where it is available, else the largest that is. Your GPU: the largest the
+ * redrawn part holds in full (a larger one costs GPU time for little more), else the smallest available.
+ */
+ export function defaultSharpenTier(engine: Engine, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenTier | null {
+ const ok = sharpenOptions(engine, film, canvas).filter((o) => o.available);
+ if (engine === "cloud" || !film) return ok.find((o) => o.tier === "2K")?.tier ?? ok.at(-1)?.tier ?? null;
+ const r = redrawnRegion(film, canvas);
+ const short = Math.min(r.width, r.height);
+ return [...ok].reverse().find((o) => SHARPEN_SHORT_EDGE[o.tier] <= short)?.tier ?? ok[0]?.tier ?? null;
+ }
+
+ /**
+ * Why your GPU sharpens a clip at a smaller size than asked: the clip's own size, the 2048 px join, and the part the
+ * character is redrawn in. Null when it makes what was asked.
+ */
+ export function openCapNote(source: { width?: number; height?: number }, asked: SharpenTier, canvas?: { width: number; height: number }): string | null {
+ const film = filmSize(source.width, source.height);
+ const made = sharpenTierFor("open", asked, film, canvas);
+ if (!film || !made || made === asked) return null;
+ const r = redrawnRegion(film, canvas);
+ const joined = film.width !== source.width || film.height !== source.height ? `, joined at ${sizeWords(film)} (up to ${FILM_MAX} px a side)` : ` (clips are joined at up to ${FILM_MAX} px a side)`;
+ return `Your clip is ${source.width}×${source.height}${joined}, and your character is redrawn in a ${sizeWords(r)} part of it, so it is sharpened at ${made}`;
+ }
+
+ /** The join's note: what a sharper take is joined at. */
+ export function joinNote(film: { width: number; height: number } | null): string | null {
+ return film ? `The clip is joined at ${sizeWords(film)} (up to ${FILM_MAX} px a side). Each sharper take keeps its own size in Takes & review` : null;
+ }
+
+ /** The cloud's price of one take made again at a size: whole seconds, 5–15 s a call (fal's H3). */
+ export function cloudSharpenUsd(tier: SharpenTier, seconds: number): number | null {
+ if (!CLOUD_TIERS.includes(tier)) return null;
+ const secs = Math.min(15, Math.max(5, Math.ceil(seconds - 1e-6)));
+ return Math.round(SWAP_PER_SECOND[tier as "2K" | "4K"] * secs * 100) / 100;
+ }
+
+ /** Your GPU's time for seconds of swaps, in words ("about 3 min" per 5 s at 2K on a 72 GB GPU). */
+ export function gpuMinutes(seconds: number): string {
+ const m = Math.max(1, Math.round((seconds / 5) * REGEN_MINUTES_PER_5S));
+ return `about ${m} min on a 72 GB GPU`;
+ }
+
+ // ---------------------------------------------------------------------------
+ // The composite's geometry
+
+ export interface Box {
+ width: number;
+ height: number;
+ x: number;
+ y: number;
+ }
+
+ /** The centre part of a frame with a given shape (what a cover-and-crop to that shape keeps), on even numbers. */
+ function centre(frame: { width: number; height: number }, aspect: number): { width: number; height: number } {
+ const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);
+ return aspect < frame.width / frame.height ? { width: Math.min(frame.width, even(frame.height * aspect)), height: frame.height } : { width: frame.width, height: Math.min(frame.height, even(frame.width / aspect)) };
+ }
+
+ /** The draft shape Open-H3 Regenerate keeps of an H3 clip: 1344 × 768 (turned for a tall one). */
+ const DRAFT = { width: 1344, height: 768 };
+
+ /**
+ * The rows (columns, for a tall clip) each tier keeps of the grid it is drawn on: the draft is stretched to 1920 × 1088,
+ * 2560 × 1440 or 3840 × 2176, and the regenerate's finish keeps the centre 1080 of 1088 (2160 of 2176) rows.
+ */
+ const REGEN_TRIM: Record<SharpenTier, { kept: number; drawn: number }> = { "1080p": { kept: 1080, drawn: 1088 }, "2K": { kept: 1440, drawn: 1440 }, "4K": { kept: 2160, drawn: 2176 } };
+
+ /**
+ * Where each layer goes in the film: the swap covers the part of the footage its canvas was cut from (H3 cover-crops the
+ * clip to its canvas), the regenerate the centre of that its 16:9 or 9:16 draft kept (`region`: it stretches the draft
+ * to its grid and keeps the centre rows of it, so at 1080p and 4K it covers the centre 1080 / 1088 of the region's
+ * height, or width for a tall clip: `regen`, at `trim` inside the region). All centred.
+ */
+ export function compositeGeometry(
+ film: { width: number; height: number },
+ canvas: { width: number; height: number },
+ tier: SharpenTier = "2K",
+ ): { take: Box; region: Box; regen: Box; trim: { x: number; y: number } } {
+ const t = centre(film, canvas.width / canvas.height);
+ const tall = canvas.height > canvas.width;
+ const draft = tall ? DRAFT.height / DRAFT.width : DRAFT.width / DRAFT.height;
+ const r = centre(t, draft);
+ const tx = Math.floor((film.width - t.width) / 2);
+ const ty = Math.floor((film.height - t.height) / 2);
+ const region = { ...r, x: tx + Math.floor((t.width - r.width) / 2), y: ty + Math.floor((t.height - r.height) / 2) };
+ const k = REGEN_TRIM[tier].kept / REGEN_TRIM[tier].drawn;
+ const width = tall ? Math.round(r.width * k) : r.width;
+ const height = tall ? r.height : Math.round(r.height * k);
+ const trim = { x: Math.floor((r.width - width) / 2), y: Math.floor((r.height - height) / 2) };
+ return { take: { ...t, x: tx, y: ty }, region, regen: { width, height, x: region.x + trim.x, y: region.y + trim.y }, trim };
+ }
+
+ /** The mask's grown and feathered edge, in the region's pixels (about 0.8 % and 1.2 % of its shorter side). */
+ export function maskEdge(region: { width: number; height: number }): { grow: number; feather: number } {
+ const short = Math.min(region.width, region.height);
+ return { grow: Math.max(2, Math.round(short * 0.008)), feather: Math.max(4, Math.round(short * 0.012)) };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Windows
+
+ /** Frames split into equal windows of at most `max` frames (no sliver at the end). */
+ export function frameWindows(frames: number, max: number): { from: number; frames: number }[] {
+ const total = Math.max(1, Math.round(frames));
+ const n = Math.ceil(total / max);
+ const out: { from: number; frames: number }[] = [];
+ let from = 0;
+ for (let i = 0; i < n; i++) {
+ const to = Math.round(((i + 1) * total) / n);
+ out.push({ from, frames: to - from });
+ from = to;
+ }
+ return out;
+ }
+
+ const sec = (frames: number) => Math.round((frames / FPS) * 1e6) / 1e6;
+
+ // ---------------------------------------------------------------------------
+ // The steps on your GPU
+
+ /** A file the step reads: a stored file, or the output of an earlier step. */
+ export type StepInput = { url: string } | { after: string };
+
+ export interface SharpenStepsInput {
+ /** Prefix of the step keys (unique within the pipeline). */
+ key: string;
+ /** Words for step labels ("Shot 1 · segment 2 · take 1"). */
+ label: string;
+ helper: Pick<GenerationRequest, "feature" | "batchTitle">;
+ /** The finished step's identity (a result of its own): feature, title. */
+ result: Pick<GenerationRequest, "feature" | "batchTitle" | "title">;
+ /** The tier the regenerate makes (already capped: sharpenTierFor). */
+ tier: SharpenTier;
+ /** What the regenerate redraws from. */
+ prompt: string;
+ seed?: number;
+ /** The regenerate's start noise (SHARPEN_SIGMA unless an evaluation asks for another in SHARPEN_SIGMA_RANGE). */
+ sigma?: number;
+ /** The swap's length in frames (24 fps). */
+ frames: number;
+ /** The 768p swap. */
+ take: StepInput;
+ /** The footage at 24 fps and the film's size, and where the swap starts in it (seconds). */
+ source: StepInput & { start: number };
+ /** The person's mask (H3's canvas, 24 fps), and where the swap starts in it (seconds). */
+ mask: StepInput & { start: number };
+ film: { width: number; height: number };
+ /** H3's canvas the swap and the mask were made at. */
+ canvas: { width: number; height: number };
+ }
+
+ /** The words a regenerate redraws a swap from: the take's own, without H3's reference tags. */
+ export function sharpenPrompt(takePrompt: string, description?: string): string {
+ const words = takePrompt
+ .replace(/<Video \d+>/g, "the clip")
+ .replace(/<Picture \d+>/g, "the reference")
+ .replace(/\s+/g, " ")
+ .trim();
+ const who = (description ?? "").replace(/\s+/g, " ").trim().replace(/[.\s]+$/, "");
+ return [who ? `The character: ${who}.` : "", words].filter(Boolean).join(" ").slice(0, 1500);
+ }
+
+ const fill = (input: StepInput, slot: ChainSlot): { after?: string; chain?: ChainSlot; url?: string } => ("after" in input ? { after: input.after, chain: slot } : { url: input.url });
+
+ /**
+ * One swap sharpened on your GPU: Open-H3 Regenerate in windows of up to 15 s, each composited over the footage in
+ * windows of up to 3 s (the swap, then the regenerate, through the mask), joined packet by packet. The last step (the
+ * join, or the only composite) is the result.
+ */
+ export function sharpenSteps(s: SharpenStepsInput): { steps: PlanStep[]; final: string } {
+ const steps: PlanStep[] = [];
+ const geo = compositeGeometry(s.film, s.canvas, s.tier);
+ const edge = maskEdge(geo.region);
+ const regen = frameWindows(s.frames, REGEN_WINDOW_SECONDS * FPS);
+ const parts: string[] = [];
+ const total = regen.reduce((n, w) => n + frameWindows(w.frames, COMPOSITE_WINDOW_SECONDS * FPS).length, 0);
+ const take = fill(s.take, { slot: "video" });
+ regen.forEach((w, wi) => {
+ const rk = `${s.key}regen${wi}`;
+ const many = regen.length > 1;
+ steps.push({
+ key: rk,
+ request: {
+ ...s.helper,
+ modelId: REGEN_MODEL,
+ op: "upscale-video",
+ prompt: s.prompt,
+ ...(take.url ? { inputs: { video: take.url } } : {}),
+ params: {
+ resolution: SHARPEN_REGEN_TIER[s.tier],
+ ...(many ? { startTime: sec(w.from), endTime: sec(w.from + w.frames) } : {}),
+ sourceDuration: sec(w.frames),
+ ...(s.seed !== undefined ? { seed: s.seed } : {}),
+ // An H3 draft (the 768p preset), and the start noise that keeps the swapped identity closer.
+ extra: { startSigma: sigmaOf(s.sigma), draftFrom: "h3" },
+ },
+ step: { label: `${s.label} · redraw at ${s.tier}${many ? ` (${wi + 1} of ${regen.length})` : ""}`, index: wi, of: regen.length },
+ },
+ ...(take.after ? { after: [take.after], chain: [take.chain!] } : {}),
+ });
+ for (const c of frameWindows(w.frames, COMPOSITE_WINDOW_SECONDS * FPS)) {
+ const ck = `${s.key}comp${parts.length}`;
+ const from = w.from + c.from;
+ const after: string[] = [rk];
+ const chain: ChainSlot[] = [{ slot: "videos", at: 1 }];
+ // The footage is the first clip, the regenerate the second, the swap the third; the mask is the mask.
+ const src = fill(s.source, { slot: "videos", at: 0 });
+ const tk = fill(s.take, { slot: "videos", at: 2 });
+ const mk = fill(s.mask, { slot: "mask" });
+ for (const x of [src, tk, mk]) {
+ if (x.after) {
+ after.push(x.after);
+ chain.push(x.chain!);
+ }
+ }
+ const own = [src.url, tk.url].filter((u): u is string => !!u);
+ steps.push({
+ key: ck,
+ request: {
+ ...s.helper,
+ modelId: COMPOSITE_MODEL,
+ op: "composite",
+ inputs: { ...(own.length ? { videos: own } : {}), ...(mk.url ? { mask: mk.url } : {}) },
+ params: {
+ startTime: Math.round((s.source.start + sec(from)) * 1e6) / 1e6,
+ endTime: Math.round((s.source.start + sec(from + c.frames)) * 1e6) / 1e6,
+ extra: {
+ windowStart: sec(c.from),
+ takeStart: sec(from),
+ maskStart: Math.round((s.mask.start + sec(from)) * 1e6) / 1e6,
+ canvasWidth: geo.take.width,
+ canvasHeight: geo.take.height,
+ takeX: geo.take.x,
+ takeY: geo.take.y,
+ // The mask is cut to the region the draft kept, then to the rows the regenerate kept of it.
+ regionWidth: geo.region.width,
+ regionHeight: geo.region.height,
+ regenWidth: geo.regen.width,
+ regenHeight: geo.regen.height,
+ regenX: geo.regen.x,
+ regenY: geo.regen.y,
+ trimX: geo.trim.x,
+ trimY: geo.trim.y,
+ maskGrow: edge.grow,
+ feather: edge.feather,
+ },
+ },
+ step: { label: `${s.label} · your character over the footage${total > 1 ? ` (${parts.length + 1} of ${total})` : ""}`, index: parts.length, of: total },
+ },
+ after,
+ chain,
+ });
+ parts.push(ck);
+ }
+ });
+ if (parts.length === 1) {
+ const last = steps.find((x) => x.key === parts[0])!;
+ last.request = { ...last.request, ...s.result };
+ return { steps, final: parts[0] };
+ }
+ const jk = `${s.key}join`;
+ steps.push({
+ key: jk,
+ request: { ...s.helper, ...s.result, modelId: "oss-join-encoded", op: "concat", step: { label: `${s.label} · join`, index: total, of: total } },
+ after: parts,
+ chain: parts.map(() => ({ slot: "videos" as const })),
+ });
+ return { steps, final: jk };
+ }
diff --cc src/server/genjutsu.ts
index 5653d00a,01860897..21fe38d5
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@@ -294,6 -299,19 +299,19 @@@ function notesFor(body: GenjutsuBody, m
notes.push(`${am.label} first puts your character into the part's first frame${m.engine === "cloud" && n > 1 ? " (one per piece)" : ""}; if that fails the swap runs without it`);
} else if (!m.h3.anchor) notes.push(`${name} runs without an anchor frame`);
if (m.engine === "cloud") notes.push("On fal, H3 has no mask: who to swap is said in words, and the whole frame is regenerated around them");
+ // 1080p / 2K / 4K (sharpen.ts): what each engine does with the 768p swap.
+ const finish = characterFinish(qualityFor(m, body.quality ?? CHARACTER_SWAP.defaultQuality));
+ if (finish && m.engine === "cloud") {
- notes.push(`fal's H3 makes ${finish} from a 768P base: the whole frame is drawn at the higher size`);
++ notes.push(`${finish} is made from the 768p swap: the whole frame is redrawn at the higher size`);
+ // Pieces are joined by fal's merge-videos, at up to 2048 px a side: only a single piece keeps its 4K.
+ if (finish === "4K" && n > 1) notes.push(SHARPEN_COPY.joinCloud4k);
+ }
+ if (finish && m.engine === "open") {
+ notes.push("The 768p swap is redrawn by Open-H3 Regenerate and only your character is put back over your clip: the background and the sound stay as filmed. Faces can change slightly");
+ const canvas = source.width && source.height ? h3Canvas(source.width, source.height, CHARACTER_SWAP.defaultQuality) : undefined;
+ const capped = openCapNote(source, finish, canvas);
+ if (capped) notes.push(capped);
+ }
if (m.engine === "open" && c.who === "index" && !body.points?.length) notes.push("Person numbers follow SAM 3.1's detections, the one it is surest of first — not left to right");
if (m.engine === "open" && !m.h3.maskSwitch && c.useMask === false) notes.push(`${name} always regenerates only the person: its graph has no switch for the whole frame`);
const warn = cutWarning(cutsInPart(body.cuts, range));
diff --cc src/server/gpu/tools.ts
index b7c79ed0,b4fb10cd..ea4d38ea
--- a/src/server/gpu/tools.ts
+++ b/src/server/gpu/tools.ts
@@@ -10,7 -10,9 +10,9 @@@ import { dualEngine, onEngine, runsOn
import { FRAMES_MODELS } from "@/lib/catalog/keyframes";
import { REMOVE_TOOLS } from "@/lib/catalog/remove-object";
import { RESTORE, RESTORE_OPEN_JOIN } from "@/lib/catalog/restore";
-import { REGEN_DEFAULT_TIER, REGEN_JOIN, REGEN_MODEL, regenerateGraphLoras } from "@/lib/catalog/regenerate";
+import { REGEN_DEFAULT_TIER, REGEN_JOIN, REGEN_MODEL, REGEN_OFFERED, regenerateGraphLoras } from "@/lib/catalog/regenerate";
+ import { COMPOSITE_MODEL } from "@/lib/catalog/sharpen";
+ import { ORIGINALS, SHARPEN_TOOLS } from "@/lib/catalog/genjutsu";
import { libraryEntry, loraEntry, loraRef, needsToken } from "@/lib/catalog/loras";
import { ANGLES_2511_LORA } from "@/lib/catalog/open-tools";
import { presetRoutes, recipeRoute } from "@/lib/catalog/preset-recipes";
@@@ -243,21 -245,34 +245,43 @@@ export const STUDIO_ROWS: StudioRowDef[
{ href: "/audio/music", label: "Music", group: "Audio", config: S.MUSIC_STUDIO },
{ href: "/audio/video", label: "Sound for video", group: "Audio", config: S.FOLEY_STUDIO },
{ href: "/upscale/video", label: "Upscale video", group: "Video tools", config: S.VIDEO_UPSCALE_STUDIO },
- // n7-3: Upscale → Video's Regenerate · creative (Open-H3 Regenerate with its refiner LoRA); a clip over 15 s is redrawn in
- // parts joined packet by packet.
- {
- href: `/upscale/video?model=${REGEN_MODEL}&resolution=${REGEN_DEFAULT_TIER}`,
- label: "Regenerate in 2K",
- group: "Video tools",
- steps: [
- { modelId: REGEN_MODEL, op: "upscale-video" },
- { modelId: REGEN_JOIN, op: "concat" },
- ],
- },
- // n7-4: the Character swap at 1080p / 2K / 4K (Genjutsu, and Sharpen in Character Swap Studio's Finish): the 768p swap,
- // the person's mask (SAM 3.1 on H3 Relay's graph), the part at 24 fps, the swap regenerated, only the character
- // composited over the footage, the windows joined and the part's sound put back.
- {
- href: "/genjutsu?mode=character",
- label: "Character swap in 2K",
- group: "Video tools",
- steps: [
- { modelId: ORIGINALS.character, op: "video-swap" },
- { modelId: SHARPEN_TOOLS.mask, op: "bg-remove-video" },
- { modelId: SHARPEN_TOOLS.fit, op: "trim" },
- { modelId: REGEN_MODEL, op: "upscale-video" },
- { modelId: COMPOSITE_MODEL, op: "composite" },
- { modelId: REGEN_JOIN, op: "concat" },
- { modelId: SHARPEN_TOOLS.mux, op: "mux" },
- ],
- },
+ // Upscale → Video's Regenerate · creative (Open-H3 Regenerate with its refiner LoRA); a clip over 15 s is redrawn in
+ // parts joined packet by packet. Listed only while it is offered (REGEN_OFFERED).
+ ...(REGEN_OFFERED
+ ? [
+ {
+ href: `/upscale/video?model=${REGEN_MODEL}&resolution=${REGEN_DEFAULT_TIER}`,
+ label: "Regenerate in 2K",
+ group: "Video tools",
+ steps: [
+ { modelId: REGEN_MODEL, op: "upscale-video" as const },
+ { modelId: REGEN_JOIN, op: "concat" as const },
+ ],
+ } satisfies StudioRowDef,
+ ]
+ : []),
++ // The Character swap at 1080p / 2K / 4K (Genjutsu, and Sharpen in Character Swap Studio's Finish): the 768p swap, the
++ // person's mask (SAM 3.1 on H3 Relay's graph), the part at 24 fps, the swap regenerated, only the character composited
++ // over the footage, the windows joined and the part's sound put back. It regenerates with Open-H3 Regenerate, so it is
++ // listed only while that is offered (REGEN_OFFERED).
++ ...(REGEN_OFFERED
++ ? [
++ {
++ href: "/genjutsu?mode=character",
++ label: "Character swap in 2K",
++ group: "Video tools",
++ steps: [
++ { modelId: ORIGINALS.character, op: "video-swap" as const },
++ { modelId: SHARPEN_TOOLS.mask, op: "bg-remove-video" as const },
++ { modelId: SHARPEN_TOOLS.fit, op: "trim" as const },
++ { modelId: REGEN_MODEL, op: "upscale-video" as const },
++ { modelId: COMPOSITE_MODEL, op: "composite" as const },
++ { modelId: REGEN_JOIN, op: "concat" as const },
++ { modelId: SHARPEN_TOOLS.mux, op: "mux" as const },
++ ],
++ } satisfies StudioRowDef,
++ ]
++ : []),
{ href: "/upscale/fps", label: "FPS boost", group: "Video tools", config: S.FPS_BOOST_STUDIO },
{ href: "/upscale/hdr", label: "SDR to HDR", group: "Video tools", config: S.SDR_TO_HDR_STUDIO },
{ href: "/upscale/export", label: "Export", group: "Video tools", config: S.VIDEO_EXPORT_STUDIO },
diff --cc tests/character-swap-2k.test.ts
index 00000000,74936164..75463b8b
mode 000000,100644..100644
--- a/tests/character-swap-2k.test.ts
+++ b/tests/character-swap-2k.test.ts
@@@ -1,0 -1,533 +1,536 @@@
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
-import { afterAll, describe, expect, it } from "vitest";
++import { afterAll, describe, expect, it, vi } from "vitest";
+ import type { PlanStep } from "@/lib/catalog/shorts";
+ import type { GenerationRequest, GenInput } from "@/lib/catalog/types";
+
-// Character swap in 2K (package n7-4-character-swap-2k): Genjutsu's 1080p / 2K / 4K and Character Swap Studio's Sharpen,
++// Character swap in 2K: Genjutsu's 1080p / 2K / 4K and Character Swap Studio's Sharpen,
+ // on both engines. Your GPU: the 768p swap regenerated (sigma 0.8, never above the footage's size), then only the
+ // character composited over the footage (video-composite-mask); the cloud: fal's H3 at 2K / 4K, a new version.
++// Your GPU's sizes regenerate with Open-H3 Regenerate, which is switched off for now (REGEN_OFFERED); these tests check
++// them as they run once it is on. tests/regenerate-offered.test.ts checks that nothing offers them while it is off.
++vi.mock("@/lib/catalog/regenerate", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/catalog/regenerate")>()), REGEN_OFFERED: true }));
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-2k-"));
+ process.env.FUOBE_DATA_DIR = dir;
+ process.env.COMFYUI_URL = "http://127.0.0.1:9";
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ const S = await import("@/lib/catalog/sharpen");
+ const C = await import("@/lib/catalog/character-swap");
+ const G = await import("@/lib/catalog/genjutsu");
+ const { DEFAULT_SETTINGS, newShot, assemblyTakes, chosenTakes, usedFinish, normalizedSize, cloudFilmSize } = await import("@/lib/catalog/swap-studio");
+ const { applyEdit, shotBusy } = await import("@/lib/catalog/swap-studio-edit");
+ type SwapClip = import("@/lib/catalog/swap-studio").SwapClip;
+ type SwapProject = import("@/lib/catalog/swap-studio").SwapProject;
+ type SwapTake = import("@/lib/catalog/swap-studio").SwapTake;
+ const { planTakeFinish, planAssembly } = await import("@/lib/catalog/swap-studio-plan");
+ const { getModel } = await import("@/lib/catalog");
+ const { estimateCost } = await import("@/lib/catalog/plan");
+ const { onEngine } = await import("@/lib/catalog/engines");
+ const { buildPayload } = await import("@/lib/catalog/payload");
+ const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");
+
+ const ROOT = path.resolve(__dirname, "..");
+ const hd = { url: "/api/files/uploads/x/clip.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true };
+ const ref = "/api/files/uploads/x/hero.png";
+ const maker = (id: string, engine: "open" | "cloud") => G.getMaker(id, engine)!;
+ const character = (engine: "open" | "cloud", quality: string, o: Partial<Parameters<typeof G.planGenjutsu>[0]> = {}) =>
+ G.planGenjutsu({ engine, mode: "character", maker: maker(G.ORIGINALS.character, engine), title: "Swap", source: hd, range: { start: 2, end: 12 }, quality, references: [ref], seed: 42, ...o });
+ const keys = (p: { steps: { key: string }[] }) => p.steps.map((s) => s.key);
+ const step = (p: { steps: PlanStep[] }, key: string) => {
+ const s = p.steps.find((x) => x.key === key);
+ if (!s) throw new Error(`no step ${key}: ${keys(p).join(", ")}`);
+ return s;
+ };
+
+ describe("qualities", () => {
+ it("480p and 768p stay H3's own; 1080p, 2K and 4K are finishing sizes of the 768p swap", () => {
+ expect(C.CHARACTER_SWAP.qualities).toEqual(["480p", "768p"]);
+ expect(C.characterQuality("480p")).toBe("480p");
+ for (const q of ["768p", "1080p", "2K", "4K", undefined]) expect(C.characterQuality(q)).toBe("768p");
+ expect(["480p", "768p", "720p", undefined].map(C.characterFinish)).toEqual([null, null, null, null]);
+ expect(["1080p", "2K", "4K"].map(C.characterFinish)).toEqual(["1080p", "2K", "4K"]);
+ // fal has no 1080P: the cloud offers 2K and 4K; your GPU all three.
+ expect(C.CHARACTER_QUALITIES).toEqual({ open: ["480p", "768p", "1080p", "2K", "4K"], cloud: ["480p", "768p", "2K", "4K"] });
+ expect(maker(G.ORIGINALS.character, "cloud").qualities).toEqual(C.CHARACTER_QUALITIES.cloud);
+ expect(maker(G.ORIGINALS.character, "open").qualities).toEqual(C.CHARACTER_QUALITIES.open);
+ expect(maker("oss-h3-character-swap-relay", "open").qualities).toEqual(C.CHARACTER_QUALITIES.open);
+ // H3 Max Recast keeps its own 768P / 1080P.
+ expect(maker("h3-max-recast", "cloud").qualities).toEqual(["768p", "1080p"]);
+ });
+
+ it("falResolution for every quality", () => {
+ expect(Object.fromEntries(["480p", "720p", "768p", "1080p", "2K", "4K", undefined].map((q) => [String(q), C.falResolution(q)]))).toEqual({
+ "480p": "480P",
+ "720p": "768P",
+ "768p": "768P",
+ "1080p": "768P",
+ "2K": "2K",
+ "4K": "4K",
+ undefined: "768P",
+ });
+ });
+
+ it("Genjutsu asks each maker for what it offers, and the setup code keeps 2K and 4K", () => {
+ expect(G.qualityFor(maker(G.ORIGINALS.character, "cloud"), "2K")).toBe("2K");
+ expect(G.qualityFor(maker(G.ORIGINALS.character, "cloud"), "1080p")).toBe("768p");
+ expect(G.qualityFor(maker(G.ORIGINALS.character, "open"), "1080p")).toBe("1080p");
+ expect(G.resolutionWords(maker(G.ORIGINALS.character, "cloud"), "1080p")).toBe("renders up to 768p");
+ expect(G.decodeSetup(G.encodeSetup({ mode: "character", quality: "4K" }))?.quality).toBe("4K");
+ });
+ });
+
+ describe("prices", () => {
+ it("fal's H3 LoRA route per second: 480P $0.0625, 768P $0.075, 2K $0.1625, 4K $0.20; 5 s at 2K = $0.81, 15 s = $2.44", () => {
+ expect(S.SWAP_PER_SECOND).toEqual({ "480P": 0.0625, "768P": 0.075, "2K": 0.1625, "4K": 0.2 });
+ expect(S.cloudSharpenUsd("2K", 5)).toBe(0.81);
+ expect(S.cloudSharpenUsd("2K", 15)).toBe(2.44);
+ expect(S.cloudSharpenUsd("4K", 5)).toBe(1);
+ // Whole seconds, at least 5 a call.
+ expect(S.cloudSharpenUsd("2K", 2)).toBe(0.81);
+ expect(S.cloudSharpenUsd("1080p", 5)).toBeNull();
+ // The catalog prices the plan's step the same way.
+ const m = getModel("fuobe-character-swap")!;
+ const cloud = onEngine(m, "cloud");
+ expect(estimateCost(cloud, { resolution: "2K", duration: 5 }, 1, "video-swap")).toBeCloseTo(0.8125, 2);
+ expect(estimateCost(cloud, { resolution: "4K", duration: 15 }, 1, "video-swap")).toBeCloseTo(3, 2);
+ expect(estimateCost(cloud, { resolution: "768p", duration: 5 }, 1, "video-swap")).toBeCloseTo(0.375, 2);
+ });
+
+ it("the cloud's Quality hint carries the price; your GPU's the time", async () => {
+ const { qualityHint, qualityShort } = await import("@/components/genjutsu/character-panel");
+ expect(qualityShort("cloud", "2K")).toBe("$0.81 for 5 s");
+ expect(qualityShort("open", "4K")).toBe("Free · your GPU");
+ expect(qualityShort("cloud", "768p")).toBe("H3's native top");
+ expect(qualityHint("cloud", "2K")).toBe("2K and 4K redraw the 768p swap at the higher size. $0.81 for 5 s, $2.44 for 15 s.");
+ expect(qualityHint("cloud", "4K")).toBe("2K and 4K redraw the 768p swap at the higher size. $1.00 for 5 s, $3.00 for 15 s.");
+ expect(qualityHint("open", "2K")).toBe(
+ "1080p and 2K redraw the 768p swap at the higher size. Free on your GPU, about 3 min more per 5 s on a 72 GB GPU. Your GPU joins the clip at up to 2048 px a side, so 2K needs a clip larger than 1080p.",
+ );
+ expect(qualityHint("open", "480p")).toBe("Faster and cheaper");
+ });
+
+ it("your GPU's 4K is turned off with the reason (it joins at up to 2048 px a side); the cloud's isn't", async () => {
+ const { qualityOff } = await import("@/components/genjutsu/character-panel");
+ expect(S.OPEN_TIER_OFF).toEqual({ "4K": "Your GPU joins the clip at up to 2048 px a side, so 4K adds nothing over 2K" });
+ expect(qualityOff("open", "4K")).toBe(S.OPEN_TIER_OFF["4K"]);
+ expect(["480p", "768p", "1080p", "2K"].map((q) => qualityOff("open", q as never))).toEqual([null, null, null, null]);
+ expect(qualityOff("cloud", "4K")).toBeNull();
+ // The picker says why as text the page shows (and links it to the group), not only in a tooltip.
+ const panel = fs.readFileSync(path.join(ROOT, "src/components/genjutsu/character-panel.tsx"), "utf8");
+ expect(panel).toMatch(/describedBy=\{offReasons\.length \? "character-quality-off"/);
+ expect(panel).toMatch(/id="character-quality-off"/);
+ });
+ });
+
+ describe("what each engine makes of a size", () => {
+ it("your GPU: tiers gated and defaulted by the part the character is redrawn in (joined at most 2048 px a side)", () => {
+ const film = S.filmSize(1920, 1080)!;
+ expect(film).toEqual({ width: 1920, height: 1080 });
+ const canvas = C.h3Canvas(1920, 1080, "768p");
+ expect(S.redrawnRegion(film, canvas)).toEqual({ width: 1842, height: 1052 });
+ expect(S.sharpenOptions("open", film, canvas).map((o) => [o.tier, o.available])).toEqual([
+ ["1080p", true],
+ ["2K", false],
+ ["4K", false],
+ ]);
+ expect(S.sharpenOptions("open", film, canvas)[1].reason).toBe("Your character is redrawn in a 1842×1052 part of the frame (the clip is joined at up to 2048 px a side), so 2K adds nothing over 1080p");
+ expect(S.sharpenOptions("open", film, canvas)[2].reason).toBe(S.OPEN_TIER_OFF["4K"]);
+ expect(S.sharpenTierFor("open", "4K", film, canvas)).toBe("1080p");
+ expect(S.defaultSharpenTier("open", film, canvas)).toBe("1080p");
+ // A 1440 square: the regenerate's 16:9 draft keeps a 1440 × 822 band of it, so 2K adds nothing there.
+ const sq1440 = S.filmSize(1440, 1440)!;
+ expect(S.redrawnRegion(sq1440, C.h3Canvas(1440, 1440, "768p"))).toEqual({ width: 1440, height: 822 });
+ expect(S.sharpenTierFor("open", "2K", sq1440, C.h3Canvas(1440, 1440, "768p"))).toBe("1080p");
+ // 4:3 at 2048 × 1536 (2048 × 1170 redrawn) and a 4K square (kept at 2048 × 2048): 2K adds a little and can be
+ // picked, but 1080p is the default, since neither part is 1440 tall.
+ for (const [w, h] of [
+ [2048, 1536],
+ [4096, 4096],
+ ]) {
+ const f = S.filmSize(w, h)!;
+ const c = C.h3Canvas(w, h, "768p");
+ expect(Math.min(S.redrawnRegion(f, c).width, S.redrawnRegion(f, c).height)).toBe(1170);
+ expect(S.sharpenTierFor("open", "4K", f, c)).toBe("2K");
+ expect(S.defaultSharpenTier("open", f, c)).toBe("1080p");
+ }
+ // Without the canvas, the film's own shape stands in for it.
+ expect(S.redrawnRegion(film)).toEqual({ width: 1890, height: 1080 });
+ // Below 1080p the 768p takes already match it.
+ expect(S.sharpenTierFor("open", "2K", S.filmSize(1280, 720))).toBeNull();
+ expect(S.sharpenOptions("open", S.filmSize(1280, 720))[0].reason).toBe(S.SHARPEN_COPY.small);
+ });
+
+ it("Genjutsu's note names the clip's own size, the 2048 px join and the part redrawn when a size is capped", () => {
+ expect(S.openCapNote({ width: 3840, height: 2160 }, "4K", C.h3Canvas(3840, 2160, "768p"))).toBe(
+ "Your clip is 3840×2160, joined at 2048×1152 (up to 2048 px a side), and your character is redrawn in a 1964×1122 part of it, so it is sharpened at 2K",
+ );
+ expect(S.openCapNote({ width: 1920, height: 1080 }, "2K", C.h3Canvas(1920, 1080, "768p"))).toBe(
+ "Your clip is 1920×1080 (clips are joined at up to 2048 px a side), and your character is redrawn in a 1842×1052 part of it, so it is sharpened at 1080p",
+ );
+ expect(S.openCapNote({ width: 1920, height: 1080 }, "1080p", C.h3Canvas(1920, 1080, "768p"))).toBeNull();
+ });
+
+ it("the studio's film sizes are sharpen.ts's (one copy of the rule)", () => {
+ for (const [w, h] of [
+ [3840, 2160],
+ [72, 128],
+ [1080, 1920],
+ ]) {
+ expect(normalizedSize(w, h)).toEqual(S.filmSize(w, h, "open"));
+ expect(cloudFilmSize(w, h)).toEqual(S.filmSize(w, h, "cloud"));
+ }
+ expect(normalizedSize(3840, 2160)).toEqual({ width: 2048, height: 1152 });
+ expect(cloudFilmSize(72, 128)).toEqual({ width: 512, height: 910 });
+ });
+
+ it("the cloud: 2K and 4K only (no 1080P on fal); 4K adds nothing to a film joined at 2048 px", () => {
+ const film = S.filmSize(3840, 2160, "cloud")!;
+ expect(film).toEqual({ width: 2048, height: 1152 });
+ const o = S.sharpenOptions("cloud", film);
+ expect(o.map((x) => [x.tier, x.available])).toEqual([
+ ["1080p", false],
+ ["2K", true],
+ ["4K", false],
+ ]);
+ expect(o[0].reason).toBe("The cloud makes 2K or 4K");
+ expect(o[2].reason).toBe("Joined at 2048×1152, so 4K adds nothing to the film");
+ expect(S.sharpenTierFor("cloud", "1080p", film)).toBeNull();
+ expect(S.sharpenTierFor("cloud", "4K", film)).toBe("2K");
+ // The join note says the size.
+ expect(S.joinNote(film)).toBe("The clip is joined at 2048×1152 (up to 2048 px a side). Each sharper take keeps its own size in Takes & review");
+ // A small clip is scaled up for merge-videos, but stays below 1080p.
+ expect(S.sharpenTierFor("cloud", "2K", S.filmSize(72, 128, "cloud"))).toBeNull();
+ });
+ });
+
+ describe("the composite's geometry and windows", () => {
+ it("the swap covers its canvas's part of the footage; the regenerate the centre its 16:9 draft kept", () => {
+ const film = { width: 1920, height: 1080 };
+ const canvas = C.h3Canvas(1920, 1080, "768p");
+ const g = S.compositeGeometry(film, canvas);
+ expect(g.take.width / g.take.height).toBeCloseTo(canvas.width / canvas.height, 2);
+ // H3's canvas for a 1080p clip (1344 × 736) is a little wider than 16:9: the swap covers the full width.
+ expect(canvas).toEqual({ width: 1344, height: 736 });
+ expect(g.take).toEqual({ width: 1920, height: 1052, x: 0, y: 14 });
+ expect(g.region.width / g.region.height).toBeCloseTo(1344 / 768, 2);
+ expect(g.region.height).toBeLessThanOrEqual(g.take.height);
+ expect(g.region.x).toBe(Math.floor((1920 - g.region.width) / 2));
+ // A tall clip: the draft turns.
+ const tall = S.compositeGeometry({ width: 1080, height: 1920 }, C.h3Canvas(1080, 1920, "768p"));
+ expect(tall.region.height / tall.region.width).toBeCloseTo(1344 / 768, 2);
+ // A square clip: the swap fills it, the regenerate is its centre 16:9 band.
+ const sq = S.compositeGeometry({ width: 2048, height: 2048 }, { width: 992, height: 992 });
+ expect(sq.take).toEqual({ width: 2048, height: 2048, x: 0, y: 0 });
+ expect(sq.region).toMatchObject({ width: 2048, x: 0 });
+ expect(sq.region.y).toBe(Math.floor((2048 - sq.region.height) / 2));
+ expect(S.maskEdge({ width: 1888, height: 1080 })).toEqual({ grow: 9, feather: 13 });
+ });
+
+ it("at 1080p and 4K the regenerate covers the centre 1080 / 1088 (2160 / 2176) of the region: its finish trims the grid's rows", () => {
+ const film = { width: 1920, height: 1080 };
+ const canvas = C.h3Canvas(1920, 1080, "768p");
+ const hd = S.compositeGeometry(film, canvas, "1080p");
+ expect(hd.region).toEqual({ width: 1842, height: 1052, x: 39, y: 14 });
+ // 1052 × 1080 / 1088 = 1044.3 rows, 4 above and 4 below.
+ expect(hd.regen).toEqual({ width: 1842, height: 1044, x: 39, y: 18 });
+ expect(hd.trim).toEqual({ x: 0, y: 4 });
+ // 2K is drawn on 1440 rows and keeps them all.
+ const k2 = S.compositeGeometry(film, canvas, "2K");
+ expect(k2.regen).toEqual({ ...k2.region });
+ expect(k2.trim).toEqual({ x: 0, y: 0 });
+ // 4K keeps 2160 of 2176 rows.
+ expect(S.compositeGeometry(film, canvas, "4K").regen.height).toBe(Math.round((1052 * 2160) / 2176));
+ // A tall clip: the columns are trimmed.
+ const tall = S.compositeGeometry({ width: 1080, height: 1920 }, C.h3Canvas(1080, 1920, "768p"), "1080p");
+ expect(tall.regen.height).toBe(tall.region.height);
+ expect(tall.regen.width).toBe(Math.round((tall.region.width * 1080) / 1088));
+ expect(tall.regen.x - tall.region.x).toBe(tall.trim.x);
+ });
+
+ it("windows: equal, never a sliver, every frame once", () => {
+ expect(S.frameWindows(362, 360)).toEqual([
+ { from: 0, frames: 181 },
+ { from: 181, frames: 181 },
+ ]);
+ expect(S.frameWindows(240, 72).map((w) => w.frames)).toEqual([60, 60, 60, 60]);
+ expect(S.frameWindows(50, 72)).toEqual([{ from: 0, frames: 50 }]);
+ });
+
+ it("the regenerate's words are the take's own, without H3's tags", () => {
+ expect(S.sharpenPrompt("Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the timing.", "a chrome robot")).toBe(
+ "The character: a chrome robot. Replace the selected person in the clip with the character in the reference. Preserve the timing.",
+ );
+ });
+ });
+
+ describe("Genjutsu's Character swap", () => {
+ it("480p and 768p are the swap alone, as before", () => {
+ for (const engine of ["open", "cloud"] as const) {
+ for (const q of ["480p", "768p"]) {
+ const p = character(engine, q);
+ expect(keys(p).some((k) => /regen|comp|mask|fit/.test(k))).toBe(false);
+ }
+ }
+ expect(keys(character("open", "768p"))).toEqual(["frame", "anchor", "swap"]);
+ });
+
+ it("your GPU at 2K: swap at 768p → mask → the part at 24 fps → regenerate (sigma 0.8, capped at 1080p for a 1080p clip) → composites → join → the sound", () => {
+ const p = character("open", "2K");
+ expect(keys(p)).toEqual(["frame", "anchor", "swap", "mask", "fit", "sharpen-regen0", "sharpen-comp0", "sharpen-comp1", "sharpen-comp2", "sharpen-comp3", "sharpen-join", "sound"]);
+ expect(p.final).toBe("sound");
+ expect(p.sound).toBe(true);
+ // The swap itself stays 768p and is a step now.
+ expect(step(p, "swap").request).toMatchObject({ feature: "genjutsu-step", params: { resolution: "768p" } });
+ expect(step(p, "mask").request).toMatchObject({
+ modelId: "oss-h3-person-mask",
+ inputs: { video: hd.url },
+ params: { startTime: 2, endTime: 12, resolution: "768p", matteOutput: "matte", extra: { keyFrame: 0, spanFrames: 240, shotFrames: 240, selection: "largest" } },
+ });
+ expect(step(p, "fit").request).toMatchObject({ modelId: "oss-fit-clip", params: { startTime: 2, endTime: 12, fps: 24, extra: { width: 1920, height: 1080 } } });
+ const regen = step(p, "sharpen-regen0");
+ expect(regen.request).toMatchObject({ modelId: "oss-h3-regenerate", op: "upscale-video", params: { resolution: "1080p", seed: 42, extra: { startSigma: 0.8, draftFrom: "h3" } } });
+ expect(regen.request.prompt).toMatch(/^Replace the selected person in the clip with the character in the reference/);
+ expect(regen.after).toEqual(["swap"]);
+ const c1 = step(p, "sharpen-comp1");
+ expect(c1.request).toMatchObject({ modelId: "oss-composite-mask", op: "composite", params: { startTime: 2.5, endTime: 5, extra: { windowStart: 2.5, takeStart: 2.5, maskStart: 2.5 } } });
+ expect(c1.after).toEqual(["sharpen-regen0", "fit", "swap", "mask"]);
+ expect(c1.chain).toEqual([{ slot: "videos", at: 1 }, { slot: "videos", at: 0 }, { slot: "videos", at: 2 }, { slot: "mask" }]);
+ expect(step(p, "sharpen-join").request).toMatchObject({ modelId: "oss-join-encoded", feature: "genjutsu-step" });
+ expect(step(p, "sound").request).toMatchObject({ modelId: "oss-mux", feature: "genjutsu", title: "Swap" });
+ expect(step(p, "sound").chain).toEqual([{ slot: "video" }, { slot: "audio" }]);
+ });
+
+ it("your GPU: a 4K square clip regenerates at 2K; a part over 15 s runs in two regenerate windows; a silent clip ends on the join", () => {
+ const sq = character("open", "4K", { source: { ...hd, width: 4096, height: 4096 } });
+ expect(step(sq, "sharpen-regen0").request.params).toMatchObject({ resolution: "1440p" });
+ const long = character("open", "2K", { range: { start: 0, end: 20 } });
+ expect(step(long, "sharpen-regen0").request.params).toMatchObject({ startTime: 0, endTime: 10, sourceDuration: 10 });
+ expect(step(long, "sharpen-regen1").request.params).toMatchObject({ startTime: 10, endTime: 20 });
+ const quiet = character("open", "1080p", { source: { ...hd, hasAudio: false } });
+ expect(quiet.final).toBe("sharpen-join");
+ expect(step(quiet, "sharpen-join").request).toMatchObject({ feature: "genjutsu", title: "Swap" });
+ expect(() => character("open", "2K", { source: { ...hd, width: 1280, height: 720 } })).toThrow(S.SHARPEN_COPY.small);
+ });
+
+ it("an evaluation may try another start noise (0.5–0.909); the page leaves it at 0.8", () => {
+ expect(step(character("open", "2K", { character: { sharpenSigma: 0.909 } }), "sharpen-regen0").request.params?.extra).toMatchObject({ startSigma: 0.909 });
+ expect(step(character("open", "2K", { character: { sharpenSigma: 0.3 } }), "sharpen-regen0").request.params?.extra).toMatchObject({ startSigma: 0.8 });
+ // It never reaches the swap's own graph settings.
+ expect(step(character("open", "2K", { character: { sharpenSigma: 0.7 } }), "swap").request.params?.extra).not.toHaveProperty("sharpenSigma");
+ const suite = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts/eval/cases/character-2k.json"), "utf8"));
+ expect(suite.cases.map((c: { submit: { body: { character: { sharpenSigma?: number } } } }) => c.submit.body.character.sharpenSigma)).toEqual([undefined, 0.7, 0.8, 0.909, undefined]);
+ expect(suite.defaults.metrics).toEqual(["identity", "background", "temporal"]);
+ });
+
+ it("the cloud at 2K: the same pieces, fal's H3 asked for 2K (no regenerate, no composite)", () => {
+ const p = character("cloud", "2K");
+ expect(keys(p).some((k) => /regen|comp/.test(k))).toBe(false);
+ const swap = p.steps.find((s) => s.request.modelId === "fuobe-character-swap")!;
+ expect(swap.request.params).toMatchObject({ resolution: "2K", duration: 10, seed: 42 });
+ // 1080p on the cloud is the 768P swap.
+ expect(character("cloud", "1080p").steps.find((s) => s.request.modelId === "fuobe-character-swap")!.request.params).toMatchObject({ resolution: "768p" });
+ // The payload fal gets.
+ const m = getModel("fuobe-character-swap")!;
+ const route = onEngine(m, "cloud").routes.find((r) => r.provider === "fal")!;
+ const payload = buildPayload(route.map!, { ...swap.request.params, prompt: swap.request.prompt, images: [ref] } as never) as Record<string, unknown>;
+ expect(payload).toMatchObject({ resolution: "2K", seed: 42, duration: 10 });
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Character Swap Studio: Sharpen per chosen take
+
+ const clipOf = (over: Partial<SwapClip> = {}): SwapClip => ({
+ id: "clip-1",
+ name: "walk",
+ source: { url: "/api/files/uploads/x/walk.mp4", name: "walk.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true },
+ normalized: { url: "/api/files/outputs/x/walk24.mp4", genId: "g-norm" },
+ frames: 480,
+ cuts: [],
+ detected: null,
+ cutsReviewed: true,
+ shots: [],
+ transcript: null,
+ review: "pending",
+ reviewNotes: "",
+ assembly: null,
+ ...over,
+ });
+
+ function studio(engine: "open" | "cloud", frames = 120) {
+ const shot = { ...newShot(48, 48 + frames, DEFAULT_SETTINGS, true, () => 0.5), id: "shot-1" };
+ const t: SwapTake = {
+ id: "take-1",
+ createdAt: 1,
+ engine,
+ state: "launched",
+ genId: "g-take",
+ signature: "",
+ dependencies: [],
+ prompt: "Replace the selected person in <Video 1> with the character in <Picture 1>.",
+ seed: 7,
+ favourite: false,
+ decision: "pending",
+ notes: "",
+ frozen: { reference: ref, shotStart: 48, start: 0, end: frames, history: 0, anchor: null, mask: engine === "open" ? "/api/files/outputs/x/mask.mp4" : null, settings: { ...DEFAULT_SETTINGS }, who: shot.who },
+ };
+ const seg = { id: "seg-1", start: 0, end: frames, connection: "start" as const, history: 0, seed: 7, prompt: "", performancePrompt: null, dialogue: null, speaker: null, anchorMode: "none" as const, anchor: null, anchors: [], takes: [t], selectedTake: t.id, needsReview: false };
+ const s = { ...shot, segments: [seg] };
+ const clip = clipOf({ shots: [s] });
+ const project: SwapProject = { id: "p1", name: "Demo", engine, character: { image: ref, description: "a chrome robot" }, defaults: { ...DEFAULT_SETTINGS }, clips: [clip], createdAt: 0, updatedAt: 0, revision: 1 };
+ return { project, clip, shot: s, seg, take: t };
+ }
+
+ describe("Character Swap Studio: Sharpen", () => {
+ it("your GPU: per take, regenerate → composites over the 24 fps copy through the mask it was made with → join", () => {
+ const x = studio("open");
+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/api/files/outputs/x/take.mp4" });
+ expect(keys(plan)).toEqual(["regen0", "comp0", "comp1", "join"]);
+ expect(plan.final).toBe("join");
+ expect(step(plan, "regen0").request).toMatchObject({ modelId: "oss-h3-regenerate", inputs: { video: "/api/files/outputs/x/take.mp4" }, params: { resolution: "1080p", seed: 7, extra: { startSigma: 0.8 } } });
+ expect(step(plan, "regen0").request.prompt).toBe("The character: a chrome robot. Replace the selected person in the clip with the character in the reference.");
+ const c1 = step(plan, "comp1");
+ // The take starts at frame 48 of the clip (2 s) and at frame 0 of the shot's mask.
+ expect(c1.request).toMatchObject({
+ inputs: { videos: ["/api/files/outputs/x/walk24.mp4", "/api/files/outputs/x/take.mp4"], mask: "/api/files/outputs/x/mask.mp4" },
+ params: { startTime: 4.5, endTime: 7, extra: { windowStart: 2.5, takeStart: 2.5, maskStart: 2.5 } },
+ });
+ expect(c1.chain).toEqual([{ slot: "videos", at: 1 }]);
+ expect(step(plan, "join").request).toMatchObject({ feature: "swap-studio-step", title: "Shot 1 · segment 1 · take 1 · 1080p" });
+ // No mask, no composite.
+ expect(() => planTakeFinish({ ...x, shot: { ...x.shot, approvedMask: null }, take: { ...x.take, frozen: { ...x.take.frozen!, mask: null } }, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/v.mp4" })).toThrow(
+ S.SHARPEN_COPY.noMask,
+ );
+ });
+
+ it("the cloud: the segment made again on fal's H3 at 2K, with its words, LoRA, references and seed", () => {
+ const x = studio("cloud");
+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "2K" });
+ expect(keys(plan)).toEqual(["cut", "swap", "fit"]);
+ expect(step(plan, "swap").request).toMatchObject({ modelId: "fuobe-character-swap", inputs: { images: [ref] }, params: { resolution: "2K", seed: 7, duration: 5, sourceDuration: 5 } });
+ expect(step(plan, "swap").request.loras?.[0]?.file).toMatch(/swap/);
+ expect((step(plan, "swap").request.step as { label: string }).label).toMatch(/swap at 2K$/);
+ expect(() => planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p" })).toThrow(/2K or 4K/);
+ });
+
+ it("the assembly uses a sharper version only once it is picked, and knows when that changed", () => {
+ const x = studio("open");
+ const pieces = [{ kind: "take" as const, start: 48, end: 168, take: x.take, segmentId: "seg-1" }];
+ expect(chosenTakes(pieces)).toHaveLength(1);
+ expect(assemblyTakes(pieces)).toEqual(["take-1"]);
+ const finish = { id: "finish-1", createdAt: 2, engine: "open" as const, asked: "2K" as const, tier: "1080p" as const, genId: "g-fin", use: false };
+ expect(usedFinish({ finish })).toBeNull();
+ const used = [{ ...pieces[0], take: { ...x.take, finish: { ...finish, use: true } } }];
+ expect(assemblyTakes(used)).toEqual(["take-1@finish-1"]);
+ const plan = planAssembly({ engine: "open", clip: x.clip, pieces: used, videoOf: (p) => (usedFinish(p.take) ? "/api/files/outputs/x/sharp.mp4" : "/v.mp4") });
+ expect(plan.steps.find((s) => s.request.inputs?.video === "/api/files/outputs/x/sharp.mp4")).toBeTruthy();
+ });
+
+ it("Finish is Sharpen alone: its card names the size picked and the model, and says why a size can't be picked", () => {
+ const page = fs.readFileSync(path.join(ROOT, "src/components/swap-studio/stage-review.tsx"), "utf8");
+ expect(page).toMatch(/SHARPEN_COPY\.title/);
+ expect(page).not.toMatch(/backplate|Not available/i);
+ expect(page).toMatch(/describedBy=\{off\.length \? offId : undefined\}/);
+ expect(S.SHARPEN_COPY.card("1080p")).toBe(
+ "Redraws each chosen take at 1080p with Open-H3 Regenerate, then puts only your character back over the original footage. The background and the sound stay as filmed. Faces can change slightly; compare before you keep it.",
+ );
+ expect(S.SHARPEN_COPY.cardCloud("2K")).toMatch(/^Makes each chosen take again at 2K on MiniMax H3/);
+ expect(S.SHARPEN_COPY.model("open", "1080p")).toBe("Open-H3 Regenerate at 1080p");
+ expect(S.SHARPEN_COPY.model("cloud", "2K")).toBe("MiniMax H3 at 2K");
+ });
+
+ it("a take's sharper version still being made keeps its take and its shot's layout from changing", () => {
+ const x = studio("open");
+ const finish = { id: "finish-1", createdAt: 2, engine: "open" as const, asked: "1080p" as const, tier: "1080p" as const, genId: "g-fin", stepIds: ["g-regen", "g-fin"], use: false };
+ const shot = { ...x.shot, segments: [{ ...x.seg, takes: [{ ...x.take, finish }] }] };
+ const project = { ...x.project, clips: [{ ...x.clip, shots: [shot] }] };
+ const running = (id: string) => id === "g-regen";
+ expect(shotBusy(shot, running)).toBe(true);
+ expect(shotBusy(shot, () => false)).toBe(false);
+ const ref = { clipId: x.clip.id, shotId: shot.id, segmentId: x.seg.id, takeId: x.take.id };
+ expect(() => applyEdit(project, { type: "take", ...ref, remove: true }, { active: running })).toThrow(/sharper version is still being made/);
+ expect(() => applyEdit(project, { type: "remove-clip", clipId: x.clip.id } as never, { active: running })).toThrow(/Wait for this clip's takes/);
+ // Done: the take can go (with its version).
+ const out = applyEdit(project, { type: "take", ...ref, remove: true }, { active: () => false });
+ expect(out.clips[0].shots[0].segments![0].takes).toHaveLength(0);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // The graph
+
+ describe("the GPU pre-flight", () => {
+ it("has a Character swap in 2K row on every graph Genjutsu's GPU run takes: the swap, the mask, the fit, the regenerate, the composite, the join and the mux", async () => {
+ const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");
+ const row = STUDIO_ROWS.find((r) => r.label === "Character swap in 2K")!;
+ expect(row).toMatchObject({ href: "/genjutsu?mode=character", group: "Video tools" });
+ // Every model the open 2K plan runs has its step on the row.
+ // (The optional anchor frame has its own models and rows.)
+ const planned = character("open", "2K").steps.filter((s) => s.key !== "frame" && s.key !== "anchor");
+ const listed = row.steps!.map((s) => `${s.modelId}#${s.op}`);
+ expect([...new Set(planned.map((s) => `${s.request.modelId}#${s.request.op}`))].sort()).toEqual([...listed].sort());
+ const t = studioTool(row)!;
+ expect(t.workflows).toEqual(expect.arrayContaining(["video-regenerate-h3", "video-composite-mask", "video-concat-encoded", "video-mask-h3-relay"]));
+ expect(t.loras.map((l) => l.file)).toContain("open_h3_regenerate_2k_lora.safetensors");
+ });
+ });
+
+ describe("video-composite-mask", () => {
+ const { manifest } = getWorkflow(S.COMPOSITE_WORKFLOW);
+
+ it("is core nodes only, validated, with the bindings the plan fills", () => {
+ expect(manifest).toMatchObject({ capability: "composite", vramGb: 0, validated: true });
+ expect(Object.keys(manifest.bindings).sort()).toEqual(
+ [
+ ...["video", "video2", "video3", "mask", "startTime", "windowStart", "takeStart", "maskStart", "duration", "canvasWidth", "canvasHeight", "takeX", "takeY"],
+ ...["regionWidth", "regionHeight", "regenWidth", "regenHeight", "regenX", "regenY", "trimX", "trimY", "maskGrow", "feather", "filenamePrefix"],
+ ].sort(),
+ );
+ const graph = JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/video-composite-mask.json"), "utf8")) as Record<string, { class_type: string }>;
+ expect(new Set(Object.values(graph).map((n) => n.class_type))).toEqual(
+ new Set(["LoadVideo", "Video Slice", "GetVideoComponents", "ImageScale", "ImageToMask", "CropMask", "GrowMask", "FeatherMask", "ImageCompositeMasked", "CreateVideo", "SaveVideo"]),
+ );
+ expect(getModel(S.COMPOSITE_MODEL)).toMatchObject({ engine: "open", hidden: true });
+ });
+
+ it("a run keeps the person's mask (it isn't taken for a painted one) and needs the three clips and the mask", async () => {
+ const { applySketch } = await import("@/lib/catalog/sketch");
+ const { missingInputs } = await import("@/lib/catalog/plan");
+ const m = getModel(S.COMPOSITE_MODEL)!;
+ const req = { feature: "genjutsu-step", modelId: m.id, op: "composite" as const, inputs: { videos: ["/s.mp4", "/r.mp4", "/t.mp4"], mask: "/m.mp4" } } as GenerationRequest;
+ const kept = applySketch(req, m);
+ expect(kept.request.inputs).toEqual(req.inputs);
+ expect(kept.note).toBeUndefined();
+ expect(missingInputs("composite", req)).toBeNull();
+ const msg = "Add the footage, the redrawn clip, the swap and the person's mask to put the character back over it";
+ expect(missingInputs("composite", { inputs: { videos: ["/s.mp4", "/r.mp4"], mask: "/m.mp4" } })).toBe(msg);
+ expect(missingInputs("composite", { inputs: { videos: ["/s.mp4", "/r.mp4", "/t.mp4"] } })).toBe(msg);
+ });
+
+ it("the provider puts the footage, the regenerate, the swap, the mask and the composite's places on their nodes", async () => {
+ const x = studio("open");
+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/take.mp4" });
+ const c = step(plan, "comp0").request;
+ const extra = c.params!.extra as Record<string, number>;
+ const { workflow: wf } = await prepareWorkflow(
+ S.COMPOSITE_WORKFLOW,
+ { video: undefined, videos: ["src.mp4", "regen.mp4", "take.mp4"], mask: "mask.mp4", startTime: c.params!.startTime, endTime: c.params!.endTime, extra: { ...extra } } as GenInput,
+ { generationId: "g1", op: "composite", upload: async (_d, _t, name) => `up_${name}`, media: () => undefined },
+ );
+ const at = (node: string, input: string) => (wf as Record<string, { inputs: Record<string, unknown> }>)[node].inputs[input];
+ expect([at("source", "file"), at("regen", "file"), at("take", "file"), at("mask", "file")]).toEqual(["src.mp4", "regen.mp4", "take.mp4", "mask.mp4"]);
+ expect(at("source_slice", "start_time")).toBe(2);
+ expect([at("source_slice", "duration"), at("regen_slice", "duration"), at("take_slice", "duration"), at("mask_slice", "duration")]).toEqual([2.5, 2.5, 2.5, 2.5]);
+ expect([at("regen_slice", "start_time"), at("take_slice", "start_time"), at("mask_slice", "start_time")]).toEqual([0, 0, 0]);
+ expect([at("take_scaled", "width"), at("take_scaled", "height"), at("base", "x"), at("base", "y")]).toEqual([extra.canvasWidth, extra.canvasHeight, extra.takeX, extra.takeY]);
+ expect([at("regen_mask_img", "width"), at("regen_mask_img", "height")]).toEqual([extra.regionWidth, extra.regionHeight]);
+ expect(at("regen_mask_img", "crop")).toBe("center");
+ // The regenerate and its mask: the rows its finish kept (1044 of the region's 1052 at 1080p), 4 rows down.
+ expect([at("regen_scaled", "width"), at("regen_scaled", "height"), at("composite", "x"), at("composite", "y")]).toEqual([extra.regenWidth, extra.regenHeight, extra.regenX, extra.regenY]);
+ expect([at("regen_trim", "x"), at("regen_trim", "y"), at("regen_trim", "width"), at("regen_trim", "height")]).toEqual([extra.trimX, extra.trimY, extra.regenWidth, extra.regenHeight]);
+ expect(extra).toMatchObject({ regionWidth: 1842, regionHeight: 1052, regenWidth: 1842, regenHeight: 1044, regenX: 39, regenY: 18, trimX: 0, trimY: 4 });
+ expect([at("take_grow", "expand"), at("regen_feather", "bottom")]).toEqual([extra.maskGrow, extra.feather]);
+ });
+ });
diff --cc tests/e2e/character-swap-2k.mjs
index 00000000,b0432253..5c1bcf02
mode 000000,100644..100644
--- a/tests/e2e/character-swap-2k.mjs
+++ b/tests/e2e/character-swap-2k.mjs
@@@ -1,0 -1,219 +1,220 @@@
-// Browser check of Character swap in 2K (n7-4-character-swap-2k).
++// Browser check of Character swap in 2K.
+ // Usage: node tests/e2e/character-swap-2k.mjs [appUrl] [outDir] (the app in demo mode: no keys, no ComfyUI)
+ // At 1440 px and 390 px, light and dark: Character Swap Studio's Assemble → Finish with "Sharpen to 1080p / 2K / 4K"
+ // (the sizes picked by keyboard and by touch, why a size can't be picked as text on the page, the price or GPU time, Run),
+ // on a cloud project with a chosen take and on a project on your GPU; a run on the cloud makes a 2K version that Takes &
+ // review shows beside the take with "Use the 2K version"; Genjutsu's Character swap Quality with 2K and 4K and their
+ // prices (the cloud) or GPU time (your GPU, with 1080p, and 4K turned off with the reason). No sideways scroll anywhere,
+ // no page error and no console error. Screenshots go to outDir.
+ import { execFileSync } from "node:child_process";
+ import fs from "node:fs";
++import os from "node:os";
+ import path from "node:path";
+ import { DESKTOP, PHONE, launch, openRoute, root } from "./_browser.mjs";
+
+ const args = process.argv.slice(2).filter((a) => !a.startsWith("--"));
-const app = (args[0] ?? "http://localhost:3000").replace(/\/$/, "");
-const out = args[1] ?? fs.mkdtempSync("/tmp/fuobe-swap-2k-");
++const app = (args[0] ?? "http://localhost:3440").replace(/\/$/, "");
++const out = args[1] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-2k-"));
+ fs.mkdirSync(out, { recursive: true });
+
+ const failures = [];
+ const check = (ok, what) => {
+ console.log(`${ok ? "✓" : "✗"} ${what}`);
+ if (!ok) failures.push(what);
+ };
+ const json = async (p, init) => {
+ const res = await fetch(app + p, { headers: { "Content-Type": "application/json" }, ...init });
+ const body = await res.json();
+ if (!res.ok) throw new Error(`${p}: ${body.error ?? res.status}`);
+ return body;
+ };
+ const upload = async (file, type) => {
+ const form = new FormData();
+ form.append("file", new Blob([fs.readFileSync(file)], { type }), path.basename(file));
+ const res = await fetch(`${app}/api/uploads`, { method: "POST", body: form });
+ const body = await res.json();
+ if (!res.ok) throw new Error(`upload: ${body.error}`);
+ return body.url;
+ };
+ const noSideScroll = async (page, label) => {
+ const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ check(over <= 0, `${label}: no horizontal scroll (${over}px)`);
+ };
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ // A 6 s 1920×1080 clip with sound (H.264: the server reads its header; the checks don't play it), and the character.
+ const clipFile = path.join(out, "street.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", path.join(root, "scripts/eval/fixtures/walk-6s.mp4"), "-t", "6", "-vf", "scale=1920:1080,setsar=1", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart", clipFile]);
+ const clipUrl = await upload(clipFile, "video/mp4");
+ const heroUrl = await upload(path.join(root, "scripts/eval/fixtures/character/drawn-face-2.png"), "image/png");
+
+ // A rerun starts clean.
+ for (const p of (await json("/api/swap-studio/projects")).items ?? []) if (/^2K check/.test(p.name)) await fetch(`${app}/api/swap-studio/projects/${p.id}`, { method: "DELETE" });
+
+ /** A project with the clip, no scene anchor, one 6 s segment; on the cloud its take is made (demo) and chosen. */
+ async function project(engine) {
+ const p = await json("/api/swap-studio/projects", { method: "POST", body: JSON.stringify({ name: `2K check · ${engine}`, engine, character: { image: heroUrl, description: "a cartoon man with round glasses" } }) });
+ let v = await json(`/api/swap-studio/projects/${p.id}/clips`, { method: "POST", body: JSON.stringify({ url: clipUrl, name: "street.mp4" }) });
+ const c = v.clips[0];
+ const shot = c.shots[0];
+ const edit = (e) => json(`/api/swap-studio/projects/${p.id}`, { method: "PATCH", body: JSON.stringify(e) });
+ await edit({ type: "shot", clipId: c.id, shotId: shot.id, patch: { settings: { useAnchor: false } } });
+ v = await edit({ type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 144 } });
+ if (engine === "cloud") {
+ const seg = v.clips[0].shots[0].segments[0];
+ await json(`/api/swap-studio/projects/${p.id}/queue`, { method: "POST", body: JSON.stringify({ clipId: c.id, shotId: shot.id, segmentId: seg.id, mode: "all" }) });
+ for (let i = 0; i < 120; i++) {
+ const view = await json(`/api/swap-studio/projects/${p.id}`);
+ const s = view.project.clips[0].shots[0].segments[0];
+ if (s.selectedTake && view.gens[s.takes[0].genId]?.status === "succeeded") break;
+ await sleep(1000);
+ }
+ }
+ return { id: p.id, clipId: c.id, shotId: shot.id };
+ }
+
+ const cloud = await project("cloud");
+ const open = await project("open");
+
+ const browser = await launch();
+ try {
+ for (const [dname, device] of [
+ ["1440", DESKTOP],
+ ["390", PHONE],
+ ]) {
+ for (const theme of ["light", "dark"]) {
+ const label = `${dname} ${theme}`;
+ const ctx = await browser.newContext({ ...device, colorScheme: theme });
+ await ctx.route((u) => u.origin !== new URL(app).origin && /^https?:$/.test(u.protocol), (rt) => rt.abort());
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => failures.push(`${label} page error: ${e.message.split("\n")[0]}`));
+ // React reports hydration errors on the console: every console error fails the check.
+ page.on("console", (m) => m.type() === "error" && failures.push(`${label} console error: ${m.text().split("\n")[0]}`));
+ const touch = !!device.hasTouch;
+ const press = (loc) => (touch ? loc.tap() : loc.click());
+
+ // ---- Character Swap Studio on the cloud: Assemble → Finish.
+ await openRoute(page, `${app}/character-swap/${cloud.id}`);
+ await press(page.getByRole("tab", { name: "Assemble" }));
+ const sharpenTitle = page.getByRole("heading", { name: "Sharpen to 1080p / 2K / 4K" });
+ await sharpenTitle.waitFor({ timeout: 60_000 });
+ check(await sharpenTitle.isVisible(), `${label} cloud: the Sharpen card`);
+ await page.getByText(/1 chosen take/).waitFor({ timeout: 30_000 }).catch(() => undefined);
+ check((await page.getByRole("heading", { name: /backplate/i }).count()) === 0 && (await page.getByText("Not available", { exact: false }).count()) === 0, `${label} cloud: Finish is Sharpen alone`);
+ const sizes = page.getByRole("radiogroup", { name: "Sharpen to" });
+ const r = (n) => sizes.getByRole("radio", { name: n, exact: true });
+ check(await r("1080p").isDisabled(), `${label} cloud: 1080p is off (fal makes 2K or 4K)`);
+ check((await r("2K").getAttribute("aria-checked")) === "true", `${label} cloud: 2K is picked`);
+ check(await r("4K").isDisabled(), `${label} cloud: 4K is off (the film is joined at 1920×1080)`);
+ // Why, as text on the page that the size group points to (a turned-off size can't take focus or show a tooltip on touch).
+ const why = await sizes.getAttribute("aria-describedby");
+ const whyText = why ? await page.locator(`[id="${why}"]`).innerText() : "";
+ check(/4K: Joined at 1920×1080, so 4K adds nothing to the film/.test(whyText) && (await page.locator(`[id="${why}"]`).isVisible()), `${label} cloud: 4K says why, on the page`);
+ check(/1080p: The cloud makes 2K or 4K/.test(whyText), `${label} cloud: 1080p says why, on the page`);
+ await page.waitForFunction(() => /Placeholder · free|≈ \$/.test(document.body.innerText), null, { timeout: 30_000 }).catch(() => undefined);
+ const body = await page.evaluate(() => document.body.innerText);
+ check(/Makes each chosen take again at 2K on MiniMax H3/.test(body), `${label} cloud: the cloud's copy (a new render, the whole frame)`);
+ check(/1 chosen take · 6 s · MiniMax H3 at 2K/.test(body), `${label} cloud: the takes and seconds`);
+ check(/Placeholder · free|≈ \$/.test(body), `${label} cloud: a price before running`);
+ check(/joined at 1920×1080/i.test(body), `${label} cloud: the join's size`);
+ // Keyboard reaches the size and the button.
+ await r("2K").focus();
+ check(await page.evaluate(() => document.activeElement?.getAttribute("role") === "radio"), `${label} cloud: keyboard focus on the size`);
+ const run = page.getByRole("button", { name: /^Sharpen to 2K/ });
+ if (await run.isEnabled()) {
+ await run.focus();
+ check(await page.evaluate(() => /Sharpen to 2K/.test(document.activeElement?.textContent ?? "")), `${label} cloud: keyboard focus on Sharpen`);
+ } else check(/1 of 1 ready/.test(body), `${label} cloud: Sharpen rests once every chosen take has its 2K version`);
+ await noSideScroll(page, `${label} cloud Assemble`);
+ await page.screenshot({ path: path.join(out, `assemble-cloud-${dname}-${theme}.png`), fullPage: true });
+
+ // Run once (the first pass), then the version beside the take in Takes & review.
+ if (dname === "1440" && theme === "light") {
+ await run.click();
+ await page.getByText(/of 1 ready/).waitFor({ timeout: 30_000 });
+ check(true, `${label} cloud: Sharpen runs (a 2K version on its way)`);
+ await page.getByText(/1 of 1 ready/).waitFor({ timeout: 120_000 });
+ }
+ await press(page.getByRole("tab", { name: "Takes & review" }));
+ await page.getByText("2K version").first().waitFor({ timeout: 60_000 });
+ const use = page.getByRole("button", { name: "Use the 2K version" });
+ const using = page.getByText("The assembly uses the 2K version");
+ if ((await use.count()) > 0) {
+ check(true, `${label} cloud: the 2K version beside the take, with Use the 2K version`);
+ await press(use);
+ await using.waitFor({ timeout: 15_000 });
+ }
+ check(await using.isVisible(), `${label} cloud: picked, the assembly uses it`);
+ await noSideScroll(page, `${label} cloud Takes & review`);
+ await page.screenshot({ path: path.join(out, `review-cloud-${dname}-${theme}.png`), fullPage: true });
+ // Back to the take for the next pass.
+ await press(page.getByRole("button", { name: "Use the take instead" }));
+ await use.waitFor({ timeout: 15_000 });
+
+ // ---- On your GPU: 1080p only (the footage is 1080p), free, the GPU time.
+ await openRoute(page, `${app}/character-swap/${open.id}`);
+ await press(page.getByRole("tab", { name: "Assemble" }));
+ await page.getByRole("heading", { name: "Sharpen to 1080p / 2K / 4K" }).waitFor({ timeout: 60_000 });
+ const og = page.getByRole("radiogroup", { name: "Sharpen to" });
+ check((await og.getByRole("radio", { name: "1080p", exact: true }).getAttribute("aria-checked")) === "true", `${label} GPU: 1080p is picked`);
+ check(await og.getByRole("radio", { name: "2K", exact: true }).isDisabled(), `${label} GPU: 2K is off (the part redrawn is below 1440)`);
+ check(await og.getByRole("radio", { name: "4K", exact: true }).isDisabled(), `${label} GPU: 4K is off (joined at up to 2048 px)`);
+ const ogWhy = await og.getAttribute("aria-describedby");
+ const ogText = ogWhy ? await page.locator(`[id="${ogWhy}"]`).innerText() : "";
+ check(/2K: Your character is redrawn in a 1842×1052 part of the frame/.test(ogText), `${label} GPU: 2K says why, on the page`);
+ check(/4K: Your GPU joins the clip at up to 2048 px a side, so 4K adds nothing over 2K/.test(ogText), `${label} GPU: 4K says why, on the page`);
+ const ob = await page.evaluate(() => document.body.innerText);
+ check(/Redraws each chosen take at 1080p with Open-H3 Regenerate, then puts only your character back over the original footage/.test(ob), `${label} GPU: the card names the size picked and the model`);
+ check(/Free on your GPU · about \d+ min on a 72 GB GPU|Placeholder · free/.test(ob), `${label} GPU: free, with the GPU time`);
+ check(/Choose a take for every swapped segment first/.test(ob), `${label} GPU: says what's missing before it can run`);
+ check(await page.getByRole("button", { name: /^Sharpen to 1080p/ }).isDisabled(), `${label} GPU: Run waits for the takes`);
+ await noSideScroll(page, `${label} GPU Assemble`);
+ await page.screenshot({ path: path.join(out, `assemble-open-${dname}-${theme}.png`), fullPage: true });
+
+ // ---- Genjutsu's Character swap: Quality with 2K and 4K.
+ for (const engine of ["cloud", "open"]) {
+ await page.evaluate((e) => localStorage.setItem("fuobe.engine", e), engine);
+ await openRoute(page, `${app}/genjutsu?mode=character&video=${encodeURIComponent(clipUrl)}&image=${encodeURIComponent(heroUrl)}`);
+ const q = page.getByRole("radiogroup", { name: "Quality" });
+ await q.waitFor({ timeout: 60_000 });
+ const names = await q.getByRole("radio").allInnerTexts();
+ check(
+ JSON.stringify(names.map((s) => s.trim())) === JSON.stringify(engine === "cloud" ? ["480p", "768p", "2K", "4K"] : ["480p", "768p", "1080p", "2K", "4K"]),
+ `${label} Genjutsu ${engine}: Quality offers ${names.join(", ")}`,
+ );
+ // Keyboard: from 768p, the arrow picks the next size.
+ await q.getByRole("radio", { name: "768p", exact: true }).focus();
+ await page.keyboard.press("ArrowRight");
+ await page.waitForTimeout(300);
+ const next = engine === "cloud" ? "2K" : "1080p";
+ check((await q.getByRole("radio", { name: next, exact: true }).getAttribute("aria-checked")) === "true", `${label} Genjutsu ${engine}: the arrow key picks ${next}`);
+ await press(q.getByRole("radio", { name: "2K", exact: true }));
+ await page.waitForTimeout(300);
+ const g = await page.evaluate(() => document.body.innerText);
+ // The whole line is on the page, not cut short (the field's hint holds the short price).
+ const line = page.getByText(/redraw the 768p swap at the higher size/);
+ const fits = await line.evaluate((el) => el.scrollWidth <= el.clientWidth + 1 && getComputedStyle(el).textOverflow !== "ellipsis").catch(() => false);
+ check(fits, `${label} Genjutsu ${engine}: the size's line wraps instead of being cut`);
+ if (engine === "cloud") {
+ check(/2K and 4K redraw the 768p swap at the higher size\. \$0\.81 for 5 s, \$2\.44 for 15 s\./.test(g), `${label} Genjutsu cloud: 2K's price ($0.81 for 5 s)`);
+ await press(q.getByRole("radio", { name: "4K", exact: true }));
+ await page.waitForTimeout(300);
+ check(/\$1\.00 for 5 s, \$3\.00 for 15 s/.test(await page.evaluate(() => document.body.innerText)), `${label} Genjutsu cloud: 4K's price`);
+ } else {
+ check(/1080p and 2K redraw the 768p swap at the higher size\. Free on your GPU, about 3 min more per 5 s on a 72 GB GPU\. Your GPU joins the clip at up to 2048 px a side/.test(g), `${label} Genjutsu GPU: free, with the GPU time and the 2048 px join`);
+ check(await q.getByRole("radio", { name: "4K", exact: true }).isDisabled(), `${label} Genjutsu GPU: 4K is off`);
+ const qWhy = await q.getAttribute("aria-describedby");
+ check(!!qWhy && /4K: Your GPU joins the clip at up to 2048 px a side, so 4K adds nothing over 2K/.test(await page.locator(`[id="${qWhy}"]`).innerText()), `${label} Genjutsu GPU: 4K says why, on the page`);
+ }
+ await noSideScroll(page, `${label} Genjutsu ${engine}`);
+ await page.screenshot({ path: path.join(out, `genjutsu-${engine}-${dname}-${theme}.png`), fullPage: true });
+ }
+ await ctx.close();
+ }
+ }
+ } finally {
+ await browser.close();
+ }
+ for (const p of [cloud, open]) await fetch(`${app}/api/swap-studio/projects/${p.id}`, { method: "DELETE" });
+ console.log(failures.length ? `\n${failures.length} failed:\n- ${failures.join("\n- ")}` : "\nAll checks passed");
+ process.exit(failures.length ? 1 : 0);
diff --cc tests/public-signup.test.ts
index 05ca26c3,2857d849..e7d2967c
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@@ -237,9 -237,11 +237,11 @@@ describe("accounts never run on the own
// A run route that ignores ?preview=1 isn't a price check.
"/api/cinema/projects/p1/generate?preview=1",
"/api/faceless/episodes/e1/estimate",
- // Restore & colourise (o/archive-restore): its run and its prompt writer.
+ // Restore & colourise: its run and its prompt writer.
"/api/restore",
"/api/restore/prompt",
- // Character Swap Studio's Sharpen (n7-4): a studio job, like its assembly.
++ // Character Swap Studio's Sharpen: a studio job, like its assembly.
+ "/api/swap-studio/projects/p1/sharpen",
]) {
const r = proxy(req(p, { method: "POST", cookie }));
expect(r.status, p).toBe(403);
diff --cc tests/regenerate-offered.test.ts
index 7f84c9a9,00000000..3572f816
mode 100644,000000..100644
--- a/tests/regenerate-offered.test.ts
+++ b/tests/regenerate-offered.test.ts
@@@ -1,77 -1,0 +1,94 @@@
+import { describe, expect, it } from "vitest";
+import type { Generation, OutputFile } from "@/lib/catalog/types";
+import { REGEN_OFFERED } from "@/lib/catalog/regenerate";
+import { UPSCALE_FIRST_STEPS } from "@/lib/catalog/upscale-first";
+import { VIDEO_UPSCALE_STUDIO } from "@/lib/studios";
+import { getModel } from "@/lib/catalog";
+import { paletteItems } from "@/lib/catalog/canvas";
+import { nextSteps, outputActions } from "@/lib/output-actions";
+import { HUB_MODES } from "@/lib/hubs";
++import { CHARACTER_QUALITIES } from "@/lib/catalog/character-swap";
++import { MAKERS } from "@/lib/catalog/genjutsu";
++import { OPEN_SHARPEN_OFF, sharpenOffered, sharpenOptions } from "@/lib/catalog/sharpen";
++import { STUDIO_ROWS } from "@/server/gpu/tools";
+
+// Regenerate · creative is switched off until it has run on a card that fits it; Restore & colourise and Remove
+// dialogue run on a self-hosted Fuobe only, so a guest or an account is never sent to them.
+
+const out = (url = "/api/files/a.mp4"): OutputFile => ({ url, kind: "video" }) as OutputFile;
+const gen = (p: Partial<Generation> = {}): Generation =>
+ ({
+ id: "g1",
+ batchId: null,
+ feature: "video",
+ presetId: null,
+ modelId: "oss-minimax-h3",
+ engine: "open",
+ provider: "comfyui",
+ op: "t2v",
+ kind: "video",
+ status: "succeeded",
+ progress: null,
+ message: null,
+ prompt: "a fox runs through snow",
+ request: { feature: "video", modelId: "oss-minimax-h3", prompt: "a fox runs through snow" },
+ outputs: [out()],
+ error: null,
+ costUsd: 0,
+ favorite: false,
+ createdAt: 1,
+ updatedAt: 1,
+ completedAt: 1,
+ ...p,
+ }) as Generation;
+const ids = (g: Generation, ctx = {}) => outputActions(g, 0, ctx).map((a) => a.id);
+const upload = () => gen({ feature: "upload", modelId: "upload", provider: "mock" as Generation["provider"], prompt: null, request: { feature: "upload", modelId: "upload" } });
+
+describe("Regenerate while it is switched off", () => {
+ it("is off", () => {
+ expect(REGEN_OFFERED).toBe(false);
+ });
+
+ it("is not a step before upscaling, a finishing choice, a model to pick or a Canvas node", () => {
+ expect(UPSCALE_FIRST_STEPS.map((s) => s.id)).not.toContain("regenerate");
+ expect(UPSCALE_FIRST_STEPS.map((s) => s.id)).toContain("restore");
+ expect(VIDEO_UPSCALE_STUDIO.finishChoices).toBeUndefined();
+ expect(getModel("oss-h3-regenerate")?.hidden).toBe(true);
+ expect(paletteItems("both").map((p) => p.id)).not.toContain("upscale-regenerate");
+ });
+
++ it("leaves the Character swap's 1080p / 2K / 4K on your GPU out, and keeps the cloud's 2K / 4K", () => {
++ expect(CHARACTER_QUALITIES.open).toEqual(["480p", "768p"]);
++ expect(CHARACTER_QUALITIES.cloud).toEqual(["480p", "768p", "2K", "4K"]);
++ for (const m of MAKERS.filter((m) => m.h3 && m.engine === "open")) expect(m.qualities).toEqual(["480p", "768p"]);
++ expect(sharpenOffered("open")).toBe(false);
++ expect(sharpenOffered("cloud")).toBe(true);
++ const film = { width: 1920, height: 1080 };
++ expect(sharpenOptions("open", film).every((o) => !o.available && o.reason === OPEN_SHARPEN_OFF)).toBe(true);
++ expect(sharpenOptions("cloud", film).find((o) => o.tier === "2K")?.available).toBe(true);
++ expect(STUDIO_ROWS.map((r) => r.label)).not.toContain("Character swap in 2K");
++ expect(STUDIO_ROWS.map((r) => r.label)).not.toContain("Regenerate in 2K");
++ });
++
+ it("is not offered on a clip or an upload", () => {
+ expect(ids(gen())).not.toContain("regenerate");
+ expect(ids(upload())).not.toContain("regenerate");
+ expect(nextSteps(gen(), 0, 5).map((a) => a.id)).not.toContain("regenerate");
+ });
+});
+
+describe("tools a guest or an account can't open", () => {
+ it("leaves Restore & colourise and Remove dialogue out of a visitor's result menus, and keeps them for the owner", () => {
+ const owner = ids(gen());
+ expect(owner).toContain("restore-video");
+ const visitor = ids(gen(), { visitor: true });
+ expect(visitor).not.toContain("restore-video");
+ expect(visitor).not.toContain("remove-dialogue");
+ expect(ids(upload(), { visitor: true })).not.toContain("restore-video");
+ });
+
+ it("marks their Video tools tabs as the owner's only", () => {
+ const tabs = Object.fromEntries(HUB_MODES["video-tools"].map((m) => [m.id, m.ownerOnly ?? false]));
+ expect(tabs).toMatchObject({ restore: true, "remove-dialogue": true, matte: false, evolution: false });
+ });
+});
diff --cc tests/swap-studio-sharpen.test.ts
index 00000000,a3dc6c11..7ec4a990
mode 000000,100644..100644
--- a/tests/swap-studio-sharpen.test.ts
+++ b/tests/swap-studio-sharpen.test.ts
@@@ -1,0 -1,298 +1,301 @@@
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+ import { NextRequest } from "next/server";
+ import type { SwapProject, SwapTake } from "@/lib/catalog/swap-studio";
+ import type { SwapProjectView } from "@/server/swap-studio";
+
+ vi.setConfig({ testTimeout: 240_000 });
+ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
-// Character Swap Studio's Sharpen (package n7-4-character-swap-2k) through the API in demo mode (no keys, no ComfyUI):
++// Character Swap Studio's Sharpen through the API in demo mode (no keys, no ComfyUI):
+ // the cloud makes each chosen take again at 2K as a version beside it, the assembly uses it once it is picked; and the
-// route under the owner's public sign-up (guests and accounts get own-gpu-tool, as for every studio job).
++// route under public sign-up (guests and accounts get own-gpu-tool, as for every studio job).
++// Your GPU's sizes regenerate with Open-H3 Regenerate, which is switched off for now (REGEN_OFFERED); these tests check
++// them as they run once it is on. tests/regenerate-offered.test.ts checks that nothing offers them while it is off.
++vi.mock("@/lib/catalog/regenerate", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/catalog/regenerate")>()), REGEN_OFFERED: true }));
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-sharpen-"));
+ 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;
+
+ const { setSetting } = await import("@/server/settings");
+ const gens = await import("@/server/generations");
+ const { saveFile } = await import("@/server/storage");
+ const { encodePng } = await import("@/server/png");
+ const projects = await import("@/app/api/swap-studio/projects/route");
+ const project = await import("@/app/api/swap-studio/projects/[id]/route");
+ const clips = await import("@/app/api/swap-studio/projects/[id]/clips/route");
+ const queue = await import("@/app/api/swap-studio/projects/[id]/queue/route");
+ const sharpen = await import("@/app/api/swap-studio/projects/[id]/sharpen/route");
+ const assemble = await import("@/app/api/swap-studio/projects/[id]/assemble/route");
+ const estimate = await import("@/app/api/swap-studio/projects/[id]/estimate/route");
+ const stop = await import("@/app/api/swap-studio/projects/[id]/stop/route");
+ const masks = await import("@/app/api/swap-studio/projects/[id]/masks/route");
+ const genjutsuEstimate = await import("@/app/api/genjutsu/estimate/route");
+
+ const req = (method: string, body?: unknown) => new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+ /** A tiny MP4 header `seconds` long with one `width`×`height` video track: enough for the server's header read. */
+ function mp4(seconds: number, width: number, height: number): Buffer {
+ const box = (type: string, ...body: Buffer[]) => {
+ const data = Buffer.concat(body);
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(8 + data.length);
+ head.write(type, 4, "latin1");
+ return Buffer.concat([head, data]);
+ };
+ const mvhd = Buffer.alloc(100);
+ mvhd.writeUInt32BE(1000, 12);
+ mvhd.writeUInt32BE(seconds * 1000, 16);
+ const tkhd = Buffer.alloc(84);
+ tkhd.writeUInt32BE(0x10000, 40);
+ tkhd.writeUInt32BE(0x10000, 56);
+ tkhd.writeUInt32BE(width << 16, 76);
+ tkhd.writeUInt32BE(height << 16, 80);
+ const mdhd = Buffer.alloc(24);
+ mdhd.writeUInt32BE(1000, 12);
+ mdhd.writeUInt32BE(seconds * 1000, 16);
+ const hdlr = Buffer.alloc(24);
+ hdlr.write("vide", 8, "latin1");
+ const trak = box("trak", box("tkhd", tkhd), box("mdia", box("mdhd", mdhd), box("hdlr", hdlr)));
+ return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isomiso2mp41", "latin1")), box("moov", box("mvhd", mvhd), trak)]);
+ }
+
+ let clip = "";
+ let square = "";
+ let hero = "";
+ beforeAll(() => {
+ setSetting("demoMode", "auto");
+ clip = saveFile({ data: mp4(6, 1920, 1080), contentType: "video/mp4", source: "upload", name: "street.mp4" }).url;
+ square = saveFile({ data: mp4(6, 2048, 2048), contentType: "video/mp4", source: "upload", name: "square.mp4" }).url;
+ hero = saveFile({ data: encodePng({ width: 64, height: 64, data: Buffer.alloc(64 * 64 * 4, 200) }), contentType: "image/png", source: "upload", name: "hero.png" }).url;
+ });
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ async function view(id: string): Promise<SwapProjectView> {
+ const res = await project.GET(req("GET"), ctx(id) as never);
+ expect(res.status).toBe(200);
+ return res.json();
+ }
+ async function patch(id: string, edit: unknown): Promise<SwapProject> {
+ const res = await project.PATCH(req("PATCH", edit), ctx(id) as never);
+ if (res.status !== 200) throw new Error(`${res.status}: ${(await res.json()).error}`);
+ return res.json();
+ }
+ async function post(route: { POST: (r: Request, c: never) => Promise<Response> }, id: string, body: unknown, status = 201) {
+ const res = await route.POST(req("POST", body), ctx(id) as never);
+ const out = await res.json();
+ if (res.status !== status) throw new Error(`${res.status}: ${out.error}`);
+ return out;
+ }
+ async function until(id: string, done: (v: SwapProjectView) => boolean, ms = 150_000): Promise<SwapProjectView> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await view(id);
+ if (done(v)) return v;
+ if (Date.now() > end) throw new Error(`timed out: ${JSON.stringify(Object.values(v.gens).map((g) => g.status))}`);
+ await sleep(300);
+ }
+ }
+
+ describe("Sharpen on the cloud (demo mode)", () => {
+ let id = "";
+
+ it("makes each chosen take again at 2K beside it, priced first; the assembly uses it once picked", async () => {
+ id = (await post(projects, "", { name: "Street", engine: "cloud", character: { image: hero, description: "a chrome robot" } })).id;
+ let p = await post(clips, id, { url: clip, name: "street.mp4" });
+ let c = p.clips[0];
+ expect(c.source).toMatchObject({ width: 1920, height: 1080 });
+ const shot = c.shots[0];
+ p = await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { settings: { useAnchor: false } } });
+ p = await patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 144 } });
+ const seg = p.clips[0].shots[0].segments![0];
+
+ // Nothing chosen yet: Sharpen says so.
+ await expect(post(sharpen, id, { clipId: c.id, tier: "2K" })).rejects.toThrow(/Choose a take for every swapped segment first/);
+ await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: seg.id, mode: "all" });
+ let v = await until(id, (x) => x.project.clips[0].shots[0].segments!.every((g) => !!g.selectedTake && x.gens[g.takes[0].genId!]?.status === "succeeded"));
+ const take = v.project.clips[0].shots[0].segments![0].takes[0];
+
+ // The price: one 6 s take at 2K is 6 whole seconds at $0.1625 (a demo here, so it costs nothing to run).
+ const est = await (await estimate.GET(req("GET"), ctx(id) as never)).json();
+ expect(est.sharpen[c.id]).toMatchObject({ takes: 1, seconds: 6 });
+ expect(Object.keys(est.sharpen[c.id].costUsd)).toEqual(["2K"]);
+
+ // The cloud makes 2K or 4K; 4K adds nothing to a film joined at 1920 × 1080; 1080p isn't on fal.
+ await expect(post(sharpen, id, { clipId: c.id, tier: "1080p" })).rejects.toThrow(/The cloud makes 2K or 4K/);
+ p = await post(sharpen, id, { clipId: c.id, tier: "4K" });
+ let t: SwapTake = p.clips[0].shots[0].segments![0].takes[0];
+ expect(t.finish).toMatchObject({ engine: "cloud", asked: "4K", tier: "2K", use: false });
+ const steps = t.finish!.stepIds!.map((s) => gens.getGeneration(s)!);
+ expect(steps.map((g) => g.modelId)).toEqual(["trim-video", "fuobe-character-swap", "trim-video"]);
+ const swap = steps[1].request;
+ expect(swap.params).toMatchObject({ resolution: "2K", seed: take.seed, duration: 6, sourceDuration: 6 });
+ expect(swap.prompt).toBe(gens.getGeneration(take.stepIds![1])!.request.prompt);
+ expect(swap.loras?.[0]?.file).toMatch(/swap/);
+ // Asked again while it is being made: nothing to do.
+ await expect(post(sharpen, id, { clipId: c.id, tier: "2K" })).rejects.toThrow(/already has a 2K version/);
+
+ v = await until(id, (x) => x.gens[x.project.clips[0].shots[0].segments![0].takes[0].finish!.genId!]?.status === "succeeded");
+ t = v.project.clips[0].shots[0].segments![0].takes[0];
+ c = v.project.clips[0];
+ // Not picked: the assembly is the 768p take.
+ let q = await post(assemble, id, { clipId: c.id });
+ expect(q.clips[0].assembly.takes).toEqual([t.id]);
+ const first = await until(id, (x) => ["succeeded", "failed"].includes(x.gens[x.project.clips[0].assembly!.genId!]?.status ?? ""));
+ const failed = Object.entries(first.gens).filter(([, g]) => g.status === "failed");
+ expect(failed.map(([gid, g]) => `${gens.getGeneration(gid)?.modelId}: ${g.error}`)).toEqual([]);
+ // Picked after comparing: a new assembly with the 2K version in it.
+ await patch(id, { type: "take", clipId: c.id, shotId: shot.id, segmentId: seg.id, takeId: t.id, finishUse: true });
+ q = await post(assemble, id, { clipId: c.id });
+ expect(q.clips[0].assembly.takes).toEqual([`${t.id}@${t.finish!.id}`]);
+ const parts = q.clips[0].assembly.stepIds.map((s: string) => gens.getGeneration(s)!);
+ // The take's piece is the 2K version scaled to the film (1920 × 1080: fal merge-videos' 512–2048 px).
+ const scaled = parts.find((g: { modelId: string }) => g.modelId === "scale-video")!;
+ expect(scaled.request.inputs?.video).toBe(v.gens[t.finish!.genId!].url);
+ expect(scaled.request.params).toMatchObject({ extra: { width: 1920, height: 1080 } });
+ });
+
+ it("only a finished version can be picked, and Stop stops what is being made", async () => {
+ const p = (await view(id)).project;
+ const c = p.clips[0];
+ const shot = c.shots[0];
+ const seg = shot.segments![0];
+ await expect(patch(id, { type: "take", clipId: c.id, shotId: shot.id, segmentId: seg.id, takeId: "take-nope", finishUse: true })).rejects.toThrow(/422/);
+ const r = await post(stop, id, { kind: "finish", clipId: c.id }, 200);
+ expect(r.id).toBe(id);
+ });
+ });
+
+ describe("Sharpen on your GPU (demo mode)", () => {
+ it("a version still being made keeps its take; Sharpen at another size stops it before replacing it", async () => {
+ const id = (await post(projects, "", { name: "Square", engine: "open", character: { image: hero, description: "a knight" } })).id;
+ let p: SwapProject = await post(clips, id, { url: square, name: "square.mp4" });
+ const c = p.clips[0];
+ const shot = c.shots[0];
+ await until(id, (x) => !!x.project.clips[0].normalized?.url);
+ p = await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { settings: { useAnchor: false } } });
+ p = await patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 144 } });
+ const seg = p.clips[0].shots[0].segments![0];
+ p = await patch(id, { type: "segment", clipId: c.id, shotId: shot.id, segmentId: seg.id, patch: { anchorMode: "none" } });
+ // Who to swap: a tracked mask, approved.
+ p = await post(masks, id, { clipId: c.id, shotId: shot.id, kind: "track", frame: 0, points: [{ x: 1024, y: 1024, label: "positive" }] });
+ const m = p.clips[0].shots[0].masks[0];
+ await until(id, (x) => !!x.project.clips[0].shots[0].masks[0].pieces[0]?.url);
+ await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { approvedMask: m.id } });
+ await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: seg.id, mode: "all" });
+ let v = await until(id, (x) => x.project.clips[0].shots[0].segments!.every((g) => !!g.selectedTake && x.gens[g.takes[0].genId!]?.status === "succeeded"));
+ const take = v.project.clips[0].shots[0].segments![0].takes[0];
+ const ref = { clipId: c.id, shotId: shot.id, segmentId: seg.id, takeId: take.id };
+
+ // A 2048 square: 2K adds a little over 1080p (a 2048 × 1170 part is redrawn), and 1080p is the default; 4K adds nothing.
+ const est = await (await estimate.GET(req("GET"), ctx(id) as never)).json();
+ expect(Object.keys(est.sharpen[c.id].costUsd)).toEqual(["1080p", "2K"]);
+ p = await post(sharpen, id, { clipId: c.id, tier: "1080p" });
+ const first = p.clips[0].shots[0].segments![0].takes[0].finish!;
+ expect(first).toMatchObject({ engine: "open", tier: "1080p" });
+ const firstIds = [...first.stepIds!, first.genId!];
+ expect(firstIds.map((g) => gens.getGeneration(g)!.modelId)).toEqual(expect.arrayContaining(["oss-h3-regenerate", "oss-composite-mask"]));
+
+ // While it is being made, its take stays, and so does the shot's layout.
+ await expect(patch(id, { type: "take", ...ref, remove: true })).rejects.toThrow(/sharper version is still being made/);
+ await expect(patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 72 } })).rejects.toThrow(/409/);
+
+ // Sharpen again at 2K: the 1080p version still being made is stopped first, then replaced.
+ p = await post(sharpen, id, { clipId: c.id, tier: "2K" });
+ const second = p.clips[0].shots[0].segments![0].takes[0].finish!;
+ expect(second).toMatchObject({ tier: "2K", asked: "2K" });
+ expect(second.id).not.toBe(first.id);
+ expect(firstIds.map((g) => gens.getGeneration(g)!.status).filter((st) => st === "queued" || st === "running")).toEqual([]);
+ expect(gens.getGeneration(first.genId!)!.status).toBe("canceled");
+ // The 2K version's regenerate is drawn at 1440p.
+ expect(second.stepIds!.map((g) => gens.getGeneration(g)!).find((g) => g.modelId === "oss-h3-regenerate")!.request.params).toMatchObject({ resolution: "1440p" });
+
+ // Stop reaches it; then the take can go.
+ await post(stop, id, { kind: "finish", clipId: c.id }, 200);
+ v = await until(id, (x) => !["queued", "running"].includes(x.gens[x.project.clips[0].shots[0].segments![0].takes[0].finish!.genId!]?.status ?? ""), 20_000);
+ expect(v.gens[second.genId!].status).toBe("canceled");
+ const after = await patch(id, { type: "take", ...ref, remove: true });
+ expect(after.clips[0].shots[0].segments![0].takes.find((t) => t.id === take.id)).toBeUndefined();
+ });
+ });
+
+ describe("Genjutsu's notes for a finishing size", () => {
+ const est = async (body: unknown) => {
+ const res = await genjutsuEstimate.POST(req("POST", body) as never);
+ const out = await res.json();
+ if (res.status !== 200) throw new Error(`${res.status}: ${out.error}`);
+ return out as { notes: string[]; quality?: string };
+ };
+ const base = (engine: string, quality: string, over: Record<string, unknown> = {}) => ({
+ engine,
+ mode: "character",
+ references: [hero],
+ quality,
+ source: { url: clip, name: "street.mp4", duration: 30, fps: 30, width: 3840, height: 2160, hasAudio: true },
+ range: { start: 0, end: 10 },
+ ...over,
+ });
+
+ it("your GPU names the clip's own size and the 2048 px join when it sharpens at a smaller size", async () => {
+ const e = await est(base("open", "4K"));
+ expect(e.notes).toContain("Your clip is 3840×2160, joined at 2048×1152 (up to 2048 px a side), and your character is redrawn in a 1964×1122 part of it, so it is sharpened at 2K");
+ expect(e.notes.join(" ")).not.toMatch(/never above the clip's own size/);
+ });
+
+ it("the cloud's 4K over 15 s says its pieces are joined at up to 2048 px a side; a single piece doesn't", async () => {
+ const long = await est(base("cloud", "4K", { range: { start: 0, end: 20 } }));
+ expect(long.notes).toContain("A part over 15 s is made in pieces, and the pieces are joined at up to 2048 px a side");
+ const short = await est(base("cloud", "4K"));
+ expect(short.notes.join(" ")).not.toMatch(/joined at up to 2048/);
+ const k2 = await est(base("cloud", "2K", { range: { start: 0, end: 20 } }));
+ expect(k2.notes.join(" ")).not.toMatch(/joined at up to 2048/);
+ });
+ });
+
-describe("the route under the owner's public sign-up", () => {
++describe("the route under public sign-up", () => {
+ it("gives guests and accounts own-gpu-tool (a studio job, like Assemble), and the owner the route", async () => {
+ process.env.FUOBE_PASSWORD = "install password";
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ try {
+ const auth = await import("@/server/auth");
+ const { proxy } = await import("@/proxy");
+ const access = await import("@/lib/guest-access");
+ const account = auth.createAccount("[email protected]", "long enough");
+ const cookie = auth.createSession(account.id).value;
+ auth.setAccountGpu(account.id, { url: "https://gpu.example" });
+ const at = (url: string, c?: string) => new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: c ? { cookie: `${auth.SESSION_COOKIE}=${c}` } : {}, body: "{}" });
+ for (const p of ["/api/swap-studio/projects/swap-1/sharpen", "/api/swap-studio/projects/swap-1/assemble", "/api/genjutsu"]) {
+ for (const c of [undefined, cookie]) {
+ const r = proxy(at(p, c));
+ expect(r.status, `${p} ${c ? "account" : "guest"}`).toBe(403);
+ expect(await r.json()).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });
+ }
+ }
+ // Genjutsu's price check (2K included) stays open to visitors.
+ expect(access.isPriceCheck("POST", "/api/genjutsu/estimate", "")).toBe(true);
+ expect(proxy(at("/api/genjutsu/estimate")).headers.get("x-middleware-next")).toBe("1");
+ } finally {
+ delete process.env.FUOBE_PASSWORD;
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+ }
+ });
+
+ it("an account's composite through /api/generations reads only its own files", async () => {
+ const auth = await import("@/server/auth");
+ const { accountInputProblem } = await import("@/server/account-inputs");
+ const a = auth.createAccount("[email protected]", "long enough");
+ const own = saveFile({ data: mp4(3, 1920, 1080), contentType: "video/mp4", source: "upload", name: "mine.mp4", accountId: a.id }).url;
+ const request = (videos: string[], mask: string) => ({ inputs: { videos, mask }, params: { extra: { windowStart: 0, takeStart: 0, maskStart: 0 } } });
+ expect(accountInputProblem(request([own, own, own], own), a.id)).toBeNull();
+ // The owner's footage, or a link, is refused.
+ expect(accountInputProblem(request([clip, own, own], own), a.id)).toMatchObject({ code: "input-not-yours" });
+ expect(accountInputProblem(request([own, own, own], "https://x.example/m.mp4"), a.id)).toMatchObject({ code: "input-not-allowed" });
+ });
+ });