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 origin/main into local/premium-previews-llm-3d

Adarsh86d06482a1c0
diff --cc README.md
index e636503f,658bd37f..36f46895
--- a/README.md
+++ b/README.md
@@@ -1,22 -1,38 +1,38 @@@
# Fuobe
**An open-source AI image, video and audio studio — a 1:1 alternative to Higgsfield.**
- Use the same frontier paid models Higgsfield uses (Nano Banana Pro, Seedance 2.5, Kling 3.0, Veo 3.1, Seedream 5, GPT Image 2.5, FLUX.3, Gemini Omni, MiniMax, ElevenLabs…, and Higgsfield's own Soul and Cinema Studio) with your own fal.ai / Replicate / Higgsfield key, **or** run the equivalent open-weight workflows on your own GPU through **ComfyUI**. Same studio, same apps, same camera motions — flip one switch.
-
- - **Assist:** describe the whole job in a chat; the agent picks models, shows the plan and its cost, runs it when you approve, checks the results and chains the next step. Free / Smart / Manual modes, 20 built-in **skills** (SKILL.md playbooks, or upload your own), **projects** with instructions and up to 20 sources (links, files and PDFs, elements, notes), and **memory**. Runs on Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or an offline planner
- - **MCP:** other agents (Claude Code, Claude Desktop, any MCP client) can drive the studio through `/api/mcp`, including whole studio jobs (layers, restyle, dub, faceless episode, ads, captions, Katana; they run as plain pipelines and don't open a studio session yet) and the skills as prompts
- - **Create:** Image · Video (text, image, start/end frame, reference images and clips, multi-shot, draft mode) · Edit · **Layers** (split a flat image into editable layers, edit text, regional edits, cropped or positioned zips) · Inpaint & Draw to Edit · Color grading · Camera motions · Effects · Storyboard (and turn it into a film) · **Canvas** (wire prompts, files and models into node workflows; every template in a cloud and an open-source version) · Apps
+ Use the same frontier paid models Higgsfield uses (Nano Banana Pro, Seedance 2.5, Kling 3.0, Veo 3.1, Seedream 5, GPT Image 2.5, FLUX.3, Gemini Omni, MiniMax, ElevenLabs…) with your own fal.ai / Replicate key, **or** run the equivalent open-weight workflows on your own GPU through **ComfyUI**. Same studio, same apps, same camera motions — flip one switch. Fuobe's own rebuilds of Higgsfield's in-house models, the **Fuobe Originals** (Fuobe Soul, DoP, Cinema and Genjutsu so far, plus Soul ID training), run either way. Higgsfield is never called: Soul, Cinema Studio and Genjutsu runs, saved setups and Assist plans from before open on the Original that replaced them. Licences are information, not gates: **Settings → Models & licences** shows the licence of every model, LoRA and node pack, everything starts switched on, and whoever runs the install switches off what doesn't fit.
+
-- **Assist:** describe the whole job in a chat; the agent picks models, shows the plan and its cost, runs it when you approve, checks the results and chains the next step. Free / Smart / Manual modes, 20 built-in **skills** (SKILL.md playbooks, or upload your own), **projects** with instructions and up to 20 sources (links, files and PDFs, elements, notes), and **memory**. **Scheduled tasks** run a request daily, weekly, every 1–168 hours or once, in your time zone; each run is a new chat that asks before it generates, or runs on its own within a cost cap ($2 a run by default). Your own **MCP connectors** (remote MCP servers, added in Settings → Assist · connectors) give Claude chats another app's tools: Anthropic's servers call them, so a local one needs a public tunnel, and their tools run without asking Fuobe, so each connector's Allowed tools list is the safeguard. Runs on Claude, a local Ollama model, or an offline planner (connectors need Claude)
++- **Assist:** describe the whole job in a chat; the agent picks models, shows the plan and its cost, runs it when you approve, checks the results and chains the next step. Free / Smart / Manual modes, 20 built-in **skills** (SKILL.md playbooks, or upload your own), **projects** with instructions and up to 20 sources (links, files and PDFs, elements, notes), and **memory**. **Scheduled tasks** run a request daily, weekly, every 1–168 hours or once, in your time zone; each run is a new chat that asks before it generates, or runs on its own within a cost cap ($2 a run by default). Your own **MCP connectors** (remote MCP servers, added in Settings → Assist · connectors) give Claude chats another app's tools: Anthropic's servers call them, so a local one needs a public tunnel, and their tools run without asking Fuobe, so each connector's Allowed tools list is the safeguard. Runs on Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or an offline planner (connectors need Claude)
+ - **MCP:** other agents (Claude Code, Claude Desktop, any MCP client) can drive the studio through `/api/mcp`, including whole studio jobs that open in their studio (a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor, a Katana edit; Genjutsu, the Character Swap Studio, Remove object, Content Factory, the AI Influencer builder and Layers' Inpaint, Enhancer and Save as element aren't tools yet) and the skills as prompts. `npx skills add workingprototype/Fuobe` installs the skills in other agents
+ - **Command line:** `fuobe` lists models, prices a run, generates, waits and downloads from a terminal, a script or a coding agent; see [`docs/cli.md`](docs/cli.md). `--engine` also picks an Original's engine, and `--look` a Fuobe Soul look (`fuobe generate --help` lists it; cli.md doesn't yet)
+ - **Fuobe Originals:** each is one model that runs on both engines, built on open-weight models and public LoRAs: free on your GPU through ComfyUI, or paid on fal or Replicate, with no Higgsfield call
+ - **Fuobe Soul**, **Fuobe Soul HD** and **Fuobe Soul Cinema** (Image studio) — a Look picker with 139 looks in two sets named after Higgsfield's versions (Soul 2.0: 33, Soul: 106), with categories, search, drawn covers and a Strength slider. Attach a picture and Fuobe Soul restyles it with the look. Soul HD (Qwen-Image 2512) is for lettering; Soul Cinema has one film look and 21:9. Your browser finishes each result (crop, grade, overlays such as DigitalCam's date stamp) and keeps the raw picture. 87 looks use civitai LoRAs: without a civitai key, a run leaves those out and says so
+ - **Fuobe DoP** (Wan 2.2) and **Fuobe DoP · LTX** (LTX-2.3) — the camera motions and effects as recipes: a move's LoRAs, a camera LoRA or (on your GPU) a Fun Camera pose, a colour grade or a relight where it has one, else its words. On the open engine, picking a move in the Video studio switches to the model it runs on (a few run on LTX-2.5). In the cloud, 152 of the 363 motions and effects use DoP's routes and switch the same way; the other 211 only add their words to the model you picked (their own route is Kling 2.5 Turbo). 15 colour-grade effects hand the clip to Color grading with the grade picked, 6 relight effects relight the start frame first, and Mix stacks both presets' LoRAs on either engine
+ - **Fuobe Cinema** (Cinema Studio's video default) — Wan 2.2 14B Lightning free on your GPU (3 or 5 s, no sound), or LTX-2.3 on fal with sound and its built-in camera LoRAs (4–30 s: one call makes up to 20 s, and a longer take gets an automatic extend). In the cloud, 14 of Cinema's 33 camera moves use LTX-2.3's camera LoRA, start frame or not; with a start frame, a move with a Wan 2.2 LoRA switches the take to Fuobe DoP, and Rack Focus uses LTX-2.5 Fast's focus move. On your GPU, with a start frame, a move takes its Wan 2.2 LoRA or a Fun Camera pose. Otherwise the move goes into the prompt
+ - **Fuobe Genjutsu** (Motion, Swap and Restyle; Motion and Swap also come in a cheaper, faster Standard quality) and **Fuobe Character swap** — Genjutsu's defaults: Wan Animate for motion transfer, SAM 3.1 and Wan VACE for object swap, Wan 2.2 Fun VACE for restyle, and MiniMax H3 with Akatz Labs' Character Swap LoRA for Character swap
+ - **Fuobe Soul ID** — train a character or a look as a LoRA, free on your GPU through AI-Toolkit or on fal's trainers (see Elements below)
+ - Built and checked in demo mode; no look, move, take, swap or training has run on a GPU or with a paid key yet, so their quality is unmeasured, and the three MiniMax H3 graphs have never loaded in a ComfyUI
+ - **Create:** Image · Video (text, image, start/end frame, **Frames**: up to 10 stills on a timeline, reference images and clips, multi-shot, draft mode) · Edit · **Layers** (split a flat image into editable layers, edit text with the lines found for you on either engine, Inpaint a painted area, an Enhancer (skin, soft glow, sharpen, detail), regional edits, save a layer as an element, cropped or positioned zips) · Inpaint & Draw to Edit · Color grading · Camera motions and Effects (on Fuobe DoP) · Storyboard (and turn it into a film) · **Canvas** (wire prompts, files and models into node workflows; every template in a cloud and an open-source version; up to 20 pages per board, groups you can run as one, comment pins with replies, and drawing, shapes and text from a toolbar with keys; a Table node runs the node it feeds once per row; Change voice, Clone voice, Translate (text, or a dub of a video) and Video concatenator (cut, mute and join up to 50 clips) nodes) · Apps
- **Studios:**
- - **Cinema Studio** — projects and scenes, Director's Panel (camera, lens, 50 palettes, lighting rig, Emotion Wheel), 33 camera moves (# in the prompt bar), AI Director, image grids, Soul Cast and Soul Location
- - **Shorts Studio** — restyle up to 2 minutes of your own footage with 44 looks (or your own references), in segments you can regenerate, stitched back under your sound; **Mixed Media** — 33 looks for 1–10 s clips with per-preset settings and a preview frame
- - **Marketing Studio** (84 templates), **Click to Ad**, **Ads Studio** (brand kit from your website, up to 20 ads per product in 1:1 / 4:5 / 9:16) and **Ad Multiplier**
- - **Moodboards**, **Color signature** (Soul HEX palettes), **Photodump / Instadump**, **Fashion Factory**, **Character Sheet**
- - **Faceless Studio** and **Explainer** — channels, scripts, narrated and subtitled episodes with a timeline editor
- - **Translate & dub** (your voice, lip-synced, over the original background on the open engine), **Captions** (transcribe, edit, burn in), **Trim**, **Katana** (recreate a reference edit with your subject), **Image to 3D**, Lipsync & avatars, Motion control, Edit / Extend / Reframe video, Video tools (matte, relight, depth, join clips, match colors), Upscale, Audio (speech with voice picker and cloning, dialogue, voice change, sound effects, music, sound for video), and a Virality predictor (a labelled heuristic)
- - **Library:** all your results (images, videos, audio, text, 3D) with layouts, filters, folders, bulk zip download and a Trash with 30-day restore; results arrive live
- - **Elements:** save characters, locations, props, styles and voices once, then `@mention` them in any prompt; train a character (Soul ID, a fal LoRA, or AI-Toolkit on your GPU) for a consistent face
- - **Catalog:** 157 cloud models + 73 open-source models (plus 32 hidden ones: chain steps, self-tests, browser tools, and four open models no studio offers yet), 123 apps, 108 camera motions (mix any two), 255 effects
- - **Open-source engine:** 115 API-format ComfyUI workflows (official templates, community packs and hand-built graphs) validated against real ComfyUI node definitions, plus 43 researched LoRAs (camera moves, VFX) attached to 55 motion, effect and app presets
+ - **Cinema Studio** — projects and scenes, Director's Panel (camera, lens, 50 palettes, lighting rig, Emotion Wheel), 33 camera moves (# in the prompt bar), AI Director, image grids, Soul Cast and Soul Location, and **3D scenes**: turn a still into a scene you fly through, set the lens and frame, and Capture a re-rendered take from that view. Takes run on Fuobe Cinema by default on both engines (Seedance 2.5, Kling 3.0 and Veo 3.1 stay in the cloud menu, LTX-2.5 and Wan 2.2 14B on your GPU), stills on Fuobe Soul Cinema, Soul Cast on Fuobe Soul in the cloud (the Soul Cast sheet on your GPU) and Soul Location on Fuobe Soul. A project can be shared as a read-only link
+ - **Shorts Studio** — restyle up to 2 minutes of your own footage with 44 looks (or your own references), in segments you can regenerate, stitched back under your sound; **Mixed Media** — 33 looks for 1–10 s clips with per-preset settings and a preview frame; on the cloud the clip's frames are sampled at the rate you pick (4–24 FPS) and each one is redrawn by default (Nano Banana 2 or Seedream 5.0 Flash, priced per frame), and **Fast** restyles in one video-to-video pass
+ - **Genjutsu** — keep a 4–30 s clip's motion, camera and framing and change what is in it: motion transfer, **Character swap**, object swap, restyle (44 looks, Fuobe Soul's 139 or your own images) or insert, with reference images, priced before it runs. Every mode but Insert defaults to a Fuobe Original on both engines, and the picker shows each model's source (Original, open weights or partner) and licence. Character swap turns the person in a 5–15 s part of one shot (up to 30 s, in pieces or windows) into your character from one image, keeping the performance and the sound: pick who (largest, leftmost, rightmost, a number or, on your GPU, a click), 480p or 768p, and by default your character goes into the first frame first; "Describe my character" and "Use the clip's words" help write the prompt. For whole clips, **Open in Character Swap Studio** takes the clip and the character there
+ - **Character Swap Studio** (`/character-swap`) — Akatz Labs' H3 Character Swap workbench, rebuilt in Fuobe on MiniMax H3: put your character into whole clips, shot by shot, and get each clip back with its own timing and sound. A project holds one character (a picture and a description) and up to 20 clips (.mp4, .mov, .mkv, .webm or .avi, each up to 149.66 s and 200 MB), worked through seven stages: **Shots** (Detect edits finds the cuts in your browser; mark each shot Replace character or Keep original), **Words** (transcribe, say who speaks each line, build the shot prompts), **Who to swap** (largest, leftmost, rightmost, person #n or words, plus clicks on any frame, giving mask versions you approve), **Scene anchors** (make or import a still of the scene with your character in it), **Segments** (5, 10 or 15 s, each starting fresh or continuing the one before; a continuation starts itself when that take is done, even with the page closed), **Takes & review** (several takes, Compare, Keep / Maybe / Skip with notes, Export decisions) and **Assemble** (the chosen takes over the original timeline with the clip's sound, to download and in the Library). Prices show before anything runs (only a cloud browser copy of a clip your browser can't play, and anchors on GPT Image 2.5 Sunburst, which bill by tokens, are left out of the estimate), and demo mode runs the whole flow for free. On your GPU, H3 Relay 2.0 swaps only the person in your approved mask, matches the anchor and continues from the take before (free; a 24 GB GPU and the opt-in H3 Relay pack). In the cloud, fal's MiniMax H3 with Akatz Labs' swap LoRA ($0.075/s at 768p, $0.0625/s at 480p) has no mask: the whole frame is regenerated and who to swap goes into the prompt. Built and checked in demo mode only: nothing has run on a GPU or with a fal key, its two GPU graphs have never loaded in a ComfyUI, and the Finish stage (a clean background plate and cut-outs) shows as not available
+ - **Marketing Studio** (84 templates), **Click to Ad** (with a logo end card), **Ads Studio** (brand kit from your website, up to 20 ads per product in 1:1 / 4:5 / 9:16, each one written copy and one picture laid out in your browser with your logo, colours and fonts) and **Ad Multiplier** (whole-ad edits in the cloud on Kling O3 or Happy Horse video edit, which keep the sound and recreate up to 15 s, or Gemini Omni Flash)
+ - **Moodboards** (the curated looks open on Fuobe Soul; **Train as a look…** trains a board into a look of its own for Fuobe Soul, on either engine), **Color signature** (Soul HEX palettes; with a Fuobe Soul model on the open engine, the colours are locked after generating by default), **Photodump / Instadump** and **Fashion Factory** (a character with a Soul ID runs on Fuobe Soul), **Character Sheet**
+ - **AI Influencer** builder — build a character game-style: a character type (Average, Bold or Extreme human, or a creature: insect, frog, cat, dog, rodent or bird) and traits in 18 categories, with Shuffle, then save the sheet as a character
+ - **Faceless Studio** and **Explainer** — channels, scripts, narrated and subtitled episodes with a timeline editor; "Frame by frame" moves the camera slowly over each still (a Ken Burns move), the music loops to cover long films, and Explainer reads PDF and Word sources
+ - **Content Factory** — a faceless series in the style of a clip you like: upload it, paste a TikTok, Instagram or web-page link, or pick one of 8 preset styles. Fuobe reads it into a style brief you can edit, prices the whole series, then makes 1–10 Faceless episodes of 30 s to 5 min here, or gives you a prompt for Claude Code to make them through Fuobe's MCP server
- - **Translate & dub** (your voice, lip-synced, over the original music and effects on both engines), **Captions** (transcribe, edit, burn in), **Trim**, **Katana** (recreate a reference edit with your subject; Fuobe Genjutsu · Motion is one of its motion models, the default on your GPU), **Image to 3D** (from one photo, several photos of one object, words or an object picked in a photo, or one photo as a Gaussian splat to open in a splat viewer such as SuperSplat; Rig & animate a finished model; Pick an object and Rig & animate run on the cloud only), Lipsync & avatars, Motion control, Edit / Extend / Reframe video, Video tools (**Remove object**: type it, paint it or, on the cloud, click it, and it's erased from the clip; on your GPU, **H3 Person Removal** erases a person you name, with the opt-in H3 Relay pack; matte, relight, depth, join clips, match colors), Upscale (images and video, **FPS Boost** and slow motion, **SDR to HDR**, and **Export** to ProRes, H.265 10-bit, FFV1 or EXR frames on the open engine), Audio (speech with voice picker and cloning, dialogue, voice change, sound effects, music, sound for video, transcribe, **loop / extend** and **join**), and a Virality predictor (a labelled heuristic)
++ - **Translate & dub** (your voice, lip-synced, over the original music and effects on both engines), **Captions** (transcribe, edit, burn in), **Trim**, **Katana** (recreate a reference edit with your subject; Fuobe Genjutsu · Motion is one of its motion models, the default on your GPU), **Image to 3D** (from one photo, several photos of one object, words or an object picked in a photo, or one photo as a Gaussian splat to open in a splat viewer such as SuperSplat; Rig & animate a finished model; Pick an object and Rig & animate run on the cloud only; on your GPU one photo goes to Pixal3D by default, and the server finishes each model for the web and renders its turntable on the CPU), Lipsync & avatars, Motion control, Edit / Extend / Reframe video, Video tools (**Remove object**: type it, paint it or, on the cloud, click it, and it's erased from the clip; on your GPU, **H3 Person Removal** erases a person you name, with the opt-in H3 Relay pack; matte, relight, depth, join clips, match colors), Upscale (images and video, **FPS Boost** and slow motion, **SDR to HDR**, and **Export** to ProRes, H.265 10-bit, FFV1 or EXR frames on the open engine), Audio (speech with voice picker and cloning, dialogue, voice change, sound effects, music, sound for video, transcribe, **loop / extend** and **join**), and a Virality predictor (a labelled heuristic)
+ - **Library:** all your results (images, videos, audio, text, 3D) with layouts, filters, nested folders, pins, a review status (In progress, Needs review, Approved, Rejected), Select all, bulk zip download and a Trash with 30-day restore. Helper steps stay hidden until you ask (Show steps), and an upload is deleted only when nothing uses it. Results arrive live, and a browser notification can tell you when a job finishes while Fuobe is in the background. **Share link…** on a result, a folder (with its subfolders) or a Cinema project makes a read-only page: choose a title, whether prompts show, and how long the link works (always, 1, 7 or 30 days). **Publish** turns selected results into a portfolio page (Feature, Series or Carousel, with a cover). The **Shared** tab lists your links with their views, to make a new link, hide prompts, re-date or revoke. A link opens without signing in, for anyone who can reach your Fuobe (Fuobe doesn't host these pages), and shared files have their embedded generation data blanked (ComfyUI workflows, video tags, EXIF). Canvas boards can't be shared yet
+ - **Getting around:** a **Get started** card on Home and Settings (use paid models, use your GPU, or just try the demo); a **⌘K / Ctrl+K palette** that searches pages, settings, apps, motions, effects, models and recent creations; Start on Home runs the job and says first what it costs; **Settings → About & licences** lists every open model's licence
-- **Models & licences:** **Settings → Models & licences** (`/settings/models`, also from ⌘K, About & licences and the Models page) shows the licence of every model, LoRA and ComfyUI node pack, with switches per licence class, provider, node pack, LoRA and model. Everything is on by default, and LoRAs licensed for your GPU only go to fal or Replicate with a note unless you turn on **Keep them on your GPU**. A model you switch off leaves every picker and listing (studios, Canvas, Cinema, ⌘K, the API and CLI, Assist and Fuobe's MCP server); automatic picks move to the next model that is on, and a run that can't is refused, naming the switch. Anyone who can sign in can change it, and trainings and Assist's own Claude or Ollama calls aren't under the switches
++- **Models & licences:** **Settings → Models & licences** (`/settings/models`, also from ⌘K, About & licences and the Models page) shows the licence of every model, LoRA and ComfyUI node pack, with switches per licence class, provider, node pack, LoRA and model. Everything is on by default, and LoRAs licensed for your GPU only go to fal or Replicate with a note unless you turn on **Keep them on your GPU**. A model you switch off leaves every picker and listing (studios, Canvas, Cinema, ⌘K, the API and CLI, Assist and Fuobe's MCP server); automatic picks move to the next model that is on, and a run that can't is refused, naming the switch. Anyone who can sign in can change it, and trainings and Assist's own Claude or local-model calls aren't under the switches
+ - **Elements:** save characters, locations, props, styles and voices once, then `@mention` them in any prompt; save one straight from a Layers layer or an AI Influencer sheet. **Train** a character (with a consent tick) or a style as a **Fuobe Soul ID** from 5 to 80 photos (20 or more recommended): free on your GPU through AI-Toolkit, or on fal's trainers (about $1.50 to $6.40, priced first). It trains for one base: Z-Image Turbo (Fuobe Soul and Soul Cinema), Qwen-Image 2512 (Fuobe Soul HD), FLUX.1 [dev] and Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 4B, and, on fal only, FLUX.2 [klein] 9B and Krea 2 (the klein and Krea 2 LoRAs run in the cloud only); the dialog shows each option's engine, price, time and licence. The LoRA then works on every model of that base, on both engines where the base has both, whenever you @mention the element. With no fal key and no AI-Toolkit (and Demo mode on "auto", the default), a training is an 8-second demo that trains nothing, and the dialog says so. An old Soul ID from Higgsfield offers "Retrain for Fuobe Soul" (Higgsfield's Soul IDs can't be exported)
+ - **LoRAs:** small add-on files that give an open model a look, a camera move or an effect. **Settings → LoRAs** lists a library of 114 researched LoRAs (67 looks, 23 motions, 24 effects) with each one's licence and source, and downloads them. On the open engine, a LoRA ComfyUI doesn't have is downloaded into your LoRA folder before the run and checked against its SHA-256 fingerprint. On the cloud, twelve hosted models take LoRAs: Z-Image Turbo (hosted, on fal and Replicate), Qwen-Image 2512, Qwen-Image-Edit 2511, FLUX.2 [klein] 4B, Wan 2.2 A14B image and video, LTX-2.3 22B, and, for Soul ID LoRAs, FLUX.1 [dev], FLUX.1 Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 9B and Krea 2 Turbo. The Fuobe Originals' cloud routes send their looks' and moves' LoRAs too (Character swap sends Akatz Labs' swap LoRA), and a LoRA a run can't carry is left out with a warning. Fuobe Soul's looks take their LoRAs from the library, and a motion's or effect's LoRA that is in the library uses its pinned download and licence
-- **Catalog:** 197 cloud models + 90 open-source models + 12 Fuobe Originals that run on both (plus 50 hidden ones: chain steps and studio helpers, self-tests, browser tools, and Gemma 4 speech translate, which no studio uses yet), 124 apps, 108 camera motions (mix any two), 255 effects
-- **Open-source engine:** 150 API-format ComfyUI workflows (official templates, community packs and hand-built graphs), 145 of them validated against real ComfyUI node definitions (the three MiniMax H3 graphs and the Character Swap Studio's two H3 Relay graphs need node packs the validation server doesn't have), plus 84 researched LoRAs (camera moves, VFX) that 122 motion, effect and app presets use today (43 of them are also in the Settings → LoRAs library, and 36 come from civitai)
++- **Catalog:** 197 cloud models + 91 open-source models + 12 Fuobe Originals that run on both (plus 50 hidden ones: chain steps and studio helpers, self-tests, browser tools, and Gemma 4 speech translate, which no studio uses yet), 124 apps, 108 camera motions (mix any two), 255 effects; 480 of their cards show a cover rendered on a GPU (6 of them short clips), the rest a drawn preview
++- **Open-source engine:** 151 API-format ComfyUI workflows (official templates, community packs and hand-built graphs), 146 of them validated against real ComfyUI node definitions (the three MiniMax H3 graphs and the Character Swap Studio's two H3 Relay graphs need node packs the validation server doesn't have), plus 84 researched LoRAs (camera moves, VFX) that 122 motion, effect and app presets use today (43 of them are also in the Settings → LoRAs library, and 36 come from civitai)
+ - **Evaluation harness (for developers):** `pnpm eval:run` (or `fuobe eval`) runs a suite of cases for each Fuobe Original, built or planned (Fuobe's own open-weight versions of Higgsfield's in-house models, such as Soul and DoP) on the demo, open or cloud engine, scores the results with pinned open models, runs a blind A/B review and says whether a recipe may become a default. Fuobe Soul, DoP, Cinema, Genjutsu and Soul ID are in the app now, and their suites run the shipped models too (with `soul-cinema`, `soul-hex` and `dop-mix` suites and a palette metric; since PR #12 the `cinema` suite has Director scenes and LTX-2.3 camera moves, `genjutsu` has Character swap and the Lite tiers, and `soul-id` trains per base and as a look, and needs your own photos of a person who agreed); the other Originals' suites measure their recipes on models already in the catalog, and cases that need the Original itself are skipped. Cloud runs are priced first and capped (default $5), and Higgsfield is never called. A recipe's licences are a note on its verdict, not a hold (`eval:promote --licence-hold` restores the hold, and `--commercial-only` keeps non-commercial metric models and covers out). Nothing has been measured on a GPU or the cloud yet; see [`scripts/eval/README.md`](scripts/eval/README.md)
- **No keys? No GPU?** Demo mode lets you click through everything with clearly-labelled placeholder outputs.
> Project status, what works, what's verified and what's left: **[docs/STATUS.md](docs/STATUS.md)** (also in-app at `/status`).
@@@ -42,20 -58,17 +58,22 @@@ The mode can also be set with `FUOBE_EN
| You have | What to set | You get |
|---|---|---|
- | A [fal.ai](https://fal.ai/dashboard/keys) key | `fal.ai API key` (or `FAL_KEY`) | Every cloud model and cloud app |
- | A Replicate token | `Replicate API token` (or `REPLICATE_API_TOKEN`) | Fallback route for models Replicate hosts; **Preferred provider** (or `FUOBE_CLOUD_PROVIDER`: `auto`, `fal`, `replicate` or `higgsfield`) picks which one goes first |
- | A [Higgsfield API](https://console.higgsfield.ai) key | `Higgsfield API key` as `KEY_ID:KEY_SECRET` (or `HIGGSFIELD_API_KEY`, `HF_KEY`, or `HF_API_KEY` + `HF_API_SECRET`) | Soul 2.0 / Soul Cinema / Soul v1 with live presets, Soul ID training, Genjutsu, Cinema Studio 4.0, Marketing Studio, Ads Studio, plus extra routes for Seedance, Kling, Wan, MiniMax… |
+ | A [fal.ai](https://fal.ai/dashboard/keys) key | `fal.ai API key` (or `FAL_KEY`) | Every cloud model and cloud app, and Soul ID training in the cloud |
+ | A Replicate token | `Replicate API token` (or `REPLICATE_API_TOKEN`) | Fallback route for models Replicate hosts; **Preferred provider** (or `FUOBE_CLOUD_PROVIDER`: `auto`, `fal` or `replicate`) picks which one goes first, unless only the other can carry the run's LoRAs or make the clip length asked |
| A GPU running ComfyUI | `ComfyUI server URL` (or `COMFYUI_URL`, default `http://127.0.0.1:8188`; `COMFYUI_TOKEN` if it sits behind a proxy) | Every open-source model, app, motion, effect and studio route |
- | An Anthropic key | `Anthropic API key` (or `ANTHROPIC_API_KEY`) | The full **Assist** agent (Smart and Manual modes), text steps (translate, write, scripts, ad copy, brand research), prompt **Enhance** and storyboard splitting with Claude |
+ | An Anthropic key | `Anthropic API key` (or `ANTHROPIC_API_KEY`) | The full **Assist** agent (Smart and Manual modes, scheduled tasks that plan with Claude, and your MCP connectors), text steps (translate, write, scripts, ad copy, brand research), prompt **Enhance**, storyboard splitting and Genjutsu's "Describe my character" with Claude |
-| Ollama | `Prompt enhancement` → Ollama (`OLLAMA_URL`, `OLLAMA_MODEL`, default `qwen3:8b`; `FUOBE_ENHANCE_PROVIDER`) | The same text steps and the Assist agent on a local model (tool calling) |
+| [Ollama](https://ollama.com) | **AI helper** → Local model server → Ollama or Automatic (`OLLAMA_URL`, `OLLAMA_MODEL`, default `qwen3:8b`) | The same text steps and the Assist agent on a local model (tool calling) |
+| [LM Studio](https://lmstudio.ai) 0.4 or later | **AI helper** → LM Studio or Automatic (`LMSTUDIO_URL`, default `http://127.0.0.1:1234`; `LMSTUDIO_MODEL`, empty for the loaded model; `LMSTUDIO_API_TOKEN` only when its Require Authentication is on). In LM Studio, start the server (Developer → Start server, or `lms server start`) and download a model (`lms get qwen/qwen3-8b`) | The same on LM Studio. A model that isn't loaded yet is loaded with 16k context (`FUOBE_LLM_CONTEXT`), which Assist's tools need |
+| [Unsloth Studio](https://unsloth.ai/docs/new/studio/install) | **AI helper** → Unsloth Studio or Automatic (`UNSLOTH_URL`, default `http://127.0.0.1:8888`; `UNSLOTH_API_KEY`: an `sk-unsloth-…` key from avatar → Settings → API; `UNSLOTH_MODEL`, empty for the loaded model). Load a model on its Chat page | The same on the model loaded in Unsloth Studio. Its server-side tools (Python, terminal, web search) are always off for Fuobe's calls |
+| Another OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…) | **AI helper** → Other (`FUOBE_LLM_URL`, the base URL such as `http://127.0.0.1:8080/v1`; `FUOBE_LLM_MODEL`; `FUOBE_LLM_API_KEY`) | The same on that server |
- | AI-Toolkit (ostris) on your GPU | `AI_TOOLKIT_URL` (+ `AI_TOOLKIT_AUTH`, `AI_TOOLKIT_DATASET_DIR`) and `COMFYUI_LORAS_DIR` | Train character and style LoRAs from an element's photos or a moodboard; the result is copied into ComfyUI and used whenever you @mention it |
+ | A LoRA folder (and a civitai account) | **Settings → LoRAs**: `LoRA folder`, ComfyUI's `models/loras` (or `COMFYUI_LORAS_DIR`), and `civitai API key` (or `CIVITAI_API_KEY`) | Fuobe downloads a LoRA ComfyUI doesn't have before the run and checks its fingerprint. 72 of the 114 library LoRAs are on civitai and need the key, which is never sent to fal or Replicate. 87 of Fuobe Soul's looks use one, and 36 of the motions' and effects' LoRA files are among them |
+ | AI-Toolkit (ostris) on your GPU | `AI_TOOLKIT_URL` (+ `AI_TOOLKIT_AUTH`, `AI_TOOLKIT_DATASET_DIR`; the Settings page has no field for them, so set the environment variables or `PUT /api/settings`) and `COMFYUI_LORAS_DIR` | Free Soul ID training of characters and styles from an element's photos or a moodboard, on Z-Image Turbo, Qwen-Image 2512, FLUX.1 [dev], FLUX.2 [dev] or FLUX.2 [klein] 4B (AI-Toolkit downloads the base weights itself; the FLUX [dev] repos need a Hugging Face token). Fuobe keeps the LoRA and copies it into ComfyUI (from an AI-Toolkit on another machine, copy it by hand). The training dialog can also download a training kit to run anywhere |
+
++**AI helper** picks who writes: Automatic (Claude when a key is set, else a local model, else the offline rewriter), Claude, a local model only, or offline (`FUOBE_ENHANCE_PROVIDER=auto|anthropic|local|none`; the old value `ollama` means `local`). Its local model server is Automatic by default (`FUOBE_LLM_PROVIDER=auto`): the first one that answers with a model, in the order Ollama, LM Studio, Unsloth Studio, then the Other URL. `FUOBE_LLM_PROVIDER=ollama|lmstudio|unsloth|custom` pins one. Settings → AI helper shows what each server answers (its models, whether one is loaded, what's missing) and has a **Send a test message** button for each server, which proves its model answers. The local model shares the GPU with ComfyUI, so a 4–8B model leaves room for generations.
+
- **AI helper** picks who writes: Automatic (Claude when a key is set, else a local model, else the offline rewriter), Claude, a local model only, or offline (`FUOBE_ENHANCE_PROVIDER=auto|anthropic|local|none`; the old value `ollama` means `local`). Its local model server is Automatic by default (`FUOBE_LLM_PROVIDER=auto`): the first one that answers with a model, in the order Ollama, LM Studio, Unsloth Studio, then the Other URL. `FUOBE_LLM_PROVIDER=ollama|lmstudio|unsloth|custom` pins one. Settings → AI helper shows what each server answers (its models, whether one is loaded, what's missing) and has a **Test connection** button. The local model shares the GPU with ComfyUI, so a 4–8B model leaves room for generations.
+ Each connection field in Settings has **Save & test**: what you typed is tested before it is saved, and a failure says why. Until something is connected (or you hide it), Home and Settings show a **Get started** card with the three ways in.
- Keys are stored in a local SQLite database (`data/fuobe.db`) and never sent to the browser. Generated media is saved under `data/files/`. Fuobe is single-user.
+ Keys (and Assist connectors' URLs and tokens) are stored in a local SQLite database (`data/fuobe.db`) and never sent to the browser in full. Generated media is saved under `data/files/`, and LoRAs downloaded only to copy them to fal or Replicate, and your trained Soul ID LoRAs, under `data/loras/`. Fuobe is single-user.
### Self-hosting and security
@@@ -82,68 -96,114 +102,125 @@@ Uploads up to 200 MB work with sign-in
### Upgrading from an earlier version
- - **Your data upgrades on its own.** The database migrations run once each at start-up, in order, and an existing `data/` folder (or `FUOBE_DATA_DIR`) keeps everything it holds. The list is in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md#storage-srcserverdbts-storagets-settingsts).
- - **If you ran one of the round-3 package branches** (`r3/*`, `r3b/*`) before they were merged, start with a fresh data folder. Those branches numbered their migrations differently, so tables can be missing. Move the old folder aside rather than deleting it if it holds results you want.
- - **Install the new dependencies:** `pnpm install` (round 3 adds `@xyflow/react`, `@google/model-viewer`, `three` and `unpdf`), then `npx next typegen` before `pnpm typecheck`.
- - **Password-less installs reached by a domain name** (a reverse proxy, a tunnel, a Tailscale name) now get 403. Set a password, or add the name to `FUOBE_ALLOWED_ORIGINS`.
- - **Inputs from LAN addresses** (an image URL on your NAS, say) are refused unless `FUOBE_ALLOW_PRIVATE_URLS=1`.
- - **ComfyUI:** re-run `scripts/comfy/install-comfyui.sh` for the three node packs round 3 adds (ComfyUI-MelBandRoFormer, ComfyUI-QwenASR, ComfyUI-HunyuanVideo-Foley) at their pinned commits.
-- **Get the new code and rebuild.** Pull `main`. On Windows, run `start.bat` as usual: it installs packages on every start and rebuilds because the code changed. On Mac or Linux, run `pnpm install`, then `pnpm build` (or just `pnpm dev`). Round 4 adds only one dependency, `@types/three` (for development; PR #9, PR #10, PR #12 and PR #13 add none, so `pnpm install` has nothing new for them); round 3 added `@xyflow/react`, `@google/model-viewer`, `three` and `unpdf`. In a checkout without `.next`, run `pnpm exec next typegen` (or a dev or build run) before `pnpm typecheck`.
++- **Get the new code and rebuild.** Pull `main`. On Windows, run `start.bat` as usual: it installs packages on every start and rebuilds because the code changed. On Mac or Linux, run `pnpm install`, then `pnpm build` (or just `pnpm dev`). Round 4 adds only one dependency, `@types/three` (for development; PR #9, PR #10, PR #12 and PR #13 add none, so `pnpm install` has nothing new for them); round 3 added `@xyflow/react`, `@google/model-viewer`, `three` and `unpdf`. The local model servers and the Image to 3D finish (below) add `@gltf-transform/core`, `@gltf-transform/extensions`, `@gltf-transform/functions`, `meshoptimizer`, `sharp` and `playwright-core`, so run `pnpm install` for them. In a checkout without `.next`, run `pnpm exec next typegen` (or a dev or build run) before `pnpm typecheck`.
+ - **Your data upgrades on its own.** The database migrations run once each at start-up, in order, and an existing `data/` folder (or `FUOBE_DATA_DIR`) keeps everything it holds. Round 4 adds seven migrations: one for the Library's nested folders, pins and review status (PR #6), two new tables in PR #9, `lora_mirrors` (each LoRA copy Fuobe makes) and `content_series` (Content Factory), two in PR #12: `shares` (share links; only a hash of each link's token is stored) and Assist's `assist_schedules` and `assist_connectors`, with four new columns on `assist_thread_state`, and two in PR #13: `swap_projects` (one document per Character Swap Studio project) and the O7 cleanup, which deletes the saved Higgsfield key, turns "Higgsfield first" into Automatic and marks the ads Higgsfield drew `baked`. They are added at the first start. PR #12's and `swap_projects` only add tables and columns, but the O7 cleanup can't be undone, so back up `data/` (or `FUOBE_DATA_DIR`) first if you might go back to an earlier version. PR #7 and PR #10 add none. Settings → Models & licences keeps its switches in the existing settings table (`models.access`), and Soul ID uses the existing trainings table. The list is in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md#storage-srcserverdbts-storagets-settingsts).
+ - **Canvases are saved in a new form (PR #10).** A board is rewritten with pages the next time it is saved, and older Fuobe builds can't read it after that. Back up the data folder if you might go back to an earlier version. Scripts that read a canvas through the API: `GET /api/canvases/:id` now returns `canvas.pages` (each page with its graph), not `canvas.graph`.
+ - **If you ran one of the round-3 package branches** (`r3/*`, `r3b/*`) before they were merged, start with a fresh data folder. Those branches numbered their migrations differently, so tables can be missing. Move the old folder aside rather than deleting it if it holds results you want. A folder used by the `r4/assist-connectors` branch before its review fixes needs the same: its migration changed in place. The same goes for a folder used by the `r4/content-factory` branch on its own: there Content Factory's table took the Library migration's number, so the Library's folders, pins and review status would never be added.
+ - **Start on Home now runs the job** in Image, Video or Edit instead of only opening the studio. With a saved key for the default model this is a paid run; the line under the box says first what will run and what it costs. **⌘K / Ctrl+K** opens the search palette instead of going Home.
+ - **Topaz Video is priced by size:** $0.01/s at 720p, $0.02/s at 1080p and $0.06/s above, doubled at 60 fps (it was a flat $0.02/s at 2×). The default target is 1080p, and a size that wouldn't enlarge the clip moves up, so a 1080p clip now goes to 1440p at $0.06/s. Open-source video upscaling (SeedVR2, Real-ESRGAN) also asks for a size now, 720p to 2160p, instead of 2× or 4×.
+ - **Cloud Mixed Media costs more by default.** It now redraws each sampled frame (**Per frame**): about $6 for 10 s at 1K, where the video-to-video pass was one call. Pick **Fast** under Restyle to keep the old behaviour. API calls with no `modelId` and no `mode` now get Per frame; a model sent for the wrong mode gets a 422.
+ - **Click to Ad ends on a logo card by default** when the product kit has a logo: 2.5 s longer, included in the price. Switch **End card** off to keep the old ads. API calls without `endCard` are unchanged.
+ - **Motion and effect links open on the move's model (PR #10).** Picking a camera motion or effect in the Video studio, or arriving from Motions or Effects, now switches to the model its move runs on: Fuobe DoP or Fuobe DoP · LTX, a few on LTX-2.5. In the cloud, 152 presets change model and price; the other 211 keep Kling 2.5 Turbo as their route and leave the model you picked alone. Moodboards' curated looks open on Fuobe Soul. Per-megapixel cloud prices (Z-Image Turbo, Qwen-Image 2512, FLUX.1 Fill [pro]…) now count every picture, so n pictures quote about n× the old estimate. On a Canvas board, dragging the empty board now draws a selection box; scroll, Space-drag, the middle button or H pans.
+ - **Open-engine motions and effects no longer all run on Wan 2.2 (PR #10).** 17 open on Fuobe DoP · LTX (FPV Drone, Wind to Face, Earth Zoom Out, Flying Cam Transition and 13 transitions) and need the LTX-2.3 checkpoint (29.53 GB, plus the 9.45 GB Gemma 3 text encoder if LTX-2 isn't set up) and a 32 GB GPU. On 24 GB, pick Fuobe DoP: it runs their words. Slow Motion, Car Drive and Wild Ride open on LTX-2.5. Relight effects first run the existing Qwen-Image-Edit 2509 Relight workflow (about 31 GB of model files).
+ - **Cloud keys for the Originals (PR #10).** The presets that moved to Fuobe DoP, Fuobe Soul HD, the relight step and Focus Change need a fal key; Fuobe DoP (start frame only) and Fuobe Soul's text to image also run on Replicate. None runs on Higgsfield: with only a Higgsfield key, motion links and curated looks opened on a model that couldn't run. Since PR #13 a Higgsfield key does nothing, so add a fal key (see the O7 note below).
+ - **Licences are information, not gates (PR #12).** Everything is switched on by default: LoRAs licensed for your GPU only (civitai files without the "Rent" permission) now go to fal or Replicate with a note, Assist and automatic picks can choose non-commercial models, and re-running the install script adds the non-commercial ComfyUI-Whisper. Studio defaults don't change with it. To stay commercial-only, or keep GPU-only LoRAs at home, use **Settings → Models & licences**: switch off licence classes, providers, node packs, LoRAs or models, and turn on **Keep them on your GPU**. There is no admin role: anyone who can sign in (or anyone who can reach a password-less install) can change it.
+ - **MiniMax H3 (PR #12)** is Character swap's default on both engines and runs H3 Person Removal. Its licence excludes the US, the EU, the UK and South Korea, needs MiniMax's written authorization above US$20M yearly revenue, and asks commercial products to show "MiniMax H3". If that doesn't fit, switch off "Fuobe Character swap", "H3 Character Swap · Relay 2.0" and "H3 Person Removal · Relay 2.0" in Settings → Models & licences. The Restricted regions switch covers only your GPU, because fal's H3 is classed as a paid API.
+ - **Share links skip sign-in (PR #12).** Nothing is shared until you make a link. Set `FUOBE_PASSWORD` so the rest of the studio stays locked (the Share dialog warns when there is none), and behind a reverse proxy set `FUOBE_TRUST_PROXY=1` so a visitor who guesses wrong links is locked out alone. Copy a link when you make it: only the browser that made it can copy it again. Revoking a link deletes it at once, though a browser may keep files it already fetched for 5 minutes.
+ - **Scheduled tasks (PR #12)** run only while Fuobe runs; a run missed while it was off happens once after the next start. A sweep every 30 s starts at boot, and every Fuobe server on the same database runs due tasks, so a dev server on your real data folder runs, and spends on, your schedules too. A task asks first by default; one that runs on its own counts Fuobe's generation jobs against its cap, not Claude's tokens. Connectors are offered in every Claude chat, the ones you already have included; a scheduled task uses them only when you tick "Let runs use my connectors".
+ - **New defaults in Cinema, Genjutsu and Soul ID (PR #12).** Cinema's video default is Fuobe Cinema on both engines, so a cloud take costs LTX-2.3's price per megapixel of video on fal (about $0.18 for 5 s at 720p), and stills default to Fuobe Soul Cinema. Cinema Studio 4.0, Soul 2.0 and Higgsfield's Soul Cinema leave Cinema's menus, and a saved pick falls back to the Original. Genjutsu's modes (all but Insert) default to the Fuobe Originals instead of Higgsfield's Genjutsu; old setup codes open the replacing Original (without a Higgsfield look), and Katana's Genjutsu motion option takes 1 reference instead of Higgsfield's 8. In the cloud, Fuobe Cinema and the Genjutsu Originals need a fal key. Soul ID no longer trains on Higgsfield: a Higgsfield training still queued or running fails with a note to retrain for Fuobe Soul. fal's Z-Image training is now 2,000 steps for about $1.70 (it was 1,000 for $0.85), elements hold up to 80 photos (was 20), and Photodump, Fashion and trained moodboards run on Fuobe Soul.
+ - **Scripts that call the API (PR #12):** training a character needs `consent: true` (`POST /api/elements/[id]/trainings` takes `{target, consent}`), `/lora` takes `family` instead of `modelId` and `/training-kit` a `family`; `POST /api/genjutsu` takes mode `character`, and look kind `soul` replaces `higgsfield`; Cinema's `GET /api/cinema/projects/[id]` returns `context` as `{cloudAllowed, civitai}` (no `higgsfield`); `GET /api/models` lists only models that are on, and `POST /api/generations` answers 422, naming the switch, for one that is off.
+ - **Higgsfield is no longer called (O7, PR #13).** The saved Higgsfield key is deleted, and **Preferred provider** goes back to Automatic if it was "Higgsfield first" (its choices are now Automatic, fal.ai first and Replicate first). Remove `HIGGSFIELD_API_KEY` and its aliases `HF_KEY`, `HF_API_KEY` and `HF_API_SECRET` (Higgsfield's, not Hugging Face's) from `.env`: they are no longer read, and `FUOBE_CLOUD_PROVIDER=higgsfield` counts as `auto`. If Higgsfield was your only cloud key, add a fal.ai (or Replicate) key; until then, cloud runs come back as demos (with Demo mode on Auto). Reuse, saved Canvas boards and Cinema projects, Genjutsu setup codes, Katana jobs, Assist plans, retries and API, CLI or MCP calls that name Soul, Soul 2.0, Soul Cinema, Cinema Studio 4.0 or a Genjutsu model run on the Fuobe Original that replaced it, on your engine (Marketing Studio Image runs on GPT Image 2.5, Ads Studio and the AI Influencer app on Nano Banana Pro, until their Originals land), and the API's notes say so. In an API, CLI or MCP call and a retry, Cinema Studio's Director settings become words in the prompt (Reuse leaves them out and says so), and its reference takes run on Seedance 2.5. Seedance 2.5's video edit and LTX 2.5's start/end-frame clip only ran there: they now run on Kling O3 and Fuobe Cinema. Past results stay in the Library under the name they ran as ("Soul 2.0 (Higgsfield)"). A job still running there when you upgrade fails on its next check with a note to run it again, a Higgsfield Soul ID training still queued or running fails with a note to retrain for Fuobe Soul, and an Ads Studio batch made there is remade the Fuobe way on retry. Switches you set in Settings → Models & licences on a retired model or on the Higgsfield provider no longer apply to anything: if you had switched off, say, Soul 2.0, switch off its replacement too.
+ - **Other O7 changes (PR #13).** Happy Horse 1.1 (text, image and reference to video) now runs with a fal key: $0.14/s at 720p, $0.18/s at 1080p. The Ad Multiplier's cloud choices are Kling O3 edit (the default) and Happy Horse video edit, which keep the ad's sound but recreate at most its first 15 s (a longer selection is cut, with a note), and Gemini Omni Flash. Character Sheet → Build from scratch in the cloud runs on Fuobe Soul in Cinema's casting look (Nano Banana Pro if that is switched off); it used Soul 2.0 or Nano Banana Pro, so its price and look change. The AI Influencer app uses Nano Banana Pro in the cloud, and the GPU path is unchanged. Grok Imagine Image 2.0 takes 5 references (was 10). Old Higgsfield Soul IDs are labelled "Older Soul ID". If you installed Fuobe's skills into another agent (Cursor, Codex…), re-run `npx skills add workingprototype/Fuobe`: four playbooks now name other models.
+ - **Scripts that call the API (PR #13):** `GET /api/providers/higgsfield/presets` is gone; `POST /api/providers/test` with `higgsfield` answers 400, `GET /api/status` no longer lists it, and `PUT /api/settings` ignores `higgsfieldKey` and refuses `cloudProvider: "higgsfield"` (400). `POST /api/generations` may answer with a replacement `modelId` and `notes` saying what changed. Ads batch and estimate bodies and `POST /api/brands/[id]/chat/confirm` ignore `route` and `ratio`, and `/api/ads/estimate` no longer returns `route`. `POST /api/uploads` also takes MKV and AVI (200 MB as before): the Character Swap Studio's picker lists them, other pickers still list MP4, MOV and WebM, and browsers can't play AVI. The Character Swap Studio's routes are new, under `/api/swap-studio/projects`.
+ - **Character Swap Studio on your GPU (PR #13)** needs the H3 Relay 2.0 node pack (`akatz-ai/h3-relay` at `e2a7665`): re-run `scripts/comfy/install-comfyui.sh` with `H3_RELAY=1`, or on Windows or ComfyUI Desktop clone it into `custom_nodes` and check out that commit. It also needs VideoHelperSuite and FFmpeg on the ComfyUI machine, a 24 GB GPU with offloading and 64–128 GB of RAM (48 GB+ advised for 768p), and ComfyUI started with a higher `--max-upload-size` (100 MB by default) for continuations with more than about 30 frames of history at 1 MP; an upload ComfyUI refuses as too large now says so. It adds no model files: it uses PR #12's MiniMax H3 files. In the cloud it needs a fal key. MiniMax H3's licence (above) applies to it too. Its swap runs on "Fuobe Character swap" in the cloud and on "H3 Character Swap · studio segment" on your GPU (listed in Settings → Models & licences as a helper step studios run), and it refuses only what is switched off there: if H3's licence doesn't fit, switch off that second one too. A sweep every 3 s, from server start, starts takes that were waiting on the one before; like scheduled tasks, it runs in every Fuobe server on the same data folder, so a dev server on your real data can launch (and pay for) them too.
-- **A busy ComfyUI no longer counts as down (PR #13).** Before, one 1.5–2 s check decided, so a ComfyUI busy with a job could send new runs to demo. Now it counts as up if it answered in the last 2 minutes, or if its port accepts a connection and it answers a longer 10 s check. A refused connection, an unknown host or an HTTP error still means down at once; a port that accepts connections but never answers (a hung ComfyUI, a tunnel to a dead box) is down after the 10 s check. A chain step after real ComfyUI steps (such as the Canvas concatenator's join) waits up to 60 s for ComfyUI before failing; cloud steps don't wait. Ollama's check is unchanged.
++- **A busy ComfyUI no longer counts as down (PR #13).** Before, one 1.5–2 s check decided, so a ComfyUI busy with a job could send new runs to demo. Now it counts as up if it answered in the last 2 minutes, or if its port accepts a connection and it answers a longer 10 s check. A refused connection, an unknown host or an HTTP error still means down at once; a port that accepts connections but never answers (a hung ComfyUI, a tunnel to a dead box) is down after the 10 s check. A chain step after real ComfyUI steps (such as the Canvas concatenator's join) waits up to 60 s for ComfyUI before failing; cloud steps don't wait. The local model servers' checks (Settings → AI helper) are unchanged.
++- **Settings → Prompt enhancement is now AI helper.** Besides Claude and Ollama it talks to LM Studio, Unsloth Studio and any other OpenAI-compatible server (see the table above). Nothing needs changing: `FUOBE_ENHANCE_PROVIDER=ollama` and a saved Ollama choice now mean "a local model", the Ollama settings and environment variables are read as before, and Assist chats saved on Ollama open on the local model. With Automatic, Fuobe uses the first local server that answers with a model (Ollama first); pin one with `FUOBE_LLM_PROVIDER`. A model LM Studio loads for Fuobe gets 16k of context (`FUOBE_LLM_CONTEXT`).
++- **Image to 3D on your GPU: Pixal3D and the finish.** From an image now runs Pixal3D by default (`image-to-3d-pixal3d`: MoGe 2 estimates the camera, about 250k triangles); TRELLIS.2 stays in the menu. It needs one new model file, Pixal3D's single-view weights (`pixal3d_int8_convrot`, 5.58 GB; the multi-view graph uses its own), plus MoGe 2 and the files TRELLIS.2 already uses; the Workflows page lists them. Like TRELLIS.2, it encodes with DINOv3, so its results show "Built with DINOv3". Before a job shows as done, the server makes a web copy of each open-engine GLB (meshopt geometry, WebP textures, the pivot at the bottom); the raw GLB stays the download. After it, the server renders a 4 s turntable on the CPU, one at a time, when ffmpeg and a Playwright Chromium are there (`npx playwright-core install chromium-headless-shell`); without them the 3D page records one in your browser.
+ - **LoRAs on the open engine:** set the **LoRA folder** in Settings → LoRAs, plus a civitai key for 72 of the 114 library LoRAs. Fuobe writes the files itself, so the folder must be one the Fuobe machine can write to (ComfyUI on the same PC, or its `models/loras` shared); otherwise place the files by hand, as you must for the two gated Hugging Face LoRAs. With no folder set, a run that needs a LoRA ComfyUI doesn't have stops and says what to do. A LoRA sent to a workflow with no model loader to attach it to now fails the run instead of being dropped silently. Since PR #10 the presets use many more LoRAs on the open engine: 84 files (was 43), 36 of them from civitai (was none). Without the civitai key, a motion, an effect or one of six Cinema Studio moves (Handheld, POV, Robot Arm, Snorricam, Tracking and Side Tracking) that needs a civitai file ComfyUI doesn't have stops before the job; Fuobe Soul leaves those LoRAs out and says so.
+ - **Cloud runs with LoRAs:** when a model runs on both fal and Replicate, Fuobe picks the one that can take every LoRA and the clip length asked, even over **Preferred provider**. LoRAs a run can't take are left out with a warning.
+ - **Password-less installs reached by a domain name** (a reverse proxy, a tunnel, a Tailscale name) get 403 since round 3. Set a password, or add the name to `FUOBE_ALLOWED_ORIGINS`.
+ - **Inputs from LAN addresses** (an image URL on your NAS, say) are refused unless `FUOBE_ALLOW_PRIVATE_URLS=1` (also since round 3).
+ - **ComfyUI node packs:** re-run `scripts/comfy/install-comfyui.sh` (it keeps what's installed and pins each pack to the commit Fuobe was validated with). Round 3 added ComfyUI-MelBandRoFormer, ComfyUI-QwenASR and ComfyUI-HunyuanVideo-Foley; round 4 adds ComfyUI-ToSVG for the open Vectorize app (PR #9 and PR #10 add none). Open-source video upscaling and FPS Boost now also need ComfyUI-VideoHelperSuite (before, core ComfyUI was enough), which the script installs too. Since PR #12 the script also installs the non-commercial ComfyUI-Whisper by default (`NC_PACKS=0` leaves it out) and Akatz Labs' GPL-3.0 `h3_character_swap` pack for Genjutsu's Character swap (`H3_PACK=0` leaves it out; it needs `ffmpeg` and `ffprobe` on PATH). H3 Relay 2.0, for H3 Person Removal and the Relay swap, adds its own HTTP routes to ComfyUI, so it is opt-in: `H3_RELAY=1` (or install it on the isolated worker). PR #13 adds no pack: the Character Swap Studio's GPU graphs use H3 Relay 2.0 and VideoHelperSuite. Workflows → **Copy install commands** gives `git clone …/tree/<commit>/…` lines for the two H3 packs, which git can't clone, so use the script for them. If you set up ComfyUI another way (ComfyUI Desktop, for example, or on Windows), install these packs yourself. ComfyUI itself needs no upgrade: the library still targets 0.41.0.
+ - **Models for the new tools.** Round 4 adds about 28 GB of model files to the library in PR #6 (PR #7 adds none): VOID with its CogVideoX VAE (22.73 GB, Remove object's "Shadows and reflections too"), MoGe 2 (0.66 GB, 3D scenes, and since PR #10 multi-view 3D too), OvisOCR3 (1.71 GB, Layers' text detection since PR #9) and TripoSplat (Image to 3D's Splat mode since PR #10). PR #10 adds about 35 GB more, both optional: the LTX-2.3 22B distilled checkpoint (29.53 GB, plus the Gemma 3 text encoder, 9.45 GB, if LTX-2 isn't set up) for Fuobe DoP · LTX, and Pixal3D multi-view (5.58 GB, plus MoGe 2 if the 3D scene isn't set up) for TRELLIS.2 Multi-view. Fuobe Soul's image to image and the Canvas Video concatenator need no new files. The new tools also use files the library already listed, which you may not have downloaded: Wan 2.1 VACE 14B (34.68 GB) and SAM 3.1 (Remove object; Genjutsu's swap and insert), Wan Animate 2 (Genjutsu's motion transfer), Qwen-Image-Edit 2511 with the Multiple-Angles LoRA (3D scenes) and RIFE 4.26 (FPS Boost). PR #9 adds no files to the library, but its tools use these: OvisOCR3 for Layers' text detection; Gemma 4 E4B (9.06 GB) plus ComfyUI-VideoHelperSuite for Content Factory's reading of a reference clip; FLUX.1 Fill [dev] (23.8 GB) for Layers' Inpaint. The **Workflows** page lists them with their install commands. GPU memory, from the manifest and not measured: Wan VACE 24 GB, VOID 24–40 GB, SeedVR2 in passes 16 GB, Gemma 4 E4B 12 GB, OvisOCR3 3 GB; since PR #10, LTX-2.3 22B 32 GB, TRELLIS.2 Multi-view 16 GB, Z-Image Turbo image to image 12 GB.
+ - **Models for Character swap (PR #12).** About 45 GB of new model files, all optional and pinned: MiniMax H3's INT8 model (20.97 GB), its NVFP4 Qwen3-VL 32B text encoder (15.69 GB), H3's video and audio VAEs (5.21 and 0.61 GB), lightx2v's FL2V Turbo 8-step LoRA (1.96 GB) and Akatz Labs' swap or person-remover LoRAs (0.16 GB each), plus SAM 3.1, which the library already listed. Fuobe downloads the LoRAs into your LoRA folder before a run. They serve Genjutsu's Character swap and Remove object's H3 Person Removal on your GPU; the Workflows page lists them. GPU memory, Fuobe's advice and not measured: 24 GB of VRAM with offloading and 64–128 GB of RAM, and 48 GB+ for 768p, Character swap's default. Fuobe Cinema on your GPU needs no new files (it uses the Wan 2.2 14B Lightning graphs already in the library), and AI-Toolkit downloads Soul ID's base weights itself. The Character Swap Studio (PR #13) adds none either: its two graphs use these files and SAM 3.1.
+ - **`pnpm test` also runs the evaluation harness's Python metric tests**, in the harness's own venv or through uv (which may download numpy, Pillow and pytest once); with neither, they are skipped. Nothing is removed in PR #9 or PR #10: no route, setting, environment variable, workflow or provider. PR #10 adds no setting or environment variable either, and `pnpm gen:catalog` now also writes Fuobe Soul's looks. PR #12 removes no route, environment variable, workflow or provider either, and adds no app environment variable (its new settings are Settings → Models & licences and Assist's connectors); the install script gains `H3_PACK` (default 1) and `H3_RELAY` (default 0), and `NC_PACKS` now defaults to 1. `pnpm gen:catalog` also runs `scripts/gen-trainers.py`, and the LoRA and Soul generators print licence notes instead of stopping. PR #13 removes the Higgsfield provider: the `higgsfieldKey` setting with its environment variables, the `higgsfield` Preferred provider value and `GET /api/providers/higgsfield/presets`. It adds no setting or environment variable, `pnpm gen:catalog` runs `scripts/gen-studio-packs.py` instead of the two Higgsfield generators, and `pnpm build` no longer prints the 4 Turbopack tracing warnings.
### Setting up the open-source engine
- 1. Install ComfyUI on a machine with a GPU (24 GB VRAM covers almost every workflow; Z-Image Turbo, Wan 2.2 5B and SDXL run in 8–16 GB). `scripts/comfy/install-comfyui.sh` installs ComfyUI and the 14 custom node packs at the commits Fuobe was validated with (`NC_PACKS=1` adds the non-commercial ComfyUI-Whisper).
+ 1. Install ComfyUI on a machine with a GPU (24 GB VRAM covers almost every workflow; Z-Image Turbo, Wan 2.2 5B and SDXL run in 8–16 GB; VOID, Remove object's "Shadows and reflections too", may need up to 40 GB, Fuobe DoP · LTX's LTX-2.3 graphs 32 GB, and the MiniMax H3 graphs of Character swap and the Character Swap Studio 24 GB with offloading and 64–128 GB of RAM, 48 GB+ advised). `scripts/comfy/install-comfyui.sh` installs ComfyUI and 17 custom node packs at pinned commits (the ones Fuobe was validated with; the H3 graphs aren't validated yet), the non-commercial ComfyUI-Whisper (`NC_PACKS=0` leaves it out) and Akatz Labs' GPL-3.0 `h3_character_swap` (`H3_PACK=0` leaves it out) included; `H3_RELAY=1` adds H3 Relay 2.0 (Genjutsu's Relay swap, H3 Person Removal and the Character Swap Studio). Settings → Models & licences switches packs and models off per install.
2. Open **ComfyUI workflows** in Fuobe. Each workflow lists the model files it needs, which are already installed (✓) and a **Copy install commands** button that produces the exact `wget` / `git clone` lines.
3. Switch the engine toggle (top-right of every studio) to **Open source**.
+ 4. For LoRAs (Fuobe Soul's looks, camera motions, effects, trained Soul IDs, Character swap's LoRAs), set **Settings → LoRAs → LoRA folder** to ComfyUI's `models/loras`, and add a civitai key for civitai files. Fuobe then downloads a LoRA ComfyUI doesn't have before the run.
- LatentSync 1.6 and ThinkSound are optional and run on a separate, isolated ComfyUI (`scripts/comfy/install-isolated-worker.sh`, port 8189); see [`scripts/comfy/README.md`](scripts/comfy/README.md). Their workflows are validated, but they are hidden models that no studio offers yet (the API takes them by `modelId`). Open dubbing, Faceless and UGC narration clone a voice with Chatterbox, so they need a voice sample (record or upload one).
-LatentSync 1.6 and ThinkSound are optional and run on a separate, isolated ComfyUI (`scripts/comfy/install-isolated-worker.sh`, port 8189); see [`scripts/comfy/README.md`](scripts/comfy/README.md). Lipsync offers LatentSync 1.6 and Sound effects offers ThinkSound, marked in the model picker as running on the isolated worker. Set its address as **Isolated worker URL** in Settings (or `COMFYUI_ISOLATED_URL`); without it, those jobs fail with a message naming the setting. Their workflows are validated, but not run with real weights. Open dubbing, Faceless and UGC narration clone a voice with Chatterbox, so they need a voice sample (record or upload one). Open-source translation uses Ollama when it's running, and Qwen3.5 4B on your ComfyUI when it isn't.
++LatentSync 1.6 and ThinkSound are optional and run on a separate, isolated ComfyUI (`scripts/comfy/install-isolated-worker.sh`, port 8189); see [`scripts/comfy/README.md`](scripts/comfy/README.md). Lipsync offers LatentSync 1.6 and Sound effects offers ThinkSound, marked in the model picker as running on the isolated worker. Set its address as **Isolated worker URL** in Settings (or `COMFYUI_ISOLATED_URL`); without it, those jobs fail with a message naming the setting. Their workflows are validated, but not run with real weights. Open dubbing, Faceless and UGC narration clone a voice with Chatterbox, so they need a voice sample (record or upload one). Open-source translation uses the local model (Settings → AI helper) when one is ready, and Qwen3.5 4B on your ComfyUI when none is.
To check a ComfyUI connection end to end without downloading any models:
```bash
pnpm dev &
pnpm test:e2e:comfyui http://localhost:3000 # runs the weight-free workflows through the full pipeline (mux, trim, segment, captions, meta-batch), checked with ffprobe when installed
+ node tests/e2e/comfyui-faceless-plus.mjs http://localhost:3000 # Ken Burns, the packet-copy join, a crossfaded audio loop and join; needs ffmpeg and ffprobe and demo mode off; on Linux it also samples ComfyUI's memory (found with pgrep, or set COMFYUI_PID)
+ node tests/e2e/comfyui-canvas-concat.mjs http://localhost:3000 # the Canvas Video concatenator: three test clips are cut, framed to 9:16 at 30 fps and joined, then the film is probed; model-free, needs ffmpeg and ffprobe
```
+## To do
+
+- [ ] **Chunked uploads, so files over 100 MB work on fuobe.com.** Cloudflare (Free and Pro plans) refuses a request body over 100 MB, but Fuobe accepts 200 MB, so a 100–200 MB upload fails there. Send files over about 90 MB as 50 MB chunks and join them on the server before `saveFile()`: add a chunk endpoint next to `src/app/api/uploads/route.ts` and one client helper for its three callers (`src/components/studio/media-slot.tsx`, `src/lib/api.ts`, and `src/components/shorts/use-source-clip.ts`, which keeps its progress bar). Smaller files upload in one request, as now. See [docs/deploy.md](docs/deploy.md#cloudflare-limits).
+
## Development
```bash
- pnpm typecheck && pnpm lint && pnpm test # TypeScript, ESLint, Vitest (79 files, 1128 tests)
-pnpm typecheck && pnpm lint && pnpm test # TypeScript, ESLint, Vitest (161 files, 2643 tests; with uv, also the harness's Python metric tests)
++pnpm typecheck && pnpm lint && pnpm test # TypeScript, ESLint, Vitest (167 files, 2714 tests; with uv, also the harness's Python metric tests)
pnpm build # production build
- pnpm gen:catalog # regenerate cloud models, Higgsfield models and presets, LoRA map and icon map from docs/research/*.json
+ pnpm gen:catalog # regenerate cloud models, studio packs, LoRA map, LoRA library, AI Influencer options, Fuobe Soul's looks, Soul ID's trainers and icon map from docs/research/*.json
pnpm dev:clean # clear the Turbopack cache if the dev server gets stuck reloading or serves stale CSS
node scripts/gen-demo-3d.mjs # regenerate the demo GLB and turntable (needs ffmpeg)
+node scripts/model3d/finish-glb.mjs --in raw.glb --out web.glb # the server's GLB finish, by hand
+node scripts/model3d/render-turntable.mjs --glb web.glb --out spin.mp4 # the server's CPU turntable (needs ffmpeg and a Playwright Chromium: npx playwright-core install chromium-headless-shell)
```
Browser checks (the app must be running; demo mode is fine; Playwright and Chromium are picked up from the repo, a global install or `$CHROMIUM_PATH`):
```bash
pnpm test:e2e:mobile [url] [--light|--dark] # no route may scroll sideways at 390 px (every route, hub mode and sample id)
- pnpm test:e2e:shell [url] # sidebar drawer, collapsed groups, settings deep links, keyboard Show more
+ pnpm test:e2e:shell [url] # skip link and landmarks, ⌘K palette, phone drawer and Search, full-screen studios, settings deep links, keyboard Show more
+ pnpm test:e2e:library [url] # helper steps, pins, review status, nested folders, zips, upload delete, phone layout (cleans up after itself; --keep leaves its data)
pnpm test:e2e:comfyui [url] # the open engine against a live ComfyUI
- node tests/e2e/composer-flows.mjs [url] # first paint, typing before hydration, paste, upload cancel, phone toolbar
+ node tests/e2e/composer-flows.mjs [url] # first paint, typing before hydration, paste, upload cancel, phone toolbar and blocker line
+ node tests/e2e/notifications.mjs [url] # job notifications and the running count in the tab title
+ node tests/e2e/clipboard.mjs [url] # Copy buttons on a plain-http LAN address (no Clipboard API)
node tests/e2e/layers.mjs [url] # Layers regressions
+ node tests/e2e/cinema-scene.mjs [url] # 3D scene: ask first, point cloud, fly, Capture → re-render, 390 px
node tests/e2e/canvas-smoke.mjs [url] --perf=60 # Canvas save, rename, trash → re-run, keystroke timing
- node tests/e2e/cinema-shortcuts.mjs [url] # Ctrl/Cmd+Enter only from Cinema's prompt bar
- node tests/e2e/assist-flows.mjs [url] # skills, memory, projects, skill upload, modes, phone sheet
+ node tests/e2e/canvas-board.mjs [url] # Canvas drawing, shapes, text, comments, groups and Run group, pages, Undo across pages
+ node tests/e2e/canvas-open-dub.mjs [url] # Translate (video) on an open-source-only install (sets Engine mode for the run, then puts it back)
+ node tests/e2e/dop-flows.mjs [url] # Fuobe DoP in the Video studio: prices, engine switch, grade hand-off, 390 px (any string as the fal key adds the cloud prices; nothing is sent)
+ node tests/e2e/cinema-shortcuts.mjs [url] # Ctrl/Cmd+Enter only from Cinema's prompt bar; new project names, phone Director chip
+ node tests/e2e/assist-flows.mjs [url] # skills, memory, projects, skill upload, modes, phone sheet (the Scheduled page too)
+ node tests/e2e/cinema-original.mjs [url] # Fuobe Cinema at 1440 and 390 px, light and dark: the model menu, camera moves on LTX-2.3's camera LoRA, prices, stills on Fuobe Soul Cinema, Soul Cast and Soul Location on Fuobe Soul in the cloud
+ node tests/e2e/genjutsu-original.mjs [url] # Genjutsu on the Originals at 1440 and 390 px, light and dark: Character swap's controls, limits and licences, a demo run, the open engine's clicks and GPU line, no Higgsfield
+ node tests/e2e/character-swap-studio.mjs [url] # Character Swap Studio's whole flow on the cloud engine in demo mode (shots, words, a mask, an anchor, a continued segment, takes, review, Export decisions, assembly), every stage at 1440 and 390 px, light and dark, the 24 fps copy on your GPU, an AVI's browser copy, the Genjutsu hand-off and a 404; needs ffmpeg
+ ```
+
+ `layers.mjs` and `cinema-scene.mjs` expect their open-engine step to run in demo mode: with a reachable ComfyUI they fail (demo stills are SVG placeholders ComfyUI can't read, and Layers needs the Qwen-Image-Layered weights). `cinema-original.mjs`, `genjutsu-original.mjs` and `character-swap-studio.mjs` also expect demo mode with ComfyUI unreachable. Since PR #13 a ComfyUI port that accepts connections counts as reachable at first, so for them point `COMFYUI_URL` at a closed port, such as `http://127.0.0.1:1`.
+
+ The Fuobe Originals evaluation harness (see [`scripts/eval/README.md`](scripts/eval/README.md); `fuobe eval <command>` does the same from a checkout). `eval:run` needs a running Fuobe:
+
+ ```bash
+ pnpm eval:validate # check every case file, and that the generated suites match the research
+ pnpm eval:run --suite selftest --engine demo # about 30 s, free: submit, wait, download, score, report
+ pnpm eval:setup # the metrics venv (needs uv; CPU torch by default)
+ pnpm eval:review latest # rate a run's pairs blind, with the keyboard
+ pnpm eval:compare latest~1 latest # wins, losses and mean gain per metric; exits 1 when a guarded metric regresses
+ pnpm eval:promote latest # does the recipe win? A person changes the default, in a reviewed commit
++pnpm eval:covers <runId> # a run's promoted renders become the cards' covers (needs ffmpeg)
++pnpm eval:covers --from-masters <dir> --run <name> # rendered masters (<dir>/<preset id>/clip.mp4 or start.png) become covers, merged with the others
+ node tests/e2e/eval-review.mjs # the report and blind review pages at 1440 and 390 px, light and dark (no app needed)
```
- `docs/ARCHITECTURE.md` — how requests flow from the composer to providers and back, pipelines, live updates, security, each studio's modules
- - `docs/research/` — the research this is built on (Higgsfield inventory, studios, image studios, marketing and agents, API; paid model APIs parts 1–3; ComfyUI equivalents parts 1–3; workflow library; Liner UI language)
+ - `docs/cli.md` — the `fuobe` command line: install, sign in, every command (`fuobe eval` included), MCP and skills for other agents
+ - `docs/research/` — the research this is built on (Higgsfield inventory, studios, image studios, marketing and agents, API, round-4 changes, in-house products; paid model APIs parts 1–4; ComfyUI equivalents parts 1–4; workflow library; the round-4 UX and speed audit; open recipes for Fuobe Originals; Openjutsu and Akatz Labs' H3 Character Swap; Liner UI language); [`docs/research/README.md`](docs/research/README.md) says what each file covers
- `docs/workers/tribe-v2.md` — the optional, non-commercial TRIBE v2 worker contract for the Virality predictor
+- `docs/deploy.md` — how fuobe.com is hosted and auto-deployed from `main` (server files in `deploy/fuobe.com/`)
- `scripts/comfy/` — the pipeline that exports and validates the ComfyUI workflow library
- - `skills/` — Assist's built-in skills (`<name>/SKILL.md` with frontmatter: name, title, description, when_to_use, icon, studio, tags, offline hints)
+ - `scripts/eval/` — the Fuobe Originals evaluation harness: suites, metrics, blind review and the promote rule
+ - `skills/` — Assist's built-in skills (`<name>/SKILL.md` in the Agent Skills format: name, description and compatibility, with Fuobe's own fields under `metadata`: title, when_to_use, icon, studio, tags, offline hints); `.agents/skills/fuobe/` teaches another agent to drive Fuobe through MCP or the CLI
## Tech
- Next.js 16 (App Router, Cache Components) · React 19 · Tailwind CSS v4 · shadcn/ui (Radix) · TanStack Query · SQLite (better-sqlite3) · zod · fal.ai queue API · Replicate predictions API · Higgsfield API · ComfyUI HTTP + WebSocket API · Anthropic SDK (Claude) · Ollama, LM Studio, Unsloth Studio and OpenAI-compatible chat APIs · @xyflow/react (Canvas) · @google/model-viewer + three (3D) · unpdf (PDF text) · cmdk · WebGL · server-sent events · Vitest · Playwright.
-Next.js 16 (App Router, Cache Components) · React 19 · Tailwind CSS v4 · shadcn/ui (Radix) · TanStack Query · SQLite (better-sqlite3) · zod · fal.ai queue API · Replicate predictions API · ComfyUI HTTP + WebSocket API · Anthropic SDK (Claude) · Ollama · @xyflow/react (Canvas) · @google/model-viewer + three (3D) · unpdf (PDF text) · cmdk · WebGL · server-sent events · Vitest · Playwright · Python with uv (the evaluation harness's metrics).
++Next.js 16 (App Router, Cache Components) · React 19 · Tailwind CSS v4 · shadcn/ui (Radix) · TanStack Query · SQLite (better-sqlite3) · zod · fal.ai queue API · Replicate predictions API · ComfyUI HTTP + WebSocket API · Anthropic SDK (Claude) · Ollama, LM Studio, Unsloth Studio and OpenAI-compatible chat APIs · @xyflow/react (Canvas) · @google/model-viewer + three (3D) · glTF Transform + meshoptimizer + sharp (the server's GLB finish) · headless Chromium through playwright-core (the CPU turntable) · unpdf (PDF text) · cmdk · WebGL · server-sent events · Vitest · Playwright · Python with uv (the evaluation harness's metrics).
## License notes
- Fuobe's code is open source. Model weights have their own licenses: several open models used here are **non-commercial** (FLUX.1/FLUX.2 [dev], inswapper, MMAudio weights, USO's FLUX.1 base, some LoRAs, ComfyUI-Whisper's node code, TRIBE v2), HunyuanVideo-Foley and Hunyuan3D 2.1 exclude the EU, UK and South Korea, and Stable Audio 3 is free under US$1M revenue (Stability Community licence). The Workflows page and `docs/research/comfyui-oss*.md` list each license. Cloud models are billed by your provider.
-Fuobe's code is open source. Model weights, LoRAs and ComfyUI node packs have their own licenses, and Fuobe treats them as information, not gates: **Settings → Models & licences** shows each one's licence and class (commercial use allowed, commercial use with conditions, restricted regions, non-commercial, research only, proprietary paid API, licence unknown), each with a switch. Everything starts switched on, so check what your use allows and switch off what doesn't fit. Several open models used here are **non-commercial** (FLUX.1/FLUX.2 [dev] and FLUX.2 [klein] 9B, which Soul ID can also train on, inswapper, MMAudio weights, USO's FLUX.1 base, some LoRAs, ComfyUI-Whisper's node code, now installed by default, TRIBE v2), HunyuanVideo-Foley and Hunyuan3D 2.1 exclude the EU, UK and South Korea, MiniMax H3 (Character swap's default, H3 Person Removal and the Character Swap Studio) excludes the US, the EU, the UK and South Korea, needs MiniMax's written authorization above US$20M yearly revenue and asks commercial products to show "MiniMax H3", Stable Audio 3 is free under US$1M revenue (Stability Community licence), and VOID (Remove object's "Shadows and reflections too" on the open engine) is built on CogVideoX-5B, whose licence asks you to register before commercial use. Fuobe DoP · LTX on your GPU uses LTX-2.3 under the LTX-2 Community License (free below US$10M annual revenue) and the Gemma terms, TRELLIS.2 and TripoSplat encode with DINOv3 (the DINOv3 License; their results show "Built with DINOv3"), and Akatz Labs' two H3 node packs are GPL-3.0. The Workflows page, **Settings → About & licences**, `docs/research/comfyui-oss*.md` and `docs/research/openjutsu-6.md` list each license. LoRAs have their own too: **Settings → LoRAs** shows each one's (commercial or not, your GPU only or also the cloud), and a LoRA licensed for your GPU only goes to fal or Replicate like any other, with a note, unless **Keep them on your GPU** is on. The Soul ID dialog shows each training's licence next to its price. Cloud models are billed by your provider, and Models & licences classes every fal and Replicate route as a proprietary paid API whatever its weights' licence, so the Non-commercial switch doesn't reach the hosted FLUX [dev] models.
++Fuobe's code is open source. Model weights, LoRAs and ComfyUI node packs have their own licenses, and Fuobe treats them as information, not gates: **Settings → Models & licences** shows each one's licence and class (commercial use allowed, commercial use with conditions, restricted regions, non-commercial, research only, proprietary paid API, licence unknown), each with a switch. Everything starts switched on, so check what your use allows and switch off what doesn't fit. Several open models used here are **non-commercial** (FLUX.1/FLUX.2 [dev] and FLUX.2 [klein] 9B, which Soul ID can also train on, inswapper, MMAudio weights, USO's FLUX.1 base, some LoRAs, ComfyUI-Whisper's node code, now installed by default, TRIBE v2), HunyuanVideo-Foley and Hunyuan3D 2.1 exclude the EU, UK and South Korea, MiniMax H3 (Character swap's default, H3 Person Removal and the Character Swap Studio) excludes the US, the EU, the UK and South Korea, needs MiniMax's written authorization above US$20M yearly revenue and asks commercial products to show "MiniMax H3", Stable Audio 3 is free under US$1M revenue (Stability Community licence), and VOID (Remove object's "Shadows and reflections too" on the open engine) is built on CogVideoX-5B, whose licence asks you to register before commercial use. Fuobe DoP · LTX on your GPU uses LTX-2.3 under the LTX-2 Community License (free below US$10M annual revenue) and the Gemma terms, Pixal3D, TRELLIS.2 and TripoSplat encode with DINOv3 (the DINOv3 License; their results show "Built with DINOv3"), and Akatz Labs' two H3 node packs are GPL-3.0. The Workflows page, **Settings → About & licences**, `docs/research/comfyui-oss*.md` and `docs/research/openjutsu-6.md` list each license. LoRAs have their own too: **Settings → LoRAs** shows each one's (commercial or not, your GPU only or also the cloud), and a LoRA licensed for your GPU only goes to fal or Replicate like any other, with a note, unless **Keep them on your GPU** is on. The Soul ID dialog shows each training's licence next to its price. Cloud models are billed by your provider, and Models & licences classes every fal and Replicate route as a proprietary paid API whatever its weights' licence, so the Non-commercial switch doesn't reach the hosted FLUX [dev] models.
diff --cc docs/ARCHITECTURE.md
index bd6bcb41,9aca8950..856580f5
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@@ -1,9 -1,11 +1,11 @@@
# Architecture
- Fuobe is a single Next.js 16 app. The browser talks only to Fuobe's own API; the server talks to providers (fal.ai, Replicate, Higgsfield, ComfyUI, and Claude or a local LLM server for text: Ollama, LM Studio, Unsloth Studio or any OpenAI-compatible one) and stores every input and output locally, so the library never depends on a provider's expiring URLs.
-Fuobe is a single Next.js 16 app. The browser (and the `fuobe` command line) talks only to Fuobe's own API; the server talks to providers (fal.ai, Replicate, ComfyUI, and Claude or Ollama for text), fetches LoRA files from Hugging Face and civitai when a run needs them, and stores every input and output locally, so the library never depends on a provider's expiring URLs. Since round 4 part 4 the admin decides which models, providers, licence classes, node packs and LoRAs the install offers (Settings → Models & licences; everything is on by default), and a read-only share link (`/s/<token>`) opens one page and its files without a session. Since round 4 part 5 Fuobe calls no Higgsfield API: Higgsfield is only what Fuobe is measured against, and a stored or scripted reference to one of its models runs on what replaced it (see Retired models).
++Fuobe is a single Next.js 16 app. The browser (and the `fuobe` command line) talks only to Fuobe's own API; the server talks to providers (fal.ai, Replicate, ComfyUI, and Claude or a local LLM server for text: Ollama, LM Studio, Unsloth Studio or any OpenAI-compatible one), fetches LoRA files from Hugging Face and civitai when a run needs them, and stores every input and output locally, so the library never depends on a provider's expiring URLs. Since round 4 part 4 the admin decides which models, providers, licence classes, node packs and LoRAs the install offers (Settings → Models & licences; everything is on by default), and a read-only share link (`/s/<token>`) opens one page and its files without a session. Since round 4 part 5 Fuobe calls no Higgsfield API: Higgsfield is only what Fuobe is measured against, and a stored or scripted reference to one of its models runs on what replaced it (see Retired models).
```
- proxy.ts: hostAllowed() (no password set) → crossSite() → sign-in (session cookie or API token)
+ proxy.ts: hostAllowed() (no password set) → crossSite() → share links (GET / HEAD on /s/<token>[/f/<path>]: openShare, no session)
+ → sign-in (session cookie or API token)
+ → a real 404 for an unknown app, hub mode or record id (src/server/records.ts)
│
Composer / studio (React) ──POST /api/generations (or a studio route that builds a pipeline)
│
@@@ -43,43 -58,77 +58,77 @@@ Feed, Library, studios (React Query cac
| file | what |
|---|---|
- | `types.ts` | `ModelDef`, `ModelRoute`, `FieldMap`, `ModelOptions`, `Pricing`, `Preset`, `GenerationRequest`, `ChainSlot`, `GenInput`, `Generation`, `OutputFile` |
- | `cloud-models.generated.ts` | fal / Replicate models. **Generated** by `scripts/gen-cloud-models.py` from the verified API schemas in `docs/research/paid-model-apis.json`, `-2.json` and `-3.json` (key fields merged, per-route options, sliders and controls read from the research, required inputs filled from their documented defaults) — field names, enums, defaults and prices are never typed by hand |
- | `higgsfield-models.generated.ts` | Higgsfield-only models (Soul, Genjutsu, Cinema Studio, Marketing Studio, Ads Studio…) and extra Higgsfield routes for models also on fal. **Generated** by `scripts/gen-higgsfield-models.py` from `docs/research/higgsfield-api.json` |
- | `higgsfield-presets.generated.ts` | 106 Soul + 33 Soul 2.0 presets (ids, categories, descriptions), the 14 Photodump / Instadump packs and the 6 Fashion Factory templates. **Generated** by `scripts/gen-higgsfield-presets.py` from `higgsfield-image-studios.json`; the fallback for the style picker |
- | `models.ts` | Open-source models (ComfyUI workflow ids), fal utility models (Join clips, and the hidden Extract frame, Crop to size, Mix voice and music, Level audio, Forced Alignment), the browser-only models (`local` provider: Color Grade, Ad compositor) + the generated cloud lists (whose hidden chain helpers include Trim video, Add soundtrack, Voice timeline and Extract soundtrack) |
- | `llm-models.ts` | `text-llm` (cloud: Claude, else a local model) and `oss-text-llm` (open: a local model only, route endpoint `ollama`), kind `text`, ops `translate` and `write` |
- | `elements.ts` | Elements (character / location / prop / style / voice), `@handle` parsing and `applyMentions` |
+ | `types.ts` | `ModelDef`, `ModelRoute`, `FieldMap`, `ModelOptions`, `Pricing`, `Preset`, `GenerationRequest`, `ChainSlot`, `GenInput`, `Generation`, `OutputFile`; since round 4 `VideoFormat`, `MatteOutput`, `PixelPoint`, `FocusPoint`, `COLORMAPS` and `ReviewStatus`; since round 4 part 2 `LoraField`, `LoraLicence` and `CHAIN_LIST_SLACK`; since round 4 part 3 `ModelDef.engines`, `engineDefaults` and `engineOptions`, `GenerationRequest.engine`, `ModelOptions.looks`, `Preset.grade` and `prestep` (`PresetPrestep`), `PresetRoute.partner`, `Pricing.roundUp` and `animationUsd`, and `FieldMap.size.table` / `key`; since round 4 part 4 `ModelLicence` (`ModelDef.licence`: the hosted weights' licence, information only), `LoraRef.own` (a trained Soul ID LoRA Fuobe keeps) and `keepOnGpu`, `ChainSlot.optional`, `GenerationRequest.chainSkipped` and `notice`, and `Pricing.videoMegapixel` and `withLorasByResolution`; since round 4 part 5 `PixelPoint.frame` (a click on a later frame of a clip: SAM 3.1's `frame_index` on fal), while `ProviderId`, `ModelOptions` and `ModelDef` lose Higgsfield's `higgsfield`, `presets` and `identity` |
+ | `cloud-models.generated.ts` | fal / Replicate models. **Generated** by `scripts/gen-cloud-models.py` from the verified API schemas in `docs/research/paid-model-apis.json`, `-2.json`, `-3.json` and `-4.json` (key fields merged, per-route options, sliders and controls read from the research, required inputs filled from their documented defaults) — field names, enums, defaults and prices are never typed by hand. Since round 4 part 2 it also reads the hosted open-weight endpoints of `docs/research/fuobe-originals-recipes-5.json` (`hostedLoraEndpoints`, `hostedBaseEndpoints`) into LoRA routes: `FieldMap.loras`, `loraEndpoint` and `Pricing.withLoras`. Since round 4 part 3 it also writes `ORIGINAL_CLOUD`, the cloud halves of the five Fuobe Originals (fal and Replicate routes, Soul's size table, DoP's fixed values; see Fuobe Originals), and the hidden helpers `qwen-image-edit-2509-cloud` and `ltx-2-5-fast`. Since round 4 part 4 (200 → 209 cloud models): `ORIGINAL_CLOUD` holds 12 cloud halves (adding Fuobe Cinema, the five Genjutsu Originals and Fuobe Character swap); five hosted LoRA models for Soul ID's families (`flux-1-dev-lora-cloud`, `flux-1-krea-lora-cloud`, `flux-2-dev-lora-cloud`, `flux-2-klein-9b-lora-cloud`, `krea-2-turbo-lora-cloud`); four Genjutsu partners (`wan-22-animate-replace`, `scail-2`, `wan-motion`, `h3-max-recast`); and `ModelDef.licence` on the hosted models whose weights the research licensed (13) and on 7 of the Originals' cloud halves. It also reads the research's `hostedBaseEndpoints` for the new fal routes. Since round 4 part 5 it also reads the recipes JSON's `partnerEndpoints`: Happy Horse 1.1 (`happy-horse-1-1`: text, image and reference to video, up to 9 references, $0.14/s at 720p, $0.18/s at 1080p), which only Higgsfield hosted, now runs on fal (this file grows from 209 to 210 entries, hidden helpers included; the cloud models Fuobe lists go from 209 to 197 as the retired ones leave, see Retired models); Grok Imagine Image 2.0 takes 5 references (fal's limit), and no tagline names Higgsfield's products any more |
+ | `trainers.generated.ts` | Round 4 part 4. The fal trainers (`HOSTED_TRAINERS`: endpoint, fields, price per step, the output field the LoRA comes back in, licence). **Generated** by `scripts/gen-trainers.py` from `fuobe-originals-recipes-5.json`'s trainers; `training.ts` prices Soul ID from it |
+ | `studio-packs.generated.ts` | Round 4 part 5. The 14 Photodump / Instadump packs and the 6 Fashion Factory templates (name, photo or shot count, description). **Generated** by `scripts/gen-studio-packs.py` from the research in `higgsfield-image-studios.json`. It replaces `higgsfield-presets.generated.ts`, which went with `higgsfield-models.generated.ts` and their generators (see Retired models); the Soul preset fallback list and `presetPrompt` left `packs.ts` with it |
+ | `replaced.ts` | Round 4 part 5 (O7). What replaced each retired model, training target and lost operation, pure and browser-safe: `REPLACED_BY` (12 model ids → the model that does the job now, with `was`, the name it ran under, a `note`, and `original`, `ops`, `withReferences` and `director` where they apply), `TRAINING_REPLACED_BY`, `OPS_REPLACED_BY`, `replacedBy`, `currentModelId`, `replacementOf` and `migrateRequest` (see Retired models) |
+ | `models.ts` | Open-source models (ComfyUI workflow ids), fal utility models (Join clips, and the hidden Extract frame, Crop to size, Mix voice and music, Level audio, Forced Alignment), the browser-only models (`local` provider: Color Grade, Ad compositor) + the generated cloud lists (whose hidden chain helpers include Trim video, Add soundtrack, Voice timeline and Extract soundtrack). A launch price (`Pricing.promo`) is applied when the list loads (`withCurrentPrice` → `pricingAt`). Since round 4 part 3 `MODELS` starts with the Fuobe Originals: `original()` joins each one's ComfyUI routes to its generated cloud half. Since round 4 part 5 the cloud list is `CLOUD_MODELS` and the cloud tools only (no Higgsfield models or routes are joined, and the hand-written `ai-influencer` is gone), and two hidden open models run Character Swap Studio's graphs: `oss-h3-swap-segment` (`video-swap` on `video-character-swap-h3-segment`) and `oss-h3-person-mask` (`bg-remove-video` on `video-mask-h3-relay`) |
-| `llm-models.ts` | `text-llm` (cloud: Claude, else Ollama) and `oss-text-llm` (open: Ollama, never Claude; since round 4 its translations run on ComfyUI's Qwen3.5 4B, `oss-qwen35-translate`, when Ollama isn't running), kind `text`, ops `translate` and `write` |
++| `llm-models.ts` | `text-llm` (cloud: Claude, else a local model) and `oss-text-llm` (open: a local model only, never Claude, route endpoint `ollama`; since round 4 its translations run on ComfyUI's Qwen3.5 4B, `oss-qwen35-translate`, when no local model server is ready), kind `text`, ops `translate` and `write` |
+ | `elements.ts` | Elements (character / location / prop / style / voice), `@handle` parsing and `applyMentions`; since round 4 part 4 an element holds up to 80 photos (`MAX_ELEMENT_PHOTOS`) and a mention brings its trained LoRA to every model of the LoRA's family on either engine (`identityFor`); since round 4 part 5 an older Soul ID (Higgsfield's `referenceId`) goes to no model; the element shows "Older Soul ID" with "Retrain for Fuobe Soul" (nothing retrains by itself) |
| `sketch.ts` | `applySketch` (masks and drawings → the right operation and inputs) |
| `storyboard.ts` | Storyboard models per engine, scene splitting and frame prompts |
- | `training.ts` | Training targets (Soul ID, fal Z-Image LoRA, AI-Toolkit), `aiToolkitJob` (character or style preset) and `trainingCaption` |
- | `apps.ts`, `motions.ts` | 123 apps, 108 camera motions, 255 effects: prompt templates, input slots, option pickers, cloud and open routes. `APP_ALIASES` keeps renamed app ids working |
- | `oss-loras.generated.ts` | Higgsfield preset name → researched Wan LoRAs + trigger words (`scripts/gen-oss-loras.py`) |
- | `index.ts` | Lookup helpers; attaches LoRAs / Wan Fun Camera poses / ReActor to open routes; registers the LLM models |
- | `plan.ts` | Pure planning logic (operation inference, prompt composition, batching, input validation, cost estimate) |
- | `payload.ts` | `buildPayload(FieldMap, GenInput)`, `extractMedia(response)`, `extractOutputs(response, op)` (structured outputs) and `noOutputsError` |
- | `palettes.ts` | `applySignature` (Color signature / Moodboard picks → native palette, style id, or words) and `withSignatureWords` |
- | `cinema.ts`, `canvas.ts`, `shorts.ts`, `shorts-models.ts`, `mixed-media.ts`, `marketing.ts`, `faceless.ts`, `packs.ts` | Each studio's data and pure planner, shared by client and server (see Studios) |
+ | `training.ts` | Fuobe Soul ID (round 4 part 4; see Training): the 7 families (`TRAINING_FAMILIES`: each base's models, lead model and fal trainer), the 13 targets (`TRAINING_TARGETS`: 5 AI-Toolkit, 8 fal), the photo rules and consent line (`SOUL_ID_PHOTOS`, `SOUL_ID_COPY`, `needsConsent`), prices (`trainerCost`), `falTrainingInput` and `trainedLoraUrl`, `AITK_MODELS` and `aiToolkitJob` (character or style preset), `identityFor` (an element's LoRA for a model's family), `trainingCaption`. Higgsfield Soul ID is no longer a target |
+ | `character-swap.ts` | Round 4 part 4. Genjutsu's Character swap, pure (see Fuobe Originals): limits (`CHARACTER_SWAP`), who to swap, the H3 window plan and canvas (`windowPlan`, `h3Canvas`, `samCoords`), prompts (`swapPrompt`, `anchorPrompt`), the anchor models, the swap, Turbo and Person Remover LoRAs with their pinned files (`SWAP_LORAS`, `TURBO_LORA`, `PERSON_REMOVER_LORA`, `graphLoras`) and the licences as data (`CHARACTER_LICENCES`, `MINIMAX_H3_LICENCE`); since round 4 part 5 `H3_WORKFLOWS` also names Character Swap Studio's segment graph, so its LoRAs download before a run |
+ | `apps.ts`, `motions.ts` | 124 apps, 108 camera motions, 255 effects: prompt templates, input slots, option pickers, cloud and open routes. `APP_ALIASES` keeps renamed app ids working. Since round 4 part 3 `index.ts` rebuilds every motion's and effect's routes with `dopPreset` (`dop.ts`) |
+ | `engines.ts` | Round 4 part 3. Pure: which engine a model runs on. `enginesOf`, `runsOn`, `dualEngine`, `providerEngine`, `onEngine` (an Original as it runs on one engine) and `pickEngine` (see Fuobe Originals) |
+ | `swap-studio.ts`, `swap-studio-plan.ts`, `swap-studio-edit.ts` | Round 4 part 5. Character Swap Studio, pure (see Studios): the project document and its rules, every job's steps on each engine, and the page's edits |
+ | `soul.ts`, `soul-cards.ts` | Round 4 part 3. Fuobe Soul: `soulRecipe` (the look's words, LoRAs in slot order, tail, grade, overlay), `soulSize` / `soulMegapixels` (`FAL_MEGAPIXEL`), `promptWithLoras`, `soulPostSteps`, legacy id lookup. `soul-cards.ts` is the browser-safe part: look cards for the pickers, `DEFAULT_LOOK` (`v1-general`), the model ids; since round 4 part 4 `OWN_LOOK` (`own-style`: a moodboard trained as a style LoRA is the look; its LoRA carries it, with no look words, look LoRAs or grade) |
+ | `soul-originals.generated.ts`, `soul-looks.generated.ts` | Round 4 part 3. The 139 Soul looks with their recipes, tails, sizes, sampler and Soul Cinema's recipe, and the pickers' slim cards. **Generated** by `scripts/gen-soul-originals.py` from `fuobe-originals-recipes-5.json` and `higgsfield-image-studios.json` |
+ | `dop.ts` | Round 4 part 3. Fuobe DoP: `dopPreset` (a motion's or effect's open and cloud routes, its grade, its relight step), `presetLoras`, `DOP_GRADES`, the relight step's models and the Fun Camera poses (moved here from `index.ts`) |
+ | `oss-loras.generated.ts` | Since round 4 part 3 the preset → LoRA map v2 (`scripts/gen-oss-loras.py`): `OSS_LORAS` (168 keys, preset ids from the research's `motionsEffects` first, then round-1 Wan matches by slug; 99 files, 36 of them on civitai; round 4 part 4 added `motion-bts` with the BTS move's LTX-2.5 LoRA), each LoRA with its base and licence flags, and `DOP_RECIPES` (300 presets: status, Fun Camera pose, LTX-2.3 `cameraLora`, LTX-2.5 `cameraMotion`, alias) |
+ | `loras.ts` | LoRAs in a run, pure (round 4 part 2): library lookups (`libraryEntry`, `loraRef`), the licence rules (`gpuOnlyLicence`; since round 4 part 4 `localOnly` keeps such a LoRA off fal and Replicate only while Settings → Models & licences keeps GPU-only LoRAs on the GPU; `gated`; `needsToken` for civitai links), `fitLoras` (what a cloud route can carry, and notes on the rest), `lorasFit` (for route choice), `loraFields` (each API's payload shape) and `loraEndpointFor`; since round 4 part 3 `triggerOf` (a LoRA's trigger without its full stop or brackets). Downloads and mirrors are in `src/server/loras.ts` (see LoRAs) |
+ | `lora-library.generated.ts` | 114 researched LoRAs (67 looks, 23 motions, 24 effects), each with its pinned download, a unique local file name, SHA256, size and licence snapshot, plus the motion / effect preset → LoRA map (`MOTION_EFFECT_LORAS`). **Generated** by `scripts/gen-lora-library.py` from `fuobe-originals-recipes-5.json`. The downloader and Settings → LoRAs read it. Since round 4 part 3 Fuobe Soul's looks name its keys, and a DoP preset's LoRA that is a library file (47 of the map's 99) takes its pinned download and licence from it |
+ | `influencer-options.generated.ts` | The AI Influencer builder's data: 19 categories (Character type first) and their options, the 6 creature types with species, Shuffle's weights and the two clash messages (`CONFLICT_MESSAGES`). **Generated** by `scripts/gen-influencer-options.py` from `docs/research/higgsfield-delta-4.json`; the rules and the prompt compiler are in `src/lib/influencer.ts` |
+ | `index.ts` | Lookup helpers; motions and effects through `dopPreset` (effects also `withPrestepPrice`: the relight step's price), round-1 Wan LoRAs on video apps (`withOssLoras`), the apps' dedicated open workflows (`APP_OPEN_OVERRIDES`: ReActor, the Qwen relight, the try-on); registers the LLM models. Since round 4 part 3 `modelsFor` lists an Original for an operation only on the engines whose routes run it |
+ | `plan.ts` | Pure planning logic (operation inference, prompt composition, batching, input validation, cost estimate, `pricingAt`, `routeLoras`); since round 4 part 3 the Soul plan (`Plan.soul`, `Plan.notes`), `mixLoras`, and per-megapixel prices for every picture made; since round 4 part 4 `withoutTriggers` (a LoRA left out takes its trigger word with it), a character's strength scaling its LoRA on every model, and video priced per megapixel (`videoMegapixels`: the tier's real size × frames, Fuobe Cinema's LTX-2.3) |
+ | `payload.ts` | `buildPayload(FieldMap, GenInput)`, `extractMedia(response)`, `extractOutputs(response, op)` (structured outputs), `keepMatte` and `noOutputsError`; `sizeValue` takes an exact size table per tier and writes one `{width, height}` field when the map names a `key` (round 4 part 3: Fuobe Soul, fal's `image_size`); since round 4 part 5 `pointsValue` adds `frame_index` to a SAM point clicked on a later frame (`PixelPoint.frame`) |
+ | `palettes.ts` | `applySignature` (Color signature / Moodboard picks → native palette, style id, or words) and `withSignatureWords`; since round 4 part 3 curated moodboards are Fuobe Soul looks, and `locksByDefault` turns the palette lock on for Soul models; since round 4 part 4 a moodboard trained as a style LoRA runs as Fuobe Soul's `own-style` look on the Z-Image family, on either engine |
+ | `keyframes.ts` | Frames mode: which models take keyframes and how (`frameSupport`, `FRAMES_MODELS`), the strip's blockers and notes, gap checks (`chainGapProblem`) and the open film's clip plan (`planKeyframeClips`) |
+ | `cinema.ts`, `canvas.ts`, `canvas-board.ts`, `shorts.ts`, `shorts-models.ts`, `mixed-media.ts`, `marketing.ts`, `faceless.ts`, `packs.ts`, `remove-object.ts`, `genjutsu.ts`, `content-factory.ts` | Each studio's data and pure planner, shared by client and server (see Studios) |
- A **model** has one **route** per (operation, provider). A route's `FieldMap` translates Fuobe's canonical input (`prompt`, `images`, `image2`, `endImage`, `video`, `videos`, `audio`, `audios`, `aspectRatio`, `duration`, `voice`, `voiceAudio`, `dialogue`, `shots`, `draft`, `startTime` / `endTime`, `fps`, `palette`, `styleId`, `numLayers`, `sourceLanguage`, `targetLanguage`…) to the provider's field names. Dotted keys (`voice_settings.stability`) are written as nested objects; `setPath` ignores `__proto__`, `constructor` and `prototype`. `defaults` are sent unless the request sets them (applied before the canonical fields), `fixed` always wins (applied after). `sourceLanguage` may be `{key, values}`, matched to the API's list. `palette {key, format, background}` converts hex colours to each API's shape (Recraft on fal, Recraft on Higgsfield, Ideogram members with falling weights, plain lists). `tracks` and `timeline` build fal FFmpeg compose timelines. Masks are converted to each API's convention (white = change, black = change, or alpha) by a small PNG codec (`src/server/png.ts`).
+ A **model** has one **route** per (operation, provider). A route's `FieldMap` translates Fuobe's canonical input (`prompt`, `images`, `image2`, `endImage`, `video`, `videos`, `audio`, `audios`, `aspectRatio`, `duration`, `voice`, `voiceAudio`, `dialogue`, `shots`, `draft`, `startTime` / `endTime`, `fps`, `palette`, `styleId`, `numLayers`, `sourceLanguage`, `targetLanguage`…) to the provider's field names. Dotted keys (`voice_settings.stability`) are written as nested objects; `setPath` ignores `__proto__`, `constructor` and `prototype`. `defaults` are sent unless the request sets them (applied before the canonical fields), `fixed` always wins (applied after). `sourceLanguage` may be `{key, values}`, matched to the API's list. `palette {key, format, background}` converts hex colours to each API's shape (Recraft on fal's `{r,g,b}` objects, Ideogram members with falling weights, plain lists; an `rgb`-array format is still supported, unused since Higgsfield's Recraft route went). `tracks` and `timeline` build fal FFmpeg compose timelines. Masks are converted to each API's convention (white = change, black = change, or alpha) by a small PNG codec (`src/server/png.ts`).
- `ModelOptions` describe what the composer shows: aspect ratios, resolutions, durations, audio, end frame, multi-shot, draft mode, voices and voice cloning, languages, sliders, enum controls, provider-fetched preset lists, motion paths, and since round 3 `minImages` + `imageLabels` (try-on: "Person photo", "Add garment"), `promptless`, `maxVideos` / `maxAudios` (reference clips), `sourceLanguages` and `requires` ({images?, prompt?, msg}, checked in `planGeneration` before any job is created). `Pricing` gains `byResolution` (a price per `params.resolution`) and `inputSeconds` (per-second prices doubled for edits billed on input + output).
+ Round 4 adds 17 operations (`remove-object`, `video-swap`, `video-insert`, `keyframes`, `sdr-to-hdr`, `export-video`, `ocr`, `still-motion`, `audio-loop`, `audio-join`, `scene-3d`, `splat`, `text-to-3d`, `rig-3d`, `extract-frames`, `images-to-video`, `overlay`) with labels, output kinds and NEEDS, and the canonical params they use: `points` (clicked on the first frame), `keyframeTimes`, `format` (a `VideoFormat`: H.264, 10-bit H.265, ProRes 422 HQ or 4444, FFV1, EXR, and on the open engine HLG or PQ 10-bit), Ken Burns `zoomFrom` / `zoomTo` / `panFrom` / `panTo` / `easing`, `crossfade`, `sourceDuration`, `frameInterval`, `targetFps`, `slowdown`, `colormap`, `sideBySide`, `matteOutput`, `position`, `scale`, `animation`, and `inputs.model3d`. `FieldMap` gains a key for each (`points` in Bria's or SAM's shape, `keyframes` as image + frame index at the API's fps, `zoom` for fal's zoompan, `loop` by repetition, `numFrames` from the clip's length, `upscaleFactor` from the target size and the clip's shorter edge…), plus `ranges` (clamped and rounded before sending), `maxImages`, `omitEmptyPrompt` and `ignore`. `EnumField.accepts` sends the closest value an API takes when a model's routes take different lists (Grok Imagine Video 1.5's text and reference routes). `GenInput.sourceSize` and `sourceFps` (and `sourceDuration`, unless the request set it) are filled on the server from the input clip's header (`src/server/media-facts.ts`: MP4 / MOV, then WebM / Matroska, and since round 4 part 5 AVI through `src/server/avi-probe.ts`).
- `plan.ts` adds `promptOptional(model, op)` (promptless ops such as trim, mux, captions, layers, image-to-3d, vectorize), NEEDS entries with `oneOf` and `media` (transcribe and separate-audio take audio or video), a server-only check that rejects inputs no route can send (it needs the field maps the slim client catalog strips), and `inferOperation` picking `ref2v` when clips are attached.
+ `ModelOptions` describe what the composer shows: aspect ratios, resolutions, durations, audio, end frame, multi-shot, draft mode, voices and voice cloning, languages, sliders, enum controls and motion paths (the provider-fetched style lists, `ModelOptions.presets`, went with Higgsfield in round 4 part 5), and since round 3 `minImages` + `imageLabels` (try-on: "Person photo", "Add garment"), `promptless`, `maxVideos` / `maxAudios` (reference clips), `sourceLanguages` and `requires` ({images?, prompt?, msg}, checked in `planGeneration` before any job is created). `Pricing` gains `byResolution` (a price per `params.resolution`) and `inputSeconds` (per-second prices doubled for edits billed on input + output). Round 4 adds `promptOptional` (the box shows, but the model also runs without words), `requires.mask` / `points` (video erasers), `formats`, `colormaps`, `sideBySide`, `matteOutputs`, `keepsNamed`, `fpsTargets`, `slowdowns` and `labels` on controls; `ModelDef.worker: "isolated"`; `ModelRoute.chained` (a route the server builds as several jobs: the open keyframe film) and `ModelRoute.preview` (the parts of the map the composer previews a result with, kept in the slim client catalog). `Pricing` gains `promo` (a launch price to a date: FLUX 3 Max at 720p is $0.0425/s until 2026-11-07, then $0.17/s) and `factors` (multipliers by a setting: Topaz 60 fps ×2, ByteDance Pro ×10, FLUX.3 Creative about ×1.4).
- A **preset** (app / motion / effect) has a `cloud` and an `open` route, each naming a model and operation, optional fixed params and LoRAs. Apps pin their model; motions and effects add their camera / effect prompt to whichever video model the user picks (LoRAs only apply to the preset's own open model). `PresetChoice.extra` lets an option set model `params.extra`.
+ `plan.ts` adds `promptOptional(model, op)` (promptless ops such as trim, mux, captions, layers, image-to-3d, vectorize), NEEDS entries with `oneOf` and `media` (transcribe and separate-audio take audio or video), a server-only check that rejects inputs no route can send (it needs the field maps the slim client catalog strips), and `inferOperation` picking `ref2v` when clips are attached. Since round 4, two or more images are `keyframes` when they carry `keyframeTimes` (or the model has no `ref2v` and no chained route), checked by `checkKeyframes` (on a chained route: up to 10, the first at 0 s, every gap within the model's clip lengths); a `format` the model doesn't write is refused; `checkVideoToolOptions` refuses colour maps and matte outputs the model can't make, and Remove background fills `params.matteOutput` with the model's first; a remove-object request can name its target with a mask or points instead of words when a route reads them (`markedTarget`). `estimateCost(model, params, jobs, op)` prices upscale-video, interpolate, sdr-to-hdr and export-video by the clip's seconds (`params.sourceDuration`; slow motion by the stretched length) and applies `Pricing.factors`. `chooseRoute` (in `src/server/generations.ts`) passes over a route whose image list takes fewer images than the run sends (`FieldMap.maxImages`).
- ## Providers (`src/server/providers/`)
+ Round 4 part 2 makes LoRAs part of any run (see LoRAs). `FieldMap.loras` is a `LoraField` in one of four shapes: `items` (fal's `loras: [{path, scale, transformer?, weight_name?}]`, with a maximum, a scale range and whether the API refuses an empty list), `arrays` (Replicate's `lora_weights[]` + `lora_scales[]`), `experts` (one LoRA per Wan 2.2 expert, Replicate's Wan 2.2 fast) and `single` (one URL and one scale field). `FieldMap.size` writes width and height from the aspect ratio on a base×base pixel budget (Replicate's Z-Image LoRA model), and `numFrames` gains `step` (Wan 4n+1, LTX 8n+1 frames) and `fromDuration` (extend: the frames to add, at the clip's own frame rate when known). `ModelRoute.loraEndpoint` is now called whenever a run carries LoRAs, not only for a trained identity, and `Pricing.withLoras` is its price. `LoraRef` gains `weightName`, `hostedUrl` (a mirror), `version` (a civitai version id or a Hugging Face commit) and `licence` (`LoraLicence`: commercial, hostedOk, the snapshot date, civitai's permissions). In `plan.ts`, `planGeneration` puts the request's own LoRAs (an @character's trained identity) before a preset's and a Mix's, so on an API that takes few the identity wins, and leaves out a LoRA at strength 0 together with its trigger word at the start of the prompt; `routeLoras(route, loras)` says which LoRAs a route applies and why each other one is dropped; `estimateCost(…, withLoras)` uses the LoRA endpoint's price (the server's estimate does; the composer's own price doesn't yet); and a concat of one clip plus an appended still counts as two clips (an ad and its end card). `chooseRoute(candidates, images, loras, seconds)` now prefers a ready route that carries every LoRA and makes the clip length asked, then one that carries the LoRAs, then one that makes the length, then the first ready one, so a LoRA or length fit wins over Preferred provider. `prepare()` then fits the LoRAs to the route (`fitLoras`) and adds a note when a frame-count API can't make the length asked (`framedLength`: Replicate's Wan 2.2 fast renders 81–121 frames); since round 4 part 3 such a run is also priced at the length it makes (the composer's price before the run still uses the length asked). The notes come back on the created generations (`Generation.notes`) and in the answer of `POST /api/generations` (and its preview), and the composer shows them as a warning toast; they aren't stored.
+
+ Round-4 open models in `models.ts`: the erasers `oss-vace-remove`, `oss-vace-remove-painted` and `oss-void-remove`; `oss-vace-swap` and `oss-vace-insert`; `oss-rife` (now `interpolate-rife-fps`), `oss-seedvr2` and `oss-upscale-video-esrgan` (now the chunked graphs, by target size), `oss-sdr-to-hdr` and `oss-export-video`; `oss-scene-moge`; `oss-vtracer`; and the hidden helpers `oss-ken-burns`, `oss-join-encoded`, `oss-audio-loop` and `oss-audio-join`. Wan 2.2 14B and Wan 2.2 14B Lightning get a chained `keyframes` route (`KEYFRAME_FILM` on `wan22-flf2v-14b`). `oss-latentsync` and `oss-thinksound` are no longer hidden; they carry `worker: "isolated"`. Round 4 part 2 wires four library graphs: `oss-ocr-lines` (OvisOCR3 on `ocr-lines-qwen35`, Layers' open text detection) and the hidden helpers `oss-reference-brief` (Gemma 4 E4B on `reference-brief-gemma4`, Content Factory), `oss-append-endcard` (`video-append-endcard`) and `oss-still-to-clip` (`still-to-clip`) for the Click to Ad end card. The cloud lists gain Seedream 5.0 Flash (`seedream-5-flash`, Mixed Media's cheaper frame editor) and six hosted open-weight models with LoRA routes: `qwen-image-2512-cloud`, `qwen-image-edit-2511-cloud`, `flux-2-klein-4b-cloud`, `wan-2-2-a14b-image-cloud`, `wan-2-2-a14b-cloud` and `ltx-2-3-22b-cloud`; `z-image-turbo-cloud` gains a LoRA field on fal and a Replicate route that takes LoRAs.
+
+ Round 4 part 3 adds the five Fuobe Originals (`fuobe-soul`, `fuobe-soul-hd`, `fuobe-soul-cinema`, `fuobe-dop`, `fuobe-dop-ltx`; see Fuobe Originals), three open 3D models (`oss-trellis2-multi` on the new `image-to-3d-trellis2-multiview`, `oss-text-trellis2`, whose `text-to-3d` route is `chained`, and `oss-triposplat` on `image-to-splat-triposplat`) and the hidden Canvas helper `oss-fit-clip` (`video-fit-clip`). In the cloud lists, `sam-3d-objects` now always asks for a textured GLB (`export_textured_glb`), `meshy-7-1-multi` takes at least 2 photos, and `meshy-rigging` adds $0.12 when an animation is asked for (`Pricing.animationUsd`). `estimateCost` now prices a per-megapixel model for every picture made (before, one picture whatever the count), with Soul's real megapixels and whole megapixels where `roundUp` is set.
+
+ Round 4 part 4 adds seven Fuobe Originals: `fuobe-cinema` (O6), the five Genjutsu Originals `fuobe-genjutsu-motion`, `fuobe-genjutsu-motion-lite`, `fuobe-genjutsu-swap`, `fuobe-genjutsu-swap-lite` and `fuobe-genjutsu-restyle`, and `fuobe-character-swap` (O5; see Fuobe Originals). Two open models run Akatz Labs' H3 Relay 2.0 graphs: `oss-h3-character-swap-relay` (Character swap's open alternative) and `oss-h3-person-remove` (Remove object's "H3 Person Removal" eraser). `Pricing.videoMegapixel` prices a frame-count video model on the clip's real size for its tier and shape × its frames, rounded up to whole megapixels (`withLoras` for the LoRA endpoint; today only Fuobe Cinema sets it), and `Pricing.withLorasByResolution` gives the LoRA price per resolution.
- Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and optionally `cancel` and `test`. `RemoteOutput` carries optional `text` and `meta`.
+ Round 4 part 5 removes the Higgsfield catalog (O7: `higgsfield-models.generated.ts` with the `HIGGSFIELD_ROUTES` of 24 partner models, and the hand-written `ai-influencer`): 12 models are retired and Happy Horse 1.1 moves to fal, so the cloud lists go from 209 to 197 models; what a stored reference to them runs on is in `replaced.ts` (see Retired models). `planGeneration` no longer asks for a provider preset. Two hidden open models run Character Swap Studio's new graphs (`oss-h3-swap-segment`, `oss-h3-person-mask`; see Studios).
- - **fal** — queue API (`queue.fal.run/<endpoint>`); always uses the `status_url` / `response_url` returned at submit. Files go to fal storage via `@fal-ai/client`.
- - **replicate** — predictions API; small files as data URIs, larger via the Files API. Outputs are copied immediately (Replicate deletes them after an hour).
- - **higgsfield** — `api.higgsfield.ai` with `Key id:secret` auth: submit with idempotency keys, poll `/requests/<id>/status` (only the documented result fields are read; extra files such as zip or fbx land in `meta.artifacts`), cancel, signed-URL uploads, live style / template lists, and Soul ID training.
- - **comfyui** — loads `workflows/comfyui/manifest.json`. `prepareWorkflow()` turns a `GenInput` into the prompt: canonical keys → bindings, uploads it makes itself (including media refs in `params.extra`), LoRA nodes after each diffusion-model loader, width / height from aspect ratio + tier, frame counts as `n·step+1`, the palette as a hex sentence plus a 512×512 swatch rendered on the server, `SLOT_RULES` (repeat, required, hints) per workflow, and graph rewrites for `expand: "captions"` (`expandCaptionWorkflow` in `src/lib/comfy.ts`) and `expand: "timeline"` (`expandTimelineWorkflow` in `src/lib/av/timeline.ts`). A left-out reference in a FLUX.2 ReferenceLatent chain is removed by `bypassReference()`. The second audio track is read from `inputs.audio2` (else `params.extra.audio2`); a mux with no background picks the one-track graph. `prepareFile` records each upload's header facts (`src/lib/media-probe.ts`: MP4 / MOV / M4A with rotation, WAV, FLAC, MP3) so the "auto" shape, trim checks, lip-sync frames, the mux bed length, caption windows and the Whisper RAM guard use them. Progress comes over the websocket (reset when the URL changes), results from `/history`; `collectOutputs()` maps them in manifest order (text with cues and language, `model3d`, stems with `meta.stem`, layers back to front with `meta.z / name / bbox`, roles, VHS meta-batch passes followed by their `fuobe/<generationId>` filename prefix). A 502 or a missing prompt is retried; a prompt fails only after it is missing three polls in a row. The first `isConfigured()` per URL waits for a real probe from a worker thread (`probeComfySync`, at most 1.5 s).
+ A **preset** (app / motion / effect) has a `cloud` and an `open` route, each naming a model and operation, optional fixed params and LoRAs. Apps pin their model; motions and effects add their camera / effect prompt to whichever video model the user picks (the preset's LoRAs, and since round 4 part 3 its LoRA's trigger word, apply only on the preset's own model, now on either engine). Since round 4 part 3 every motion and effect is Fuobe DoP's (`dopPreset`): a preset can carry a `grade` and a `prestep` (a relight before the clip), and a cloud route marked `partner` runs the preset's words on its old model until Fuobe DoP is measured on them. `PresetChoice.extra` lets an option set model `params.extra`.
+
+ ## Providers (`src/server/providers/`)
+
+ Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and optionally `cancel` and `test`. `RemoteOutput` carries optional `text` and `meta`. `prepareFile(data, type, name, route)` gets the route the file is for (ComfyUI sends an isolated-worker workflow's inputs to that worker). `test({ focus })` names the setting being checked, for a provider whose settings reach more than one server (the Anthropic key, the isolated worker's address).
+
+ - **fal** — queue API (`queue.fal.run/<endpoint>`); always uses the `status_url` / `response_url` returned at submit. Files go to fal storage via `@fal-ai/client`. The key test (15 s timeout) counts only 2xx, 400, 404 and 422 as "accepted"; a proxy or an outage (405, 407, 5xx) reads "Couldn't check the key". Since round 4 part 2, LoRAs go in the route's LoRA field (`routeLoraField`: one item per file, Wan 2.2's expert as `transformer`, `weight_name`, the scale clamped, at most the API's maximum) and the call switches to the route's `loraEndpoint` (`loraEndpointFor`; an endpoint that needs at least one LoRA is never called with none). `prepareFile` uploads a named `File`, so uploads keep their name and extension (a mirrored LoRA stays `.safetensors`).
+ - **replicate** — predictions API; small files as data URIs, larger via the Files API. Outputs are copied immediately (Replicate deletes them after an hour). Since round 4 part 2 it sends LoRAs (before, it ignored them): `lora_weights` / `lora_scales` arrays, one LoRA per Wan 2.2 expert, or one field, switching to the route's LoRA model when it has one (`loraEndpointFor`).
+ - **retired providers** (round 4 part 5). The Higgsfield adapter (`higgsfield.ts`) is gone, with its key, its key test and its live style lists (`GET /api/providers/higgsfield/presets`). Rows stored before still name it, so `provider(id)` (`index.ts`) gives a stand-in for a provider id Fuobe no longer has: `poll` fails the job with `RETIRED_PROVIDER_ERROR` ("This job ran on a provider Fuobe no longer uses, so its result can't be collected: run it again (Reuse picks the model that replaced it)"), `submit` and `prepareFile` throw it and `cancel` does nothing, so the runner no longer throws on every tick for such a row. `pollOne` gives the same message for a job whose model is gone because it was retired, or whose provider is unknown (see Retired models).
+ - **comfyui** — loads `workflows/comfyui/manifest.json`. `prepareWorkflow()` turns a `GenInput` into the prompt: canonical keys → bindings, uploads it makes itself (including media refs in `params.extra`), LoRA nodes after each diffusion-model loader, width / height from aspect ratio + tier, frame counts as `n·step+1`, the palette as a hex sentence plus a 512×512 swatch rendered on the server, `SLOT_RULES` (repeat, required, hints) per workflow, and graph rewrites for `expand: "captions"` (`expandCaptionWorkflow` in `src/lib/comfy.ts`) and `expand: "timeline"` (`expandTimelineWorkflow` in `src/lib/av/timeline.ts`). A left-out reference in a FLUX.2 ReferenceLatent chain is removed by `bypassReference()`. The second audio track is read from `inputs.audio2` (else `params.extra.audio2`); a mux with no background picks the one-track graph. `prepareFile` records each upload's header facts (`src/lib/media-probe.ts`: MP4 / MOV / M4A with rotation, WAV, FLAC, MP3) so the "auto" shape, trim checks, lip-sync frames, the mux bed length, caption windows and the Whisper RAM guard use them. Progress comes over the websocket (reset when the URL changes), results from `/history`; `collectOutputs()` maps them in manifest order (text with cues and language, `model3d`, stems with `meta.stem`, layers back to front with `meta.z / name / bbox`, roles, VHS meta-batch passes followed by their `fuobe/<generationId>` filename prefix). A 502 or a missing prompt is retried; a prompt fails only after it is missing three polls in a row. The first `isConfigured()` per URL waits for a real probe from a worker thread (`probeComfySync`: a 1.5 s request, and the wait gives the worker 1 s more; since round 4 part 5 it also opens a TCP connection, below).
+
+ Round 4:
+ - **Isolated worker routing.** `workerFor(endpoint)` reads the manifest's `worker: "isolated"`; that workflow's uploads, prompt, progress socket (a second websocket), polls and cancels go to Settings → Isolated worker URL (`comfyIsolatedUrl`, `COMFYUI_ISOLATED_URL`) instead of the main ComfyUI. With no address, or a worker that doesn't answer, the job fails with a message naming the setting; the connection test reports the worker beside the main server.
+ - **Per-request graph work** in `prepareWorkflow()`: EXR requests switch to their own graph (`exrWorkflow`); `videoFinishValues()` sets export formats, the HDR colour space, FPS Boost's multiplier and frame step (FrameInterpolate is bypassed when the multiplier is 1) and the size of each pass of a chunked graph (`framesPerPass`, about 1.5 GB of frames); Ken Burns zoom / pan / easing are bound; a graph with `limits.maxDurationSec` refuses longer jobs; a crossfade uploads a small fade-curve WAV (`fadeCurveWav`) and refuses clips too short for it (`crossfadeProblem`). Remove object turns the words into SAM 3.1's target (`targetPhrase`), fills the gap with a neutral scene prompt (`REMOVE_SCENE`) and keeps the painted graph's hand-off mask output only when `params.extra.handOffMask` asks; swap and insert take SAM's target from `maskPrompt` or the prompt (`swapTarget`) and refuse clicks. Depth maps bind `colormap` and `sideBySide`; Remove background deletes the save node not asked for (`matteOutput`). Graphs that hold a whole clip in memory are refused above half the server's RAM (`wholeClipProblem`; `comfyRam()` reads `/system_stats`).
+ - **Graph rewrites** in `src/lib/comfy.ts`: `tagMetaBatch` gives every VideoHelperSuite batch manager a per-job tag, and `dropVhsAudio` removes the sound link from VHS video loaders when the clip header says it is silent (both for every workflow that has those nodes, old ones too). `expand: "videos"` and `expand: "audios"` rewrite a join for every clip in one prompt (`expandVideoJoinWorkflow`, `expandAudioJoinWorkflow` in `src/lib/av/joins.ts`).
+ - **Results and cancel.** EXR frames (output role `frames`) are fetched one at a time into a stored zip in the scratch folder and ride on the preview clip as `meta.artifacts.exr` (`bundleFrames`). Cancel (`stopPrompts`) deletes every queued prompt carrying the job's filename prefix and interrupts the running one; a meta-batch job is swept again up to 5 times, 1 s apart (`sweepPasses`). Uploads of `.webm` and `.mkv` are probed too.
+ - **Round 4 part 2.** A graph with no diffusion-model loader refuses LoRAs instead of dropping them (`canTakeLoras` in `src/lib/comfy.ts`), and a missing-LoRA error points at the LoRA's model card and at Settings → LoRAs. `comfyLoraFiles(route)` reads `GET /models/loras` from the server that runs the route, for the download before submit (see LoRAs). An OCR graph's `lines` output is read by `parseOcrLines` (`src/lib/ocr.ts`: code fences, `bbox_2d` / `text_content`, 0–1000 boxes, cut-off answers) into text, `meta.lines` and `meta.size` (from its `frame` output); an answer with no list keeps its words, with `meta.unreadable`. `video-append-endcard` is bound to the ad's own width, height and fps from its header (an unreadable header is refused), and a silent ad loses the LoadAudio chain that would read its sound (`dropLoadedSound`).
+ - **Round 4 part 3.** Image uploads record their size (`imageSize`), so "auto" takes the start frame's shape on any graph when there is no clip header (before, the workflow's default size). Fuobe DoP: a request with a Fun Camera pose (`params.extra.cameraMotion`) on `wan22-i2v-14b` runs on `wan22-fun-camera-14b` (`CAMERA_POSE_GRAPH`), with any LoRAs injected as on the plain graph. Fuobe Soul's image to image binds `megapixels` (1 for 720p, 2 for 1080p; a new binding key in `scripts/comfy/build-library.mjs`). Multi-view 3D: `SLOT_RULES` can name `views` (the sides of one object, into one node); `viewSlots` puts each photo on the side `params.extra.views` names (in order when unnamed; two photos of one side are refused), and a side with no photo is cut out of the graph with its cut-out and crop (`dropBranch` in `src/lib/comfy.ts`), instead of reusing the previous image. The Canvas concatenator's `video-fit-clip`: a muted clip, or one whose header says it has no sound, gets stereo silence as long as its kept frames (`silenceVhsAudio`), so every clip of a packet-copy join carries a track; with no known length it gets no track. Splat outputs are typed `model/ply`, `model/x-spz` or `model/x-ksplat` (ComfyUI serves them as octet-stream), and an output with role `splat` carries `meta.format`.
+ - **Round 4 part 4.** `CAMERA_POSE_GRAPH` also moves Fuobe Cinema's `wan22-i2v-14b-lightx2v` to `wan22-fun-camera-14b` when a request carries a Fun Camera pose. Character swap (manifest capability `video-character-swap`, the H3 graphs): the quality goes out as the unpatched `h3_character_swap` pack's strings ("480" / "768", `packResolution`); the window and history frames are fitted to the pack's rules (`windowPlan`); `params.extra.lora` picks the swap LoRA's file, and "none" links the swap-LoRA loader out (`bypassNode`); clicks become SAM 3.1 coordinates in H3's canvas (`samCoords`) with `selection` index 0 (the clicked mask comes first); with no anchor frame (`images[1]`), `withoutAnchor` deletes the anchor loader and the `ImageScale` nodes that read only it, and sets `use_anchor` false; with no words, the prompt is Openjutsu's instruction (`swapPrompt`). In `submit()` (`generations.ts`), a graph that loads its own LoRAs (the H3 Turbo and swap LoRAs, or the Person Remover) gets them downloaded before the run like injected ones (`graphLoras`).
- - **Round 4 part 5: reachability.** A busy ComfyUI is no longer taken for a down one. Before, one `GET /system_stats` with a 1.5–2 s timeout decided, so a CPU ComfyUI busy with a job could send new runs to the demo provider. Now `probeComfy(force)` asks with a 2 s timeout (`askComfy`: yes, with the RAM it reports; no; or late). A refused connection, a name that doesn't resolve or an HTTP error is down at once. A late answer is busy, so reachable, when the server answered in the last 2 minutes (`seen`). Otherwise, when its port takes a TCP connection within 3 s (`takesConnection`, `node:net`), it gets one longer look of 10 s and counts as reachable if it answers then. A longer look that goes unanswered marks it down and isn't tried again for 2 minutes (`silent`), so further checks stay quick: a port that only takes connections (an ssh tunnel or a proxy whose ComfyUI is gone, a hung ComfyUI) isn't busy forever. The numbers are `REACH` (`answerMs`, `connectMs`, `lookMs`, `answeredLatelyMs`), exported for the tests; they aren't settings. Callers that arrive while a check of the same URL runs share it (`globalThis.__fuobeComfyProbe`); the 10 s cache is unchanged, and a check of an old address no longer overwrites the status of a new one. A busy record keeps its RAM, so `comfyRam()` still works. The blocking first check (`probeComfySync`) still waits at most 1.5 s plus 1 s, and its worker also opens a TCP connection: an answer is reachable, a refusal or an HTTP error unreachable, and no answer counts as reachable for now when the connection was taken (unreachable when it wasn't); either way a forced `probeComfy` settles it in the background. `isConfigured()`'s background refresh catches its errors. `GET /api/status` and `GET /api/comfyui` force a check and keep their shape, but can take longer: about 5 s for a host that drops packets, about 15 s for a port that answers late (at most once every 2 minutes per silent server). Right after start or an address change, a port that takes connections counts as up until the background check ends, so a run started then can go to a ComfyUI that never answers. Only the main URL is checked this way, not the isolated worker. Ollama's check (`probeOllama`) is unchanged and still takes a timeout as down.
++ - **Round 4 part 5: reachability.** A busy ComfyUI is no longer taken for a down one. Before, one `GET /system_stats` with a 1.5–2 s timeout decided, so a CPU ComfyUI busy with a job could send new runs to the demo provider. Now `probeComfy(force)` asks with a 2 s timeout (`askComfy`: yes, with the RAM it reports; no; or late). A refused connection, a name that doesn't resolve or an HTTP error is down at once. A late answer is busy, so reachable, when the server answered in the last 2 minutes (`seen`). Otherwise, when its port takes a TCP connection within 3 s (`takesConnection`, `node:net`), it gets one longer look of 10 s and counts as reachable if it answers then. A longer look that goes unanswered marks it down and isn't tried again for 2 minutes (`silent`), so further checks stay quick: a port that only takes connections (an ssh tunnel or a proxy whose ComfyUI is gone, a hung ComfyUI) isn't busy forever. The numbers are `REACH` (`answerMs`, `connectMs`, `lookMs`, `answeredLatelyMs`), exported for the tests; they aren't settings. Callers that arrive while a check of the same URL runs share it (`globalThis.__fuobeComfyProbe`); the 10 s cache is unchanged, and a check of an old address no longer overwrites the status of a new one. A busy record keeps its RAM, so `comfyRam()` still works. The blocking first check (`probeComfySync`) still waits at most 1.5 s plus 1 s, and its worker also opens a TCP connection: an answer is reachable, a refusal or an HTTP error unreachable, and no answer counts as reachable for now when the connection was taken (unreachable when it wasn't); either way a forced `probeComfy` settles it in the background. `isConfigured()`'s background refresh catches its errors. `GET /api/status` and `GET /api/comfyui` force a check and keep their shape, but can take longer: about 5 s for a host that drops packets, about 15 s for a port that answers late (at most once every 2 minutes per silent server). Right after start or an address change, a port that takes connections counts as up until the background check ends, so a run started then can go to a ComfyUI that never answers. Only the main URL is checked this way, not the isolated worker. The local LLM servers' check (`probeLocal`, also exported as `probeOllama`) is unchanged and still takes a timeout as down.
+ - **Round 4 part 5: Character Swap Studio and uploads.** `prepareWorkflow()` rewrites the studio's two graphs per job (`segmentGraph` and `maskGraph` in `src/lib/swap-studio-graphs.ts`, pure, keyed by `STUDIO_WORKFLOWS`). A segment (`video-character-swap-h3-segment`): without history the plan, the window and the append lose their initial history; with it, the previous take's master comes in as `historyVideo` from `historyStart` for `historyLength` frames; the approved mask replaces SAM's chain (`maskVideo` from `maskStart`); the anchor is Picture 2, or Picture 3 at the canvas size after a history boundary (`anchorAfterHistory`); masked generation off bypasses the edit mask; and an `ImageFromBatch` node (`master_tail`) keeps only the take's last `masterKeep` frames in its 16-bit FFV1 master (output role `master`). A mask (`video-mask-h3-relay`): words, a selection or clicks (moved into H3's canvas by `samCoords`) on frame `keyFrame`, followed for `spanFrames`, spliced between the frames of the version it corrects (`prevMask`), with blank frames before a track that starts mid-shot and has nothing to correct; a shot too long for the server's RAM is refused before it runs (`maskMemoryProblem`). An upload ComfyUI answers with HTTP 413 now fails in words, naming `--max-upload-size` (100 MB unless set), for every feature (on the isolated worker before its own message). `.avi` uploads are probed too (`aviInfo`).
- **llm** — text steps in this process (below).
- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites; `/api/generations/local` records them).
- - **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup.
+ - **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup. Round-4 operations answer too: a scene-3d job gets the GLB plus a grey depth PNG on the open engine and a Spectral-coloured depth PNG on the cloud, and an EXR job a sample clip with a zip that holds only a README. An extract-frames job returns as many frames as `max_frames` asks (4 without a count), so a per-frame Mixed Media demo fans out like the real one. Splat and rig jobs get the demo GLB too (`meta.format` `glb`), so a demo run never shows the splat card. Since round 4 part 5 a `video-swap` on Character Swap Studio's segment graph also returns a `master`, so a demo continuation runs like a real one.
## Structured outputs
@@@ -88,7 -137,7 +137,7 @@@ Outputs are not only media. `extractOut
| kind / meta | from |
|---|---|
| `text` with `.text`, `meta.cues [{start, end, text, speaker}]`, `meta.language` | transcribe, translate, write; saved as `.srt` when timed, else `.txt` |
--| `model3d` (GLB) with `meta.preview`, `meta.formats` | image-to-3d |
++| `model3d` (GLB) with `meta.preview`, `meta.formats`; on ComfyUI also `meta.web` (the web GLB the server's finish made) and `meta.finish` (version, material, the turntable's state and progress), plus a `video` output with `meta.role` `turntable` added after the job | image-to-3d |
| layers with `meta {name, z, bbox, bboxNormalized, description}` | Seedream layers, Qwen-Image-Layered (bbox from alpha) |
| `meta.textBlocks`, `meta.textHtml` on the background | Ideogram text layers |
| `meta.stem` (`voice` / `background`, aliases vocals, accompaniment…) | separate-audio |
@@@ -110,33 -174,99 +174,114 @@@ A generation can depend on others (`Cre
An audio slot can carry `stem` to take the output whose `meta.stem` matches ("voice" also matches vocals / speech / target; "background" also accompaniment / instrumental / residual / no_vocals). `pickOutput()` in `generations.ts` does the choosing; a missing stem fails the step with a clear message.
- **`createPipeline(steps, opts)`** creates any DAG of steps `{key, request, after?, chain?}`. Before a single row exists it checks duplicate or unknown keys, self-waits, loops (Kahn sort), chain-slot counts, that a step others depend on makes one job, and previews every step with placeholders; a mix of demo and real steps is refused (`assertOneMode`). Rows are created in topological order with `dependsOn`, labelled "Step n of N", and it returns `{batchId, items, byKey}`; if creation fails partway, what it started is canceled. Its TSDoc example is a whole dub. Layers, Shorts, Mixed Media, the palette lock, Photodump / Fashion / Character Sheet, Marketing Studio / Click to Ad / Ad Multiplier, dub, Katana and the Assist studio tools build their jobs this way; Cinema, Canvas, Faceless / Explainer, Ads Studio and moodboards call `createGenerations` (with `dependsOn` for chained steps) directly; Cinema, Canvas and Faceless preview every step first.
+ **`createPipeline(steps, opts)`** creates any DAG of steps `{key, request, after?, chain?}`. Before a single row exists it checks duplicate or unknown keys, self-waits, loops (Kahn sort, linear in steps + edges, since a per-frame render has hundreds), chain-slot counts and output numbers (`index` / `of`), that a step others depend on makes one job, and previews every step with placeholders; a mix of demo and real steps is refused (`assertOneMode`). Rows are created in topological order with `dependsOn`, labelled "Step n of N", and it returns `{batchId, items, byKey}`; if creation fails partway, what it started is canceled. Since round 4 part 2, `opts.existing` maps keys to generations made before (a retry's finished or running steps): new steps may wait for them, they aren't made again, and a demo step can't continue steps that ran for real. Its TSDoc example is a whole dub. Layers, Shorts, Mixed Media, the palette lock, Photodump / Fashion / Character Sheet, the AI Influencer builder's two-step sheet, Marketing Studio / Click to Ad / Ad Multiplier, dub, Katana, Remove object, Genjutsu, the Audio hub's Loop / extend and Join, and the Assist studio tools build their jobs this way; Cinema, Canvas, Faceless / Explainer, Content Factory's reading steps, Ads Studio and moodboards call `createGenerations` (with `dependsOn` for chained steps) directly (since round 4 part 3 Canvas uses `createPipeline` for a node made in steps or rows); Cinema, Canvas and Faceless preview every step first.
+
+ At launch the runner fills the slots (`slotsFor` pads short chains, `chainValue` reads text files when the text isn't inline) and checks the mode again (`chainMode`: a real step after demo steps runs as a demo, or fails with what to connect when demo mode is off). Round 4 part 2 changes the runner for every chain, for per-frame work:
- At launch the runner fills the slots (`slotsFor` pads short chains, `chainValue` reads text files when the text isn't inline) and checks the mode again (`chainMode`: a real step after demo steps runs as a demo, or fails with what to connect when demo mode is off). Built on that:
+ - **Fan-out and fan-in by output number.** `ChainSlot.index` takes the dependency's output number i of the slot's kind (by `meta.index` when the outputs carry it; past the end, the last one). One step per index fans a list out (a step per extracted frame); one step with a slot per index gathers it back in order. With `of`, the number of outputs planned, a list more than `CHAIN_LIST_SLACK` (2) short fails the step before it runs (`listShortfall`), so a frame or two lost at the clip's end is held, and half a clip of frozen, paid frames is not.
+ - **Waiting steps are picked by readiness.** `advanceDependents` reads `READY_DEPENDENTS` (`generations.ts`): waiting rows none of whose inputs is still queued or running, or one of whose inputs failed, was canceled or is gone. Before, it read the 50 oldest waiting rows, so a render with hundreds of waiting steps held up every chain started after it. A step whose input failed is now failed at once, even behind a backlog.
+ - **`dropWhenUnused`.** A waiting step marked so (today only per-frame Mixed Media's frame edits and clips) is canceled unpaid ("Stopped before it ran: the steps it was for failed", `DROPPED_UNUSED`) once every step that would use it has failed or been canceled. `dropUnused` runs when a chained step fails and on cancel, and walks up the chain.
+ - **Retries.** A launched step is stored with `chainFilled: true`; `unfilledRequest()` takes the chained inputs out again, so a retry can rebuild the step from new or kept dependencies (Mixed Media's `retryMixed`, with `createPipeline`'s `existing`).
+ - **Optional inputs** (round 4 part 4, Genjutsu's anchor first frame). A `ChainSlot` marked `optional {prompt?, notice}` is an input the step can do without: when the step feeding it fails or is canceled, `advanceDependents` launches the step without that slot (`withoutSkipped`) instead of failing it, with the slot's fallback prompt, and records `chainSkipped` (the slots left out and the planned prompt). The `notice` is said on the result and carried down to every later step (`GenerationRequest.notice`). `unfilledRequest()` puts the planned prompt back, so a retry tries the full plan again. Chains without optional slots run as before; the runner now reads each dependency's stored request to gather notices.
+ - **Model access** (round 4 part 4). `createGenerations` checks the model with `offeredFor` before any step is queued, and `assertOneMode` (`chains.ts`) checks every step's model and routes against Settings → Models & licences, so a chain with a step switched off is refused, naming the switch, before a row exists. The chains built after the first row (`createShotFilm`, `createExtendChain`, `createRelitClip`, `joinClips`) cancel what they queued when a later step throws.
+ - **Waiting for ComfyUI** (round 4 part 5). Before it launches a step whose model runs on ComfyUI, `advanceDependents` reads the cached reachability (an Original counts with the routes of the engine it will run on, `pickEngine` with ComfyUI taken as answering, so a step on the cloud half doesn't wait). When ComfyUI doesn't answer and an earlier step ran on it for real, one missed check (a server busy finishing those steps, or restarting) mustn't turn this step into a demo, which `chainMode` would fail: the step looks again at once (one forced check per sweep), then stays queued with "Waits for ComfyUI to answer" for up to 60 s from the first miss (`COMFY_WAIT`; the first miss is kept in memory by step id) before `chainMode` has its say. The Canvas concatenator's join after its fit steps is such a step.
- - **Join clips** (`joinClips`): fal's FFmpeg `merge-videos` on the cloud, ComfyUI's `video-concat-{2,3,4}` on the open engine (folded four at a time). `oss-join-sound1/2` are joins that keep one clip's own sound at 25 fps (marketing films).
+ Built on that:
+
+ - **Join clips** (`joinClips`): fal's FFmpeg `merge-videos` on the cloud, ComfyUI's `video-concat-{2,3,4}` on the open engine (folded four at a time). `oss-join-sound1/2` are joins that keep one clip's own sound at 25 fps (marketing films). `oss-join-encoded` (`video-concat-encoded`, `expand: "videos"`) joins up to 100 clips in one prompt by packet copy when they share size and frame rate; Faceless Frame by frame films use it, 24 clips per join.
- **Open multi-shot** (`createShotFilm`), **storyboard film** (`createStoryboardFilm`), **last-frame extend** (`createExtendChain`: extract frame → the model's image-to-video → join; `oss-extract-frame` on the open engine).
+ - **Keyframe film** (`createKeyframeFilm`): Frames mode on an open model whose `keyframes` route is `chained`. `createGenerations` hands a keyframes request on Wan 2.2 14B (or Lightning) to it: one `wan22-flf2v-14b` clip per pair of neighbouring frames, each as long as its gap in the workflow's frame steps (`planKeyframeClips`), then an image-to-video clip after the last frame when it isn't at the end, then a join. The whole request is previewed first, and clips already made are canceled when one fails. A chained route can't be a step that waits for another step's output: `createGenerations`, `previewChained` and Canvas's `describeNode` refuse it with one message (`chainedWaitMessage`).
+ - **Pieces and windows** (`src/lib/catalog/remove-object.ts`, shared by Remove object and Genjutsu): a long clip is cut into pieces each cloud model takes (`planCloudPieces`), or into frame-exact windows for the open graphs (`planWindows`, `planFrameCuts`; `VACE_WINDOW` is 4n+1 frames, up to 81). Each piece is trimmed and made, the pieces are joined, and the clip's own sound is put back (`joinWithSound`), with the helpers in `REMOVE_TOOLS` (fal trim / join / mux, or `oss-trim` / `oss-join-clips` / `oss-mux`). Open windows are joined with hard cuts; the seams have not been checked on real models.
+ - **Text to 3D on the open engine** (`createStillTo3d`, round 4 part 3): `oss-text-trellis2`'s `text-to-3d` route is `chained`. `createGenerations` reads the operation as the planner does (`inferOperation`, so Assist, MCP and API calls that leave `op` out get it too) and makes one batch of two steps: a Z-Image Turbo still (`oss-z-image-turbo`, 1:1 at 1K, the words plus "a single object … on a plain light grey background", feature `image-to-3d-step`, a helper the Library hides), then `oss-trellis2` on that still (`BUILDERS_3D`). A photo sent with the words is dropped. Like a keyframe film, it can't wait for another step's output: `chainedWaitMessage(name, op)` now has 3D wording, and Canvas refuses any chained route fed by another node before Run.
+ - **Relit clip** (`createRelitClip`, round 4 part 3): a Fuobe DoP relight effect run on its own model (`relightStep` in `generations.ts`) is one batch of two steps. "Relit start frame" runs the preset's `prestep` on the clip's engine (`oss-qwen-relight` on ComfyUI; `qwen-image-edit-2509-cloud` with the Relight LoRA on fal); "Relit clip" takes it as its start frame. `createGenerations` checks text to 3D first, then the relight.
+ - **Canvas nodes made in steps, or once per table row** (round 4 part 3, `runCanvas` in `src/server/canvas.ts`): a node whose `NodeRequest` has `steps` (the Video concatenator) runs as one `createPipeline` whose last step holds its result (`NodeRun.out`; the steps before it have feature `canvas-step`). A node fed by a Table has `rows`: one step per filled row (`StepSource {node, row}`: a row of the next node waits for the same row), each row a result (`NodeRun.rows`). Each row has a signature (`NodeRun.rowSigs`); a row whose inputs didn't change and whose result is live is kept (`keptRow`), so a failed, trashed or added row runs and is billed alone, and a node that takes rows is signed by all its row ids (`depIdentity`), so a film joined from rows goes stale when one is redone. The concatenator's steps, per clip: on the cloud `trim-video` (when cut) → `scale-video` (cropped to the film's size) → for a muted or soundless clip `merge-audio-video` with a silent WAV the server writes when the run starts (`silenceRef`, `silenceWriter`; for a muted clip of unknown length `extract-soundtrack` → `ffmpeg-loudnorm` at −70 dB → the mux), then `join-clips` at 30 fps, folded in joins of up to 24; on the open engine `oss-fit-clip` (`video-fit-clip`: cut, framed, 30 fps, its sound or silence, in one streamed pass), then `oss-join-encoded`.
+
+ ## LoRAs (`src/lib/catalog/loras.ts`, `src/server/loras.ts`)
+
+ Round 4 part 2. A run's LoRAs come from a preset's LoRAs (since round 4 part 3 on either engine: Fuobe DoP's map v2 in `oss-loras.generated.ts`, through `dop.ts`), a Fuobe Soul look (round 4 part 3: `LORA_LIBRARY` keys), a Mix, an @character's trained LoRA (since round 4 part 4 on every model of its family: see Training), the request's `loras` (API callers and the evaluation harness: at most 8), or, since round 4 part 4, a graph that loads its own (the H3 graphs' `graphLoras`). The library (`lora-library.generated.ts`) gives each researched file its pins and licence; a LoRA the library doesn't know is the user's own. Nothing is committed to the repo: files are fetched when a run needs them.
+
+ Since round 4 part 4 a LoRA's licence is information, not a gate (the owner's decision of 2026-10-27). A LoRA licensed for the user's GPU only (civitai without "Rent", `gpuOnlyLicence`) goes to fal or Replicate like any other, and the run's notes say what its licence says, unless Settings → Models & licences turns on "Keep them on your GPU" (under "LoRAs licensed for your GPU only"; `keepGpuOnlyLoras`): the server then marks the run's LoRAs `keepOnGpu`, and `localOnly` keeps those off the cloud. LoRAs switched off there, by file or by licence class, leave the run with their trigger words (`offeredLoras` in `src/server/model-access.ts`); the user's own LoRAs (no recorded licence, no library entry) are exempt from the class switches.
+
+ - **Open engine.** Before a ComfyUI run, `ensureLorasOnComfy` compares the run's LoRAs with ComfyUI's own list (`comfyLoraFiles`) and the LoRA folder. A missing file is downloaded into Settings → LoRAs folder (`comfyLorasDir`, `COMFYUI_LORAS_DIR`) by `downloadLora`: a Hugging Face file at its pinned commit, a civitai file by its pinned version with the user's civitai key (`?token=`, redacted from error messages). The bytes are hashed while they stream to a `.part` file and kept only when they match the SHA256 pinned in the library (else the one Hugging Face or civitai states). One download per file runs at a time (`downloadOnce`), and the job's card shows its progress ("Downloading … · 40%"). With no folder set, the run stops with what to do; a gated Hugging Face file has to be placed by hand. A trained Soul ID LoRA (round 4 part 4) is copied into the folder from Fuobe's own copy (`ownCopy`). `injectLoras` then adds the loader nodes.
+ - **Cloud engine.** `fitLoras` keeps what the route can carry: never a gated Hugging Face file or a file that exists only on ComfyUI, nor a GPU-only LoRA while the admin keeps those on the GPU (`localOnly`); over the API's maximum, the first ones win. Before submit, `prepareCloudLoras` gives each LoRA a URL the provider can fetch: a public file as it is; a civitai file is mirrored once to fal or Replicate storage through the adapter's `prepareFile`. civitai's permissions are read before each copy and recorded with it; since round 4 part 4 they decide only while GPU-only LoRAs are kept on the GPU (then no "Rent", or no answer, means no copy); otherwise the copy is made and the mirror's licence snapshot says how (`hostingNote`). A trained Soul ID LoRA (`LoraRef.own`) goes through `sendOwnLora`: the copy the trainer left on fal while it lives, else Fuobe's own copy (or the one in ComfyUI's folder) uploaded once, else the trainer's URL. A mirror is made again after 7 days on fal and 1 day on Replicate (guesses: neither documents how long uploads live). The civitai key is never sent to fal or Replicate. Files downloaded only to mirror them live in `<data dir>/loras` (`LORA_CACHE_DIR`).
+ - **Without a civitai key** (round 4 part 3). Before a Fuobe Soul run, `withoutUnreachableCivitai` (`src/server/loras.ts`) leaves out the civitai LoRAs the run can't get (not in ComfyUI's LoRA folder, or no live mirror for the cloud), takes their triggers off the front of the prompt (`promptWithLoras`) and adds a note; the look's words still carry it. On the open engine it only does this when the LoRA folder is set: without the folder, a missing file still stops the run. Since round 4 part 4 Fuobe Cinema's planner does the same for a cloud camera move whose LoRA is on civitai (`cinemaMoveRoute` with the project context's `civitai`: the move runs on its words, with a note). Any other run (a motion, whose LoRA is the point) still stops before the job.
+ - **Records.** Every copy, a download into ComfyUI's folder or a mirror, is a `lora_mirrors` row (file, target, source URL, version, hosted URL, SHA256, size and the licence / permission snapshot it was made under). Since round 4 part 4 a trained LoRA's copies are rows too (source `fuobe:<file>`, or the trainer's fal URL: `recordTrainedMirror`).
+ - **Settings → LoRAs** (`src/components/lora-settings.tsx`) reads `GET /api/loras`: the library with each file's licence line, whether it is in the folder, where it was mirrored, a `folderProblem` for a folder setting that can't be read, and whether a civitai key is set (never the key). `POST /api/loras {file}` downloads one library LoRA now (`downloadToComfy`). The civitai key's Save & test asks civitai's `/me` (`testCivitaiKey`).
+ - **Research pins.** `scripts/fetch-lora-pins.py` pins every LoRA of the research to exact bytes (SHA256, size, the Hugging Face commit), and `scripts/fetch-hosted-schemas.py` reads the hosted endpoints' input schemas (since round 4 part 4 also `--trainers` and `--base-only`); both need the network and aren't part of `gen:catalog`. `gen-lora-library.py` fails on a missing pin; since round 4 part 4 it prints a licence-rule break (a non-commercial LoRA in a default row) as a note instead of failing.
+
+ Checked: one pinned 85 MB Hugging Face LoRA was downloaded live through `/api/loras` and matched its hash, and the payloads are tested against the providers' schemas. No LoRA has run on fal, Replicate or a GPU, civitai downloads and mirrors have never run live, and no trained Soul ID LoRA has been sent anywhere. Apart from a Fuobe Soul look's and a Fuobe Cinema cloud move's (above), a civitai LoRA sent to the cloud without a civitai key fails the run instead of being left out with a note. `ensureLorasOnComfy` copies a trained LoRA synchronously and `sendOwnLora` reads the whole file into memory.
+
+ ## Fuobe Originals (`src/lib/catalog/engines.ts`, `soul.ts`, `dop.ts`, `cinema.ts`, `genjutsu.ts`, `character-swap.ts`)
+
+ Round 4 part 3. A Fuobe Original is Fuobe's own open-weight rebuild of one of Higgsfield's in-house models. It is one model on both engines: its ComfyUI routes run on the user's GPU, and its cloud routes run the same open weights hosted on fal or Replicate. No Original has a Higgsfield route; since round 4 part 5 Fuobe has no Higgsfield provider at all, and a stored request for a model an Original replaced runs on that Original (see Retired models). Round 4 part 3 shipped five: `fuobe-soul`, `fuobe-soul-hd`, `fuobe-soul-cinema` (O2) and `fuobe-dop`, `fuobe-dop-ltx` (O4). Round 4 part 4 adds seven: `fuobe-cinema` (O6), and the Genjutsu Originals `fuobe-genjutsu-motion`, `fuobe-genjutsu-motion-lite`, `fuobe-genjutsu-swap`, `fuobe-genjutsu-swap-lite`, `fuobe-genjutsu-restyle` and `fuobe-character-swap` (O5). Soul ID (O3) trains LoRAs for the Originals' bases (see Training).
+
+ - **One model, two engines.** `ModelDef.engines` lists both. `original()` in `models.ts` joins the Original's ComfyUI routes to its cloud half from `ORIGINAL_CLOUD` (written by `gen-cloud-models.py` from the research) and gives it its own options (`SOUL_OPTIONS`, `DOP_OPTIONS`). `engineDefaults` and `engineOptions` change them on one engine (Fuobe DoP: 480p on the GPU, 720p in the cloud; Fuobe DoP · LTX: no sound toggle on the GPU, whose graphs make silent clips). `engines.ts` is pure and used on both sides: `onEngine(m, engine)` is the model as it runs there (that engine's routes, defaults and options; the same object every time), and `pickEngine` chooses the engine asked for, else the engine mode's, else the first one connected (the GPU first), else the model's own; it throws when Settings → Engine mode rules out the engine asked for. On the server `engineFor()` wraps it, `prepare()` and `createGenerations()` plan an Original as `onEngine(model, engineFor(…))`, and the stored `request_json` keeps the engine, so a retry or a chained step stays on it. The engine comes from the composer's switch, `POST /api/generations` (`engine`; another value is a 400; the preview answers with it), `POST /api/palettes/lock`, `fuobe generate --engine`, Assist's `generate` (`engine`, else the user's engine) or a Canvas node (`CanvasNodeData.engine`). Lists show an Original once, on both engines: `findModels` and `GET /api/models` (a list for one engine, asked for or the install's only one, gets that engine's view, with its routes and price), `modelsFor`, the Models page (`ModelRow.engines`: "Open source + cloud", "Free · $… / megapixel"), ⌘K, the canvas (`nodeEngine`, `nodeModel`; `convertEngine` flips only the engine) and `fuobe models` (`open+cloud`).
+ - **Fuobe Soul: the looks.** `scripts/gen-soul-originals.py` reads `fuobe-originals-recipes-5.json` (each look's template, LoRAs and strengths, grade, tail, base and overlay; Soul's tails, sizes and sampler; Soul Cinema's recipe) and `higgsfield-image-studios.json` (each look's family and picker categories). It writes `soul-originals.generated.ts`, 139 looks (106 Soul, 33 Soul 2.0) with Fuobe ids (`v1-general`, `v2-y2k-studio`) and Higgsfield's id kept only as `legacyStyleId`, read for old requests and moodboard picks and never sent, plus the browser's slim `soul-looks.generated.ts` (cards, categories, the old-id map). It exits 1 when the research breaks a rule: a LoRA that isn't in the LoRA library (since round 4 part 4 a non-commercial or GPU-only LoRA is printed as a licence note instead); more than 3 LoRAs or one for another base; a bad template or trigger; an unknown grade or overlay; a size off the 16-pixel grid or above 2048; or a count other than 139.
+ - **Fuobe Soul: a run.** `planGeneration` reads a Soul model's `presetId` as a look id and calls `soulRecipe`: the prompt is "{triggers}, {prompt}. {look}. {tail}"; the LoRAs go in slot order (the user's own, then the look's, then the core LoRA, which gives way first on a 3-slot API), scaled by the preset strength. A look made for the other base keeps only its words (Graffiti is the one look made for Soul HD's Qwen-Image 2512), and Soul Cinema has one fixed recipe (filmstill 0.7, moviewide 0.5, the `cine` tail, a teal-orange grade). `Plan.soul` carries the user's words, the triggers and the post steps; `Plan.notes` says what was left out. Sizes come from Soul's table: 7 shapes at 720p (about 1 MP) and 1080p (about 2 MP), sent to ComfyUI as `params.extra` width and height and to the cloud through `FieldMap.size.table` (fal's `image_size` object, through `key`; Replicate's width and height, capped at 1440). Soul Cinema's 21:9 is made at 16:9 and cropped afterwards. A megapixel is 1024×1024 (`FAL_MEGAPIXEL`). With Enhance prompt on, only the user's words are expanded (`enhanceSoulWords` in `src/server/enhance.ts`, an LLM only, no offline rewrite) and the look stays as it is. Routes: on the GPU, `fuobe-soul` makes new pictures on `z-image-turbo-t2i` and restyles one on the new `z-image-turbo-i2i` (denoise 0.6, `megapixels` 1 or 2); `fuobe-soul-hd` runs `qwen-image-2512-t2i`; `fuobe-soul-cinema` runs `z-image-turbo-t2i`. In the cloud, fal `fal-ai/z-image/turbo` (its `/lora` endpoint when the run carries LoRAs) or Replicate's pinned `prunaai/z-image-turbo-lora` make new pictures (priced at fal's $0.005 per megapixel, $0.0085 with LoRAs); fal `fal-ai/z-image/turbo/image-to-image` (`/lora`) restyles, keeping the picture's shape and fal's default strength; Soul HD is fal `fal-ai/qwen-image-2512` (`/lora`), $0.02 per megapixel ($0.035 with LoRAs) on whole megapixels (`Pricing.roundUp`). A ComfyUI route has no `numOutputs`, so 4 pictures there are 4 jobs (`prepare()` now splits any route without that field).
+ - **Fuobe Soul: after the run.** When the job succeeds, `pollOne` writes `soulPostSteps` into each image's meta (`look`, `grade`, `overlay`, `crop`). The browser does the rest: `useSoulFinish` (`src/components/studio/soul-finish.ts`, called by every studio feed) crops, grades with the Color grading tool's WebGL shader (`src/lib/grade.ts`, which gains Invert and Solarize) and draws the overlay (`overlayLayout` in `src/lib/soul-post.ts`: DigitalCam's date stamp, CCTV's caption, Vintage PhotoBooth's print). It uploads the PNG to `POST /api/generations/[id]/finish` (multipart `file` and `index`; a PNG by its magic bytes, 64 MB at most). `finishOutput` puts it in place of the raw picture, keeps the raw one as `meta.original` and sets `meta.finished`; the first copy wins (409 after that; 400 for an output with nothing to apply). A failed finish is tried again, up to 3 times. A run made through the API, the CLI or Canvas keeps the raw picture, with the meta, until a studio feed shows it. The viewer's Details show a Look row and a Finish row.
+ - **Fuobe Soul: the composer, HEX and moodboards.** The Look chip is `src/components/studio/look-chip.tsx` (models with `options.looks`: Fuobe Soul and Soul HD; a Strength slider sends `presetStrength`). In `palettes.ts`, a picked palette goes into the prompt on both engines, and on the open engine a Soul model chains the palette lock after it unless it is turned off (`locksByDefault`); the lock route takes `presetStrength` and `engine`. Curated moodboards are Fuobe Soul looks (`lookCard`): the look itself on a model that takes looks, its words on any other. Moodboards no longer fetch Higgsfield's preset list.
+ - **Fuobe DoP: the map.** `scripts/gen-oss-loras.py` writes the preset → LoRA map v2 (`oss-loras.generated.ts`) from `comfyui-oss.json` (round-1 Wan LoRAs, matched by slug) and the research's `motionsEffects` (by preset id, so they win): each LoRA with its base and licence flags, and `DOP_RECIPES` per preset (its status, Fun Camera pose, LTX-2.3 `cameraLora`, LTX-2.5 `cameraMotion`, alias). Until round 4 part 4 a round-1 LoRA without a known commercial licence was left out, and the generator exited 1 when a row would make a non-commercial LoRA a default or send a LoRA that may not be hosted to the cloud; since then such a LoRA is kept with `commercial: false` (a commercial one for the same preset wins), and both cases are printed as licence notes.
+ - **Fuobe DoP: the routes.** `dopPreset()` gives every motion and effect its routes. On the GPU: Fuobe DoP (Wan 2.2 14B with each LoRA on its expert) when it has Wan LoRAs, else Fuobe DoP · LTX (LTX-2.3 LoRAs), else `oss-ltx25` (LTX-2.5 LoRAs; fal has no LTX-2.5 LoRA endpoint), else a Fun Camera pose on Fuobe DoP (`params.extra.cameraMotion`, which the ComfyUI provider moves to `wan22-fun-camera-14b`), else Fuobe DoP on the preset's words. In the cloud: LTX-2.5 Fast's own move (Focus Change's `focus_shift` on `ltx-2-5-fast`), LTX-2.3's built-in `camera_lora` on Fuobe DoP · LTX, the Wan or LTX LoRAs a host may run, Wan 2.2 on the words for a grade or relight effect, and otherwise the preset's old route marked `partner: true` (Kling 2.5 Turbo on the words, until the evaluation harness promotes Fuobe DoP). Until round 4 part 4 a LoRA whose licence doesn't allow hosting stayed on the GPU; now it rides along on a cloud route that is already Fuobe DoP (unless the admin keeps such LoRAs on the GPU), but doesn't make Fuobe DoP a preset's cloud default by itself (Wiggle keeps its partner route). `fuobe-dop` runs `wan22-i2v-14b`, `wan22-flf2v-14b` and the chained keyframe film on the GPU; in the cloud, fal `fal-ai/wan/v2.2-a14b/image-to-video` (`/lora`; `interpolator_model` none, 16 fps, 20 steps; start frame or start and end frame; $0.08 a second at 720p, $0.10 with LoRAs), with Replicate `wan-video/wan-2.2-i2v-fast` as a start-frame-only fallback that takes one LoRA per expert (the price before the run is fal's even when it goes to Replicate). `fuobe-dop-ltx` runs the new `ltx23-i2v-lora` and `ltx23-flf2v-lora` on the GPU, and fal `fal-ai/ltx-2.3-22b/image-to-video` in the cloud (`/lora` for the LoRA presets; `camera_lora` on the plain endpoint; prompt expansion off; sound off unless asked; $0.036 a second, $0.04 with LoRAs). Focus Change's `ltx-2-5-fast` is $0.09 a second; the relight step's `qwen-image-edit-2509-cloud` is $0.035 per megapixel, priced as a 1-megapixel still.
+ - **Fuobe DoP: effects as steps, Mix.** The 15 colour-grade effects carry `Preset.grade` (`DOP_GRADES`; 14 of the grades are new in `grade.ts`). `pollOne` writes it as the clip's `meta.grade`, and the clip's first next step opens `/color-grade?video=…&preset=<grade>` (`gradeOf` in `src/lib/output-actions.ts`): a hand-off, not an automatic re-encode. The 6 relight effects carry a `prestep` that relights the start frame first (`createRelitClip`, see Pipelines), priced into the clip by `withPrestepPrice` and the composer's `prestepCost`. Mix stacks the second preset's LoRAs on either engine (`mixLoras`), scaled by the mix strength and deduplicated by file; a preset whose LoRA is for another model family joins as words only, with a note. The preset strength also sets `camera_lora_scale`. Cinema Studio's open camera route now takes LoRAs only from a preset whose open route is Fuobe DoP (Wan).
+ - **Fuobe DoP: the composer.** Picking a motion or effect, or arriving from `/motions` or `/effects` (`?preset=`), moves the studio to the preset's Original on that engine (`presetOriginal`, never a partner route) with its settings (`presetParams`). An engine switch takes a move to its model there (`engineSwitchModel`) and moves settings left at their default (`followEngineParams`). These helpers are pure, in `src/lib/composer.ts`, with `followEngineDefault`, which fixed a `?model=` link on the open engine landing on the studio's default model in every studio.
+ - **Fuobe Cinema: the model** (round 4 part 4, O6). `fuobe-cinema` in `models.ts`. On the GPU: Wan 2.2 14B Lightning (`wan22-t2v-14b-lightx2v`, `wan22-i2v-14b-lightx2v`) and `wan22-flf2v-14b`, graphs the library already had, no custom nodes; 3 or 5 s at 480p or 720p, no sound, several shots made one clip each and joined (`engineOptions.open`). In the cloud: LTX-2.3 22B on fal, `fal-ai/ltx-2.3-22b/text-to-video`, `image-to-video` (start and end frame through `end_image_url`), `extend-video` and `video-to-video`, each switching to its `/lora` endpoint only when a LoRA rides along; prompt expansion off, sound follows the toggle, 24 fps, `num_frames` 9–481 in steps of 8 (up to 20 s a call, `CINEMA_MAX_SECONDS`), `video_size` from a table per tier and shape, `camera_lora` and `extend_direction` from `params.extra`. It is priced per megapixel of video (`Pricing.videoMegapixel`: $0.001605, $0.001805 on `/lora`; about $0.18 for 5 s at 720p 16:9).
+ - **Fuobe Cinema: the Director compiler** (`cinema.ts`). The Director's Panel now always compiles into words (`compileDirector` with `target: "prompt"`; the Cinema Studio 4.0 `native` target stays in the file, unused; since round 4 part 5 `directorFieldWords` turns a stored Cinema Studio 4.0 request's Director fields into the same words when `migrateRequest` moves it to Fuobe Cinema). `planVideo` turns the first camera move into a route with `cinemaMoveRoute(slug, engine, hasStartFrame, {civitai})`. In the cloud: LTX-2.3's built-in `camera_lora` where one of its seven fits (`CINEMA_CAMERA_LORA`: 14 of the 33 moves, a zoom taken as a dolly; no start frame needed); else, with a start frame, the move's Wan 2.2 LoRA moves the take to Fuobe DoP (16 fps, no sound, with a note), or Rack Focus runs on `ltx-2-5-fast`'s `focus_shift`; else the move's words. On the GPU: the move's Wan 2.2 LoRA or a Fun Camera pose (both need a start frame), else words. The move picker shows each route as a badge on both engines. A cloud take over 20 s adds an "Extended to N s" extend step. Reference clips: Fuobe Cinema takes none yet, so a cloud take with clips runs on the first partner model that takes them (Seedance 2.5) with a note (`clipModel`); picking Fuobe Cinema in the menu leaves them out. Extend and prequel (`videoModelFor`): on the GPU, extend on Wan 2.2 Fun VACE and the prequel on Fuobe Cinema's start and end frame graph; in the cloud, the picked model when it does that on fal or Replicate, else Fuobe Cinema, whose prequel is one `extend-video` call with `extend_direction: backward`. Edit (`planEdit`): a take made on a partner model in the menu (Seedance 2.5, Kling 3.0, Veo 3.1) goes to Kling O3; any other to LTX-2.3 video-to-video with the take's scene and the change (`editPrompt`), `video_strength` 0.5 (`CINEMA_EDIT_STRENGTH`, a guess until measured) and `audio_strength` 1, the first 20 s of a longer take. The take's facts (model, prompt, length, size) come from the browser in the generate body's `source`; the server doesn't re-derive them. `stepCost` prices each step on the engine it runs on, at the LoRA rate when LoRAs ride along.
+ - **Fuobe Cinema: stills, Soul Cast, Soul Location.** Stills default to Fuobe Soul Cinema on both engines (`CINEMA_STILL_MODEL`); Cinema's 1K / 2K / 4K tiers map to Soul's 720p / 1080p, and the Cinema feed and its builders run Soul's browser finish (`useSoulFinish(items, ["cinema"])`), so a 21:9 still is cropped from 16:9 and graded. Soul Cast (`CAST_MODELS`): in the cloud Fuobe Soul with the Realistic look (`v1-realistic`) and the 17-field compiler; on the GPU the Soul Cast sheet graph (`oss-zimage-soul-cast`) with that look's LoRAs and words, Fuobe Soul as the fallback. Soul Location (`LOCATION_MODELS`): Fuobe Soul with the Movie look (`v1-movie`) on both engines. Another view of a location (`planLocationView`) uses the Multiple-Angles LoRA: fal's hosted `qwen-multiple-angles` with the view's angles as fields in the cloud, Qwen-Image-Edit 2511 with the LoRA's `<sks>` words on the GPU. The project context (`cinemaContext`, returned by `GET /api/cinema/projects/[id]`) is `{cloudAllowed, civitai}`, and its `has` also asks `isOffered`.
+ - **Fuobe Genjutsu: the models** (round 4 part 4, O5, `genjutsu.ts`). One Original per mode on both engines, Lite being the cheaper tier of the same Original (`Maker.pair`, picked as Quality: Standard / High): Motion (`fuobe-genjutsu-motion[-lite]`: Wan Animate 2 on `wan-animate2`; fal `fal-ai/wan/v2.2-14b/animate/move`), Object swap (`fuobe-genjutsu-swap[-lite]`: SAM 3.1 and Wan 2.1 VACE 14B on `video-swap-wan-vace`; fal `fal-ai/wan-vace-14b/inpainting` plus a SAM 3.1 mask track), Restyle (`fuobe-genjutsu-restyle`: `video-restyle-wan22-fun-vace`; fal `fal-ai/wan-22-vace-fun-a14b/depth` after a first-frame restyle) and Character swap (`fuobe-character-swap`, below); Insert has no Original yet. `MAKERS` lists every model per engine with its source (`original`, `open` or `partner`: `SOURCE_LABELS`) and licence line (`makerLicence`), and `chooseMaker` picks the mode's Original first, then other open weights, then partners, passing over models switched off. No maker is Higgsfield's: old setup codes and model ids open the Original that replaced them (`LEGACY_MAKERS`, since round 4 part 5 built from `REPLACED_BY` for the retired Genjutsu ids), and Restyle's looks are Fuobe Soul's 139 (look kind `soul`). Katana's motion step and the Ad Multiplier's open recreation run `fuobe-genjutsu-motion` (`RETIRED_MOTION_MODELS` in `src/lib/av/katana.ts` maps the old open id; since round 4 part 5 `currentMotionModel` sends any other retired id through `currentModelId`).
+ - **Character swap** (`character-swap.ts`, `planCharacterSwap` in `genjutsu.ts`; Openjutsu and Akatz Labs' H3 Character Swap, `docs/research/openjutsu-6.md`). The person in a 5–15 s part of one shot (up to 30 s) becomes the character in one image, keeping the performance and the clip's sound.
+ - **On the GPU:** one `video-swap` step on `video-character-swap-h3` (MiniMax H3 with the FL2V Turbo LoRA and Akatz Labs' swap LoRA, on the `h3_character_swap` pack). SAM 3.1 finds the person on the part's first frame (Largest, Leftmost, Rightmost, a detection number, words or clicks), and H3 regenerates only them in 124-frame windows with 18 frames of history, continuing window by window past 15 s. `oss-h3-character-swap-relay` runs the same swap on H3 Relay 2.0's graph (no anchor, no mask switch).
+ - **In the cloud:** fal's `minimax/h3/reference-to-video/lora` with the swap LoRA loaded from its pinned Hugging Face URL (the route needs one: `CLOUD_NO_LORA`). It has no mask, so who to swap is said in words. A part over 15 s is cut into pieces (`planCloudPieces`), each trimmed, swapped on whole seconds and trimmed back, then joined under the clip's sound (`joinWithSound`); a silent clip gets a last mux to silence, since fal's H3 makes a soundtrack of its own.
+ - **The anchor step** ("Make the first frame first", on by default). The part's first frame is taken (`oss-extract-frame` on the GPU, `extract-frame` per piece in the cloud) and an image edit puts the character in it (`ANCHOR_MODELS`: GPT Image 2.5 Sunburst at low quality or Nano Banana Pro in the cloud, Qwen-Image-Edit 2511 on the GPU), in the part's shape (`anchorAspect`). It reaches the swap through an optional chain slot (see Pipelines): when the anchor fails, the swap runs without it, with the fallback prompt and the notice "Couldn't make the first frame — swapped without it". Sunburst is billed by tokens, so the estimate leaves it out and says so.
- - **Helpers.** `POST /api/genjutsu/describe` writes "What your character looks like" from the image (`describeCharacter`: Claude or Ollama in the cloud; on the GPU Ollama only, through `llmText`'s new `ollamaOnly`). `POST /api/genjutsu/transcribe` starts one transcription for "Use the clip's words" (`TRANSCRIBERS`: `scribe-v2` or `oss-qwen3-asr`), with no estimate first. The browser looks for hard cuts by frame difference (`components/genjutsu/use-cuts.ts`), and the estimate repeats the warning.
++ - **Helpers.** `POST /api/genjutsu/describe` writes "What your character looks like" from the image (`describeCharacter`: Claude or a local model in the cloud; on the GPU a local model only, through `llmText`'s new `ollamaOnly`, which means any local server). `POST /api/genjutsu/transcribe` starts one transcription for "Use the clip's words" (`TRANSCRIBERS`: `scribe-v2` or `oss-qwen3-asr`), with no estimate first. The browser looks for hard cuts by frame difference (`components/genjutsu/use-cuts.ts`), and the estimate repeats the warning.
+ - **Weights and licences.** The H3 graphs' files (H3 Ref2VA INT8, the Qwen3-VL 32B NVFP4 text encoder, the video and audio VAEs, SAM 3.1, the FL2V Turbo LoRA, the swap LoRA) are pinned to Hugging Face revisions, and the provider downloads the LoRAs before a run (`graphLoras`). The licences are data (`CHARACTER_LICENCES`): MiniMax H3's Community License is classed "Restricted regions" and shown on the picker, in the estimate and in Settings → Models & licences, never as a gate.
+ - **H3 Person Removal** (Remove object's open eraser `oss-h3-person-remove`, `planPersonRemoval` in `remove-object.ts`): fit the part (24 fps, H3's canvas) → its first frame → a clean first frame (Qwen-Image-Edit) → H3 Relay's Person Removal with the Person Remover LoRA → the clip's sound put back.
+ - **Character Swap Studio** (round 4 part 5) takes the same recipe to whole clips, shot by shot, with a one-pass segment graph and a mask graph of its own on the GPU (see Studios).
+ - **Checked.** Round 4 part 3: unit tests cover the cloud payloads (Fuobe DoP's through the fal adapter with fetch stubbed, Fuobe Soul's built from their field maps), the ComfyUI graph payloads, prices and routing; the browser checks ran in demo mode; every workflow part 3 added was accepted by a live CPU ComfyUI. Nothing has run on a GPU or with real fal or Replicate keys, so no look's picture or move's clip has been seen, and the evaluation harness hasn't measured any Original. Round 4 part 4: unit tests cover Fuobe Cinema's fal payloads (through the fal adapter with fetch stubbed), its prices, every move on both engines and the 30 s chain, and the Character swap's prompts, canvas, windows, the binding of the real H3 graphs (anchor removal, clicks, LoRA none) and the optional anchor slot on the database runner; browser checks of Cinema and of Genjutsu with Character swap pass in demo mode (the Cinema one failed once at 390 px while the folded Director panel re-rendered mid-click, then passed 3 times out of 3). Unverified: LTX-2.3's camera LoRAs and real bills, whether fal's `extend-video` returns the whole clip and honours a backward extend (the 30 s chain and the prequel rely on it), the edit strength, and every H3 graph, which no ComfyUI here has loaded (see the workflow library). Round 4 part 5: the Cinema and Genjutsu browser checks (`tests/e2e/cinema-original.mjs`, `genjutsu-original.mjs`) wait for closing dialogs, sheets, menus and select lists to finish before the next click, which removes the likely cause of that failure (it was never reproduced); both pass in PR #13's run, in demo mode with ComfyUI unreachable.
+
+ ## Retired models: no Higgsfield (`src/lib/catalog/replaced.ts`)
+
+ Round 4 part 5 (O7). Fuobe no longer calls Higgsfield's API; Higgsfield stays only as what Fuobe is measured against (the research and the parity notes). Deleted: the adapter (`src/server/providers/higgsfield.ts`), the generated catalog and its generator (`higgsfield-models.generated.ts` with `HIGGSFIELD_ROUTES`, `scripts/gen-higgsfield-models.py`), the presets file and its generator (`higgsfield-presets.generated.ts`, `gen-higgsfield-presets.py`), the live style lists (`GET /api/providers/higgsfield/presets`, the composer's provider style chip), the `higgsfieldKey` setting and the `higgsfield` value of `cloudProvider`, the provider id (`ProviderId`, the connection test, `PROVIDER_NAME`, the model-access providers) and Ads Studio's route that drew whole ads. Twelve models were retired with it, and 24 partner models lost their Higgsfield routes and keep their fal or Replicate ones.
+
+ - **What replaced what** (`replaced.ts`, pure and browser-safe). `REPLACED_BY` maps each retired id to the model that does the job now: `soul-1` and `soul-2` → `fuobe-soul`, `soul-cinema` → `fuobe-soul-cinema`, `cinema-studio-4` → `fuobe-cinema` (a take with references → `seedance-2-5`: `withReferences: "ref2v"` and `ops`), the five Genjutsu and Genjutsu Lite ids → the matching `fuobe-genjutsu-*` Original, `marketing-studio-image` → `gpt-image-2-5`, and `ads-studio` and `ai-influencer` → `nano-banana-pro` (these three run on partner models in the cloud until O10 builds their Originals). Each entry keeps `was` (the name it ran under, "Soul 2.0 (Higgsfield)") and a `note`. A request moved to an Original (`original`) names no engine: it runs where the install runs Originals. `TRAINING_REPLACED_BY` points the two old Soul ID targets (`soul-id-v2`, `soul-id-cinema`) at `fal-z-image`, but nothing retrains by itself. `OPS_REPLACED_BY` covers the operations only the retired provider ran for current partner models: Seedance 2.5's video edit (`v2v`) → `kling-o3`, LTX 2.5's start and end frame clip (`flf2v`) → `fuobe-cinema`.
+ - **`migrateRequest(req, {directorWords})`** moves a stored request to the replacement's model and operation. A Soul `style_id` becomes the Fuobe look that replaced it (`presetId`, through `lookCard`). Cinema Studio 4.0's Director fields (`DIRECTOR_FIELDS`) become prompt words when `directorWords` is given: the server passes `cinema.ts`'s `directorFieldWords`; the browser has none, so there they are dropped and the note says so. The retired API's own settings (`style_id`, `custom_reference_id`, `preset_id`, `color_palette`, `template_id`…) are dropped. A current model's request comes back as it is, so moving a request twice changes nothing. `note` says what changed.
+ - **Where stored references resolve.** On the server through `currentRequest()` (`generations.ts`): `previewGeneration` and `createGenerations` (so `POST /api/generations` and its preview, `createPipeline`, the CLI and MCP calls), `advanceDependents` (a waiting chain step starts on the replacement, and its row's `model_id` and `engine` are updated), Photodump's `retryPhoto` (its chained step too) and Assist's `toRequest` (plans and MCP calls; the note isn't shown there). The generations API answers with the replacement's `modelId` and the note in `notes`. In the browser: studio Reuse (`draftFromGeneration`, then a toast), a `?model=` link (`currentModelId` in `studio-page.tsx`), Canvas boards when read (`withCurrentModels`), Genjutsu setup codes (`LEGACY_MAKERS`) and Katana jobs (`currentMotionModel`). The Library keeps past runs and their files and names them as they ran (`toGeneration`'s `modelName` falls back to `was`); its Engine row still shows the raw provider id.
+ - **In-flight work.** A job stored under a provider Fuobe no longer has gets the stand-in adapter (`provider()` in `src/server/providers/index.ts`): its next poll fails it with `RETIRED_PROVIDER_ERROR`, and `pollOne` gives the same message for a job whose model was retired or whose provider is unknown. A training on a retired target fails by target (see Training).
+ - **Stored settings and ads.** Migration 22 deletes the saved key, turns "Higgsfield first" into Automatic and marks Higgsfield ads `baked` (see Storage). Model-access switches saved for the retired provider or a retired model match nothing any more (see Models & licences).
+ - **Partner routes added.** Happy Horse 1.1 (`happy-horse-1-1`), which only Higgsfield hosted, gets fal's text, image and reference to video routes from the research's `partnerEndpoints` (`fetch-hosted-schemas.py --partner`, checked 2026-10-27; $0.14/s at 720p, $0.18/s at 1080p). The Ad Multiplier's cloud edits become Kling O3 (the default), Happy Horse video edit and Gemini Omni Flash (see Studios).
+ - **The guard** (`tests/no-higgsfield.test.ts`, 28 tests) scans `src`, `scripts`, `bin`, `skills`, `workflows`, `package.json` and the README outside its "Upgrading from an earlier version" section, and fails on code or copy that offers Higgsfield as something Fuobe uses: lowercase ids, its environment variables, identifiers, label and value strings, "runs on" wording, and a retired model or training id quoted in `src` or `bin`. Only `replaced.ts` and `db.ts` (the migration) may name it; research file names (`higgsfield-*.md` / `.json`, `higgsfieldEquivalent`) and comparison wording pass. It also checks the catalog's providers, the settings, `REPLACED_BY`'s targets and operations, the Director words, the API notes, retries, waiting steps, the in-flight error and the migration on seeded rows. It doesn't scan `docs/` or `tests/`.
+ - **Checked** by the guard and the updated unit tests, in demo mode. No fal or Replicate call and no GPU run: Happy Horse 1.1 and the replacements' payloads are checked against the research schemas and planner tests only. Left over: browser Reuse drops Cinema Studio's Director fields (the toast says so), Soul 2.0's `color_palette` is dropped rather than turned into a palette lock, and Assist and MCP move a retired model without saying why.
+
+ ## Models & licences (`src/lib/licences.ts`, `src/lib/model-access.ts`, `src/server/model-access.ts`)
+
+ Round 4 part 4. Licences are information, not gates (the owner's decision of 2026-10-27): every model, LoRA and ComfyUI node pack carries its licence as data, and the admin decides what the install offers. Everything is on by default.
+
-- **Licence data** (`src/lib/licences.ts`). Each licence falls in a class (`LicenceClass`: Commercial use allowed, Commercial use with conditions, Restricted regions, Non-commercial, Research only, Proprietary paid API, Licence unknown); `licenceInfo` reads a licence text and `mergeLicences` keeps the strictest. An open route's licence comes from its workflow's licence text in the manifest (or `EARLIER_LICENCES`) and its node packs from the manifest; `NODE_PACKS` records each pack's licence (20, with `h3_character_swap` and `h3-relay`). Every fal and Replicate route is classed "Proprietary paid API" (`paidApiLicence`), whatever its weights' licence; the text LLM route follows Anthropic's terms or the Ollama model's licence (`llmLicence`); the browser tools are Fuobe's own code. A LoRA's licence is its ref's snapshot, else the library's (`loraLicence`); the Character swap's LoRAs carry MiniMax H3's terms. The generated `ModelDef.licence` isn't read here yet.
++- **Licence data** (`src/lib/licences.ts`). Each licence falls in a class (`LicenceClass`: Commercial use allowed, Commercial use with conditions, Restricted regions, Non-commercial, Research only, Proprietary paid API, Licence unknown); `licenceInfo` reads a licence text and `mergeLicences` keeps the strictest. An open route's licence comes from its workflow's licence text in the manifest (or `EARLIER_LICENCES`) and its node packs from the manifest; `NODE_PACKS` records each pack's licence (20, with `h3_character_swap` and `h3-relay`). Every fal and Replicate route is classed "Proprietary paid API" (`paidApiLicence`), whatever its weights' licence; the text LLM route follows Anthropic's terms or the licence of the local model in use (`llmLicence` with `localModelInUse()`: the model the ready server reports in its cached probe, else the pinned server's model setting, else Ollama's; an LM Studio or Unsloth id such as `google/gemma-3-12b` is matched on its last part). With a licence class switched off, `readAccess()` makes a new switches object when that model changes, so the gated views don't keep the old model's class; the browser tools are Fuobe's own code. A LoRA's licence is its ref's snapshot, else the library's (`loraLicence`); the Character swap's LoRAs carry MiniMax H3's terms. The generated `ModelDef.licence` isn't read here yet.
+ - **The switches** (`ModelAccess` in `src/lib/model-access.ts`): the models, licence classes, providers (`fal`, `replicate`, `comfyui`, `llm`, `local`; `higgsfield` until round 4 part 5), node packs and LoRAs switched off, and `keepGpuOnlyLoras` (off by default). They are one JSON value in the settings table under `models.access` (`readAccess` / `saveAccess` in `src/server/model-access.ts`; no migration), and a missing or unreadable value means everything is on (`ALL_ON`). A saved value that switched off the retired provider or a retired model keeps those entries, which match nothing any more and aren't carried over to the replacements. A route is off when its model, its provider, one of its node packs or its licence class is off (`routeOff`); a model is off when none of its routes is on, and a Fuobe Original with one engine's routes off runs on the other only (`gateModel`). There is no admin role: anyone who can sign in or holds an API token can change them, and on an install without a password anyone who can reach it.
+ - **Enforcement.** Runs: `prepare()` and `createGenerations()` go through `offeredFor` (`requireOffered`; then `offeredRoutes` for the route choice and `offeredLoras` for the LoRAs), and `assertOneMode` checks every step of a chain before a row exists (see Pipelines). A refusal names the switch (`offMessage`: "… is turned off in Settings → Models & licences (Non-commercial is switched off). Turn it back on there, or pick another model"), and `POST /api/generations` answers it with a 422. Listings: `GET /api/models` (and so the CLI) and the `search_models` tool of Assist and Fuobe's MCP server list only what is on (`offeredModels`). `GET /api/status` adds an `access` summary while anything is off (`offeredSummary`); the browser filters with it (`useModelAccess`, `offered`): the studio catalog (`CatalogProvider`), the canvas node picker, Cinema's menus, the studios' own menus (Genjutsu, Remove object, Image to 3D, Marketing, Katana, Shorts, Layers…), the Models page and ⌘K (`indexEntries` in `src/lib/command-search.ts`). Automatic picks fall back to the next model that is on and does the same job (`offeredDefault`, `firstOn`, `chooseMaker`'s `offered`); a fixed pick with no menu (a hidden helper step, Storyboard's model per engine) is refused, naming the switch.
+ - **Settings → Models & licences** (`/settings/models`: `src/app/(studio)/settings/models/page.tsx`, `src/components/model-access-view.tsx`): the class and provider switches with counts, searchable tabs for models (by class), LoRAs and node packs, each row with its licence, link and note, its own switch and the switch that turns it off, an Off filter and "Back to the defaults". `GET /api/settings/models` returns the whole list (`accessList`); `PUT` takes `{changes: [{kind: model | class | provider | pack | lora, id, on} | {kind: "keepGpuOnlyLoras", on} | {kind: "reset"}]}` and answers 400 when asked to switch off an id the install doesn't have (`knownSwitch`). Settings, ⌘K, About & licences and the Models page link to it.
+ - **Gates turned into information.** LoRAs licensed for the GPU only go to the cloud with a note unless `keepGpuOnlyLoras` is on (see LoRAs), and `dop.ts` lets such a LoRA ride on a cloud route that is already Fuobe DoP. The BTS motion's non-commercial LTX-2.5 LoRA joins the map (`motion-bts` in `oss-loras.generated.ts`); the preset keeps running on its words until the LoRA is evaluated, and its line says why. `gen-oss-loras.py`, `gen-lora-library.py` and `gen-soul-originals.py` print licence notes instead of failing. The evaluation harness holds a recipe for its licence only when asked (`--licence-hold`). `install-comfyui.sh` installs the non-commercial ComfyUI-Whisper unless `NC_PACKS=0`. Studio defaults a licence gate once chose are unchanged.
-- **Not covered.** Trainings (fal trainers and AI-Toolkit) and the Assist agent's and prompt enhancement's own Claude or Ollama calls aren't under the switches, and the user's own LoRAs aren't listed. Since every hosted route is "Proprietary paid API", switching off Non-commercial doesn't reach the hosted FLUX [dev] models.
++- **Not covered.** Trainings (fal trainers and AI-Toolkit) and the Assist agent's and the AI helper's own Claude or local-model calls aren't under the switches, and the user's own LoRAs aren't listed. Since every hosted route is "Proprietary paid API", switching off Non-commercial doesn't reach the hosted FLUX [dev] models.
## LLM provider (`src/server/providers/llm.ts`)
- Text steps (`translate`, `write`) run inside the server and are polled like any job; cancel aborts the call and a restart fails the job as "Interrupted" (retryable). `llmBackends(route)` lists the backends in order: Claude (claude-opus-5-5, low effort, server-side fallback) when an Anthropic key is set and AI helper is Claude, or Automatic on an install that isn't open-only; then the local model (`local`, see below) when a local server is ready, unless AI helper is pinned to Claude; for an open translation with none, ComfyUI's Qwen3.5 4B. Claude errors fall back to the next backend; endpoint `ollama` (`oss-text-llm`: the id predates the other servers and means "local only") never uses Claude; AI helper → Offline rewriter (`none`) turns text steps off. The job keeps the local server it started on (`payload.local`), polls as "Writing with LM Studio", and a text step on a local model costs 0. The provider's label is a getter, `Claude or <server>` (`llmLabel()`), so chain errors and `/api/status` name the server in use. `llmMissing()` adds the server's own reason (a key, no model loaded). `probeOllama` is kept as an alias of `probeLocal`.
-Text steps (`translate`, `write`) run inside the server and are polled like any job; cancel aborts the call and a restart fails the job as "Interrupted" (retryable). `llmBackends(route)` lists the backends in order: Claude (claude-opus-5-5, low effort, server-side fallback) when an Anthropic key is set and Prompt enhancement is Claude, or Auto on an install that isn't open-only; then Ollama when it answers, unless Prompt enhancement is pinned to Claude. Claude errors fall back to the next backend; endpoint `ollama` (`oss-text-llm`) never uses Claude; Prompt enhancement → Offline rewriter (`none`) turns text steps off. Since round 4 an open-source **translation** with no Ollama answering runs on ComfyUI instead, when ComfyUI answers: `viaComfy()` submits and polls the hidden `oss-qwen35-translate` model (Qwen3.5 4B, workflow `translate-qwen35-textgen`) with the same numbered batches, one prompt at a time, so cues keep their timing; writing still needs Ollama, and the message with neither running names both. The first check for a new Ollama URL is a blocking worker-thread probe (`probeOllama`), later checks refresh a 15 s cache in the background. A text step on Ollama costs 0. The connection test asks the servers themselves: the Anthropic key with a free one-model list call (`testClaude`), Ollama with `/api/tags` and whether the model Settings names is pulled (`testOllama`).
++Text steps (`translate`, `write`) run inside the server and are polled like any job; cancel aborts the call and a restart fails the job as "Interrupted" (retryable). `llmBackends(route)` lists the backends in order: Claude (claude-opus-5-5, low effort, server-side fallback) when an Anthropic key is set and AI helper is Claude, or Automatic on an install that isn't open-only; then the local model (`local`, see Local LLM servers) when a local server is ready, unless AI helper is pinned to Claude. Claude errors fall back to the next backend; endpoint `ollama` (`oss-text-llm`: the id predates the other servers and means "local only") never uses Claude; AI helper → Offline rewriter (`none`) turns text steps off. Since round 4 an open-source **translation** with no local model ready runs on ComfyUI instead, when ComfyUI answers: `viaComfy()` submits and polls the hidden `oss-qwen35-translate` model (Qwen3.5 4B, workflow `translate-qwen35-textgen`) with the same numbered batches, one prompt at a time, so cues keep their timing; writing still needs a local model, and the message with neither running names both. The job keeps the local server it started on (`payload.local`), polls as "Writing with LM Studio", and a text step on a local model costs 0. The provider's label is a getter, `Claude or <server>` (`llmLabel()`), so chain errors and `/api/status` name the server in use; `llmMissing()` adds the server's own reason (a key, no model loaded). `probeOllama` is kept as an alias of `probeLocal`. The connection test asks the servers themselves: the Anthropic key with a free one-model list call (`testClaude`; when text steps run elsewhere it says where), and a local server's URL, model or key by asking that server whether it answers with the model (`checkLocal`).
- `translateCues()` translates JSON cue lists, SRT and WebVTT (`src/lib/cues.ts`) in numbered batches of 30 (multi-line cues kept together); a batch that comes back merged or short is redone in pieces of 10, then cue by cue through a pool (1 request in flight on a local model, 4 on Claude). The output keeps `meta.cues`. `write` uses `params.extra.system` when given. Studios that need free text (brand research, the AI Director, storyboard splitting, ad copy, Click to Ad scripts) call `llmText(system, user, { json?, timeoutMs? })` in `src/server/enhance.ts`, with offline fallbacks (60 s, or 3 minutes while the local model still has to load). Faceless and Explainer names, topics and scripts go through the llm provider itself (`askLlm()` in `src/server/faceless.ts` submits and polls a `text-llm` / `oss-text-llm` job, `extra.json` carrying the schema), so they follow the episode's engine. The callers that want JSON pass a JSON Schema next to their prompt (brand kit, manual kit and product facts in `brand.ts`, ad copy with exactly `count` ads and the brand chat in `ads.ts`, the Director's answer with its slug enums, Faceless topics, scripts and pictures in `lib/catalog/faceless.ts`, and a root array of exactly n frames for storyboards). Claude ignores it; the parsers stay tolerant of prose and fences either way.
-`translateCues()` translates JSON cue lists, SRT and WebVTT (`src/lib/cues.ts`) in numbered batches of 30 (multi-line cues kept together); a batch that comes back merged or short is redone in pieces of 10, then cue by cue through a pool (1 request in flight on Ollama, 4 on Claude). The output keeps `meta.cues`. `write` uses `params.extra.system` when given. Studios that need free text (brand research, the AI Director, storyboard splitting, ad copy, Click to Ad scripts, Content Factory's cloud style brief) call `llmText()` in `src/server/enhance.ts`, with offline fallbacks. Since round 4 part 2 `llmText` also takes pictures (Content Factory's reference frames: Claude image blocks, or `images` for an Ollama vision model; Content Factory asks again with words only when Ollama doesn't answer with the frames), and `llmTextBackend()` says which LLM would answer (Claude is the one that costs money). Faceless and Explainer names, topics and scripts, and Content Factory's episode titles, go through the llm provider itself (`askLlm()` in `src/server/faceless.ts` submits and polls a `text-llm` / `oss-text-llm` job), so they follow the episode's engine. The Explainer also reads PDF and Word sources (`POST /api/explainer/document`, up to 20 MB; `readDocument()` in `faceless.ts`): PDFs through Assist's unpdf reader, `.docx` through `src/server/assist/docx.ts` (`word/document.xml` via the bounded unzip, which skips entries it doesn't need); a document longer than the script writer reads is summarised by the engine's text model first. The file itself isn't kept.
++`translateCues()` translates JSON cue lists, SRT and WebVTT (`src/lib/cues.ts`) in numbered batches of 30 (multi-line cues kept together); a batch that comes back merged or short is redone in pieces of 10, then cue by cue through a pool (1 request in flight on a local model, 4 on Claude). The output keeps `meta.cues`. `write` uses `params.extra.system` when given. Studios that need free text (brand research, the AI Director, storyboard splitting, ad copy, Click to Ad scripts, Content Factory's cloud style brief) call `llmText(system, user, { json?, timeoutMs? })` in `src/server/enhance.ts`, with offline fallbacks (60 s, or 3 minutes while the local model still has to load or reads pictures). Since round 4 part 2 `llmText` also takes pictures (Content Factory's reference frames: Claude image blocks, or images sent to a local vision model; Content Factory asks again with words only when the local model doesn't answer with the frames), and `llmTextBackend()` says which LLM would answer (Claude is the one that costs money). Faceless and Explainer names, topics and scripts, and Content Factory's episode titles, go through the llm provider itself (`askLlm()` in `src/server/faceless.ts` submits and polls a `text-llm` / `oss-text-llm` job, `extra.json` carrying the schema), so they follow the episode's engine. The callers that want JSON pass a JSON Schema next to their prompt (brand kit, manual kit and product facts in `brand.ts`, ad copy with exactly `count` ads and the brand chat in `ads.ts`, the Director's answer with its slug enums, Faceless topics, scripts and pictures in `lib/catalog/faceless.ts`, and a root array of exactly n frames for storyboards). Claude ignores it; the parsers stay tolerant of prose and fences either way. The Explainer also reads PDF and Word sources (`POST /api/explainer/document`, up to 20 MB; `readDocument()` in `faceless.ts`): PDFs through Assist's unpdf reader, `.docx` through `src/server/assist/docx.ts` (`word/document.xml` via the bounded unzip, which skips entries it doesn't need); a document longer than the script writer reads is summarised by the engine's text model first. The file itself isn't kept.
+
+## Local LLM servers (`src/server/llm/`)
+
+One layer for every local model: `ollama` (its own `/api/chat`), `lmstudio`, `unsloth` and `custom` (any OpenAI-compatible server: llama.cpp's llama-server, vLLM, Jan…), the last three on `POST {base}/chat/completions`. Text steps, `llmText()` and the Assist agent all call `chatLocal(ready, request)`; nothing streams.
+
+| file | what |
+|---|---|
+| `servers.ts` | Settings → `LocalServer`s: `localServers()` is the pinned one (`llmProvider`) or, in Automatic, Ollama, LM Studio, Unsloth Studio and the custom URL when set, in that order. URLs lose a pasted `/v1`; a custom URL is an OpenAI base URL (a bare host gets `/v1`). `aiHelper()` reads the old `enhanceProvider` value `ollama` as `local`. LM Studio's token also comes from `LM_API_TOKEN`, Unsloth's key from `UNSLOTH_STUDIO_AUTH_TOKEN` |
+| `probe.ts` | Each server is asked with GETs sent at once (1.5 s): Ollama `/api/tags`; LM Studio `/api/v1/models` (loaded copies, context, `trained_for_tool_use`, reasoning) and `/v1/models` for versions before 0.4; Unsloth `/api/liveness` (its `service` must be "Unsloth UI Backend": Jupyter also likes :8888) and `/v1/models` (rows with a `task` are speech or image models); custom `{base}/models`. Answers are cached 15 s per kind, URL and key hash; `interpret()` turns them into a `LocalStatus` (up, auth, chat models without embeddings, the model a call uses, `loaded`, `context`, `problem` in the user's words, `warning`) with the current Settings, so a new model name needs no new probe. The blocking first look (`refreshSync`) runs every GET in one worker thread and reads the answers with `receiveMessageOnPort` |
- | `index.ts` | `probeLocal()`, `activeLocal()` (async) and `localReady()` (sync, for routing: the first look at a server waits, later looks refresh in the background) return the first ready server. `chatLocal()` loads an LM Studio model that isn't loaded yet with `llmContext` (`POST /api/v1/models/load`, shared by concurrent calls; the chat endpoint can't set the context and LM Studio's default is 4k–8k), sends the call with the request's signal and timeout, asks again without `response_format` when a server rejects structured output, and reads tool calls written as text. `reloadLmStudio()` unloads and reloads with the context; `testLocal()` times a tiny call; `localSummary()` feeds `/api/status` |
- | `wire.ts` | Pure request builders and parsers. Ollama: `think:false` for one-shot text, `format` (a schema, or `"json"`), `options.num_ctx`. OpenAI: string tool arguments, `tool_call_id` results, `response_format` json_schema (LM Studio without `strict`; `json_object` for "any object" except on LM Studio), Unsloth's `enable_tools:false` on every call and `enable_thinking:false` for one-shot text, and no `model` for Unsloth unless one is picked (its loaded model answers). Answers lose `<think>` blocks (also a lone closing tag, or a thought cut off); `reasoning_content` / `reasoning` only mark `thought`. Tool calls get Fuobe's own nine-character ids |
++| `index.ts` | `probeLocal()`, `activeLocal()` (async) and `localReady()` (sync, for routing: the first look at a server waits, later looks refresh in the background) return the first ready server. `chatLocal()` loads an LM Studio model that isn't loaded yet with `llmContext` (`POST /api/v1/models/load`, shared by concurrent calls; the chat endpoint can't set the context and LM Studio's default is 4k–8k), sends the call with the request's signal and timeout, asks again without `response_format` when a server rejects structured output, and reads tool calls written as text. `reloadLmStudio()` unloads and reloads with the context; `testLocal()` times a tiny call; `checkLocal(kind?)` only asks the servers (Settings fields Save & test, through the llm provider's `test`); `localSummary()` feeds `/api/status` |
++| `wire.ts` | Pure request builders and parsers. Ollama: `think:false` for one-shot text, `format` (a schema, or `"json"`), `options.num_ctx`, pictures as `images`. OpenAI: string tool arguments, `tool_call_id` results, pictures as `image_url` data URLs, `response_format` json_schema (LM Studio without `strict`; `json_object` for "any object" except on LM Studio), Unsloth's `enable_tools:false` on every call and `enable_thinking:false` for one-shot text, and no `model` for Unsloth unless one is picked (its loaded model answers). Answers lose `<think>` blocks (also a lone closing tag, or a thought cut off); `reasoning_content` / `reasoning` only mark `thought`. Tool calls get Fuobe's own nine-character ids |
+| `messages.ts` | `toChatMessages()`: Assist's stored history for a local model. One system message first; for the OpenAI kinds a mid-chat context update joins the user's turn ("Context update from Fuobe (not the user):"), user turns in a row merge, and tool ids become nine letters and digits (a stable hash), as strict templates (Gemma, Mistral, some Qwen ones) need; Ollama keeps its old shape. `healToolCalls()` reads `<tool_call>{…}</tool_call>`, LM Studio's `[TOOL_REQUEST]{…}[END_TOOL_REQUEST]` and a reply that is only the call's JSON, for the offered tools only |
+| `errors.ts` | Failed calls in words that say what to do: start the server (the command for each), add or check the key (where each server makes them), download or load a model, reload with more context, or free GPU memory. `emptyReply()` says when a model spent its whole reply thinking |
+
+`GET /api/llm` (`?refresh=1` asks again) lists every server's status for Settings → AI helper, without keys; `POST /api/llm` runs `{action: "test", kind?}` or `{action: "load", model?}` (LM Studio reload). `GET /api/status` adds an `llm` block: the helper, whether Claude takes text steps, the pinned server, the local server in use (kind, label, URL, model, loaded, context, warning), the reason when none can run, and what each candidate answered. `fuobe status` prints it as "Local LLM: LM Studio at … · model".
## Live updates (`src/server/live.ts`, `src/lib/api.ts`)
@@@ -155,12 -304,14 +319,14 @@@ Checked: unit tests (token storage and
## Security (`src/proxy.ts`, `src/server/auth.ts`, `src/server/remote-fetch.ts`)
- - **Sign-in** is off until a password is set in Settings → Security or `FUOBE_PASSWORD`. State lives in `data/auth.json` (not SQLite) so the proxy can check requests with `fs` and `crypto` alone: a scrypt password hash, an HMAC secret for 30-day session cookies (replaced when the password changes), and API tokens stored as SHA-256 hashes. The proxy lets `/login` and `/api/auth/login` through, answers other API calls with 401 and redirects pages to `/login?next=…` (`safeNext()` in `src/lib/safe-redirect.ts` keeps it on the same origin). Its matcher leaves out only build assets, `samples/` and root SVGs.
+ - **Sign-in** is off until a password is set in Settings → Security or `FUOBE_PASSWORD`. State lives in `data/auth.json` (not SQLite) so the proxy can check requests with `fs` and `crypto` alone: a scrypt password hash, an HMAC secret for 30-day session cookies (replaced when the password changes), and API tokens stored as SHA-256 hashes. The proxy lets `/login` and `/api/auth/login` through (and, since round 4 part 4, GET and HEAD on a share link's page and files, checked by `openShare`: see Share links), answers other API calls with 401 and redirects pages to `/login?next=…` (`safeNext()` in `src/lib/safe-redirect.ts` keeps it on the same origin). Its matcher leaves out only build assets, `samples/` and root SVGs.
- **Host allowlist** (`hostAllowed`), for every method when no password is set, before anything else: IP literals, localhost and `*.localhost`, single-label names, `.local` / `.lan` / `.home.arpa` / `.internal` / `.localdomain`, this machine's hostname, and `FUOBE_ALLOWED_ORIGINS` (`*` allows any). This stops DNS rebinding. `X-Forwarded-Host` is not trusted here.
- **Cross-site writes** (`crossSite`): non-GET/HEAD/OPTIONS requests get 403 when `Origin` matches neither Host, `X-Forwarded-Host` nor `FUOBE_ALLOWED_ORIGINS`, when it is `null`, or when `Sec-Fetch-Site` is cross-site — with or without a password.
- - **Login throttle** (`LoginGuard`): 5 misses per client and 20 a minute overall, bounded map, `Retry-After`. Route handlers can't see the socket address, so the client key is the last `X-Forwarded-For` hop only with `FUOBE_TRUST_PROXY=1` (then a 60 s lock per client); otherwise everyone shares a key that is slowed to one attempt every 4 s and never locked.
- - **Remote fetch** (`fetchRemote`): every caller-supplied URL (references, brand research, product links, YouTube oEmbed, Assist sources) is fetched only from public addresses. The check runs inside the socket lookup (DNS can't change after it) and again on each of at most 5 redirects; it blocks loopback, RFC 1918, link-local / metadata, CGNAT, multicast, ULA and mapped / NAT64 / 6to4 IPv4. 60 s deadline, 200 MB cap. `FUOBE_ALLOW_PRIVATE_URLS=1` turns it off for LAN installs.
- - Uploads up to 200 MB pass the proxy (`experimental.proxyClientMaxBodySize: "210mb"` in `next.config.ts`, room for the multipart overhead). `/api/files` sends `nosniff` and a UTF-8 charset for text. The MCP endpoint refuses a foreign `Origin`. Unknown `/apps/<id>` is rewritten to a real 404.
+ - **Login throttle** (`LoginGuard`): 5 misses per client and 20 a minute overall, bounded map, `Retry-After`. Route handlers can't see the socket address, so the client key is the last `X-Forwarded-For` hop only with `FUOBE_TRUST_PROXY=1` (then a 60 s lock per client); otherwise everyone shares a key that is slowed to one attempt every 4 s and never locked. Since round 4 part 4 the same client key drives `ShareGuard`, the throttle on wrong share tokens.
+ - **Remote fetch** (`fetchRemote`): every caller-supplied URL (references, brand research, product links, YouTube oEmbed, Assist sources) is fetched only from public addresses. The check runs inside the socket lookup (DNS can't change after it) and again on each of at most 5 redirects; it blocks loopback, RFC 1918, link-local / metadata, CGNAT, multicast, ULA and mapped / NAT64 / 6to4 IPv4. 60 s deadline, 200 MB cap. `fetchRemoteToFile` makes the same checks but streams to a file (16 GB cap, 30-minute deadline; a failed download leaves no file); it fetches the extra files a result links to. `FUOBE_ALLOW_PRIVATE_URLS=1` turns both off for LAN installs, and since round 4 part 4 also lets an Assist connector's URL use plain http beyond localhost (Fuobe never fetches a connector's URL itself: Anthropic's servers do).
+ - **LoRA links** (round 4 part 2) don't go through `fetchRemote`. `POST /api/generations` takes a LoRA link only over https on huggingface.co, hf.co, civitai.com, fal.media or replicate.delivery, with no credentials in it (`LORA_HOSTS` in `src/app/api/generations/route.ts`), and a file name that stays inside the LoRA folder (`lorasPath` also requires `.safetensors`). The server may download such a file into the LoRA folder before a ComfyUI run. Downloads from huggingface.co and civitai must match a SHA256; a link on hf.co, fal.media or replicate.delivery isn't held to one, so such a file can be kept unchecked, with no size limit and a 60-minute timeout. The civitai key travels only in civitai's download URL and is redacted from messages.
-- **Connection tests** (`POST /api/providers/test`, `src/lib/connections.ts`): Settings' Save & test sends the typed, unsaved values; the route runs the provider's `test()` inside `withCandidates()` (an `AsyncLocalStorage` override of `getSetting`, `src/server/settings.ts`) and stores nothing. Testing a different, unsaved ComfyUI address doesn't send the saved token to it (`isCandidate` / `savedSetting`). Like saving an address, a test makes the server fetch the ComfyUI or Ollama address it is given. Since round 4 part 2 the route also tests the civitai key (`{provider: "civitai"}`, civitai's `/me`), which isn't a model provider's. Since round 4 part 5 `higgsfield` is no test provider: the route answers 400 "Unknown provider".
++- **Connection tests** (`POST /api/providers/test`, `src/lib/connections.ts`): Settings' Save & test sends the typed, unsaved values; the route runs the provider's `test()` inside `withCandidates()` (an `AsyncLocalStorage` override of `getSetting`, `src/server/settings.ts`) and stores nothing. Testing a different, unsaved ComfyUI address doesn't send the saved token to it (`isCandidate` / `savedSetting`), and the same holds for LM Studio's token, Unsloth Studio's key and the Other server's key (`localServer()` in `src/server/llm/servers.ts`): only a key typed with the new address goes to it. The local model's context field (`llmContext`) only saves, since no server tests it on its own (`ConnectField`'s `saveOnly`). Like saving an address, a test makes the server fetch the ComfyUI or local LLM server address it is given. Since round 4 part 2 the route also tests the civitai key (`{provider: "civitai"}`, civitai's `/me`), which isn't a model provider's. Since round 4 part 5 `higgsfield` is no test provider: the route answers 400 "Unknown provider".
+ - Uploads up to 200 MB pass the proxy (`experimental.proxyClientMaxBodySize: "210mb"` in `next.config.ts`, room for the multipart overhead). Since round 4 part 5 `POST /api/uploads` also takes MKV (`video/x-matroska`) and AVI (`video/x-msvideo`) for every upload (only Character Swap Studio's picker lists them; the others still list MP4, MOV and WebM), and maps the names browsers give them (`video/avi`, `video/msvideo`, `video/vnd.avi`, `video/mkv`); browsers can't play AVI, so only Character Swap Studio makes a playable copy (on the cloud), and some providers may refuse it. `/api/files` sends `nosniff` and a UTF-8 charset for text; since round 4 part 4 it and the share files route share `fileResponse` (`src/server/file-response.ts`), and a path that exists but isn't a file is a 404. The MCP endpoint refuses a foreign `Origin`. **Real 404s**: the proxy rewrites an unknown `/apps/<id>`, an unknown hub mode (`unknownHubMode`) and a record page whose id isn't stored (`recordForPath` in `src/lib/record-pages.ts`, then `recordExists` in `src/server/records.ts`, one primary-key lookup; a database that can't be read counts as "exists") to the not-found page with a 404, because a page's `loading.tsx` streams a 200 before the page knows. Every `[id]` page also calls `notFound()` (round 4 part 5 adds `/character-swap/[id]`, record kind `swap-project`).
## Studios
@@@ -168,39 -319,89 +334,89 @@@ Each studio keeps its data and pure pla
| studio | pure logic | server | routes | UI |
|---|---|---|---|---|
- | **Cinema Studio** (`/cinema`, `/cinema/[id]`) | `catalog/cinema.ts`: research data (genres, eras, 33 camera moves, 50 palettes, 7 lighting presets, Emotion Wheel, 17 Soul Cast fields, grids), `compileDirector` (native Cinema Studio 4.0 fields or prose), `planCinema` (steps with `after`, notes, blocker, cost), `takesClips` (feature-detected from the FieldMap) | `cinema.ts` (projects, nested scenes, `cinema_items` with per-take meta: take, tiles, cost, req, removed; spend in SQL), `cinema-generate.ts` (`generateInProject`: previews every step, checks the cost cap), `cinema-director.ts` (AI Director via `llmText`, offline fallback, never generates), `cinema-schemas.ts` | `/api/cinema/projects[/id[/folders[/folderId] \| /items[/genId/retry \| /tiles] \| /generate \| /director]]` | `components/cinema/*`: workspace, folder sidebar, feed, prompt bar, Director's Panel, palette editor (`color-math.ts`), grid crops (`grid-math.ts`), Soul builders, autosave |
- | **Canvas** (`/canvas`, `/canvas/[id]`) | `catalog/canvas.ts`: node types and typed ports, `connectionError`, `topoOrder`, `describeNode` (a GenerationRequest validated with `planGeneration` on placeholders), `planCanvas` (run vs reuse by signature, pins), `convertEngine`, the 5 templates (cloud and open) | `canvas.ts`: zod graph, CRUD, `canvasView`, `runCanvas` (one generation per step with `dependsOn`; runs kept in `runs_json`), `graphProblem` | `/api/canvases[/id[/duplicate \| /run]]` | `components/canvas/*` on @xyflow/react: editor store (`canvas-context.tsx`, `useSyncExternalStore`, `DescribeCache`), nodes, palette, phone node list |
- | **Layers** (`/layers`, `/layers/[id]`) | `lib/layers.ts`: LayerDoc / LayerNode geometry, export scale, zip naming `layer-z{z}-{slug}.png`, stored zip, Copy JSON, `historyReducer` (same-key edits within 1.2 s are one undo), `layersModelFor`, `MAX_NODES = 200`, `MAX_REVISIONS = 50` | `layers.ts`: projects and versions (autosave into the head, 409 from a stale tab), tool jobs built by `jobSteps` (a cut-out step after edits on transparent layers), "decomposed" derived from applied jobs | `/api/layers[/id[/versions \| /jobs[/jobId]]]`, `/api/layers/renders` (PNG-only "derived" assets) | `components/layers/*`: results measured in the browser (`measure.ts`) and laid out by `applyMeasured` (`apply.ts`), zips and composites rendered with canvas (`render.ts`), WebGL grade |
- | **Shorts Studio** (`/shorts`, `/shorts/[id]`) | `catalog/shorts.ts`: 44 presets, `planCloudSegments` (equal ≤10 s), `planOpenSegments` (4n+1 frames ≤81 at 16 fps), `planTake`, `planStitch`, `planShorts`, `chainState`; `catalog/shorts-models.ts` (what each restyle model takes, read from its v2v routes); `lib/trim-range.ts` | `shorts.ts` (sessions, segments with takes and the primary take, stitches; `probeSource` reads MP4 then WebM via `webm-probe.ts`), `shorts-schemas.ts` (`once(scope, requestId, fn)`: one paid submit per click, 10 min) | `/api/shorts/{probe,estimate,sessions[/id[/segments/i[/primary] \| /stitch]],presets[/id]}` | `components/shorts/*`, the shared `components/studio/video-trimmer.tsx` |
- | **Mixed Media** (`/mixed-media`) | `catalog/mixed-media.ts`: 33 presets with settings, frames = floor(s × fps), open render (one `oss-mixed-media` job) and cloud plan (trim → restyle → original sound), preview plan | `mixed-media.ts`: estimate, render, preview, `retryMixed`; no table (History is the feed: features `mixed-media`, `mixed-media-step`, `mixed-media-preview`) | `/api/mixed-media[/preview \| /estimate \| /retry]` | `components/mixed-media/*` |
- | **Image studios** (Color signature, Moodboards, Photodump, Fashion Factory, Character Sheet) | `catalog/palettes.ts` (`applySignature`, `SignatureRecord` in `request.signature`), `catalog/packs.ts` (photo-run planners with `PlanCaps`) | `palettes.ts` (seeded 50 palettes, lock chains), `moodboards.ts` (status derived from the cover job, Recraft style id, style LoRA), `photodump.ts` (runs as one `createPipeline` batch; `retryPhoto`) | `/api/palettes[/id \| /lock]`, `/api/moodboards[/id[/retry \| /train]]`, `/api/photodump[/packs[/id] \| /character \| /fashion \| /retry]` | `components/{palettes,moodboards,photodump,fashion}/*`; k-means in `palettes/extract.worker.ts`; the chips load through `useSignature` in the composer |
- | **Marketing** (Marketing Studio, Click to Ad, Ads Studio, Ad Multiplier) | `catalog/marketing.ts`: 84 templates, 11 formats, 9 hooks, 14 settings, 10 ad styles, angles, word budgets, `formatModels`, `UGC_MODELS`, `OPEN_SOUND_JOIN` | `brand.ts` (website scrape, research job, `kitForSite`), `marketing.ts` (`planMarketing`, `planClickToAd`, `planMultiplier` with `referenceFacts` → RunPlan → `createPipeline`; `marketing_runs` keeps the input for Run again and the browser composite), `ads.ts` (batches, creatives, concepts, chat, proposals) | `/api/brands/**`, `/api/products/**`, `/api/marketing/**`, `/api/ads/**` | `components/{marketing,ads,brand}/*`; ad layout math (`ads/layout.ts`) → canvas render with Google fonts (`ads/render.ts`) → stored zip (`ads/zip.ts`); @mention helpers (`ads/mention.ts`) |
- | **Faceless Studio / Explainer** (`/faceless`, `/explainer`) | `catalog/faceless.ts`: genres, 22 styles (12 for Faceless), block planning, `buildEpisodeGraph` (steps keyed still / clip / join / narration / music / mix / words / captions), `planRerun`, `planRetry`, `estimateGraph`, `spokenTimes`, `sceneTiming`, `musicLength`, `styleRefLimit` | `faceless.ts`: channels (avatar job), episodes, scripts written in the background by the llm provider (`askLlm`), `launch()` (stage one: stills, narration, word timings) and `advance()` (scenes cut to the spoken times, then clips, joins, music, mix, subtitles), `settle()`, `ensureFacelessRunner()` (2 s sweep, started at boot) | `/api/faceless/**`, `/api/explainer[/link]` | `components/{faceless,explainer}/*` |
- | **Translate & dub, Captions, Trim, Katana, Image to 3D, Virality** | `lib/av/*.ts` as plain data: `dub.ts` (one-shot and step plans, takes, timeline), `captions.ts` (burner capabilities), `cue-edit.ts`, `katana.ts` (cuts, `stepsToRedo`), `model3d.ts`, `frames.ts`, `timeline.ts`, `virality.ts`, `languages.ts` | `dub.ts` and `katana.ts` keep generation ids per step in `dub_sessions` / `katana_jobs` (`retryKatana`, `rerunKatana`); deleting stops unfinished steps | `/api/dub[/id[/voice]]` (`?preview=1` prices), `/api/katana[/id[/retry]]` | `components/{dub,captions,katana,model3d,virality,av}/*`. Hub tool modes: `ModeSwitchStudio` has a `TOOLS` map (`audio/translate`, `video-tools/captions`, `video-tools/trim`) |
- | **Assist** (`/assist`, `/assist/skills`, `/assist/memory`, `/assist/projects/[id]`) | `lib/assist.ts`: SKILL.md parsing (`parseSkillMd`, `toSkillMd`), slash helpers, modes, `planRunnable` | `server/skills.ts` (built-ins from `skills/` or `FUOBE_SKILLS_DIR`, user skills and toggles in SQLite, `.md` / `.zip` / `.skill` import via `assist/unzip.ts`), `assist/projects.ts` (sources fetched safely; PDFs read by `assist/pdf.ts` with unpdf), `assist/memory.ts`, `assist/context.ts`, `assist/studio-tools.ts` | `/api/assist/**` | `components/assist/*`, `assist-view.tsx` |
+ | **Cinema Studio** (`/cinema`, `/cinema/[id]`) | `catalog/cinema.ts`: research data (genres, eras, 33 camera moves, 50 palettes, 7 lighting presets, Emotion Wheel, 17 Soul Cast fields, grids), `compileDirector` (prose; the native Cinema Studio 4.0 fields are no longer used; since round 4 part 5 `directorFieldWords` writes a stored Cinema Studio 4.0 request's fields as those words), `planCinema` (steps with `after`, notes, blocker, cost), `takesClips` (feature-detected from the FieldMap). Round 4 part 4 (Fuobe Cinema, see Fuobe Originals): the menus per mode and engine (`CINEMA_MODELS`, the Original first, `ORIGINAL_LINES`), `CINEMA_CAMERA_LORA`, `cinemaMoveRoute`, `CAST_MODELS` / `LOCATION_MODELS`, `planLocationView`, `editPrompt`; no Higgsfield model or key check (`HIGGSFIELD_ONLY` is gone). 3D scenes (round 4): the `scene` and `recompose` actions with `SCENE_MODELS` (cloud `marigold-depth`, open `oss-scene-moge`) and `RECOMPOSE_MODELS` (cloud Nano Banana Pro or Qwen Multiple Angles, open `oss-qwen-edit` with the Multiple-Angles LoRA); `src/lib/scene3d.ts` (lens 18–300 mm and field of view, fly controls, Spectral depth decoding → point cloud, `scenePose`, `recomposePrompt`, capture size) | `cinema.ts` (projects, nested scenes, `cinema_items` with per-take meta: take, tiles, cost, req, removed; spend in SQL; the automatic cover skips depth maps), `cinema-generate.ts` (`generateInProject`: previews every step, checks the cost cap; a recompose take keeps its `camera`), `cinema-director.ts` (AI Director via `llmText`, offline fallback, never generates), `cinema-schemas.ts` (a recompose `capture`: an `/api/files/` URL, lens, aperture, pose; since round 4 part 4 the `source` take's facts: `modelId`, `prompt`, `seconds`, `resolution`, `aspectRatio`); `cinemaContext()` is `{cloudAllowed, civitai, has}` | `/api/cinema/projects[/id[/folders[/folderId] \| /items[/genId/retry \| /tiles] \| /generate \| /director]]` (generate takes `action` `scene` and `recompose`; the project's `context` is `{cloudAllowed, civitai}`) | `components/cinema/*`: workspace (since round 4 part 4 a Share button in the header and a share item in the project menu), folder sidebar, feed (finishes Fuobe Soul stills), prompt bar (the Original first with its badge and per-engine line, models switched off left out), Director's Panel, camera moves (a route badge per move on both engines), palette editor (`color-math.ts`), grid crops (`grid-math.ts`), Soul builders (Fuobe Soul looks), autosave; `scene-actions.tsx` (Create 3D scene, priced, asks first), `scene-viewer.tsx` + `scene-engine.ts` (full-screen three.js viewer, loaded only when a scene opens; Capture uploads the framed view and queues a recompose take) |
+ | **Canvas** (`/canvas`, `/canvas/[id]`) | `catalog/canvas.ts`: node types and typed ports, `connectionError`, `topoOrder`, `describeNode` (a GenerationRequest validated with `planGeneration` on placeholders), `planCanvas` (run vs reuse by signature, pins), `convertEngine`, the templates (cloud and open); since round 4 part 5 `withCurrentModels` (on every board read: `toCanvas` in `src/server/canvas.ts`) and `cleanGraph` move a node on a retired model, or on a partner model's lost operation, to what replaced it (`currentNode`; an Original node keeps the cloud unless it names an engine); input ports for the round-4 operations, and a chained route fed by another node (a keyframe film, the open text-to-3D route) is refused before Run. Round 4 part 3: 18 node types (new: Change voice, Clone voice with a `voice` port type, Translate for text or video, Video concatenator with per-clip `clips` cuts, mutes and `order`, Table with `columns` and `rows`; their default models are in `PREFERRED`: `voice-change` ElevenLabs Voice Changer or `oss-chatterbox-vc`, `dub` ElevenLabs Dubbing, `translate` `text-llm` or `oss-text-llm`), 7 templates (new: `clips-film`, `table-film`; the talking avatar's sample is a Clone voice node), `concatRequest` and `rowRequest` (a node made in steps, a node run per table row: see Pipelines), `tablesFeeding`, `CONCAT_LIMITS` (50 clips, 30 fps, 512 MB a clip, cloud joins of 24), `CONCAT_RATIOS` (8 shapes, 720 on the short side) and `TABLE_LIMITS` (8 columns, 50 rows). `catalog/canvas-board.ts`: pages (`readPages`: a row saved before pages reads as page 1; `copyPage` with `remapNodeData`), groups (`groupMembers`: a node belongs to every group its top-left corner sits in; `groupTargets` for Run group), comment pins with replies, shapes and pen strokes (`penShape`, at most 400 points), `BOARD_LIMITS` (20 pages) | `canvas.ts`: zod graph (since round 4 part 3 with groups, comments and shapes, and `PagesSchema`), CRUD, `canvasView`, `runCanvas` (one generation per step with `dependsOn`, or one `createPipeline` for a node made in steps or rows; runs kept in `runs_json`), `graphProblem`, `pagesProblem`. Round 4 part 3: `graph_json` holds `{pages: [{id, name, graph}]}` (no migration; a canvas switches when next saved); `updateCanvas` takes every page or one page's graph, and a page it can't take (a 21st, or one the run names that is gone) is a `CanvasConflict` (409); a run saves every page first and runs one page, a selection or a group; the cloud concatenator's silent WAVs are written per run (`silenceWriter`), and a stored clip over 512 MB is refused (`oversizedClip`) | `/api/canvases[/id[/duplicate \| /run]]`. Since round 4 part 3 create, PATCH and run take `pages` (PATCH also `graph` with `page`; run also `page` and `group`), and responses return `pages`, not `graph` (summaries add `pageCount`) | `components/canvas/*` on @xyflow/react: editor store (`canvas-context.tsx`, `useSyncExternalStore`, `DescribeCache`, whose key follows a concatenator's tables), nodes, palette, phone node list. Round 4 part 3: `board.tsx` (groups, comments and shapes as React Flow nodes), `toolbar.tsx` (V, H, D, E, N, ⇧T, R, T, C), page tabs and per-page undo in `canvas-editor.tsx`, and in `nodes.tsx` the Clone voice, Table, concatenator and open dub hand-off (a Translate video node on an open-only install starts a `/api/dub` session, keeps it as `dubId` and offers the dubbed clip back as a Video input); phones get a page picker over the read-only board |
+ | **Layers** (`/layers`, `/layers/[id]`) | `lib/layers.ts`: LayerDoc / LayerNode geometry, export scale, zip naming `layer-z{z}-{slug}.png`, stored zip, Copy JSON, `historyReducer` (same-key edits within 1.2 s are one undo), `layersModelFor`, `MAX_NODES = 200`, `MAX_REVISIONS = 50`, `TOOL_MODELS` (each tool's models per engine). Round 4 part 2: Inpaint (`inpaintPrompt`) and the Enhancer (`ENHANCE_LOOKS` Skin, Soft glow, Sharpen and Detail; `ENHANCE_DETAIL_SCALE` makes Detail 2× on every engine), text rows placed from OCR boxes (`placeTextBlocks`), `seeThrough`, `readableBackdrop`, `elementDraft`; `src/lib/ocr.ts` reads an OCR model's answer into lines with 0–1 boxes | `layers.ts`: projects and versions (autosave into the head, 409 from a stale tab), tool jobs built by `jobSteps` (a cut-out step after edits on transparent layers), "decomposed" derived from applied jobs. Round 4 part 2: `text-detect` picks op `ocr` or `text-layers` from the model's routes (cloud Ideogram 3.0 Text Layers or Florence-2 OCR, open OvisOCR3); `inpaint` sends the painted mask (and a red-tinted sketch), and `applySketch` gives mask models the mask and edit models the tinted copy (cloud Nano Banana Pro, FLUX.1 Fill [pro], Z-Image Turbo Inpaint; open FLUX.1 Fill [dev]); `enhance` is an edit with a fixed instruction (Nano Banana Pro, Seedream 5.0 Pro; open Qwen-Image-Edit 2511) or, for Detail, an upscaler (Topaz, SeedVR; open SeedVR2 or ESRGAN) | `/api/layers[/id[/versions \| /jobs[/jobId]]]` (jobs take `inpaint` with `mask` and `sketch`, and `enhance` with `settings.look`), `/api/layers/renders` (PNG-only "derived" assets) | `components/layers/*`: results measured in the browser (`measure.ts`) and laid out by `applyMeasured` (`apply.ts`), zips and composites rendered with canvas (`render.ts`), WebGL grade; paint mode on the stage (`stage.tsx`), Keep transparency on only for layers with see-through pixels (`keep-alpha.ts`), and Save as element (`save-element.tsx`: the layer's trimmed PNG through `POST /api/elements`, as a character, prop or style) |
+ | **Shorts Studio** (`/shorts`, `/shorts/[id]`) | `catalog/shorts.ts`: 44 presets, `planCloudSegments` (equal ≤10 s), `planOpenSegments` (4n+1 frames ≤81 at 16 fps), `planTake`, `planStitch`, `planShorts` (with `keepShape` for Genjutsu's restyle: no crop, framing as filmed), `chainState`; `catalog/shorts-models.ts` (what each restyle model takes, read from its v2v routes); `lib/trim-range.ts` | `shorts.ts` (sessions, segments with takes and the primary take, stitches; `probeSource` reads MP4 then WebM via `webm-probe.ts`), `shorts-schemas.ts` (`once(scope, requestId, fn)`: one paid submit per click, 10 min) | `/api/shorts/{probe,estimate,sessions[/id[/segments/i[/primary] \| /stitch]],presets[/id]}` | `components/shorts/*`, the shared `components/studio/video-trimmer.tsx` |
+ | **Mixed Media** (`/mixed-media`) | `catalog/mixed-media.ts`: 33 presets with settings, frames = floor(s × fps), open render (one `oss-mixed-media` job), cloud Fast plan (trim → restyle → original sound), preview plan. Round 4 part 2: the cloud Per frame plan (`planMixedFrames`, the cloud default): cut → `extract-frames` (every Nth frame of the clip, `frameSampling`; up to 500 a call) → one Nano Banana 2 or Seedream 5.0 Flash edit per frame (`frameEditParams`: a fixed seed on Nano Banana 2, while Seedream 5.0 Flash takes none; `planMixedFrames` gives each frame the one styled before it as a second picture, in lanes of 12 that start from the approved preview) → `images-to-video` in clips of up to 200 frames → `join-clips` at up to 2048 px (`frameJoinSize`; 4K frames are then drawn at 2K, `frameResolution`) → the cut's own sound; the limits are `FRAME_LIMITS` | `mixed-media.ts`: estimate (adds `mode`, `perFrameUsd`, the sampled `fps`, `providers`, `modelId`), render, preview; `cloudMode` takes `mode` or reads it from the model (a model of the other mode is a 422); `retryMixed` redoes only failed or canceled steps and what follows them (`createPipeline` `existing`, `unfilledRequest`) and cancels the old waiting ones; `framesProgress` names the frame that failed; no table (History is the feed: features `mixed-media`, `mixed-media-step`, `mixed-media-frame-step`, `mixed-media-preview`) | `/api/mixed-media[/preview \| /estimate \| /retry \| /progress?id=]` | `components/mixed-media/*` (the Restyle switch, Per frame or Fast, and the price per frame) |
+ | **Image studios** (Color signature, Moodboards, Photodump, Fashion Factory, Character Sheet) | `catalog/palettes.ts` (`applySignature`, `SignatureRecord` in `request.signature`; since round 4 part 3 a Soul model locks the palette by default on the open engine, and curated moodboards are Fuobe Soul looks: see Fuobe Originals), `catalog/packs.ts` (photo-run planners with `PlanCaps`; since round 4 part 5 `PlanCaps` is only `has(id, engine)`, the packs and templates come from `studio-packs.generated.ts`, and `castSheetModel` makes Character Sheet's Soul Cast sheet on Fuobe Soul's cloud half in Cinema's casting look (Nano Banana Pro when that half is switched off; the Soul Cast sheet graph on the GPU); since round 4 part 4 Photodump and Fashion run a character with a Soul ID on Fuobe Soul with its trained LoRA on both engines, `PHOTODUMP_SOUL` and `soulIdOf`, else Nano Banana Pro, Seedream 5.0 Pro or Qwen-Image-Edit from the photos). Since round 4 part 4 a moodboard trained as a style LoRA is a Fuobe look (`OWN_LOOK`, `own-style`: its LoRA, no look words) on Fuobe Soul and the Z-Image family on either engine (`palettes.ts`) | `palettes.ts` (seeded 50 palettes, lock chains; the lock keeps a Soul look's `presetStrength` and the `engine`), `moodboards.ts` (status derived from the cover job, Recraft style id, style LoRA; since round 4 part 4 `moodboardTrainingTargets` and `trainMoodboard`: a style element from up to 80 of the board's images, trained on the GPU or with fal's Z-Image style trainer), `photodump.ts` (runs as one `createPipeline` batch; `retryPhoto`, since round 4 part 5 through `currentRequest`, its chained step too; the AI Influencer app's sheet runs on Nano Banana Pro in the cloud, `sheetRequest`) | `/api/palettes[/id \| /lock]`, `/api/moodboards[/id[/retry \| /train]]` (since round 4 part 4 `GET …/train` lists the style targets with price, blocker and demo flag, and `POST` takes an optional `target`), `/api/photodump[/packs[/id] \| /character \| /fashion \| /retry]` | `components/{palettes,moodboards,photodump,fashion}/*`; k-means in `palettes/extract.worker.ts`; the chips load through `useSignature` in the composer; the curated sets are built in (`CURATED_SETS` in `moodboards/logic.ts`, drawn covers, nothing fetched from Higgsfield) and a curated card opens `/image?model=fuobe-soul&moodboard=curated:<id>`; since round 4 part 5 the empty Image studio's "Make your own Soul look" cards (`moodboards/soul-preset-cards.tsx`) show for Fuobe Soul and Soul HD, where they showed for Soul 2.0 |
+ | **AI Influencer builder** (`/influencer`; round 4 part 2) | `src/lib/influencer.ts`: the tiers (Average, Bold, Extreme, and six creature types with species and body colour), what each tier shows, pick rules and the two clashes (`togglePick`, `conflictFor`, `setTier`), seeded Shuffle with the researched weights and per-category locks (`shuffleInfluencer`), the prompt compiler (`compileSheetPrompt`, `compileCastPrompt`, `compileDressPrompt`), `faceOfRun` and `planInfluencer` per engine; the option data is generated (`catalog/influencer-options.generated.ts`) | `influencer.ts`: prices with Photodump's helpers (`planCaps`, `previewRun`, `runEngine`) and makes one job or a two-step `createPipeline`. Cloud: one sheet on Nano Banana Pro (16:9, 2K, the default) or Seedream 5.0 Pro, with the photo and clothing as references. Open: the Soul Cast sheet (`oss-zimage-soul-cast`); with a face, a reference or clothing, Qwen-Image-Edit 2511 (`oss-qwen-edit`) then takes the sheet as image 1, the photo and clothing after it (3 images at most), and the sheet becomes a helper step (`influencer-step`). No Higgsfield route. `retryPhoto` (`photodump.ts`) runs both steps again when the sheet failed, and re-chains a pass that never launched | `POST /api/influencer` (`?preview=1` prices it); retries through `POST /api/photodump/retry` | `components/influencer/*` (`influencer-builder.tsx`, `option-panel.tsx`); Save as character reuses `SaveCharacter` from `fashion/character-sheet.tsx` and reads the face from the run itself (`faceOfRun`); linked from Character Sheet, and from the AI Influencer app through `StudioConfig.related` |
+ | **Marketing** (Marketing Studio, Click to Ad, Ads Studio, Ad Multiplier) | `catalog/marketing.ts`: 84 templates, 11 formats, 9 hooks, 14 settings, 10 ad styles, angles, word budgets, `formatModels` (since round 4 part 5 without Marketing Studio Image), `UGC_MODELS`, `OPEN_SOUND_JOIN`; since round 4 part 5 the Ad Multiplier's `MULTIPLIER_MODELS` (cloud: Kling O3 edit by default, Happy Horse video edit and Gemini Omni Flash), `MULTIPLIER_WINDOW` (Kling O3 and Happy Horse recreate at most 15 s) and `mentionsFor` binding `@ImageN` for Happy Horse as for Kling; since round 4 part 2 the Click to Ad logo end card (`END_CARD`, `END_CARD_MODELS`, `endCardSteps`: cloud [`overlay-image`: the logo on the brand colour →] `ken-burns` → a silent track (`merge-audio-video`) → `join-clips` after the ad; open `oss-append-endcard`, or `oss-still-to-clip` + `oss-join-sound1` for an ad ComfyUI didn't encode) | `brand.ts` (website scrape, research job, `kitForSite`), `marketing.ts` (`planMarketing`, `planClickToAd`, `planMultiplier` with `referenceFacts` → RunPlan → `createPipeline`; since round 4 part 5 it cuts a longer selection to the edit model's window with a note, prices the edit by the clip's length and keeps the reference's sound (`KEEP_SOUND`: Kling's `keep_audio`, Happy Horse's `audio_setting` "origin"); since round 4 part 4 the Ad Multiplier's open recreation runs `fuobe-genjutsu-motion` pinned to the open engine; `marketing_runs` keeps the input for Run again and the browser composite; `withEndCard` turns the ad's last step into a helper and adds the card, with `adEncoder`, `cardBackground` and `silentWav`), `ads.ts` (batches, creatives, concepts, chat, proposals; since round 4 part 5 every ad is copy plus one visual composited in the browser: `BatchBody` has no `route` or `ratio`, the estimate no `route`, and an ad Higgsfield drew whole is `baked`, shown as it is and remade the Fuobe way on Retry) | `/api/brands/**` (since round 4 part 5 `POST /api/brands/[id]/chat/confirm` takes `{messageId, engine}`), `/api/products/**`, `/api/marketing/**` (Click to Ad and its estimate take `endCard`), `/api/ads/**` | `components/{marketing,ads,brand}/*`; ad layout math (`ads/layout.ts`) → canvas render with Google fonts (`ads/render.ts`) → stored zip (`ads/zip.ts`); @mention helpers (`ads/mention.ts`); the 9:16 end card drawn in the browser (`marketing/end-card.ts`) and uploaded once per look |
+ | **Faceless Studio / Explainer** (`/faceless`, `/explainer`) | `catalog/faceless.ts`: genres, 22 styles (12 for Faceless), block planning, `buildEpisodeGraph` (steps keyed still / clip / join / narration / music / mix / words / captions), `planRerun`, `planRetry`, `estimateGraph`, `spokenTimes`, `sceneTiming`, `musicLength`, `styleRefLimit`. Round 4: Frame by frame is a Ken Burns move per scene, not a video model (`ENGINE_MODELS.kenBurns`: the cloud's `ken-burns` zooms only, the open `oss-ken-burns` pans and zooms and splits scenes over 10 s; the moves come from the scene's words, `sceneMoves` in `src/lib/av/ken-burns.ts`), joined with `framesJoin` (`oss-join-encoded` on the open engine); `musicPlan` adds a `music-loop` step when the film outlasts the music (open `oss-audio-loop` crossfades up to 600 s, the cloud's `join-audio` repeats whole plays); `staleSteps` / `bedFits` redo kept steps whose model, operation, clip length or music bed no longer fits; the open `upscale` is `oss-upscale-video-esrgan`. Since round 4 part 2 a channel's `settings.brief` (`BriefLook`, from Content Factory) adds look, camera and music words to the prompts, sets the scene length and the captions' words and position | `faceless.ts`: channels (avatar job), episodes, scripts written in the background by the llm provider (`askLlm`), `launch()` (stage one: stills, narration, word timings) and `advance()` (scenes cut to the spoken times, then clips, joins, music, mix, subtitles), `settle()`, `ensureFacelessRunner()` (2 s sweep, started at boot); a Motion change that reads as the scene's current camera move answers 422 (`sameCameraMove`); `readDocument()` for PDF and Word sources | `/api/faceless/**`, `/api/explainer[/link \| /document]` | `components/{faceless,explainer}/*` |
+ | **Content Factory** (`/content-factory`, `/content-factory/[id]`; round 4 part 2) | `catalog/content-factory.ts`: the style brief (`StyleBrief`: format, hook, pacing, shots, look, animation, voice, music, captions, topics; `parseBrief` reads an LLM's answer, `offlineBrief` makes one from the clip's shape, length and speech rate), 8 preset styles, 4 animation styles, lengths 30 s to 5 min, up to 10 episodes, the link guard (`referenceLink`: TikTok, Instagram, a direct clip or a web page; YouTube asks for an upload; `pageMedia` finds a page's og:video or `<video>`), episode titles (`parseSeries`, `offlineSeries`), prices (`seriesPrice`, `briefCostUsd`) and the Generate in Claude message (`claudePlan`, `claudeMessage`, `mcpCommand`) | `content-factory.ts`: a series is a `content_series` row whose episodes are ordinary Faceless episodes in a channel of its own (`createChannel` with the brief in its settings, then `createEpisode` per title; nothing is forked). Reading a reference: cloud = `extract-frames` (about a frame a second, JPEG) and Scribe v2 as generations, then `llmText` writes the brief from up to 20 frames (`fitFrames` keeps them within 15 MB) and the transcript; open = one `oss-reference-brief` job (Gemma 4 E4B, the first 30 s). A link is fetched through `fetchRemote`. The brief is written in this process when the series is next read (`seriesView`), and Generate / Next episode hold a one-process claim, so repeated clicks make one series | `/api/content-factory/series[/id[/generate \| /episodes \| /read]]`, `/api/content-factory/{estimate,claude}`; `POST /api/faceless/episodes` takes 30–300 s on a channel whose settings carry a brief | `components/content-factory/*` (`home.tsx`, `series-view.tsx`, `parts.tsx`, `hooks.ts`); the series page is a record page with a real 404 (`series` in `record-pages.ts` / `records.ts`) |
-| **Image to 3D** (`/image-to-3d`; round 4 part 3: five modes and Rig & animate) | `lib/av/model3d.ts`: the modes (From an image, From several images, From text, Pick an object, Splat: `MODEL3D_MODES`), the models per mode and engine, the default first (`MODELS_3D`; Pick an object has no open model, rigging is Meshy on fal only), the sides of a multi-view model (`VIEW_SIDES`: the front is needed; left and right are the object's own), `model3dBlocker`, `model3dRequest` (the sides go in `params.extra.views`), `stillPromptFor3d`, what a card shows (`model3dView`, `splatFormatOf`, `stillOf`: the still a text-to-3D model was built from), `CLOUD_NOTICES` ("Built with DINOv3" for TripoSplat and TRELLIS.2 on fal too), 30 curated Meshy animations in 6 groups (`ANIMATION_PRESETS`; the dialog starts on Casual walk, and any id up to 696 can be typed) and `rigRequest` | ordinary generations; the open text route is `createStillTo3d` (see Pipelines); the extra formats and previews are stored (`persistArtifacts`) | `POST /api/generations` (and `?preview=1` for the price line before a run); `?mode=` and `?model=` pick the mode and model (⌘K opens every 3D model and Meshy Rigging here) | `app/(studio)/image-to-3d/page.tsx` (an async server component: each open model's licence line, read from the manifest in a `"use cache"` function), `components/model3d/*`: `model3d-studio.tsx` (the mode radio group, the side slots, the price), `model-card.tsx` (a splat shows its orbit video or cut-out and a .spz / .ply download, since Fuobe doesn't draw splats; a rigged model plays its animation), `rig-dialog.tsx`, `hooks.ts`. The Library viewer (`ModelViewer` in `result-media.tsx`) never loads model-viewer for a splat |
++| **Image to 3D** (`/image-to-3d`; round 4 part 3: five modes and Rig & animate) | `lib/av/model3d.ts`: the modes (From an image, From several images, From text, Pick an object, Splat: `MODEL3D_MODES`), the models per mode and engine, the default first (`MODELS_3D`; From an image opens on Pixal3D, `oss-pixal3d` on `image-to-3d-pixal3d`, with TRELLIS.2 as the fallback; Pick an object has no open model, rigging is Meshy on fal only), the sides of a multi-view model (`VIEW_SIDES`: the front is needed; left and right are the object's own), `model3dBlocker`, `model3dRequest` (the sides go in `params.extra.views`), `viewerGlb` (the web GLB when there is one), `stillPromptFor3d`, what a card shows (`model3dView`, `splatFormatOf`, `stillOf`: the still a text-to-3D model was built from), `CLOUD_NOTICES` ("Built with DINOv3" for TripoSplat and TRELLIS.2 on fal too), 30 curated Meshy animations in 6 groups (`ANIMATION_PRESETS`; the dialog starts on Casual walk, and any id up to 696 can be typed) and `rigRequest` | ordinary generations; the open text route is `createStillTo3d` (see Pipelines); the extra formats and previews are stored (`persistArtifacts`). `src/server/model3d-finish.ts` finishes the first GLB of an open image-to-3D job in two steps, each a child process: `finishModel` before the job succeeds (`scripts/model3d/finish-glb.mjs` with glTF Transform, meshoptimizer and sharp: a roughness floor by material read from the metallic channel, the pivot at the bottom centre, meshopt geometry and WebP textures at 2048, in `meta.web`; the raw GLB stays the download), then `startTurntable` after it (`scripts/model3d/render-turntable.mjs`: `<model-viewer>` in headless Chromium on SwiftShader, CPU only, 96 frames at 24 fps on a studio backdrop, encoded by ffmpeg, plus a poster), one at a time at below-normal priority; `meta.finish.turntable` is queued, rendering (with progress), done, skipped (no Chromium or ffmpeg: the page records one in the browser) or failed, and a restart picks up the queued ones. A failure keeps what was made | `POST /api/generations` (and `?preview=1` for the price line before a run); `?mode=` and `?model=` pick the mode and model (⌘K opens every 3D model and Meshy Rigging here) | `app/(studio)/image-to-3d/page.tsx` (an async server component: each open model's licence line, read from the manifest in a `"use cache"` function), `components/model3d/*`: `model3d-studio.tsx` (the mode radio group, the side slots, the price), `model-card.tsx` (cards play the turntable and never load a GLB; a splat shows its orbit video or cut-out and a .spz / .ply download, since Fuobe doesn't draw splats; a rigged model plays its animation), `model-viewer.ts` (the viewer's setup: the same-origin meshopt decoder `public/vendor/meshopt_decoder.js`), `turntable.ts` and `webm.ts` (the browser's own turntable when the server can't: 96 frames at 24 fps through WebCodecs), `rig-dialog.tsx`, `hooks.ts`. The Library viewer (`ModelViewer` in `result-media.tsx`) never loads model-viewer for a splat |
+ | **Translate & dub, Transcribe, Captions, Trim, Katana, Virality** | `lib/av/*.ts` as plain data: `dub.ts` (one-shot and step plans, takes, timeline; since round 4 the cloud step plan splits the soundtrack with Demucs, lowers each background stem by 3 dB with fal's loudnorm, as the open route lowers its background stem, and mixes the new voice over them with compose; a failed split leaves a voice-only dub), `captions.ts` (burner capabilities), `cue-edit.ts`, `katana.ts` (cuts, `stepsToRedo`; since round 4 part 4 the motion step offers `fuobe-genjutsu-motion` on both engines instead of Higgsfield's Genjutsu, and `RETIRED_MOTION_MODELS` maps saved jobs' old ids; since round 4 part 5 it keeps only `oss-wan22-animate`, and `currentMotionModel` sends other retired ids through `currentModelId`), `frames.ts`, `timeline.ts`, `virality.ts`, `languages.ts`; Audio → Transcribe is a composer studio (`TRANSCRIBE_STUDIO`) with a spoken-language picker (`src/lib/speech-languages.ts`, sent as `params.sourceLanguage`) | `dub.ts` and `katana.ts` keep generation ids per step in `dub_sessions` / `katana_jobs` (`retryKatana`, `rerunKatana`); deleting stops unfinished steps | `/api/dub[/id[/voice]]` (`?preview=1` prices), `/api/katana[/id[/retry]]` | `components/{dub,captions,katana,virality,av}/*`; Trim and Ad Multiplier use the shared `video-trimmer.tsx`. Hub tool modes: `ModeSwitchStudio` has a `TOOLS` map (`audio/translate`, `audio/loop`, `audio/join`, `video-tools/remove-object`, `video-tools/captions`, `video-tools/trim`) |
+ | **Remove object** (`/video-tools/remove-object`) | `catalog/remove-object.ts`: the erasers per engine and way of pointing (`ERASERS`, `erasersFor`, `chooseEraser`: Type it, Click it, Paint it, and VOID for "Shadows and reflections too"), `targetPhrase` (words → SAM 3.1's target), `klingPrompt`, pieces and windows (above), `planRemoval`, `joinWithSound`, the SAM 3.1 mask preview (`planMaskPreview`); since round 4 part 4 the open "H3 Person Removal" eraser for a named person (`oss-h3-person-remove`, `planPersonRemoval`: see Fuobe Originals; Wan VACE stays the default) | `remove-object.ts`: `estimateRemoval`, `createRemoval` (one `createPipeline`: feature `remove-object`, its steps `remove-object-step`), `createRemovalPreview` (`remove-object-preview`); Kling O3 edit and LTX clean-plate prices are set here (`EDIT_USD_PER_SECOND`, `MEGAPIXEL_USD`). No table: history is the feed | `/api/remove-object[/estimate \| /preview]`; a repeated `requestId` gets the first run (`once()`) | `components/remove-object/*`: `frame-stage.tsx` (the first frame decoded in the browser, click points or paint), `video-compare.tsx` (before / after wipe) |
+ | **Genjutsu** (`/genjutsu`, `?mode=character`) | `catalog/genjutsu.ts`: modes Motion transfer, Character swap (round 4 part 4), Object swap, Restyle, Insert; the models per engine (`MAKERS`, `chooseMaker`: since round 4 part 4 the mode's Fuobe Original first, then other open weights, then partners; the alternatives include SCAIL-2, Wan Motion, Wan 2.2 Animate Replace, H3 Max Recast, Kling O3 and P-Video Replace in the cloud and H3 Character Swap · Relay 2.0 on the GPU; no Higgsfield model; see Fuobe Originals), `LEGACY_MAKERS` (since round 4 part 5 built from `REPLACED_BY`), list prices (`MAKER_USD`), `swapTarget`, `makerPrompt`, `planGenjutsu` (reuses Remove object's pieces, windows and `joinWithSound`; Restyle runs Shorts' planner with `keepShape`, or in the cloud the Original's own plan; Character swap is `planCharacterSwap` with `catalog/character-swap.ts`; every step names its engine), Copy / Paste setup codes (`encodeSetup` / `decodeSetup`, `gj1.` + base64url JSON, `/api/files/` URLs only; old codes open the replacing Original) | `genjutsu.ts`: `estimateGenjutsu` (since round 4 part 4 with each model's `source`, the anchors, the Character swap's limits and the GPU it was tested on), `createGenjutsu` (one `createPipeline`: `genjutsu`, `genjutsu-step`), `characterSwitches` (the Character swap's settings for the chosen model, with notes), `describeCharacter`, `transcribeClip`; `mixProblem` refuses a run that would mix paid and demo steps before anything starts. No table | `/api/genjutsu[/estimate]` (`once()` on `requestId`; since round 4 part 4 mode `character` with a `character` object and the part's `cuts`, and look kind `soul` instead of `higgsfield`), `POST /api/genjutsu/describe` and `/transcribe` (round 4 part 4) | `components/genjutsu/*` (`genjutsu-studio.tsx` with source badges and licence lines in the picker, `character-panel.tsx`, `look-picker.tsx` with Fuobe Soul's 139 looks, `use-cuts.ts`, `setup-code.tsx`); "Use in Genjutsu" / "Animate with Genjutsu" result actions; `StudioConfig.related` links from Motion control (to the Character swap) and Edit video; since round 4 part 5 the Character swap's "Open in Character Swap Studio" (`CharacterFacts`) makes a studio project on the same engine with the clip and the character's picture and description (`openInStudio`, `studioHandOff`), and is a plain link to `/character-swap` before a clip is loaded |
+ | **Character Swap Studio** (`/character-swap`, `/character-swap/[id]`; round 4 part 5) | `catalog/swap-studio.ts`: Akatz Labs' H3 Character Swap workbench for whole clips (`docs/research/openjutsu-6.md` §4.2) as one project document (`SwapProject`: one character, a picture and a description, and up to 20 clips of .mp4, .mov, .mkv, .webm or .avi, each at most 3,592 frames at 24 fps, 149.66 s, and 200 MB; `SWAP_STUDIO`). A clip holds its cuts and shots (`shotsFromCuts`; each shot Replace character or Keep original), its transcript and voices; a shot holds who to swap, mask versions (`MaskVersion`: Track shot or Update frame, made and approved on one engine), anchor variants and segments (`applyLayout`: 5, 10 or 15 s layouts, split, merge, moved boundaries; each segment Starts fresh or Continues previous, with its own words, speaker, prompt, seed and anchor). A take is frozen as queued (`freezeTake`: settings, who, anchor, mask, history), waits for the takes it continues from (`planQueue`, `dependencies`) and carries its review (favourite, Keep / Maybe / Skip, notes; `exportDecisions`); `masterKeep` is how many last frames a GPU take's master keeps for the next segment; `assemblyPieces` lays the chosen takes over the timeline, kept shots as filmed, and names out-of-date takes (`stale`) instead of refusing them; also `maskMemoryProblem` and `studioHandOff`. `swap-studio-plan.ts`: every job as `PlanStep`s per engine (`STUDIO_MODELS`): the GPU's 24 fps copy (`planNormalize`, `oss-fit-clip`) or the cloud's browser copy of a clip the page can't play (`planPreview`, fal `scale-video`); words (`planTranscribe`: `oss-qwen3-asr` or `scribe-v2`); masks (`planMask`: `oss-h3-person-mask`, or fal's SAM 3.1 video with `frame_index`, for review only; `cloudMaskCut`); anchors (`planAnchor`: Qwen-Image-Edit 2511, or GPT Image 2.5 Sunburst or Nano Banana Pro); a take (`planSegmentTake`: on the GPU one `video-swap` on `oss-h3-swap-segment` with the approved mask, the anchor and the previous take's master as history; in the cloud the segment cut with `trim-video`, the previous take's last frame (`extract-frame`), `fuobe-character-swap` on whole seconds (`cloudCallSeconds`, 5–15) and a `fit` trim back to the segment); `frozenTakePlan`; and the assembly (`planAssembly`: on the GPU every piece fitted at 24 fps, `oss-join-encoded` up to 100 a join, `oss-mux`; in the cloud pieces cut, scaled to one size with `scale-video` (`cloudFilmSize`), joined with `join-clips` up to 24 a join at `target_fps` 24, then `merge-audio-video` with the clip's sound or silence). `swap-studio-edit.ts`: `applyEdit`, the page's edits (refused while a shot's takes run: `shotBusy`, `EditError`). `src/lib/av/scene-cuts.ts`: Detect edits' maths (FFmpeg's scene score at 0.32; a coarse 64 px pass at 0.18, then a fine pass at the clip's width, up to 1280 px). `src/lib/swap-studio-graphs.ts`: the per-job graph rewrites (see Providers) | `swap-studio.ts`: projects in `swap_projects`, changed in one synchronous read-modify-write (`mutate`; `revision`, `waiting`). Every job is a `createPipeline` (helper feature `swap-studio-step`; the assembled clip is `swap-studio` and lands in the Library). Reading a project (`advanceProject`: the view, the estimate and the decisions) fills in finished jobs and launches waiting takes, which can be paid fal calls; `ensureSwapStudioRunner`, started by `src/instrumentation.ts`, does the same every 3 s for projects with `waiting > 0`, with the page closed too, in every Fuobe server on the same data folder. `queueTakes` checks and prices every take first (`price`: no demo and real steps mixed); `mustOffer` and `loraFor` apply Settings → Models & licences (the GPU refuses to run without the Turbo LoRA and runs without a switched-off swap LoRA, with a note; fal's route needs a swap LoRA); `editProject` stops the jobs an edit leaves nothing pointing at; `estimateProject` prices segments, shots, the project, masks, anchors, words and the assembly (Sunburst anchors are billed by tokens and left out, as is a cloud browser copy, billed by compute seconds); `studioNotes`, `decisions` | `GET` / `POST /api/swap-studio/projects`; `GET` / `PATCH` / `DELETE …/[id]`; `POST …/[id]/clips`, `/prepare`, `/transcribe`, `/masks`, `/anchors`, `/queue` (mode `segment`, `from` or `all`), `/stop`, `/takes/stop`, `/assemble`; `GET …/[id]/estimate`, `/decisions` (the Export decisions JSON) | `components/swap-studio/*`: `home.tsx` (the projects; New project on your GPU or the cloud), `workbench.tsx` with seven stages (Shots, Words, Who to swap, Scene anchors, Segments, Takes & review, Assemble; `stage-*.tsx`), `use-scene-cuts.ts` (Detect edits in the browser), `hooks.ts` (`openInStudio`); the Finish stage (a clean background plate, cut-outs) shows as not available (`FINISH_UNAVAILABLE`). Checked: unit and API tests (`swap-studio`, `swap-studio-edit`, `swap-studio-api` with the demo provider on both engines, `comfy-swap-studio` through the real provider on the library graphs, `avi-probe`) and a browser check of the whole flow in demo mode on the cloud engine (`tests/e2e/character-swap-studio.mjs`); nothing has run on a GPU or with a fal key |
+ | **Upscale hub: FPS Boost, SDR to HDR, Export** (`/upscale/fps`, `/upscale/hdr`, `/upscale/export`) | composer studios `FPS_BOOST_STUDIO`, `SDR_TO_HDR_STUDIO`, `VIDEO_EXPORT_STUDIO` (`StudioConfig.comfyOnly`: Export runs on ComfyUI only and says so); `lib/av/fps.ts` (`fpsPlan`: interpolate by m, keep every n-th frame), `upscale.ts` (`upscaleTier`, `upscaleFactorFor`: a target size, as a factor of the clip's shorter edge for APIs that take one), `formats.ts` (`FORMAT_INFO`), `video-finish.ts` (open export values, HDR colour space, passes, the whole-clip RAM budget) | ordinary generations; on submit the input clip's header fills `sourceSize` / `sourceFps` / `sourceDuration`, and an upscale tier that wouldn't enlarge the clip moves up (or is refused when picked) | `POST /api/media/probe` (a stored clip's length, size, fps and sound, from its header); `GET /api/status` reports ComfyUI's `ramBytes` | the composer's clip-facts line, format picker and no-ComfyUI notice; `VideoFileCard` in `result-media.tsx` for ProRes / FFV1 and clips the browser can't play; "Download EXR frames (.zip)" |
+ | **Audio hub: Loop / extend, Join** (`/audio/loop`, `/audio/join`) | `lib/av/audio-tools.ts` (`planLoop`, `planJoin`: up to 600 s, 2–10 clips; the open engine crossfades in one job, the cloud chains `join-audio` calls of whole plays and hard cuts), `lib/av/crossfade.ts` (`fadeCurveWav`, `crossfadeProblem`, cloud play counts) | `audio-tools.ts`: each clip's length read from its own header, the plan priced step by step, one `createPipeline` run | `POST /api/audio-tools` (`?preview=1` plans and prices) | `components/audio-tools/*`; any audio result gets "Loop / extend" |
+ | **Video studio · Frames mode** (`/video`) | `catalog/keyframes.ts` (above); `framesRequest` and the strip helpers in `src/lib/composer.ts` | cloud: FLUX 3 Max's keyframes route; start + end frame models get the first and last frame; open: `createKeyframeFilm` (Pipelines; since round 4 part 3 Fuobe DoP films keyframes this way, on the GPU only) | `POST /api/generations` with op `keyframes` and `params.keyframeTimes` | `StudioConfig.frames` on `VIDEO_STUDIO`; `components/studio/frames-strip.tsx` (up to 10 stills on a time ruler, keyboard-movable markers) |
+ | **Assist** (`/assist`, `/assist/skills`, `/assist/memory`, `/assist/projects/[id]`, since round 4 part 4 `/assist/scheduled`) | `lib/assist.ts`: SKILL.md parsing (`parseSkillMd`, `toSkillMd`; since round 4 the Agent Skills frontmatter, with Fuobe's own fields under `metadata`, and the old layout still read), slash helpers, modes, `planRunnable`, `ASSIST_SUGGESTIONS`; `lib/assist-studios.ts` (a studio call's words → a Shorts preset, a Faceless style, a dub language); since round 4 part 4 `lib/assist-schedule.ts` (rules, time zones, the cap) and `lib/assist-connectors.ts` (URL checks and masking) | `server/skills.ts` (built-ins from `skills/` or `FUOBE_SKILLS_DIR`, user skills and toggles in SQLite, `.md` / `.zip` / `.skill` import via `assist/unzip.ts`), `assist/projects.ts` (sources fetched safely; PDFs read by `assist/pdf.ts` with unpdf), `assist/docx.ts` (Word text, used by the Explainer), `assist/memory.ts`, `assist/context.ts`, `assist/studio-tools.ts`, `assist/studio-routes.ts` (the studio tools' adapters, below); since round 4 part 4 `assist/schedules.ts` and `assist/connectors.ts` (see Assist agent) | `/api/assist/**`; since round 4 part 4 `/api/assist/schedules[/scheduleId[/run]]` and `/api/assist/connectors[/connectorId]` | `components/assist/*`, `assist-view.tsx`; "Open in <Studio>" cards for studio jobs; since round 4 part 4 `schedule-dialog.tsx` (from a chat's Schedule button), `scheduled-view.tsx` (the Scheduled page and each project's Scheduled tab), `connectors-settings.tsx` (Settings → Assist · connectors) and connector tool calls in the transcript |
## ComfyUI workflow library (`workflows/comfyui/`, `scripts/comfy/`)
- `manifest.json` lists 115 workflows, all `validated: true`, each with its **bindings** (canonical key → node id + input), outputs (with `stem` and `role`), defaults, limits, required model files with download URLs and sizes, custom node packs, VRAM, licence, notes, `autoDownloads`, and since round 3 `expand` (`captions` or `timeline`: the provider rewrites the graph per request) and `worker: "isolated"`. The pipeline in `scripts/comfy/` exports the official templates through the real ComfyUI frontend (`app.graphToPrompt()`), applies documented transforms (`library.spec.mjs`, `lib/graph.mjs`), builds hand-written API graphs from `hand-built/*.json`, and validates every graph with `POST /prompt` against a live ComfyUI using zero-byte placeholder models.
-`manifest.json` lists 150 workflows, 145 of them `validated: true` (the five H3 graphs of round 4 parts 4 and 5 are `validated: false`, below), each with its **bindings** (canonical key → node id + input), outputs (with `stem` and `role`), defaults, limits, required model files with download URLs and sizes, custom node packs, VRAM, licence, notes, `autoDownloads`, and since round 3 `expand` (`captions` or `timeline`: the provider rewrites the graph per request) and `worker: "isolated"`. Round 4 adds `expand: "videos"` / `"audios"` (joins, one loader per clip), model files marked `optional` (FILM beside RIFE; the Workflows page leaves them out of the missing count), and output roles `scene`, `depth`, `mask`, `cutout`, `matte`, `preview`, `frames`, `frame`, `lines`, `splat` and `brief` (the graphs with `frame`, `lines` and `brief` got their models in round 4 part 2, for Layers' OCR and Content Factory, and the `splat` graph in round 4 part 3, for Image to 3D; round 4 part 5 adds `master`, Character Swap Studio's lossless take). The pipeline in `scripts/comfy/` exports the official templates through the real ComfyUI frontend (`app.graphToPrompt()`), applies documented transforms (`library.spec.mjs`, `lib/graph.mjs`), builds hand-written API graphs from `hand-built/*.json`, and validates every graph with `POST /prompt` against a live ComfyUI using zero-byte placeholder models.
++`manifest.json` lists 151 workflows, 146 of them `validated: true` (the five H3 graphs of round 4 parts 4 and 5 are `validated: false`, below), each with its **bindings** (canonical key → node id + input), outputs (with `stem` and `role`), defaults, limits, required model files with download URLs and sizes, custom node packs, VRAM, licence, notes, `autoDownloads`, and since round 3 `expand` (`captions` or `timeline`: the provider rewrites the graph per request) and `worker: "isolated"`. Round 4 adds `expand: "videos"` / `"audios"` (joins, one loader per clip), model files marked `optional` (FILM beside RIFE; the Workflows page leaves them out of the missing count), and output roles `scene`, `depth`, `mask`, `cutout`, `matte`, `preview`, `frames`, `frame`, `lines`, `splat` and `brief` (the graphs with `frame`, `lines` and `brief` got their models in round 4 part 2, for Layers' OCR and Content Factory, and the `splat` graph in round 4 part 3, for Image to 3D; round 4 part 5 adds `master`, Character Swap Studio's lossless take). The pipeline in `scripts/comfy/` exports the official templates through the real ComfyUI frontend (`app.graphToPrompt()`), applies documented transforms (`library.spec.mjs`, `lib/graph.mjs`), builds hand-written API graphs from `hand-built/*.json`, and validates every graph with `POST /prompt` against a live ComfyUI using zero-byte placeholder models.
+
+ Round 3 added 42 workflows (73 → 115), all hand-built: the 29 graphs of `comfyui-oss-3` (layers, style references, palette, segments and restyle, Mixed Media, SFX, dub preparation, ASR captions, translation, lip re-sync, 3D, try-on, grids, Soul Cast) plus Fuobe's own `video-mux-audio-replace`, `captions-burnin` (chunked, constant memory) and `selftest-meta-batch`; then `frame-extract`, `v2a-hunyuan-foley`, `product-shot-qwen-edit-2509`, `audio-timeline` and `video-concat-sound{1,2}-{2,3,4}`. `lipsync-latentsync16` and `sfx-thinksound` are **isolated-worker** workflows: their packs change process-wide state or pin old packages, so `scripts/comfy/install-isolated-worker.sh` sets up a second ComfyUI with its own code copy, base directory, `HOME` and virtualenv, sharing the main install's models read-only through `extra_model_paths.yaml` (port 8189). Since round 4 Fuobe routes them there itself (Settings → Isolated worker URL; see Providers). `install-comfyui.sh` installs 15 packs at pinned commits (round 4 added ComfyUI-ToSVG for VTracer). Since round 4 part 4 it also installs the non-commercial ComfyUI-Whisper (and `openai-whisper`) unless `NC_PACKS=0` (before, only with `NC_PACKS=1`), and Akatz Labs' GPL-3.0 `h3_character_swap` pack, a sparse checkout of one folder of their H3 Character Swap tool at a pinned commit (`H3_PACK=0` skips it; it needs `ffmpeg` and `ffprobe` on PATH, and the script warns when they're missing); H3 Relay 2.0 (`h3-relay`, GPL-3.0) registers its own HTTP routes when it loads, so it is opt-in (`H3_RELAY=1`). A failed fetch warns instead of stopping the install. The manifest names 19 packs in all (17 before round 4 part 4).
+
+ Round 4 added 24 hand-built workflows (115 → 139). Eighteen came first: object removal on Wan 2.1 VACE 14B by name (`video-inpaint-wan-vace`) or by a painted mask (`video-inpaint-wan-vace-painted`, which hands its last tracked mask to the next window), VOID on CogVideoX-5B (`video-erase-void`), VACE swap and insert with a reference image (`video-swap-wan-vace`, `video-insert-wan-vace`), a Ken Burns move over a still (`kenburns-still`), audio loop and join with crossfades (`audio-loop-crossfade`, `audio-join-crossfade`), ProRes / H.265 10-bit / FFV1 and EXR export (`video-export-pro`, `video-export-exr`), `video-sdr-to-hdr`, a MoGe 2 whole-scene mesh (`scene-mesh-moge`), a TripoSplat splat (`image-to-splat-triposplat`), OCR text lines (`ocr-lines-qwen35`), a Gemma 4 reference-video brief (`reference-brief-gemma4`), `still-to-clip`, a logo end card (`video-append-endcard`) and VTracer (`image-vectorize-vtracer`). `wan21-vace-14b-ref2v` swapped the template's CC-BY-NC CausVid LoRA for the Apache-2.0 lightx2v LoRA. Six more finish video in passes or join without re-encoding: `interpolate-rife-fps`, `upscale-video-esrgan-chunked`, `upscale-video-seedvr2-chunked`, `video-export-pro-chunked`, `video-sdr-to-hdr-exr` and `video-concat-encoded`. The chunked graphs use VideoHelperSuite's batch manager, which the provider tags per job. The models moved off `interpolate-rife`, `upscale-video-seedvr2`, `upscale-video-esrgan` and `video-export-pro`, which stay in the library unused. Round 4 part 2 adds no workflow (still 139) but gives four of them a catalog model: `ocr-lines-qwen35` (Layers), `reference-brief-gemma4` (Content Factory), `still-to-clip` and `video-append-endcard` (the Click to Ad end card).
+
+ Round 4 part 3 adds 6 hand-built workflows (139 → 145), all core nodes except `video-fit-clip` (VideoHelperSuite, already in the set of packs, so still 17): `z-image-turbo-i2i` (Fuobe Soul's image to image; the Z-Image Turbo files already listed; ~12 GB VRAM; a new `megapixels` binding key), `ltx23-i2v-lora`, `ltx23-flf2v-lora` and `ltx23-t2v-lora` (Fuobe DoP · LTX, from the official `video_ltx2_3_flf2v` template: LTX-2.3 22B distilled fp8, 29.53 GB, with the 9.45 GB Gemma 3 text encoder; LoRAs after the checkpoint loader; silent; 32 GB VRAM; LTX-2 Community License and the Gemma terms), `image-to-3d-trellis2-multiview` (TRELLIS.2 Multi-view, from the official `3d_pixal3d_multi_views` template: one upload per side, `pixal3d_multiview_int8_convrot` 5.58 GB, the field of view measured on the front photo by MoGe 2, 0.66 GB; `fovX` sets it, 0 = estimate; 16 GB VRAM, not checked) and `video-fit-clip` (the Canvas concatenator: VHS loader in 64-frame passes, centre crop, 30 fps, no model). `image-to-3d-trellis2` changes only its licence text: like the multi-view graph and TripoSplat, it encodes with DINOv3, so it names the DINOv3 License and its "Built with DINOv3" notice. `object_info.subset.json` gains five core node classes (271 → 276). `image-to-splat-triposplat` now has a catalog model (`oss-triposplat`); `ltx23-t2v-lora` has none yet, and the four graphs the models moved off in round 4 stay unused.
- Round 3 added 42 workflows (73 → 115), all hand-built: the 29 graphs of `comfyui-oss-3` (layers, style references, palette, segments and restyle, Mixed Media, SFX, dub preparation, ASR captions, translation, lip re-sync, 3D, try-on, grids, Soul Cast) plus Fuobe's own `video-mux-audio-replace`, `captions-burnin` (chunked, constant memory) and `selftest-meta-batch`; then `frame-extract`, `v2a-hunyuan-foley`, `product-shot-qwen-edit-2509`, `audio-timeline` and `video-concat-sound{1,2}-{2,3,4}`. `lipsync-latentsync16` and `sfx-thinksound` are **isolated-worker** workflows: their packs change process-wide state or pin old packages, so `scripts/comfy/install-isolated-worker.sh` sets up a second ComfyUI with its own code copy, base directory, `HOME` and virtualenv, sharing the main install's models read-only through `extra_model_paths.yaml` (port 8189). `install-comfyui.sh` installs 14 packs at pinned commits; `NC_PACKS=1` adds the non-commercial ComfyUI-Whisper.
+ Round 4 part 4 adds 3 hand-built workflows (145 → 148) for Genjutsu's Character swap and Remove object: `video-character-swap-h3` (capability `video-character-swap`: Openjutsu's graph, from Akatz Labs' H3 Character Swap graph, with a Video Slice for the part; pack `h3_character_swap`, used unpatched), `video-character-swap-h3-relay` (H3 Relay 2.0's example graph, no anchor; pack `h3-relay`) and `video-person-remove-h3-relay` (capability `remove-object`: H3 Relay's Person Removal with the Person Remover V1 LoRA, 22-frame windows; pack `h3-relay`). Their model files are pinned to Hugging Face revisions per workflow (`spec.modelUrls`): MiniMax H3 Ref2VA INT8 (20.97 GB), the Qwen3-VL 32B NVFP4 text encoder (15.69 GB), the H3 video VAE (5.21 GB) and audio VAE (0.61 GB), SAM 3.1 (1.75 GB, already listed), the FL2V Turbo 8-step LoRA (1.96 GB) and the swap or remover LoRA (0.16 GB each): about 45 GB of new files. `vramGb` is 24 for each (with offloading and 64–128 GB of RAM; 48 GB+ of VRAM advised for 768p). `scripts/comfy/build-library.mjs` learns `spec.packs` / `PACK_CLASSES` (a declared pack's node classes aren't lint errors when the pack isn't installed), `spec.modelUrls` and the new binding keys (`quality`, `selection`, `subjectIndex`, `positiveCoords` / `negativeCoords`, `audioGuide`, `useMask`, `windowFrames`, `historyFrames`); `object_info.subset.json` gains the core node classes the H3 graphs use. `captions-whisper-burnin` changes only its notes. Workflows → Copy install commands gives `git clone …/tree/<commit>/…` lines for the two H3 packs, which git can't clone: install them with the script.
- ## Training (`src/server/training.ts`)
+ Round 4 part 5 adds 2 hand-built workflows (148 → 150) for Character Swap Studio, on the `h3-relay` pack (pinned at `e2a7665`, installed with `H3_RELAY=1`) and files the library already pins, so no new node pack or model download: `video-character-swap-h3-segment` (capability `video-character-swap`, also on VideoHelperSuite: one H3 Relay 2.0 pass with the approved mask, an anchor and the previous take's FFV1 master as history; it saves the segment and a `master`; at most 30 s or 703 frames; `vramGb` 24) and `video-mask-h3-relay` (capability `person-mask`: SAM 3.1 finds the person on any frame of a shot from words, a selection or clicks, follows them and is spliced into the version it corrects; role `matte`; at most 150 s or 3,592 frames; `vramGb` 6). Each graph carries every branch a job can use, and the provider drops or adds branches per job (see Providers). `scripts/comfy/build-library.mjs` learns 8 binding keys (`historyVideo`, `historyStart`, `historyLength`, `keyFrame`, `spanFrames`, `tailStart`, `tailFrames`, `prevMask`).
- A `trainings` row per job, polled by the same runner. Higgsfield Soul ID returns a reference id stored on the element; fal's Z-Image trainer gets a zipped dataset with captions and returns a LoRA URL; AI-Toolkit gets a dataset folder and a job through its UI's job API, and the finished LoRA is copied into `COMFYUI_LORAS_DIR`. A style element (moodboards) uses the style preset (`aiToolkitJob({ kind: "style" })`, captions "<trigger> style", 1500 steps). Failed fal jobs (4xx, `FAILED`), a missing AI-Toolkit job, 8 h without a result and uploads cut off by a restart fail the training and settle the element back to ready.
+ `validated: true` means a live ComfyUI accepted the graph through `POST /prompt`. Graphs that need no model weights also ran on a CPU ComfyUI; the heavy graphs the round-4 tools use (Wan VACE, VOID, Wan Animate 2, chunked SeedVR2, Wan 2.2 keyframe clips, the Qwen-Image-Edit re-render) have not run on a GPU. Nor have the graphs round 4 part 2 wires in that need weights (OvisOCR3, the Gemma 4 brief, FLUX.1 Fill [dev], the Soul Cast sheet and Qwen-Image-Edit 2511 for the AI Influencer builder), or any graph with LoRAs. `video-append-endcard` needs no weights and ran twice on a CPU ComfyUI during development (an ad with a sound track and one without); those runs aren't in the test suite. Round 4 part 3: all six new graphs and the rebuilt `image-to-3d-trellis2` were accepted by a live CPU ComfyUI 0.41; none has run on a GPU. `video-fit-clip` with `video-concat-encoded` ran end to end on that CPU ComfyUI on PR #10's final code (`tests/e2e/comfyui-canvas-concat.mjs`: three clips with different sizes, frame rates and sound cut, framed to 9:16 at 30 fps and joined, sound only where kept). The multi-view graph's MoGe step ran on the CPU during development (`scripts/comfy/README.md`). Round 4 part 4: the three H3 graphs were built and sent to the CPU ComfyUI, which answered `missing_node_type` because their packs aren't installed there; they are recorded `validated: false` with that `validationError` (and in `scripts/comfy/validation-state.json`), the Workflows page shows them as unverified, and `tests/comfy-library-4.test.ts` allows exactly these three. None has loaded in a ComfyUI or run on a GPU. On PR #12's code a live CPU ComfyUI 0.41 accepts 141 of the 148 workflows; the other seven need packs that server doesn't have (`sfx-thinksound`, `captions-whisper-burnin`, `lipsync-latentsync16`, `image-vectorize-vtracer` and the three H3 graphs). Round 4 part 5: the two new graphs got the same `missing_node_type` answer (H3 Relay's nodes) and are recorded `validated: false`; `tests/comfy-library-4.test.ts` now allows these five. On PR #13's code the live CPU ComfyUI 0.41 accepts 141 of the 150 workflows; the other nine are the same four, the three H3 graphs of part 4 and the two new ones. The new graphs' per-job rewrites are tested through the real provider on the library files (`tests/comfy-swap-studio.test.ts`), but neither has loaded in a ComfyUI with H3 Relay or run on a GPU. The Canvas concatenator's live run (`tests/e2e/comfyui-canvas-concat.mjs`) passed on its first try on PR #13's code, where PR #12's needed re-runs because a busy ComfyUI was taken for an unreachable one.
+
+ ## Training: Fuobe Soul ID (`src/lib/catalog/training.ts`, `src/server/training.ts`)
+
+ A `trainings` row per job, polled by the same runner. Since round 4 part 4 (O3, Fuobe Soul ID) a training makes a LoRA for a **family**: a base and every model on it, on both engines (`TRAINING_FAMILIES`): Z-Image Turbo (Fuobe Soul and Soul Cinema, plain Z-Image Turbo), Qwen-Image 2512 (Fuobe Soul HD, Qwen-Image), FLUX.1 [dev] and Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 4B, FLUX.2 [klein] 9B and Krea 2 (the last three families' LoRAs run only in the cloud, on the hosted LoRA models). There are 13 **targets** (`TRAINING_TARGETS`):
+
+ - **fal** (8): the trainer endpoint with a zip of `001.jpg` + `001.txt` caption pairs uploaded to fal storage (`falTrainingInput`, `falQueueUrl`), priced before the run as steps × the trainer's price per step (`trainers.generated.ts`): Z-Image Turbo 2,000 steps ≈ $1.70 (characters) and Z-Image style 1,500 steps ≈ $3.39 (looks), Qwen-Image 2512 ≈ $1.50, FLUX portrait ≈ $6.00 (characters only), FLUX.2 [dev] ≈ $6.40 (asks for ComfyUI-named weights), klein 4B ≈ $5.00, klein 9B ≈ $4.30, Krea 2 ≈ $3.00. The LoRA comes back in the trainer's own output field (`trainedLoraUrl`). It is usable at once from fal's URL; Fuobe's own copy downloads in the background (`keepInBackground` → `keepTrainedLora`, `meta.keep` pending / kept / failed, restarted after a restart, never retried after a failure), and the fal URL is recorded as a mirror (`recordTrainedMirror`).
+ - **AI-Toolkit** (5, on the user's GPU, through its job API at the AI-Toolkit URL setting): Z-Image Turbo (with ostris's training adapter), Qwen-Image 2512, FLUX.1 [dev], FLUX.2 [dev] and klein 4B (`AITK_MODELS`; AI-Toolkit downloads the base weights itself, the FLUX [dev] ones gated). `aiToolkitJob` writes the config: rank 32 for 20+ photos, else 16; a style element uses the style preset (captions "<trigger> style", 1,500 steps). The finished LoRA is kept by Fuobe and copied into ComfyUI's LoRA folder. A LoRA trained by an AI-Toolkit on another machine has to be copied by hand. `GET /api/elements/[id]/training-kit?family=` downloads a kit for one of the five bases (config, dataset, README with the licence line) to train anywhere.
+
+ **Rules.** A character trains only with consent: `POST /api/elements/[id]/trainings` takes `{target, consent}`, refuses a character without `consent: true` and stores `consentAt` in `trainings.meta_json`; styles don't need it. 5 to 80 photos (`SOUL_ID_PHOTOS`; elements hold up to 80). `GET …/trainings` lists the targets for the element's kind with each one's blocker, price, licence (information) and whether it would run as a demo. With no fal key or AI-Toolkit URL and Demo mode on "auto" (the default) or "on", a training runs as an 8-second demo (provider `demo`, `demoTraining`) that trains nothing and never replaces a real LoRA of the family; Settings → Engine mode still refuses. Trainings aren't under Settings → Models & licences.
+
+ **The LoRA on the element.** `addIdentity` puts the trained LoRA on the element with its family, target, engine and file (`fuobe/<handle>-<training id>.safetensors`, one name per training), replacing only that family's earlier LoRA, so Fuobe Soul and Soul HD LoRAs live side by side. An @mention brings it to every model of the family on either engine (`identityFor` in `applyMentions`), scaled by the character strength; a trained element's studio opens on its family's lead model. Fuobe keeps every trained file in `<data dir>/loras` (`TRAINED_DIR`), copies it into ComfyUI's folder before an open run and sends it once to fal or Replicate for a cloud run (`LoraRef.own`; see LoRAs). `POST /api/elements/[id]/lora` attaches a LoRA trained elsewhere to a `family`. LoRAs from before O3 map to a family through their model id.
+
+ **Higgsfield retired.** Higgsfield Soul ID stopped being a target in round 4 part 4, and an old Soul ID now shows "Older Soul ID" with "Retrain for Fuobe Soul". Since round 4 part 5 a training still queued or running on one of its two targets (`soul-id-v2`, `soul-id-cinema`: `TRAINING_REPLACED_BY` in `replaced.ts`) is failed by target on the next poll, with `retiredTraining()`'s message ("… was retired: train the character again for Fuobe Soul on the same photos"), and `pollOne` gives that message for those targets too; nothing retrains by itself. An old Soul ID's `custom_reference_id` reaches no model any more: `applyMentions` no longer sends it.
+
+ **Moodboards and photo runs.** "Train as a look…" trains a moodboard's style element on either engine (`trainMoodboard`); the board then runs as Fuobe Soul's own look (`own-style`). Photodump and Fashion run a character with a Soul ID on Fuobe Soul (see Studios). The Image studio gains the five hosted LoRA models (see Catalog).
+
+ Failed fal jobs (4xx, `FAILED`), a missing AI-Toolkit job, 8 h without a result and uploads cut off by a restart fail the training and settle the element back to ready. Checked: tests against a fake network (request bodies, AI-Toolkit configs, every open model of each family taking the LoRA, the background copy and restart, the demo rule, the retired Higgsfield training) and the Train dialog in a demo-mode browser. No real training has run: likeness is unmeasured, the new AI-Toolkit configs are unchecked, and whether fal's FLUX.2 LoRA endpoint reads the ComfyUI-named files is unknown. No Replicate trainers. Keeping Fuobe's own copy of a trained LoRA (`src/server/loras.ts`, `src/server/training.ts`) gave `next build` three Turbopack "dynamic filesystem access" tracing warnings. Since round 4 part 5 those file calls carry `/*turbopackIgnore: true*/` (as `db.ts`, `auth.ts`, `storage.ts` and `skills.ts` already did), and the About & licences page spells out the two files it reads (`package.json` and the workflow manifest), so `next build` prints none of the four warnings PR #12's build had.
## Assist agent (`src/server/assist/`)
- A manual tool-use loop over Claude (adaptive thinking with `block_binding` drop-block, betas `thinking-binding-controls-2026-08-01` and `server-side-fallback-2026-07-01` (not for Haiku), top-level `cache_control` and two cached system blocks, streamed with `client.beta.messages.stream(...).finalMessage()`, `max_tokens` 32k or 64k at Extra / Max effort). Modes: **Free** (a local model, or the offline planner), **Smart** (Claude, needs a key), **Manual** (pick claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 or claude-fable-5-1 and the effort, or one of the local server's models). `resolveAgent()` picks one per chat. The agent ids are `claude`, `local` and `offline`; chats and browsers that saved the old `ollama` read as `local` (`normalizeAgent()`, the `ModeChoice` schema).
-A manual tool-use loop over Claude (adaptive thinking with `block_binding` drop-block, betas `thinking-binding-controls-2026-08-01` and `server-side-fallback-2026-07-01` (not for Haiku), and since round 4 part 4 `mcp-client-2025-11-20` when connectors ride along, top-level `cache_control` and two cached system blocks, streamed with `client.beta.messages.stream(...).finalMessage()`, `max_tokens` 32k or 64k at Extra / Max effort). Modes: **Free** (Ollama, or the offline planner), **Smart** (Claude, needs a key), **Manual** (pick claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 or claude-fable-5-1 and the effort). `resolveAgent()` picks one per chat.
++A manual tool-use loop over Claude (adaptive thinking with `block_binding` drop-block, betas `thinking-binding-controls-2026-08-01` and `server-side-fallback-2026-07-01` (not for Haiku), and since round 4 part 4 `mcp-client-2025-11-20` when connectors ride along, top-level `cache_control` and two cached system blocks, streamed with `client.beta.messages.stream(...).finalMessage()`, `max_tokens` 32k or 64k at Extra / Max effort). Modes: **Free** (a local model, or the offline planner), **Smart** (Claude, needs a key), **Manual** (pick claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 or claude-fable-5-1 and the effort, or one of the local server's models). `resolveAgent()` picks one per chat. The agent ids are `claude`, `local` and `offline`; chats and browsers that saved the old `ollama` read as `local` (`normalizeAgent()`, the `ModeChoice` schema).
- **Context.** Each chat's context (date, engine, approval mode, project, sources, memory, skills index, active skills) is built once and frozen in `assist_thread_state`; later changes arrive as role `system` "Context update" messages, saved only after a reply succeeds, so preserved thinking stays valid.
- - **Tools** (`tools.ts`, `context-tools.ts`, `studio-tools.ts`): `search_models` (kinds image, video, audio, text, model3d), `list_elements`, `list_recent`, `check_generations` (text inline, meta, images attached), `generate` (with `after`: the call becomes one `createPipeline`; not `strict`, zod-validated), `create_storyboard` (the only `strict` tool), `list_skills`, `load_skill`, `remember` (asks first), `read_source`, the studio tools `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, and `katana`. Gated calls stop the loop with an approval card priced by `previewGeneration`; `PlannedJob.atomic` marks a pipeline's steps and `planRunnable()` keeps Run off while any step has an error. `answerApproval` claims the thread before its first await.
- - **Studio tools** resolve through `STUDIO_ROUTES`, a registry a studio module can fill; while an entry is empty (all of them today) the tool builds the same job as a `createPipeline` of catalog models on either engine.
- - History is stored append-only exactly as the API returned it; local images are kept as URLs and converted to base64 per request. The same loop runs on a local model's tool calling (`local` in `agent.ts`: the history through `toChatMessages()`, the answer back as `tool_use` blocks; a picked model the server doesn't list gives way to its default), or with no LLM on a rule-based planner (still → animate, N-shot films, N portraits, translations, skill hints, "remember that…").
+ - **Tools** (`tools.ts`, `context-tools.ts`, `studio-tools.ts`): `search_models` (kinds image, video, audio, text, model3d; since round 4 part 3 it says an Original runs on both engines and names the 139 looks; since round 4 part 4 it lists only models Settings → Models & licences offers, and the offline planner's default picks fall back with `offeredDefault`), `list_elements` (since round 4 part 4 a trained element counts only LoRAs some run can use), `list_recent`, `check_generations` (text inline, meta, images attached), `generate` (with `after`: the call becomes one `createPipeline`; not `strict`, zod-validated; since round 4 part 3 a job takes `look` and `engine`, and a job without an engine follows the user's; since round 4 part 5 a job naming a retired model or operation runs on its replacement, `toRequest` through `currentRequest`, without the note), `create_storyboard` (the only `strict` tool), `list_skills`, `load_skill`, `remember` (asks first), `read_source`, the studio tools `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, and `katana`. Gated calls stop the loop with an approval card priced by `previewGeneration`; `PlannedJob.atomic` marks a pipeline's steps and `planRunnable()` keeps Run off while any step has an error. `answerApproval` claims the thread before its first await.
+ - **Studio tools** resolve through `STUDIO_ROUTES`, which `assist/studio-routes.ts` fills (since round 4) for `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads` and `add_captions`. Each adapter prices the job with the studio's own estimate and starts it through the studio's server module, so it opens as a Layers project, a Shorts session, a dub to review, a Faceless episode (in an "Assist" channel made once) or an Ads Studio batch, or in the Captions editor. Since round 4 part 5 `create_ads` always plans Fuobe's ads (copy and a visual, each in 1:1, 4:5 and 9:16). A call the studio can't take runs as a `createPipeline` of catalog models in the Library, and the card, the result and the chat say why. `planFor()` returns where the job opens (`JobPlace`: studio and page), for the approval card and MCP's `estimate_job`. Genjutsu, Character Swap Studio, Remove object, Content Factory, the AI Influencer builder and Layers' Inpaint, Enhancer and Save as element have no Assist or MCP tool yet.
-- History is stored append-only exactly as the API returned it; local images are kept as URLs and converted to base64 per request. The same loop runs on Ollama's tool calling, or with no LLM on a rule-based planner (still → animate, N-shot films, N takes numbered on their tiles and then "animate 2" for the one picked, translations, skill hints, "remember that…").
++- History is stored append-only exactly as the API returned it; local images are kept as URLs and converted to base64 per request. The same loop runs on a local model's tool calling (`local` in `agent.ts`: the history through `toChatMessages()`, the answer back as `tool_use` blocks; a picked model the server doesn't list gives way to its default), or with no LLM on a rule-based planner (still → animate, N-shot films, N takes numbered on their tiles and then "animate 2" for the one picked, translations, skill hints, "remember that…").
+ - **Scheduled tasks** (round 4 part 4; `src/lib/assist-schedule.ts`, `src/server/assist/schedules.ts`). A task is a prompt (with files, a project, an engine and the chat's mode) that runs as a new chat on the server's clock. Rules (`ScheduleRule`): daily at a time, weekly on some days, every N real hours (1–168), or once, in an IANA time zone. `nextRun` works out the next time with `zonedToUtc` / `wallClock`, pure, so the dialog's "Next run" preview and the server agree: a time a spring-forward skips runs as much later as the clocks jumped, a time a fall-back repeats runs once, and every N hours ignores the clocks. The sweep (`ensureScheduleRunner`, started at boot by `src/instrumentation.ts`, and when a task is made) runs every 30 s, the first one 5 s after boot, and starts up to 10 due tasks, each claimed by a compare-and-set on `next_run_at`, so two sweeps never start the same run and a run missed while the server was off happens once. A run time that passes while the previous run is still going is skipped and recorded, not queued. Every process on the same database sweeps, dev servers included. Each run is a new chat ("<task> · <time>") in the task's project; its context says it is a scheduled run nobody watches (`scheduleLine`), so the model doesn't ask questions and ends with a summary. **Approval modes:** Ask first (the default: the plan waits as an approval card, and nothing is generated until it is approved, though a Claude run still uses the Anthropic key to plan) or auto-run within a cap per run (`cap_usd`, default $2, at most $500): `step()` prices each gated call with `planFor()` and `spendOf` (demo jobs $0, an unknown price always waits), `withinCap` lets it start while the run's `spent_usd` stays under the cap, and a plan over it waits. Claude's own tokens and connector side effects aren't counted. `POST /api/assist/schedules/[id]/run` (Run now) answers 202 with the chat, 409 only while the last run is still going, 422 with the reason when paused or failed. Deleting a project pauses its tasks, with the reason shown (`deleteProject` in `assist/projects.ts`). The UI: the Schedule button in a chat's header, `/assist/scheduled` and each project's Scheduled tab.
-- **Connectors** (round 4 part 4; `src/lib/assist-connectors.ts`, `src/server/assist/connectors.ts`). Custom remote MCP servers in Settings → Assist · connectors (`#assist-connectors`; `/api/assist/connectors[/id]`): name, URL, optional token and optional allowed tools. `checkConnectorUrl` takes https, plain http only for localhost unless `FUOBE_ALLOW_PRIVATE_URLS=1`, no user name or password in the URL, at most 2,048 characters, and warns that a local or private address needs a public tunnel. Tokens and URLs are stored in plain text in SQLite like the other keys; the browser gets them masked (`maskToken`, `maskConnectorUrl`: the query and every path segment that isn't a short plain word hidden). Claude chats send them through the Messages API's MCP connector (beta `mcp-client-2025-11-20` beside the others): `mcpParams` gives one `mcp_servers` entry (URL, slug, `authorization_token`) and one `mcp_toolset` per enabled connector, and an allow-list turns the rest off (`default_config: {enabled: false}` plus `configs`). Anthropic's servers connect and call the tools inside the reply, so approval cards and the cap never see those calls; the context's `connectorsLine` tells the model to check in chat before posting, sending, creating, editing or deleting in an Ask-first chat. Every ordinary Claude chat gets every enabled connector (`assist_thread_state.connectors` defaults to 1); a scheduled run only when its task opts in (`assist_schedules.connectors`, off by default). History from a connector deleted or switched off is sent as text (`withoutMissingServers`); the stored history is unchanged. Ollama and the offline planner can't use connectors and say so once. The transcript lists each connector tool Claude used.
++- **Connectors** (round 4 part 4; `src/lib/assist-connectors.ts`, `src/server/assist/connectors.ts`). Custom remote MCP servers in Settings → Assist · connectors (`#assist-connectors`; `/api/assist/connectors[/id]`): name, URL, optional token and optional allowed tools. `checkConnectorUrl` takes https, plain http only for localhost unless `FUOBE_ALLOW_PRIVATE_URLS=1`, no user name or password in the URL, at most 2,048 characters, and warns that a local or private address needs a public tunnel. Tokens and URLs are stored in plain text in SQLite like the other keys; the browser gets them masked (`maskToken`, `maskConnectorUrl`: the query and every path segment that isn't a short plain word hidden). Claude chats send them through the Messages API's MCP connector (beta `mcp-client-2025-11-20` beside the others): `mcpParams` gives one `mcp_servers` entry (URL, slug, `authorization_token`) and one `mcp_toolset` per enabled connector, and an allow-list turns the rest off (`default_config: {enabled: false}` plus `configs`). Anthropic's servers connect and call the tools inside the reply, so approval cards and the cap never see those calls; the context's `connectorsLine` tells the model to check in chat before posting, sending, creating, editing or deleting in an Ask-first chat. Every ordinary Claude chat gets every enabled connector (`assist_thread_state.connectors` defaults to 1); a scheduled run only when its task opts in (`assist_schedules.connectors`, off by default). History from a connector deleted or switched off is sent as text (`withoutMissingServers`); the stored history is unchanged. A local model and the offline planner can't use connectors and say so once. The transcript lists each connector tool Claude used.
## MCP server (`src/server/mcp.ts`, `/api/mcp`)
- Fuobe's MCP server (version 1.1.0; protocol revisions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05) over streamable HTTP, stateless with JSON responses: `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list` (empty), `prompts/list`, `prompts/get`. The tools are Assist's (shared `executeTool`) with read-only hints, plus `estimate_cost` (a generate call priced with `previewGeneration`) and `estimate_job` (a studio tool's plan). The prompts are the enabled skills. Requests from a foreign `Origin` are refused; the proxy applies the same sign-in rules as the REST API.
+ Fuobe's MCP server (version 1.2.0; protocol revisions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05) over streamable HTTP, stateless with JSON responses: `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list` (empty), `prompts/list`, `prompts/get`. The tools are Assist's (shared `executeTool`, so since round 4 part 4 `search_models` lists only models that are on and a run of one switched off is refused, naming the switch) with read-only hints, plus `estimate_cost` (a generate call priced with `previewGeneration`) and `estimate_job` (a studio tool's plan, with the studio and page it opens in). A studio tool's result carries its job's `href` on this server. `mcp.ts` imports `assist/studio-routes.ts` itself, so the studio adapters are always loaded. The prompts are the enabled skills. Requests from a foreign `Origin` are refused; the proxy applies the same sign-in rules as the REST API. Content Factory's Generate in Claude (round 4 part 2) sends nothing itself: its dialog shows the `claude mcp add --transport http fuobe <origin>/api/mcp` line (`mcpCommand`, with a Bearer header when a password is set) and the prompt `POST /api/content-factory/claude` writes for the existing `faceless_episode` tool, on the engine this server's MCP runs on (Settings → Engine mode). That tool takes up to 8 scenes a call, so a longer episode comes out in parts. Assist's scheduled tasks can't be made through it (or the CLI) yet. It is Fuobe's own server; the remote MCP servers Claude chats can use are Assist's connectors (above).
+
+ ## Command line (`bin/`)
+
+ `fuobe` (round 4) is a client of a Fuobe server, not part of it: plain Node 20+ with no dependencies, `bin/fuobe.mjs` (the `bin` entry in `package.json`) with the logic in `bin/lib/*.mjs` so tests drive it without a terminal. It finds the server and token in `--url` / `--token`, then `FUOBE_URL` / `FUOBE_TOKEN`, then the file `fuobe login` saves (`~/.config/fuobe/config.json`, written 0600; the saved token goes only to the server it was saved for). It uses the same REST API as the browser: `GET /api/models` (`src/app/api/models/route.ts` with `src/lib/model-list.ts`: what this install can run, with `runs` real / demo / refused worked out as `chooseRoute` would, and the studios' default picks; since round 4 part 4 only models Settings → Models & licences offers, each with its routes that are on, and a default switched off falls back to the next one that is on), `POST /api/generations` and its `?preview=1` (model, operation, jobs, outputs and cost, nothing created; since round 4 part 3 `fuobe generate --engine` also picks an Original's engine, `--look` and `--look-strength` send a Fuobe Soul look, and `fuobe models` shows an Original as `open+cloud`), `POST /api/uploads`, `GET /api/generations[/<id>]`, the Assist skills routes, and `POST /api/mcp` for the studio tools (`fuobe tool`). Skills follow the Agent Skills format, so other agents can install them (`.agents/skills/fuobe` teaches one to drive Fuobe through MCP or the CLI). Since round 4 part 2, `fuobe eval <command>` is a `passthrough` command (it takes its arguments as they are): it imports the evaluation harness (`scripts/eval/eval.mjs`) from the checkout next to the CLI and refuses to run without one; the harness finds its server and token the same way, so a saved token still goes only to the server it was saved for. Commands, options and exit codes: [`docs/cli.md`](cli.md) (it doesn't list `--look` and `--look-strength` yet; `fuobe generate --help` does).
+
+ ## Evaluation harness (`scripts/eval/`)
+
+ Round 4 part 2. A developer tool, not part of the app: it measures the Fuobe Originals (Fuobe's own open-weight versions of Higgsfield's in-house models) so that a recipe (models, LoRAs, settings) becomes a default only after it has been measured, and then only in a commit a person reviews. Like the CLI it is a client of a running Fuobe, in plain Node: `scripts/eval/eval.mjs` (`run`, `report`, `review`, `compare`, `promote`, `covers`, `history`, `validate`, `setup`, `trash`; `pnpm eval:<command>` or `fuobe eval <command>`) with the logic in `scripts/eval/lib/*.mjs`. The full guide is [`scripts/eval/README.md`](../scripts/eval/README.md).
+
+ - **Cases** (`cases/*.json`, checked against `case.schema.json`, which `lib/schema.mjs` writes): one suite per Original (`selftest`, `soul`, `soul-id`, `dop`, `genjutsu`, `mixed-media`, `shorts`, `speak`, `cinema`, and since round 4 part 3 `soul-cinema`, `soul-hex` and `dop-mix`) with model targets per engine (`demo`, `open`, `cloud`), variants (`recipe`, `prompt-only`, `half-strength`, a cloud `partner`…) and inputs from `local/` (git-ignored: photos, clips, voices) or the small synthetic `fixtures/` for demo runs. `soul.json`, `soul-cinema.json`, `soul-hex.json`, `dop.json` and `dop-mix.json` are generated by `gen-cases.mjs` from `higgsfield-image-studios.json` (look ids) and `fuobe-originals-recipes-5.json` (recipes, LoRAs, Soul Cinema's recipe, the motion map); `eval:validate` fails when they're out of date. Since round 4 part 3 every request names its `engine` (an Original runs on both), the `original` variant runs the shipped Originals (Graffiti on `fuobe-soul-hd`), a variant can add fixed `words` after the prompt and its own `submit` route (`{{request}}` in a route body is the job's own request: Soul HEX's lock goes through `POST /api/palettes/lock`), and a recipe's Hugging Face LoRA is fetched at the commit the research pinned (`pinnedLora` in `lib/recipes.mjs`). Round 4 part 4 extends `cinema.json` (Fuobe Cinema on both engines, equal to `planCinema`'s plans), `genjutsu.json` (7 cases with the Originals and Character swap, and a synthetic 6 s `fixtures/walk-6s.mp4` so demo runs meet the 5 s minimum) and `soul-id.json` (5 cases: character, cinema, hd, flux and look, each trained, half-strength and with the photos as references); a training can name its `kind` (character or style).
+ - **Runner** (`lib/run.mjs`, `plan.mjs`, `recipes.mjs`): every job goes through Fuobe's REST API (`/api/generations` with the recipe's `loras`, `/api/uploads`, `/api/elements`, and studio routes such as `/api/genjutsu` and `/api/mixed-media`) with the feature `eval`, a helper the Library hides. The harness holds no prices: each job is priced by the server's preview or estimate, a cloud job reserves its price under the spend cap (`--max-usd`, default $5), and an unpriced one is skipped unless `--allow-unpriced`. Round 4 part 5 drops its Higgsfield skip (`HIGGSFIELD_SKIP`, `viaHiggsfield`, and the one for Higgsfield training targets) with the provider. Since round 4 part 4 a character training sends `consent: true` only when the case says the person agreed, a training the server would run as a demo (or can't start) is skipped or stopped, so "trained" results always come from a real LoRA, and an element takes up to 80 photos. On the open engine it also reads ComfyUI, read-only (`/system_stats`, `/history`, `/object_info/LoraLoader`). Each run is a folder under the git-ignored `scripts/eval/results/` (`run.json`, `jobs.jsonl`, the outputs, `metrics.json`, `summary.json`, `report.html`).
+ - **Metrics** (`metrics/fuobe_metrics`, Python) run in their own venv, which `pnpm eval:setup` makes with uv from pinned requirements (CPU torch by default); `lib/metrics.mjs` starts `python -m fuobe_metrics.score` from that venv, else through `uv run`. CLIP score, the LAION aesthetic predictor, style against reference images (CLIP or DINOv2), identity (AuraFace with the YuNet face detector, installed with `--identity`; since round 4 part 4 the non-commercial buffalo_l runs when asked for, unless `--commercial-only`), temporal drift and warp error, a lip-sync proxy, shot continuity and, since round 4 part 3, palette fit (`paletteFit`, `paletteCover`: how close the pixels are to the palette the request sent, in Lab); every weight is pinned to a Hugging Face revision and its licence is stored with the scores. Without Python, a run keeps its timing and cost.
-- **Report, review, compare, promote** (`report.mjs`, `review.mjs`, `compare.mjs`, `covers.mjs`): a contact sheet; a blind A/B page served on 127.0.0.1:4173 (ratings saved next to the run; the key to which side is which is never served); `compare` exits 1 when a guarded metric regresses; `promote` applies the promote rule (at least 3 results, metrics against every alternative, and at least 6 blind ratings of the case's pairs, or every pair when the review offered fewer, with 55 % of the non-tie ones for the candidate; since round 4 part 4 a licence is reported, and holds the recipe only with `--licence-hold`) and with `--record` writes its verdicts into `fuobe-originals-recipes-5.json` (`--apply-strengths` also lowers over-cooked LoRA strengths) as a diff to review; `covers` turns promoted renders into preset covers listed in `src/lib/preset-previews.generated.ts` (`--commercial-only` leaves out a render whose LoRAs can't be sold), which `previewFor` shows instead of the procedural preview.
++- **Report, review, compare, promote** (`report.mjs`, `review.mjs`, `compare.mjs`, `covers.mjs`): a contact sheet; a blind A/B page served on 127.0.0.1:4173 (ratings saved next to the run; the key to which side is which is never served); `compare` exits 1 when a guarded metric regresses; `promote` applies the promote rule (at least 3 results, metrics against every alternative, and at least 6 blind ratings of the case's pairs, or every pair when the review offered fewer, with 55 % of the non-tie ones for the candidate; since round 4 part 4 a licence is reported, and holds the recipe only with `--licence-hold`) and with `--record` writes its verdicts into `fuobe-originals-recipes-5.json` (`--apply-strengths` also lowers over-cooked LoRA strengths) as a diff to review; `covers` turns promoted renders into preset covers listed in `src/lib/preset-previews.generated.ts` (`--commercial-only` leaves out a render whose LoRAs can't be sold), which `previewFor` shows instead of the procedural preview; with `--from-masters <dir>` it takes rendered masters instead, one folder per preset id (`coversFromMasters`: a `clip.mp4` becomes a clip cover, else `start.png` a still one), merged so that only the ids it writes are replaced, and re-runnable (a cover newer than its master is kept).
+ - **Server seams** it relies on: `loras` on `POST /api/generations`, the preview's `route`, `prompt` and `loras {applied, dropped}` (`routeLoras`), and `providers` on the Genjutsu and Mixed Media estimates.
+
-Checked: the self-test ran on a CPU ComfyUI and scored 4 CPU-only jobs, demo runs pass, and the report and review pages are browser-tested (`tests/e2e/eval-review.mjs`). The Originals are in the app now, but none has been measured on a GPU or the cloud, no recipe has been promoted, and `preset-previews.generated.ts` is still empty.
++Checked: the self-test ran on a CPU ComfyUI and scored 4 CPU-only jobs, demo runs pass, and the report and review pages are browser-tested (`tests/e2e/eval-review.mjs`). The Originals are in the app now, but none has been measured on a GPU or the cloud, no recipe has been promoted, and `preset-previews.generated.ts` holds only the covers made from rendered masters (see UI → Galleries), none from a measured run.
## Storage (`src/server/db.ts`, `storage.ts`, `settings.ts`)
@@@ -224,19 -425,39 +440,39 @@@ SQLite (WAL). Migrations are an append-
| 13 | `faceless_channels`, `faceless_episodes` |
| 14 | `dub_sessions`, `katana_jobs` |
| 15 | `skills`, `skill_toggles`, `assist_projects`, `assist_project_sources`, `assist_memory`, `assist_thread_state` |
+ | 16 | Library: `folders.parent_id`, `folders.pinned_at`, `generations.pinned_at`, `generations.review` (nested folders, pins, review status) |
+ | 17 | `lora_mirrors` (every LoRA copy: a download into ComfyUI's folder or a mirror on fal / Replicate, with source, version, SHA256, size and licence snapshot) |
+ | 18 | `content_series` (a Content Factory series: the reference, its style brief, the planned episodes and settings; the episodes are Faceless episodes in the series' channel) |
+ | 19 | `shares` (round 4 part 4: a share link or published page; `id` is the token's first 12 characters, `token_hash` the SHA-256 of the whole token; kind, target, title, description, tags, layout, items, cover, `show_prompts`, `expires_at`, views) and index `shares_target` |
+ | 20 | `assist_schedules` (round 4 part 4: a scheduled task's prompt, files, project, rule and time zone, approval, `cap_usd`, `connectors`, engine, mode, paused, next and last run), `assist_connectors` (name, unique slug, URL, token, allowed tools, enabled), and on `assist_thread_state` `schedule_id`, `cap_usd`, `spent_usd` and `connectors` (default 1) |
+ | 21 | `swap_projects` (round 4 part 5: a Character Swap Studio project as one document, `data_json`, beside `name`, `engine`, `revision` and `waiting`, the takes queued behind earlier segments) and indexes `swap_projects_updated` and `swap_projects_waiting` (partial, `waiting > 0`) |
+ | 22 | no table (round 4 part 5, O7): deletes the saved Higgsfield key (`higgsfield.key`), turns a `cloud.provider` of `higgsfield` into `auto`, and marks Higgsfield ads `baked` (`ad_batches.route`, and `route` in `ad_creatives.meta_json` where that is valid JSON) |
- Settings (`src/server/settings.ts`) are typed and validated against allowed values; environment variables give the defaults, and a value saved in Settings wins over them (the password is the exception: `FUOBE_PASSWORD` can't be changed from Settings). Secrets are masked before reaching the browser. `engineMode` is enforced server-side; the client reads it from `/api/status`. Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` (content types include .txt / .srt / .vtt / .json / .glb / .aac) and are served by `/api/files/...` with HTTP range support. `FUOBE_DATA_DIR` moves everything.
+ Round 4 part 3 adds no migration. It changes what some existing columns hold: `canvases.graph_json` is written as `{pages: [{id, name, graph}]}` and a row saved before reads as page 1 (`readPages`) until it is saved again (an older build can't read a board after that save); `runs_json`'s node runs gain `out`, `rows` and `rowSigs`; `generations.request_json` keeps the engine a Fuobe Original ran on; and output meta gains `finished`, `original`, `grade`, `overlay` and `crop`, with `meta.formats` and `meta.preview` now stored as local files.
- ## UI (`src/components/`, `src/app/(studio)/`)
+ Round 4 part 4 adds migrations 19 and 20 (above); they only add tables and columns, so an older build can still open the database. Other new state uses existing places: the Models & licences switches are the settings row `models.access` (JSON); a training's `meta_json` holds its family, photo count, `consentAt`, file and `keep` (provider `demo` for a demo training); an element's LoRAs gain `family`, `target`, `own`, `demo` and `trainedAt` inside its JSON; generation requests can carry `chainSkipped` and `notice`. `ASSET_REFS` gains `assist_schedules.attachments_json`; `ASSET_FREE` gains `shares.tags_json`, `shares.items_json`, `assist_schedules.rule_json` and `mode_json`, and `assist_connectors.url` and `tools_json`.
+
+ Round 4 part 5 adds migrations 21 and 22 (above). 21 only adds a table, so an older build can still open the database; 22 changes stored data and can't be undone (the saved Higgsfield key is gone for good). Jobs and trainings still on Higgsfield aren't migrated: they fail on their next poll (see Retired models). `ASSET_REFS` gains `swap_projects.data_json` (the character picture, each clip and its copies, masks, anchors, takes and their masters).
- Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif headlines, pill composer). The sidebar (`app-sidebar.tsx`) remembers its rail and groups without making the layout dynamic (`SIDEBAR_STATE_SCRIPT` in `src/lib/nav.ts` runs before paint). Branded not-found and error pages, and `loading.tsx` skeletons on studio and gallery routes.
-Settings (`src/server/settings.ts`) are typed and validated against allowed values; environment variables give the defaults, and a value saved in Settings wins over them (the password is the exception: `FUOBE_PASSWORD` can't be changed from Settings). Secrets are masked before reaching the browser. `engineMode` is enforced server-side; the client reads it from `/api/status`. Round 4 adds `comfyIsolatedUrl` (`COMFYUI_ISOLATED_URL`, the isolated ComfyUI worker) and `onboarded` (key `onboarding.done`, no environment variable): `GET /api/status` sets it the first time something the engine mode generates with is connected, and putting the Get started guide away sets it too. `/api/status` also returns it, and ComfyUI's RAM as `providers.comfyui.ramBytes`. Round 4 part 2 adds `civitaiKey` (key `civitai.key`, `CIVITAI_API_KEY`, secret: it downloads civitai LoRAs and is never sent to fal or Replicate), and `comfyLorasDir` (`COMFYUI_LORAS_DIR`) is now also where LoRAs are downloaded before a ComfyUI run, so it must be ComfyUI's `models/loras` folder as this machine sees it, writable by Fuobe. Round 4 part 3 adds no setting and no environment variable, but those two matter more: Fuobe DoP's open runs download their preset's LoRAs before the job (the presets' open routes use 84 of the map's 99 files, 98 before round 4 part 4; 36 of the map's files are on civitai) and stop with a message without the folder or, for a civitai file, the key; only a Fuobe Soul look leaves an unreachable civitai LoRA out (see LoRAs). Round 4 part 4 adds no typed setting and no app environment variable: the Models & licences switches are one settings row (`models.access`, read and written by `src/server/model-access.ts`, edited at `/settings/models`); `FUOBE_TRUST_PROXY` now also keys the share-link throttle and `FUOBE_ALLOW_PRIVATE_URLS` also lets a connector URL use plain http beyond localhost; the install script gains `H3_PACK` (default 1), `H3_TOOL_REF`, `H3_RELAY` (default 0) and `H3_RELAY_REF`, and `NC_PACKS` now defaults to 1. The browser keeps the share links it made in localStorage (`fuobe.shareLinks`), since the server can't show a token again. Round 4 part 5 removes `higgsfieldKey` (`HIGGSFIELD_API_KEY`; `HF_KEY` and `HF_API_KEY` + `HF_API_SECRET` aren't read either) and the `higgsfield` value of `cloudProvider` (`FUOBE_CLOUD_PROVIDER` is `auto`, `fal` or `replicate`; a leftover value counts as `auto`, as any value outside the options does, and Settings refuses to save it), and adds no setting or environment variable: `REACH` and `COMFY_WAIT` are constants in the code. `withCandidates()` runs code as if typed values were saved (connection tests; see Security). Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` (content types include .txt / .srt / .vtt / .json / .glb / .aac, since round 4 .ply / .spz splats, .mkv, .exr and .zip, since round 4 part 3 .ksplat, and since round 4 part 5 .avi; a finished Fuobe Soul picture and the Canvas concatenator's silent WAVs are saved there too) and are served by `/api/files/...` with HTTP range support. `<data dir>/tmp` is a scratch folder on the same file system (`scratchDir()` in `storage.ts`), never served: EXR zips and downloaded result files are written there, then moved into `files/outputs` by `adoptFile`; a partial file is removed on failure. `<data dir>/loras` holds LoRA files downloaded only to mirror them to fal or Replicate, and since round 4 part 4 Fuobe's own copy of every trained Soul ID LoRA (`TRAINED_DIR`), so expect it to grow. `FUOBE_DATA_DIR` moves everything.
++Settings (`src/server/settings.ts`) are typed and validated against allowed values; environment variables give the defaults, and a value saved in Settings wins over them (the password is the exception: `FUOBE_PASSWORD` can't be changed from Settings). Secrets are masked before reaching the browser. `engineMode` is enforced server-side; the client reads it from `/api/status`. Round 4 adds `comfyIsolatedUrl` (`COMFYUI_ISOLATED_URL`, the isolated ComfyUI worker) and `onboarded` (key `onboarding.done`, no environment variable): `GET /api/status` sets it the first time something the engine mode generates with is connected, and putting the Get started guide away sets it too. `/api/status` also returns it, and ComfyUI's RAM as `providers.comfyui.ramBytes`. Round 4 part 2 adds `civitaiKey` (key `civitai.key`, `CIVITAI_API_KEY`, secret: it downloads civitai LoRAs and is never sent to fal or Replicate), and `comfyLorasDir` (`COMFYUI_LORAS_DIR`) is now also where LoRAs are downloaded before a ComfyUI run, so it must be ComfyUI's `models/loras` folder as this machine sees it, writable by Fuobe. Round 4 part 3 adds no setting and no environment variable, but those two matter more: Fuobe DoP's open runs download their preset's LoRAs before the job (the presets' open routes use 84 of the map's 99 files, 98 before round 4 part 4; 36 of the map's files are on civitai) and stop with a message without the folder or, for a civitai file, the key; only a Fuobe Soul look leaves an unreachable civitai LoRA out (see LoRAs). Round 4 part 4 adds no typed setting and no app environment variable: the Models & licences switches are one settings row (`models.access`, read and written by `src/server/model-access.ts`, edited at `/settings/models`); `FUOBE_TRUST_PROXY` now also keys the share-link throttle and `FUOBE_ALLOW_PRIVATE_URLS` also lets a connector URL use plain http beyond localhost; the install script gains `H3_PACK` (default 1), `H3_TOOL_REF`, `H3_RELAY` (default 0) and `H3_RELAY_REF`, and `NC_PACKS` now defaults to 1. The browser keeps the share links it made in localStorage (`fuobe.shareLinks`), since the server can't show a token again. Round 4 part 5 removes `higgsfieldKey` (`HIGGSFIELD_API_KEY`; `HF_KEY` and `HF_API_KEY` + `HF_API_SECRET` aren't read either) and the `higgsfield` value of `cloudProvider` (`FUOBE_CLOUD_PROVIDER` is `auto`, `fal` or `replicate`; a leftover value counts as `auto`, as any value outside the options does, and Settings refuses to save it), and adds no setting or environment variable: `REACH` and `COMFY_WAIT` are constants in the code. The local LLM servers (see Local LLM servers) add `llmProvider` (`FUOBE_LLM_PROVIDER`: auto, ollama, lmstudio, unsloth or custom), `lmstudioUrl`, `lmstudioModel` and `lmstudioToken` (`LMSTUDIO_URL`, `LMSTUDIO_MODEL`, `LMSTUDIO_API_TOKEN` or `LM_API_TOKEN`), `unslothUrl`, `unslothModel` and `unslothKey` (`UNSLOTH_URL`, `UNSLOTH_MODEL`, `UNSLOTH_API_KEY` or `UNSLOTH_STUDIO_AUTH_TOKEN`), `llmUrl`, `llmModel` and `llmKey` (`FUOBE_LLM_URL`, `FUOBE_LLM_MODEL`, `FUOBE_LLM_API_KEY`) and `llmContext` (`FUOBE_LLM_CONTEXT`, default 16384; `parseContext` also takes `16k`, and 0 leaves it to the server). A setting may name several environment variables, and the first one set wins (`envValue`). `enhanceProvider` (Settings → AI helper) takes `local`, and the old `ollama` still means it. `withCandidates()` runs code as if typed values were saved (connection tests; see Security). Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` (content types include .txt / .srt / .vtt / .json / .glb / .aac, since round 4 .ply / .spz splats, .mkv, .exr and .zip, since round 4 part 3 .ksplat, and since round 4 part 5 .avi; a finished Fuobe Soul picture and the Canvas concatenator's silent WAVs are saved there too) and are served by `/api/files/...` with HTTP range support. `<data dir>/tmp` is a scratch folder on the same file system (`scratchDir()` in `storage.ts`), never served: EXR zips and downloaded result files are written there, then moved into `files/outputs` by `adoptFile`; a partial file is removed on failure. `<data dir>/loras` holds LoRA files downloaded only to mirror them to fal or Replicate, and since round 4 part 4 Fuobe's own copy of every trained Soul ID LoRA (`TRAINED_DIR`), so expect it to grow. `FUOBE_DATA_DIR` moves everything.
+
+ ## UI (`src/components/`, `src/app/(studio)/`)
- - **Studio pages** render `<Studio config>` (`src/components/studio/studio.tsx`), a server component that passes `studioCatalog(config)` from `src/lib/studio-catalog.ts`: the studio's models without provider field maps. Inside, `CatalogProvider` / `useCatalog()` resolve models; `loadFullCatalog()` imports `@/lib/catalog` lazily for motions, effects, `?preset=` and unknown ids. Client components under `studio/` must not import `@/lib/catalog` or `@/lib/studios`. `StudioPage` renders the same tree in the static shell and after hydration; hand-off params merge into the draft with `mergeHandoff`. `StudioConfig` (`studio-context.tsx`) gained `pickerOps`, `anyOf`, `signature` and `extraModels`.
- - **Hubs** (Audio, Video tools, Upscale) have one prerendered path per mode (`src/lib/hubs.ts`, `ModeSwitchStudio` in `mode-switch-studio.tsx`, `[mode]/page.tsx`); old `?mode=` links redirect in `next.config.ts`.
- - **Composer** pieces: pure logic in `src/lib/composer.ts` (summary, blockers, `onImageChange`, `fitAttachments`, `firstMissingSlot`), `attachments.ts` (`useAttach`, `useUploadReaper`), `settings-panel.tsx`, `model-picker.tsx` (cmdk), `attach-menu.tsx`, `preset-chips.tsx` (lazy), `radio-keys.ts`.
- - **Galleries** get slim cards (`src/lib/preset-cards.ts`, built on the server by `toPresetCard()` in `preset-card-data.ts`). A preset with rendered media carries only its hash (from `src/lib/catalog/preview-media.generated.json`, which only `preset-card-data.ts` reads so that client chunks don't carry it; file names in `src/lib/preview-media.ts`): `preview-media.tsx` shows the AVIF/WebP poster and mounts the muted loop only while it plays. The others, and any card whose files don't load, get procedural previews (`preset-preview.tsx`, `move-glyphs.ts`). `preview-playback.ts` plays one at a time: hover after a short rest, on phones the centred card once scrolling stops (not with Save-Data or on 2G).
- - Stand-alone views: color grading (`color-grade-view.tsx`, `src/lib/grade.ts`), storyboard, elements + train dialog, library (`library-view.tsx` + `components/library/*`), Assist, and the studios above.
+ Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif headlines, pill composer). The sidebar (`app-sidebar.tsx`, rows in `nav-items.ts`) remembers its rail and groups without making the layout dynamic (`SIDEBAR_STATE_SCRIPT` in `src/lib/nav.ts` runs before paint); since round 4 its Studios and Engine groups start folded (`DEFAULT_NAV_CLOSED`) and a remembered choice wins. Branded not-found and error pages, and `loading.tsx` skeletons on studio and gallery routes (`skeletons.tsx`; `/marketing` has its own).
+
+ - **Shell (round 4).** "Skip to content" is the first Tab stop, the sidebar is a `<nav aria-label="Main">`, and each page has one `<main>`. Full-screen studios (`fullScreenStudio()` in `nav.ts`: a Cinema, Canvas or Layers project, and every Assist page) fold the sidebar to its icon rail without touching the remembered choice: only `SidebarShell` writes the sidebar cookie, and only when that choice changes (`persistOpen` on `SidebarProvider`). Phones get a header with the menu and Search on gallery and settings pages (`phone-bar.tsx`). `intent-link.tsx` prefetches a link on hover or focus instead of when it appears on screen (rows marked `eager` still prefetch on view). Shortcut labels show ⌘ on Apple devices and Ctrl elsewhere (`src/lib/keys.ts`). Every Copy button goes through `copyText` (`src/lib/clipboard.ts`), so copying works on plain-http LAN addresses.
+ - **Command palette** (`command-palette.tsx`, ⌘K / Ctrl+K, also the sidebar's Search row and the phone header's Search): pages, Settings sections, apps, camera motions, effects, models (filtered by engine mode, and since round 4 part 4 by Settings → Models & licences through the access summary) and recent creations, ranked with typo tolerance in `src/lib/command-search.ts`. The catalog part is `GET /api/search-index`, a static, prerendered slim index built by `paletteIndex()` in `src/lib/palette-index.ts` and fetched the first time the palette opens. `modelHref()` opens a model where it runs (a studio with `?model=`, a Video tools mode, Image to 3D, an app, Layers, Captions / Trim / Translate), else the Models page filtered by `?q=`; the round-4 tools (Remove object, Genjutsu, FPS Boost, SDR to HDR, Export, the 3D scene) aren't in its lists yet, so their models open the Models page. Since round 4 part 3 every Image to 3D model and Meshy Rigging open `/image-to-3d`, and a Fuobe Original is listed once with both engines. Since round 4 part 4 it also lists "Models & licences" (`/settings/models`) and "Assist connectors". It replaces `global-shortcuts.tsx` (⌘K used to go Home).
+ - **Getting started and connections.** `get-started.tsx` is the first-run guide under Home's composer and at the top of Settings (Use paid models, Use your GPU, Just try it), shown until `onboarded` is set (`showFirstRun`, `FIRST_RUN_SCRIPT` in `src/lib/connections.ts`). Every connection field in Settings is a `ConnectField` (`connect-field.tsx`): Save & test sends the typed value to `POST /api/providers/test` (`{provider, value | values, field}`; the old `{provider}` body still works) and saves it only when the test passes, with a "Save anyway" link. `settings-form.tsx` has a status strip with one chip per connection (`connectionSummary`); since round 4 part 2 it has a LoRAs section (`#loras`, `lora-settings.tsx`: the LoRA folder, the civitai key with Save & test, and the library with licences and Download buttons), which the command palette also lists. `/settings/about` (`licences-view.tsx`, `src/lib/licences.ts`) lists each open model's licence from the catalog and the workflow manifest, read at build time, and since round 4 part 4 links to Settings → Models & licences (`/settings/models`, `model-access-view.tsx`: the switches; see Models & licences). Round 4 part 4 also adds a Models & licences section and Assist · connectors (`#assist-connectors`, `components/assist/connectors-settings.tsx`) to `settings-form.tsx`. Round 4 part 5 drops the Higgsfield key field and chip and the "Higgsfield first" Preferred provider (`PROVIDER_SETTINGS`, `CLOUD_PROVIDERS` and `connectionSummary` in `src/lib/connections.ts`).
+ - **Studio pages** render `<Studio config>` (`src/components/studio/studio.tsx`), a server component that passes `studioCatalog(config)` from `src/lib/studio-catalog.ts`: the studio's models without provider field maps. Inside, `CatalogProvider` / `useCatalog()` resolve models; `loadFullCatalog()` imports `@/lib/catalog` lazily for motions, effects, `?preset=` and unknown ids. Client components under `studio/` must not import `@/lib/catalog` or `@/lib/studios`. `StudioPage` renders the same tree in the static shell and after hydration; hand-off params merge into the draft with `mergeHandoff`. `StudioConfig` (`studio-context.tsx`) gained `pickerOps`, `anyOf`, `signature` and `extraModels`, and in round 4 `frames` (Frames mode), `comfyOnly` (a tool that runs only on ComfyUI, with a note and an alternative) and `related` (a link under the hero). `HandoffSync` in `studio-page.tsx` also runs Home's Start: Home issues a one-time token (`issueStartToken` in `src/lib/composer.ts`, kept in sessionStorage) and opens the studio with `?prompt=…&go=<token>`; the studio submits once if `claimStartToken` accepts it, so a link from elsewhere can't start a run. A `?model=` that names the other engine's model switches the remembered engine; since round 4 part 3 it also survives the composer's swap of an untouched draft's default model when the engine is read after hydration (`followEngineDefault`: before, a link on the open engine landed on the studio's default model). Since round 4 part 5 a `?model=` naming a retired model opens on its replacement (`currentModelId`), and Reuse of a run on one migrates its request in the browser (`migrateRequest` without Director words) and toasts what changed; the composer's provider style chip (`ProviderPresetChip`, Higgsfield's live styles) is gone. The line under Home's composer prices what Start will run from the catalog (`startQuotes` in `src/lib/starter-prices.ts`, worded by `startLine` in `src/lib/connections.ts`).
+ - **Hubs** (Audio, Video tools, Upscale) have one prerendered path per mode (`src/lib/hubs.ts`, `ModeSwitchStudio` in `mode-switch-studio.tsx`, `[mode]/page.tsx`); old `?mode=` links redirect in `next.config.ts`, and an unknown mode is a real 404. Round 4 adds `/upscale/fps`, `/upscale/hdr`, `/upscale/export`, `/audio/transcribe`, `/audio/loop`, `/audio/join` and `/video-tools/remove-object`.
+ - **Composer** pieces: pure logic in `src/lib/composer.ts` (summary, blockers, `onImageChange`, `fitAttachments`, `firstMissingSlot`; since round 4 `blockerLine` for the phone's blocked-Generate line, `framesRequest` and the Frames strip helpers, the start token), `attachments.ts` (`useAttach`, `useUploadReaper`), `settings-panel.tsx`, `model-picker.tsx` (cmdk), `attach-menu.tsx`, `preset-chips.tsx` (lazy), `radio-keys.ts`, `frames-strip.tsx`, and since round 4 part 3 `look-chip.tsx` (lazy: Fuobe Soul's looks, a popover on desktop and a sheet on phones). Since round 4 part 3 the composer sends `engine` for a Fuobe Original, drops a look when the model changes to one without looks, moves to a motion's or effect's Original when one is picked, and follows a move across an engine switch (the pure helpers are in `src/lib/composer.ts`: see Fuobe Originals). Video finishing reads the attached clip's facts from `POST /api/media/probe` for its "24 → 60 fps · 5 s → 10 s" line and its prices.
+ - **Feed and results**: running tiles show elapsed time and, once progress has moved, time left (`use-now.ts`; `notePace` / `timeLeft` in `src/lib/format.ts`); the newest single result offers next steps (`nextSteps` in `output-actions.ts`); video tiles get a poster (`videoPoster`); ProRes, FFV1 and clips the browser can't decode show as a file card (`VideoFileCard` in `result-media.tsx`). Since round 4 part 2, `useCreateGeneration` (`src/lib/api.ts`) shows a run's `notes` (LoRAs left out, a length the API rounds) as a warning toast. Since round 4 part 3 every studio feed finishes Fuobe Soul pictures (`useSoulFinish`), the viewer's Details show a Look row and a Finish row, and a clip with `meta.grade` offers "Apply the … grade" first.
-- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`, `preview-playback.ts`); `previewFor` shows a real cover instead when `src/lib/preset-previews.generated.ts` lists one (written by the evaluation harness's `eval:covers`; empty so far).
++- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`); `previewFor` (`src/lib/preset-card-data.ts`) shows a real cover instead when `src/lib/preset-previews.generated.ts` lists one: a still cover is the card's picture as rendered (no tint, bleed, mirroring or move glyph), a clip cover is a muted `<video preload="none">` over its first-frame poster. Every entry records the run, engine, model and variant that made it. `preset-card-data.ts` is the only module that reads the manifest, and only the server gallery pages and the preset header (loaded on its own with `next/dynamic`) import it, so the manifest never ships in the shared client chunks (`tests/preset-covers.test.ts` checks the importers, and checks the real manifest against `public/previews`). Covers are served with a day's cache and a week of background revalidation, outside the sign-in proxy like `samples/`. The file is written by the evaluation harness's `eval:covers`, from a measured run's promoted renders or, with `--from-masters <dir>`, from rendered masters kept outside the repo (`coversFromMasters()` in `scripts/eval/lib/covers.mjs`; it replaces only the ids it writes, and skips an id whose cover another run made elsewhere unless `--replace`). Stills are 4:2:0 JPEGs of at most 768 px; a clip cover is at most 4 s and 512 px, and its last 6 frames are crossfaded into its first ones so the card's loop has no jump (a clip that already ends where it starts is only cut). The first covers come that way: 480 of the 487 app, motion and effect cards (474 stills from Ideogram 4 and 6 clips from MiniMax H3, all rendered in ComfyUI; run `comfyui-previews-2026-10`, in `public/previews/presets/`), while the other 7 keep their procedural preview. `preview-playback.ts` plays one card at a time: on hover after a short rest or on keyboard focus, on phones the centred card once scrolling stops, and not with Save-Data or on 2G (the preset header's autoplay too).
+ - **Sidebar** (round 4 part 2): Studios gains AI Influencer (`/influencer`) and Content Factory (`/content-factory`) in `nav-items.ts`. Round 4 part 5 adds Character Swap Studio (`/character-swap`, short label "Character swap") after Genjutsu.
+ - **Models page** (round 4 part 3): `ModelRow.engines` (`src/lib/model-rows.ts`) puts an Original under both the Cloud and Open source filters, with both engine icons, "Open source + cloud" (`enginesLabel`) and a "Free · $… / megapixel" price. Since round 4 part 4 models switched off leave the list (`models-table.tsx`), which says how many and links to Settings → Models & licences.
+ - **Sharing** (round 4 part 4): the studio layout (`src/app/(studio)/layout.tsx`) wraps every page in `ShareProvider`, so any result menu can open the Share dialog; the Library gains the Shared tab and Publish in its selection bar, whose phone version folds Like, Pin and Review into a ⋯ menu (see Share links). The public share page lives outside the `(studio)` group, without the studio's frame.
+ - Stand-alone views: color grading (`color-grade-view.tsx`, `src/lib/grade.ts`; since round 4 part 3 Invert and Solarize sliders, the Soul and DoP grade presets, and `?preset=` to open with a grade picked), storyboard, elements + train dialog (since round 4 part 4 `train-dialog.tsx`: the photo rules and tips, the consent tick for characters, the options by family with where each runs, price, time estimate and licence, Train / Retrain / Upgrade, the demo note, "Train anywhere" with the training kit and attaching a LoRA; element cards show a Soul ID, Training, Retrain or Demo badge; `moodboards/train-board.tsx` for "Train as a look…"), library (`library-view.tsx` + `components/library/*`), Assist, About & licences, and the studios above.
## Generators (`scripts/`)
- `pnpm gen:catalog` runs `gen-cloud-models.py`, `gen-higgsfield-models.py`, `gen-higgsfield-presets.py`, `gen-oss-loras.py` and the icon map. Each reads a research JSON in `docs/research/` and writes a `*.generated.ts` file; the catalog integrity tests catch broken references. `gen-preview-scenes.mjs` draws the gallery preview stills (`public/samples/previews/`), `gen-demo-3d.mjs` the demo GLB and turntable (needs ffmpeg). `build-previews.mjs --masters <dir>` turns rendered masters (kept outside the repo) into the preset cards' posters and loops in `public/previews/` plus their manifest (needs ffmpeg; unchanged masters are skipped).
-`pnpm gen:catalog` runs `gen-cloud-models.py`, `gen-studio-packs.py` (since round 4 part 5, in place of `gen-higgsfield-models.py` and `gen-higgsfield-presets.py`), `gen-oss-loras.py`, since round 4 part 2 `gen-lora-library.py` and `gen-influencer-options.py`, since round 4 part 3 `gen-soul-originals.py` and since round 4 part 4 `gen-trainers.py` (standard-library Python; `trainers.generated.ts` from the recipes JSON's trainers), then the icon map. Each reads a research JSON in `docs/research/` and writes a `*.generated.ts` file; the catalog integrity tests catch broken references, and `gen-lora-library.py` itself fails on a missing pin. Since round 4 part 3 `gen-oss-loras.py` (the map v2) and `gen-soul-originals.py` also exit 1 when the research breaks their recipe rules (since round 4 part 4 a licence-rule break is printed as a note instead, in `gen-lora-library.py` too, while data checks such as pins, hashes and names still fail), `gen-cloud-models.py` writes the Originals' cloud halves (`ORIGINAL_CLOUD`; 12 since round 4 part 4) and warns on a rule break (since round 4 part 4 no longer about an endpoint whose LoRAs are required), and rerunning them reproduces the committed files exactly. `fetch-lora-pins.py` and `fetch-hosted-schemas.py` refresh the research JSON from the network and aren't part of `gen:catalog` (`fetch-hosted-schemas.py --only <endpoint>` fetches one endpoint's schema; since round 4 part 4 `--trainers` reads the fal trainers' fields and outputs and `--base-only` the hosted base endpoints'; since round 4 part 5 `--partner` writes the partner routes in `partnerEndpoints`, Happy Horse 1.1's three fal routes); `scripts/eval/gen-cases.mjs` writes the evaluation harness's generated suites. The Higgsfield research files stay as research and history: `gen-studio-packs.py`, `gen-soul-originals.py`, `gen-influencer-options.py` and the evaluation harness's case generator still read them (and `gen-oss-loras.py` matches LoRAs by the `higgsfieldEquivalent` column of `comfyui-oss.json`). `gen-preview-scenes.mjs` draws the gallery preview stills (`public/samples/previews/`), `gen-demo-3d.mjs` the demo GLB and turntable (needs ffmpeg).
++`pnpm gen:catalog` runs `gen-cloud-models.py`, `gen-studio-packs.py` (since round 4 part 5, in place of `gen-higgsfield-models.py` and `gen-higgsfield-presets.py`), `gen-oss-loras.py`, since round 4 part 2 `gen-lora-library.py` and `gen-influencer-options.py`, since round 4 part 3 `gen-soul-originals.py` and since round 4 part 4 `gen-trainers.py` (standard-library Python; `trainers.generated.ts` from the recipes JSON's trainers), then the icon map. Each reads a research JSON in `docs/research/` and writes a `*.generated.ts` file; the catalog integrity tests catch broken references, and `gen-lora-library.py` itself fails on a missing pin. Since round 4 part 3 `gen-oss-loras.py` (the map v2) and `gen-soul-originals.py` also exit 1 when the research breaks their recipe rules (since round 4 part 4 a licence-rule break is printed as a note instead, in `gen-lora-library.py` too, while data checks such as pins, hashes and names still fail), `gen-cloud-models.py` writes the Originals' cloud halves (`ORIGINAL_CLOUD`; 12 since round 4 part 4) and warns on a rule break (since round 4 part 4 no longer about an endpoint whose LoRAs are required), and rerunning them reproduces the committed files exactly. `fetch-lora-pins.py` and `fetch-hosted-schemas.py` refresh the research JSON from the network and aren't part of `gen:catalog` (`fetch-hosted-schemas.py --only <endpoint>` fetches one endpoint's schema; since round 4 part 4 `--trainers` reads the fal trainers' fields and outputs and `--base-only` the hosted base endpoints'; since round 4 part 5 `--partner` writes the partner routes in `partnerEndpoints`, Happy Horse 1.1's three fal routes); `scripts/eval/gen-cases.mjs` writes the evaluation harness's generated suites. The Higgsfield research files stay as research and history: `gen-studio-packs.py`, `gen-soul-originals.py`, `gen-influencer-options.py` and the evaluation harness's case generator still read them (and `gen-oss-loras.py` matches LoRAs by the `higgsfieldEquivalent` column of `comfyui-oss.json`). `gen-preview-scenes.mjs` draws the gallery preview stills (`public/samples/previews/`), `gen-demo-3d.mjs` the demo GLB and turntable (needs ffmpeg). `pnpm eval:covers --from-masters <dir>` turns rendered masters into preset covers (see UI → Galleries). `scripts/model3d/finish-glb.mjs` and `render-turntable.mjs` aren't generators: they are the server's GLB finish and CPU turntable, which it runs as child processes (see Studios → Image to 3D), and they also run by hand.
diff --cc docs/STATUS.md
index 5b39aa15,72541f95..ef5dc067
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@@ -1,6 -1,6 +1,6 @@@
# Fuobe — project status
- _Last updated: 2026-10-21 (round 3). The research behind this is in [`docs/research/`](research/README.md); the Higgsfield inventory it is measured against is [`higgsfield-inventory.md`](research/higgsfield-inventory.md), deepened for round 3 by [`higgsfield-studios.md`](research/higgsfield-studios.md), [`higgsfield-image-studios.md`](research/higgsfield-image-studios.md) and [`higgsfield-marketing-agents.md`](research/higgsfield-marketing-agents.md)._
-_Last updated: 2026-10-28 (round 4, part 5). The research behind this is in [`docs/research/`](research/README.md); the Higgsfield inventory it is measured against is [`higgsfield-inventory.md`](research/higgsfield-inventory.md), deepened for round 3 by [`higgsfield-studios.md`](research/higgsfield-studios.md), [`higgsfield-image-studios.md`](research/higgsfield-image-studios.md) and [`higgsfield-marketing-agents.md`](research/higgsfield-marketing-agents.md), and brought up to date for round 4 by [`higgsfield-delta-4.md`](research/higgsfield-delta-4.md), with [`paid-model-apis-4.md`](research/paid-model-apis-4.md), [`comfyui-oss-4.md`](research/comfyui-oss-4.md) and the UX and speed audit [`ux-audit-4.md`](research/ux-audit-4.md). The plan for Fuobe Originals (open-weight versions of Higgsfield's own products) is in [`higgsfield-originals-5.md`](research/higgsfield-originals-5.md) and [`fuobe-originals-recipes-5.md`](research/fuobe-originals-recipes-5.md); Genjutsu's Character swap and the Character Swap Studio follow [`openjutsu-6.md`](research/openjutsu-6.md) (Comfy Org's Openjutsu and Akatz Labs' H3 Character Swap). Since round 4, part 5 (O7), Fuobe calls no Higgsfield model or API: Higgsfield is only what Fuobe is measured against._
++_Last updated: 2026-10-30 (round 4, part 5, merged with the local work: local LLM servers, Pixal3D and the Image to 3D finish, and covers from preview renders). The research behind this is in [`docs/research/`](research/README.md); the Higgsfield inventory it is measured against is [`higgsfield-inventory.md`](research/higgsfield-inventory.md), deepened for round 3 by [`higgsfield-studios.md`](research/higgsfield-studios.md), [`higgsfield-image-studios.md`](research/higgsfield-image-studios.md) and [`higgsfield-marketing-agents.md`](research/higgsfield-marketing-agents.md), and brought up to date for round 4 by [`higgsfield-delta-4.md`](research/higgsfield-delta-4.md), with [`paid-model-apis-4.md`](research/paid-model-apis-4.md), [`comfyui-oss-4.md`](research/comfyui-oss-4.md) and the UX and speed audit [`ux-audit-4.md`](research/ux-audit-4.md). The plan for Fuobe Originals (open-weight versions of Higgsfield's own products) is in [`higgsfield-originals-5.md`](research/higgsfield-originals-5.md) and [`fuobe-originals-recipes-5.md`](research/fuobe-originals-recipes-5.md); Genjutsu's Character swap and the Character Swap Studio follow [`openjutsu-6.md`](research/openjutsu-6.md) (Comfy Org's Openjutsu and Akatz Labs' H3 Character Swap). Since round 4, part 5 (O7), Fuobe calls no Higgsfield model or API: Higgsfield is only what Fuobe is measured against._
**Legend**
@@@ -21,22 -19,43 +19,44 @@@ Checks for round 4, part 5 (PR #13). Th
| check | result |
|---|---|
- | `pnpm typecheck`, `pnpm lint` | clean. Lint has 0 errors and one old warning (unused `WAN_NEG_EN` in `scripts/comfy/library.spec.mjs`) |
- | `pnpm test` (Vitest, 79 files, 1128 tests) | pass. New this round: pipelines and chain slots (stems, `audio2`, `audios`, `prompt`), the LLM provider (cue translation in batches, Ollama fallback), runner timeouts and restarts, structured outputs (text with cues, 3D, layers, stems), payload mapping for the new FieldMap keys (palettes, try-on, reference clips, compose tracks), the Library (Trash, folders, bulk, zip read back by Python's `zipfile`, cursor paging), the live stream reducers, security (cross-site, host allowlist, remote-fetch SSRF guard, login throttle, safe redirect), every new studio's planner and API (Cinema, Canvas, Layers, Shorts, Mixed Media, image studios, marketing, Faceless/Explainer, dub, Katana, captions, 3D, Virality), ComfyUI bindings of every new workflow through `prepareWorkflow`, Assist skills/projects/memory/modes, the streamed Claude request (against an SSE fake), and MCP 1.1.0 |
- | `pnpm build` | passes |
- | ComfyUI workflow library | ✅ 115/115 workflows accepted by `POST /prompt` with no `node_errors` against a live CPU ComfyUI v0.41 with zero-byte placeholder weights. This checks graph structure, input names, types and file references, **not output quality**. `lipsync-latentsync16` and `sfx-thinksound` were validated on a separate isolated worker (port 8189) |
- | Real CPU runs through the production build (`tests/e2e/comfyui-selftest.mjs`) | ✅ uploads → `POST /api/generations` → ComfyUI → stored output, each checked with ffprobe: add a soundtrack (one track, and voice over a background bed), trim, cut a resampled segment, caption burn-in and a 3-pass VHS meta-batch, including 20 s 640x360 30 fps clips. Captions are drawn on their cues and absent in the gaps |
- | Other real CPU runs this round (package branches) | ✅ Dub voice timeline: three tones placed at 1 / 4.5 / 9 s on a 12 s track (ffprobe 12.0 s, silencedetect found them at 1.00, 4.50 and 9.00 s). Joins that keep a clip's sound: `sound2-3` gave 8.92 s, 223 frames at 25 fps, silent until 2.96 s and then the voiced clip's tone; `sound1-2` 5.96 s with sound from 0. Extract frame: the first frame, the frame at 0.5 s and the last frame of a fixture clip. Memory: soundtrack mux of 600 frames +0.01 GB RSS (the picture is stream-copied, bit-identical); chunked caption burn-in under RAM pressure +0.50 GB for 20 s and +0.45 GB for 40 s (the old one-batch graph: +5.16 GB) |
- | Live updates | ✅ in dev and production: a 3.5 s demo image shows 3.8 s after the POST (was 4.6–5.2 s with polling). One stream per browser, shared by tabs (Web Locks + BroadcastChannel) |
- | Runner and security fixes | ✅ each with a regression test: provider timeouts (45 min running, 4 h queued) with poll-before-timeout, cancel during submit, boot-time runner, interrupted-submit sweep, demo/real mix refused, cross-site writes refused, Host allowlist on password-less installs, SSRF-safe remote fetch, login throttle, safe `?next=` redirect, matcher keeping only root SVGs public. The sign-in proxy's body limit is raised to 210 MB so 200 MB uploads pass; that is a config setting with no test (a 15 MB upload was checked live) |
- | Demo-mode browser passes (each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Layers: `tests/e2e/layers.mjs` (5 checks) plus scratch flows (Angles, Edit text, geometry, full-detail export, Compare after Expand, failures). Shorts + Mixed Media: 40 checks (one session per double-click, crop note, take picker keys, retry). Image studios: Photodump retry inside its batch, Fashion retry, signature routing and Reuse, `?create=1`, Save as character once. Marketing: Click to Ad kit progress and brand kit, @mentions, grid order, baked formats, auto-composited open posters. Faceless: channel in 678 ms, topics, script review autosave, render to the end, timeline change + Undo, delete stops 8 steps, Explainer 30 s render. av-tools: 112 page loads (14 pages × both engines × 2 widths × 2 themes), dub review flush, Katana cuts, captions per burner. Assist: 51 checks plus `tests/e2e/assist-flows.mjs` 6/6. Canvas: `tests/e2e/canvas-smoke.mjs` incl. 60 nodes at 19 ms keystroke → paint. Cinema: `tests/e2e/cinema-shortcuts.mjs`. Composer: `tests/e2e/composer-flows.mjs`. Shell: `tests/e2e/shell.mjs`. Phone layout: `tests/e2e/no-horizontal-scroll.mjs` fit 55 routes in light and dark |
- | LLM text steps (translate, write) | 🟢 tested against stand-in Ollama, LM Studio, Unsloth Studio and llama-server servers (`tests/llm.test.ts`, `tests/local-llm.test.ts`) and a stubbed Claude API. No live Claude or local-model run: this machine has LM Studio 0.4.18 with no chat model downloaded and an Unsloth Studio whose Python environment needs a repair |
- | Assist on Claude | 🟢 the streamed request (adaptive thinking, betas, cached system blocks, max_tokens per effort) is built through the SDK against an SSE fake. **No live Claude call yet**: needs an Anthropic key |
++| Local work merged after PR #13: local LLM servers, Pixal3D and the Image to 3D finish, covers from preview renders | 🟢 by tests, not live: `tests/local-llm.test.ts` (the wire formats, Assist history for strict chat templates, reading each server, and stand-in LM Studio, Unsloth Studio and llama-server servers, Automatic included), `model3d-finish`, `model3d-runner` and `model3d-webm` (the 3D graphs and routes, the GLB finish, the runner's finish and turntable steps, and the browser recorder's WebM muxer), `covers-from-masters` (the merge with other runs' covers, re-runs) and `preset-cards` (still and clip covers). No live local chat model and no Pixal3D run through Fuobe on a GPU yet |
+ | `pnpm typecheck`, `pnpm lint` | clean. Lint has 0 errors and one old warning (unused `WAN_NEG_EN` in `scripts/comfy/library.spec.mjs`). In a checkout without `.next`, run `pnpm exec next typegen` (or a dev or build run) before `pnpm typecheck` |
-| `pnpm test` (Vitest, 161 files, 2,643 tests) | pass. New in round 4, part 5: the Character Swap Studio (`swap-studio`, 48 tests: shots, segments and continuation, prompts, masks, takes, assembly and prices; `swap-studio-edit`, 17; `swap-studio-api`, 9: the demo provider end to end through the server on both engines, a continuation waiting for its take, jobs stopped when a clip is removed, a 404 after delete; `comfy-swap-studio`, 14: the two new graphs rewritten per job through the real provider on the library files, the LoRA download, the master's tail, mask splices and the memory refusal), AVI headers (`avi-probe`, 3), ComfyUI reachability (`comfy-reach`, 10: busy, refused, a silent port, shared checks, chain steps waiting, a cloud step not waiting, an old address's check not overwriting a new one; against a stand-in HTTP server, a silent socket, closed ports and a fetch that times out) and the O7 guard (`no-higgsfield`, 28: it scans `src`, `scripts`, `bin`, `skills`, `workflows`, `package.json` and the README outside its upgrade notes for the provider's id, key, env vars, identifiers and copy that offers it, and for retired model ids in code; it also checks the catalog and settings without it, REPLACED_BY and the moved operations, Cinema Studio's Director fields as prompt words, retired ids resolving in the API, retries, waiting steps, Canvas, Assist and the Library, the failed in-flight job and the migration on seeded rows). `higgsfield.test.ts` is gone. Round 4, part 4 added, and the suite still runs: Fuobe Cinema (fal payloads through the adapter with fetch stubbed: the plain endpoint, `camera_lora`, prompt expansion off, frames and sizes, the LoRA endpoint only with a LoRA, the backward-extend prequel and the edit body; prices per megapixel for each tier and shape; the Fun Camera pose and LoRA injection on the open graphs; the Soul Cast sheet's LoRA chain; the editor picked from the take; all 33 moves on both engines; a 30 s take plus an extend, Soul Cast, Soul Location and Reverse angle through the API in demo mode), Genjutsu and Character swap (prompts, canvas sizes, click mapping, windows, limits and licences; the real library graphs bound, Relay included, with expected values taken from the pack's sources; model and install pins; the first-frame step failing and Retry on the real chain runner; estimates with fal and Replicate keys and in demo mode; Describe against a fake Ollama server; H3 Person Removal), Soul ID (every trainer's request and the AI-Toolkit configs, a demo never replacing a real Soul ID, the background LoRA copy, a remote AI-Toolkit, a retired Soul ID training, every open model of a family taking the LoRA; all against a fake network), Models & licences (switches, fallbacks, chains refused before anything is queued, the 422 naming the switch, the settings API round trip, the studio menus), share links (hashed tokens, expiry, files limited to one share, 404 when revoked, expired or trashed, hidden prompts, the paths the proxy opens, the wrong-token guard) and the metadata cleaner, and Assist (time zones across clock changes, every rule and the cap; a fake-clock sweep with no double run, one catch-up after downtime, pause on project delete, Ask first and auto-run within the cap, Run now; connector URL rules, masking, the allow-list and the MCP request built through the real SDK against an SSE fake). Round 4, part 3 added, and the suite still runs: Fuobe Soul (the look generator and its licence, trigger and size rules, legacy ids, fal and Replicate payloads, the ComfyUI text-to-image and image-to-image graphs, prices per megapixel, picking the engine, `engine` on the REST route, the finish route, the Soul HEX lock, one test per review finding), Fuobe DoP (fal payloads through the adapter with fetch stubbed, when the Replicate fallback is picked and how it is priced, LoRA injection, sizing from the start frame and the end-frame node on the ComfyUI graphs, prices, the relight chain, the grade and its next step, the partner routes, Focus Change, the preset → LoRA map's licence, expert and alias rules, a Mix dry run in the harness), Image to 3D (38 tests: a plan per mode and engine, the blockers, the SAM 3D, Meshy multi-view, Tripo text, TripoSplat and rig payloads, the rig price, extra formats stored against a local HTTP server, the multi-view bindings with sides cut out, the open text-to-3D chain in demo mode) and Canvas (the new ports and node plans on both engines, a 30-clip concatenator folded into joins of at most 24, groups, tables and row re-runs, pages and the 409 at 20 pages, the silent track, the `video-fit-clip` binding). Round 4, part 2 added, and the suite still runs: the evaluation harness (its runner end to end against the real route handlers on the demo provider: spend cap, resume, promote and `--record`; the API seams; its Python metric tests through uv, skipped when uv isn't there), LoRAs (the generated library, fal and Replicate payloads checked against the researched schemas, downloads and hash checks with no network, LoRA nodes added to the real ComfyUI graphs), Content Factory (the link guard and private-address refusal, prices, one series per Generate, Next episode, the Claude message per engine mode, the Gemma 4 binding), the AI Influencer builder (pick and clash rules, Shuffle frequencies over many seeds, the prompt compiler, plans per engine, both retry paths, the two ComfyUI bindings), Layers (the OCR parser, Inpaint and Enhancer plans per model and engine, mask or tinted copy, the OvisOCR3, FLUX Fill, Qwen Edit, SeedVR2 and ESRGAN bindings, Save as element), per-frame Mixed Media (sampling, the 500 / 200 chunks, lanes, joins at 2048 px, a demo render where frame 14 fails and the frames still waiting are dropped unpaid, partial Try again), chains (fan-out and fan-in by output number, a new chain launching with more than 50 older steps waiting) and the Click to Ad end card (steps per engine, the silent track, provider bindings, a demo open run). Round 4, part 1 added, and the suite still runs: Remove object (planner, estimates, ComfyUI bindings on the real graphs, demo runs end to end), Genjutsu (plans per mode and engine, prices and key mixes, bindings), video finishing (the fps table, upscale tiers, formats, prices by clip length, cloud payloads, bindings, cancel), Frames (with a seeded property test over 4,000 films), 3D scenes (lens, frame, Spectral depth decode, pose), Faceless+ (Ken Burns moves, music loops, the crossfade curve, which steps a change redoes), Audio Loop and Join, the ⌘K palette, Save & test, Home's one-time Start token, the licence list, the `fuobe` CLI (run as a child process against a stand-in server), `GET /api/models` and `?preview=1`, the Library (nested folders, pins, review status, where a file is used), notifications, the isolated worker, Explainer documents, the cloud dub mix and the Assist / MCP studio routes |
++| `pnpm test` (Vitest, 167 files, 2,714 tests) | pass. The local merge adds `local-llm` (29), `model3d-finish` (16), `model3d-runner` (4), `model3d-webm` (2), `covers-from-masters` (5) and `preset-covers` (6: the real covers manifest against `public/previews`, its importers and its cache header); `preview-media.test.ts` is gone with the old card media. On Windows, 41 tests and 66 temp-folder cleanups (EPERM) fail, all of them on `origin/main` too: POSIX paths, CRLF checkouts, `python3` and Ctrl+C. New in round 4, part 5: the Character Swap Studio (`swap-studio`, 48 tests: shots, segments and continuation, prompts, masks, takes, assembly and prices; `swap-studio-edit`, 17; `swap-studio-api`, 9: the demo provider end to end through the server on both engines, a continuation waiting for its take, jobs stopped when a clip is removed, a 404 after delete; `comfy-swap-studio`, 14: the two new graphs rewritten per job through the real provider on the library files, the LoRA download, the master's tail, mask splices and the memory refusal), AVI headers (`avi-probe`, 3), ComfyUI reachability (`comfy-reach`, 10: busy, refused, a silent port, shared checks, chain steps waiting, a cloud step not waiting, an old address's check not overwriting a new one; against a stand-in HTTP server, a silent socket, closed ports and a fetch that times out) and the O7 guard (`no-higgsfield`, 28: it scans `src`, `scripts`, `bin`, `skills`, `workflows`, `package.json` and the README outside its upgrade notes for the provider's id, key, env vars, identifiers and copy that offers it, and for retired model ids in code; it also checks the catalog and settings without it, REPLACED_BY and the moved operations, Cinema Studio's Director fields as prompt words, retired ids resolving in the API, retries, waiting steps, Canvas, Assist and the Library, the failed in-flight job and the migration on seeded rows). `higgsfield.test.ts` is gone. Round 4, part 4 added, and the suite still runs: Fuobe Cinema (fal payloads through the adapter with fetch stubbed: the plain endpoint, `camera_lora`, prompt expansion off, frames and sizes, the LoRA endpoint only with a LoRA, the backward-extend prequel and the edit body; prices per megapixel for each tier and shape; the Fun Camera pose and LoRA injection on the open graphs; the Soul Cast sheet's LoRA chain; the editor picked from the take; all 33 moves on both engines; a 30 s take plus an extend, Soul Cast, Soul Location and Reverse angle through the API in demo mode), Genjutsu and Character swap (prompts, canvas sizes, click mapping, windows, limits and licences; the real library graphs bound, Relay included, with expected values taken from the pack's sources; model and install pins; the first-frame step failing and Retry on the real chain runner; estimates with fal and Replicate keys and in demo mode; Describe against a fake Ollama server; H3 Person Removal), Soul ID (every trainer's request and the AI-Toolkit configs, a demo never replacing a real Soul ID, the background LoRA copy, a remote AI-Toolkit, a retired Soul ID training, every open model of a family taking the LoRA; all against a fake network), Models & licences (switches, fallbacks, chains refused before anything is queued, the 422 naming the switch, the settings API round trip, the studio menus), share links (hashed tokens, expiry, files limited to one share, 404 when revoked, expired or trashed, hidden prompts, the paths the proxy opens, the wrong-token guard) and the metadata cleaner, and Assist (time zones across clock changes, every rule and the cap; a fake-clock sweep with no double run, one catch-up after downtime, pause on project delete, Ask first and auto-run within the cap, Run now; connector URL rules, masking, the allow-list and the MCP request built through the real SDK against an SSE fake). Round 4, part 3 added, and the suite still runs: Fuobe Soul (the look generator and its licence, trigger and size rules, legacy ids, fal and Replicate payloads, the ComfyUI text-to-image and image-to-image graphs, prices per megapixel, picking the engine, `engine` on the REST route, the finish route, the Soul HEX lock, one test per review finding), Fuobe DoP (fal payloads through the adapter with fetch stubbed, when the Replicate fallback is picked and how it is priced, LoRA injection, sizing from the start frame and the end-frame node on the ComfyUI graphs, prices, the relight chain, the grade and its next step, the partner routes, Focus Change, the preset → LoRA map's licence, expert and alias rules, a Mix dry run in the harness), Image to 3D (38 tests: a plan per mode and engine, the blockers, the SAM 3D, Meshy multi-view, Tripo text, TripoSplat and rig payloads, the rig price, extra formats stored against a local HTTP server, the multi-view bindings with sides cut out, the open text-to-3D chain in demo mode) and Canvas (the new ports and node plans on both engines, a 30-clip concatenator folded into joins of at most 24, groups, tables and row re-runs, pages and the 409 at 20 pages, the silent track, the `video-fit-clip` binding). Round 4, part 2 added, and the suite still runs: the evaluation harness (its runner end to end against the real route handlers on the demo provider: spend cap, resume, promote and `--record`; the API seams; its Python metric tests through uv, skipped when uv isn't there), LoRAs (the generated library, fal and Replicate payloads checked against the researched schemas, downloads and hash checks with no network, LoRA nodes added to the real ComfyUI graphs), Content Factory (the link guard and private-address refusal, prices, one series per Generate, Next episode, the Claude message per engine mode, the Gemma 4 binding), the AI Influencer builder (pick and clash rules, Shuffle frequencies over many seeds, the prompt compiler, plans per engine, both retry paths, the two ComfyUI bindings), Layers (the OCR parser, Inpaint and Enhancer plans per model and engine, mask or tinted copy, the OvisOCR3, FLUX Fill, Qwen Edit, SeedVR2 and ESRGAN bindings, Save as element), per-frame Mixed Media (sampling, the 500 / 200 chunks, lanes, joins at 2048 px, a demo render where frame 14 fails and the frames still waiting are dropped unpaid, partial Try again), chains (fan-out and fan-in by output number, a new chain launching with more than 50 older steps waiting) and the Click to Ad end card (steps per engine, the silent track, provider bindings, a demo open run). Round 4, part 1 added, and the suite still runs: Remove object (planner, estimates, ComfyUI bindings on the real graphs, demo runs end to end), Genjutsu (plans per mode and engine, prices and key mixes, bindings), video finishing (the fps table, upscale tiers, formats, prices by clip length, cloud payloads, bindings, cancel), Frames (with a seeded property test over 4,000 films), 3D scenes (lens, frame, Spectral depth decode, pose), Faceless+ (Ken Burns moves, music loops, the crossfade curve, which steps a change redoes), Audio Loop and Join, the ⌘K palette, Save & test, Home's one-time Start token, the licence list, the `fuobe` CLI (run as a child process against a stand-in server), `GET /api/models` and `?preview=1`, the Library (nested folders, pins, review status, where a file is used), notifications, the isolated worker, Explainer documents, the cloud dub mix and the Assist / MCP studio routes |
+ | `pnpm eval:validate` | valid: the twelve case files (`selftest`, `soul` with 139 cases, `soul-cinema` with 6, `soul-hex` with 3, `soul-id` with 5, `dop` with 89, `dop-mix` with 5, `genjutsu` with 7, `mixed-media`, `shorts`, `speak`, `cinema` with 9), and the generated suites match the research. Round 4, part 4 points `cinema` at Fuobe Cinema and `genjutsu` at the Genjutsu Originals, Character swap included, and `soul-id` now trains a character, a look and one case per family |
+ | `pnpm build` | passes, with no Turbopack "dynamic filesystem access" tracing warnings (PR #12 had 4). Soul ID's LoRA copy (`src/server/loras.ts`, `src/server/training.ts`) now tells Turbopack not to trace its runtime paths, and Settings → About & licences reads only `package.json` and the workflow manifest |
+ | ComfyUI workflow library | ✅ 141 of 150 workflows accepted by `POST /prompt` with no `node_errors` against a live CPU ComfyUI 0.41 with zero-byte placeholder weights. This checks graph structure, input names, types and file references, **not output quality**. The other nine need node packs that server doesn't have: `lipsync-latentsync16` and `sfx-thinksound` (validated on a separate isolated worker in round 3), `captions-whisper-burnin` (ComfyUI-Whisper) and `image-vectorize-vtracer` (ComfyUI-ToSVG; validated and run on a CPU ComfyUI with the pack in PR #6), PR #12's three MiniMax H3 graphs: `video-character-swap-h3` (Akatz Labs' `h3_character_swap` pack), `video-character-swap-h3-relay` and `video-person-remove-h3-relay` (H3 Relay), and PR #13's two H3 Relay graphs for the Character Swap Studio: `video-character-swap-h3-segment` (one H3 Relay 2.0 pass with the approved mask, an anchor and the take before's FFV1 master as history; 24 GB) and `video-mask-h3-relay` (a SAM 3.1 person mask on any frame of a shot; 6 GB). These five were built and submitted to the CPU ComfyUI, which answered `missing_node_type`; they are recorded `validated: false` (before PR #12 every entry was validated; now 145 of 150 are), and the Workflows page shows them as unverified. `install-comfyui.sh` installs `h3_character_swap` by default and H3 Relay with `H3_RELAY=1`; neither is installed on this machine. Their core node classes are in `object_info.subset.json`, which lists 306 (276 before PR #12). PR #10 added six graphs, none with a node pack: `z-image-turbo-i2i` (Fuobe Soul's image to image), `ltx23-i2v-lora`, `ltx23-flf2v-lora` and `ltx23-t2v-lora` (Fuobe DoP · LTX; nothing uses the text-to-video one yet), `image-to-3d-trellis2-multiview` (TRELLIS.2 Multi-view) and `video-fit-clip` (the Canvas concatenator) |
+ | Browser checks (Playwright against the production server, demo mode, ComfyUI unreachable) | ✅ all 18 pass: `shell.mjs`, `no-horizontal-scroll.mjs` (every route at 390 px, light and dark; it finds new studio pages such as `/assist/scheduled` and `/settings/models` itself, but not the public `/s/<token>` page), `composer-flows.mjs`, `library-flows.mjs`, `cinema-scene.mjs`, `cinema-shortcuts.mjs`, `notifications.mjs`, `clipboard.mjs`, `layers.mjs`, `assist-flows.mjs`, `canvas-smoke.mjs`, `canvas-board.mjs` (20 checks), `canvas-open-dub.mjs` (9 checks, with Settings → Engine mode set to open source only for the run), `dop-flows.mjs` (its 2 cloud price checks need a fal key and were skipped), `eval-review.mjs` (the harness's report and blind A/B review pages), PR #12's `cinema-original.mjs` and `genjutsu-original.mjs`, and the new `character-swap-studio.mjs`. `cinema-original.mjs` (1440 and 390 px, light and dark): Fuobe Cinema first in the model menu as an Original, with what runs on each engine; no Higgsfield in the menu or the project's context; Dolly In on LTX-2.3's camera LoRA, and a demo take that asked for it; 30 s shown as 30 s; no move badges for a partner model; the price before running; a still on Fuobe Soul Cinema cropped to 21:9 and graded in the feed; the open-engine menu (Fuobe Cinema, LTX-2.5, Wan 2.2 14B); Soul Cast on Fuobe Soul's Realistic look and Soul Location on its Movie look, with the grade applied. In PR #12's first full run it failed once at 390 px (the Soul Location button was swapped out mid-click while the folded Director panel re-rendered); that failure was never reproduced. Since PR #13 it and `genjutsu-original.mjs` wait for closing dialogs, sheets, menus and select lists to settle before the next click, which removes the likely cause; both passed on the first run here. `genjutsu-original.mjs` (1440 and 390 px, light and dark): Character swap's controls, limits and licence lines; each model's source badge; the swap LoRA's choices per engine and partners' resolutions; a demo run to the result; Describe my character, and its message without a text model; Use the clip's words; on the open engine Click them, the GPU line, SAM's detection numbers, the window and History lists and the mask switch on the Original's graph only; Motion and Restyle list the Originals first, Restyle has Soul looks, and no Higgsfield anywhere. `character-swap-studio.mjs` (58 checks): the whole flow in demo mode on the cloud engine (a project, the character, a clip, Detect edits, a cut at the playhead and Keep original, the transcript and Build shot prompts, a click on a frame and Track shot, a mask and a scene anchor approved, two segments with the second continuing from the first, takes compared and reviewed, Export decisions, the assembly with a download, and Finish shown as not available), then every stage at 1440 and 390 px, light and dark, with no sideways scroll; a GPU project's 24 fps copy, an AVI's browser copy on the cloud, the sidebar link, Genjutsu's hand-off making a project with its clip and character, and a 404 for an unknown project. `cinema-scene.mjs` and `layers.mjs` need ComfyUI unreachable: with this machine's ComfyUI reachable they fail, and neither is an app bug (demo stills are SVG placeholders ComfyUI can't read, and the Layers step needs the Qwen-Image-Layered weights; the app names the missing files). The Cinema, Genjutsu and Character Swap Studio checks also expect demo mode with ComfyUI unreachable. `/content-factory/[id]` has no sample in the 390 px sweep, so only its not-found page is checked there |
+ | Real CPU runs through the production build (`tests/e2e/comfyui-selftest.mjs`) | ✅ passes again on this tree. As in round 3: uploads → `POST /api/generations` → ComfyUI → stored output, each checked with ffprobe: add a soundtrack (one track, and voice over a background bed), trim, cut a resampled segment, caption burn-in and a 3-pass VHS meta-batch, including 20 s 640x360 30 fps clips. Captions are drawn on their cues and absent in the gaps |
+ | Canvas Video concatenator on CPU (`tests/e2e/comfyui-canvas-concat.mjs`) | ✅ on this tree, on the first try, through the canvas API (upload → `POST /api/canvases` → run → poll → download): three clips made with ffmpeg, with different sizes, frame rates and sound (one with a tone, one silent, one with a tone the node mutes), were reordered, cut and framed to 9:16 by `video-fit-clip`, one CPU pass each, then joined by `video-concat-encoded`, all on a live CPU ComfyUI. ffprobe: 720x1280 at 30 fps, every clip's kept frames in the order picked, sound only where it was kept. No model is involved; the cloud concatenator hasn't run with a real key. In PR #12 it passed only on the third try: Fuobe asked ComfyUI "are you there?" with a 1.5 s or 2 s timeout, a busy ComfyUI missed it, and steps went to the demo provider. PR #13's reachability fix (§2, Getting started and connections) ended that |
+ | Packages (round 4, parts 2 to 5) | Each package went through implement → adversarial review → fix before it was merged into the integration branch; typecheck, lint and the full suite ran after every merge. In parts 3 to 5 no merge needed a fix commit; in part 4 the Models & licences merge resolved three conflicts with Soul ID inside the merge, keeping both sides, and in part 5 the only conflict was settled inside `o/no-higgsfield` (a README conflict, by leaving out the Higgsfield key row) |
+ | Demo-mode browser passes (round 4, part 5: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Character Swap Studio: `character-swap-studio.mjs` on a dev server in demo mode with ComfyUI unreachable, after the review fixes; the last 3 runs passed (one earlier run failed on a timing race in the Export decisions check, which now polls). No Higgsfield: a pass over the 14 changed routes and a brand workspace (no route picker, no Higgsfield copy, no sideways scroll, no console errors), `no-horizontal-scroll.mjs` on 21 routes, Reuse of a stored Soul 2.0 run in the Image studio switching to Fuobe Soul with its look and a toast, and the Library viewer naming it "Soul 2.0 (Higgsfield)" with its outputs; after the review fixes, `/image?model=soul-2` opens on Fuobe Soul with the Make your own Soul look cards, `/image?model=fuobe-soul` shows them and `/image?model=nano-banana-pro` doesn't. Check fixes: `cinema-original.mjs` passed twice (118 checks, once on a loaded machine) and `genjutsu-original.mjs` once (126) with `COMFYUI_URL` on a closed port, before the review fixes; both passed again in the full run above |
+ | ComfyUI reachability (round 4, part 5: `r4/check-fixes`) | ✅ by tests (`comfy-reach`, above) and live: after the fix, the Canvas concatenator check passed against a live CPU ComfyUI with all 4 steps on ComfyUI, and `/api/status` showed ComfyUI with its RAM. A stress run with `/system_stats` answering only after 4 s (longer than every check's timeout) ran all 4 steps on ComfyUI, but before a review fix changed the check; it wasn't repeated. The blocking first check's "no answer and no connection" case (a host that drops packets) has no test |
+ | ComfyUI checks in round 4, part 5 (package branches) | Not validated here: the two new H3 Relay graphs were submitted to the live CPU ComfyUI, which answered `missing_node_type` (`validated: false`). How the provider rewrites them per job is tested on the library files (`comfy-swap-studio`). O7 and the check fixes add no graph. No new graph has run on a GPU |
+ | Demo-mode browser passes (round 4, part 4: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Share links, on a dev server in demo mode with `FUOBE_PASSWORD` set and the visitor signed out (58 of 58 scripted checks): cleaned files of the same size with byte ranges, an MP4 that still decodes, view counting, the link-preview picture, the wrong-token guard (100 bad tokens give 404 then 429 while the real link still opens), the expired-link flow, the Feature, Series and Carousel layouts, and a prompts-hidden page. The metadata cleaner also ran over 26 files made with ffmpeg and PIL (each decodes, same pixels, no tags left) and over real ComfyUI PNG and MP4 outputs. The Share dialog's entry points (the viewer on desktop and in the phone drawer, the folder menu, Cinema's header and menu) and the Publish wizard were clicked through before the review fixes; the Revoke button itself wasn't clicked (API tests and live HTTP checks cover it). Soul ID: Elements, an element's page, the Train dialog for a character (Train stays off until the consent tick; More models with licences and prices) and for a style, the moodboard's Train as a look dialog, the old Higgsfield row and its remove button, the demo note, two families on one element; no sideways scroll. Models & licences: `/settings/models` with no sideways scroll or page errors, and a mistyped switch id answered with 400; with the paid-API class off, 11 studios loaded with no page errors, and with Kling O3 edit off Katana's menu moved to the next model; `no-horizontal-scroll.mjs` passed on `/settings/models` and 10 studio pages. Assist: a connector with a secret in its path shown as …/s/…/mcp and a short token as ••••yz (neither in the page's HTML), a bad tool name blocking Save, the Schedule dialog prefilled from a chat with connectors off by default, Run now (202), pause and resume, a project's Scheduled tab, ⌘K finding "Assist connectors", no sideways scroll on `/assist/scheduled`, `/settings`, `/assist` and a project page, and `assist-flows.mjs` 6/6. Fuobe Cinema and Genjutsu: their checks are in the suite now (above) |
+ | ComfyUI checks in round 4, part 4 (package branches) | Not validated here: the three H3 graphs were built and submitted to the live CPU ComfyUI, which answered `missing_node_type` because their packs aren't installed (`validated: false`). The Openjutsu research checked the swap graph's 22 core node classes against that server's `/object_info`. Fuobe Cinema reuses Wan 2.2 graphs already in the library; Soul ID, Models & licences, share links and Assist add no graph. No new graph has run on a GPU |
+ | Evaluation harness (round 4, part 4: `o/cinema-original`, `o/soul-id`, `o/genjutsu-original`) | ✅ by tests on the demo engine: the `cinema` cases run on the demo engine and match Cinema's own planner on both engines, with the cloud variants dry-run; `genjutsu` runs demo Character swap cases on a 6 s walking-figure clip made for it; `soul-id` never measures a demo training as trained, sends the consent a character needs and uploads up to 80 photos. No Cinema, Genjutsu or Soul ID recipe has been measured on a GPU or the cloud |
+ | Demo-mode browser passes (round 4, part 3: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Fuobe Soul: a curated moodboard link lands on Fuobe Soul with "Look: Y2K studio" on the Look chip; the General look at 20% sends `presetStrength` 0.2; the Look panel's radio groups work with the keyboard; a Soul Cinema 21:9 demo run was cropped from 1024x576 to 1024x439 with its grade; a 90s Grain run got its grade and a DigitalCam run its date stamp, each saved with the raw picture kept; the Soul HEX lock started on and went to `/api/palettes/lock`; a run made with the Cloud switch was stored as cloud; the Models page lists Soul under Cloud and Open source; no sideways scroll on `/image`, `/moodboards`, `/edit` and `/character-sheet`. Fuobe DoP: `dop-flows.mjs` 23/23 with a placeholder fal key (nothing sent): besides the checks above, the cloud price is $0.50 for a LoRA move and $0.435 with the relight step (its desktop screenshots were light only). Image to 3D: the five modes, blockers, the price line, the keyboard, Pick an object on the open engine and the rig dialog; the side slots at 8 widths from 390 to 1440 px with no overlap; the side hint, rig hint, Still link and the Library's splat viewer on hand-edited demo rows (demo mode returns a plain model); no sideways scroll on `/image-to-3d` and `/library`. Canvas: the toolbar tools, groups, pages, comments and the open dub node at 1440 px; `/canvas` and a board fit 390 px in light and dark |
+ | ComfyUI checks in round 4, part 3 (package branches) | ✅ every new workflow accepted by `POST /prompt` on the live CPU ComfyUI. TRELLIS.2 Multi-view was also accepted with sides cut out (front + back, front + right), and its MoGe field-of-view step ran for real on the CPU: 137 s for two runs, 40.0° estimated on a test image and a given 20° passed through. No new model graph has run on a GPU |
+ | Evaluation harness (round 4, part 3: `o/soul`, `o/dop`) | ✅ on a demo server, `soul-hex` made 5 of 5 and scored the new palette metric; a `soul-cinema` dry run had 2 of 2 runnable; the harness tests include a demo palette-lock run and a DoP Mix dry run; the Python metric tests passed (20, 5 skipped). No Soul or DoP recipe has been measured on a GPU or the cloud |
+ | LoRA download (round 4, part 2: `o/lora-plumbing`) | ✅ one pinned 85 MB Hugging Face LoRA (`lenovo_z.safetensors`) downloaded live through Settings → LoRAs (`POST /api/loras`) on a dev server; its SHA-256 matched the fingerprint in the library. Settings → LoRAs was checked in the browser at 1440 and 390 px, light and dark: arrow keys, one Tab stop, no sideways scroll, the folder-problem alert. No civitai download (no civitai key here), no mirror on fal or Replicate, and no LoRA has rendered on fal, Replicate or a GPU |
+ | Click to Ad end card on CPU (round 4, part 2: `r4/marketing-mixed`) | ✅ the open end card (`video-append-endcard`) ran twice on a live CPU ComfyUI 0.41 through the real runner, with a temporary test that isn't committed: an ad with a (silent) AAC sound track plus a 1.5 s card gave 3.5 s with the sound track kept, and the ad's first 50 frames were framemd5-identical; an ad with no sound track gave a video with none. The suite covers the bindings and a demo run, not these live runs. The cloud end card hasn't run with a real key |
+ | Evaluation harness (round 4, part 2: `o/harness`) | ✅ against a dev server and a CPU ComfyUI: the open self-test made and scored 4 CPU-only jobs (trim, palette lock, join, extract frame), kept them out of the Library, and `eval:trash` moved all 4 to the Trash. In demo mode the self-test made 5 of 5 and a Soul run with 3 variants 9 of 9. A dry run of Soul on the open engine listed 2,085 jobs (1,650 runnable; that ComfyUI lacked 54 LoRAs). Its 23 Python metric tests pass in its own venv. No Original has been measured on a GPU or the cloud, and no recipe has been promoted |
+ | Demo-mode browser passes (round 4, part 2: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Layers: Edit text on the cloud (Florence-2 and Ideogram) and on the open engine (an OvisOCR3 job, 3 rows with boxes); detection on a see-through Text layer sends a flattened picture; Inpaint on the whole image and on a rotated layer; Clear; the Enhancer's Skin look; Save as element ("Tulip vase" as a prop). Content Factory (14 checks): three Enters made one series of 3 episodes; picking a preset after an upload deleted the draft; the Generate in Claude dialog's notes; an orphaned series page fits and Delete works. Mixed Media and Click to Ad: `/mixed-media` (How it works, History) and `/marketing/click-to-ad` with no sideways scroll; a demo per-frame render with a frame failure injected in the database showed "Frame 14 of 16" in progress and in History, and Try again finished it. AI Influencer: the model picker lists only Nano Banana Pro and Seedream 5.0 Pro; 25 Shuffles with Heavy locked gave no clash; an Add your face run on a phone, then Save as character, kept the run's face and name; no sideways scroll on `/influencer`, `/character-sheet` and the AI Influencer app |
+ | Real CPU runs in round 4, part 1 (package branches) | ✅ Faceless+ through Fuobe's API (`tests/e2e/comfyui-faceless-plus.mjs`): an eased Ken Burns push-in at 854x480 (48 frames); a move split into two linear pieces that stays smooth across the seam; a three-clip packet-copy join in 2.2 s with ComfyUI RSS +0.00 GB; a 6 s bed looped to 20 s with 1 s crossfades (a 20.000 s FLAC); 4 + 3 + 5 s joined with 0.5 s crossfades (11.000 s, in order). MoGe 2 with its real weights: a 960x720 still became a 3D mesh and a depth map in about 100 s. Frames: a join of 41-, 25- and 21-frame 16 fps clips gave 87 frames, 5.4375 s. Remove object's model-free parts: the painted mask handed from one window to the next lands on the right frame, and windows are cut frame-exact at 29.97 fps (81, 81, 77) and 24 fps (197). Video finishing: RIFE with random-weight stand-ins (quality not judged) 24 → 60 fps (121 frames), 25 → 30 at 2× slow motion and 30 → 24; with no model needed, ProRes, H.265 Main 10, FFV1, PQ and EXR zips; Real-ESRGAN in passes, also with a stand-in, on 30 s 256x144 → 1080p: 750 frames in 47 passes, 0.87 GB above idle (the old whole-clip graph already held 3.0 GB for 10 s of the same clip at only 1024x576); a ProRes 4444 export cancelled in pass 4 ran nothing afterwards |
+ | PR #6 (round 4 research, engine seams, catalog, workflows, Library, CLI) | ✅ the 17 round-4 workflows (132 in the library then) accepted by the live server, and the eight model-free ones run on CPU and checked with ffprobe; the VACE / VOID window, sound and work-size nodes ran on CPU (frame counts, sound lengths, a silent clip, a window at 50 s of a 60 s clip); `image-vectorize-vtracer` validated and run on a CPU ComfyUI. Browser: `library-flows.mjs` 35/35 in demo mode, `notifications.mjs`, `clipboard.mjs`, and Assist's "Open in Captions" hand-off on a production build. The 20 skill playbooks and the agent skill (21 SKILL.md files) pass the Agent Skills reference validator (`skills-ref`), and the skills CLI lists and installs them |
+ | Demo-mode browser passes (round 4, part 1: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Remove object: the whole flow on both engines, plus the Remove background and Depth map panels. Genjutsu: all four modes on both engines, references, the look grid, Copy / Paste setup, hand-offs, the missing-key blockers. Video finishing: the five Upscale tabs, the format picker, the no-ComfyUI note and its cloud link, the greyed "already 1080p". Frames: the strip, keys and drag, the model notes and switches, 10 frames on a phone. 3D scenes: `cinema-scene.mjs`. Faceless+: the wizard rendered to the end on both engines, the episode page, Audio Loop and Join. Onboarding: a cross-site link with a `go` token, and a guessed token, made no generation, Home's Start made exactly one, and a live ComfyUI connected through the guide. Shell: axe clean on five pages; on a cold visit (mean of 23 routes), JS fetched after load 525 → 189 KB and RSC requests 38.3 → 11. Flows: axe 0 violations on seven pages; layout shift on a phone in Assist 0.126 → 0.000 and in the Library 0.482 → 0.001, and on desktop in Cinema 0.048 → 0.000 |
+ | Other real CPU runs (round 3, package branches) | ✅ Dub voice timeline: three tones placed at 1 / 4.5 / 9 s on a 12 s track (ffprobe 12.0 s, silencedetect found them at 1.00, 4.50 and 9.00 s). Joins that keep a clip's sound: `sound2-3` gave 8.92 s, 223 frames at 25 fps, silent until 2.96 s and then the voiced clip's tone; `sound1-2` 5.96 s with sound from 0. Extract frame: the first frame, the frame at 0.5 s and the last frame of a fixture clip. Memory: soundtrack mux of 600 frames +0.01 GB RSS (the picture is stream-copied, bit-identical); chunked caption burn-in under RAM pressure +0.50 GB for 20 s and +0.45 GB for 40 s (the old one-batch graph: +5.16 GB) |
+ | Live updates (round 3) | ✅ in dev and production: a 3.5 s demo image shows 3.8 s after the POST (was 4.6–5.2 s with polling). One stream per browser, shared by tabs (Web Locks + BroadcastChannel) |
+ | Runner and security fixes (round 3) | ✅ each with a regression test: provider timeouts (45 min running, 4 h queued) with poll-before-timeout, cancel during submit, boot-time runner, interrupted-submit sweep, demo/real mix refused, cross-site writes refused, Host allowlist on password-less installs, SSRF-safe remote fetch, login throttle, safe `?next=` redirect, matcher keeping only root SVGs public. The sign-in proxy's body limit is raised to 210 MB so 200 MB uploads pass; that is a config setting with no test (a 15 MB upload was checked live) |
+ | Demo-mode browser passes (round 3: each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Layers: `tests/e2e/layers.mjs` (5 checks) plus scratch flows (Angles, Edit text, geometry, full-detail export, Compare after Expand, failures). Shorts + Mixed Media: 40 checks (one session per double-click, crop note, take picker keys, retry). Image studios: Photodump retry inside its batch, Fashion retry, signature routing and Reuse, `?create=1`, Save as character once. Marketing: Click to Ad kit progress and brand kit, @mentions, grid order, baked formats, auto-composited open posters. Faceless: channel in 678 ms, topics, script review autosave, render to the end, timeline change + Undo, delete stops 8 steps, Explainer 30 s render. av-tools: 112 page loads (14 pages × both engines × 2 widths × 2 themes), dub review flush, Katana cuts, captions per burner. Assist: 51 checks plus `tests/e2e/assist-flows.mjs` 6/6. Canvas: `tests/e2e/canvas-smoke.mjs` incl. 60 nodes at 19 ms keystroke → paint. Cinema: `tests/e2e/cinema-shortcuts.mjs`. Composer: `tests/e2e/composer-flows.mjs`. Shell: `tests/e2e/shell.mjs`. Phone layout: `tests/e2e/no-horizontal-scroll.mjs` fit 55 routes in light and dark |
-| LLM text steps (translate, write) | 🟢 tested against a stand-in Ollama server, a stubbed Claude API and, for open translation without Ollama, a stand-in ComfyUI answering for Qwen3.5 4B. Content Factory's brief (frames and a transcript sent to Claude or Ollama) is tested on its request shape and byte budget, and the Canvas Translate node's text mode on its plan per engine. Genjutsu's Describe my character (round 4, part 4) is tested against a fake Ollama server. No live Claude, Ollama, Qwen3.5 or Gemma 4 run, and no vision model has described a character |
++| LLM text steps (translate, write) | 🟢 tested against stand-in Ollama, LM Studio, Unsloth Studio and llama-server servers (`tests/llm.test.ts`, `tests/local-llm.test.ts`), a stubbed Claude API and, for open translation without a local model, a stand-in ComfyUI answering for Qwen3.5 4B. Content Factory's brief (frames and a transcript sent to Claude or Ollama) is tested on its request shape and byte budget, and the Canvas Translate node's text mode on its plan per engine. Genjutsu's Describe my character (round 4, part 4) is tested against a fake Ollama server. No live Claude, local-model, Qwen3.5 or Gemma 4 run, and no vision model has described a character. The local-LLM layer was written on a machine with LM Studio 0.4.18 but no chat model downloaded, and an Unsloth Studio whose Python environment needed a repair |
+ | Assist on Claude | 🟢 the streamed request (adaptive thinking, betas, cached system blocks, max_tokens per effort) is built through the SDK against an SSE fake. **No live Claude call yet**: needs an Anthropic key (a rejected key did reach Anthropic's API through Settings → Save & test). Round 4, part 4's connectors add `mcp_servers`, one `mcp_toolset` per connector (with its allowed tools) and the MCP beta to that request, also built through the real SDK against the SSE fake; no real remote MCP server has been called |
-| Assist on Ollama | 🟢 tested against a fake Ollama server (round 2). Model downloads aren't reachable from this environment |
+| Assist on a local model | 🟢 tested against a fake Ollama server (round 2) and a fake LM Studio (a tool call and its result under the same id). No live local model has run it yet |
- | Cloud providers (fal / Replicate / Higgsfield) | 🟢 156 fal / Replicate / Higgsfield models (157 cloud models with the Claude text model, plus 10 hidden helpers used by chains) built from the providers' schemas; structured outputs tested on stubbed responses. **No live paid run yet** |
- | MCP server | ✅ 1.1.0 tools and prompts by unit tests; the round-2 run with the official MCP Inspector CLI (initialize, tools/list, estimate_cost, generate, check_generations) still applies |
- | AI-Toolkit training | 🟢 the job flow ran end to end against a fake AI-Toolkit job API (round 2); the new style-LoRA preset (moodboards) by unit tests. No real training run: it needs a GPU |
- | Sign-in and API tokens | ✅ curl and browser checks (round 2); the new throttle and Host checks by unit tests |
+ | Cloud providers (fal / Replicate) | 🟢 196 fal / Replicate models (197 cloud models with the Claude text model, plus 20 hidden helpers used by chains and studios; Overlay image, Extract frames and Images to video, which only the API reached before, now serve Click to Ad's end card, per-frame Mixed Media and Content Factory) built from the providers' schemas; structured outputs tested on stubbed responses. Round 4, part 2 adds Seedream 5.0 Flash and six hosted open-weight models that take LoRAs; every field a route sends, LoRA fields included, is checked against the researched schema. Round 4, part 3 adds the cloud halves of the five Fuobe Originals (Fuobe Soul, Soul HD and Soul Cinema on fal's Z-Image Turbo and Qwen-Image 2512 and Replicate's Z-Image Turbo; Fuobe DoP on fal's Wan 2.2 A14B with Replicate's fast Wan 2.2 as the fallback; Fuobe DoP · LTX on fal's LTX-2.3), two of the hidden helpers (LTX 2.5 Fast for Focus Change, hosted Qwen-Image-Edit 2509 for the relight step) and puts round 4's 3D models (Meshy 7.1 Multi-view, Tripo H3.1 Text to 3D, SAM 3D Objects, TripoSplat, Meshy Rigging) in the Image to 3D studio. Fuobe DoP's payloads are tested through the fal adapter with fetch stubbed; Fuobe Soul's and the 3D models' are tested by building them from their field maps. Round 4, part 4 adds the cloud halves of seven more Originals (12 in all): Fuobe Cinema on fal's LTX-2.3 22B (text, image, start and end frame, extend and video to video, priced per megapixel of video), Fuobe Genjutsu · Motion and its Lite tier on Wan 2.2 Animate, · Swap and its Lite tier on Wan VACE 14B inpainting, · Restyle on Wan 2.2 VACE Fun depth, and Fuobe Character swap on MiniMax H3 reference-to-video with Akatz Labs' LoRA; four more Genjutsu choices (Wan 2.2 Animate Replace, SCAIL-2, Wan Motion, MiniMax H3 Max Recast); five hosted models that take Soul ID LoRAs (FLUX.1 [dev], FLUX.1 Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 9B, Krea 2 Turbo); and eight fal trainers. Fuobe Cinema's payloads are tested through the fal adapter with fetch stubbed, and the H3 payload was checked against the researched fields. Round 4, part 5 removes the Higgsfield provider (O7): the 12 models that ran only there are retired (stored ids run on their replacements), 24 partner models lose their Higgsfield routes and keep their fal or Replicate ones, and Happy Horse 1.1 (text, image and reference to video), which ran only on Higgsfield before, moves to fal at $0.14/s at 720p and $0.18/s at 1080p, built from fal's schemas recorded in the research (`partnerEndpoints`). The Character Swap Studio adds no cloud model: it chains MiniMax H3 with fal's trim, frame, scale, join and mux tools, SAM 3.1, Scribe v2 and the anchor models already in the catalog. **No live paid run yet**. The fal key test reports a proxy or an outage as "Couldn't check the key", not "Key accepted" |
+ | MCP server | ✅ 1.2.0 tools and prompts by unit tests; the round-2 run with the official MCP Inspector CLI (initialize, tools/list, estimate_cost, generate, check_generations) still applies. Since round 4, part 4, `search_models` leaves out models switched off in Settings → Models & licences (tested); since part 5, a call or plan naming a retired model runs on its replacement (tested) |
+ | `fuobe` CLI | ✅ by tests: the CLI runs as a child process against a stand-in of Fuobe's REST API (upload → generate → wait → download, the MCP bridge, skills add, login, the messages for a missing token or server); the two REST routes it added are tested on the real route handlers. Round 4, part 3's `--look`, `--look-strength` and `--engine` for an Original are tested on the request the CLI builds |
+ | AI-Toolkit training | 🟢 the job flow ran end to end against a fake AI-Toolkit job API (round 2); the style-LoRA preset (moodboards) by unit tests. Round 4, part 4's Soul ID tests every trainer's request against a fake network: the AI-Toolkit configs for Z-Image Turbo, Qwen-Image 2512, FLUX.1 [dev], FLUX.2 [dev] and FLUX.2 [klein] 4B, and fal's eight trainers. No real training run: it needs a GPU or a fal key |
+ | Sign-in and API tokens | ✅ curl and browser checks (round 2); the throttle and Host checks by unit tests. Round 4, part 4: the share routes that skip sign-in, by unit tests and a live signed-out check with a password set |
## 2. Feature matrix vs Higgsfield
@@@ -46,33 -65,37 +66,37 @@@ Model names are the defaults first, the
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
- | Create Image (multi-model) | 🟢 | 56 image models: Nano Banana Pro / 2 / 2.1, Seedream 5.0 Pro / Lite, GPT Image 2.5 Flare / Sunburst, FLUX.3, FLUX.2 [pro], Kontext [max], Ideogram 4.5 / 3.0, Recraft V4.1 / Pro, Qwen Image 3, Wan 2.7 Image, Z-Image Turbo, Imagen 4, Grok Imagine Image 2.0 | Z-Image Turbo, Qwen-Image 2512 (+ Lightning), FLUX.2 [dev] (+ Turbo), FLUX.1 Krea / dev / schnell, HiDream, SDXL | Batch ×1–4, aspect ratios, quality tiers, seeds, negative prompts, references. The Image studio lists text-to-image models only; edit tools live in Edit |
- | Soul 2.0 / Soul Cinema / Soul v1 | 🟢 cloud · 🟡 open | Higgsfield's own API with the Soul style picker | Each preset's description as a prompt template on any open model | Needs a Higgsfield key for the real look. Soul Cinema has one fixed look and no presets, so a look is described in words there |
- | Soul presets (without a key) | 🟢 | `style_id` on the preset's own Soul model; the description in words elsewhere | The description as a prompt template | 106 Soul + 33 Soul 2.0 presets with Higgsfield's ids and categories, generated from the research (`scripts/gen-higgsfield-presets.py`, part of `pnpm gen:catalog`). Used when there is no key, the live list is empty or it fails; live previews are added when a key is set |
- | Soul ID (character training) | 🟢 | Higgsfield Soul ID (Soul 2.0, Soul Cinema) → `custom_reference_id`; fal Z-Image Turbo LoRA trainer | AI-Toolkit job on your GPU → Z-Image Turbo LoRA copied into ComfyUI | Train from an element's photos. A trained element is used when @mentioned on its model |
- | Moodboards | 🟢 | Recraft V4 Styles makes a style from the board's 10 most representative images; the returned `style_id` is reused by "Recraft V4 Styles · saved style". Otherwise the images go as style references on Nano Banana Pro. Curated looks: Soul 2.0 `style_id`. Also Krea 2 Style Reference, FLUX1.1 [pro] (Ultra) Redux | Qwen-Image-Edit Style Reference from 1–2 collages (default), FLUX.2 [klein] / Krea 2 / USO style reference; a Z-Image Turbo style LoRA through AI-Toolkit | `/moodboards` and a Moodboard chip in the Image studio. 5–80 images, ≥256 px, name ≤100 characters, quality meter; status follows the cover job. The `style_id` round trip is tested with a stubbed fal response only |
- | Soul HEX / Color Transfer | 🟢 | Native palettes on Recraft V4.1 / Pro (≤10 colours + background) and Ideogram 3.0; the palette slug on Cinema Studio 4.0; the hex list in the prompt on every other model | Z-Image Turbo · Palette (hex prompt + ColorTransfer lock to a swatch the server renders); other open models get an optional palette-lock step (`oss-palette-image`) | Color signature chip in the Image studio: the 50 Cinema Studio palettes, Upload & Create (k-means over ≤20 photos in a Web Worker), manual editor (≤12 colours, EyeDropper, Use as background). The user's words stay the prompt; Reuse restores the picks |
- | Elements (@characters, locations, props, styles, voices) | ✅ app · 🟢 outputs | Reference images with a legend; video switches to reference-to-video | Same, plus LoRA + trigger word for trained elements | `/elements`; @ menu in every composer and in shots. The mention → reference/LoRA mapping is verified; the outputs need a key or a GPU |
- | Create Video (multi-model) | 🟢 | 65 video models in all: Seedance 2.5 / 2.0, Kling 3.0 / O3 / O1 / 2.6 / 2.5, Veo 3.1 (Fast, Lite), Gemini Omni Flash 1.1, Wan 3.0 / Prime / 2.7 / 2.6 / 2.5, MiniMax H3 / H3 Max / Hailuo, FLUX.3 Video, LTX 2.5, PixVerse V6, Vidu Q3, Luma Ray 3.2, Cinema Studio 4.0, Grok Imagine Video 1.5, Happy Horse 1.1, Genjutsu | Wan 2.2 14B (+ Lightning), Wan 2.2 5B, LTX-2.5 / 2, HunyuanVideo 1.5, Wan VACE | Text, image, start + end frame, references, native audio. Reference clips (`inputs.videos` / `inputs.audios`) go to Seedance 2.5 / 2.0, Cinema Studio 4.0, Wan 3.0, MiniMax H3, and (videos only) Wan 2.7 / 2.6 and Gemini Omni; models that only read images say so |
- | Start & end frame | 🟢 | Kling, Veo, Seedance, Wan, MiniMax, PixVerse, FLUX.3 | Wan 2.2 FLF2V | |
- | Camera motions (DoP presets) | 🟢 | 108 presets on any video model | Wan 2.2 with camera LoRAs on 18 motions, 11 moves via Wan 2.2 Fun Camera, the rest prompt-only | Procedural previews show each move's parallax |
- | Mix (two motions or effects) | 🟢 | The second preset's description joins the prompt, worded by its strength | Both presets' LoRAs stacked, each scaled by its strength | |
- | Effects / Visual Effects / viral presets | 🟢 | 255 effects on any video model | 35 with dedicated LoRAs, the rest prompt-only | Most open effect LoRAs target Wan 2.1 I2V; **quality needs a GPU check** |
- | Multi-shot | 🟢 | Kling 3.0 / O3 native `multi_prompt`; Seedance, Wan 2.6, Cinema Studio get the shots written into the prompt | One clip per shot on the open model, then joined (the join ✅ on CPU) | Off / Auto / Custom; open models have no Auto |
+ | Create Image (multi-model) | 🟢 | 64 image models: Nano Banana Pro / 2 / 2.1, Seedream 5.0 Pro / Flash / Lite, GPT Image 2.5 Flare / Sunburst, FLUX.3, FLUX.2 [pro], Kontext [max], Ideogram 4.5 / 3.0, Recraft V4.1 / Pro, Qwen Image 3, Wan 2.7 Image, Z-Image Turbo, Imagen 4, Grok Imagine Image 2.0, Krea 3, Bria FIBO 2, Ideogram Vector, and hosted open-weight models that take LoRAs: Qwen-Image 2512, Qwen-Image-Edit 2511, FLUX.2 [klein] 4B, Wan 2.2 A14B Image, and (new for Soul ID) FLUX.1 [dev], FLUX.1 Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 9B and Krea 2 Turbo, each with its licence in its tagline | Z-Image Turbo, Qwen-Image 2512 (+ Lightning), FLUX.2 [dev] (+ Turbo), FLUX.1 Krea / dev / schnell, HiDream, SDXL | Batch ×1–4, aspect ratios, quality tiers, seeds, negative prompts, references. The Image studio lists text-to-image models only; edit tools live in Edit. Fuobe Soul, Soul HD and Soul Cinema (both engines, next rows) are listed first. On the open engine a `?model=` link now keeps the linked model (it used to land on Z-Image Turbo). Per-megapixel cloud prices now count every picture asked for. Grok Imagine Image 2.0 takes up to 5 references (fal's edit limit; it took 10 through Higgsfield) |
+ | Soul 2.0 / Soul v1 (139 looks) → Fuobe Soul and Fuobe Soul HD | 🟢 cloud · 🟢 open | Fuobe Soul: Z-Image Turbo on fal (its LoRA endpoint when the look has LoRAs, its image-to-image endpoint for a picture), Replicate's Z-Image Turbo for text to image: $0.005 a megapixel, $0.0085 with LoRAs (the default General look has LoRAs). Fuobe Soul HD: Qwen-Image 2512 on fal, $0.02 a megapixel, $0.035 with LoRAs. No Higgsfield call: Soul 2.0 and Soul v1 themselves are retired (O7), and a stored or linked run on them (`/image?model=soul-2`, Reuse, the API) opens on Fuobe Soul, its Soul style becoming the matching Fuobe look | Fuobe Soul: Z-Image Turbo with up to 3 of the look's LoRAs; image to image on the new `z-image-turbo-i2i` (~12 GB VRAM, no new download). Fuobe Soul HD: Qwen-Image 2512 | Image studio → Look chip on Fuobe Soul and Soul HD: 139 looks in two sets named after Higgsfield's versions, Soul 2.0 (33) and Soul (106), with categories, search, drawn covers and a Strength slider. 87 looks use civitai LoRAs and are marked; without a civitai key a run leaves those out and says so. Attach a picture and the look restyles it (how much is fixed: 0.6 on the GPU, fal's default in the cloud). Soul HD is for lettering; the Graffiti look moves a run there. In a studio feed the browser finishes each result (crop, grade, overlays such as DigitalCam's date stamp) and saves it, keeping the raw picture. Also in ⌘K, `/models`, Canvas (General look only), Assist and the CLI (`--look`, `--look-strength`, `--engine`). The empty Image studio's **Make your own Soul look** cards show on Fuobe Soul and Soul HD (only Soul 2.0 had them). Checked in demo mode; no look's picture has been seen (no GPU, no key) |
+ | Soul Cinema → Fuobe Soul Cinema | 🟢 cloud · 🟢 open | Z-Image Turbo on fal (Replicate for text to image) with the film-still LoRAs, priced as Fuobe Soul. Higgsfield's Soul Cinema is retired; a stored run on it opens on Fuobe Soul Cinema | Z-Image Turbo with the film-still LoRAs | One fixed film look (filmstill 0.7 + moviewide 0.5 and a teal-orange grade) and a 21:9 shape, made at 16:9 and cropped in the browser. A look picked for it is described in words. moviewide is a civitai LoRA, so without a key the cloud runs filmstill only. A 21:9 demo run was cropped with its grade in the browser check. It is now Cinema Studio's still model on both engines, and the Cinema feed finishes it too (`cinema-original.mjs`) |
+ | Soul presets (without a key) | 🟢 | Fuobe Soul's looks on fal or Replicate; a look is words on any other model | Fuobe Soul's looks with their LoRAs; the words on any other open model | Fuobe Soul's 139 looks and the curated moodboards are Fuobe's own: Fuobe ids (`v1-general`, `v2-y2k-studio`…), Fuobe wording and drawn covers, generated from the research by `scripts/gen-soul-originals.py` (part of `pnpm gen:catalog`); each look is a prompt sentence, up to 3 LoRAs, Soul's sizes and a grade or overlay. Higgsfield's old style ids are only read, so older picks still work: a run saved with one opens on Fuobe Soul with the matching look. Higgsfield's Soul models, their style picker and `scripts/gen-higgsfield-presets.py` are gone (round 4, part 5) |
+ | Soul ID (character training) → Fuobe Soul ID (characters and looks) | 🟢 cloud · 🟢 open | fal's trainers, priced first: Z-Image Turbo for Fuobe Soul and Soul Cinema (2,000 steps, ≈ $1.70; a look ≈ $3.39), Qwen-Image 2512 for Soul HD (≈ $1.50), FLUX.1 [dev] (the portrait trainer, characters only, ≈ $6.00), FLUX.2 [dev] (≈ $6.40), FLUX.2 [klein] 4B (≈ $5.00), FLUX.2 [klein] 9B (≈ $4.30) and Krea 2 (≈ $3.00). The LoRA runs on fal's hosted models of its family. Higgsfield Soul ID training is retired, and old Higgsfield Soul IDs no longer go into any run: they show as "Older Soul ID" | AI-Toolkit on your GPU, free, for Z-Image Turbo, Qwen-Image 2512, FLUX.1 [dev], FLUX.2 [dev] and FLUX.2 [klein] 4B (set `AI_TOOLKIT_URL`, or download a training kit). The LoRA is copied into ComfyUI and goes into every open model of its family (Fuobe Soul, Soul Cinema and Z-Image Turbo; Soul HD and Qwen-Image; FLUX.1 [dev] and Krea [dev]; FLUX.2 [dev]) | Elements → an element → Train: 5–80 photos (20+ recommended), a consent tick for a character, and each option's engine, price, time estimate and licence; Train, Retrain (replaces that family's LoRA) or Upgrade (another family, same photos); Train anywhere (an AI-Toolkit kit, or attach a LoRA you trained). A trained LoRA works on every model of its family on both engines (klein 4B, klein 9B and Krea 2 LoRAs run in the cloud only), and the character strength scales it on every model. With no fal key and no AI-Toolkit (Demo mode on "auto", the default), a training is an 8-second demo that trains nothing; the dialog says so. Old Higgsfield Soul IDs offer "Retrain for Fuobe Soul". Checked in demo mode; no real training ran |
+ | Moodboards | 🟢 | Recraft V4 Styles makes a style from the board's 10 most representative images; the returned `style_id` is reused by "Recraft V4 Styles · saved style". Otherwise the images go as style references on Nano Banana Pro. Curated looks: Fuobe Soul's own looks, the look itself on Fuobe Soul and its words on every other model. Also Krea 2 Style Reference, FLUX1.1 [pro] (Ultra) Redux. Train as a look: fal's Z-Image style trainer (≈ $3.39) | Qwen-Image-Edit Style Reference from 1–2 collages (default), FLUX.2 [klein] / Krea 2 / USO style reference. Train as a look: a Z-Image Turbo style LoRA through AI-Toolkit (free). Curated looks: Fuobe Soul with the look's LoRAs | `/moodboards` and a Moodboard chip in the Image studio. 5–80 images, ≥256 px, name ≤100 characters, quality meter; status follows the cover job. The Curated tab shows Fuobe's looks with drawn covers and opens them on Fuobe Soul with the look on the Look chip; nothing is fetched from Higgsfield, and picks saved with Higgsfield's old style ids still work. **Train as a look…** (Retrain once trained) in a board's menu lists Your GPU (Free) and Cloud (≈ $3.39), priced first; a trained board then runs as Fuobe Soul's own look on either engine (before, it ran on Z-Image Turbo on the open engine only, and cloud-only installs didn't show it). The `style_id` round trip is tested with a stubbed fal response only |
+ | Soul HEX / Color Transfer | 🟢 | Native palettes on Recraft V4.1 / Pro (≤10 colours + background) and Ideogram 3.0; the hex list in the prompt on every other model, Fuobe Soul, Soul HD and Soul Cinema included (fal has no colour-match step) | Z-Image Turbo · Palette (hex prompt + ColorTransfer lock to a swatch the server renders); other open models get an optional palette-lock step (`oss-palette-image`). On Fuobe Soul models the hex list goes in the prompt and "Lock the colours after generating" starts on | Color signature chip in the Image studio: the 50 Cinema Studio palettes, Upload & Create (k-means over ≤20 photos in a Web Worker), manual editor (≤12 colours, EyeDropper, Use as background). The user's words stay the prompt; Reuse restores the picks. On a Soul run with the lock on, the look's grade lands on the picture from before the lock (§3) |
+ | Elements (@characters, locations, props, styles, voices) | ✅ app · 🟢 outputs | Reference images with a legend; video switches to reference-to-video | Same, plus LoRA + trigger word for trained elements | `/elements`; @ menu in every composer and in shots. Up to 80 photos an element (was 20); a trained element opens on its family's lead model. The mention → reference/LoRA mapping is verified; the outputs need a key or a GPU |
+ | Create Video (multi-model) | 🟢 | 89 video models in all: Seedance 2.5 / 2.0, Kling 3.0 / O3 / O1 / 2.6 / 2.5, Veo 3.1 (Fast, Lite), Gemini Omni Flash 1.1, Wan 3.0 / Prime / 2.7 / 2.6 / 2.5, MiniMax H3 / H3 Max / Hailuo, FLUX.3 Video, FLUX 3 Max, LTX 2.5, PixVerse V6 / V6 Max, Vidu Q3, Luma Ray 3.2, Grok Imagine Video 1.5 / 1.5 Lite, Happy Horse 1.1, HeyGen Video, Creatify Boreal, P-Video 2 Pro Reference, Pixelcut Looping Video, the hosted open-weight Wan 2.2 A14B and LTX-2.3 22B, which take LoRAs, and Genjutsu's other choices: Wan 2.2 Animate Replace, SCAIL-2, Wan Motion and MiniMax H3 Max Recast | Wan 2.2 14B (+ Lightning), Wan 2.2 5B, LTX-2.5 / 2, HunyuanVideo 1.5, Wan VACE | Text, image, start + end frame, references, native audio. Reference clips (`inputs.videos` / `inputs.audios`) go to Seedance 2.5 / 2.0, Wan 3.0, MiniMax H3, and (videos only) Wan 2.7 / 2.6 and Gemini Omni; models that only read images say so. Fuobe DoP and Fuobe DoP · LTX (both engines) are where camera motions and effects run (next rows). On the open engine "auto" now takes the start frame's shape for every workflow. Happy Horse 1.1 (text, image and reference to video, up to 9 images) runs with a fal key since round 4, part 5: $0.14/s at 720p, $0.18/s at 1080p. Cinema Studio 4.0 and Higgsfield's Genjutsu models are retired (stored runs open on Fuobe Cinema and the Genjutsu Originals) |
+ | Start & end frame | 🟢 | Kling, Veo, Seedance, Wan, MiniMax, PixVerse, FLUX.3, FLUX 3 Max, Fuobe DoP, Fuobe DoP · LTX | Wan 2.2 FLF2V (also as Fuobe DoP), Fuobe DoP · LTX (`ltx23-flf2v-lora`) | Fuobe DoP's Replicate fallback can't make start-and-end clips (fal only) |
+ | Frames (keyframes, Kling 4.0) | 🟢 | FLUX 3 Max follows every frame at its time. Start + end frame models (Kling O3, Seedance…) use the first and last, with a note and a "Use FLUX 3 Max" button | Wan 2.2 14B: one 20-step start/end-frame clip per pair of frames, joined into one film, shown as Free. On Wan 2.2 14B Lightning the strip says it is no faster here and offers plain Wan 2.2 14B | Video studio → Frames chip: up to 10 stills on a timeline; drag the markers or use the keyboard; times snap to 0.1 s, and the open engine needs gaps of at least 0.5 s. Kling 4.0 itself can't be called (fal's route is playground-only), so FLUX 3 Max stands in. Fuobe DoP takes Frames on the open engine only, with the move's LoRAs on each clip; the cloud lists don't offer it for Frames. The open clips are planned and bound in tests; the join ✅ on CPU |
+ | Camera motions (DoP presets) → Fuobe DoP | 🟢 | 108 motions. 59 run on Fuobe DoP's own routes: Fuobe DoP (fal's Wan 2.2 A14B with the move's LoRAs, 38), Fuobe DoP · LTX (fal's LTX-2.3 with its built-in camera LoRA, 17, or a LoRA: Earth Zoom Out, FPV Drone, Flying Cam Transition) and Focus Change on LTX-2.5 Fast's focus shift (about $0.54). The other 49 run on their words on Kling 2.5 Turbo, a partner route until the evaluation measures Fuobe DoP on them. Any other video model gets the move's words | Fuobe DoP: Wan 2.2 14B with the move's LoRAs (42) or Wan 2.2 Fun Camera's pose (21); Fuobe DoP · LTX: LTX-2.3 with its LoRA (3, 32 GB VRAM); Slow Motion on LTX-2.5; the other 41 on Wan 2.2 with words only | Picking a motion, or arriving from `/motions`, switches the Video studio to the move's model with its settings; in the cloud a words-only move keeps the model you picked. Switching engine takes the move along. Fuobe DoP: $0.40 per 5 s at 720p on fal, $0.50 with LoRAs; Replicate fallback for a start frame only. Fuobe DoP · LTX: about $0.18 per 5 s in the cloud. Open: 480p by default (720p in the cloud). Without a civitai key a move whose LoRA is on civitai stops before the job (§3). Procedural previews show each move's parallax. Camera motion and effect presets also work with Frames |
+ | Mix (two motions or effects) | 🟢 | Both presets' LoRAs stacked when both run on the same model, each scaled by the mix strength; otherwise the second joins as words and the run says so | Same: both presets' LoRAs stacked, each scaled by its strength, the same file once | The Replicate fallback takes one LoRA per Wan 2.2 stage, so a Mix is trimmed there |
+ | Effects / Visual Effects / viral presets → Fuobe DoP | 🟢 | 255 effects. 93 run on Fuobe DoP's own routes: 58 with Wan LoRAs, 14 on Fuobe DoP · LTX (Wind to Face and 13 transitions), 15 colour grades and 6 relights. The other 162 run on their words on Kling 2.5 Turbo (partner) | Fuobe DoP with Wan LoRAs (58), Fuobe DoP · LTX (14), LTX-2.5 (Car Drive, Wild Ride); the rest on Wan 2.2 with words, the grades and relights included | 15 colour-grade effects animate without a LoRA; the clip's first next step, "Apply the … grade", opens Color grading with that grade picked. 6 relight effects relight the start frame first (Qwen-Image-Edit 2509 + its Relight LoRA), then animate it; the price includes that step (about $0.035 in the cloud, free on the GPU). The Mixed Media effects run on words (O9). Most open effect LoRAs target Wan 2.1 I2V; **quality needs a GPU check** |
+ | Multi-shot | 🟢 | Kling 3.0 / O3 native `multi_prompt`; Seedance and Wan 2.6 get the shots written into the prompt | One clip per shot on the open model, then joined (the join ✅ on CPU) | Off / Auto / Custom; open models have no Auto |
| Seedance draft mode | 🟢 | Seedance 2.5 480p draft → "Render 1080p" | — | |
- | Cinema Studio 4.0 workspace | 🟢 | Cinema Studio 4.0 (Higgsfield) with native Director fields (genre, era, pacing, light, camera body, lens, aperture, move, palette). With no Higgsfield key or another model picked: Seedance 2.5, Kling 3.0 or Veo 3.1 with the panel compiled into the prompt | Wan 2.2 14B Lightning; a camera LoRA or Fun Camera when there is a start frame; palette lock chained after it (`oss-palette-video`) | `/cinema`, `/cinema/[id]`: projects with cover and cost cap, nested scenes (colour, pin, order), feed (Square / Masonry / List, filters, multi-select), prompt bar (@ elements, # 33 camera moves, references, 4–30 s, batch 1–4), Director's Panel (50 palettes + editor, 7 lighting presets + a 2-light rig, Emotion Wheel), retry as a unit, Trash with Undo, live updates |
- | Cinema Studio Extend (forward / backward) and Edit | 🟡 | Extend: Seedance 2.5 extension. Backward ("prequel"): extract frame → edit a still → start/end-frame clip. Edit: Seedance 2.5 edit (Kling O3 without a Higgsfield key) | Extend forward with Wan 2.2 Fun VACE extend; the prequel the same way on Wan 2.2; edit with Wan 2.2 Fun VACE restyle | The prequel is a 3-step approximation. Cinema Studio 4.0 is capped at 720p on the public API |
- | Cinema Studio image mode and grid | 🟢 | Camera stills (camera, lens, focal length required) on Nano Banana Pro, Seedream 5.0 Pro, Soul Cinema; grids 2×2 / 3×3 / 4×4 (freeform, zooms, shots, next / previous shots) as one sheet | Z-Image Turbo / Qwen-Image stills; Z-Image Turbo · Grid sheet | The sheet is cut into tiles in the browser and stored as uploads |
- | Cinema Studio 3D scene / recomposition | ⬜ | — | — | |
+ | Cinema Studio 4.0 workspace → Fuobe Cinema | 🟢 cloud · 🟢 open | Fuobe Cinema (default): LTX-2.3 22B on fal with sound, 4–30 s (one call makes up to 20 s; a longer take adds an automatic "Extended to N s" step), priced per megapixel of video ($0.001605, $0.001805 with LoRAs; about $0.18 for 5 s at 720p). 14 of the 33 camera moves use LTX-2.3's built-in camera LoRA, with no start frame needed. With a start frame, a move that has a Wan 2.2 LoRA switches the take to Fuobe DoP (16 fps, no sound, with a note) and Rack Focus runs on LTX-2.5 Fast's focus shift; otherwise the move goes into the prompt. Without a civitai key, a move whose LoRA is on civitai runs on its words, with a note. Seedance 2.5, Kling 3.0 and Veo 3.1 stay as choices, with the Director compiled into the prompt. Reference clips move a take to Seedance 2.5 at its partner price, with a note; picking Fuobe Cinema in the menu drops them | Fuobe Cinema (default): Wan 2.2 14B Lightning, 3 or 5 s, 480p or 720p, no sound, free; with a start frame, camera moves take Fuobe DoP's Wan LoRAs (16 of the 33 moves have one) or a Fun Camera pose (14 moves); Handheld, POV, Robot Arm, Snorricam, Tracking and Side Tracking fetch theirs from civitai. LTX-2.5 (with sound) and Wan 2.2 14B as other choices; palette lock chained after it (`oss-palette-video`) | `/cinema`, `/cinema/[id]`: projects with cover and cost cap (a new project starts as "Untitled project"), nested scenes (colour, pin, order), feed (Square / Masonry / List, filters, multi-select), prompt bar (@ elements, # 33 camera moves, references, 4–30 s, batch 1–4; one Director chip on phones), Director's Panel (50 palettes + editor, 7 lighting presets + a 2-light rig, Emotion Wheel), retry as a unit, Trash with Undo, live updates. Fuobe Cinema is first in the model menu with an Original badge and one line per engine; each move shows how it runs (Camera LoRA, LoRA, Fun Camera or Focus move). In the cloud the palette goes into the prompt; the palette lock runs on the GPU only. Cinema Studio 4.0, Soul 2.0 and Higgsfield's Soul Cinema are gone from Cinema's menus and, since O7, from Fuobe: a saved pick falls back to the Original, and a stored take on Cinema Studio 4.0 runs on Fuobe Cinema (its reference takes on Seedance 2.5). A Share button in the header (desktop) and the project menu make a read-only link. `tests/e2e/cinema-original.mjs`; no take has been rendered (no fal key, no GPU) |
+ | Cinema Studio Extend (forward / backward) and Edit | 🟢 cloud · 🟡 open | Extend: LTX-2.3 extend-video on Fuobe Cinema, up to 20 s a run (a partner model with no fal extend route extends through Fuobe Cinema; it used to fall back to Seedance 2.5). Backward ("prequel"): one backward extend-video call (it took 3 steps; partner models still take them). Edit: LTX-2.3 video to video for a take made on Fuobe Cinema, Fuobe DoP or the open engine (the take's scene with the change written in; the first 20 s of a longer take), and Kling O3 for a take made on Seedance 2.5, Kling 3.0 or Veo 3.1 | Extend forward with Wan 2.2 Fun VACE extend; the prequel is a still of the moment before, then Fuobe Cinema's Wan 2.2 14B start/end-frame clip; edit with Wan 2.2 Fun VACE restyle | "Extend or edit this take" carries the take's model, prompt, size and length, so an edit picks the right editor and price. The cloud's 30 s chain and prequel assume fal's extend-video returns the whole clip and honours a backward extend (§3). The open prequel is a 2-step approximation (3 when the browser couldn't read the take's first frame: a cloud step reads it, and without the cloud the prequel is blocked) |
+ | Cinema Studio image mode and grid | 🟢 cloud · 🟢 open | Camera stills (camera, lens, focal length required) on Fuobe Soul Cinema (default), Nano Banana Pro or Seedream 5.0 Pro; grids 2×2 / 3×3 / 4×4 (freeform, zooms, shots, next / previous shots) as one sheet | Fuobe Soul Cinema (default), Z-Image Turbo or Qwen-Image stills; Z-Image Turbo · Grid sheet | The Cinema feed finishes a Fuobe Soul Cinema still in the browser (a 21:9 crop from 16:9 and the teal-orange grade). Cinema's 1K / 2K / 4K map to 720p / 1080p on Fuobe Soul, with a note at 4K. The sheet is cut into tiles in the browser and stored as uploads |
+ | Cinema Studio 3D scene / recomposition | 🟢 | Scene: a Marigold V2 depth map ($0.03) drawn as a point cloud in the browser. Re-render: Nano Banana Pro with the capture and the still, or Qwen Multiple Angles with the still and the flown angles | Scene: a MoGe 2 mesh plus a depth map (runs on a CPU too). Re-render: Qwen-Image-Edit 2511 + the Multiple-Angles LoRA with the capture and the still | "Create 3D scene" on an image take asks first, with the price. Full-screen viewer (three.js, loaded when a scene opens): fly with W A S D Q E, drag, wheel or pinch, touch and a Camera sheet on phones; lens 18–300 mm, aperture f/1.4–f/16 with a depth-of-field preview, a frame in the project's aspects; Capture queues a re-rendered take from that view. MoGe 2 ✅ on CPU; Marigold and the re-renders haven't run for real. `tests/e2e/cinema-scene.mjs` |
-| Cinema AI Director + Project Brief | 🟢 | Claude | Ollama, or an offline storyboard writer | Writes prompts and shot breakdowns into the prompt bar, answers craft questions; never starts a generation. The brief is prepended to every prompt |
+| Cinema AI Director + Project Brief | 🟢 | Claude | A local model (Ollama, LM Studio, Unsloth Studio…), or an offline storyboard writer | Writes prompts and shot breakdowns into the prompt bar, answers craft questions; never starts a generation. The brief is prepended to every prompt |
- | Genjutsu (motion transfer, object swap, restyle) | 🟢 cloud · ⬜ open | Higgsfield Genjutsu models with their look picker | — (Motion control and Shorts restyle on Wan are the closest) | Genjutsu Restyle needs a look; the list comes live from Higgsfield |
- | Motion Control | 🟢 | Kling 3.0 Motion Control, Genjutsu Motion Transfer | Wan Animate 2, Wan 2.2 Fun Control | `/motion-control` |
- | Edit Video | 🟢 | Kling O3 / O1, Kling O3 4K Edit, Gemini Omni Flash 1.1, Seedance 2.5, Wan 2.7, Luma Ray 3.2, FLUX.3 Video, Happy Horse Video Edit, Lucy Edit Pro, Runway Aleph 2, Grok Imagine Video Edit, LTX 2.3 Reference Restyle, Genjutsu Object Swap / Restyle | Wan 2.2 Fun Control, Z-Image Mixed Media | `/video-edit`. Wan 2.2 Fun VACE restyle is a hidden model used by Shorts Studio and Cinema Studio's Edit, not offered here |
+ | Genjutsu (motion transfer, object swap, restyle, insert) → Fuobe Genjutsu | 🟢 cloud · 🟢 open | Fuobe Originals on fal, no Higgsfield: Motion transfer on Wan 2.2 Animate ($0.08/s at 720p; the Lite tier $0.04/s at 480p), Object swap on Wan VACE 14B with a SAM 3.1 mask ($0.08/s plus the mask; Lite $0.04/s), Restyle on Wan 2.2 VACE Fun depth ($0.10/s at 720p). fal bills these by frames ÷ 16, so a 30 fps clip costs about 1.9× the per-second price. Other choices: SCAIL-2, Wan Motion and Kling 3.0 Motion Control (motion); Kling O3 edit, P-Video Replace and hosted Wan 2.2 VACE (swap); Gemini Omni Flash, Kling O3 4K Edit and Happy Horse (restyle). Insert has no Original yet: Kling O3 (say where) or hosted Wan 2.2 VACE (paint the spot). Restyle on Fuobe Soul's 139 looks, 44 Fuobe looks or your own images | Fuobe Genjutsu: Motion on Wan Animate 2 (Lite: 4 steps at 480p); Swap by name on Wan 2.1 VACE + SAM 3.1; Restyle on Wan 2.2 Fun VACE, 480p at 16 fps. Insert by paint: Wan 2.1 VACE | `/genjutsu`: trim 4–30 s, up to 10 references; Object swap by typing, clicking or painting on the first frame, Insert by saying where or painting the spot; price and notes before running, a run never mixes paid and demo steps, before/after, Run again, Copy / Paste setup as a link; "Use in Genjutsu" and "Animate with Genjutsu" on results. Every mode but Insert defaults to a Fuobe Original on both engines. The picker shows each model's source (Fuobe Original, Open weights or Partner) and licence, Originals first, with Lite and full as Quality: Standard / High. Old setup codes and model ids open the replacing Original (a Higgsfield look is dropped). On the open engine, swap is by name only and insert by painting; clicking or painting a swap, and saying where to insert, are cloud only. Checked in demo mode (`tests/e2e/genjutsu-original.mjs`); no real run |
-| Genjutsu Character swap (new: Openjutsu and Akatz Labs' H3 Character Swap) | 🟢 cloud · 🟡 open (its graphs haven't loaded in a ComfyUI yet) | Fuobe Character swap: MiniMax H3 reference-to-video on fal with Akatz Labs' swap LoRA (V1.5 or V1), $0.075/s at 768p, $0.0625/s at 480p, 5–15 s a call; parts up to 30 s run as 15 s pieces, joined under the clip's sound. The first frame: GPT Image 2.5 Sunburst (low quality; billed by tokens, so left out of the estimate) or Nano Banana Pro. Other choices: Wan 2.2 Animate Replace ($0.08/s at 720p), MiniMax H3 Max Recast ($0.30/s at 768p), SCAIL-2, Kling O3 edit and P-Video Replace | Fuobe Character swap: Openjutsu's graph on Akatz Labs' `h3_character_swap` pack (`video-character-swap-h3`), window by window up to 30 s, with Masked generation, an audio guide and a mask margin; the first frame on Qwen-Image-Edit 2511. Other choice: H3 Character Swap · Relay 2.0 (needs `H3_RELAY=1`). About 46 GB of model files; a 24 GB GPU with offloading and 64–128 GB of RAM, 48 GB+ of VRAM advised for 768p | `/genjutsu?mode=character`: the person in a 5–15 s part of one shot becomes your character, keeping the performance and the sound. One character image, 480p or 768p (768p by default), an optional direction and seed. Who: Largest, Leftmost, Rightmost or a number, plus words; on your GPU also Click them. "Make the first frame first" (on by default) puts your character into the part's first frame before the swap; if that fails, the swap still runs and says so. "Describe my character" (Claude or Ollama in the cloud, Ollama with a vision model on your GPU) and "Use the clip's words" (Scribe v2 or Qwen3-ASR) help write the prompt. Advanced: who speaks, the swap LoRA release (None only on your GPU). The page lists the limits and the GPU the open route was tested on, and warns about hard cuts it finds in the browser. Each model shows its licence line (MiniMax H3's terms, §3). For whole clips, shot by shot, **Open in Character Swap Studio** makes a studio project with the clip and the character (next row). Checked in demo mode; no H3 run anywhere |
++| Genjutsu Character swap (new: Openjutsu and Akatz Labs' H3 Character Swap) | 🟢 cloud · 🟡 open (its graphs haven't loaded in a ComfyUI yet) | Fuobe Character swap: MiniMax H3 reference-to-video on fal with Akatz Labs' swap LoRA (V1.5 or V1), $0.075/s at 768p, $0.0625/s at 480p, 5–15 s a call; parts up to 30 s run as 15 s pieces, joined under the clip's sound. The first frame: GPT Image 2.5 Sunburst (low quality; billed by tokens, so left out of the estimate) or Nano Banana Pro. Other choices: Wan 2.2 Animate Replace ($0.08/s at 720p), MiniMax H3 Max Recast ($0.30/s at 768p), SCAIL-2, Kling O3 edit and P-Video Replace | Fuobe Character swap: Openjutsu's graph on Akatz Labs' `h3_character_swap` pack (`video-character-swap-h3`), window by window up to 30 s, with Masked generation, an audio guide and a mask margin; the first frame on Qwen-Image-Edit 2511. Other choice: H3 Character Swap · Relay 2.0 (needs `H3_RELAY=1`). About 46 GB of model files; a 24 GB GPU with offloading and 64–128 GB of RAM, 48 GB+ of VRAM advised for 768p | `/genjutsu?mode=character`: the person in a 5–15 s part of one shot becomes your character, keeping the performance and the sound. One character image, 480p or 768p (768p by default), an optional direction and seed. Who: Largest, Leftmost, Rightmost or a number, plus words; on your GPU also Click them. "Make the first frame first" (on by default) puts your character into the part's first frame before the swap; if that fails, the swap still runs and says so. "Describe my character" (Claude or a local model in the cloud, a local vision model on your GPU) and "Use the clip's words" (Scribe v2 or Qwen3-ASR) help write the prompt. Advanced: who speaks, the swap LoRA release (None only on your GPU). The page lists the limits and the GPU the open route was tested on, and warns about hard cuts it finds in the browser. Each model shows its licence line (MiniMax H3's terms, §3). For whole clips, shot by shot, **Open in Character Swap Studio** makes a studio project with the clip and the character (next row). Checked in demo mode; no H3 run anywhere |
+ | Character swap for whole clips (new: Akatz Labs' H3 Character Swap workbench) → Character Swap Studio | 🟢 cloud · 🟡 open (its two graphs haven't loaded in a ComfyUI yet) | MiniMax H3 reference-to-video on fal with Akatz Labs' swap LoRA (V1.5 or V1): $0.075/s at 768p, $0.0625/s at 480p, whole seconds, at least 5 s a take. No mask: the whole frame is regenerated and who to swap goes into the prompt; a continuing segment gets the take before's last frame. fal's trim cuts each segment out and fits the take back to its length. Masks: SAM 3.1 ($0.015/s) shows who it would pick; the swap doesn't use it. Words: ElevenLabs Scribe v2. Anchors: GPT Image 2.5 Sunburst (billed by tokens, not in the estimate) or Nano Banana Pro (about $0.15). Assembly: fal's scale-video and merge-videos at 24 fps, then the clip's sound | A new H3 Relay 2.0 graph (`video-character-swap-h3-segment`) swaps only the person in your approved mask, matches the anchor and continues from the take before's lossless master; a new SAM 3.1 graph (`video-mask-h3-relay`) makes the mask from any frame of the shot. Words: Qwen3-ASR. Anchors: Qwen-Image-Edit 2511. Each clip gets a free 24 fps copy on import. Free; a 24 GB GPU, the opt-in H3 Relay pack (`H3_RELAY=1`) and PR #12's H3 files (no new downloads) | `/character-swap`, `/character-swap/[id]` (sidebar → Studios, after Genjutsu): one character (picture and description) and up to 20 clips (.mp4, .mov, .mkv, .webm or .avi, each up to 149.66 s and 200 MB), back with their own timing and sound at 24 fps. Seven stages: **Shots** (Detect edits finds the cuts in the browser; fix them; Replace character or Keep original per shot), **Words** (Transcribe, who speaks each line, Build shot prompts), **Who to swap** (largest, leftmost, rightmost, person #n or words, plus Include / Exclude clicks on any frame; Track shot and Update frame make mask versions you approve), **Scene anchors** (make or Import a still of the scene with your character, approve one), **Segments** (5, 10 or 15 s, each Starts fresh or Continues previous, queued one, from here or all, each priced; a continuation starts itself when the take before is done, even with the page closed), **Takes & review** (several takes, Compare, Keep / Maybe / Skip with notes, Export decisions as JSON) and **Assemble** (the chosen takes over the original timeline with the clip's sound, to download and in the Library). Settings per shot (swap LoRA, 480 or 768, window, history, seed, anchor and mask on or off; the mask on your GPU only) and per segment. Prices show before anything runs, except a cloud **browser copy** of a clip the browser can't play (AVI, or an unsupported codec), billed per compute second. Removing a clip or re-cutting shots stops jobs nothing uses any more. The Finish stage (a clean background plate and cut-outs) shows as "Not available", with the reason. Demo mode runs the whole flow for free. `tests/e2e/character-swap-studio.mjs`; nothing has run on a GPU or with a fal key (§3) |
+ | Motion Control | 🟢 | Kling 3.0 Motion Control (default), Fuobe Genjutsu · Motion and its Lite tier (Wan 2.2 Animate on fal), SCAIL-2, Wan Motion | Wan Animate 2 (default), Fuobe Genjutsu · Motion, Wan 2.2 Fun Control | `/motion-control`; links to Genjutsu's Character swap |
+ | Edit Video | 🟢 | Kling O3 / O1, Kling O3 4K Edit, Gemini Omni Flash 1.1, Wan 2.7, Luma Ray 3.2, FLUX.3 Video, Happy Horse Video Edit, Lucy Edit Pro, Runway Aleph 2, Grok Imagine Video Edit, LTX 2.3 Reference Restyle, Fuobe Genjutsu · Restyle. Seedance 2.5's edit (Higgsfield only) is gone: a request for it runs on Kling O3 edit, with a note | Wan 2.2 Fun Control, Z-Image Mixed Media | `/video-edit`, with a link to Genjutsu for swaps and restyles. Wan 2.2 Fun VACE restyle is a hidden model used by Shorts Studio, Genjutsu and Cinema Studio's Edit, not offered here |
| Extend video | 🟢 | Seedance 2.5, MiniMax H3 Max, PixVerse V6, FLUX.3, Veo 3.1; Kling via last frame → image-to-video → join | Wan 2.2 Fun VACE extend; the last frame comes from the open Extract frame workflow (✅ on CPU) | `/extend`, "Extend" tile action |
- | Reframe video | 🟢 | Luma Ray 3.2, LTX Reframe, hosted Wan VACE | Wan 2.2 Fun VACE reframe | `/reframe` |
+ | Reframe video | 🟢 | Luma Ray 3.2, LTX Reframe, hosted Wan VACE, MiniMax H3 Max Reframe | Wan 2.2 Fun VACE reframe | `/reframe` |
| Draw to Video | 🟢 | Annotated first frame + instructions on any image-to-video model | Wan-Move: brush strokes become motion paths | Paint tools in the Video studio |
| Shorts Studio | 🟢 | Gemini Omni Flash (default), Kling O3 4K Edit and Happy Horse Video Edit (both read references), Lucy Edit Pro, Runway Aleph 2, LTX 2.3 Reference Restyle, Wan 2.7. Per segment: trim → centre-crop to 9:16 / 16:9 when needed (fal `scale-video`) → restyle; joined, then the original sound muxed back | Cut a resampled segment (≤81 frames at 16 fps) → restyle its first frame with Qwen-Image-Edit 2511 → Wan 2.2 Fun VACE restyle with depth → join → mux | `/shorts`, `/shorts/[id]`: 44 presets plus custom presets from ≤10 references; MP4 / MOV (WebM headers are read too), 4 s–2 min, ≤200 MB; segments with takes, Regenerate, Stitch again, Download full video or parts; prices per resolution. Cutting, joining and muxing ✅ on CPU; the restyle needs a GPU or a key |
- | Mixed Media | 🟡 cloud · 🟢 open | Trim → LTX 2.3 Reference Restyle anchored on a Nano Banana 2 preview still → original sound | Z-Image Turbo img2img + Fun Union ControlNet per frame at 4–24 fps (VHS meta-batch) | `/mixed-media`: 33 presets with per-preset settings, preview frame, History with Try again. The cloud route is a video-to-video restyle, not Higgsfield's per-frame stylization. Meta-batch passes ✅ on CPU (self-test graph) |
+ | Mixed Media | 🟢 cloud · 🟢 open | Restyle switch. **Per frame** (default, like Higgsfield): trim → every Nth frame taken (fal extract-nth-frame) → each frame redrawn by Nano Banana 2 (default, fixed seed) or Seedream 5.0 Flash, in lanes of 12 that start from the approved preview → images-to-video → joined when over 200 frames → original sound. **Fast**: trim → one video-to-video pass (LTX 2.3 Reference Restyle by default; Lucy Edit Pro, Gemini Omni Flash, Kling O3 4K edit, Happy Horse video edit, Wan 2.7, Runway Aleph 2) anchored on a Nano Banana 2 preview still → original sound | Z-Image Turbo img2img + Fun Union ControlNet per frame at 4–24 fps (VHS meta-batch); unchanged | `/mixed-media`: 33 presets with per-preset settings, preview frame, History with Try again. Per frame: a frame rate from 4 to 24 FPS and 1K / 2K / 4K (Seedream 5.0 Flash up to 2K; a 4K render of over 200 frames is drawn at 2K), priced as "N frames × $X a frame" before you render (10 s filmed at 30 FPS, at the 8 FPS setting: every 4th frame, 75 frames × $0.08 = $6.00 at 1K). A failed render names the frame ("Frame 14 of 16 failed"), frames still waiting stop before they're paid for, and Try again redraws only what didn't finish (`GET /api/mixed-media/progress?id=`). Meta-batch passes ✅ on CPU (self-test graph); the per-frame chain ran in demo mode only, including an injected frame failure and Try again |
| Storyboards (Popcorn) | 🟢 | Nano Banana Pro, each frame made from the previous one | Z-Image / Qwen-Image-Edit, then Qwen-Image-Edit + next-scene LoRA | `/storyboard`: up to 8 frames; the board is named after the idea |
| Storyboard → film | 🟢 | Seedance 2.5 start + end frame per pair, clips joined | Wan 2.2 Lightning start/end frame, joined on ComfyUI | "Make the film" once every frame is done |
@@@ -80,20 -103,25 +104,25 @@@
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
- | Edit image (instruction edit) | 🟢 | Any edit model (Nano Banana Pro, Seedream 5.0, GPT Image 2.5, FLUX.2 / Kontext, Qwen Image 3…): the image plus up to 6 references, within each model's own limit | Qwen-Image-Edit 2511, FLUX.1 Kontext [dev], FLUX.2 [dev] (up to 3 images in all) | `/edit`, with the new Bria Extract Object. Ideogram Remove Background is a Layers tool; Recraft Vectorize and Image to SVG (VTracer) run only from a Canvas model node (no studio page offers them) |
- | Inpaint / Draw to Edit | 🟢 | Native mask routes (GPT Image, Ideogram, FLUX Fill [pro], Z-Image) in each API's convention; a red-tinted copy + instructions elsewhere | FLUX.1 Fill [dev] | `/inpaint`, compare slider in the viewer |
- | Layers | ✅ editor · 🟡 AI tools | Decompose: Seedream 5.0 Layers (default), Seedream 5.0 Flash Layers, Qwen-Image Layered (hosted). Edit text: Ideogram 3.0 Text Layers detects, Nano Banana Pro or Seedream 5.0 Pro edits. Background: BiRefNet, Ideogram. Regional edit: Seedream 5.0 Pro, Nano Banana Pro. Upscale: Topaz, SeedVR2, Recraft Crisp. Relight, Expand: Nano Banana Pro. Angles: Qwen Multiple Angles | Qwen-Image-Layered (a named element runs on Layered-Control), Qwen-Image-Edit 2511 (typed text lines, regional edit, angles), RMBG, FLUX Kontext, ESRGAN / SeedVR2, Qwen relight, FLUX Fill | `/layers`, `/layers/[id]`: canvas (move, resize, rotate, masks), Layers panel, per-layer prompt with revisions, history and versions, Compare, Cropped / Positioned zips and PNG at full detail, Copy JSON, Color grading (WebGL); phones get a read-only view. "Open in Layers" on every image result. The editor and the browser-built downloads ran end to end on demo layers; the AI tools that exist are built against verified schemas and validated graphs. Not built: open-source text detection, Higgsfield's Inpaint and Enhancer tools, comments, Save as Element |
- | Color Grading (free, in the browser) | ✅ | — (WebGL in the browser) | same | `/color-grade`: Higgsfield's five looks plus seven film looks, manual controls, PNG / WebM export into the library; looks preview on a bundled sample before an upload |
- | Expand (outpaint), Upscale image | 🟢 | Expand: Nano Banana Pro (Expand Image and Zoom Out apps). Upscale: Topaz, SeedVR2, Recraft Crisp | FLUX Fill outpaint, 4x ESRGAN, SeedVR2 | `/upscale`; the Expand Image and Zoom Out apps |
- | Upscale video (+ FPS boost, SDR→HDR, pro codecs) | 🟡 | Topaz Video, SeedVR2 Video | SeedVR2, ESRGAN video | Upscaling only. FPS boost, SDR→HDR and ProRes / EXR output ⬜ (the open RIFE interpolation model runs only from a Canvas model node) |
- | Video tools: remove background, relight, depth | 🟢 | BiRefNet video, Bria video, Video Depth Anything, LightX relight | BiRefNet / SAM 3 matte, Bernini-R relight, Depth Anything 3 / VDA | `/video-tools`. Remove object ⬜ (Edit video with a prompt is the closest) |
+ | Edit image (instruction edit) | 🟢 | Any edit model (Nano Banana Pro, Seedream 5.0, GPT Image 2.5, FLUX.2 / Kontext, Qwen Image 3, Krea 3, Bria FIBO 2…): the image plus up to 6 references, within each model's own limit | Qwen-Image-Edit 2511, FLUX.1 Kontext [dev], FLUX.2 [dev] (up to 3 images in all) | `/edit`, with Bria Extract Object. Promptless models (e.g. FASHN) get no prompt suggestions. Ideogram Remove Background is a Layers tool |
+ | Inpaint / Draw to Edit | 🟢 | Native mask routes (GPT Image, Ideogram, FLUX Fill [pro], Z-Image) in each API's convention; a red-tinted copy + instructions elsewhere | FLUX.1 Fill [dev] | `/inpaint`, compare slider in the viewer. With a mask-only model (FLUX Fill), Generate asks to paint the area once the image is in |
+ | Layers | ✅ editor · 🟢 AI tools (cloud and open) · 🟡 Enhancer | Decompose: Seedream 5.0 Layers (default), Seedream 5.0 Flash Layers, Qwen-Image Layered (hosted). Edit text: Ideogram 3.0 Text Layers (default) or Florence-2 OCR detects, Nano Banana Pro or Seedream 5.0 Pro edits. Inpaint: Nano Banana Pro (shown a red-tinted copy), FLUX.1 Fill [pro] or Z-Image Turbo Inpaint (they take the mask). Enhancer: Skin, Soft glow and Sharpen on Nano Banana Pro or Seedream 5.0 Pro; Detail (2×) on Topaz or SeedVR. Background: BiRefNet, Ideogram. Regional edit: Seedream 5.0 Pro, Nano Banana Pro. Upscale: Topaz, SeedVR2, Recraft Crisp. Relight, Expand: Nano Banana Pro. Angles: Qwen Multiple Angles | Qwen-Image-Layered (a named element runs on Layered-Control), OvisOCR3 text detection (~3 GB VRAM), Qwen-Image-Edit 2511 (text edits, regional edit, angles, the Enhancer's looks), FLUX.1 Fill [dev] (Inpaint), RMBG, FLUX Kontext, ESRGAN / SeedVR2 (also the Enhancer's Detail at 2×), Qwen relight, FLUX Fill | `/layers`, `/layers/[id]`: canvas (move, resize, rotate, masks), Layers panel, per-layer prompt with revisions, history and versions, Compare, Cropped / Positioned zips and PNG at full detail, Copy JSON, Color grading (WebGL); phones get a read-only view. "Open in Layers" on every image result. Edit text has a Detector picker on both engines (typing the lines still works); a see-through layer is put on a white or black backdrop first. Inpaint (paint an area, say what goes there) and the Enhancer give a new version or a new layer. Save as element in each layer's menu (Character, Prop or Style, with an `@handle`). "Keep transparency" starts on only when the layer has see-through pixels. The editor and the browser-built downloads ran end to end on demo layers; the new tools were checked in the demo-mode browser on both engines, and no AI tool has run with real keys or on a GPU. The Enhancer is Fuobe's approximation of Higgsfield's single skin-enhancer job. Not built: comments |
+ | Color Grading (free, in the browser) | ✅ | — (WebGL in the browser) | same | `/color-grade`: Higgsfield's five looks plus seven film looks, 14 more from Fuobe DoP's grade effects, and Invert and Solarize (sliders and presets, also used by two Soul looks); manual controls, PNG / WebM export into the library; looks preview on a bundled sample before an upload. `/color-grade?preset=<id>` opens with a grade picked (a graded DoP clip's "Apply the … grade" step lands here) |
+ | Expand (outpaint), Upscale image | 🟢 | Expand: Nano Banana Pro (Expand Image and Zoom Out apps). Upscale: Topaz, SeedVR2, Recraft Crisp | FLUX Fill outpaint, 4x ESRGAN, SeedVR2 | `/upscale`; the Expand Image and Zoom Out apps. Bria Expand is in the catalog, but no studio page offers it |
+ | Upscale video | 🟢 | Topaz Video (Original / 1080p / 1440p / 4K, 24 / 30 / 60 fps; $0.01/s at 720p, $0.02/s at 1080p, $0.06/s above, doubled at 60 fps), Topaz Starlight, ByteDance Upscale (up to 8K), FLUX.3 Upscale, SeedVR2 (to a size, 1080p by default) | SeedVR2 or Real-ESRGAN in passes of a few frames, 720p to 2160p (1080p by default) | `/upscale/video`. A line under the clip says what will come out, and prices use the clip's real length. A size that wouldn't enlarge the clip moves up: a 1080p clip now goes to 1440p on Topaz ($0.06/s), where it used to become 4K at $0.02/s. This applies to every caller, Canvas included. Real-ESRGAN in passes ✅ on CPU with stand-in weights |
+ | FPS boost and slow motion | 🟢 | Topaz FPS Boost (24–120 fps, 2× / 4× / 8× slow motion), RIFE (hosted) | RIFE 4.26 (default) or FILM | `/upscale/fps`: "24 → 60 fps · 2× slow motion · 5 s → 10 s" under the clip. The open graph ✅ on CPU with stand-in weights; it still loads the whole clip (§3) |
+ | SDR to HDR | ✅ open · 🟢 cloud | Topaz SDR to HDR (H.265 10-bit, ProRes 422 HQ), LTX 2.3 HDR (EXR frames) | ComfyUI's inverse tone map: HLG or HDR10 MP4, or EXR frames, with a peak-brightness slider | `/upscale/hdr`. A format the picked model can't write moves the run to the model that can, and the list says so. EXR results download as a .zip. The open HDR10 (PQ) and EXR graphs ✅ on CPU through the API (no model needed) |
+ | Pro codecs (ProRes, EXR…) | ✅ open · — cloud | — (Topaz SDR to HDR writes ProRes 422 HQ) | Export: ProRes 422 HQ / 4444, H.265 10-bit, FFV1 lossless, H.264, EXR frames; free | `/upscale/export`, open engine only; without ComfyUI the tab links to Topaz's ProRes on the cloud. ProRes and FFV1 results show as a file card ("made for your editor"). ProRes, H.265 10-bit, FFV1 and EXR ✅ on CPU (no model needed) |
+ | Video tools: remove background, relight, depth | 🟢 | BiRefNet video, Bria video, SAM 3.1 (keeps only what you name, alpha mask only, $0.015/s), Video Depth Anything, LightX relight | BiRefNet / SAM 3 matte, Bernini-R relight, Depth Anything 3 / VDA | `/video-tools`. Remove background has an Output picker (cut-out or alpha mask) and makes only that file; SAM models need "what to keep". Depth map has a Color map picker (five on the cloud, grayscale or inferno on open VDA, grayscale on DA3) and Side by side. The Video Background Remover app mattes the whole video (BiRefNet video on both engines) |
+ | Remove object (video) | 🟢 | Type it: Kling O3 edit (default, $0.168/s), Kling O3 4K, Bria erase, LTX 2.3 clean plate (people). Click it: Bria keypoints, or a SAM 3.1 track → Bria mask erase. Paint it: SAM 3.1 tracks the paint → Bria mask erase. "Shadows and reflections too": VOID | Type it: Wan 2.1 VACE 14B + SAM 3.1. Paint it: Wan VACE with the painted mask tracked by SAM 3.1. "Shadows and reflections too": VOID on CogVideoX-5B. A person, by name: H3 Person Removal (MiniMax H3 with Akatz Labs' Person Remover LoRA; not the default, needs `H3_RELAY=1`, and its graph hasn't loaded in a ComfyUI yet). Click it: not on the open engine (the page says so) | `/video-tools/remove-object`: up to 60 s of a clip (≤200 MB), the price first, a SAM 3.1 mask preview of the first 2 s, before/after wipe, Download. Long clips are cut into pieces (cloud) or frame-exact windows (open), erased one by one and joined, and the sound is put back. The model-free parts ✅ on CPU; the erasers need a key or a GPU |
| Join clips, match colours of a video (Color Palette) | ✅ open · 🟢 cloud (join only) | fal FFmpeg merge; there is no cloud video colour match (the Match Colors app re-grades images with Nano Banana Pro) | ComfyUI concat and palette transfer, both run for real on CPU | Video tools tabs |
- | Trim video | ✅ open · 🟢 cloud | fal `trim-video` | Trim Video (core nodes, keeps the audio) | Video tools → Trim: filmstrip + in/out picker. Ran on CPU through the production build |
- | Captions (transcribe, edit, burn in) | ✅ open burn-in and cue editing · 🟢 transcription and cloud burn-in | Transcribe: ElevenLabs Scribe v2 (also Wizper, Whisper). Burn: VEED Subtitles (your edited lines as SRT) or Auto Subtitle (quick karaoke, ignores edits) | Transcribe: Qwen3-ASR 0.6B + ForcedAligner. Burn: Fuobe's chunked core-node burn-in (`oss-captions-burnin`); Whisper captions with `NC_PACKS=1` | Video tools → Captions: cue editor (text, timing, split / merge / insert / remove, undo), import .srt / .vtt, 6 styles incl. karaoke with a live preview, export .srt / .vtt. Each burner shows only the controls it supports |
- | Image to 3D / product spin | 🟢 | Hunyuan3D 3.1 Pro (default) / Rapid, TRELLIS.2, Tripo H3.1, Meshy 7.1 | Pixal3D (default: MoGe-2 camera, ~250k-triangle textured GLB), TRELLIS.2 (the fallback, MIT), Hunyuan3D 2.1 (shape only, territory-restricted licence). Before the job shows as done the server finishes each GLB in about a second (`src/server/model3d-finish.ts`: roughness floor by material, pivot at the bottom, meshopt + WebP web GLB); after it, one at a time and at low priority, it renders a 96-frame 24 fps turntable on the CPU when Chromium and ffmpeg are there, and adds it to the result (the card shows its progress) | `/image-to-3d` and an app: cards play the turntable, the orbitable viewer (web GLB, meshopt decoder from `/vendor`) loads only when opened, downloads (the raw GLB), turntable (the server's, or recorded in the browser: 96 frames, 24 fps, WebCodecs), "Animate the spin" |
- | Try-On, Angles, Product Shot apps | 🟢 | FASHN Try-On 1.6 (also Google, Leffa); Qwen Multiple Angles (rotate / tilt / zoom); Bria Product Shot | FLUX.2 [klein] 4B + try-on LoRA; Qwen-Image-Edit 2511 + Multiple-Angles LoRA; Qwen-Image-Edit 2509 + White_to_Scene LoRA | The old approximation notes are gone; the notes now say what the open route runs. Try-on needs the person and the garment |
- | Relight, Skin Enhancer, Headshots, Packshot, Face/Character Swap, Transitions… | 🟢 | 123 apps: 121 on both engines, 2 open-only | Relight LoRA, ReActor, Qwen-Image-Edit… | Match Lighting, Match Colors, Hook Frame (formerly the Virality Predictor app; its old `/apps/app-virality-predictor` URL now redirects to `/virality`) |
- | Approximated apps | 🟡 | — | — | 17 apps are marked as approximations on their page (e.g. one silent clip where Higgsfield beat-matches several), out of 41 with a parity note (what the Fuobe or open version does differently) |
+ | Trim video | ✅ open · 🟢 cloud | fal `trim-video` | Trim Video (core nodes, keeps the audio) | Video tools → Trim: the shared trimmer (filmstrip, draggable window and handles, keyboard sliders, play the selection, typed times); for a clip the browser can't decode, only its header is read for the length. Ran on CPU through the production build |
+ | Captions (transcribe, edit, burn in) | ✅ open burn-in and cue editing · 🟢 transcription and cloud burn-in | Transcribe: ElevenLabs Scribe v2 (also Wizper, Whisper). Burn: VEED Subtitles (your edited lines as SRT) or Auto Subtitle (quick karaoke, ignores edits) | Transcribe: Qwen3-ASR 0.6B + ForcedAligner. Burn: Fuobe's chunked core-node burn-in (`oss-captions-burnin`); Whisper captions (ComfyUI-Whisper, now installed by default; `NC_PACKS=0` leaves it out) | Video tools → Captions: cue editor (text, timing, split / merge / insert / remove, undo), import .srt / .vtt, 6 styles incl. karaoke with a live preview, export .srt / .vtt. Each burner shows only the controls it supports |
-| Image to 3D / product spin, plus 3D from several photos, from text, a picked object, splats, rigging | 🟢 | From an image: Hunyuan3D 3.1 Pro (default) / Rapid, TRELLIS.2, Tripo H3.1, Meshy 7.1. From several images: Meshy 7.1 Multi-view (≈ $1.20). From text: Tripo H3.1 (≈ $0.20). Pick an object: SAM 3D Objects, now asked for a textured GLB. Splat: TripoSplat ($0.05). Rig & animate: Meshy Rigging ($0.20, +$0.12 with an animation) | From an image: TRELLIS.2 (textured GLB + turntable MP4, MIT), Hunyuan3D 2.1 (shape only, territory-restricted licence). From several images: TRELLIS.2 Multi-view (the front plus 1–3 sides; a 5.58 GB download; 16 GB VRAM, unverified). From text: Z-Image Turbo draws the object, then TRELLIS.2 builds it. Splat: TripoSplat (.spz + an orbit video). No open Pick an object or rigging; the page offers the cloud or From an image | `/image-to-3d` and an app: a mode picker (From an image, From several images, From text, Pick an object, Splat; also `?mode=` and `?model=`), the price before you run, licence lines for open models, orbitable GLB viewer, downloads, turntable (TRELLIS.2's, or recorded in the browser for mesh-only models), "Animate the spin". Rig & animate on a finished model: a skeleton with walk and run cycles, or one of 30 curated Meshy animations in 6 groups (any other by its number, up to 696); the dialog starts on Casual walk ($0.32); a rigged model plays its animation here and in the Library. A splat gets a .spz / .ply download and a pointer to a viewer such as SuperSplat; Fuobe doesn't draw splats yet. A cloud model's extra formats (OBJ, FBX, USDZ…) and previews are now stored with the result. "Built with DINOv3" shows under TRELLIS.2 and TripoSplat results on both engines. Checked in demo mode; no GPU or paid run |
++| Image to 3D / product spin, plus 3D from several photos, from text, a picked object, splats, rigging | 🟢 | From an image: Hunyuan3D 3.1 Pro (default) / Rapid, TRELLIS.2, Tripo H3.1, Meshy 7.1. From several images: Meshy 7.1 Multi-view (≈ $1.20). From text: Tripo H3.1 (≈ $0.20). Pick an object: SAM 3D Objects, now asked for a textured GLB. Splat: TripoSplat ($0.05). Rig & animate: Meshy Rigging ($0.20, +$0.12 with an animation) | From an image: Pixal3D (default: MoGe-2 camera, ~250k-triangle textured GLB; its own 5.58 GB download), TRELLIS.2 (the fallback, MIT), Hunyuan3D 2.1 (shape only, territory-restricted licence). From several images: TRELLIS.2 Multi-view (the front plus 1–3 sides; a 5.58 GB download; 16 GB VRAM, unverified). From text: Z-Image Turbo draws the object, then TRELLIS.2 builds it. Splat: TripoSplat (.spz + an orbit video). No open Pick an object or rigging; the page offers the cloud or From an image. Before an open GLB job shows as done, the server finishes the model in about a second (`src/server/model3d-finish.ts`: roughness floor by material, pivot at the bottom, meshopt + WebP web GLB); after it, one at a time and at low priority, it renders a 96-frame 24 fps turntable on the CPU when Chromium and ffmpeg are there, and adds it to the result (the card shows its progress), in place of the one the multi-view graph renders | `/image-to-3d` and an app: a mode picker (From an image, From several images, From text, Pick an object, Splat; also `?mode=` and `?model=`), the price before you run, licence lines for open models, cards that play the turntable, the orbitable viewer (the web GLB, with the meshopt decoder from `/vendor`), which loads only when opened, downloads (the raw GLB), turntable (the server's, TripoSplat's orbit, or recorded in the browser: 96 frames, 24 fps, WebCodecs), "Animate the spin". Rig & animate on a finished model: a skeleton with walk and run cycles, or one of 30 curated Meshy animations in 6 groups (any other by its number, up to 696); the dialog starts on Casual walk ($0.32); a rigged model plays its animation here and in the Library. A splat gets a .spz / .ply download and a pointer to a viewer such as SuperSplat; Fuobe doesn't draw splats yet. A cloud model's extra formats (OBJ, FBX, USDZ…) and previews are now stored with the result. "Built with DINOv3" shows under TRELLIS.2 and TripoSplat results on both engines, and under Pixal3D's. Checked in demo mode, and the finish, the turntable runner and the browser recorder by tests (`model3d-finish`, `model3d-runner`, `model3d-webm`); no GPU or paid run through Fuobe yet |
+ | Vectorize (image → SVG) | ✅ open · 🟢 cloud | Recraft Vectorize | VTracer through ComfyUI (ComfyUI-ToSVG; no AI model) | The Vectorize app (Utility). VTracer is crisp on logos and flat art and makes many small shapes on photos. SVG results are stored as .svg and offer Download and Favorite, not raster hand-offs. VTracer ran on a CPU ComfyUI |
+ | Try-On, Angles, Product Shot apps | 🟢 | FASHN Try-On 1.6 (also Google, Leffa); Qwen Multiple Angles (rotate / tilt / zoom); Bria Product Shot | FLUX.2 [klein] 4B + try-on LoRA; Qwen-Image-Edit 2511 + Multiple-Angles LoRA; Qwen-Image-Edit 2509 + White_to_Scene LoRA | The notes say what the open route runs. Try-on needs the person and the garment |
+ | Relight, Skin Enhancer, Headshots, Packshot, Face/Character Swap, Transitions… | 🟢 | 124 apps: 122 on both engines, 2 open-only | Relight LoRA, ReActor, Qwen-Image-Edit… | Match Lighting, Match Colors, Hook Frame (formerly the Virality Predictor app; its old `/apps/app-virality-predictor` URL now redirects to `/virality`), Vectorize (new) |
+ | Approximated apps | 🟡 | — | — | 16 apps are marked as approximations on their page (e.g. one silent clip where Higgsfield beat-matches several), out of 42 with a parity note (what the Fuobe or open version does differently) |
### Characters, lipsync, audio
@@@ -108,93 -137,140 +138,140 @@@
| Voice cloning | 🟢 | Chatterbox and IndexTTS-2 (hosted) | Chatterbox, IndexTTS-2 | From a mic recording or an upload; saved as Voice elements |
| Dialogue | 🟢 | ElevenLabs Dialogue | Chatterbox Dialogue | |
| Voice change | 🟢 | ElevenLabs Voice Changer, Chatterbox VC (hosted) | Chatterbox Voice Conversion | |
- | Translate & dub | 🟢 open and cloud one-shot · 🟡 cloud step by step | One shot: HeyGen Translate / Translate Speed, ElevenLabs Dubbing. Step by step: ElevenLabs Voice Isolation → Scribe v2 → Claude → review → ElevenLabs v4 per take → fal compose (each take at its cue) → extract the track → Chatterbox VC (the speaker's voice) → Sync Lipsync 3 | MelBand RoFormer stems + Qwen3-ASR 1.7B cues (one job) → local LLM → review → Chatterbox per take in the cloned voice → voice timeline (core nodes) → InfiniteTalk lip re-sync → mux over the background stem (−3 dB) | Audio → Translate: spoken language + up to 8 targets, prices before Translate and Voice, autosaved cue editor, lip re-sync toggle, Voice again. The voice follows the reviewed cue times and the video keeps its length. The timeline step ✅ on CPU. **Cloud step by step keeps the voice only** (no background stem) |
- | Sound effects | 🟢 | Mirelo SFX 2.0 (default, Higgsfield's model), Sonilo SFX 1.1, Stable Audio 3 SFX, Stable Audio 2.5, CassetteAI, Seed Audio 1.0, ElevenLabs SFX | Stable Audio 3 Small SFX (default; Stability Community licence, free under US$1M revenue), Stable Audio Open 1.0, HunyuanVideo-Foley, MMAudio (non-commercial) | Audio → Sound effects. ThinkSound (isolated worker) is a hidden catalog model with a validated workflow; no studio offers it yet |
- | Music | 🟢 | Sonilo Music 1.1 (default, Higgsfield's model), Lyria 3 / Pro, MiniMax Music 2.5, Stable Audio 3 Music, Stable Audio 2.5, Mureka 9.5, ElevenLabs Music | ACE-Step 1.5 | Audio → Music |
+ | Translate & dub | 🟢 | One shot: HeyGen Translate / Translate Speed, ElevenLabs Dubbing. Step by step: Demucs splits the soundtrack while ElevenLabs Voice Isolation → Scribe v2 make the cues → Claude → review → ElevenLabs v4 per take → fal compose (each take at its cue) → extract the track → Chatterbox VC (the speaker's voice) → Sync Lipsync 3 → the voice mixed over the drums, bass and other stems, 3 dB under their level (fal loudnorm, then compose) | MelBand RoFormer stems + Qwen3-ASR 1.7B cues (one job) → local LLM → review → Chatterbox per take in the cloned voice → voice timeline (core nodes) → InfiniteTalk lip re-sync → mux over the background stem (−3 dB) | Audio → Translate: spoken language + up to 8 targets, prices (split and mix included) before Translate and Voice, autosaved cue editor, lip re-sync toggle, Voice again. The voice follows the reviewed cue times and the video keeps its length. If the cloud split fails or finds nothing but the voice, the dub says it is voice only. The timeline step ✅ on CPU |
+ | Sound effects | 🟢 | Mirelo SFX 2.0 (default; the one Higgsfield uses), Sonilo SFX 1.1, Stable Audio 3 SFX, Stable Audio 2.5, CassetteAI, Seed Audio 1.0, ElevenLabs SFX | Stable Audio 3 Small SFX (default; Stability Community licence, free under US$1M revenue), Stable Audio Open 1.0, HunyuanVideo-Foley, MMAudio (non-commercial), ThinkSound (on the isolated worker) | Audio → Sound effects. ThinkSound runs only on the isolated worker; its packages are installed there but it has never run |
+ | Music | 🟢 | Sonilo Music 1.1 (default; the one Higgsfield uses), Lyria 3 / Pro, MiniMax Music 2.5, Stable Audio 3 Music, Stable Audio 2.5, Mureka 9.5, ElevenLabs Music | ACE-Step 1.5 | Audio → Music. Audio → Loop / extend makes a track longer |
+ | Audio loop / extend and join | ✅ open · 🟢 cloud | fal merge-audios: whole plays of the clip, and joins with hard cuts (up to 5 files a call, chained) | Crossfaded loops (equal power or linear), a fade-out and an exact length; joins with crossfades in one job | Audio → Loop / extend (`/audio/loop`, up to 10 min) and Join (`/audio/join`, 2–10 clips); price and summary before running. Every audio result offers "Loop / extend". Both open graphs ✅ on CPU through the API |
| Sound for a video | 🟢 | Mirelo SFX 2.0 for video (default), MMAudio | HunyuanVideo-Foley fed the clip's frames (default; as long as the clip, ≤30 s), MMAudio | Audio → Sound for video. HunyuanVideo-Foley's licence excludes the EU, UK and South Korea |
- | Transcription and voice separation | 🟢 | ElevenLabs Scribe v2, Wizper, Whisper; Demucs stems, ElevenLabs Voice Isolation | Qwen3-ASR; MelBand RoFormer + Qwen3-ASR | Text results carry timed cues (saved as .srt); stems carry `meta.stem`. Used by captions, dubbing and Faceless |
- | Text steps (translate, write) | 🟢 | Claude (`text-llm`) | A local model on Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server (`oss-text-llm`, never calls Claude) | Translations keep the cue timing (numbered batches of 30, then 10, then line by line). Settings → AI helper → Offline rewriter (`FUOBE_ENHANCE_PROVIDER=none`) turns text steps off |
+ | Transcription and voice separation | 🟢 | ElevenLabs Scribe v2, Wizper, Whisper; Demucs stems, ElevenLabs Voice Isolation | Qwen3-ASR; MelBand RoFormer + Qwen3-ASR | Audio → Transcribe on both engines, with a Spoken language picker (Detect automatically, or one of the model's languages; also on Canvas nodes). Text results carry timed cues (saved as .srt); stems carry `meta.stem`. Used by captions, dubbing and Faceless |
-| Text steps (translate, write) | 🟢 | Claude (`text-llm`) | A local model on Ollama (`oss-text-llm`, never calls Claude); when Ollama isn't running, translation runs on ComfyUI's Qwen3.5 4B | Translations keep the cue timing (numbered batches of 30, then 10, then line by line), on either open backend. Writing still needs Ollama. Settings → Prompt enhancement → Offline rewriter (`FUOBE_ENHANCE_PROVIDER=none`) turns text steps off |
++| Text steps (translate, write) | 🟢 | Claude (`text-llm`) | A local model on Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server (`oss-text-llm`, never calls Claude); when none is ready, translation runs on ComfyUI's Qwen3.5 4B | Translations keep the cue timing (numbered batches of 30, then 10, then line by line), on either open backend. Writing still needs a local model. Settings → AI helper → Offline rewriter (`FUOBE_ENHANCE_PROVIDER=none`) turns text steps off |
### Studios & marketing
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
-| Brand kit + products | 🟢 | Website research needs no model; Claude fills the soft fields (tone, audience, selling points) | Ollama, or offline heuristics | Reads HTML meta, OpenGraph, JSON-LD, Shopify `/products.json`, CSS colours, Google fonts, logo, hero images and socials through the SSRF-safe fetch; 14 rotating research labels, Cancel / Retry. Manual path with k-means colours. Products from a link or an upload. The scraper ran against local fixture shops, not real sites |
+| Brand kit + products | 🟢 | Website research needs no model; Claude fills the soft fields (tone, audience, selling points) | A local model, or offline heuristics | Reads HTML meta, OpenGraph, JSON-LD, Shopify `/products.json`, CSS colours, Google fonts, logo, hero images and socials through the SSRF-safe fetch; 14 rotating research labels, Cancel / Retry. Manual path with k-means colours. Products from a link or an upload. The scraper ran against local fixture shops, not real sites |
- | Marketing Studio | 🟢 | Per format: Bria Product Shot / Nano Banana Pro / GPT Image 2.5 / Product Photography (product shots), GPT Image 2.5 / Ideogram 4.5 / 3.0 / Recraft V4.1 (ads, posters, listings), Marketing Studio Image (Higgsfield, with a key), Seedance 2.5 / Kling O3 / Gemini Omni (motion), OmniHuman 2 / Kling Avatar (UGC). UGC chain: ElevenLabs v4 → Nano Banana Pro still → OmniHuman 2 presenter → Auto Subtitle → Seedance 2.5 hook and b-roll → joined | Qwen-Image / Qwen-Image-Edit stills (words set in the browser), Wan 2.2 Lightning motion; UGC: Chatterbox (voice sample needed) → Qwen-Image-Edit → InfiniteTalk → caption burn-in → joins that keep the voice | `/marketing`: 84 Fuobe templates in 11 formats with procedural previews, 9 hooks and 14 settings, product / avatar / reference slots, brand kit chip, live price, Run again. Higgsfield's library has 1,074 templates; Fuobe ships its own set |
- | Click to Ad / Link to Video Ad | 🟢 | Same UGC models, or product-only shots; 9:16, ≤12 s, voiceover and captions | Same open UGC chain | `/marketing/click-to-ad`: link → "Building your product kit" → 10 styles → script (Claude, a local model or an offline writer within the word budget). The product joins its site's brand kit, so logo and colours persist. The two old parity apps now open this flow. No logo end card in the video |
- | Ads Studio | 🟢 | Higgsfield Ads Studio one-shot (with a key), or Fuobe: Claude copy (angle, headline, body, CTA) + Nano Banana Pro visual + compositing in the browser | Qwen-Image-Edit / Qwen-Image visual + the same compositing; local-model or rule-based copy | `/ads`, `/ads/[brandId]`: brands, up to 10 products × up to 20 ads, 1:1 / 4:5 / 9:16 with logo, colours and Google fonts, editor, Download all (zip built in the browser), brand chat with @product mentions and priced proposals |
- | Ad Multiplier | 🟢 | Seedance 2.5 edit (Higgsfield), Kling O3 edit, Gemini Omni Flash. Hook / CTA: first or last frame → image-to-video → joined around the original | Wan 2.2 Animate + the original sound muxed back; hook / CTA on Wan 2.2 Lightning, joined keeping the reference's sound | `/ads/multiplier`: 4–30 s reference, up to 20 @image_N, Prompt or Change hook / Change CTA, 480p / 720p / 1080p (open ≤720p), 1–4 versions, live estimate |
- | Faceless Studio | 🟢 | Nano Banana Pro stills, Gemini Omni Flash clips (Seedance 2.5 in Advanced), ElevenLabs v4 / Multilingual v2 or a Chatterbox clone, ElevenLabs forced alignment, Sonilo music levelled to −28 LUFS and mixed by fal FFmpeg compose, Auto Subtitle; Upscale to 1080p with SeedVR2 | Z-Image Turbo or Qwen-Image-Edit Style Reference stills, Wan 2.2 Lightning, Chatterbox (voice sample needed), ACE-Step (≤240 s) mixed by the soundtrack workflow, Qwen3-ASR timings + caption burn-in | `/faceless`: channels (genre, idea, YouTube reference, saved look and sound, avatar), topics, 1–5 min, 12 styles or 3 style references, narrator, script review, then a two-stage render (stills + narration + word timings, then each scene cut to where its lines are spoken). Timeline editor: change a scene's picture, motion or the narration, see the price, Undo. Deleting stops the render |
- | Higgsfield Explainer | 🟡 | Same pipeline as Faceless | Same; stills drawn from your source images with Qwen-Image-Edit | `/explainer`: 22 styles, up to 3 sources (images, .txt / .md, a summarised link), Auto / 20 s–10 min / Manual 15–600 s, History. PDF and Word sources aren't read (Higgsfield takes documents), hence 🟡 |
- | Katana | 🟢 | Per segment: cut → first frame → your subject put in (Nano Banana Pro) → motion with Kling O3 edit, Genjutsu Motion Transfer or Kling 3.0 Motion Control; joined at the original cut times over the original soundtrack | Same chain with Qwen-Image-Edit, Wan 2.2 Animate / Fun Control | `/katana` plus a `katana` Assist / MCP tool and a skill. Scene cuts found in the browser and refined to a frame; Retry failed steps; Run again |
+ | Marketing Studio | 🟢 | Per format: Bria Product Shot / Nano Banana Pro / GPT Image 2.5 / Product Photography (product shots), GPT Image 2.5 / Ideogram 4.5 / 3.0 / Recraft V4.1 (ads, posters, listings), Seedance 2.5 / Kling O3 / Gemini Omni (motion), OmniHuman 2 / Kling Avatar (UGC). UGC chain: ElevenLabs v4 → Nano Banana Pro still → OmniHuman 2 presenter → Auto Subtitle → Seedance 2.5 hook and b-roll → joined | Qwen-Image / Qwen-Image-Edit stills (words set in the browser), Wan 2.2 Lightning motion; UGC: Chatterbox (voice sample needed) → Qwen-Image-Edit → InfiniteTalk → caption burn-in → joins that keep the voice | `/marketing`: 84 Fuobe templates in 11 formats with procedural previews, 9 hooks and 14 settings, product / avatar / reference slots, brand kit chip, live price, Run again. The composer stays slim until a template is picked or something is added. Higgsfield's library has 1,074 templates; Fuobe ships its own set. Higgsfield's Marketing Studio Image model is retired: a stored run on it moves to GPT Image 2.5 until O10 |
-| Click to Ad / Link to Video Ad | 🟢 · end card ✅ open (CPU), 🟢 cloud | Same UGC models, or product-only shots; 9:16, ≤12 s, voiceover and captions. End card: the card drawn in the browser becomes a 2.5 s zoom (fal's Ken Burns) with a silent track, joined after the ad (fal merge-videos); an API call with no drawn card gets the kit's logo on its accent colour (fal overlay-image) | Same open UGC chain. End card: `video-append-endcard` on core nodes (CPU, no model download); still-to-clip plus a sound-keeping join when ComfyUI didn't encode the ad | `/marketing/click-to-ad`: link → "Building your product kit" → 10 styles → script (Claude, Ollama or an offline writer within the word budget). The product joins its site's brand kit, so logo and colours persist. The two old parity apps now open this flow. **End card** switch with a live 9:16 preview: accent colour, logo (or brand name), product, an editable call to action ("Shop now") and the shop's web address; on by default when the product kit has a logo; adds 2.5 s, included in the price. The open end card ran twice on a CPU ComfyUI (§1); the cloud one hasn't run with a real key |
-| Ads Studio | 🟢 | Claude copy (angle, headline, body, CTA) + Nano Banana Pro visual + compositing in the browser, until O10 | Qwen-Image-Edit / Qwen-Image visual + the same compositing; Ollama or rule-based copy | `/ads`, `/ads/[brandId]`: brands, up to 10 products × up to 20 ads, 1:1 / 4:5 / 9:16 with logo, colours and Google fonts, editor, Download all (zip built in the browser), brand chat with @product mentions and priced proposals. The "Made by Higgsfield / Fuobe" picker is gone: every ad is made this way, in all three formats; ads Higgsfield drew whole stay as they were, and Retry remakes them this way |
++| Click to Ad / Link to Video Ad | 🟢 · end card ✅ open (CPU), 🟢 cloud | Same UGC models, or product-only shots; 9:16, ≤12 s, voiceover and captions. End card: the card drawn in the browser becomes a 2.5 s zoom (fal's Ken Burns) with a silent track, joined after the ad (fal merge-videos); an API call with no drawn card gets the kit's logo on its accent colour (fal overlay-image) | Same open UGC chain. End card: `video-append-endcard` on core nodes (CPU, no model download); still-to-clip plus a sound-keeping join when ComfyUI didn't encode the ad | `/marketing/click-to-ad`: link → "Building your product kit" → 10 styles → script (Claude, a local model or an offline writer within the word budget). The product joins its site's brand kit, so logo and colours persist. The two old parity apps now open this flow. **End card** switch with a live 9:16 preview: accent colour, logo (or brand name), product, an editable call to action ("Shop now") and the shop's web address; on by default when the product kit has a logo; adds 2.5 s, included in the price. The open end card ran twice on a CPU ComfyUI (§1); the cloud one hasn't run with a real key |
++| Ads Studio | 🟢 | Claude copy (angle, headline, body, CTA) + Nano Banana Pro visual + compositing in the browser, until O10 | Qwen-Image-Edit / Qwen-Image visual + the same compositing; local-model or rule-based copy | `/ads`, `/ads/[brandId]`: brands, up to 10 products × up to 20 ads, 1:1 / 4:5 / 9:16 with logo, colours and Google fonts, editor, Download all (zip built in the browser), brand chat with @product mentions and priced proposals. The "Made by Higgsfield / Fuobe" picker is gone: every ad is made this way, in all three formats; ads Higgsfield drew whole stay as they were, and Retry remakes them this way |
+ | Ad Multiplier | 🟢 | Kling O3 edit (default) or Happy Horse video edit, both keeping the ad's sound and recreating at most the first 15 s (a longer selection is cut, with a note), or Gemini Omni Flash (prompt only). Hook / CTA: first or last frame → image-to-video → joined around the original | Fuobe Genjutsu · Motion (Wan Animate 2) + the original sound muxed back; hook / CTA on Wan 2.2 Lightning, joined keeping the reference's sound | `/ads/multiplier`: 4–30 s reference picked with the shared trimmer, up to 20 @image_N, Prompt or Change hook / Change CTA, 480p / 720p / 1080p (open ≤720p), 1–4 versions, live estimate |
+ | Faceless Studio | 🟢 | Nano Banana Pro stills, Gemini Omni Flash clips (Seedance 2.5 in Advanced); Frame by frame: fal's Ken Burns zoom (no video model, list price $0.001 a request); ElevenLabs v4 / Multilingual v2 or a Chatterbox clone, ElevenLabs forced alignment, Sonilo music (played again for long films) levelled to −28 LUFS and mixed by fal FFmpeg compose, Auto Subtitle; Upscale to 1080p with SeedVR2 | Z-Image Turbo or Qwen-Image-Edit Style Reference stills, Wan 2.2 Lightning; Frame by frame: a Ken Burns pan and zoom on core nodes (no GPU needed for the motion), joined by packet copy; Chatterbox (voice sample needed), ACE-Step (≤240 s, looped with crossfades up to 600 s) mixed by the soundtrack workflow, Qwen3-ASR timings + caption burn-in; Upscale to 1080p with Real-ESRGAN in passes, free | `/faceless`: channels (genre, idea, YouTube reference, saved look and sound, avatar), topics, 1–5 min, 12 styles or 3 style references, narrator, script review, then a two-stage render (stills + narration + word timings, then each scene cut to where its lines are spoken). Frame by frame aims each move at what the scene's words name. Timeline editor: change a scene's picture, motion (camera moves only in Frame by frame) or the narration, see the price, Undo. Deleting stops the render. The open upscale is tested through the API in demo mode only. A channel with a style brief (only Content Factory makes them) follows it: the brief's look, camera and music words go into the prompts, scenes are paced by it, captions take its words per caption and position, and episodes can be 30 s long |
-| Content Factory (faceless series from a reference) | 🟢 cloud · 🟢 open | Reading the reference: frames (fal extract-frames, about one a second) and a transcript (ElevenLabs Scribe v2), written into a brief by Claude (up to 20 frames) or Ollama (Settings → Prompt enhancement; a text-only Ollama model uses only the transcript). Episodes: Faceless Studio's cloud pipeline | Reading: Gemma 4 E4B on ComfyUI reads the first 30 s with their sound (`reference-brief-gemma4`, ~12 GB VRAM, needs ComfyUI-VideoHelperSuite). Episodes: Faceless Studio's open pipeline | `/content-factory`, `/content-factory/[id]` (sidebar → Studios): upload a clip (MP4, MOV, WebM), paste a TikTok, Instagram or web-page link (YouTube links and pages with no video ask for an upload), or pick one of 8 preset styles. The editable brief covers format, hook, pacing, look, music and narrator; in demo mode, with the Offline rewriter, or when the LLM doesn't answer, a simpler offline brief is used and marked as such. Compose: topic, 30 s to 5 min, 1–10 episodes, animation style, genre, 9:16 or 16:9, narrator, optional script review; the whole series' price first. **Generate here** makes a Faceless channel that carries the brief, starts one episode per title and opens the series page (episodes, brief, Next episode, Delete series). **Generate in Claude** gives a `claude mcp add` line and a prompt for Claude Code, which uses the existing `faceless_episode` MCP tool; nothing is sent. Checked in demo mode; no real fal, Scribe or Claude call and no Gemma 4 run |
++| Content Factory (faceless series from a reference) | 🟢 cloud · 🟢 open | Reading the reference: frames (fal extract-frames, about one a second) and a transcript (ElevenLabs Scribe v2), written into a brief by Claude (up to 20 frames) or a local model (Settings → AI helper; a text-only model uses only the transcript). Episodes: Faceless Studio's cloud pipeline | Reading: Gemma 4 E4B on ComfyUI reads the first 30 s with their sound (`reference-brief-gemma4`, ~12 GB VRAM, needs ComfyUI-VideoHelperSuite). Episodes: Faceless Studio's open pipeline | `/content-factory`, `/content-factory/[id]` (sidebar → Studios): upload a clip (MP4, MOV, WebM), paste a TikTok, Instagram or web-page link (YouTube links and pages with no video ask for an upload), or pick one of 8 preset styles. The editable brief covers format, hook, pacing, look, music and narrator; in demo mode, with the Offline rewriter, or when the LLM doesn't answer, a simpler offline brief is used and marked as such. Compose: topic, 30 s to 5 min, 1–10 episodes, animation style, genre, 9:16 or 16:9, narrator, optional script review; the whole series' price first. **Generate here** makes a Faceless channel that carries the brief, starts one episode per title and opens the series page (episodes, brief, Next episode, Delete series). **Generate in Claude** gives a `claude mcp add` line and a prompt for Claude Code, which uses the existing `faceless_episode` MCP tool; nothing is sent. Checked in demo mode; no real fal, Scribe or Claude call and no Gemma 4 run |
+ | Higgsfield Explainer | 🟢 | Same pipeline as Faceless | Same; stills drawn from your source images with Qwen-Image-Edit | `/explainer`: 22 styles, up to 3 sources (images, .txt / .md, PDF and Word .docx up to 20 MB, a summarised link), Auto / 20 s–10 min / Manual 15–600 s, History. A long document is summarised by the engine's text model, and a long PDF says how many of its pages were read; .doc, scanned PDFs and damaged files get a clear message |
+ | Katana | 🟢 | Per segment: cut → first frame → your subject put in (Nano Banana Pro) → motion with Kling O3 edit, Fuobe Genjutsu · Motion (Wan 2.2 Animate on fal, 1 reference) or Kling 3.0 Motion Control; joined at the original cut times over the original soundtrack | Same chain with Qwen-Image-Edit, Fuobe Genjutsu · Motion (Wan Animate 2) / Wan 2.2 Fun Control | `/katana` plus a `katana` Assist / MCP tool and a skill. Scene cuts found in the browser and refined to a frame; Retry failed steps; Run again. A saved job naming Higgsfield's Genjutsu Motion Transfer or Wan Animate 2 opens Fuobe Genjutsu · Motion |
| Virality Predictor | 🟡 | — | — | `/virality` runs a clearly labelled heuristic check of the first 3 seconds in the browser and shows no score. Higgsfield's output matches Meta's TRIBE v2 (CC BY-NC); its worker contract is in [`docs/workers/tribe-v2.md`](workers/tribe-v2.md), but Fuobe doesn't host it |
- | Photodump Studio / Instadump | 🟢 | Soul 2.0 + Soul ID with a key, else Nano Banana Pro or Seedream 5.0 Pro | The character's Z-Image Turbo LoRA when trained, else Qwen-Image-Edit 2511 | `/photodump`: 9 Photodump packs + 5 Instadump packs (one Fuobe prompt per photo), Create pack from ≤15 photos, a selfie (≤20 MB) or a character, Download all, Animate, Edit, Retry a failed photo inside its run |
- | Fashion Factory | 🟢 | Soul 2.0 / Nano Banana Pro base shots, FASHN try-on (Nano Banana Pro as the alternative), Nano Banana Pro photoset | Z-Image Turbo (+ character LoRA), FLUX.2 [klein] try-on, Qwen-Image-Edit photoset | `/fashion-factory`: 6 templates, the 5 steps with Higgsfield's copy; progress survives a reload |
- | Canvas (node workflows) | 🟡 | Any cloud model on a node | Any open model on a node | `/canvas`, `/canvas/[id]` on @xyflow/react: 13 node types (text prompt, image / video / audio input, element, model, join, extract frame, upscale, remove background, speech, output / compare, note), typed edges, Run node / selected / all, fresh results reused, pins, autosave, phone node list. 5 templates, each in a cloud and an all-open-source version. Higgsfield's pages (nested canvases), tables, comments, drawing and shapes, Change Voice / Translate nodes and multiplayer aren't built |
+ | Photodump Studio / Instadump | 🟢 | Fuobe Soul with the character's Soul ID, else Nano Banana Pro or Seedream 5.0 Pro with their photos | Fuobe Soul with the character's Soul ID, else Qwen-Image-Edit 2511 | `/photodump`: 9 Photodump packs + 5 Instadump packs (one Fuobe prompt per photo), Create pack from ≤15 photos, a selfie (≤20 MB) or a character, Download all, Animate, Edit, Retry a failed photo inside its run |
+ | Fashion Factory | 🟢 | Base shots on Fuobe Soul with the character's Soul ID, else Nano Banana Pro; FASHN try-on (Nano Banana Pro as the alternative), Nano Banana Pro photoset | Base shots on Fuobe Soul with the character's Soul ID, else Qwen-Image-Edit; FLUX.2 [klein] try-on, Qwen-Image-Edit photoset | `/fashion-factory`: 6 templates, the 5 steps with Higgsfield's copy; progress survives a reload |
-| Canvas (node workflows) | 🟡 · board ✅ in the browser · new nodes 🟢 (the open Video concatenator ✅ on CPU) | Any cloud model on a node. Change voice: ElevenLabs Voice Changer, or hosted Chatterbox for a cloned voice. Translate: text through the app's text model, video through ElevenLabs Dubbing. Video concatenator: fal's trim, scale, silent-track mux and merge (joins of at most 24) | Any open model on a node. Change voice: Chatterbox VC. Translate: text through Ollama or ComfyUI's Qwen3.5; video starts a Translate & dub session (open-source-only installs). Video concatenator: the new `video-fit-clip` (CPU, no model) per clip, then the packet-copy join | `/canvas`, `/canvas/[id]` on @xyflow/react: 18 node types (text prompt, image / video / audio input, element, model, join, extract frame, upscale, remove background, speech, Change voice, Clone voice, Translate, Video concatenator, Table, output / compare, note), typed edges (now with a Voice type), Run node / selected / all, fresh results reused, pins, autosave, phone node list. On desktop: page tabs (up to 20, Undo on delete), a toolbar with keys (V Select, H Pan, D Draw, E Eraser, N Note, ⇧T Table, R Shapes, T Text, C Comment), drawing and shapes in six ink colours, groups (⌘/Ctrl+G) with Run group showing the node count and price, and comment pins with replies. Dragging the empty board draws a selection box; scroll or H pans, pinch or ⌘/Ctrl-scroll zooms. Clone voice records, uploads or picks a saved voice. The Video concatenator joins up to 50 clips, each cut and muted on its own, in 8 aspect ratios at 30 fps. A Table (up to 8 columns × 50 rows) runs the node it feeds once per row. Phones get a page picker over the read-only board. Model nodes take the round-4 operations that have a visible model: remove object, swap and insert, keyframes, SDR to HDR, export, OCR, the open 3D scene, splat, text to 3D and vectorize; a Fuobe Soul node keeps its own engine and uses the General look. Ken Burns, audio loop, extract frames, images to video and overlay have input ports, but only hidden helper models, which node pickers leave out; rigging and audio joins aren't offered on nodes. Element nodes follow a later rename. 7 templates, each in a cloud and an all-open-source version (new: "Clips → one film" and "Table → shots → film"; the talking-avatar template's voice sample is now a Clone voice node). Not built: nested groups, a Folder node, comment reactions, multiplayer |
++| Canvas (node workflows) | 🟡 · board ✅ in the browser · new nodes 🟢 (the open Video concatenator ✅ on CPU) | Any cloud model on a node. Change voice: ElevenLabs Voice Changer, or hosted Chatterbox for a cloned voice. Translate: text through the app's text model, video through ElevenLabs Dubbing. Video concatenator: fal's trim, scale, silent-track mux and merge (joins of at most 24) | Any open model on a node. Change voice: Chatterbox VC. Translate: text through a local model or ComfyUI's Qwen3.5; video starts a Translate & dub session (open-source-only installs). Video concatenator: the new `video-fit-clip` (CPU, no model) per clip, then the packet-copy join | `/canvas`, `/canvas/[id]` on @xyflow/react: 18 node types (text prompt, image / video / audio input, element, model, join, extract frame, upscale, remove background, speech, Change voice, Clone voice, Translate, Video concatenator, Table, output / compare, note), typed edges (now with a Voice type), Run node / selected / all, fresh results reused, pins, autosave, phone node list. On desktop: page tabs (up to 20, Undo on delete), a toolbar with keys (V Select, H Pan, D Draw, E Eraser, N Note, ⇧T Table, R Shapes, T Text, C Comment), drawing and shapes in six ink colours, groups (⌘/Ctrl+G) with Run group showing the node count and price, and comment pins with replies. Dragging the empty board draws a selection box; scroll or H pans, pinch or ⌘/Ctrl-scroll zooms. Clone voice records, uploads or picks a saved voice. The Video concatenator joins up to 50 clips, each cut and muted on its own, in 8 aspect ratios at 30 fps. A Table (up to 8 columns × 50 rows) runs the node it feeds once per row. Phones get a page picker over the read-only board. Model nodes take the round-4 operations that have a visible model: remove object, swap and insert, keyframes, SDR to HDR, export, OCR, the open 3D scene, splat, text to 3D and vectorize; a Fuobe Soul node keeps its own engine and uses the General look. Ken Burns, audio loop, extract frames, images to video and overlay have input ports, but only hidden helper models, which node pickers leave out; rigging and audio joins aren't offered on nodes. Element nodes follow a later rename. 7 templates, each in a cloud and an all-open-source version (new: "Clips → one film" and "Table → shots → film"; the talking-avatar template's voice sample is now a Clone voice node). Not built: nested groups, a Folder node, comment reactions, multiplayer |
### Platform & agents
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
- | Supercomputer / Assist agent | 🟢 | Claude (claude-opus-5-5 by default; Manual offers claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-1 with an effort level) | A local model's tool calling (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or the offline rule-based planner | `/assist`: plans, prices, asks first (or auto-runs), chains steps with `after`. Modes Free / Smart / Manual; each chat's context is frozen when it starts and later changes arrive as "Context update" messages |
- | Assist skills | ✅ app · 🟢 with an LLM | Loaded into Claude's context with `/name` or `load_skill` | Same on a local model; the offline planner uses their hints | 20 built-in SKILL.md playbooks in `skills/`; create, edit, duplicate, download, turn on / off, upload .md / .zip / .skill (bounded unzip). Also offered as MCP prompts |
-| Supercomputer / Assist agent | 🟢 | Claude (claude-opus-5-5 by default; Manual offers claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-1 with an effort level) | Ollama tool calling, or the offline rule-based planner | `/assist`: plans, prices, asks first (or auto-runs), chains steps with `after`. Modes Free / Smart / Manual; each chat's context is frozen when it starts and later changes arrive as "Context update" messages. The offline planner can make several takes and animate the one you pick ("animate 2"). `search_models` describes the Fuobe Originals as running on both engines, and a generate job can name a Soul `look` and an `engine` (without one it follows the user's engine). Models switched off in Settings → Models & licences leave `search_models` and the offline planner's picks. A plan naming a retired model runs on its replacement. Scheduled tasks and connectors: next rows |
-| Assist skills | ✅ app · 🟢 with an LLM | Loaded into Claude's context with `/name` or `load_skill` | Same on Ollama; the offline planner uses their hints | 20 built-in SKILL.md playbooks in `skills/`, in the Agent Skills format; their studio links open the real studios. Create, edit, duplicate, download, turn on / off, upload .md / .zip / .skill (bounded unzip). Also offered as MCP prompts |
++| Supercomputer / Assist agent | 🟢 | Claude (claude-opus-5-5 by default; Manual offers claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-1 with an effort level) | A local model's tool calling (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or the offline rule-based planner | `/assist`: plans, prices, asks first (or auto-runs), chains steps with `after`. Modes Free / Smart / Manual; each chat's context is frozen when it starts and later changes arrive as "Context update" messages. The offline planner can make several takes and animate the one you pick ("animate 2"). `search_models` describes the Fuobe Originals as running on both engines, and a generate job can name a Soul `look` and an `engine` (without one it follows the user's engine). Models switched off in Settings → Models & licences leave `search_models` and the offline planner's picks. A plan naming a retired model runs on its replacement. Scheduled tasks and connectors: next rows |
++| Assist skills | ✅ app · 🟢 with an LLM | Loaded into Claude's context with `/name` or `load_skill` | Same on a local model; the offline planner uses their hints | 20 built-in SKILL.md playbooks in `skills/`, in the Agent Skills format; their studio links open the real studios. Create, edit, duplicate, download, turn on / off, upload .md / .zip / .skill (bounded unzip). Also offered as MCP prompts |
| Assist projects | ✅ app · 🟢 with an LLM | — | — | Instructions, colour, up to 20 sources (links and PDFs fetched safely, files with PDF text, elements, notes), project skills, chats per project, an Assets tab |
| Assist memory | ✅ app · 🟢 with an LLM | — | — | 8 categories, add / edit / delete, import from other assistants, per project or across all chats; the `remember` tool asks first |
- | Studio jobs from Assist and MCP | 🟡 | `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, `katana` | Same on the open engine (`faceless_episode` needs a voice sample there) | Each runs as a `createPipeline` job and is priced on the approval card first. They don't open a studio session yet, so there is no dub review, Layers project or Shorts session to continue in (see §3) |
- | AI Employees, Apps builder, Websites, Games, 3D Jutsu, connectors (Slack, Drive, Notion…) | ⬜ | — | — | |
- | MCP (other agents use the studio) | ✅ | — | — | `/api/mcp` 1.1.0: search_models, estimate_cost, estimate_job, generate, create_storyboard, check_generations, list_recent, list_elements, list_skills, load_skill, read_source, remember and the studio tools; prompts built from the enabled skills |
- | CLI + skills (`npx skills add …`), ChatGPT plugin | ⬜ | — | — | Skills are SKILL.md files that MCP clients receive as prompts; there is no Fuobe CLI or ChatGPT app |
-| Assist scheduled tasks | ✅ app (demo mode) · 🟢 with an LLM | Claude plans (with your Anthropic key); generations are priced at fal / Replicate prices and counted against the run's cap | Ollama or the offline planner; open-engine jobs are $0 | `/assist/scheduled` and a Scheduled tab in each project; a chat's Schedule button opens the dialog with its first request, files, project, engine and mode. Daily, weekly (any days), every 1–168 hours or once, in a time zone you pick, with the next run shown. Ask me first (the plan waits as an approval card; nothing is generated until you approve) or Run on its own within a cap (default $2, at most $500 a run; a plan over it waits). Each run is a new chat in the task's project. Run now, Edit, Pause / Resume, Delete; deleting a project pauses its tasks and says why. A sweep every 30 s starts at boot; a run missed while Fuobe was off happens once after the next start. Ran in demo mode only |
-| Connectors (Slack, Drive, Notion…) → your own MCP connectors | ✅ settings · 🟢 with Claude | Remote MCP servers you add, in Claude chats: Anthropic's servers call them (the MCP connector beta), Fuobe never does, so a local address needs a public tunnel | — (Ollama and the offline planner say once that connectors need Claude) | Settings → Assist · connectors (also in ⌘K): a name, an https URL (http only for localhost unless `FUOBE_ALLOW_PRIVATE_URLS=1`), an optional token and Allowed tools; tokens and secret-looking URL parts are masked when shown. Every enabled connector is offered in every Claude chat, Ask-first chats included, and its tools run without asking Fuobe, so Allowed tools is the main safeguard. Scheduled tasks use connectors only when ticked. A chat lists each connector tool Claude used. There are no built-in Slack, Drive or Notion connectors: add the app's own MCP server. The request is built through the real SDK against a fake; no live call |
++| Assist scheduled tasks | ✅ app (demo mode) · 🟢 with an LLM | Claude plans (with your Anthropic key); generations are priced at fal / Replicate prices and counted against the run's cap | A local model or the offline planner; open-engine jobs are $0 | `/assist/scheduled` and a Scheduled tab in each project; a chat's Schedule button opens the dialog with its first request, files, project, engine and mode. Daily, weekly (any days), every 1–168 hours or once, in a time zone you pick, with the next run shown. Ask me first (the plan waits as an approval card; nothing is generated until you approve) or Run on its own within a cap (default $2, at most $500 a run; a plan over it waits). Each run is a new chat in the task's project. Run now, Edit, Pause / Resume, Delete; deleting a project pauses its tasks and says why. A sweep every 30 s starts at boot; a run missed while Fuobe was off happens once after the next start. Ran in demo mode only |
++| Connectors (Slack, Drive, Notion…) → your own MCP connectors | ✅ settings · 🟢 with Claude | Remote MCP servers you add, in Claude chats: Anthropic's servers call them (the MCP connector beta), Fuobe never does, so a local address needs a public tunnel | — (a local model and the offline planner say once that connectors need Claude) | Settings → Assist · connectors (also in ⌘K): a name, an https URL (http only for localhost unless `FUOBE_ALLOW_PRIVATE_URLS=1`), an optional token and Allowed tools; tokens and secret-looking URL parts are masked when shown. Every enabled connector is offered in every Claude chat, Ask-first chats included, and its tools run without asking Fuobe, so Allowed tools is the main safeguard. Scheduled tasks use connectors only when ticked. A chat lists each connector tool Claude used. There are no built-in Slack, Drive or Notion connectors: add the app's own MCP server. The request is built through the real SDK against a fake; no live call |
+ | Studio jobs from Assist and MCP | 🟢 | `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, `katana` | Same on the open engine (`faceless_episode` needs a voice sample there) | Each is priced by its studio's own estimate and opens that studio: a Layers project, a Shorts session, a dub to review, a Faceless episode (in an "Assist" channel), an Ads Studio batch, the Captions editor; the chat shows an "Open in <Studio>" card and MCP's `estimate_job` returns the studio and its page. A call a studio can't take runs as a pipeline in the Library, and the card says why. Content Factory's "Generate in Claude" uses `faceless_episode`. Genjutsu, Remove object, Content Factory itself, the AI Influencer builder, the Character Swap Studio and Layers' Inpaint, Enhancer and Save as element have no Assist / MCP tool yet |
+ | AI Employees, Apps builder, Websites, Games, 3D Jutsu | ⬜ | — | — | |
+ | MCP (other agents use the studio) | ✅ | — | — | `/api/mcp` 1.2.0: search_models, estimate_cost, estimate_job, generate, create_storyboard, check_generations, list_recent, list_elements, list_skills, load_skill, read_source, remember and the studio tools; `katana` is named in the instructions; prompts built from the enabled skills. `search_models` leaves out models switched off in Settings → Models & licences; a call naming a retired model runs on its replacement |
+ | CLI + skills (`npx skills add …`), ChatGPT plugin | ✅ CLI and skills · ⬜ ChatGPT plugin | — | — | `fuobe` ([`docs/cli.md`](cli.md)): plain Node 20+, no dependencies. models, estimate, generate (`--wait`, `--out`), status, wait, download, cancel, list, upload, skills, tools / tool (MCP tools), mcp (prints the `claude mcp add` line), login / logout, and eval (the evaluation harness, from a Fuobe checkout); `--json` on every command. `generate --look <id> --look-strength 0–1` picks a Fuobe Soul look, `--engine` an Original's engine, and `models` lists an Original as open+cloud (`docs/cli.md` doesn't list `--look` yet; `fuobe generate --help` does). `npx skills add workingprototype/Fuobe` installs the playbooks, plus an agent skill that drives Fuobe through MCP or the CLI, in other agents. `fuobe models` lists only models that are on (it reads `GET /api/models`). No ChatGPT app |
| Plugins (Photoshop, Figma, Blender, After Effects, DaVinci) | ⬜ | — | — | |
- | Assets library | ✅ | — | — | `/library`: Square / Masonry / List, Fit / Fill, card size, split by date; tabs All / Images / Videos / Audio / Text / 3D / Favorites / Uploads / Trash; filters by model, date and status; batch stacks; select mode with a bulk bar (zip, like, move, delete); folders with colours and drag and drop; Reuse, hand-offs (Animate, Extend, Lipsync, Open in Layers…) and downloads. Missing: nested folders, pins, review status, projects in the library |
- | Trash | ✅ | — | — | Delete moves to the Trash with Undo (feed, viewer, Library, Cinema); 30 days, Restore, Delete forever (asks first), Empty trash; purged at startup and then daily; files still used elsewhere are kept |
- | Live progress, cancel, retry, failure messages | ✅ | — | — | Results arrive over one server-sent-events stream per browser; polling slows to every 10 s while it's connected (1.5 s without it) |
- | Text, 3D and layer results | ✅ | — | — | Shown in the feed, viewer and Library: text with cue timings (copy, .txt / .srt / .vtt), .glb in `@google/model-viewer` (loaded on demand), layers as a composite with a named list |
- | Studio UI (composer, model picker, viewer, galleries, navigation) | ✅ | — | — | Compact composer ("+" for upload / paste / library, one settings chip, Cmd/Ctrl+Enter), cmdk model picker with Recent / Starred / Best for this studio, typing before hydration kept, blockers that name the missing slot; viewer with a phone bottom bar, drawer and swipe; procedural previews on the app, motion and effect galleries; one prerendered page per hub mode; branded 404 and error pages, loading skeletons. Checked by `composer-flows.mjs`, `shell.mjs` and the 390 px sweep |
+ | Assets library | ✅ | — | — | `/library`: Square / Masonry / List, Fit / Fill, card size, split by date; tabs All / Images / Videos / Audio / Text / 3D / Favorites / Uploads / Trash; filters by model, date, status and review status; batch stacks; select mode with a bulk bar (zip, like, pin, review, move, delete), Select all (N), a Select per day and Ctrl/⌘+A; nested folders with breadcrumbs, colours, drag and drop, a Move to tree and folder zips with their subfolders; pins and a Pinned section; review status (In progress, Needs review, Approved, Rejected); helper steps (and evaluation jobs) hidden unless Show steps; an upload is deleted only when nothing uses it (otherwise it says where it is used); Reuse, hand-offs (Animate, Extend, Lipsync, Open in Layers…) and downloads; a Shared tab and Publish (next row), with Like, Pin and Review folded into a ⋯ menu in the phone selection bar. `tests/e2e/library-flows.mjs`. Past runs on retired Higgsfield models keep their outputs and the name they ran under ("Soul 2.0 (Higgsfield)"). Missing: projects in the library |
+ | Share links and Publish (portfolio page) | ✅ app (unit tests, and a live check signed out) | — | — | "Share link…" on a finished result, a Library folder (with its subfolders) and a Cinema project: a title, prompts shown or hidden, and how long it works (Always, 1, 7 or 30 days), then the link with Copy and Open page. **Publish** turns selected Library results into a portfolio page (Feature, Series or Carousel, with a cover; up to 100 pieces and 8 tags). **Library → Shared** (`/library?tab=shared`) lists links with views and expiry: a new link (the old one stops), hide or show prompts, re-date, revoke. `/s/<token>` needs no sign-in: the media, which model made each, Download and, with prompts shown, "Recreate in your Fuobe" (it copies the prompt); a dead link gets a "Link unavailable" page with a real 404. Shared files have their embedded generation data blanked (ComfyUI workflows, video and audio tags, EXIF / XMP), whether or not prompts show. Fuobe doesn't host the pages: a link opens only for people who can reach your Fuobe. Canvas boards can't be shared yet |
+ | Trash | ✅ | — | — | Delete moves to the Trash with Undo (feed, viewer, Library, Cinema); 30 days, Restore, Delete forever (asks first), Empty trash; purged at startup and then daily; files still used elsewhere are kept. The Trash lists helper steps too |
+ | Live progress, cancel, retry, failure messages | ✅ | — | — | Results arrive over one server-sent-events stream per browser; polling slows to every 10 s while it's connected (1.5 s without it). Running tiles show the time spent and, once progress has moved, the time left; the newest single result offers next steps (Animate, Upscale, Edit for an image; Extend, Upscale, Add sound for a video; Lipsync, Voice change for audio) |
+ | Browser notifications | ✅ | — | — | Opt-in per browser (Settings → Notifications, with Send a test), plus a one-time offer once a job has run about 20 s. A job that finishes or fails while no Fuobe tab is on screen notifies once, from the live stream's leader tab; clicking it opens the result. The tab title counts running jobs. `tests/e2e/notifications.mjs` |
+ | Text, 3D and layer results | ✅ | — | — | Shown in the feed, viewer and Library: text with cue timings (copy, .txt / .srt / .vtt), .glb in `@google/model-viewer` (loaded on demand), layers as a composite with a named list, SVG as SVG, EXR frames as a .zip, and ProRes or FFV1 (which browsers don't play) as a file card. A rigged .glb plays its animation instead of turning; a splat shows its orbit video or picture and a .spz / .ply download, not a 3D view. A Fuobe Soul result's details show its Look and Finish |
-| Studio UI (composer, model picker, viewer, galleries, navigation) | ✅ | — | — | Compact composer ("+" for upload / paste / library, one settings chip, Cmd/Ctrl+Enter), cmdk model picker with Recent / Starred / Best for this studio, typing before hydration kept, blockers that name the missing slot (on phones a line under the composer says why Generate is blocked); viewer with a phone bottom bar, drawer and swipe; procedural previews on the app, motion and effect galleries; one prerendered page per hub mode; a skip link, one `<main>` per page, a shorter sidebar (Studios and Engine start folded), full-screen studios that fold it, a phone header with Search, links that prefetch on hover; branded 404 and error pages (unknown ids and hub modes answer a real 404), loading skeletons. Reuse of a run on a retired model brings it back on its replacement, with a toast saying what changed, and `?model=` with a retired id opens the replacement (round 4, part 5). Checked by `composer-flows.mjs`, `shell.mjs` and the 390 px sweep |
++| Studio UI (composer, model picker, viewer, galleries, navigation) | ✅ | — | — | Compact composer ("+" for upload / paste / library, one settings chip, Cmd/Ctrl+Enter), cmdk model picker with Recent / Starred / Best for this studio, typing before hydration kept, blockers that name the missing slot (on phones a line under the composer says why Generate is blocked); viewer with a phone bottom bar, drawer and swipe; covers rendered in ComfyUI on 480 of the 487 app, motion and effect cards (474 stills, 6 clips that play on hover), procedural previews on the rest; one prerendered page per hub mode; a skip link, one `<main>` per page, a shorter sidebar (Studios and Engine start folded), full-screen studios that fold it, a phone header with Search, links that prefetch on hover; branded 404 and error pages (unknown ids and hub modes answer a real 404), loading skeletons. Reuse of a run on a retired model brings it back on its replacement, with a toast saying what changed, and `?model=` with a retired id opens the replacement (round 4, part 5). Checked by `composer-flows.mjs`, `shell.mjs` and the 390 px sweep |
+ | Search (⌘K / Ctrl+K palette) | ✅ | — | — | Searches pages, settings, apps, motions, effects, models (filtered to the engine mode) and recent creations, forgiving typos; a model opens where it runs, on its own engine (every Image to 3D model and Meshy Rigging now open `/image-to-3d`; an Original is listed once, as "Open source + cloud"). 33 models still open the filtered Models page (§3). Models switched off in Settings → Models & licences leave the palette; it finds Models & licences and Assist connectors. Checked by `shell.mjs` |
-| Getting started and connections | ✅ app · ✅ ComfyUI when busy (tests, a live CPU run) · 🟢 key tests | Save & test for the fal.ai, Replicate and Anthropic keys, and the civitai key (Settings → LoRAs). Preferred provider: Automatic, fal.ai first or Replicate first (the Higgsfield key and "Higgsfield first" are gone since round 4, part 5) | Save & test for the ComfyUI address, its auth token, the isolated worker, and Ollama (with its model) | A Get started card on Home and Settings: Use paid models, Use your GPU, or Just try it (the demo). Every connection field tests what you typed before saving it and gives the reason on failure; a status strip shows each connection. Home's Start runs the job in Image, Video or Edit, and the line under the box says first what will run and what it costs. Settings → About & licences (`/settings/about`) lists every open model's licence and links to Settings → Models & licences. **A busy ComfyUI counts as up** (round 4, part 5): before, one 1.5–2 s check decided, so a busy ComfyUI could send new runs to demo. Now it counts as up if it answered in the last 2 minutes, or if its port accepts a connection and it answers a longer 10 s check; refused, an unknown host or an HTTP error still means down at once, and a port that never answers (a hung ComfyUI, a tunnel to a dead box) is down after the 10 s check. A chain step after real ComfyUI steps waits up to 60 s for ComfyUI ("Waits for ComfyUI to answer") before failing; cloud steps don't wait. A live ComfyUI connected through the guide; no accepted key and no running Ollama were tested |
++| Getting started and connections | ✅ app · ✅ ComfyUI when busy (tests, a live CPU run) · 🟢 key tests | Save & test for the fal.ai, Replicate and Anthropic keys, and the civitai key (Settings → LoRAs). Preferred provider: Automatic, fal.ai first or Replicate first (the Higgsfield key and "Higgsfield first" are gone since round 4, part 5) | Save & test for the ComfyUI address, its auth token, the isolated worker, and each local LLM server's URL, model and key (Settings → AI helper) | A Get started card on Home and Settings: Use paid models, Use your GPU, or Just try it (the demo). Every connection field tests what you typed before saving it and gives the reason on failure; a status strip shows each connection. Home's Start runs the job in Image, Video or Edit, and the line under the box says first what will run and what it costs. Settings → About & licences (`/settings/about`) lists every open model's licence and links to Settings → Models & licences. **A busy ComfyUI counts as up** (round 4, part 5): before, one 1.5–2 s check decided, so a busy ComfyUI could send new runs to demo. Now it counts as up if it answered in the last 2 minutes, or if its port accepts a connection and it answers a longer 10 s check; refused, an unknown host or an HTTP error still means down at once, and a port that never answers (a hung ComfyUI, a tunnel to a dead box) is down after the 10 s check. A chain step after real ComfyUI steps waits up to 60 s for ComfyUI ("Waits for ComfyUI to answer") before failing; cloud steps don't wait. A live ComfyUI connected through the guide; no accepted key and no running Ollama were tested |
| Engine choice (open only, paid only, both) | ✅ | — | — | Settings → Engine mode, or `FUOBE_ENGINE_MODE` |
- | Credits / pricing | 🟡 | — | — | Bring your own key: live cost estimates per run, per pipeline step, per Assist plan; prices per resolution and per input + output second where the API bills that way; a cost cap per Cinema project; "Free" for open source. No billing, credits or Unlimited mode |
- | Sign-in and security | ✅ | — | — | Optional password (`FUOBE_PASSWORD`) and API tokens; cross-site writes refused; Host allowlist on password-less installs (`FUOBE_ALLOWED_ORIGINS`); remote URLs fetched only from public addresses (`FUOBE_ALLOW_PRIVATE_URLS=1` for a LAN); login throttle (`FUOBE_TRUST_PROXY=1` behind a proxy) |
- | Accounts, teams, sharing, community feed, contests, Academy | ⬜ | — | — | Single-user and self-hosted today |
- | Content checks (IP / face eligibility), browser notifications | ⬜ | — | — | |
- | Public API | 🟢 | — | — | The REST API (incl. `GET /api/generations/stream`) and the MCP endpoint, behind the password / API tokens once a password is set |
+ | Models & licences (Fuobe's own: licences as information, with admin switches) | ✅ page and switches (tests, browser) · 🟢 with real providers | Every fal and Replicate route is classed "Proprietary paid API", whatever its weights' licence; Claude by Anthropic's terms | Each open route takes its licence from the workflow manifest, plus its node packs' licences; an Ollama model by its own licence | Settings → Models & licences (`/settings/models`; also from ⌘K, About & licences and the Models page): every model, LoRA and node pack with its licence, link, class and note, in searchable tabs, with switches per licence class (Commercial use allowed, Commercial use with conditions, Restricted regions, Non-commercial, Research only, Proprietary paid API, Licence unknown), provider, node pack, LoRA and model, plus "Keep them on your GPU" (under "LoRAs licensed for your GPU only"), an Off filter and Back to the defaults. Everything is on by default and that rule is off. A switched-off model leaves every picker and listing (studios, Canvas, Cinema, ⌘K, the Models page, `GET /api/models` and the CLI, Assist and MCP's `search_models`). Automatic picks move to the next model that is on, an Original runs on the engine still on, and a run that can't fall back is refused naming the switch (`POST /api/generations` answers 422; chains check every step before queuing). Switched-off LoRAs are left out with a note, their trigger words too; your own LoRAs are exempt from the class switches. Stored in the settings table (`models.access`), no migration; switches set on a retired model or on Higgsfield no longer match anything (§3) |
+ | LoRAs on both engines (Settings → LoRAs) | ✅ settings page and one Hugging Face download · 🟢 civitai downloads and mirrors · 🟢 open runs · 🟢 cloud runs | Seven hosted open-weight models take LoRAs: Qwen-Image 2512, Qwen-Image-Edit 2511, FLUX.2 [klein] 4B, Wan 2.2 A14B image and video, LTX-2.3 22B (on fal; Qwen-Image-Edit 2511 and Wan 2.2 video also on Replicate), and Z-Image Turbo (hosted), which takes any LoRA on fal and on Replicate (before round 4, part 2, only a trained character's LoRA, on fal). Round 4, part 4 adds five on fal for Soul ID: FLUX.1 [dev], FLUX.1 Krea [dev], FLUX.2 [dev], FLUX.2 [klein] 9B and Krea 2 Turbo. The Fuobe Originals' cloud routes send their looks' and moves' LoRAs the same way, and the hidden relight step sends its Relight LoRA. A LoRA licensed for your own GPU only (a civitai file without the "Rent" permission) now goes to fal or Replicate with a note, unless Settings → Models & licences keeps such LoRAs on your GPU. LoRAs a run can't take (a gated Hugging Face file, more than the model accepts, or one kept on your GPU) are left out with a warning. A civitai file is copied ("mirrored") once to fal or Replicate storage, with civitai's permissions (or the fact that civitai didn't answer) recorded beside it; only with the keep-on-GPU rule on does a copy wait for civitai to allow hosting. A Soul ID trained on your GPU is uploaded once for a cloud run. When a model runs on both providers, Fuobe picks the one that takes every LoRA and the clip length asked, even over the preferred provider | A LoRA ComfyUI lacks is downloaded into the LoRA folder before the run and checked against its SHA-256 fingerprint. This also covers the existing open camera motions and effects and trained @character LoRAs; a Soul ID trained in the cloud is copied into ComfyUI. With no folder set, the run stops and says what to do; a graph with no model loader refuses LoRAs instead of dropping them | Settings → LoRAs (also in the ⌘K palette): the LoRA folder (`COMFYUI_LORAS_DIR`), a civitai API key (`CIVITAI_API_KEY`) with Save & test, and a library of 114 researched LoRAs (67 looks, 23 motions, 24 effects) with licence, source and a Download button: 40 Hugging Face files pinned to a commit, 72 on civitai (they need the key) and 2 gated Hugging Face files placed by hand. An @character's trained LoRA comes before a look's; a preset at strength 0 drops its LoRA and trigger word. Fuobe Soul's looks and Fuobe DoP's motions and effects now take a LoRA from the library, with its pinned download and licence, whenever the file is in it; 36 of the LoRA files the open motions and effects load are on civitai (none were before). One 85 MB LoRA was downloaded live and matched its fingerprint (§1); no LoRA has run on fal, Replicate or a GPU, and civitai downloads and mirrors haven't run live. Settings → LoRAs no longer says GPU-only files are never sent to a cloud API, and no longer paints non-commercial licences red: licences are information (Settings → Models & licences) |
+ | Originals evaluation harness (developer tool) | ✅ demo and CPU self-test · 🟢 open and cloud measurement | Jobs go through Fuobe's own API to hosted models, priced first, under a spend cap (default $5) | Jobs go through Fuobe's API to your ComfyUI; it also reads ComfyUI's memory peak and timings | `scripts/eval` ([README](../scripts/eval/README.md)): `pnpm eval:run --suite <selftest\|soul\|soul-cinema\|soul-hex\|soul-id\|dop\|dop-mix\|genjutsu\|mixed-media\|shorts\|speak\|cinema> --engine demo\|open\|cloud` (or `fuobe eval`), plus report, a blind A/B review page, compare, promote, covers, history, validate, setup and trash. It scores each Original's recipe (models, LoRAs, settings) with pinned open models (CLIP, an aesthetic score; DINOv2 and AuraFace identity optional) and a palette metric (how close a picture keeps to the palette it was sent) in its own Python venv (`pnpm eval:setup`, needs uv), and its jobs stay hidden in the Library unless Show steps is on. Round 4, part 3 adds `soul-cinema`, `soul-hex` and `dop-mix`; `soul` now names the engine on every request and runs the Graffiti look on Soul HD, and `dop` targets Fuobe DoP with 20 more camera moves. Round 4, part 4 points `cinema` at Fuobe Cinema (9 cases) and `genjutsu` at the Genjutsu Originals (7 cases, Character swap included, with a 6 s walking-figure clip), and gives `soul-id` 5 cases (character, cinema, hd, flux, look), each trained, at half strength and as plain reference photos; the runner sends a character's consent, never measures a demo training as trained and uploads up to 80 photos. `promote` no longer holds a recipe back for its licence (`--licence-hold` brings that back), `covers` gains `--commercial-only`, and the non-commercial buffalo_l face model runs when asked for (`--identity-model buffalo_l`, no longer needing `--accept-noncommercial`) unless `--commercial-only` is given; AuraFace stays the default. Nothing changes in the app. No Original has been measured on a GPU or the cloud, no recipe has been promoted, and there are no preset covers yet |
+ | Credits / pricing | 🟡 | — | — | Bring your own key: live cost estimates per run, per pipeline step, per Assist plan; prices per resolution and per input + output second where the API bills that way, and by the clip's real length for the finishing tools; per megapixel of video for Fuobe Cinema; a cost cap per Cinema project and per scheduled Assist run; "Free" for open source. No billing, credits or Unlimited mode |
+ | Sign-in and security | ✅ | — | — | Optional password (`FUOBE_PASSWORD`) and API tokens; cross-site writes refused; Host allowlist on password-less installs (`FUOBE_ALLOWED_ORIGINS`); remote URLs fetched only from public addresses (`FUOBE_ALLOW_PRIVATE_URLS=1` for a LAN); login throttle (`FUOBE_TRUST_PROXY=1` behind a proxy). Share links (`/s/<token>`) skip sign-in by design, after the host and cross-site checks, with a throttle on wrong tokens (§3) |
+ | Accounts, teams, community feed, contests, Academy | ⬜ | — | — | Single-user and self-hosted today; sharing is read-only links (above) |
+ | Content checks (IP / face eligibility) | ⬜ | — | — | |
+ | Public API | 🟢 | — | — | The REST API (incl. `GET /api/generations/stream`, `GET /api/models` with how each model runs today, and `POST /api/generations?preview=1` for a priced plan that creates nothing) and the MCP endpoint, behind the password / API tokens once a password is set. Round 4, part 3: `POST /api/generations` takes `engine` for an Original; `GET /api/models` lists an Original once with both engines, or as the engine asked for; `POST /api/generations/[id]/finish` saves a browser-finished Fuobe Soul picture (PNG, up to 64 MB; the raw one stays as `meta.original`). **Breaking** (round 4, part 3): canvas responses return `pages`, not `graph` (writes still take `graph`, with an optional `page`). Round 4, part 4: new `/api/shares[/id]`, `/api/assist/schedules[/id[/run]]`, `/api/assist/connectors[/id]`, `GET/PUT /api/settings/models`, `POST /api/genjutsu/describe` and `/transcribe`, `GET /api/moodboards/[id]/train`, and the public `/s/<token>` and `/s/<token>/f/<path>`. `GET /api/models` lists only models that are on; `POST /api/generations` answers 422 naming the switch for a model that is off; `GET /api/status` adds `access` while anything is off. **Breaking:** `POST /api/genjutsu` and `/estimate` take mode `character`, and look kind `soul` replaces `higgsfield`; `POST /api/elements/[id]/trainings` takes `{target, consent}` (a character needs `consent: true`), `/lora` takes `family` instead of `modelId`, and `/training-kit` a `family`; Cinema's `GET /api/cinema/projects/[id]` returns `context` as `{cloudAllowed, civitai}` (no `higgsfield`), and `POST …/generate` takes the take's model, prompt, length and size. Elements take up to 80 references. Round 4, part 5: new `/api/swap-studio/projects[/id]` with `clips`, `prepare`, `transcribe`, `masks`, `anchors`, `queue`, `stop`, `takes/stop`, `assemble`, `estimate` and `decisions`; `POST /api/uploads` takes MKV and AVI; `POST /api/generations` may answer with a replacement `modelId` plus `notes` for a retired model; ads batch and estimate bodies and `POST /api/brands/[id]/chat/confirm` ignore `route` and `ratio`, and `/api/ads/estimate` no longer returns `route`; `POST /api/providers/test` with `higgsfield` answers 400, `GET /api/status` no longer lists it, and `PUT /api/settings` ignores `higgsfieldKey` and refuses `cloudProvider: "higgsfield"` (400). **Removed:** `GET /api/providers/higgsfield/presets` |
## 3. Known issues and caveats
Most important first.
**Not run for real (no keys, no GPU)**
- - **Paid providers are untested with real keys.** That now includes the round-3 response shapes Fuobe reads: Seedream layer boxes, Recraft's returned `style_id`, transcript cues, 3D files, Demucs stems, and the fal FFmpeg tools (compose `tracks`, loudnorm, forced alignment, `scale-video` crop, extract-audio). Two behaviours are assumptions from the docs: fal compose cuts an audio keyframe at its `duration`, and it renders an audio-only timeline over a still. Cloud `join-clips` is assumed to keep each clip's audio.
- - **Open-source quality is unverified.** Round 3 added about 165 GB of new model files (plus about 9 GB that nodes download on first use) that have never run here. Whole open chains (a UGC presenter film, a Faceless episode, a dub with lip re-sync, a Shorts restyle) ran only on the demo provider. The try-on single-garment graph and the new InfiniteTalk sizing are checked by `/prompt` validation only; ThinkSound's packages are installed on the isolated worker but never ran.
- - **Assist hasn't talked to a live model.** The streamed Claude call is tested against an SSE fake, and Ollama and LM Studio against fake servers. Skills, projects and memory work end to end with the offline planner only. Small local models follow tool instructions less reliably.
+ - **Paid providers are untested with real keys.** That includes round 3's response shapes (Seedream layer boxes, Recraft's returned `style_id`, transcript cues, 3D files, Demucs stems, the fal FFmpeg tools) and round 4, part 1's routes: Topaz Video by size, Starlight, ByteDance and FLUX.3 Upscale, Topaz FPS Boost and SDR to HDR, LTX 2.3 HDR's EXR zip, the Bria erasers, VOID, LTX clean plate, SAM 3.1 masks, hosted VACE, P-Video Replace, Genjutsu and Genjutsu Lite, FLUX 3 Max keyframes, Marigold V2, fal's Ken Burns and merge-audios, and the cloud dub's split, loudnorm and mix. Round 4, part 2 adds: per-frame Mixed Media (how many frames extract-nth-frame returns and in what order, Nano Banana 2 edits with two images, images-to-video at a fractional fps such as 7.5, merge-videos with a set size), the cloud end card (whether merge-videos keeps the ad's voiceover next to the card's silent track, how overlay-image scales a very large logo), Florence-2 OCR (its box units, pixels assumed, and its real price; the $0.001 shown is a placeholder), the Inpaint and Enhancer models, Content Factory's reading (fal frames, Scribe v2, Claude with frames), the AI Influencer sheets, the six hosted LoRA models and every LoRA payload, and civitai downloads and mirrors (mirror lifetimes of 7 days on fal and 1 day on Replicate are guesses). Round 4, part 3 adds: Fuobe Soul on fal and Replicate (fal's rounding to whole megapixels for Qwen-Image 2512 is assumed from its price text, and Replicate is priced at fal's rate), Fuobe DoP on fal's Wan 2.2 A14B and LTX-2.3 and its Replicate fallback, LTX-2.5 Fast's focus shift, the hosted Qwen-Image-Edit 2509 relight, SAM 3D Objects, Meshy multi-view and rigging (and playing a real Meshy animation), Tripo text to 3D, TripoSplat, and the Canvas nodes' ElevenLabs Voice Changer and Dubbing, hosted Chatterbox and the concatenator's fal steps (whether merge-videos keeps sound when one clip has no sound track is unknown). Round 4, part 4 adds: Fuobe Cinema on fal's LTX-2.3 22B (its camera LoRA, the sizes on the 32-pixel grid, the per-megapixel estimate against the real bill, whether extend-video returns the whole clip and honours a backward extend, and the edit's video strength of 0.5, a guess), the Genjutsu Originals on fal (Wan 2.2 Animate move, Wan VACE 14B inpainting, Wan 2.2 VACE Fun depth), MiniMax H3 reference-to-video with Akatz Labs' LoRA (and its mute step for a silent clip), H3 Max Recast, Wan 2.2 Animate Replace, SCAIL-2, Wan Motion, the GPT Image 2.5 Sunburst first frame, Scribe v2 for "Use the clip's words", the eight fal trainers and the five hosted LoRA models (whether fal's FLUX.2 endpoint reads ComfyUI-named LoRA weights, whether a LoRA trained on the klein base behaves the same on the distilled klein endpoint, Krea 2's trainer with Fuobe's captions), real fal and Replicate files through the share metadata cleaner, and Claude with a remote MCP connector. Round 4, part 5 adds: the Character Swap Studio's cloud chain (MiniMax H3 takes and their real prices, whether fal's trim cuts each take back frame-exact, so the next segment starts from the right frame, scale-video and merge-videos at 24 fps with mixed sources, SAM 3.1's `frame_index` for clicks on later frames, taken from the research, fal reading AVI, and merge-audio-video taking the clip as the sound), Happy Horse 1.1 on fal and the Happy Horse video edit's payload (checked against the researched schemas only), and the models that replaced Higgsfield's (GPT Image 2.5 for Marketing images, Nano Banana Pro for Ads Studio and the AI Influencer app, Kling O3 edit for Seedance 2.5's edit and in the Ad Multiplier, Seedance 2.5 for Cinema Studio 4.0's reference takes), which ran in demo mode and tests only. Prices are list prices; ByteDance's 6K and 8K prices are extrapolated from 4K, and Genjutsu's 50% promotion is mentioned, not subtracted. Assumptions from the docs: fal compose cuts an audio keyframe at its `duration` and renders an audio-only timeline over a still; cloud `join-clips` keeps each clip's audio.
+ - **Open-source quality is unverified.** Round 3 added about 165 GB of model files (plus about 9 GB that nodes download on first use) that have never run here. Round 4, part 1's heavy open workflows were only accepted by ComfyUI, not run: Wan 2.1 VACE (remove, swap, insert), VOID, Wan Animate 2, SeedVR2 in passes, Frames films, the Qwen-Image-Edit 2511 + Multiple-Angles re-render and a full open Faceless render. Round 4, part 2's open models haven't run through Fuobe either: OvisOCR3 (it ran only during the research, directly on a CPU ComfyUI: two test posters, 161–194 s each; its weight isn't installed here, and the parser is checked only against the answer formats recorded there), the Gemma 4 E4B brief, FLUX.1 Fill [dev] Inpaint, the Enhancer's looks and its Detail at 2× (bindings only), and the AI Influencer's Soul Cast sheet + Qwen-Image-Edit chain. Round 4, part 3's open routes were only accepted by ComfyUI: every Soul look, Soul Cinema, `z-image-turbo-i2i` and stacks of three LoRAs; Fuobe DoP on Wan 2.2 and the three LTX-2.3 graphs; the relight step; TRELLIS.2 Multi-view, open TripoSplat and the open text-to-3D chain. Round 4, part 4's open routes: the three MiniMax H3 graphs have never loaded in a ComfyUI (their packs aren't installed here), so a first real run may fail on wiring or a missing pack, and open Character swap parts over 15 s are only modelled; Fuobe Cinema's open half runs Wan 2.2 Lightning graphs that were only accepted; Soul ID's AI-Toolkit configs for Qwen-Image 2512, FLUX.1 [dev], FLUX.2 [dev] and klein 4B have never trained (the dialog's VRAM and time figures are estimates), and no trained LoRA has run in ComfyUI. Round 4, part 5's: the Character Swap Studio's two H3 Relay graphs have never loaded in a ComfyUI either (five H3 graphs in all), its continuation (the take before's last frames as history, which assumes exact frame counts) is proven only in pure and demo tests, and retired Higgsfield ids running on the Originals' open halves were checked in demo mode and tests only. To check on the first runs: Wan 2.1 LoRAs on Wan 2.2, the LTX-2 19B Earth Zoom Out LoRA on LTX-2.3, the 2509 Relight LoRA on fal's plus-lora endpoint, `camera_lora_scale` on the plain LTX-2.3 endpoint, `focus_shift` on LTX-2.5 Fast, and whether MoGe's estimated field of view helps multi-view models from real phone photos. No LoRA has rendered on a GPU. Whole open chains (a UGC presenter film, a Faceless episode, a dub with lip re-sync, a Shorts restyle, a Content Factory series) ran only on the demo provider.
-- **No Fuobe Original has been measured.** Fuobe Soul, DoP, Cinema, Genjutsu (with Character swap) and Soul ID are in the app, but the evaluation harness ran only on the demo provider and on CPU-only tools; its `soul`, `soul-cinema`, `soul-hex`, `soul-id`, `dop`, `dop-mix`, `cinema` and `genjutsu` suites are ready for GPU and cloud runs (`soul-id` needs 20+ photos of a person who consented; a cloud run is about $14.29 of training plus renders). No recipe has been promoted, and the preset covers it can make (`src/lib/preset-previews.generated.ts`) are still empty.
-- **Assist hasn't talked to a live model.** The streamed Claude call is tested against an SSE fake and Ollama against a fake server. Skills, projects and memory work end to end with the offline planner only. Small local models follow tool instructions less reliably. Scheduled tasks ran only in demo mode, and no Claude call has used a real MCP connector.
++- **No Fuobe Original has been measured.** Fuobe Soul, DoP, Cinema, Genjutsu (with Character swap) and Soul ID are in the app, but the evaluation harness ran only on the demo provider and on CPU-only tools; its `soul`, `soul-cinema`, `soul-hex`, `soul-id`, `dop`, `dop-mix`, `cinema` and `genjutsu` suites are ready for GPU and cloud runs (`soul-id` needs 20+ photos of a person who consented; a cloud run is about $14.29 of training plus renders). No recipe has been promoted, so no cover comes from a measured run: the 480 covers in `src/lib/preset-previews.generated.ts` are ComfyUI preview renders turned into covers with `pnpm eval:covers --from-masters`.
++- **Assist hasn't talked to a live model.** The streamed Claude call is tested against an SSE fake, and Ollama and LM Studio against fake servers. Skills, projects and memory work end to end with the offline planner only. Small local models follow tool instructions less reliably. Scheduled tasks ran only in demo mode, and no Claude call has used a real MCP connector.
**Gaps that change what a user gets**
- - **Assist / MCP studio tools always use their pipeline fallback.** `STUDIO_ROUTES` in `src/server/assist/studio-tools.ts` is empty, so a `dub_video` or `split_layers` job lands in the Library, not as a dub session or a Layers project. The `katana` tool is in the tool list but isn't named in Assist's system prompt or the MCP instructions. Several skills still link to stand-in pages: `faceless-video` → `/storyboard`, `katana` and `ad-multiplier` → `/video-edit`, `marketing-studio-cards` → `/apps/app-ad-creative`, `character-sheet` → `/elements`.
- - **Cloud step-by-step dubbing keeps the voice only.** Its soundtrack step (`merge-audio-video`) takes one track, so the background music and effects are lost. The open route mixes the background stem back in. (`ffmpeg-compose`, which Faceless uses, could carry both.)
- - **Some models are in the catalog but no studio page offers them.** LatentSync 1.6 and ThinkSound (isolated worker), Qwen3.5 4B translate and Gemma 4 speech translate are hidden models with validated workflows, reachable only through the API (`modelId`); Recraft Vectorize, Image to SVG and RIFE interpolation are visible but only a Canvas model node can run them.
- - **Mixed Media on the cloud is a video-to-video restyle**, not Higgsfield's per-frame pipeline. A real one needs a per-index chain slot, an images-to-video tool and splitting renders above 200 frames.
- - **Open-engine limits.** Music beds stop at 240 s (ACE-Step; there is no open audio concat or loop). Open "Frame by frame" in Faceless is a slow-camera image-to-video, not a pan. The joins that keep a clip's sound hold every frame in RAM at 25 fps (about 1 GB per 8 s at 480x848). Open video upscaling decodes the whole film (about 38 GB for 30 s at 480p), so Faceless offers Upscale to 1080p on the cloud only. InfiniteTalk lip re-sync is capped at 40 s per job (for dubs, the whole source length). Whisper captions refuse clips that need more than half the server's RAM (the estimate isn't measured).
+ - **Home's Start spends money.** Start (or Enter) on Home now runs the job; with a saved key for the default model that is a paid run (for example a Seedance 2.5 clip). The line under the box, which says what will run and what it costs, is the only warning. A link from elsewhere can't start a run.
-- **ComfyUI reachability:** a busy ComfyUI now counts as up (§2, Getting started and connections). But right after start or an address change, a port that accepts connections counts as up for about 15 s until the background check ends, so a run started then can go to a ComfyUI that never answers (it fails with "Can't reach ComfyUI" once the connection times out). A forced status check on a slow, silent port can take about 15 s (at most every 2 minutes per server), and can hold the runner's next sweep that long. A ComfyUI that answers nothing for over 2 minutes and then also misses the 10 s check is marked down for the next 2 minutes: new open-engine runs go to demo (Demo mode on Auto), and waiting chain steps fail after 60 s. Only the main ComfyUI address is checked this way, not the isolated worker. Ollama's check still treats a timeout as down.
++- **ComfyUI reachability:** a busy ComfyUI now counts as up (§2, Getting started and connections). But right after start or an address change, a port that accepts connections counts as up for about 15 s until the background check ends, so a run started then can go to a ComfyUI that never answers (it fails with "Can't reach ComfyUI" once the connection times out). A forced status check on a slow, silent port can take about 15 s (at most every 2 minutes per server), and can hold the runner's next sweep that long. A ComfyUI that answers nothing for over 2 minutes and then also misses the 10 s check is marked down for the next 2 minutes: new open-engine runs go to demo (Demo mode on Auto), and waiting chain steps fail after 60 s. Only the main ComfyUI address is checked this way, not the isolated worker. The local LLM servers' check still treats a timeout as down.
+ - **Fuobe DoP became the cloud default for 152 presets before any clip was compared.** The motions and effects with a recipe of their own (a LoRA, a camera LoRA, a hosted move, a grade or a relight) moved from Kling 2.5 Turbo to Fuobe DoP, so their model and price changed. That includes the 15 grade and 6 relight effects, whose animation step is Wan 2.2 with no LoRA. Whether to keep this, or keep them on Kling 2.5 Turbo until the evaluation runs, is still open. The other 211 stay on Kling 2.5 Turbo on their words.
+ - **Remove object:** H3 Person Removal (open, people only) needs the opt-in H3 Relay pack and its graph has never loaded in a ComfyUI. Seams between pieces (cloud) and windows (open) are untested, and open typed windows are joined with hard cuts. Click it and Paint it need the browser to decode the first frame (not ProRes, for example), and there is no server-side fallback. Click it is cloud only. On the open engine SAM 3.1 tracks at most 4 objects. Erasers that work in 4- or 8-frame steps (VACE, VOID, LTX) leave out up to 7 frames at the end (the estimate says so). Try again uses the form as it is now, not the run's own request.
+ - **Genjutsu:** Insert has no Original yet. fal bills Motion, Swap and Restyle by frames ÷ 16, so a 30 fps clip costs about 1.9× the per-second price. The references panel counts to 10, though no model uses more than 4, and open swap and insert use only the first; Katana's cloud Genjutsu motion takes 1 reference where Higgsfield's took 8. Clips over 30 fps aren't resampled for the hosted VACE. An old setup code with a Higgsfield look opens without a look. Higgsfield's batch, community presets and Recreate aren't built. Assist and MCP can't run Genjutsu or Remove object yet.
+ - **Character swap:** the H3 graphs have never loaded in a ComfyUI, and open parts over 15 s have never run. In the cloud, fal's H3 has no mask: who to swap is said in words and the whole frame is regenerated, and 15 s pieces start fresh, so seams can show. The estimate leaves out the Sunburst first frame's tokens; "Use the clip's words" starts a paid transcription with no estimate first; "Describe my character" sends the picture to Claude when an Anthropic key is set. The scene-cut warning was checked on WebM only. After a click on your GPU, frames where the pack loses the person are found again by the words and the first detection, which may not be the person clicked (pack behaviour). The default graph pins the last commit with Akatz Labs' `h3_character_swap` pack; their later fixes go into H3 Relay. The pack's assemble step also writes a second MP4 and a JSON report into ComfyUI's output folder. Workflows → **Copy install commands** gives `git clone …/tree/<commit>/…` lines for the two H3 packs, which git can't clone: use the install script. Not built: Replicate's Wan 2.2 Animate routes. Whole clips, shot by shot (Replace character or Keep original per shot), are the Character Swap Studio's (next bullet).
+ - **Character Swap Studio:** nothing ran on a GPU or with a real fal key. Its two graphs have never loaded in a ComfyUI with H3 Relay, and its cloud chain ran only in demo mode (what is unconfirmed: above). Continuations assume exact frame counts on both engines. Cloud clips keep their own frame rate (your GPU converts them to 24 fps), though the studio counts frames at 24 fps. The GPU mask memory guard is an unmeasured estimate and may be too strict (on a 64 GB server, 1 MP corrections stop at shots of about 18 s). A history of over about 30 frames at 1 MP needs ComfyUI started with a higher `--max-upload-size` (the page and the error say so). A take that runs out of GPU memory isn't retried with lower memory use (Try again makes a new take). Opening a project, its estimate or its decisions also moves it forward and can launch queued, paid takes; a background sweep every 3 s does the same, and, like scheduled tasks, it runs in every Fuobe server on the same data folder, so a dev server on your real data can launch (and pay for) takes too. Assembly uses chosen takes even when they are out of date, and names them in a warning. No Finish stage. On a phone you scroll past the project panels to reach the workbench. No Assist or MCP tool.
+ - **.avi clips** don't play in browsers: the Character Swap Studio makes a playable copy on the cloud; elsewhere there's no preview, and some providers may refuse them. The upload API now takes .mkv and .avi for every feature, though only the studio's picker lists them (the others still list MP4, MOV and WebM). A ComfyUI upload refused as too large now says to raise ComfyUI's `--max-upload-size` (100 MB by default).
+ - **The Happy Horse video edit looks priced about 2× too high** (already so before PR #13): $0.28/s is counted on input and output seconds, where fal's wording suggests $0.14 for each. It overestimates, so spend caps stay safe. It affects Shorts, Mixed Media, Genjutsu and the Ad Multiplier.
+ - **Higgsfield is gone (O7), with a few leftovers.** Fuobe calls no Higgsfield model or API. A stored or scripted Higgsfield model or operation runs on what replaced it: Soul and Soul 2.0 on Fuobe Soul, Soul Cinema on Fuobe Soul Cinema, Cinema Studio 4.0 on Fuobe Cinema (its reference takes on Seedance 2.5), the five Genjutsu models on the Genjutsu Originals, Marketing Studio Image on GPT Image 2.5, Ads Studio and the AI Influencer sheet on Nano Banana Pro, Seedance 2.5's video edit on Kling O3 edit, and LTX 2.5's start/end-frame clip on Fuobe Cinema. Leftovers: browser Reuse drops Cinema Studio's Director fields (the toast says so; the API, CLI and MCP write them into the prompt). Soul 2.0's colour palette is dropped, not turned into a palette lock. Assist and MCP plans move a retired model without the note saying why (from reading the code, not a test). The Library's Engine row still shows "Cloud · higgsfield" for old runs. On the open engine, an old LTX 2.5 start/end-frame request runs on Fuobe Cinema's Wan 2.2 clip, though its note names LTX-2.3. Jobs still running on Higgsfield when you upgrade fail on their next check with a message to run them again, and Higgsfield Soul ID trainings with one to retrain; Higgsfield Soul IDs aren't moved. Switches set in Settings → Models & licences on a retired model or on Higgsfield no longer apply: switch off the replacement. An install whose only cloud key was Higgsfield's has no cloud engine until a fal.ai or Replicate key is added (cloud runs come back as demos meanwhile). Marketing images, Ads Studio and the AI Influencer app run on partner models until O10, and Seedance 2.5's edit can't be picked any more. The Higgsfield research files stay as research, and some generators still read them.
+ - **Fuobe Cinema:** camera-LoRA quality and real bills are unchecked. The cloud's 30 s chain and prequel assume fal's extend-video returns the whole clip and honours a backward extend: check that first. A cloud move with a Wan 2.2 LoRA (with a start frame) switches the take to Fuobe DoP: 16 fps, no sound, DoP's lengths and no 20 s + extend chain, at DoP's price (a note says so). Fuobe Cinema doesn't take reference clips yet (fal's LTX-2.3 reference route has no recorded inputs), so such a take runs on Seedance 2.5 at its partner price, and the move badges still follow the menu pick. A cloud shot list longer than 20 s reuses its shot-timed prompt for the extend step (unchecked). An edit sent before "Use take" has read the take's length is priced as 5 s. On your GPU the six civitai camera LoRAs need a civitai key unless ComfyUI already has them, and the move badges don't say so. The Cast and Location looks, the edit strength and treating a zoom as a dolly for the camera LoRA are guesses for the harness to settle. Open routes take no reference clips. Collaboration and a community feed are out of scope (a project can be shared as a read-only link). Spend uses the estimate stored at creation for takes deleted for good, so it can be slightly over-counted.
+ - **Soul ID:** no real training ran, so likeness is unmeasured. The new AI-Toolkit configs, and whether fal's FLUX.2 [dev] LoRA endpoint reads the trained files (Fuobe asks fal's trainer for ComfyUI-named weights), are unverified; if fal can't read them, a cloud FLUX.2 Soul ID could do nothing in the cloud. Not built: Replicate trainers (an install with only a Replicate key can't train in the cloud), Wan 2.2 image Soul IDs, and fetching a LoRA from a remote AI-Toolkit (copy it into ComfyUI by hand). The AI-Toolkit address is set with `AI_TOOLKIT_URL` (or `PUT /api/settings`): the Settings page has no field for it, though the training message points there. With no fal key and no AI-Toolkit, Demo mode on "auto" (the default) makes a training an 8-second demo that trains nothing; it never replaces a real Soul ID. Consent is one tick, checked on the server and stored with the training. Trainings aren't under the Models & licences switches: switching off fal.ai doesn't stop a paid training (runs that use the LoRA are refused later). A finished fal training is used from fal's link at once while Fuobe's copy downloads in the background; a failed copy isn't retried. Trained LoRAs are kept in the data folder (expect it to grow); copying one into ComfyUI blocks the server while it copies, and a cloud upload reads the whole file into memory (FLUX LoRAs can be hundreds of MB).
-- **Models & licences:** hosted fal and Replicate models are all classed "Proprietary paid API", whatever their weights' licence, so switching off Non-commercial doesn't reach the hosted FLUX [dev] or klein 9B models (the licence recorded on 20 models, `ModelDef.licence` on 13 hosted models and 7 of the Originals' cloud halves, isn't read yet). Trainings, and Assist's and prompt enhancement's own Claude or Ollama calls, aren't under the switches. A fixed pick with no menu (Storyboard's models, Faceless's still and narration helpers, hidden helper steps) doesn't fall back: the run is refused, naming the switch. Any LoRA with no recorded licence counts as your own, so the class switches don't reach it. Defaults that the old licence rules chose are unchanged (the Wiggle, BTS and Bullet Time motions, Whisper captions, the Soul bases and others). 8 node packs are classed "Licence unknown"; ComfyUI-ReActor is listed as MIT from the research, unconfirmed. There is no admin role (below).
++- **Models & licences:** hosted fal and Replicate models are all classed "Proprietary paid API", whatever their weights' licence, so switching off Non-commercial doesn't reach the hosted FLUX [dev] or klein 9B models (the licence recorded on 20 models, `ModelDef.licence` on 13 hosted models and 7 of the Originals' cloud halves, isn't read yet). Trainings, and Assist's and the AI helper's own Claude or local-model calls, aren't under the switches. The text steps' licence follows the local model in use as far as Fuobe knows it (the server's last answer, else the model setting): a model outside the known families (Qwen, Mistral, Mixtral, Phi, DeepSeek, Gemma, Llama) is "Not recorded", and a server that picks its own model is "Not recorded" until it answers. A fixed pick with no menu (Storyboard's models, Faceless's still and narration helpers, hidden helper steps) doesn't fall back: the run is refused, naming the switch. Any LoRA with no recorded licence counts as your own, so the class switches don't reach it. Defaults that the old licence rules chose are unchanged (the Wiggle, BTS and Bullet Time motions, Whisper captions, the Soul bases and others). 8 node packs are classed "Licence unknown"; ComfyUI-ReActor is listed as MIT from the research, unconfirmed. There is no admin role (below).
+ - **Share links:** Fuobe doesn't host these pages, so a link opens only for people who can reach your Fuobe (on `localhost` the Share dialog says so). Real fal and Replicate files weren't run through the metadata cleaner; a file it can't read shows as missing on the share page, and MP4 track handler names aren't blanked. Canvas boards can't be shared. A link's full address is kept only in the browser that made it, so copy it then (elsewhere, Library → Shared can only make a new link). With no password, your own visits count as views. Revoking deletes the link at once, but browsers may keep files they already fetched for 5 minutes. Demo pictures draw the prompt into the image, so a prompts-hidden demo page still shows it. "Recreate in your Fuobe" only copies the prompt; there are no comment or reuse access levels. In `next dev`, a link-preview bot fetching a share page logs an InvariantError (the answer is still right; not seen after a build).
+ - **Assist scheduled tasks and connectors:** tasks run only while Fuobe runs; a missed run happens once after the next start, and a run that comes due while the last one is still going is skipped. Every Fuobe server on the same database runs due tasks, so a dev server on your real data runs, and spends on, your schedules too. The cap counts priced generation jobs, not Claude's tokens or what connector tools do, and plans approved by hand don't count against it. Nothing tells you when an Ask-first plan waits, and tasks can't be made from Fuobe's MCP server or the CLI. Connector tools run on Anthropic's side without asking Fuobe, in Ask-first chats too: each connector's Allowed tools, the per-task opt-in and Claude's instructions are the only safeguards, and every enabled connector is offered in every Claude chat. Tool names are typed by hand (no tool list or connection test). Switching a connector on or off, or deleting it, mid-chat drops Claude's earlier thinking in that chat (it costs tokens, no error).
+ - **Fuobe Soul:** a picture gets its crop, grade and overlay only when a studio feed shows it in a browser; after an API, CLI or Canvas run the Library and downloads have the raw picture (a 21:9 Soul Cinema run from the API is the 16:9 picture plus `meta.crop`). With the colour lock on, the grade lands on the picture from before the lock, and the lock drops LoRAs you added. Canvas quotes $0.005 a megapixel where fal bills $0.0085 for a look with LoRAs (the default General look has them). On fal, Soul HD's 1080p 3:2 and 2:3 would bill 3 megapixels if fal rounds up as its price text suggests (unconfirmed). On the open engine the look's LoRAs, even its Hugging Face ones, need Settings → LoRAs' LoRA folder (or the files placed by hand). The photo-booth overlay is one print, not a 4-shot strip. A studio picker's other-engine tab lists the Originals only after you switch engine, and on Soul HD a non-lettering look doesn't move the run back to Fuobe Soul (it runs on its words, with a note). Image to image has no strength control, and there is no 1080p upscale step (1080p is made directly at about 2 megapixels).
+ - **Fuobe DoP:** the Replicate fallback can't make start-and-end-frame clips (transitions need a fal key) and takes one LoRA per Wan 2.2 stage; the pre-run price is fal's even when the run goes to Replicate. The grade is a hand-off to Color grading, not applied automatically. Roll Transition runs on its words for a Wan start-and-end-frame clip, and the Mixed Media effects run on words. Many more moves now load LoRAs on the open engine, so a move whose LoRA ComfyUI doesn't have stops before the job (no charge) when Fuobe can't fetch it: no LoRA folder set, or no civitai key for a civitai file. That includes six Cinema Studio moves on your GPU (Handheld, POV, Robot Arm, Snorricam, Tracking, Side Tracking); in Cinema's cloud they now run on their words. On a 24 GB GPU the 17 moves on Fuobe DoP · LTX need its 32 GB; pick Fuobe DoP to run their words. Reading the code suggests a cloud link to a words-only move might start on Kling 2.5 Turbo instead of keeping your model (not run). The `ltx23-t2v-lora` workflow ships but nothing uses it yet.
+ - **Image to 3D:** no open rigging (UniRig has no ComfyUI pack verified on 0.41) and no open Pick an object; splats aren't drawn in the browser, and demo mode returns a plain model for splat and rig jobs, so the splat card was checked only on hand-edited rows. Storing every format makes cloud 3D results finish slower and use more disk. The open text-to-3D chain can't wait for another step's words (a Canvas text node, say); it is refused with a message. Retrying a failed text-to-3D run may lose the card's link to its source picture (from reading the code). MoGe always estimates the multi-view field of view: the graph takes a fixed one, but the page doesn't offer it. A multi-view job from Assist or the API that doesn't name its sides takes the photos as front, left, back, right, in that order.
+ - **Canvas:** two tabs on one board overwrite each other (each save sends every page). Cloud concatenator: muting a clip made earlier in the same run fails the film when that clip has no sound (the next run works); cutting a clip from a table row needs both ends set; its silent sound files are never deleted. A per-row node re-run only because of something upstream shows every row's price, though only rows that run are billed, and only a row's first output passes on. On a both-engines install a video Translate node always uses ElevenLabs Dubbing; on the open engine the dub is a hand-off to Translate & dub, not a node output. Drawing, comments and page tabs are desktop only. Groups don't nest (membership is by position).
+ - **FPS Boost, SDR to HDR and Export on the open engine:** FPS Boost, SDR to HDR and EXR still load the whole clip; Generate is greyed when a clip needs more than half of ComfyUI's RAM (5 s of 1080p at 24 → 60 fps is refused on a 32 GB ComfyUI). HDR is H.264 High 10 (core ComfyUI has no H.265 encoder; H.265 HDR10 is cloud only). "ProRes 422 HQ" carries 4:4:4 samples. SeedVR2 restores each 33-frame pass on its own, so seams are possible (not measured). A cancelled or failed pass leaves an idle ffmpeg and a partial .mov in ComfyUI's output folder.
+ - **Frames:** in an open film each still is on screen for two video frames (about 1/8 s). Ten stills mean nine or ten 20-step Wan clips on your GPU: free, but slow. On Lightning the stretch after the last frame is a 4-step clip next to 20-step pairs. Reuse on an open Frames film brings back the join step, not the frames.
+ - **3D scenes:** the open MoGe mesh drops sky and far-away areas, leaving empty space for the re-render to fill. Every cloud scene depends on Marigold returning the Spectral colour map of fal's example output, the only thing the decoder was checked against. The open re-render is told the LoRA's reference pose with the capture as image 1; that is untested on a GPU.
+ - **Some models are in the catalog but no studio page offers them.** Gemma 4 speech translate is hidden and nothing uses it yet (API only). Bria Expand and Image to SVG (VTracer, hosted) run from a Canvas model node or the API. (The round-4 3D models, Meshy Rigging included, are now in the Image to 3D studio.) In the ⌘K palette, 33 models, those of Remove object (H3 Person Removal included), Genjutsu (Character swap included), FPS Boost / SDR to HDR / Export and the 3D scene among them, open the filtered Models page instead of their own studio.
+ - **Mixed Media Per frame (cloud):** the look can shift slightly every 12 frames, because each lane of 12 starts from the approved preview, not from the frame before it. Seedream 5.0 Flash takes no fixed seed, so its frames may vary more than Nano Banana 2's. Per frame is the default and costs more than Fast (about $6 for 10 s at 1K, where Fast was one call); an API call with no model and no mode now gets Per frame, and a model sent for the wrong mode gets a 422. Every frame is downloaded to Fuobe's storage and uploaded again.
+ - **LoRAs:** a civitai LoRA sent to the cloud without a civitai key fails the run instead of being left out; only Fuobe Soul's looks leave such a LoRA out and say so, and Cinema's cloud moves run on their words (a motion or effect elsewhere still stops before it is charged). LoRAs licensed for your GPU only now go to the cloud by default, and civitai mirrors are made even when civitai doesn't answer; turn on "Keep them on your GPU" (under "LoRAs licensed for your GPU only") in Settings → Models & licences to stop both. The composer's price ignores the LoRA endpoint's price (the server's estimate uses it), and Replicate's LoRA models are priced at fal's base rate. The warning about a left-out LoRA is gone after a reload. The video-to-video estimate bills the length picked, while LTX-2.3 follows the input clip's length. Fuobe writes LoRA files itself, so the LoRA folder must be one the Fuobe machine can write to (ComfyUI on the same PC, or its `models/loras` shared); otherwise place files by hand, as for the two gated Hugging Face LoRAs (there is no Hugging Face token setting).
+ - **Content Factory:** TikTok and Instagram links work only when the page exposes the video (YouTube always asks for an upload). The paid brief call starts when the series page is next opened, not in the background. A pasted link downloads while you wait (up to 200 MB). Through Generate in Claude, an episode over 8 scenes comes out as separate videos to join in Video tools → Join clips, and runs use Settings → Engine mode, not the composer's switch (the dialog says so). The preset grid is 8 local styles with no view counts; Explore and My presets tabs, and saving a brief as a preset, aren't built. Every series makes an ordinary Faceless channel, and deleting the series deletes that channel. The Generate lock and the brief writer live in one server process, and old drafts and orphaned series are cleared only when a new series is made.
+ - **AI Influencer builder:** picks are lost on reload (finished sheets come back from the feed). The two clash messages are copied word for word from the Higgsfield research (worth a copy check). Not built yet: option preview pictures, a style reference, batches, hand-offs to Genjutsu and 3D.
+ - **Evaluation harness:** 87 of the 139 looks in its Soul test set use civitai LoRAs, which it keeps off cloud runs for now. Its Mixed Media test set measures Fast, not Per frame. A DoP case with few clips can be promoted on 2 blind ratings (otherwise 6). Fuobe Cinema, the Genjutsu Originals and Soul ID's trainers are in the catalog now; variants that target an Original that isn't yet (Shorts, Speak) still skip. A Soul ID run needs your own photos of a person who consented.
+ - **Open-engine limits.** ACE-Step makes up to 240 s of music; Faceless loops it with crossfades up to 600 s, and loops (Faceless and Audio → Loop) stop at 600 s on both engines. The joins that keep a clip's sound hold every frame in RAM at 25 fps (about 1 GB per 8 s at 480x848). InfiniteTalk lip re-sync is capped at 40 s per job (for dubs, the whole source length). Whisper captions refuse clips that need more than half the server's RAM (the estimate isn't measured).
- **Qwen-Image-Edit keeps the first image's shape** on the open engine. Photodump, Fashion Factory and Character Sheet turn the aspect picker off and say so; the open Character Sheet asks for a landscape photo first.
- - **Layers:** text detection is cloud only (no open OCR model; on the open engine you type the lines to change). A decomposition that finishes while the editor is closed is laid out only when the project is opened (the server can't decode PNG alpha). Upscale doesn't resize the document; downloads use the layers' detail instead.
- - **Cinema Studio:** Cinema Studio 4.0 runs at up to 720p through the public API. Open routes take no reference clips. 3D recomposition, collaboration and community publishing are out of scope. Spend uses the estimate stored at creation for takes deleted for good, so it can be slightly over-counted.
+ - **Layers:** the editor stays read-only on phones, and Assist and MCP can't reach Inpaint, the Enhancer or Save as element. Inpaint and edits on see-through layers run a background cut-out afterwards instead of reusing the layer's own transparency; whether that gives clean text layers with real models is unchecked. A decomposition that finishes while the editor is closed is laid out only when the project is opened (the server can't decode PNG alpha). Upscale doesn't resize the document; downloads use the layers' detail instead.
- **Shorts Studio:** the 9:16 crop is a plain centre crop (no subject tracking). Kling O3 4K's 720 px minimum input isn't checked. The one-submit-per-click guard (`requestId`) is in memory, so a restart forgets it.
- - **Marketing:** Click to Ad videos have no logo end card (the logo is used by the Ads Studio compositor and the brand line in prompts). Brand kits are matched by host and port, so one site on two ports gets two kits. An Ad Multiplier reference whose header Fuobe can't read (e.g. WebM) gets a picture-only join.
- - **Faceless / Explainer:** one narration take per episode, re-timed to the scenes; stage two waits for it, so a first render takes a few seconds longer and a narration change takes two passes. Every new channel draws an avatar (about $0.15 on the cloud). Scripts over 64 KB are flushed without keepalive, so the last edit may not survive closing the tab. PDF and Word sources aren't read (Assist projects can read PDFs).
- - **Formats the header reader doesn't know** (WebM, MKV, Ogg on the open engine) fall back to coarse defaults: caption windows to the millisecond, InfiniteTalk at 16:9 and its frame cap, a mux bed as long as the longest known track. Shorts and Mixed Media read WebM headers themselves.
+ - **Marketing:** Click to Ad now ends on a logo card by default when the product kit has a logo (2.5 s longer, priced in); switch End card off for the old ads. The open end card needs the card drawn on the page, so an API call without one is refused on the open engine; the cloud's own card (for an API call with no drawn card) skips SVG logos. The cloud end card, with its silent sound step, hasn't run through Generate in the browser (unit tests and the estimate only). Brand kits are matched by host and port, so one site on two ports gets two kits. An Ad Multiplier reference whose header Fuobe can't read gets a picture-only join. Its Kling O3 and Happy Horse edits recreate at most the first 15 s of a 4–30 s selection (the run says so), and the cloud default is always Kling O3.
+ - **Faceless / Explainer:** one narration take per episode, re-timed to the scenes; stage two waits for it, so a first render takes a few seconds longer and a narration change takes two passes. Every new channel draws an avatar (about $0.15 on the cloud). Scripts over 64 KB are flushed without keepalive, so the last edit may not survive closing the tab. The first change, retime or Retry of an older Frame by frame episode re-makes all its clips as Ken Burns moves. The cloud Ken Burns zooms only (no pan; it always starts or ends on the whole picture). A plain open ACE-Step bed (no loop) is still cut off when the film gets shorter. Upscale to 1080p is still offered on an episode that is already 1080p (it stops with "already 1080p").
+ - **Audio Loop and Join on the cloud:** whole plays (a loop can come out longer than asked; the result says its real length) and hard cuts only.
+ - **Clips whose header neither reader knows** (MP4 / MOV and WebM / Matroska are read) fall back to coarse defaults: caption windows to the millisecond, InfiniteTalk at 16:9 and its frame cap, a mux bed as long as the longest known track.
**Library, data and security**
- - Helper steps (features `shorts-step`, `mixed-media-step` and other chain steps) are listed in the Library; there is no filter that hides them yet.
- - Uploads can't be deleted (they need an in-use check first). Folders are flat.
- - `ASSET_REFS` (the tables a permanent delete checks before removing an output file) doesn't list `dub_sessions` or `katana_jobs`. If a dub or Katana job started from a *generated* clip and every generation that used that clip is later deleted for good, the job's row points at a missing file. Uploads are never removed by a permanent delete.
+ - "Move to" and "new folder" in the Library's selection bar still act on the whole selection, including results hidden by a search or filter; the count and the other actions follow the shown results.
- Without Web Locks (plain `http://` on a LAN IP) each visible tab reads its own live stream; six or more visible windows on one host could hit the browser's connection limit.
- - **Sign-in is off by default.** Without a password Fuobe answers only on local addresses and names in `FUOBE_ALLOWED_ORIGINS`, but anyone who can reach it can use it (and your keys). With a password, a page that rebinds DNS can still post password guesses; the throttle caps that at roughly 15–20 a minute. Without `FUOBE_TRUST_PROXY=1` behind a reverse proxy, all visitors share one throttle (slowed, never locked out). `comfyLorasDir` and `aiToolkitDatasetDir` make the server write files where you point them.
-- **Sign-in is off by default.** Without a password Fuobe answers only on local addresses and names in `FUOBE_ALLOWED_ORIGINS`, but anyone who can reach it can use it (and your keys). With a password, a page that rebinds DNS can still post password guesses; the throttle caps that at roughly 15–20 a minute. Without `FUOBE_TRUST_PROXY=1` behind a reverse proxy, all visitors share one throttle (slowed, never locked out). `comfyLorasDir` (now also where LoRAs are downloaded) and `aiToolkitDatasetDir` make the server write files where you point them. Save & test lets a signed-in caller make the server fetch a ComfyUI or Ollama address without saving it (saving it already allowed the same). Share links skip sign-in by design (next bullet).
++- **Sign-in is off by default.** Without a password Fuobe answers only on local addresses and names in `FUOBE_ALLOWED_ORIGINS`, but anyone who can reach it can use it (and your keys). With a password, a page that rebinds DNS can still post password guesses; the throttle caps that at roughly 15–20 a minute. Without `FUOBE_TRUST_PROXY=1` behind a reverse proxy, all visitors share one throttle (slowed, never locked out). `comfyLorasDir` (now also where LoRAs are downloaded) and `aiToolkitDatasetDir` make the server write files where you point them. Save & test lets a signed-in caller make the server fetch a ComfyUI or local LLM server address without saving it (saving it already allowed the same). Share links skip sign-in by design (next bullet).
+ - **Share links are public.** GET and HEAD on `/s/<token>` and its files pass without a session, even with a password set, after the host allowlist and the cross-site check. Set `FUOBE_PASSWORD` so the rest of the studio stays locked (the Share dialog warns if not): on a password-less install an outside visitor can open a link only if the host is in `FUOBE_ALLOWED_ORIGINS`, which opens the whole studio too. Only a SHA-256 of each token is stored. Wrong tokens get 404, and 429 past 100 a minute; behind a reverse proxy, `FUOBE_TRUST_PROXY=1` lets Fuobe lock out the client that guesses, and without it no one is locked out. The files route serves only what the share page shows, and blanks generation data with a hand-written cleaner (`src/server/media-clean.ts`): a bug there would leak metadata or hide a file.
+ - **Models & licences has no admin role:** anyone who can sign in, or holds an API token, can change the switches (`PUT /api/settings/models`); with no password, anyone who can reach the install.
+ - Assist connector tokens and URLs are stored in plain text in SQLite, like the other keys, and masked before they reach the browser.
+ - **LoRA downloads through the API:** anyone with a Fuobe API token can name a LoRA link in `POST /api/generations` (at most 8; only links on huggingface.co, hf.co, civitai.com, fal.media and replicate.delivery) and make the server download it into the LoRA folder. Links on hf.co, fal.media and replicate.delivery aren't fingerprint-checked and have no size limit (60-minute timeout).
+ - **Canvas data format:** a canvas is saved as pages (`{pages:[…]}`) the next time it is saved, and older Fuobe builds can't read it after that; back up the data folder before trying this version if you might go back. Scripts that read `canvas.graph` from `GET /api/canvases/:id` must read `canvas.pages` now. No database migration was needed.
+ - **Migrations 21 and 22** (round 4, part 5) run on their own at the first start. 21 adds the Character Swap Studio's `swap_projects` table. 22 deletes the saved Higgsfield key, turns "Higgsfield first" into Automatic and marks Higgsfield ads `baked`; it can't be undone, so back up the data folder (or `FUOBE_DATA_DIR`) before upgrading if you might roll back.
+ - **Fuobe Soul's finish route** (`POST /api/generations/[id]/finish`) takes the PNG the browser made and puts it in place of the output; the raw picture stays as `meta.original`, the first upload wins, and the route is guarded only by the app's usual sign-in.
- `MAX_INLINE_TEXT` caps a result's inline text at 64,000 characters; `meta.cues` of a very long transcript stays inline.
-- The first routing check after the Ollama or ComfyUI URL changes can hold a request for up to 1.5 s when the host doesn't answer.
+- The first routing check after a local LLM server's or ComfyUI's URL changes can hold a request for up to 1.5 s when the host doesn't answer.
- - Unknown Cinema, Canvas and Assist project ids show a not-found state with HTTP 200; only `/apps/<unknown>` returns a real 404.
**UI leftovers (small)**
- - Canvas: keystroke → paint is 19 ms at 60 nodes and 29 ms at 120 (target 16 ms). Element nodes don't follow a later rename of their element.
- - Video tools → Trim and the Ad Multiplier use simple in/out pickers, not the shared `VideoTrimmer`. `options.sourceLanguages` (spoken language for transcribe models) has no picker.
- - Some buttons still call `navigator.clipboard` directly and fail on plain-http LAN origins (feed, viewer, result actions, Cinema workspace / feed / projects, Layers top bar); `copyText` in `src/lib/clipboard.ts` is the fix. Studio pages nest a second `<main>`.
- - The Edit studio shows prompt suggestions for promptless models (e.g. FASHN). Inpaint's blocker after a new image still asks to add an image. The Video Background Remover app's note says Fuobe has no video matting model; Video tools → Remove background does whole videos. On narrow Assist tiles a "Demo" badge can overlap the "TEXT" label.
+ - Canvas: keystroke → paint at 60 nodes measured 27–36 ms in round 4, part 3, in dev mode on a loaded shared machine (target 16 ms; round 3 measured 19 ms at 60 nodes and 29 ms at 120). No production build was measured.
+ - Layout shift: in a browser that never opened Home, on an install that is already connected, the Get started card shows briefly once (about 0.16 desktop / 0.38 phone). Home's demo-mode line still shifts the page by about 0.03 for returning users, and a brand-new browser on an install with results shifts about 0.033 on desktop when Recent arrives.
+ - At a 4× CPU slowdown, the first visit to Marketing after a hover takes 760–923 ms against 493–649 ms before (pages now prefetch on hover instead of at load).
+ - Settings' Engine mode section still sits above the providers. Layers, Captions, Trim and Translate open from the palette without preselecting the picked model.
+ - When Assist asks which still to animate, a length given earlier ("for 5 seconds") isn't carried over to the bare-number reply.
+ - In Frames mode, reference images left in the draft still count in the folded "N attached" chip but aren't sent.
+ - The Faceless wizard can show several `<main>` elements after a client-side navigation, and its phone footer price line wraps between the two buttons.
+ - `/mixed-media`'s phone bottom bar always says "Add a clip", even with a clip loaded.
+ - `shell.mjs`'s last step ("Show more focuses the first new card") is timing-sensitive on a cold dev server.
+ - The one-off failure of `cinema-original.mjs` at 390 px in PR #12's run was never reproduced. The Cinema and Genjutsu checks now wait for closing dialogs, which removes the likely cause (a click while a dialog was still closing), but the fix isn't proven against that failure (§1). If a dialog never finishes closing, the wait gives up after 5 s and the script carries on.
+ - The Scheduled list says "uses your connectors" for a task that opted in even when its mode isn't Claude (no connectors are sent then).
- The files route logged "ReadableStream is already closed" once when a crashed test browser dropped its connections; not reproduced.
**Environment and licences**
@@@ -206,15 -285,14 +286,14 @@@
## 4. What's next (prioritized)
- 1. **Live-key smoke test** of the round-3 cloud routes with the highest risk: Seedream 5.0 Layers, Recraft V4 Styles (style id), FASHN, Mirelo SFX / Sonilo, Scribe v2, Auto Subtitle / VEED, Hunyuan3D 3.1, Gemini Omni Flash edit, the fal FFmpeg tools (compose, loudnorm, forced alignment, scale-video, extract-audio), HeyGen / ElevenLabs dubbing, Higgsfield Cinema Studio 4.0 with reference clips, Ads Studio and Soul 2.0 + Soul ID; then a first real Assist conversation on Claude and on Ollama, with a skill and a project. Fix any schema surprises.
- 2. **GPU run** of the round-3 open set: Qwen-Image-Layered, Qwen-Image-Edit Style Reference, Z-Image Turbo · Palette, Wan 2.2 Fun VACE restyle, Z-Image Mixed Media, Stable Audio 3, MelBand + Qwen3-ASR, Chatterbox, InfiniteTalk lip re-sync, TRELLIS.2 and the FLUX.2 [klein] try-on; then one whole open UGC film, Faceless episode and dub. Record VRAM and timings and tune defaults.
- 3. **Wire Assist and MCP into the studios:** register the `STUDIO_ROUTES` adapters (Layers, Shorts, dub / captions, Ads, Faceless) so jobs open as real sessions; name `katana` in the system prompt and MCP instructions; point the skills' `studio:` links at `/faceless`, `/katana`, `/ads/multiplier`, `/marketing` and `/character-sheet`.
- 4. **Close the engine seams:** the cloud dub background through `ffmpeg-compose`; a per-frame cloud Mixed Media pipeline; an open audio concat / loop (music beyond 240 s) and an open pan / zoom workflow for Frame by frame; an open OCR model for Layers; LatentSync and ThinkSound offered in Lipsync and Sound effects; PDF and Word sources in the Explainer (Assist's `unpdf` reader could serve it); a logo end card for Click to Ad.
- 5. **Library:** hide `*-step` helper generations by default, nested folders and pins, deleting uploads safely, and `ASSET_REFS` entries for the dub and Katana tables.
- 6. **UI clean-up:** the shared `VideoTrimmer` in Trim and the Ad Multiplier, a spoken-language picker for transcription, `copyText` everywhere, real 404s for unknown project ids.
- 7. **Virality Predictor:** an optional, clearly non-commercial TRIBE v2 worker (`docs/workers/tribe-v2.md`).
- 8. **Accounts:** several users with their own libraries, shareable links, a community feed.
- 9. **Real preview media** for apps, motions, effects and studio presets (the previews are procedural today).
+ 1. **Measure the Originals: the evaluation harness on a GPU and with paid keys.** Round 4's packages are all in: PR #13 brings the last ones (the Character Swap Studio, O7 and the fixes for what PR #12's checks found). None of the Originals is measured yet. Next is the harness running `soul`, `soul-cinema`, `soul-hex`, `soul-id`, `dop`, `dop-mix`, `cinema` and `genjutsu` on a GPU and in the cloud, which also decides whether the 152 moved presets stay on Fuobe DoP in the cloud and whether the 211 words-only ones leave Kling 2.5 Turbo, and settles Fuobe Cinema's guesses (the edit strength, the Cast and Location looks, a zoom as a dolly). No Original counts as verified until the harness has measured it on a GPU or with a paid key.
-2. **Live-key smoke test** of the riskiest cloud routes: round 3's (Seedream 5.0 Layers, Recraft V4 Styles, FASHN, Mirelo SFX / Sonilo, Scribe v2, Auto Subtitle / VEED, Hunyuan3D 3.1, Gemini Omni Flash edit, the fal FFmpeg tools, HeyGen / ElevenLabs dubbing, Ads Studio), round 4, part 1's (Topaz Video by size, ByteDance / Starlight / FLUX.3 Upscale, Topaz FPS Boost and SDR to HDR, the Bria erasers, VOID, SAM 3.1, hosted VACE, FLUX 3 Max keyframes, Marigold V2, fal's Ken Burns and merge-audios, the cloud dub mix), part 2's (per-frame Mixed Media, the cloud end card, Florence-2 OCR, the Inpaint and Enhancer models, Content Factory's reading, the AI Influencer sheets, the hosted LoRA models, a civitai download and a mirror) and part 3's (Fuobe Soul and Soul HD on fal and Replicate, Fuobe DoP on fal's Wan 2.2 A14B and LTX-2.3 and its Replicate fallback, LTX-2.5 Fast's focus shift, the hosted relight, SAM 3D Objects, Meshy multi-view and rigging, Tripo text to 3D, TripoSplat, the Canvas concatenator's fal steps, ElevenLabs Voice Changer and Dubbing) and part 4's (Fuobe Cinema on LTX-2.3 22B, extend-video's whole clip and the backward extend first; the Genjutsu Originals; MiniMax H3 with Akatz Labs' LoRA and H3 Max Recast; Wan 2.2 Animate Replace, SCAIL-2 and Wan Motion; the Sunburst first frame; the eight fal trainers and the five hosted LoRA models, FLUX.2 [dev]'s ComfyUI-named LoRA first; real provider files through the share metadata cleaner) and part 5's (the Character Swap Studio's cloud chain: MiniMax H3 takes and their real prices, frame-exact trims, scale-video and merge-videos at 24 fps with mixed sources, SAM 3.1's `frame_index`, fal reading AVI; Happy Horse 1.1 and the Happy Horse video edit; the models that replaced Higgsfield's); then a first real Assist conversation on Claude and on Ollama, with a skill, a project, a scheduled task and a remote MCP connector. Fix any schema surprises.
++2. **Live-key smoke test** of the riskiest cloud routes: round 3's (Seedream 5.0 Layers, Recraft V4 Styles, FASHN, Mirelo SFX / Sonilo, Scribe v2, Auto Subtitle / VEED, Hunyuan3D 3.1, Gemini Omni Flash edit, the fal FFmpeg tools, HeyGen / ElevenLabs dubbing, Ads Studio), round 4, part 1's (Topaz Video by size, ByteDance / Starlight / FLUX.3 Upscale, Topaz FPS Boost and SDR to HDR, the Bria erasers, VOID, SAM 3.1, hosted VACE, FLUX 3 Max keyframes, Marigold V2, fal's Ken Burns and merge-audios, the cloud dub mix), part 2's (per-frame Mixed Media, the cloud end card, Florence-2 OCR, the Inpaint and Enhancer models, Content Factory's reading, the AI Influencer sheets, the hosted LoRA models, a civitai download and a mirror) and part 3's (Fuobe Soul and Soul HD on fal and Replicate, Fuobe DoP on fal's Wan 2.2 A14B and LTX-2.3 and its Replicate fallback, LTX-2.5 Fast's focus shift, the hosted relight, SAM 3D Objects, Meshy multi-view and rigging, Tripo text to 3D, TripoSplat, the Canvas concatenator's fal steps, ElevenLabs Voice Changer and Dubbing) and part 4's (Fuobe Cinema on LTX-2.3 22B, extend-video's whole clip and the backward extend first; the Genjutsu Originals; MiniMax H3 with Akatz Labs' LoRA and H3 Max Recast; Wan 2.2 Animate Replace, SCAIL-2 and Wan Motion; the Sunburst first frame; the eight fal trainers and the five hosted LoRA models, FLUX.2 [dev]'s ComfyUI-named LoRA first; real provider files through the share metadata cleaner) and part 5's (the Character Swap Studio's cloud chain: MiniMax H3 takes and their real prices, frame-exact trims, scale-video and merge-videos at 24 fps with mixed sources, SAM 3.1's `frame_index`, fal reading AVI; Happy Horse 1.1 and the Happy Horse video edit; the models that replaced Higgsfield's); then a first real Assist conversation on Claude and on a local model (Ollama or LM Studio), with a skill, a project, a scheduled task and a remote MCP connector. Fix any schema surprises.
+ 3. **GPU run** of the open sets: round 3's (Qwen-Image-Layered, Qwen-Image-Edit Style Reference, Z-Image Turbo · Palette, Wan 2.2 Fun VACE restyle, Z-Image Mixed Media, Stable Audio 3, MelBand + Qwen3-ASR, Chatterbox, InfiniteTalk lip re-sync, TRELLIS.2, the FLUX.2 [klein] try-on), round 4, part 1's (Wan 2.1 VACE remove / swap / insert, VOID, Wan Animate 2, SeedVR2 in passes and its seams, a Frames film, the MoGe → Qwen re-render, a full open Faceless render), part 2's (OvisOCR3, the Gemma 4 brief, FLUX.1 Fill [dev] Inpaint, the Enhancer, the AI Influencer chain, runs with LoRAs) and part 3's (the Soul looks, Soul Cinema and `z-image-turbo-i2i`, Fuobe DoP on Wan 2.2 and the LTX-2.3 graphs, the relight step, TRELLIS.2 Multi-view, TripoSplat and the open text-to-3D chain) and part 4's (the three H3 graphs first, since none has loaded in a ComfyUI yet, then Character swap parts over 15 s; Fuobe Cinema's Wan 2.2 Lightning takes with camera LoRAs and Fun Camera poses; Soul ID's AI-Toolkit trainings on each base, then the LoRA in ComfyUI) and part 5's (the Character Swap Studio's two H3 Relay graphs, a continuation from a take's master, and the mask memory guard measured on a real server); then one whole open UGC film, Faceless episode and dub, and the harness on the Originals. Record VRAM and timings and tune defaults.
+ 4. **Fuobe Originals**, open-weight versions of Higgsfield's own products ([`fuobe-originals-recipes-5.md`](research/fuobe-originals-recipes-5.md)). Done in round 4, part 2 (PR #9): O1, LoRAs on both engines, and O8, the evaluation harness. Built in round 4, part 3 (PR #10): O2 Fuobe Soul (139 looks, Soul HD, Soul Cinema and Soul HEX on both engines) and O4 Fuobe DoP (camera motions, Mix and effects on both engines), the first looks and presets that take their LoRAs from the library. Built in round 4, part 4 (PR #12): O6 Fuobe Cinema (Cinema Studio's video, stills, Soul Cast and Soul Location on Originals), O3 Fuobe Soul ID (characters and looks on every trainer, moodboards trained as looks) and O5 Fuobe Genjutsu with Character swap on MiniMax H3. Done in round 4, part 5 (PR #13): O7, the Higgsfield provider removed. Next, after the harness (item 1): O9 Mixed Media and Shorts on hosted open models (with DoP's Mixed Media effects), O10 Marketing, Ads, AI Influencer, Photodump and Fashion on Originals (until then Marketing images run on GPT Image 2.5, Ads and the AI Influencer app on Nano Banana Pro, and Photodump and Fashion keep what they use: Fuobe Soul, plus partner models such as FASHN try-on), O11 the rebranded open tools, Speak and finishing, O12 Fuobe's own LoRAs and the motion library, O13 Popcorn, Evolution and Effects 2.0.
-5. **Round-4 follow-ups:** from part 5, the Happy Horse video-edit price, Ollama's reachability check (a timeout still counts as down), the Library's engine label for old runs, Soul 2.0 palettes as a palette lock, and Assist / MCP tools for the Character Swap Studio; from earlier parts, palette entries for the studios still missing (`MODEL_STUDIOS` / `TOOL_PAGES` in `src/lib/palette-index.ts`); Assist / MCP tools for Genjutsu (Character swap included), Remove object, Content Factory, the AI Influencer builder and Layers' new tools; an open crossfade join for Remove object's windows; FPS Boost, SDR to HDR and EXR in passes; "Move to" on the shown selection only; a fingerprint check or size limit for LoRA links on hf.co, fal.media and replicate.delivery; a civitai LoRA without a key left out with a note instead of failing for motions and effects too (Fuobe Soul and Cinema's cloud moves do it); the composer's price with LoRAs, and Canvas's for Fuobe Soul; Fuobe Soul's finish for API, CLI and Canvas runs; the harness measuring per-frame Mixed Media; Canvas keystroke → paint under 16 ms, measured on a production build; splats drawn in the browser and an open rigging route; Soul ID trainings under the Models & licences switches, and hosted models classed by their weights' licence; a Settings field for the AI-Toolkit address; Replicate trainers and Wan 2.2 image Soul IDs; reference clips on Fuobe Cinema itself; Canvas boards as share links; a tool list and connection test for connectors, a notice when an Ask-first plan waits, and scheduled tasks from MCP and the CLI.
++5. **Round-4 follow-ups:** from part 5, the Happy Horse video-edit price, the local LLM servers' reachability check (a timeout still counts as down), the Library's engine label for old runs, Soul 2.0 palettes as a palette lock, and Assist / MCP tools for the Character Swap Studio; from earlier parts, palette entries for the studios still missing (`MODEL_STUDIOS` / `TOOL_PAGES` in `src/lib/palette-index.ts`); Assist / MCP tools for Genjutsu (Character swap included), Remove object, Content Factory, the AI Influencer builder and Layers' new tools; an open crossfade join for Remove object's windows; FPS Boost, SDR to HDR and EXR in passes; "Move to" on the shown selection only; a fingerprint check or size limit for LoRA links on hf.co, fal.media and replicate.delivery; a civitai LoRA without a key left out with a note instead of failing for motions and effects too (Fuobe Soul and Cinema's cloud moves do it); the composer's price with LoRAs, and Canvas's for Fuobe Soul; Fuobe Soul's finish for API, CLI and Canvas runs; the harness measuring per-frame Mixed Media; Canvas keystroke → paint under 16 ms, measured on a production build; splats drawn in the browser and an open rigging route; Soul ID trainings under the Models & licences switches, and hosted models classed by their weights' licence; a Settings field for the AI-Toolkit address; Replicate trainers and Wan 2.2 image Soul IDs; reference clips on Fuobe Cinema itself; Canvas boards as share links; a tool list and connection test for connectors, a notice when an Ask-first plan waits, and scheduled tasks from MCP and the CLI.
+ 6. **Virality Predictor:** an optional, clearly non-commercial TRIBE v2 worker (`docs/workers/tribe-v2.md`).
+ 7. **Accounts:** several users with their own libraries and a community feed (sharing is read-only links today).
-8. **Real preview media** for apps, motions, effects and studio presets (the previews are procedural today); the O8 harness (`pnpm eval:covers`) can turn promoted, reviewed GPU or cloud renders into covers once there are some.
++8. **Real preview media.** 480 of the 487 app, motion and effect cards now show covers from ComfyUI preview renders (474 stills, 6 clips; `pnpm eval:covers --from-masters`). The covers and the filled manifest wait for a person's review before they are committed; until then the committed manifest is empty and every card keeps its procedural preview. Left: the other 7 (two apps and five camera moves), clips for more motion and effect cards (their end frames are still rendering), the studio presets and Fuobe Soul's looks, and covers from measured runs (`pnpm eval:covers <runId>`), which replace a preview render's cover for the same id.
## 5. How to reproduce the checks
diff --cc next.config.ts
index 20332fd2,60b44f74..7fd3ec2a
--- a/next.config.ts
+++ b/next.config.ts
@@@ -8,16 -8,6 +8,15 @@@ const nextConfig: NextConfig =
// The sign-in proxy buffers request bodies (10 MB by default): uploads take up to 200 MB plus the form overhead.
proxyClientMaxBodySize: "210mb",
},
+ async headers() {
+ return [
- // Preset preview media (scripts/build-previews.mjs) has its content hash in every file name,
- // so it can be cached for good; the public folder's default is max-age=0.
- { source: "/previews/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }] },
+ // Vendored scripts (public/vendor: the 3D viewer's meshopt decoder) keep their name across upgrades:
+ // a day, then revalidated in the background.
+ { source: "/vendor/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=604800" }] },
++ // Preset covers (public/previews, pnpm eval:covers) keep their name when a cover is made again: the same.
++ { source: "/previews/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=604800" }] },
+ ];
+ },
async redirects() {
return [
{ source: "/characters", destination: "/elements", permanent: true },
diff --cc pnpm-lock.yaml
index 63725187,0e422101..09ff6025
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -3412,9 -3394,9 +3436,12 @@@ packages
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==}
+
+ resolution: {integrity: sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==}
+
resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==}
@@@ -8127,8 -8077,8 +8176,10 @@@ snapshots
+
+
dependencies:
decode-named-character-reference: 1.3.0
diff --cc scripts/comfy/README.md
index 5e39a97a,4829f421..85f8fbb6
--- a/scripts/comfy/README.md
+++ b/scripts/comfy/README.md
@@@ -205,6 -205,155 +205,161 @@@ node validate-workflows.mjs <ids> wan21
VOID (197 frames, 7.880 s of picture and of sound, 672×376) and a window at 50 s of a 60 s clip (0.6 s instead of
2.6 s with the whole-clip decode). MoGe's guard ran on 1536×3000, 3000×1536 and 1024×768 stills.
+ ### Round-4 video finishing (r4/video-finish, 2026-10-23)
+
+ Five hand-built entries for the Upscale hub's FPS Boost, SDR to HDR and Export modes and for R4-38 (open video
+ upscaling decoded the whole film: about 38 GB of float frames for 30 s at 480p). No new node pack: core nodes plus
+ VHS's `VHS_LoadVideo` meta-batch, `VHS_BatchManager`, `VHS_SelectEveryNthImage` and `VHS_VideoCombine`.
+ `video-sdr-to-hdr` also binds `colorSpace` (HLG, or `HDR PQ` for HDR10), and `video-export-exr` saves a preview clip.
+
+ ```bash
+ npm run build -- interpolate-rife-fps upscale-video-esrgan-chunked upscale-video-seedvr2-chunked video-export-pro-chunked video-sdr-to-hdr-exr video-sdr-to-hdr video-export-exr
+ node validate-workflows.mjs <the same ids> --shared
+ ```
+
+ | id | capability | what | ran for real here |
+ |---|---|---|---|
+ | `interpolate-rife-fps` | interpolate | FrameInterpolate by m, keep every n-th: source fps × m / n = target × slowdown; output fps computed in the graph | yes: 24 → 60, 25 → 30 at 2× slow, 30 → 24 |
+ | `upscale-video-esrgan-chunked` | upscale-video | Real-ESRGAN in passes of `framesPerBatch` frames, scaled to `shortSide`, one H.264 encode across passes | yes: 30 s 144p → 1080p, 47 passes, +0.87 GB RSS |
+ | `upscale-video-seedvr2-chunked` | upscale-video | SeedVR2 3B in passes of 4n+1 frames (no context across passes: a seam is possible) | no (GPU); /prompt only |
+ | `video-export-pro-chunked` | export-video | ProRes 422 HQ / 4444, H.265 10-bit, FFV1, H.264 in passes, with the sound | yes: ProRes, H.265, FFV1 |
+ | `video-sdr-to-hdr-exr` | sdr-to-hdr | scene-linear Rec.2020 half-float EXR per frame + an HLG preview | yes: 60 frames + preview |
+
+ - **What the provider does** (`src/server/providers/comfyui.ts`, `src/lib/av/fps.ts`, `src/lib/av/video-finish.ts`): m and n
+ from the clip's header frame rate (the cheapest exact pair, the nearest one for 29.97-style rates); FrameInterpolate
+ linked out when m is 1; slow motion drops the sound link; params.format → VHS format / ProRes profile, CreateVideo's
+ colour space, or the EXR graphs; EXR frames zipped one at a time onto the preview clip (`meta.artifacts.exr`);
+ `framesPerBatch` sized from the clip so a pass holds about 1.5 GB of frames; each job tags its `VHS_BatchManager`
+ (ComfyUI otherwise reuses a cached manager after a failed meta-batch run and silently loses frames: 32 of 48 seen
+ here); a silent clip loses the `VHS_LoadVideo` audio link (VHS fails on it); graphs that still decode the whole clip
+ (FPS Boost, HDR, EXR) refuse a clip that needs more than half the server's RAM, and the composer checks the same rule
+ before Generate (`/api/status` reports the ComfyUI's RAM). They hold 2 frame-sized float copies of the clip (decoding
+ stacks the frames; the tone map makes one more; encoders and the EXR writer take a frame at a time), FPS Boost 2 + m
+ (`VHS_SelectEveryNthImage` is a view): measured here, SDR to HDR on 10 s of 640×360 at 30 fps peaked 1.57 GB above idle,
+ 2.04 copies. FPS Boost needs the clip's frame rate (header) and refuses without it rather than guess m and n.
+ - **Cancel**: VHS re-queues each pass under a new prompt id with a negative queue number (it runs before anything else),
+ so cancelling a meta-batch job deletes every pending prompt carrying the job's filename prefix, interrupts the one
+ running, and looks again for a few seconds (a pass that was already saving can still queue the next). Checked here on a
+ 38-pass ProRes 4444 export: cancelled during pass 4, nothing ran after it. VHS keeps that pass's ffmpeg encode open in
+ the cached batch manager (a partial `.mov` without its moov atom stays in `output/`) until ComfyUI drops the cache; the
+ same happens to any meta-batch run that fails or is interrupted.
+ - **Real runs**: through Fuobe's API on the dev server (the comfyui provider end to end: upload, bindings, meta-batch
+ follow, EXR zip) and directly with a small runner, on the shared CPU server with own prompt ids only, every output
+ ffprobe-checked. The model graphs ran with random-weight stand-ins (`vftest_rife_random.safetensors`,
+ `vftest_esrgan_x4_random.safetensors`, removed afterwards), so they prove frame counts, sizes, rates, sound and memory,
+ not picture quality. Chunked vs whole-clip ESRGAN: 30 s at 256×144 to 1920×1080 held 0.87 GB above idle in 47 passes;
+ the whole-clip graph held 3.0 GB for 10 s of the same clip at only 1024×576.
+ - **Caveat**: VHS's ProRes `hq` profile leaves the pixel format to `prores_ks`, which picks `yuv444p10le` for RGB frames, so
+ "ProRes 422 HQ" is the HQ tag (`apch`) carrying 4:4:4 samples (FFmpeg reads it). A strict 4:2:2 file needs a VHS format
+ with `-pix_fmt yuv422p10le`, a change to the node pack (not made). Core ComfyUI has no H.265 encoder, so the open HDR
+ is H.264 High 10 (HLG or PQ); HDR10 in H.265 comes from Topaz on the cloud.
+ - **FILM**: oss-rife's Model control can pick `film_net_fp16.safetensors`; the spec lists it under `optionalModels`, so
+ the manifest carries it with `optional: true` (named with its download when it's missing, not counted as missing on
+ the Workflows page). Its URL is the repo's current name, `Comfy-Org/Frame-Interpolation` (the old lowercase one redirects).
+
+ ### Round-4 Image to 3D extras (r4/3d-plus, 2026-10-25)
+
+ One hand-built entry for Image to 3D's "From several images" on the open engine, from the official template
+ `3d_pixal3d_multi_views` (2026-09-09; core nodes only):
+
+ ```bash
+ node export-templates.mjs 3d_pixal3d_multi_views # build/raw/, then the hand-built graph was made from it
+ npm run build -- image-to-3d-trellis2-multiview image-to-3d-trellis2
+ node validate-workflows.mjs image-to-3d-trellis2-multiview image-to-3d-trellis2 --shared
+ ```
+
+ | id | capability | what | ran for real here |
+ |---|---|---|---|
-| `image-to-3d-trellis2-multiview` | image-to-3d | One upload per side (image = front, image2 = left, image3 = back, image4 = right) → BiRefNet cut-out and crop per side → `Pixal3DMultiViewConditioning` (a fixed orbit rig; its field of view measured on the front crop by MoGe 2) → TRELLIS.2 stages on `pixal3d_multiview_int8_convrot` (5.58 GB, MIT) → PBR GLB + the single-view graph's 36-view turntable | no (GPU); /prompt only (every side, and front + back / front + right pruned); the MoGe FOV subgraph ran on CPU |
++| `image-to-3d-trellis2-multiview` | image-to-3d | One upload per side (image = front, image2 = left, image3 = back, image4 = right) → BiRefNet cut-out and crop per side → `Pixal3DMultiViewConditioning` (a fixed orbit rig; its field of view measured on the front crop by MoGe 2) → TRELLIS.2 stages on `pixal3d_multiview_int8_convrot` (5.58 GB, MIT) → PBR GLB + a 36-view turntable (RotateMesh + RenderMesh, 12 fps), which the server replaces with its CPU turntable when it can | no (GPU); /prompt only (every side, and front + back / front + right pruned); the MoGe FOV subgraph ran on CPU |
+
+ - **What the provider does**: `SLOT_RULES` gives the workflow its sides; each photo goes to the side
+ `params.extra.views` names (in order when unnamed), and a side with no photo is cut out of the graph
+ (`dropBranch` in `src/lib/comfy.ts`: its loader, cut-out and crop go, and the rig loses that input). The front is needed.
+ - **Field of view**: the official multi-view template keeps the rig's 20° (right for rendered turnaround sheets). Photos are
+ wider as framed, so the graph measures it as the single-view Pixal3D template does: `MoGeInference` on the front crop →
+ `MoGeGeometryToFOV` (horizontal, degrees) → the rig's `fov` (+0.66 GB, `moge_2_vitl_normal_fp16`). `fovX` fixes MoGe's lens
+ instead (0 = estimate; 20 for a generated sheet). On the CPU server two runs of the subgraph (resolution level 9, one estimating,
+ one given 20°) took 137 s in all, model load included: 40.0° estimated on a test image, 20° passed through.
+ - **Sides**: the rig's left is the object's own left (camera at +90° azimuth): facing the front, walk to your right to photograph it.
-- **Licences**: the TRELLIS.2 graphs (single and multi-view) encode with DINOv3 ViT-L (`dino_v3_L_naf`), so their
- licence now names the DINOv3 License and its "Built with DINOv3" notice, like TripoSplat's.
++- **Single view**: `image-to-3d-pixal3d` (Pixal3D with MoGe 2's camera, the default "From an image" route) and
++ `image-to-3d-trellis2` (the fallback) remesh with `sign_mode` solid (fill 20) and decimate to 250,000 faces, and have no
++ turntable in the graph: the Fuobe server finishes every open image-to-3D GLB (a meshopt + WebP web GLB as `meta.web`, the
++ pivot at the bottom) and renders a 96-frame turntable on the CPU (`src/server/model3d-finish.ts`, `scripts/model3d/`).
++ The multi-view graph still has the template's udf remesh, a 700,000-face decimate and its GPU turntable; moving it to the
++ single-view settings needs a new /prompt validation.
++- **Licences**: the TRELLIS.2 and Pixal3D graphs (single and multi-view) encode with DINOv3 ViT-L (`dino_v3_L_naf`), so their
++ licence names the DINOv3 License and its "Built with DINOv3" notice, like TripoSplat's.
+ - **Not open**: rigging. UniRig (MIT) has no ComfyUI pack verified against v0.41, so Rig & animate is Meshy on fal only.
+ SAM 3D Objects has no open route either (the core SAM 3D nodes are body only).
+
+ ### Genjutsu Character swap (o/genjutsu-original, 2026-10-27)
+
+ Two hand-built entries for Genjutsu's Character swap on MiniMax H3, and one for Remove object's person removal on the same
+ model (docs/research/openjutsu-6.md):
+
+ ```bash
+ npm run build -- video-character-swap-h3 video-character-swap-h3-relay video-person-remove-h3-relay
+ node validate-workflows.mjs video-character-swap-h3 video-character-swap-h3-relay video-person-remove-h3-relay --shared
+ ```
+
+ | id | capability | what | validated here |
+ |---|---|---|---|
+ | `video-character-swap-h3` | video-character-swap | Openjutsu's `swap.api.json` (Akatz Labs' H3 Character Swap graph at `0670e4f` with a `Video Slice` in front): the part (start + length, 5–15 s, longer continues window by window), quality as the unpatched pack's string (`"480"` / `"768"`), H3 reference tags in the prompt, who to swap (SAM 3.1 words, largest / leftmost / rightmost / index, or clicks as JSON points on H3's canvas), the anchor first frame as `image2` (absent: its loader and fit are deleted and the shot's `use_anchor` is off), the swap LoRA release (V1.5, V1, or none: the Turbo LoRA alone) | no: `missing_node_type` (the `h3_character_swap` nodes are not on this server; its 22 core nodes are in `object_info.subset.json`) |
+ | `video-character-swap-h3-relay` | video-character-swap | H3 Relay 2.0's character-swap example (akatz-ai/h3-relay at `e2a7665b`) with a `Video Slice`: the same part, quality, words, seed and who; no anchor | no: `missing_node_type` (`H3RelayAppendWindow`) |
+ | `video-person-remove-h3-relay` | remove-object | H3 Relay 2.0's Person Removal example with Akatz Labs' Person Remover V1 LoRA (`akatz-ai/MiniMax-H3-Person-Remover-LoRA` at `fe136b3`): SAM 3.1 marks the person you name in green, H3 rebuilds the background in 22-frame windows from a clean first frame (`image`, fitted to the video's size by an added `ImageScale`). Remove object's "H3 Person Removal" eraser fits the part to 24 fps on the 32-pixel grid, makes the clean frame with Qwen-Image-Edit and puts the sound back | no: `missing_node_type` (`H3RelayAppendWindow`) |
+
+ - **Node packs**: `h3_character_swap` (GPL-3.0) is copied out of `akatz-labs/h3-character-swap-tool` at
+ `0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b` by `install-comfyui.sh` (`H3_PACK=0` skips it; it needs FFmpeg and FFprobe on
+ PATH). H3 Relay (GPL-3.0) registers HTTP routes and patches H3's layout in memory when it loads, so it is opt-in:
+ `H3_RELAY=1` clones it at `e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220`. Neither pack is installed on the CPU server
+ these graphs were built on, so both entries are recorded with `validated: false` and the missing node named.
+ - **Weights** (46.33 GB, pinned to Hugging Face revisions in `library.spec.mjs`): H3 Ref2VA int8, its video and audio VAEs and
+ the NVFP4 Qwen3-VL text encoder (Comfy-Org/MiniMax-H3), lightx2v's FL2V Turbo 8-step LoRA, SAM 3.1, and Akatz Labs'
+ Character Swap LoRA V1.5 (V1 optional). The provider downloads the two LoRAs before a run (`graphLoras`).
+ - **Licences, as information**: MiniMax H3 Community License (territory excludes the US, the EU, the UK and South Korea;
+ over US$20M yearly revenue needs MiniMax's written authorization; show "MiniMax H3"), Meta's SAM License, Apache-2.0
+ (Turbo LoRA), GPL-3.0 (both packs). The admin decides what runs (Settings → Models & licences).
+ - **Clicks**: the provider moves them into the frame the pack prepares (its `canvas_dimensions`: a 0.5 / 1.0 MP budget
+ on the 32-pixel grid, the clip scaled to cover and the middle cropped) and sets SelectSubject to `index` 0, since
+ `SAM3_Detect` returns the clicked mask first and the "person" detections after it. Person numbers (`index`) are SAM's
+ detections in order of confidence, not left to right. A window and history the pack's `validate_settings` would
+ refuse (history ≥ window) is brought below the window.
+ - **GPU**: tested by their authors on a 96 GB RTX PRO 6000 and on a 24 GB RTX 4090 with 128 GB RAM and offloading.
+ - **Comfy Developer Platform** (what Openjutsu deploys to): a deployment is not a plain ComfyUI server — it is driven by
+ the v2 API (`@comfyorg/sdk`: upload, job, poll), not `/prompt` and `/history` — so Fuobe does not add a provider for it.
+ Point `COMFYUI_URL` at a ComfyUI that has the packs installed instead.
+
+ ### Character Swap Studio (o/h3-studio, 2026-10-27)
+
+ Two hand-built entries for the Character Swap Studio (`/character-swap`) on your GPU, on H3 Relay 2.0's nodes; the
+ segment graph is built from `video-character-swap-h3-relay`. They follow Akatz Labs' app (docs/research/openjutsu-6.md
+ §4.2):
+
+ ```bash
+ npm run build -- video-character-swap-h3-segment video-mask-h3-relay
+ node validate-workflows.mjs video-character-swap-h3-segment video-mask-h3-relay --shared
+ ```
+
+ | id | capability | what | validated here |
+ |---|---|---|---|
+ | `video-character-swap-h3-segment` | video-character-swap | One segment: a single H3 Relay 2.0 pass (its "segment" schedule, at most 362 frames) over the clip's 24 fps copy. The approved mask (a whole-shot mask from `video-mask-h3-relay`) replaces SAM's own chain, the anchor goes in as Picture 2 (Picture 3 after a history boundary), and the previous take's lossless master (16-bit FFV1, output role `master`) gives the history frames (`historyVideo`, `historyStart`, `historyLength`). Outputs: the segment (H.264) and its master for the next segment. The provider rewrites the graph per job (`src/lib/swap-studio-graphs.ts`). Limits 30 s / 703 frames; 24 GB | no: `missing_node_type` (`H3RelayAppendWindow`) |
+ | `video-mask-h3-relay` | person-mask | Who to swap in one shot, as a black-and-white mask video at H3's canvas size and 24 fps: SAM 3.1 detects on frame `keyFrame` from words or clicks, H3 Relay picks largest / leftmost / rightmost / #n, and SAM 3.1 tracks it for `spanFrames` (the rest of the shot for Track shot, 1 for Update frame). The new part is spliced into the version it corrects (`prevMask`, `tailStart`, `tailFrames`). Limits 150 s / 3,592 frames; 6 GB | no: `missing_node_type` (`H3RelayPrepareSource`) |
+
+ - **Node packs**: no new one. Both use H3 Relay (GPL-3.0, opt-in with `H3_RELAY=1`, pinned at
+ `e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220`); the segment graph also uses ComfyUI-VideoHelperSuite and needs FFmpeg.
+ `build-library.mjs` gains eight binding keys for them: `historyVideo`, `historyStart`, `historyLength`, `keyFrame`,
+ `spanFrames`, `tailStart`, `tailFrames` and `prevMask`.
+ - **Weights**: no new files. The segment graph uses the same pinned MiniMax H3 files, Turbo LoRA, SAM 3.1 and swap LoRA
+ as `video-character-swap-h3-relay`, and the provider downloads the LoRAs before a segment runs; the mask graph needs
+ only SAM 3.1 (1.75 GB).
+ - **Uploads**: a continuation uploads the previous take's master, about 3 MB a frame at 1 MP. ComfyUI takes uploads up to
+ 100 MB unless started with a higher `--max-upload-size`, so more than about 30 frames of history needs a higher one.
+ An upload ComfyUI refuses as too large now fails with a message that says this, for every feature.
+ - **Memory**: the provider refuses a mask shot too long for the server's RAM before it runs. That limit is an estimate,
+ not a measurement, and may be too strict (on a 64 GB server, 1 MP corrections stop at shots of about 18 s).
+ - **Not run**: neither graph has loaded in a ComfyUI with H3 Relay, and nothing has run on a GPU.
+ `tests/comfy-swap-studio.test.ts` checks the provider's rewrites on the library files.
+
## Adding a workflow
1. Find the template name in `$COMFYUI_DIR/.venv/lib/python3.*/site-packages/comfyui_workflow_templates_json/templates/index.json`
diff --cc scripts/comfy/build-library.mjs
index deddef09,94a5f3eb..57a4ea39
--- a/scripts/comfy/build-library.mjs
+++ b/scripts/comfy/build-library.mjs
@@@ -14,8 -14,8 +14,8 @@@ import fs from 'node:fs'
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
--import { fileURLToPath } from 'node:url';
- import { SPEC, KNOWN_MODELS, CUSTOM_NODE_REPOS } from './library.spec.mjs';
++import { fileURLToPath, pathToFileURL } from 'node:url';
+ import { SPEC, KNOWN_MODELS, CUSTOM_NODE_REPOS, PACK_CLASSES } from './library.spec.mjs';
import * as G from './lib/graph.mjs';
import { resolveSource } from './export-templates.mjs';
@@@ -385,7 -418,7 +418,7 @@@ async function main()
console.log(`\nWrote ${entries.length} workflows + manifest.json to ${path.relative(REPO, OUT_DIR)}/`);
}
--if (import.meta.url === `file://${process.argv[1]}`) {
++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((e) => {
console.error(e);
process.exit(1);
diff --cc scripts/comfy/export-templates.mjs
index 453cb049,453cb049..f1888ae4
--- a/scripts/comfy/export-templates.mjs
+++ b/scripts/comfy/export-templates.mjs
@@@ -22,7 -22,7 +22,7 @@@
import fs from 'node:fs';
import path from 'node:path';
--import { fileURLToPath } from 'node:url';
++import { fileURLToPath, pathToFileURL } from 'node:url';
import { chromium } from 'playwright-core';
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@@ -216,7 -216,7 +216,7 @@@ async function main()
if (results.some((r) => !r.ok)) process.exitCode = 1;
}
--if (import.meta.url === `file://${process.argv[1]}`) {
++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((e) => {
console.error(e);
process.exit(1);
diff --cc scripts/comfy/library.spec.mjs
index 0f22d221,0e6a5d91..bcdcc8f9
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@@ -2296,32 -2428,49 +2428,62 @@@ export const SPEC =
},
// ---- Product 3D, try-on --------------------------------------------------------
+ {
+ id: 'image-to-3d-pixal3d',
+ title: 'Image to textured 3D (Pixal3D, PBR GLB, ~250k triangles)',
+ capability: 'image-to-3d',
+ handBuilt: 'hand-built/image-to-3d-pixal3d.json',
+ bindings: {
+ image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')],
+ },
+ outputs: [{ node: '322', kind: 'model3d' }],
+ vramGb: 16,
- license: 'Pixal3D weights, DINOv3-NAF and TRELLIS VAEs as repackaged by Comfy-Org (licence not reviewed yet); MoGe-2 and BiRefNet as in their own entries',
++ license:
++ 'MIT (Pixal3D weights by TencentARC, as the multi-view weights; TRELLIS.2 VAEs as repackaged by Comfy-Org, BiRefNet, microsoft/MoGe 2); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License ' +
++ '(royalty-free, commercial use allowed; the app must show a "Built with DINOv3" notice)',
+ notes: 'Template 3d_pixal3d_trellis2_image_to_model, Pixal3D branch (the default image-to-3D route): MoGe-2 (geometry_estimation/moge_2_vitl_normal_fp16, resolution_level 9) estimates the camera from the cut-out, MoGeGeometryToFOV (horizontal, degrees) -> Pixal3DConditioning (camera_angle_x) with the DINOv3 encoder, UNet pixal3d_int8_convrot; ImageCropToMask pad_factor 1.1 (as the node asks for Pixal3D). BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui "3d"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23 (RTX 5090, the same graph run end to end): 114-185 s per object, 25-35 MB raw GLB at ~250k triangles (was 8M triangles / 317 MB before the decimate step), web GLB 1.6-3.6 MB; more faithful to the photo than TRELLIS.2 (209-238 s). The origin is the camera-aligned volume centre, hence the pivot fix. Surfaces can show faint planar facets from the shape decode (no graph setting removes them).',
+ },
{
id: 'image-to-3d-trellis2',
- title: 'Image to textured 3D (TRELLIS.2, PBR GLB) + a 36-view turntable video',
+ title: 'Image to textured 3D (TRELLIS.2, PBR GLB, ~250k triangles; fallback to Pixal3D)',
capability: 'image-to-3d',
handBuilt: 'hand-built/image-to-3d-trellis2.json',
bindings: {
- image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')], turntableFps: [b('701', 'fps')],
+ image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')],
},
- outputs: [{ node: '322', kind: 'model3d' }, { node: '702', kind: 'video', role: 'turntable' }],
+ outputs: [{ node: '322', kind: 'model3d' }],
vramGb: 16,
- license: 'MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet)',
+ license:
+ 'MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License ' +
+ '(royalty-free, commercial use allowed; the app must show a "Built with DINOv3" notice)',
- notes:
- 'Template 3d_pixal3d_trellis2_image_to_model: BiRefNet cut-out -> crop to mask -> TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> remesh -> UV unwrap -> ' +
- 'baked base colour / metallic / roughness / AO / normal at textureSize -> GLB (Save3DAdvanced, history ui "3d"). The graph adds a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps.',
+ notes: 'Template 3d_pixal3d_trellis2_image_to_model, TRELLIS.2 branch (the fallback image-to-3D route; Pixal3D is the default): Trellis2Conditioning with the DINOv3 encoder, UNet trellis_2_int8_convrot; ImageCropToMask pad_factor 1.0. BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui "3d"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23: 209-238 s, 28-43 MB raw GLB at ~250k triangles. The 36-view RotateMesh + RenderMesh turntable (unlit, aliased, 12 fps) was removed.',
},
+ {
+ id: 'image-to-3d-trellis2-multiview',
+ title: 'Photos of 2-4 sides to textured 3D (Pixal3D multi-view on TRELLIS.2, PBR GLB) + a 36-view turntable video',
+ capability: 'image-to-3d',
+ handBuilt: 'hand-built/image-to-3d-trellis2-multiview.json',
+ bindings: {
+ image: [b('360', 'image')], image2: [b('361', 'image')], image3: [b('362', 'image')], image4: [b('363', 'image')],
+ seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')], turntableFps: [b('701', 'fps')], fovX: [b('381', 'fov_x_degrees')],
+ },
+ outputs: [{ node: '372', kind: 'model3d' }, { node: '702', kind: 'video', role: 'turntable' }],
+ vramGb: 16,
+ license:
+ 'MIT (Pixal3D multi-view weights by TencentARC, TRELLIS.2 VAEs as repackaged by Comfy-Org, BiRefNet, microsoft/MoGe 2); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License ' +
+ '(royalty-free, commercial use allowed; the app must show a "Built with DINOv3" notice)',
+ notes:
+ 'Template 3d_pixal3d_multi_views (2026-09-09) with the turnaround-sheet loader and its crops replaced by one upload per side: image = front, image2 = left, image3 = back, image4 = right ' +
+ '(Pixal3DMultiViewConditioning, a fixed orbit rig 90 degrees apart, Z up: the left view is the object\'s own left, the camera at +90 degrees azimuth from the front, i.e. the photographer walks to their right; ' +
+ 'every side but the front is optional and the provider drops the branch of a side with no photo). ' +
+ 'Each side: BiRefNet cut-out -> crop to mask (1024, pad 1.1) -> the view. Then TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) on Pixal3D multi-view ' +
- '-> decimate to 700k faces -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB. The same 36-view turntable as image-to-3d-trellis2. ' +
++ '-> decimate to 700k faces -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB, plus a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps; the Fuobe server then finishes the GLB (web GLB as meta.web) and, when Chromium and ffmpeg are there, replaces that turntable with its CPU render (src/server/model3d-finish.ts). ' +
+ 'The views\' horizontal field of view as framed (Pixal3DMultiViewConditioning.fov) is measured on the front crop: MoGe 2 (LoadMoGeModel -> MoGeInference -> MoGeGeometryToFOV, horizontal, degrees), ' +
+ 'as the node\'s tooltip says for photos and as the official single-view template 3d_pixal3d_trellis2_image_to_model feeds Pixal3DConditioning; the multi-view template keeps the rig value 20, ' +
+ 'which suits rendered turnaround sheets but not phone photos, whose crops are usually wider. fovX (degrees, 0 = estimate, the default) fixes MoGe\'s lens instead, ' +
+ 'so MoGeGeometryToFOV passes it on (20 for a generated turnaround sheet). ' +
+ 'Weights: pixal3d_multiview_int8_convrot 5.58 GB + moge_2_vitl_normal_fp16 0.66 GB + the TRELLIS.2 VAEs, DINOv3-NAF and BiRefNet the single-view graph already uses. VRAM unverified (as the single-view graph: 16 GB). Validated by /prompt only.',
+ },
{
id: 'image-to-3d-hunyuan3d-21',
title: 'Image to 3D shape: Hunyuan3D 2.1 (native, untextured GLB; territory-restricted licence)',
diff --cc scripts/comfy/validation-state.json
index fb1f4565,623e6595..223b7754
--- a/scripts/comfy/validation-state.json
+++ b/scripts/comfy/validation-state.json
@@@ -161,18 -161,18 +161,24 @@@
"error": null,
"at": "2026-10-17T21:02:04.747Z"
},
+ "image-to-3d-pixal3d": {
+ "sha256": "581d29c7322dbb089db04cef398428c1ec3ba13208f020a39eaadb8d23ce5a6f",
+ "validated": true,
+ "error": null,
+ "at": "2026-10-23T16:54:45.150Z"
+ },
"image-to-3d-trellis2": {
- "sha256": "7bfa7ebe14aa128a4b9b513e653998c5293ddc9221ca1d668191d27dc52725f6",
+ "sha256": "71818818d7bec8ee685bcb5e3e6a81aa9abb9f60104c46900d2ce429a693dbb1",
"validated": true,
"error": null,
- "at": "2026-10-26T00:46:02.904Z"
+ "at": "2026-10-23T16:54:45.150Z"
},
+ "image-to-3d-trellis2-multiview": {
+ "sha256": "06ac47b57c4007ed0bb6f96ecde799de1e24285baf590f14357ffde87081b118",
+ "validated": true,
+ "error": null,
+ "at": "2026-10-26T00:46:07.467Z"
+ },
"image-to-splat-triposplat": {
"sha256": "cb65f4660b4d5fef3c0544146ed51b7d3acf059f3190a102dccf8166908f5413",
"validated": true,
diff --cc scripts/eval/README.md
index 00000000,23c72802..54fd7b8e
mode 000000,100644..100644
--- a/scripts/eval/README.md
+++ b/scripts/eval/README.md
@@@ -1,0 -1,479 +1,505 @@@
+ # Fuobe evaluation harness
+
+ `scripts/eval` measures the Fuobe Originals. You give it a suite of cases. It runs each case through a
+ running Fuobe's REST API, downloads what comes back, scores it and writes a report. The report holds
+ timing, cost, memory, metrics and a blind A/B review page. Runs are kept, so you can compare them.
+
+ The rule it serves: **an Original's recipe becomes a default only after the harness has measured
+ it** (see [The promote rule](#the-promote-rule)). The harness never changes a default by itself. A
+ person does that in a reviewed commit.
+
+ It works against any Fuobe, on three engines:
+
+ | `--engine` | What runs | Cost |
+ | --- | --- | --- |
+ | `demo` | The demo provider's media. It checks the harness itself, with no keys and no GPU. | Free |
+ | `open` | Your ComfyUI (the open engine), with the recipe's LoRAs. | Free (your GPU) |
+ | `cloud` | Hosted open models on fal / Replicate that take LoRA URLs. Partner models run where a suite asks. | Priced before anything starts, under a spend cap (default $5) |
+
+ ## Quick start
+
+ ```bash
+ pnpm dev # or any running Fuobe
+ pnpm eval:run --suite selftest --engine demo # about 30 s, free: submit, wait, download, score, report
+ pnpm eval:report latest # score again and rewrite the report
+ open scripts/eval/results/<runId>/report.html # the contact sheet
+ ```
+
+ A real look on your GPU, A/B against the same words without LoRAs and at half strength:
+
+ ```bash
+ pnpm eval:run --suite soul --engine open --looks v1-general,v2-y2k-studio \
+ --variants recipe,prompt-only,half-strength --dry-run # lists the jobs, the LoRAs and the spend; starts nothing
+ pnpm eval:run --suite soul --engine open --looks v1-general,v2-y2k-studio --variants recipe,prompt-only,half-strength
+ pnpm eval:review latest # rate the pairs blind, with the keyboard
+ pnpm eval:promote latest # does the recipe win?
+ ```
+
+ `fuobe eval <command>` runs the same commands from the `fuobe` CLI (from a Fuobe checkout). It finds
+ the server and token the way every `fuobe` command does, so the token `fuobe login` saved goes only to
+ the server it was saved for, even when `--url` names another one.
+
+ ### Which Fuobe it talks to
+
+ The harness finds its server the way `bin/fuobe.mjs` does: `--url` / `--token`, then `FUOBE_URL` /
+ `FUOBE_TOKEN`, then what `fuobe login` saved. A Fuobe with a password needs an API token from
+ **Settings → Security → API tokens**. The token goes only to that server. Everything goes through
+ the public API (`/api/generations`, `/api/uploads`, `/api/elements`, the studio routes), so the
+ harness measures what a user gets.
+
+ - `--engine demo` needs **Settings → Demo mode** on Auto or On. A job that would run for real is
+ skipped.
+ - `--engine open` / `cloud` refuse a server whose engine mode excludes them. A job that would come
+ back as demo media is skipped and says why: Demo mode is On, no ComfyUI is connected, or there is
+ no cloud key.
+ - **The model it names.** A job the server would run on another model than the one the case names
+ (a studio's default maker, or a retired model the server runs on the Original that replaced it) is
+ skipped, since it wouldn't measure that model.
+ - **Your Library stays yours.** Every generation the harness starts has the feature `eval`, a helper
+ like a studio's steps: the Library and Home feeds leave it out unless **Show steps** is on. A studio
+ route's steps (Genjutsu, Mixed Media) carry that studio's feature instead. `pnpm eval:trash <runId>`
+ moves a run's generations, studio steps included, to that Fuobe's Trash.
+ - On the open engine the harness also reads ComfyUI directly (`--comfy-url`, default `COMFYUI_URL`
+ or `http://127.0.0.1:8188`). It uses three read-only endpoints: `/system_stats` for memory,
+ `/history` for ComfyUI's own timings, and `/object_info/LoraLoader` to name the LoRAs ComfyUI
+ doesn't have yet. It never queues or cancels anything there.
+
+ ## Commands
+
+ | Command | What it does |
+ | --- | --- |
+ | `pnpm eval:run --suite <s> --engine demo\|open\|cloud` | Runs a suite, then scores it and writes the report (`--no-metrics`, `--no-report` to stop earlier) |
+ | `pnpm eval:report <runId\|latest>` | Scores again (only what changed) and rewrites `summary.json`, `report.html` and the history lines |
+ | `pnpm eval:review <runId>` | Serves the blind A/B page and saves ratings next to the run |
+ | `pnpm eval:compare <runA> <runB>` | Wins, losses and mean gain per metric. Exits 1 when a guarded metric regresses |
+ | `pnpm eval:promote <runId>` | Applies the promote rule. `--record` writes the verdicts into the research JSON; `--apply-strengths` also lowers over-cooked strengths there |
+ | `pnpm eval:covers <runId>` | Turns each promoted case's best render into its preset's cover (`public/previews/`, `src/lib/preset-previews.generated.ts`) |
++| `pnpm eval:covers --from-masters <dir> --run <name>` | Turns rendered masters (one folder per preset id) into covers, merged into the same file |
+ | `pnpm eval:history` | Lists runs, newest first, and the per-case scores of one case (`--case soul/v1-general`) |
+ | `pnpm eval:validate` | Checks every case file, and that the generated suites match the research |
+ | `pnpm eval:setup` | Creates the metrics venv with uv (`--identity`, `--download`, `--dinov2`, `--torch-backend`) |
+ | `pnpm eval:trash <runId>` | Moves the run's generations to the Trash of the Fuobe it ran on (`--dry-run` counts them). The run's folder here keeps its outputs and scores |
+
+ Every command takes `--json`. Runs are named by id, by path, or as `latest`, `latest~1` (the run
+ before) and so on. `pnpm eval:<command> --help` lists each command's options.
+
+ Useful `run` options:
+
+ - `--looks v1-general,"Flash editorial"`: looks by slug, name or id.
+ - `--cases dop/motion-*`, `--tags v1,civitai`, `--limit 5`, `--prompts 1`, `--seeds 1,2`: run fewer
+ jobs.
+ - `--variants recipe,prompt-only` or `all`: the recipe variants to run. Each suite has a default.
+ - `--model <id>`: one model id for every job, instead of the suite's targets.
+ - `--max-usd 2`: the cloud spend cap. The run is priced first, training included. It refuses to start
+ over the cap, and it starts no job that would go over it: each job reserves its price before it
+ starts, and its real cost replaces the reservation when it ends. A resumed run counts what its earlier
+ attempts spent (every attempt that reached the server, and any training).
+ - A cloud job or training the server can't price is skipped, because the cap can't cover it.
+ `--allow-unpriced` runs it anyway: it holds whatever is left of the cap while it runs, so nothing
+ starts beside it, and its cost counts once the server reports it. Such a job can take the run over
+ the cap by its own cost.
+ - `--concurrency`: open 1, others 4.
+ - `--resume <runId>`: runs only the failed and missing jobs again. Ctrl+C stops new jobs from
+ starting; the jobs already running finish on the server.
+ - `--allow-fixtures`: uses the synthetic fixtures where your own inputs are missing.
+ - `--label "after the LoRA strength change"`: a note kept with the run.
+
+ ## Suites
+
+ One JSON file per Original in `cases/`. Later Original packages add their own files here.
+
+ | Suite | Measures | Cases | Variants (default first) | Main metrics |
+ | --- | --- | --- | --- | --- |
+ | `selftest` | the harness itself | 5 small tools (trim, palette lock, join, frame, image) | — | temporal, clip |
+ | `soul` | Fuobe Soul, the 139 looks | 139 looks × 3 subjects, pinned seeds | `recipe`, `prompt-only`, `half-strength`, `plain`, `original` | clip, aesthetic, style |
+ | `soul-cinema` | Soul Cinema's one film look | 6 scenes, pinned seeds | `recipe`, `prompt-only`, `plain`, `original` | clip, aesthetic, style |
+ | `soul-hex` | Soul HEX palettes | 3 Fuobe palettes × 2 subjects | `words`, `lock` (open), `base`, `palette-model` (open), `plain` | palette, clip, aesthetic |
+ | `soul-id` | character and look training | your photos → train per family (Fuobe Soul, Soul Cinema, Soul HD, FLUX.1 [dev]) → scenes; a moodboard → a look | `trained`, `half-strength`, `references` | identity (style for the look), clip, aesthetic |
+ | `dop` | Fuobe DoP motions and effects | the 69 the research gives a LoRA, and the 20 camera moves it gives a Fun Camera pose or an LTX camera LoRA | `catalog`, `prompt-only`, `research` (the candidate), `partner` (cloud) | temporal, clip |
+ | `dop-mix` | Fuobe DoP's Mix | 5 move + effect pairs | `mix` (the candidate), `first` (the move alone) | temporal, clip |
+ | `genjutsu` | Genjutsu move / swap / restyle / Character swap | 7: Motion transfer and Object swap (each also on the Lite tier), Restyle, and Character swap with and without the first frame (through `/api/genjutsu`) | `original`, `partner` (cloud: each mode's own partner on fal) | temporal, clip |
+ | `mixed-media` | Mixed Media | 5 looks on one clip (through `/api/mixed-media`) | `studio` | temporal, style |
+ | `shorts` | Shorts restyle | 1 | `restyle` | temporal, style, clip |
+ | `speak` | talking portraits | 1 portrait + voice | `infinitetalk`, `s2v` | lipsync, temporal, identity |
+ | `cinema` | Fuobe Cinema (O6) | 3 Director scenes (the prompt Cinema compiles), 4 camera moves as LTX-2.3's `camera_lora` (cloud), 2 films of 3 shots | `original`, `words` (no camera LoRA), `expansion` (fal's prompt expansion on), `wan` (Wan 2.2 A14B hosted), `partner` (Seedance 2.5); all but `original` cloud only | clip, temporal, continuity |
+
+ `soul.json`, `soul-cinema.json`, `soul-hex.json`, `dop.json` and `dop-mix.json` are **generated** from the research. They come from
+ `docs/research/higgsfield-image-studios.json` (the look ids) and
+ `docs/research/fuobe-originals-recipes-5.json` (recipes, LoRAs, Soul Cinema's recipe, the motion map).
+ `soul-hex`'s palettes are Fuobe's own. Run
+ `node scripts/eval/gen-cases.mjs` after the research changes, and don't edit the generated files by
+ hand. `pnpm eval:validate` fails when they are out of date. The subject prompts are Fuobe's own. No
+ Higgsfield prompt or preview is used anywhere.
+
+ Soul variants, all on the same subjects and seeds:
+
+ - **recipe**: the look's template, its LoRA triggers, and its LoRAs at the listed strengths.
+ - **prompt-only**: the same words without LoRAs. Does each LoRA earn its slot?
+ - **half-strength**: every LoRA at half strength. This is the over-cooking check.
+ - **plain**: the base model with the subject alone.
+ - **original**: the shipped `fuobe-soul` Original (O2), which applies the look on the server. The look
+ goes as its Fuobe id in `presetId` (`v1-general`, the slug `--looks` takes); a Higgsfield look id never
+ leaves the harness. A lettering look (Graffiti) runs on `fuobe-soul-hd`. Every request names the engine
+ the run is on (`engine`), so an Original that runs on both takes that one. Its grade and overlay are
+ applied in the browser after generation, so the scores are of the raw picture.
+
+ Soul Cinema's variants are the same idea for its one look: **recipe** (the research's LoRAs with their
+ triggers, then the `cine` tail), **prompt-only** (the tail alone), **plain** and **original**
+ (`fuobe-soul-cinema`). Soul HEX's: **words** (the palette sentence the Color signature adds, on Fuobe
+ Soul: the cloud's HEX), **lock** (the same, then `POST /api/palettes/lock`: the open engine's HEX),
+ **base** (the words on today's base), **palette-model** (Z-Image Turbo · Palette) and **plain** (no
+ palette words, the control). A variant can carry fixed `words` after the prompt and its own `submit`
+ route; `{{request}}` in a route body is the job's own request.
+
+ DoP variants, on your start frame with two seeds:
+
+ - **catalog**: the preset as it ships, with today's open LoRA if it has one.
+ - **prompt-only**: preset strength 0, so the preset's words without its LoRAs. The server leaves the
+ LoRA's trigger word out too, since it means nothing without the LoRA.
+ - **research**: the research's LoRA map at the listed strengths, its trigger words in front of the
+ words (`trigger, prompt`, as a Soul look's).
+ - **partner**: the preset's words on Kling 2.5 Turbo (cloud only).
+
+ A variant that would send the server the same request as an earlier variant of the same case, prompt
+ and seed (model, route, final prompt, LoRAs, settings and inputs) is skipped and names the one it
+ repeats. Most DoP presets have no open LoRA in today's catalog, so their prompt-only run would repeat
+ the catalog run.
+
+ ### Licence rules in the runs
+
+ The recipe's licence flags go with every job, following the research's "Licence rules for
+ Originals":
+
+ - Licences are information (Settings → Models & licences): a LoRA licensed for the GPU only goes to the
+ cloud engine like any other, unless the install keeps such LoRAs on the GPU there.
+ - A civitai link is left out on the cloud until a mirrored copy exists, because civitai answers 401
+ without your token.
+ - A non-commercial LoRA is noted on the verdict; with `--licence-hold`, a recipe that uses one isn't
+ promoted.
+ - A LoRA link (your own variant's included) must be on Hugging Face, civitai, fal or Replicate: the API
+ refuses other hosts, since the server may download an unknown file from it before a ComfyUI run.
+
+ A job records which LoRAs it asked for, which ones the route actually loaded, and which ones were
+ left out and why.
+
+ ## Your own inputs: `scripts/eval/local/`
+
+ Inputs the repo can't ship live in `scripts/eval/local/`, which is git-ignored and never committed.
+ That covers photos of people, reference clips, licensed style references and voices. Cases name them
+ as `local/…`. A job whose local input is missing is skipped and names the file. Demo runs use the
+ small synthetic files in `fixtures/` instead.
+
+ ```
+ scripts/eval/local/
+ references/soul/<look-slug>/*.jpg # style references per look (your own or licensed images; never Higgsfield previews)
+ references/mixed-media/<look>/* # what each Mixed Media look should look like
+ characters/default/*.jpg # 20+ photos (80 at most) of ONE consenting person (soul-id)
+ styles/default/*.jpg # 20+ images in one style, a moodboard (soul-id/look)
+ dop/start.png, dop/end.png # a start frame (a person on a bridge fits the prompts), an end frame for transitions
+ genjutsu/dance.mp4, character.png, style.png
+ genjutsu/street.mp4, object.png # street.mp4 at least 720 px on each side (Kling O3's edit, the cloud partner)
+ mixed-media/clip.mp4
+ shorts/clip.mp4, shorts/frame0.png
+ speak/portrait.png, speak/voice.wav
+ ```
+
+ **Training needs consent.** `soul-id.json` ships with `"consent": false`, so a character's training
+ refuses to start. Copy the file to `local/soul-id.json`. In your copy, set `"consent": true` only
+ when the person in the photos agreed: the runner then sends Fuobe the consent line with the training,
+ as the Train dialog does. A look (`"kind": "style"`) needs no consent. Then run it with
+ `--suite scripts/eval/local/soul-id.json`. To reuse a character you already trained, put its element
+ id in `"element"` instead of training again. Each case trains its own element (a Soul ID runs on the
+ models of the base it was trained on), so a full cloud run trains five times: about $1.70 + $1.70 +
+ $1.50 + $6.00 for the four character cases (Soul Cinema trains Fuobe Soul's family again unless its
+ `"element"` names the character case's element) and $3.39 for the look, priced before anything
+ starts. A training the server would run as a demo (no fal.ai key or AI-Toolkit connected, or Demo
+ mode On) is skipped with its case, so a "trained" result is always a trained LoRA. The look case runs
+ the trained style as the board's own look (`"presetId": "own-style"`), as a trained moodboard does in
+ the app.
+
+ ## The case format
+
+ A suite file follows `cases/case.schema.json`, which editors use for completion. The schema is
+ written from `lib/schema.mjs`.
+
+ ```jsonc
+ {
+ "$schema": "./case.schema.json",
+ "suite": "my-original",
+ "title": "Fuobe Something",
+ "description": "What it measures and what it needs.",
+ "original": "fuobe-something", // the Original(s) measured
+ "kind": "image", // image | video | audio
+ "recipe": "none", // soul-look | motion | none: where a case's recipe comes from
+ "targets": { // model ids per engine, in order of preference:
+ "open": { "models": ["fuobe-something", "oss-z-image-turbo"] }, // the first one this Fuobe has is used
+ "cloud": { "models": ["z-image-turbo-cloud"], "extra": { "num_inference_steps": 8 } },
+ "demo": { "models": ["oss-z-image-turbo"] }
+ },
+ "defaults": { "seeds": [1001], "metrics": ["clip", "aesthetic"], "timeoutSeconds": 1800 },
+ "variants": {
+ "recipe": { "description": "The recipe as researched", "loras": "recipe" },
+ "half": { "description": "Half strength", "loras": "recipe", "loraScale": 0.5 },
+ "mine": { "loras": [{ "file": "my-lora.safetensors", "url": "https://huggingface.co/…", "strength": 0.8, "trigger": "myword" }] },
+ "partner": { "models": { "cloud": ["kling-2-5-turbo"] }, "engines": ["cloud"] } // engines: where the variant runs
+ },
+ "cases": [
+ {
+ "id": "my-original/portrait",
+ "title": "A portrait",
+ "prompts": [{ "id": "p1", "text": "a woman reading by a window", "seed": 1001 }],
+ "references": "local/references/my-original/portrait", // a folder or a list of files
+ "inputs": { "images": ["local/my-original/face.png"] }, // images, video, videos, audio, endImage, mask…
+ "demoInputs": { "images": ["fixtures/start-frame.png"] },
+ "params": { "aspectRatio": "3:4" }
+ }
+ ]
+ }
+ ```
+
+ Other case fields:
+
+ - `look` / `motion`: a Soul look id, or a motion or effect name. The recipe comes from the
+ research.
+ - `presetId`: a catalog preset.
+ - `models` / `op`: per-case models, and the operation.
+ - `variantModels`: a variant's models for this case (`{"partner": {"cloud": ["kling-o3"]}}`), over
+ the variant's own. Each Genjutsu mode names its own partner this way.
+ - `shots`: a film's shots. Continuity is measured across them.
+ - `train`: photos, a target per engine, `kind` (`character` or `style`), `consent`, and `minPhotos`.
+ - `submit`: a studio route and its body, with `{{inputs.video}}`, `{{source:inputs.video}}`,
+ `{{prompt}}`, `{{seed}}`, `{{engine}}` and `{{requestId}}` filled in.
+ - `engines`: the engines the case runs on.
+ - `tags`, `metrics` and `note`.
+
+ Paths can start with:
+
+ - `local/…`: your own inputs.
+ - `fixtures/…`: the synthetic fixtures.
+ - `samples/…`: `public/samples`.
+ - Anything else is a path relative to the case file, an absolute path, or a link.
+
+ Run `pnpm eval:validate` after editing.
+
+ ## What a run records
+
+ Everything goes to `scripts/eval/results/` (git-ignored; move it with `--out` or `FUOBE_EVAL_RESULTS`):
+
+ ```
+ results/
+ history.jsonl # one line per run × case × variant: mean scores (pnpm eval:history)
+ <runId>/
+ run.json # suite, engine, filters, variants and the candidate, the server and ComfyUI it ran on,
+ # git commit, the research files' hashes, spend cap, the training estimate and the spend
+ elements.json # training cases: the element made or trained, its training and what it cost
+ jobs.jsonl # one row per job, appended as each one ends (see below)
+ outputs/<jobId>/… # the downloaded results
+ metrics.json # scores per job (and per film), which model made them, at which revision, under which licence
+ summary.json # means per variant, variant-against-variant wins, blind ratings, failures
+ report.html # the contact sheet: every case × variant with its scores (light and dark, phone-friendly)
+ review/index.html # the blind A/B page; review/key.json (which side was which) is never served
+ review/ratings.json # your ratings
+ promote.json # the promote verdicts
+ ```
+
+ Each row in `jobs.jsonl` records:
+
+ - the case, prompt, seed and variant;
+ - the model id asked for and the one that ran;
+ - the route (`provider`, `endpoint`) and the final prompt;
+ - the recipe: look or motion, template, the LoRAs with their strengths, which LoRAs the route loaded
+ and which it dropped and why, the sampler settings, and the licence flags;
+ - the generation ids and the downloaded files;
+ - the time: submitted, finished, wall clock;
+ - the cost: the estimate before running and the cost after;
+ - on the open engine: peak memory from `/system_stats` (CPU ComfyUIs are marked as RAM, not VRAM)
+ and ComfyUI's own execution time from `/history`;
+ - notes and errors.
+
+ ## Metrics
+
+ The metrics are written in Python (`metrics/fuobe_metrics`). Each metric is a small module with
+ tests on tiny fixtures. They run on the CPU by default (`--device cuda|mps|auto` to change that).
+ `pnpm eval:setup` creates the venv with [uv](https://docs.astral.sh/uv/) from the pinned
+ `metrics/requirements.txt`, which is compiled from `requirements.in` with CPU torch.
+ `--download` fetches the weights now; otherwise they download on first use. Every weight is pinned
+ to a Hugging Face revision, and its licence is recorded with every result. Without Python, a run
+ still has its timing and cost, and the report says why the scores are missing.
+
+ | Metric | Key(s) | Better | How | Model and licence |
+ | --- | --- | --- | --- | --- |
+ | Prompt adherence | `clip` | higher | CLIPScore (100·cos) between the output and the case's own words. Clips are sampled at 4 frames | open_clip ViT-B/32 laion2B, **MIT** (`--clip-model clip-l14`: OpenAI ViT-L/14, MIT) |
+ | Aesthetic | `aesthetic` | higher | LAION improved aesthetic predictor v2 on CLIP ViT-L/14 embeddings, about 1–10 | head **Apache-2.0** (christophschuhmann/improved-aesthetic-predictor), CLIP MIT |
+ | Style vs references | `style`, `styleNearest` | higher | cosine of the output's embedding to the centroid of the look's reference set, and to the nearest reference | CLIP (default), or `--style-model dinov2`: DINOv2 ViT-S/14 via timm, **Apache-2.0** |
+ | Identity | `identity`, `faceRate` | higher | ArcFace-style face embeddings of the output against the person's photos; the share of frames with a face | **AuraFace v1**'s recognition model (fal, **Apache-2.0**, trained for commercial use), with faces found and aligned by **YuNet** (OpenCV Zoo, **MIT**). The SCRFD detector AuraFace's repo ships comes from insightface's model zoo (released for non-commercial research; the licence is unclear), so it runs only with `--face-detector scrfd`. insightface's `buffalo_l` is **non-commercial research only** (recorded with the result): pick it with `--identity-model buffalo_l`; `--commercial-only` refuses it |
+ | Temporal consistency | `drift`, `driftMax`, `warp` | lower | frame-to-frame CLIP embedding drift (mean and worst jump), and a warp error: Farneback optical flow with a forward-backward occlusion mask | CLIP, OpenCV (Apache-2.0) |
+ | Lip-sync | `lipsync`, `lipsyncOffset` | higher | a proxy: mouth-region motion against the voice's loudness, with the best lag as the A/V offset | the identity metric's face detector for the face box when identity is installed, else a fixed lower-centre region |
+ | SyncNet (optional) | `syncnet` | higher | runs only when `FUOBE_EVAL_SYNCNET_CMD` points at your own SyncNet. It isn't bundled because its weights' licence isn't stated | yours |
+ | Shot continuity | `continuity` | higher | CLIP similarity between consecutive shots of a film | CLIP |
+ | Palette | `paletteFit`, `paletteCover` | lower, higher | the mean ΔE (CIE76, Lab) from each pixel to the nearest colour of the palette the request sent (`params.palette`, or the palette lock's colours), and the share of the palette's colours that are nearest for at least 3% of the pixels | none (numpy) |
+ | Time, cost, memory | `seconds`, `costUsd`, `vramGb` | lower | from the runner | — |
+
+ Identity needs `pnpm eval:setup --identity`, which installs insightface and onnxruntime (MIT
+ libraries). `metrics.json` records the face detector apart from the recognition model, each with its
+ licence, and compare warns when two runs used different detectors. Re-scoring is incremental: a job whose outputs and settings haven't changed keeps its
+ scores. `--metrics clip,style` re-scores only those families and keeps the others. `--force`
+ re-scores everything.
+
+ The metrics are signals, not verdicts. CLIP rewards literal prompt matches. The aesthetic predictor
+ has its own taste. Style needs references that really show the look. That is why promotion also
+ needs people's ratings.
+
+ ## Blind A/B review
+
+ `pnpm eval:review <runId>` writes `review/index.html` and serves it at `http://127.0.0.1:4173`. The
+ page shows two results side by side. Their order comes from a hash, and nothing on the page names
+ the variant, model or file.
+
+ - `--against variants` is the default when the run has two or more variants. It pairs the run's
+ candidate (see [the promote rule](#the-promote-rule)) with each of the others on the same case,
+ prompt and seed.
+ - `--against references` is the default otherwise. It pairs each output with one of your references
+ from `local/references/…`.
+ - `--against <otherRunId>` pairs the same jobs across two runs, for example before and after a
+ change.
+
+ Use **←** / **1** for the left result, **→** / **2** for the right one, **↓** / **0** / **Space**
+ for "about the same", **S** to skip and **U** / **Backspace** to undo. Space and Enter on a focused
+ button press that button. On a phone, use the three buttons. The server answers only on 127.0.0.1 /
+ localhost, and saves ratings only from its own page. Ratings save to `review/ratings.json` as you go. Opened as a plain file, the page keeps
+ them in the browser and offers a download. `pnpm eval:report` unblinds the ratings with
+ `review/key.json` and adds the preference per variant pair to `summary.json`.
+
+ ## Comparing runs and catching regressions
+
+ ```bash
+ pnpm eval:compare latest~1 latest # wins / losses / ties and mean gain per metric
+ pnpm eval:compare base-run new-run --fail-on clip,style --threshold 5% # exit 1 when either mean drops by more than 5 %
+ pnpm eval:compare run:prompt-only run:recipe --fail-on style # two variants of one run
+ pnpm eval:compare a b --fail-on warp --per-case # also fail on any single case's regression
+ ```
+
+ Compare matches jobs on case, prompt, seed and variant. `--threshold` can be an absolute amount in
+ the metric's units, or a percentage of A's mean. Without it, each metric's own noise band applies
+ (`lib/metric-info.mjs`). A guarded metric with no scores in both runs counts as a failure, so the
+ check can't pass just because the metric never ran. Every report appends its per-case means to
+ `results/history.jsonl`, and `pnpm eval:history --case soul/v1-general` shows a case over time.
+
+ ## The promote rule
+
+ The candidate is the variant a suite names in `defaults.candidate` (DoP: `research`), else `recipe`
+ when the run has it, else the run's first variant; `--candidate` picks another. It is **eligible** to
+ become the default only when one run, on the same prompts and seeds, shows all of the following for
+ the case:
+
+ 1. **Complete**: none of the recipe's LoRAs was left out on that engine. Its licences are information:
+ a non-commercial LoRA (or one licensed for the GPU only, on a cloud run) is a note on the verdict, and
+ holds the recipe only with `--licence-hold`.
+ 2. **Enough results**: at least 3 for the case.
+ 3. **Metrics**: against every alternative in the run (prompt only, half strength, the bare base,
+ today's default), it scores at least as well on the case's main metric: the first of style (a look
+ with references), lip-sync, identity, aesthetic, CLIP (a DoP motion's words) and warp error that the
+ case has scores for. It also gives up no more than 1.0 CLIP, 0.15 aesthetic, and on clips 0.002 warp
+ error and 0.004 drift.
+ 4. **People**: at least 6 blind ratings of this case's own pairs against the alternatives (every pair
+ the review offered, when it offered fewer), with at least 55 % of the non-tie ratings going to the
+ candidate. Ratings of other looks don't count.
+
+ If half strength wins, the verdict is **lower strengths**, not another recipe: the LoRAs over-cook,
+ so lower them in the research JSON and run again. When the candidate and an alternative ran on
+ different endpoints (fal's Z-Image runs LoRAs on `/lora`), the verdict says so. Demo runs never
+ promote anything. A run on one engine says to check the other engine too.
+
+ `pnpm eval:promote <runId>` writes `promote.json`. `--record` also writes each case's verdict into
+ the research JSON (`docs/research/fuobe-originals-recipes-5.json`). The verdict goes in the `eval`
+ list of the entry it measured: a Soul look's `presets[]` entry, or a motion's `motionsEffects[]`
+ entry. Each record holds:
+
+ - the run, the engine and the date;
+ - the verdict and the reasons for it;
+ - the main metric against each alternative;
+ - the LoRAs it ran, and the strengths to try when half strength won.
+
+ A newer record for the same engine and case replaces the older one. The file keeps its format, so
+ the diff shows only the records. Recording alone never changes a recipe, a strength or a default.
+
+ `--record --apply-strengths` does lower strengths that over-cook: where half strength won, the entry's
+ LoRAs take the strengths that variant ran, and the record lists each change (`appliedStrengths`). It
+ still lands as a diff for a person to review. Defaults stay code changes that a person reviews:
+
+ 1. Review the research JSON's diff (or edit it).
+ 2. Regenerate the catalog (`pnpm gen:catalog`).
+ 3. Measure both engines again.
+
+ ## Covers: the renders become the preview media
+
+ `pnpm eval:covers <runId>` takes the best render of each **promoted** case (best on the case's main
+ metric) and makes it that preset's cover. A still becomes a JPEG of at most 768 px; a clip becomes its
+ first 4 seconds, muted, at most 512 px, with its first frame as the poster. They go to
+ `public/previews/<suite>/`, and `src/lib/preset-previews.generated.ts` lists them by preset id (a
+ DoP preset, `effect-thunder-god`) or look id (`v1-general`). The gallery cards play a listed cover
+ instead of their procedural preview.
+
+ - `--variant catalog` takes that variant's renders for every case instead, such as what ships today.
+ - `--dry-run` lists what it would pick.
+ - Only Fuobe's own renders become covers: a demo run never does. A render whose LoRAs aren't commercial
+ becomes one with its licence noted (`licence` in the result); `--commercial-only` leaves it out. No
+ Higgsfield preview is used anywhere.
+ - It needs ffmpeg. Look at the media and the generated file's diff before committing them.
+
++### Covers from rendered masters
++
++Preview renders made outside a run (the gallery renders made in ComfyUI) become covers the same way:
++
++```sh
++pnpm eval:covers --from-masters <dir> --run comfyui-previews-2026-10 --engine comfyui --model ideogram4 --video-model minimax-h3 --variant lean-json
++```
++
++- `<dir>` has one folder per preset id (`effect-set-on-fire/`). A folder's `clip.mp4` becomes a clip
++ cover (first 4 seconds, its first frame as the poster). The cards play a clip in a loop, so its last 6
++ frames are crossfaded into its first ones and the loop has no jump (every clip cover is made this way,
++ also `eval:covers` from a run). A folder without a clip uses its `start.png` as a still cover (a 4:2:0
++ JPEG at most 768 px). A folder with neither is skipped.
++- The covers go to `public/previews/presets/` (`--suite` names another folder).
++- Each cover records the run, the engine, the model and the variant: `--model` for stills, `--video-model`
++ for clips. A folder's `meta.json` can name its own `model` and `variant`.
++- The manifest is merged. Covers that other runs wrote stay, and only the ids found in `<dir>` are
++ replaced. An id whose cover another run made in another folder (a measured `eval:covers` cover) is
++ skipped and listed, so re-running the masters never undoes a measured cover; `--replace` takes it over
++ and removes its old files. A manifest that can't be read stops the run instead of being overwritten.
++- Run it again as new masters land. A cover that is newer than its master is kept, so only new or
++ changed masters are encoded (`--force` encodes all of them). `--only id,id` limits the run to those
++ presets. A preset whose cover changes from a clip to a still loses its old clip.
++- `--dry-run` lists what it would make. Review the media and the manifest diff before committing them.
++
+ ## Tests
+
+ - `tests/eval-harness.test.ts` (Vitest) covers several areas:
+ - The runner runs end to end against Fuobe's real route handlers, served over HTTP, with the demo
+ provider: plan, price, upload, submit, wait, download and record.
+ - A studio route (Genjutsu), and a training case.
+ - The engine checks, the spend cap, `--resume` and the dry run.
+ - Case-file validation.
+ - Report, blind review, compare (with its exit codes), promote and `--record`.
+ - `tests/eval-api.test.ts` covers the API seams the harness needs: a recipe's LoRAs on
+ `POST /api/generations`, and a preview that says which LoRAs the route loads.
+ - `tests/eval-metrics.test.ts` runs the Python tests (`metrics/tests`, pytest) in the metrics venv,
+ or through uv. Without either, they are skipped. The maths tests use numpy only. The media tests
+ need ffmpeg. The model tests run when their weights are cached.
+ - `tests/e2e/eval-review.mjs` checks the report and review pages in a browser at 1440 and 390 px,
+ light and dark, and rates every pair with the keyboard.
+
+ ```bash
+ pnpm vitest run tests/eval-harness.test.ts tests/eval-api.test.ts tests/eval-metrics.test.ts
+ cd scripts/eval/metrics && .venv/bin/python -m pytest -q tests
+ ```
+
+ ## Adding an Original's cases
+
+ 1. Add `cases/<original>.json`. Use `selftest.json` or `genjutsu.json` as a model, depending on
+ whether the Original runs through `/api/generations` or through a studio route.
+ 2. Name targets per engine. Put the Original's model id first and today's base model after it, so
+ the suite runs now and switches to the Original once it exists.
+ 3. Put inputs the repo can't ship under `local/…`, with small `demoInputs` from `fixtures/`.
+ 4. Choose metrics. Add references if style or identity matter.
+ 5. Run `pnpm eval:validate`, then `pnpm eval:run --suite <original> --engine demo`.
diff --cc scripts/eval/eval.mjs
index 00000000,9983c0ce..7b42d9a0
mode 000000,100644..100644
--- a/scripts/eval/eval.mjs
+++ b/scripts/eval/eval.mjs
@@@ -1,0 -1,442 +1,506 @@@
+ #!/usr/bin/env node
+ // The evaluation harness's command line: pnpm eval:<command> (or fuobe eval <command>). See
+ // scripts/eval/README.md. Every command takes --json for scripts, and --url / --token for the
+ // Fuobe to measure (else FUOBE_URL / FUOBE_TOKEN, else what `fuobe login` saved).
+ import { spawnSync } from "node:child_process";
+ import fs from "node:fs";
+ import path from "node:path";
++import { fileURLToPath, pathToFileURL } from "node:url";
+ import { parseArgs } from "node:util";
+ import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
+ import { compareRuns, compareText, promote, promoteText, researchRecords } from "./lib/compare.mjs";
-import { makeCovers } from "./lib/covers.mjs";
++import { coversFromMasters, makeCovers } from "./lib/covers.mjs";
+ import { scoreRun } from "./lib/metrics.mjs";
+ import { METRICS_DIR, REPO_DIR, resultsDir } from "./lib/paths.mjs";
+ import { RECIPES_FILE } from "./lib/recipes.mjs";
+ import { writeReport } from "./lib/report.mjs";
+ import { serveReview, writeReview } from "./lib/review.mjs";
+ import { DEFAULT_CLOUD_CAP, money, runEval } from "./lib/run.mjs";
+ import { connect } from "./lib/server.mjs";
+ import { listRuns, readJsonl, resolveRun } from "./lib/store.mjs";
+
+ const list = (v) => (v ? String(v).split(",").map((s) => s.trim()).filter(Boolean) : undefined);
+ const num = (v, name) => {
+ if (v === undefined) return undefined;
+ const n = Number(v);
+ if (!Number.isFinite(n)) throw new Usage(`--${name} takes a number, not “${v}”`);
+ return n;
+ };
+
+ class Usage extends Error {}
+
+ const COMMON = { url: { type: "string" }, token: { type: "string" }, out: { type: "string" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } };
+ const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "style-model": { type: "string" }, "identity-model": { type: "string" }, "face-detector": { type: "string" }, "accept-noncommercial": { type: "boolean" }, "commercial-only": { type: "boolean" }, force: { type: "boolean" } };
+
+ const HELP = {
+ run: `pnpm eval:run --suite <name> --engine demo|open|cloud [options]
+
+ --suite <name|file> soul, soul-cinema, soul-hex, soul-id, dop, dop-mix, genjutsu, mixed-media, shorts, speak, cinema, selftest (or a path)
+ --engine <e> demo (free self-test), open (your ComfyUI) or cloud (hosted open models)
+ --looks <a,b> Soul looks by slug, name or id (v1-general, "Flash editorial")
+ --cases <ids> case ids or prefixes with * (dop/motion-*)
+ --tags <t> cases with any of these tags (v1, civitai, train-own…)
+ --variants <a,b> recipe variants to run (default: the suite's default); all = every variant
+ --model <id> one model id for every job instead of the suite's targets
+ --limit <n> at most n cases · --prompts <n> at most n prompts per case · --seeds 1,2
+ --dry-run list the jobs and the estimated spend; uploads and starts nothing
+ --max-usd <n> the cloud spend cap (default $${DEFAULT_CLOUD_CAP}): jobs, training and an earlier attempt's spend count;
+ the run refuses to start over it and starts no job that would go over it
+ --allow-unpriced also run cloud jobs (and training) the server can't price; they count once their cost is known
+ --concurrency <n> jobs at a time (open 1, others 4)
+ --resume <runId> run the failed and missing jobs of an earlier run again
+ --allow-fixtures use the synthetic fixtures where your own inputs are missing
+ --comfy-url <url> ComfyUI's address, for memory and its own timings (open engine; default COMFYUI_URL)
+ --label <text> a note for this run
+ --no-metrics don't score afterwards · --no-report: don't write the report either`,
+ report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--style-model clip|dinov2] [--face-detector yunet|scrfd] [--force]",
+ review: "pnpm eval:review <runId|latest> [--against variants|references|<otherRunId>] [--port 4173] [--no-serve] [--limit n]",
+ compare: "pnpm eval:compare <runA[:variant]> <runB[:variant]> [--fail-on clip,aesthetic] [--threshold 1|5%] [--per-case]",
+ promote: `pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain] [--record [--apply-strengths] [--research file]] [--licence-hold]
+
+ --licence-hold a non-commercial LoRA (or one licensed for the GPU only, on a cloud run) holds the recipe;
+ without it the licence is a note on the verdict
+
+ --record writes each case's verdict into the research JSON entry it measured
+ --apply-strengths with --record: where half strength won, lowers that entry's LoRA strengths to the ones it ran
+ (review the diff, then pnpm gen:catalog and run both engines again)`,
+ covers: `pnpm eval:covers <runId> [--variant <name>] [--dry-run] [--public-dir public] [--manifest src/lib/preset-previews.generated.ts] [--commercial-only]
+
+ The best render of each promoted case becomes its preset's cover: encoded small into public/previews/<suite>/
+ and listed in src/lib/preset-previews.generated.ts, which the gallery cards show. --variant takes that
- variant's renders for every case instead (catalog: what ships today). Demo runs never make covers.`,
++ variant's renders for every case instead (catalog: what ships today). Demo runs never make covers.
++
++pnpm eval:covers --from-masters <dir> --run <name> [--engine comfyui] [--model <id>] [--video-model <id>] [--variant <name>]
++ [--suite presets] [--only id,id] [--force] [--replace] [--dry-run] [--public-dir public] [--manifest …]
++
++ Rendered masters outside a run, one folder per preset id: its clip.mp4 becomes a clip cover, else its
++ start.png a still cover, in public/previews/<suite>/ (presets by default). Each records --run, --engine,
++ --model (--video-model for clips) and --variant; a folder's meta.json can name its own model and variant.
++ The manifest is merged: other entries stay, and an id whose cover another run made elsewhere (a measured
++ cover) is skipped (--replace takes it over). Run again, it encodes only new or changed masters (--force: all).
++ Clips loop without a jump: their last frames are crossfaded into their first ones.`,
+ history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
+ validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
+ trash: "pnpm eval:trash <runId> [--dry-run] moves the run's generations to that Fuobe's Trash (its results here stay)",
+ setup: "pnpm eval:setup [--identity] [--download [--dinov2] [--scrfd]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",
+ };
+
+ function usage() {
+ return [
+ "Fuobe evaluation harness. Commands:",
+ ...Object.values(HELP).map((h) => ` ${h.split("\n")[0]}`),
+ "",
+ "Results go to scripts/eval/results/<runId>/ (git-ignored; --out or FUOBE_EVAL_RESULTS to move them).",
+ "More: scripts/eval/README.md",
+ ].join("\n");
+ }
+
+ /**
+ * @param {string[]} argv the arguments after the command name's position (command first)
+ * @param {{ stdout?: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, env?: Record<string, string | undefined>, home?: string, fetch?: typeof fetch, signal?: AbortSignal }} [io]
+ * @returns {Promise<number>} the exit code
+ */
+ export async function main(argv, io = {}) {
+ const out = io.stdout ?? process.stdout;
+ const err = io.stderr ?? process.stderr;
+ const env = io.env ?? process.env;
+ const print = (s) => out.write(`${s}\n`);
+ const note = (s) => err.write(`${s}\n`);
+ const [command, ...rest] = argv;
+ if (!command || command === "help" || command === "--help" || command === "-h") {
+ print(rest[0] && HELP[rest[0]] ? HELP[rest[0]] : usage());
+ return 0;
+ }
+ const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup, trash, covers };
+ if (!commands[command]) {
+ note(`Unknown command “${command}”.\n${usage()}`);
+ return 2;
+ }
+ try {
+ return (await commands[command](rest, { print, note, env, io })) ?? 0;
+ } catch (e) {
+ if (e instanceof Usage) {
+ note(`${e.message}\n\n${HELP[command] ?? usage()}`);
+ return 2;
+ }
+ if (env.FUOBE_DEBUG) note(e.stack);
+ note(e.message);
+ return 1;
+ }
+ }
+
+ function parse(args, options, { positionals = false } = {}) {
+ try {
+ return parseArgs({ args, options: { ...COMMON, ...options }, allowPositionals: positionals, strict: true });
+ } catch (e) {
+ throw new Usage(e.message.replace(/^TypeError \[[A-Z_]+\]: /, ""));
+ }
+ }
+
+ const root = (values, env) => resultsDir(env, values.out);
+
+ async function score(dir, v, ctx) {
+ if (v["no-metrics"]) return null;
+ ctx.note("Scoring the outputs…");
+ const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], styleModel: v["style-model"], identityModel: v["identity-model"], faceDetector: v["face-detector"], commercialOnly: v["commercial-only"], force: v.force, log: ctx.note, env: ctx.env });
+ if (!r.ok) ctx.note(`Not scored: ${r.reason}. Timing and cost are in the report; pnpm eval:report ${path.basename(dir)} scores it later.`);
+ return r;
+ }
+
+ function reportAll(dir, rootDir, ctx) {
+ const summary = writeReport(dir, rootDir);
+ const loaded = { dir, runId: summary.runId, rows: readJsonl(path.join(dir, "jobs.jsonl")) };
+ // The latest row per job (a resumed run appends retries).
+ loaded.rows = [...new Map(loaded.rows.map((r) => [r.id, r])).values()];
+ const rv = writeReview(loaded);
+ ctx.note(`Report: ${path.join(dir, "report.html")}`);
+ ctx.note(`Review: ${rv.pairs} blind pair${rv.pairs === 1 ? "" : "s"} · pnpm eval:review ${summary.runId}`);
+ return summary;
+ }
+
+ function printSummary(summary, ctx) {
+ const free = summary.engine !== "cloud";
+ ctx.print(`${summary.title} · ${summary.engine} · ${summary.counts.succeeded}/${summary.counts.jobs} done${summary.counts.failed ? ` · ${summary.counts.failed} failed` : ""}${summary.counts.skipped ? ` · ${summary.counts.skipped} skipped` : ""} · ${free ? "Free" : money(summary.costUsd.spent)}`);
+ for (const [v, s] of Object.entries(summary.variants)) {
+ const means = Object.entries(s.mean)
+ .map(([k, x]) => `${k} ${k === "costUsd" ? money(x) : Number(x).toFixed(k === "clip" || k === "seconds" ? 1 : 3)}`)
+ .join(" · ");
+ ctx.print(` ${v}: ${s.succeeded}/${s.jobs}${means ? ` · ${means}` : ""}`);
+ }
+ for (const s of summary.skips.slice(0, 5)) ctx.print(` skipped ${s.count}: ${s.reason}`);
+ for (const f of summary.failures.slice(0, 5)) ctx.print(` failed ${f.id}: ${f.error}`);
+ }
+
+ async function run(args, ctx) {
+ const { values: v } = parse(args, {
+ suite: { type: "string" },
+ engine: { type: "string" },
+ looks: { type: "string" },
+ cases: { type: "string" },
+ tags: { type: "string" },
+ variants: { type: "string" },
+ model: { type: "string" },
+ limit: { type: "string" },
+ prompts: { type: "string" },
+ seeds: { type: "string" },
+ "dry-run": { type: "boolean" },
+ list: { type: "boolean" },
+ "max-usd": { type: "string" },
+ "allow-unpriced": { type: "boolean" },
+ concurrency: { type: "string" },
+ resume: { type: "string" },
+ "allow-fixtures": { type: "boolean" },
+ "comfy-url": { type: "string" },
+ label: { type: "string" },
+ "no-report": { type: "boolean" },
+ ...SCORE,
+ });
+ if (v.help) return ctx.print(HELP.run), 0;
+ const rootDir = root(v, ctx.env);
+ // A resumed run keeps its own suite and engine.
+ const resumeRun = v.resume ? resolveRun(rootDir, v.resume) : null;
+ const before = resumeRun ? JSON.parse(fs.readFileSync(path.join(resumeRun.dir, "run.json"), "utf8")) : null;
+ const suiteName = v.suite ?? before?.harness?.suiteFile ?? before?.suite;
+ if (!suiteName) throw new Usage("Name a suite with --suite (soul, dop, selftest…)");
+ const suite = loadSuite(before?.harness?.suiteFile && !v.suite ? path.join(REPO_DIR, before.harness.suiteFile) : suiteName);
+ const engine = v.engine ?? before?.engine;
+ if (!["demo", "open", "cloud"].includes(engine)) throw new Usage("Pick --engine demo, open or cloud");
+ const variants = v.variants === "all" ? Object.keys(suite.variants ?? { default: {} }) : list(v.variants);
+ const { client, target } = connect({ url: v.url, token: v.token }, { env: ctx.env, home: ctx.io.home, fetch: ctx.io.fetch });
+ const ac = new AbortController();
+ const signal = ctx.io.signal ?? ac.signal;
+ const onInt = () => {
+ if (ac.signal.aborted) process.exit(130);
+ ctx.note("Stopping: no new jobs start; the ones running keep going on the server. Ctrl+C again to quit now.");
+ ac.abort();
+ };
+ if (!ctx.io.signal) process.on("SIGINT", onInt);
+ try {
+ const result = await runEval(
+ {
+ suite,
+ engine,
+ variants,
+ cases: list(v.cases),
+ looks: list(v.looks),
+ tags: list(v.tags),
+ limit: num(v.limit, "limit"),
+ prompts: num(v.prompts, "prompts"),
+ seeds: list(v.seeds)?.map((s) => num(s, "seeds")),
+ model: v.model,
+ dryRun: v["dry-run"],
+ maxUsd: num(v["max-usd"], "max-usd"),
+ allowUnpriced: v["allow-unpriced"],
+ concurrency: num(v.concurrency, "concurrency"),
+ root: rootDir,
+ resume: resumeRun?.runId,
+ allowFixtures: v["allow-fixtures"],
+ comfyUrl: v["comfy-url"] ?? (engine === "open" ? (ctx.env.COMFYUI_URL ?? "http://127.0.0.1:8188") : undefined),
+ label: v.label,
+ },
+ { client, target, log: ctx.note, signal, fetch: ctx.io.fetch },
+ );
+ if (result.dryRun) {
+ if (v.json) return ctx.print(JSON.stringify(result, null, 2)), 0;
+ const free = engine !== "cloud";
+ ctx.print(`${suite.title} on ${engine} (${result.server})`);
+ ctx.print(`${result.total} jobs · ${result.runnable} can run · ${result.skipped} skipped · ${result.cases} cases · estimated ${free ? "Free" : money(result.estimateUsd)}${result.unknownCost ? ` (+${result.unknownCost} without a price)` : ""}${engine === "cloud" ? ` · cap ${money(result.maxUsd)}` : ""}`);
+ if (result.models.length) ctx.print(`Models: ${result.models.join(", ")} · variants: ${result.variants.join(", ")}`);
+ for (const [why, n] of Object.entries(result.skipReasons).sort((a, b) => b[1] - a[1]).slice(0, 8)) ctx.print(` ${n} skipped: ${why}`);
+ if (result.missingLoras?.length) ctx.print(`LoRAs ComfyUI doesn't have yet (${result.missingLoras.length}): ${result.missingLoras.map((l) => `${l.file} (${l.jobs} job${l.jobs === 1 ? "" : "s"})`).join(", ")}`);
+ if (v.list) for (const j of result.jobs) ctx.print(` ${j.skip ? "·" : "▸"} ${j.case} · ${j.variant} · ${j.prompt} · s${j.seed} · ${j.model}${j.skip ? "" : ` · ${j.costUsd == null ? "price unknown" : free ? "Free" : money(j.costUsd)}`}${j.loras?.applied ? ` · ${j.loras.applied.join(" + ") || "no LoRAs"}` : ""}${j.skip ? ` — ${j.skip}` : ""}`);
+ return 0;
+ }
+ if (v["no-report"]) {
+ ctx.note(`Results: ${result.dir}`);
+ return result.run.results.failed ? 1 : 0;
+ }
+ await score(result.dir, v, ctx);
+ const summary = reportAll(result.dir, rootDir, ctx);
+ if (v.json) ctx.print(JSON.stringify(summary, null, 2));
+ else printSummary(summary, ctx);
+ return summary.counts.failed || result.run.interrupted ? 1 : 0;
+ } finally {
+ if (!ctx.io.signal) process.off("SIGINT", onInt);
+ }
+ }
+
+ async function report(args, ctx) {
+ const { values: v, positionals } = parse(args, SCORE, { positionals: true });
+ if (v.help) return ctx.print(HELP.report), 0;
+ const rootDir = root(v, ctx.env);
+ const { dir } = resolveRun(rootDir, positionals[0] ?? "latest");
+ await score(dir, v, ctx);
+ const summary = reportAll(dir, rootDir, ctx);
+ if (v.json) ctx.print(JSON.stringify(summary, null, 2));
+ else printSummary(summary, ctx);
+ return 0;
+ }
+
+ async function review(args, ctx) {
+ const { values: v, positionals } = parse(args, { against: { type: "string" }, port: { type: "string" }, "no-serve": { type: "boolean" }, limit: { type: "string" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.review), 0;
+ const rootDir = root(v, ctx.env);
+ const { dir, runId } = resolveRun(rootDir, positionals[0] ?? "latest");
+ let against = v.against;
+ if (against && !["variants", "references"].includes(against)) {
+ const other = resolveRun(rootDir, against);
+ against = { dir: other.dir, runId: other.runId, rows: [...new Map(readJsonl(path.join(other.dir, "jobs.jsonl")).map((r) => [r.id, r])).values()] };
+ }
+ const rows = [...new Map(readJsonl(path.join(dir, "jobs.jsonl")).map((r) => [r.id, r])).values()];
+ const r = writeReview({ dir, runId, rows }, { against, limit: num(v.limit, "limit") });
+ if (!r.pairs) ctx.note("Nothing to compare yet: the run needs two variants of a case, your own references (scripts/eval/local/references/…), or --against another run.");
+ if (v["no-serve"]) {
+ ctx.print(r.file);
+ return 0;
+ }
+ const { server, url } = await serveReview(dir, { port: num(v.port, "port") ?? 4173 });
+ ctx.print(`Blind review of ${r.pairs} pair${r.pairs === 1 ? "" : "s"}: ${url}`);
+ ctx.note("Ratings are saved to review/ratings.json as you go. Ctrl+C stops the server; pnpm eval:report then adds them to the summary.");
+ await new Promise((resolve) => {
+ const stop = () => server.close(resolve);
+ process.once("SIGINT", stop);
+ ctx.io.signal?.addEventListener("abort", stop, { once: true });
+ });
+ return 0;
+ }
+
+ async function compare(args, ctx) {
+ const { values: v, positionals } = parse(args, { "fail-on": { type: "string" }, metric: { type: "string" }, threshold: { type: "string" }, "per-case": { type: "boolean" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.compare), 0;
+ if (positionals.length !== 2) throw new Usage("Give two runs: pnpm eval:compare <runA> <runB> (latest~1 latest compares the last two)");
+ const rootDir = root(v, ctx.env);
+ const a = resolveRun(rootDir, positionals[0]);
+ const b = resolveRun(rootDir, positionals[1]);
+ const c = compareRuns(a, b, { failOn: list(v["fail-on"] ?? v.metric), threshold: v.threshold, perCase: v["per-case"] });
+ ctx.print(v.json ? JSON.stringify(c, null, 2) : compareText(c));
+ return c.failed ? 1 : 0;
+ }
+
+ async function promoteCmd(args, ctx) {
+ const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" }, record: { type: "boolean" }, "apply-strengths": { type: "boolean" }, research: { type: "string" }, "licence-hold": { type: "boolean" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.promote), 0;
+ const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
+ const doc = promote(dir, { candidate: v.candidate, alternatives: list(v.against), ...(v["licence-hold"] && { rule: { licenceHold: true } }) });
+ ctx.print(v.json ? JSON.stringify(doc, null, 2) : promoteText(doc));
+ if (v["apply-strengths"] && !v.record) throw new Usage("--apply-strengths goes with --record");
+ if (!v.record) return 0;
+ // --record: the verdicts go into the research JSON for a person to review (git diff), never a default.
+ if (doc.engine === "demo") throw new Error("A demo run measures the harness, not models: there is nothing to record in the research.");
+ const records = researchRecords(doc, { applyStrengths: v["apply-strengths"] });
+ if (!records.length) return ctx.note("No look or motion in this run to record."), 0;
+ const file = path.resolve(v.research ?? path.join(REPO_DIR, RECIPES_FILE));
+ const recordsFile = path.join(dir, "research-records.json");
+ fs.writeFileSync(recordsFile, `${JSON.stringify(records, null, 2)}\n`);
+ const py = ctx.env.FUOBE_EVAL_PYTHON ?? (process.platform === "win32" ? "python" : "python3");
+ const r = spawnSync(py, ["-I", path.join(METRICS_DIR, "fuobe_metrics", "research.py"), recordsFile, file], { encoding: "utf8", env: ctx.env });
+ if (r.error) throw new Error(`--record needs Python 3 (${py} isn't there; set FUOBE_EVAL_PYTHON)`);
+ if (r.status !== 0) throw new Error(`Recording failed: ${(r.stderr || r.stdout).trim().split("\n").at(-1)}`);
+ const res = JSON.parse(r.stdout);
+ ctx.note(`Recorded ${res.recorded} result${res.recorded === 1 ? "" : "s"} in ${path.relative(REPO_DIR, file) || file} (each entry's "eval" list). Review the diff; recipes and defaults change only by hand.`);
+ if (res.lowered?.length) {
+ ctx.note(`Lowered the strengths of ${res.lowered.length} LoRA${res.lowered.length === 1 ? "" : "s"} where half strength won:`);
+ for (const l of res.lowered) ctx.note(` ${l.entry}: ${l.file} ${l.from} → ${l.to}`);
+ ctx.note("Review the diff, run pnpm gen:catalog, and measure both engines again before committing.");
+ }
+ for (const m of res.missing) ctx.note(` not in the research: ${JSON.stringify(m)}`);
+ return 0;
+ }
+
+ async function history(args, ctx) {
+ const { values: v } = parse(args, { suite: { type: "string" }, case: { type: "string" }, limit: { type: "string" } });
+ if (v.help) return ctx.print(HELP.history), 0;
+ const rootDir = root(v, ctx.env);
+ const runs = listRuns(rootDir).filter((r) => !v.suite || r.run.suite === v.suite);
+ const rows = readJsonl(path.join(rootDir, "history.jsonl")).filter((r) => (!v.suite || r.suite === v.suite) && (!v.case || r.caseId === v.case));
+ if (v.json) return ctx.print(JSON.stringify({ runs: runs.map((r) => ({ runId: r.runId, ...r.run.results, engine: r.run.engine, suite: r.run.suite, startedAt: r.run.startedAt, label: r.run.label })), history: rows }, null, 2)), 0;
+ if (!runs.length) return ctx.print(`No runs in ${rootDir} yet. Start with: pnpm eval:run --suite selftest --engine demo`), 0;
+ for (const r of runs.slice(0, num(v.limit, "limit") ?? 20)) {
+ const res = r.run.results ?? {};
+ ctx.print(`${r.runId} ${r.run.engine} ${res.succeeded ?? 0} done${res.failed ? ` · ${res.failed} failed` : ""}${res.skipped ? ` · ${res.skipped} skipped` : ""}${r.run.engine === "cloud" && r.run.spentUsd != null ? ` · ${money(r.run.spentUsd)}` : ""}${r.run.label ? ` ${r.run.label}` : ""}`);
+ }
+ if (v.case) for (const h of rows) ctx.print(` ${h.runId} ${h.variant}: ${Object.entries(h.scores).map(([k, x]) => `${k} ${Number(x).toFixed(3)}`).join(" · ")}`);
+ return 0;
+ }
+
+ async function validate(args, ctx) {
+ const { values: v, positionals } = parse(args, {}, { positionals: true });
+ if (v.help) return ctx.print(HELP.validate), 0;
+ const results = validateAll(positionals.length ? positionals.map((p) => path.resolve(p)) : suiteFiles());
+ let bad = results.filter((r) => !r.ok).length;
+ const { generated } = await import("./gen-cases.mjs");
+ const gen = generated();
+ const stale = ["soul.json", "dop.json", "dop-mix.json", "case.schema.json"].filter((name) => {
- const file = path.join(path.dirname(new URL(import.meta.url).pathname), "cases", name);
++ const file = path.join(path.dirname(fileURLToPath(import.meta.url)), "cases", name);
+ const want = `${JSON.stringify(gen[name], null, 2)}\n`;
- return !fs.existsSync(file) || fs.readFileSync(file, "utf8") !== want;
++ // A Windows checkout may have CRLF line endings: the same content.
++ return !fs.existsSync(file) || fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n") !== want;
+ });
+ if (v.json) return ctx.print(JSON.stringify({ suites: results, stale }, null, 2)), bad || stale.length ? 1 : 0;
+ for (const r of results) {
+ ctx.print(`${r.ok ? "✓" : "✗"} ${path.relative(REPO_DIR, r.file)}${r.ok ? ` · ${r.cases} cases` : ""}`);
+ for (const l of r.lines) ctx.print(` ${l}`);
+ }
+ for (const s of stale) ctx.print(`✗ cases/${s} is out of date with the research: node scripts/eval/gen-cases.mjs`);
+ bad += stale.length;
+ return bad ? 1 : 0;
+ }
+
+ /**
+ * A run's generations to the Trash of the Fuobe it ran on: the harness's renders stay out of the Library
+ * anyway (feature "eval" is a helper), but a studio route's steps carry the studio's own feature. The run's
+ * folder here keeps its outputs and scores. The token rides only to that server, as with every command.
+ */
+ async function trash(args, ctx) {
+ const { values: v, positionals } = parse(args, { "dry-run": { type: "boolean" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.trash), 0;
+ const { dir, runId } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
+ const run = JSON.parse(fs.readFileSync(path.join(dir, "run.json"), "utf8"));
+ if (!run.server?.url && !v.url) throw new Error(`${runId} doesn't say which Fuobe it ran on: name it with --url`);
+ // Every attempt's generations, and a studio route's steps.
+ const ids = [...new Set(readJsonl(path.join(dir, "jobs.jsonl")).flatMap((r) => [...(r.generations ?? []), ...(r.steps ?? [])]))];
+ const { client, target } = connect({ url: v.url ?? run.server?.url, token: v.token }, { env: ctx.env, home: ctx.io.home, fetch: ctx.io.fetch });
+ if (v["dry-run"]) return ctx.print(`${ids.length} generation${ids.length === 1 ? "" : "s"} of ${runId} would go to the Trash on ${target.url}`), 0;
+ let moved = 0;
+ let gone = 0;
+ for (const id of ids) {
+ try {
+ await client.request("DELETE", `/api/generations/${encodeURIComponent(id)}`);
+ moved++;
+ } catch (e) {
+ if (e.status === 404) gone++;
+ else throw e;
+ }
+ }
+ if (v.json) return ctx.print(JSON.stringify({ runId, server: target.url, moved, gone }, null, 2)), 0;
+ ctx.print(`Moved ${moved} generation${moved === 1 ? "" : "s"} of ${runId} to the Trash on ${target.url}${gone ? ` (${gone} were gone already)` : ""}. The run's results here stay; empty the Trash in Fuobe to delete them for good.`);
+ return 0;
+ }
+
+ async function covers(args, ctx) {
- const { values: v, positionals } = parse(args, { variant: { type: "string" }, "dry-run": { type: "boolean" }, "public-dir": { type: "string" }, manifest: { type: "string" }, "commercial-only": { type: "boolean" } }, { positionals: true });
++ const { values: v, positionals } = parse(
++ args,
++ {
++ variant: { type: "string" },
++ "dry-run": { type: "boolean" },
++ "public-dir": { type: "string" },
++ manifest: { type: "string" },
++ "commercial-only": { type: "boolean" },
++ "from-masters": { type: "string" },
++ run: { type: "string" },
++ engine: { type: "string" },
++ model: { type: "string" },
++ "video-model": { type: "string" },
++ suite: { type: "string" },
++ only: { type: "string" },
++ force: { type: "boolean" },
++ replace: { type: "boolean" },
++ },
++ { positionals: true },
++ );
+ if (v.help) return ctx.print(HELP.covers), 0;
++ if (v["from-masters"]) return coversFromMastersCmd(v, ctx);
+ const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
+ const r = makeCovers(dir, { variant: v.variant, dryRun: v["dry-run"], publicDir: v["public-dir"] && path.resolve(v["public-dir"]), manifest: v.manifest && path.resolve(v.manifest), commercialOnly: v["commercial-only"] });
+ if (v.json) return ctx.print(JSON.stringify(r, null, 2)), 0;
+ ctx.print(`${r.covers.length} cover${r.covers.length === 1 ? "" : "s"} from ${r.runId} (${r.engine}, ${r.variant})${v["dry-run"] ? " would be made" : ""}`);
+ for (const c of r.covers) ctx.print(` ${c.key} ← ${c.job}${c.metric ? ` (best ${c.metric}${c.score != null ? ` ${Number(c.score).toFixed(3)}` : ""})` : ""}`);
+ for (const sk of r.skipped.slice(0, 10)) ctx.print(` · ${sk.caseId}: ${sk.why}`);
+ if (r.skipped.length > 10) ctx.print(` · and ${r.skipped.length - 10} more`);
+ if (r.covers.length && !v["dry-run"]) ctx.note(`Look at the media in ${path.relative(REPO_DIR, r.folder) || r.folder} and the diff of ${path.relative(REPO_DIR, r.manifest) || r.manifest} before committing them.`);
+ return 0;
+ }
+
++/** pnpm eval:covers --from-masters <dir>: covers from rendered masters, merged into the manifest. */
++function coversFromMastersCmd(v, ctx) {
++ if (!v.run) throw new Usage("--from-masters needs --run <name>: the provenance every cover it makes records");
++ const r = coversFromMasters(path.resolve(v["from-masters"]), {
++ run: v.run,
++ engine: v.engine,
++ model: v.model,
++ videoModel: v["video-model"],
++ variant: v.variant,
++ suite: v.suite,
++ only: v.only?.split(",").map((s) => s.trim()).filter(Boolean),
++ force: v.force,
++ replace: v.replace,
++ dryRun: v["dry-run"],
++ publicDir: v["public-dir"] && path.resolve(v["public-dir"]),
++ manifest: v.manifest && path.resolve(v.manifest),
++ });
++ if (v.json) return ctx.print(JSON.stringify(r, null, 2)), 0;
++ const n = (k, word) => `${k} ${word}${k === 1 ? "" : "s"}`;
++ const clips = r.covers.filter((c) => c.video).length;
++ const kept = r.covers.filter((c) => c.kept).length;
++ const tail = v["dry-run"] ? " would be made" : kept ? `, ${kept} already up to date` : "";
++ ctx.print(`${n(r.covers.length, "cover")} from masters (${n(clips, "clip")}, ${n(r.covers.length - clips, "still")}) as ${r.run} (${r.engine})${tail}`);
++ for (const c of r.covers.slice(0, 20)) ctx.print(` ${c.key} ← ${path.basename(c.from)}${c.model ? ` (${c.model})` : ""}${c.kept ? " · up to date" : ""}`);
++ if (r.covers.length > 20) ctx.print(` and ${r.covers.length - 20} more`);
++ for (const sk of r.skipped.slice(0, 10)) ctx.print(` · ${sk.id}: ${sk.why}`);
++ if (r.skipped.length > 10) ctx.print(` · and ${r.skipped.length - 10} more`);
++ if (r.covers.length && !v["dry-run"]) ctx.note(`Look at the media in ${path.relative(REPO_DIR, r.folder) || r.folder} and the diff of ${path.relative(REPO_DIR, r.manifest) || r.manifest} before committing them.`);
++ return 0;
++}
++
+ async function setup(args, ctx) {
+ const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, scrfd: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
+ if (v.help) return ctx.print(HELP.setup), 0;
+ const step = (cmd, a, opts = {}) => {
+ ctx.note(`$ ${cmd} ${a.join(" ")}`);
+ const r = spawnSync(cmd, a, { cwd: METRICS_DIR, stdio: "inherit", env: ctx.env, ...opts });
+ if (r.error) throw new Error(`${cmd} isn't installed: get uv from https://docs.astral.sh/uv/ (one command), then run pnpm eval:setup again`);
+ if (r.status !== 0) throw new Error(`${cmd} ${a[0]} failed (exit ${r.status})`);
+ };
+ const py = process.platform === "win32" ? ".venv/Scripts/python.exe" : ".venv/bin/python";
+ if (!fs.existsSync(path.join(METRICS_DIR, py))) step("uv", ["venv", ".venv", "--python", ">=3.11"]);
+ step("uv", ["pip", "install", "--python", py, "-r", "requirements.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);
+ if (v.identity) step("uv", ["pip", "install", "--python", py, "-r", "requirements-identity.txt"]);
+ if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.dinov2 ? ["--dinov2"] : []), ...(v.scrfd ? ["--scrfd"] : [])]);
+ ctx.print(`Metrics ready in ${path.join(METRICS_DIR, ".venv")}${v.download ? "" : " (weights download on first use, or run pnpm eval:setup --download)"}.`);
+ return 0;
+ }
+
-if (import.meta.url === `file://${process.argv[1]}`) {
++// Run directly (not imported by the tests). Compared as URLs, so a Windows script path matches too.
++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ process.exitCode = await main(process.argv.slice(2));
+ }
diff --cc scripts/eval/gen-cases.mjs
index 00000000,4be86d84..8b618411
mode 000000,100644..100644
--- a/scripts/eval/gen-cases.mjs
+++ b/scripts/eval/gen-cases.mjs
@@@ -1,0 -1,418 +1,420 @@@
+ #!/usr/bin/env node
+ // Writes the generated suites from the research, so the case files can't drift from it:
+ // cases/soul.json one case per Soul look (139, ids from docs/research/higgsfield-image-studios.json)
+ // cases/soul-cinema.json Soul Cinema's one look (research soul.soulCinema) on cinematic scenes
+ // cases/soul-hex.json Soul HEX: Fuobe's own palettes in the prompt, and the open engine's palette lock
+ // cases/dop.json one case per DoP motion / effect that the research gives a LoRA, a camera pose or a camera LoRA
+ // cases/dop-mix.json Fuobe DoP's Mix: a move and an effect on one run, against the move alone
+ // cases/case.schema.json the suite format as JSON Schema (for editors)
+ // The prompts are Fuobe's own (never Higgsfield's). Run: node scripts/eval/gen-cases.mjs [--check]
+ import fs from "node:fs";
+ import path from "node:path";
++import { pathToFileURL } from "node:url";
+ import { CASES_DIR, REPO_DIR } from "./lib/paths.mjs";
+ import { pinnedLora, research, slug, soulLooks } from "./lib/recipes.mjs";
+ import { schemaJson } from "./lib/schema.mjs";
+
+ /** Subjects every look is tried on; the first two go to every look (so looks compare on the same scenes and seeds). */
+ const SOUL_PROMPTS = [
+ { id: "portrait", seed: 1001, text: "a young woman with freckles and loose dark hair looks over her shoulder on a quiet city street" },
+ { id: "street", seed: 2002, text: "a man in a long camel coat crosses a pedestrian crossing, full body, morning light" },
+ { id: "friends", seed: 3003, text: "two friends laughing together on a rooftop at dusk, the skyline behind them" },
+ { id: "kitchen", seed: 3003, text: "a cosy kitchen in morning light, a woman pours coffee while a cat sits on the counter" },
+ { id: "fisherman", seed: 3003, text: "an old fisherman mending a net on a wooden pier, weathered hands, overcast sky" },
+ { id: "skater", seed: 3003, text: "a teenager on a skateboard under neon shop signs at night, motion in the background" },
+ { id: "cyclist", seed: 3003, text: "a lone cyclist on a coastal road between green cliffs and the sea" },
+ { id: "perfume", seed: 3003, text: "a glass perfume bottle on a marble table beside a sprig of white flowers" },
+ { id: "dog", seed: 3003, text: "a golden retriever with sunglasses in the passenger seat of a convertible" },
+ { id: "dancer", seed: 3003, text: "a dancer mid-leap in an empty rehearsal studio with tall windows" },
+ { id: "market", seed: 3003, text: "a woman choosing oranges at a busy outdoor market stall" },
+ { id: "musician", seed: 3003, text: "a guitarist playing on a small stage in a dim bar, people in the foreground" },
+ ];
+
+ /** Stable pick of the third subject per look (a hash of the look id). */
+ function thirdPrompt(id) {
+ let h = 0;
+ for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
+ const rest = SOUL_PROMPTS.slice(2);
+ return rest[h % rest.length];
+ }
+
+ const HEADER = "Generated by scripts/eval/gen-cases.mjs from the research files; edit the generator, not this file.";
+
+ function soulSuite() {
+ const looks = soulLooks();
+ if (looks.length !== 139) throw new Error(`expected 139 Soul looks, found ${looks.length}`);
+ const missing = looks.filter((l) => !l.recipe).map((l) => l.id);
+ if (missing.length) throw new Error(`no research recipe for ${missing.join(", ")}`);
+ const qwen = { open: ["oss-qwen-image"], demo: ["oss-qwen-image"], cloud: ["fuobe-soul-hd"] };
+ return {
+ $schema: "./case.schema.json",
+ suite: "soul",
+ title: "Fuobe Soul · the 139 looks",
+ description: `${HEADER} Each look on three subjects with pinned seeds: the research recipe (look template, triggers, LoRAs at their listed strengths) against the same words without LoRAs, half-strength LoRAs, the bare prompt, and the shipped Original (fuobe-soul; Soul HD for a lettering look). The Original's grade and overlay are applied in the browser after generation, so its scores are of the raw picture. Style references (your own or licensed images, never Higgsfield previews) go in local/references/soul/<look>/.`,
+ original: ["fuobe-soul", "fuobe-soul-hd"],
+ kind: "image",
+ recipe: "soul-look",
+ targets: {
+ // Today's bases; the Soul recipe (§4) is applied by the harness. fal's Z-Image LoRA endpoint takes the LoRAs.
+ open: { models: ["oss-z-image-turbo"], extra: { steps: 8, shift: 3 } },
+ cloud: { models: ["z-image-turbo-cloud"], extra: { num_inference_steps: 8, enable_prompt_expansion: false, output_format: "png" } },
+ demo: { models: ["oss-z-image-turbo"] },
+ },
+ defaults: {
+ seeds: [1001],
+ params: { aspectRatio: "3:4" },
+ metrics: ["clip", "aesthetic", "style"],
+ variant: "recipe",
+ timeoutSeconds: 900,
+ },
+ variants: {
+ recipe: { description: "The research recipe: look template, LoRA triggers and LoRAs at the listed strengths" },
+ "prompt-only": { description: "The look's words without LoRAs: does each LoRA earn its slot?", loras: "none" },
+ "half-strength": { description: "The recipe with every LoRA at half strength (over-cooking check)", loraScale: 0.5 },
+ plain: { description: "The base model with the subject prompt alone", template: false, loras: "none" },
+ original: {
+ description: "The shipped Original on the server (O2's fuobe-soul, on the engine the run names): the look's Fuobe id (v1-general) goes in presetId and the server applies its own recipe",
+ models: { open: ["fuobe-soul"], cloud: ["fuobe-soul"], demo: ["fuobe-soul"] },
+ lookParam: "presetId",
+ },
+ },
+ cases: looks.map((l) => ({
+ id: `soul/${l.slug}`,
+ title: `Soul ${l.family === "v1" ? "v1" : "2.0"} · ${l.name}`,
+ look: l.id,
+ // A lettering look is made for Qwen-Image 2512: the Original that runs it is Fuobe Soul HD.
+ ...(l.recipe.base === "qwen-image-2512" && { models: qwen, variantModels: { original: { open: ["fuobe-soul-hd"], cloud: ["fuobe-soul-hd"], demo: ["fuobe-soul-hd"] } }, extra: { steps: 20 } }),
+ prompts: [SOUL_PROMPTS[0], SOUL_PROMPTS[1], thirdPrompt(l.id)],
+ references: `local/references/soul/${l.slug}`,
+ tags: [l.family, slug(l.category) || "all", slug(l.recipe.coverage), ...(l.recipe.trainOwn ? ["train-own"] : []), ...(l.recipe.needsCivitaiToken ? ["civitai"] : [])],
+ })),
+ };
+ }
+
+ /** Today's Z-Image Turbo bases with Soul's sampler settings (§4); the Originals apply their own. */
+ const SOUL_TARGETS = {
+ open: { models: ["oss-z-image-turbo"], extra: { steps: 8, shift: 3 } },
+ cloud: { models: ["z-image-turbo-cloud"], extra: { num_inference_steps: 8, enable_prompt_expansion: false, output_format: "png" } },
+ demo: { models: ["oss-z-image-turbo"] },
+ };
+ const everywhere = (id) => ({ open: [id], cloud: [id], demo: [id] });
+
+ /** A research library LoRA (loraLibrary[key]) as a case's LoRA, at the recipe's strength. */
+ function libraryLora(key, strength) {
+ const l = research().recipes.loraLibrary.find((x) => x.key === key);
+ if (!l) throw new Error(`no LoRA ${key} in the research's loraLibrary`);
+ return {
+ name: l.name,
+ file: l.file,
+ // Pinned to the research's commit, as the app's LoRA library downloads it.
+ url: pinnedLora(l).url,
+ ...(l.hostedUrl && { hostedUrl: l.hostedUrl }),
+ strength,
+ ...(l.trigger && { trigger: l.trigger }),
+ base: l.base,
+ licence: l.licence,
+ commercial: l.commercial !== false,
+ hostedOk: l.hostedOk !== false,
+ download: l.download ?? (/civitai\.com/.test(l.url ?? "") ? "civitai-token" : "direct"),
+ };
+ }
+
+ /** Cinematic scenes for Soul Cinema (Fuobe's own words), one pinned seed each. */
+ const CINEMA_SCENES = [
+ { id: "diner", seed: 4101, text: "a waitress refills a coffee cup for a tired trucker in an empty roadside diner at night" },
+ { id: "platform", seed: 4102, text: "a woman in a trench coat waits alone on a rain-soaked train platform, wide shot" },
+ { id: "rooftop", seed: 4103, text: "two detectives argue on a rooftop above a city at blue hour" },
+ { id: "desert", seed: 4104, text: "a lone rider crosses a desert ridge at sunset, long shadow, wide landscape" },
+ { id: "kitchen", seed: 4105, text: "a family eats breakfast in a sunlit farmhouse kitchen, the youngest spills milk" },
+ { id: "corridor", seed: 4106, text: "a nurse walks down a hospital corridor at 3am under flickering lights" },
+ ];
+
+ function soulCinemaSuite() {
+ const { soul } = research().recipes;
+ const cinema = soul.soulCinema;
+ const tail = soul.template.tails[cinema.tail];
+ if (!tail) throw new Error(`no "${cinema.tail}" tail in the research's soul.template.tails`);
+ const loras = cinema.loras.map((l) => libraryLora(l.key, l.strength));
+ return {
+ $schema: "./case.schema.json",
+ suite: "soul-cinema",
+ title: "Fuobe Soul Cinema · one film look",
+ description: `${HEADER} Soul Cinema has one fixed look (research soul.soulCinema): ${loras.map((l) => `${l.name} at ${l.strength}`).join(" + ")}, the "${cinema.tail}" tail, a ${cinema.grades.join(" or ")} grade after generation (in the browser, so the Original's scores are of the raw picture) and ${cinema.defaultAspect} by default. The recipe on today's base against its words alone, the bare prompt, and the shipped Original (fuobe-soul-cinema). A civitai LoRA without a mirrored copy is left out on the cloud (the runner says so). Style references (your own or licensed film stills) go in local/references/soul-cinema/.`,
+ original: "fuobe-soul-cinema",
+ kind: "image",
+ targets: SOUL_TARGETS,
+ defaults: {
+ seeds: [1001],
+ params: { aspectRatio: cinema.defaultAspect },
+ metrics: ["clip", "aesthetic", "style"],
+ variant: "recipe",
+ timeoutSeconds: 900,
+ },
+ variants: {
+ recipe: { description: "Soul Cinema's research recipe on today's base: its LoRAs with their triggers, then the cine tail", loras, words: tail },
+ "prompt-only": { description: "The cine tail without the LoRAs: do they earn their slots?", loras: "none", words: tail },
+ plain: { description: "The base model with the scene alone", template: false, loras: "none" },
+ original: { description: "The shipped Original (fuobe-soul-cinema): the server adds its LoRAs, tail and grade", models: everywhere("fuobe-soul-cinema"), loras: "none" },
+ },
+ cases: CINEMA_SCENES.map((p) => ({
+ id: `soul-cinema/${p.id}`,
+ title: `Soul Cinema · ${p.id}`,
+ prompts: [p],
+ references: "local/references/soul-cinema",
+ tags: ["cinema"],
+ })),
+ };
+ }
+
+ /** Fuobe's own palettes for Soul HEX (never Higgsfield's), five colours each, dark to light. */
+ const HEX_PALETTES = [
+ { id: "teal-dusk", name: "Teal dusk", colors: ["#0B1D2A", "#1F4E5F", "#2A9D8F", "#E9C46A", "#F4A261"] },
+ { id: "candy-pop", name: "Candy pop", colors: ["#118AB2", "#06D6A0", "#FF5DA2", "#FFD166", "#FDF6EC"] },
+ { id: "green-editorial", name: "Green editorial", colors: ["#1B1B1B", "#0F3D2E", "#2E7D4F", "#A7C957", "#F2E8CF"] },
+ ];
+
+ const HEX_PROMPTS = [
+ { id: "portrait", seed: 5101, text: "a woman in a knitted sweater sits by a window with a cup of tea, half-length portrait" },
+ { id: "still-life", seed: 5102, text: "a still life of fruit, a ceramic jug and a folded cloth on a wooden table" },
+ ];
+
+ /** The palette sentence the composer's Color signature adds (src/lib/catalog/palettes.ts palettePrompt, no background). */
+ export const hexWords = (colors) => `Color palette: use only these colors, in roughly this balance: ${colors.map((c) => c.toUpperCase()).join(", ")}.`;
+
+ function soulHexSuite() {
+ return {
+ $schema: "./case.schema.json",
+ suite: "soul-hex",
+ title: "Fuobe Soul HEX · palettes",
+ description: `${HEADER} A palette on Fuobe Soul, as the composer's Color signature sends it: the colours in the prompt on both engines, and on the open engine the palette lock after it (oss-palette-image, POST /api/palettes/lock: on by default for Fuobe Soul). Against the same words on today's base, Z-Image Turbo · Palette (the open engine's palette model before the Originals) and Fuobe Soul without the palette. The palette metric scores how closely each picture keeps to the colours (mean ΔE to the nearest one, and how many of them it uses). The palettes are Fuobe's own.`,
+ original: "fuobe-soul",
+ kind: "image",
+ targets: SOUL_TARGETS,
+ defaults: {
+ seeds: [1001],
+ params: { aspectRatio: "3:4" },
+ metrics: ["palette", "clip", "aesthetic"],
+ variant: "words",
+ timeoutSeconds: 900,
+ },
+ variants: {
+ words: { description: "Fuobe Soul (its General look) with the palette in the prompt: the cloud's Soul HEX", models: everywhere("fuobe-soul") },
+ lock: {
+ description: "Fuobe Soul with the palette in the prompt, then the palette lock (strength 0.8): the open engine's Soul HEX",
+ models: { open: ["fuobe-soul"], demo: ["fuobe-soul"] },
+ engines: ["demo", "open"],
+ submit: { route: "/api/palettes/lock", body: { request: "{{request}}", colors: "{{request.params.palette}}" }, estimate: false },
+ },
+ base: { description: "The palette in the prompt on today's base, no look" },
+ "palette-model": {
+ description: "Z-Image Turbo · Palette: the provider writes the colours into the prompt and locks them in one graph (open engine)",
+ models: { open: ["oss-zimage-palette"], demo: ["oss-zimage-palette"] },
+ engines: ["demo", "open"],
+ template: false,
+ },
+ plain: { description: "Fuobe Soul without the palette's words (the control)", models: everywhere("fuobe-soul"), template: false },
+ },
+ cases: HEX_PALETTES.map((p) => ({
+ id: `soul-hex/${p.id}`,
+ title: `Soul HEX · ${p.name}`,
+ words: hexWords(p.colors),
+ params: { palette: p.colors },
+ prompts: HEX_PROMPTS,
+ tags: ["hex"],
+ })),
+ };
+ }
+
+ /** Preset names the catalog has (motions.ts specs), so every DoP case's presetId exists. */
+ function catalogPresetNames() {
+ const src = fs.readFileSync(path.join(REPO_DIR, "src/lib/catalog/motions.ts"), "utf8");
+ const effectsAt = src.indexOf("const EFFECT_SPECS");
+ const names = (text) => new Set([...text.matchAll(/\{\s*name: "([^"]+)"/g)].map((m) => m[1]));
+ const endFrames = new Set([...src.matchAll(/\{\s*name: "([^"]+)"[^\n]*endFrame: true/g)].map((m) => m[1]));
+ return { motion: names(src.slice(0, effectsAt)), effect: names(src.slice(effectsAt)), endFrames };
+ }
+
+ /** Research statuses with a LoRA to A/B (§7.2); prompt-only presets have nothing to compare yet. */
+ const LORA_STATUSES = new Set(["add-lora", "alias", "replace", "weak-candidate", "local-only", "relight-route"]);
+
+ /**
+ * The models a DoP preset runs on when it isn't Fuobe DoP's Wan (src/lib/catalog/dop.ts): an LTX-2.3 LoRA runs on Fuobe
+ * DoP · LTX on both engines; an LTX-2.5 LoRA on the open LTX-2.5 graph only. In the cloud the harness measures Fuobe
+ * DoP on its words, against the partner model the catalog keeps there until a run promotes it.
+ */
+ function dopModels(m) {
+ const bases = (m.loras ?? []).map((l) => l.base ?? "");
+ if (m.status === "relight-route" || bases.some((b) => /^wan2\.[12]/.test(b))) return undefined;
+ if (bases.some((b) => /^ltx-2(\.3-|-19b)/.test(b))) return everywhere("fuobe-dop-ltx");
+ if (bases.some((b) => /^ltx-2\.5/.test(b))) return { open: ["oss-ltx25"], demo: ["oss-ltx25"], cloud: ["fuobe-dop"] };
+ return undefined;
+ }
+
+ function dopSuite() {
+ const catalog = catalogPresetNames();
+ const cases = [];
+ const later = [];
+ for (const m of research().recipes.motionsEffects) {
+ if (!LORA_STATUSES.has(m.status) || !(m.loras ?? []).length) continue;
+ for (const name of m.presets) {
+ if (!catalog[m.kind].has(name)) {
+ later.push(name);
+ continue;
+ }
+ const transition = catalog.endFrames.has(name);
+ const models = dopModels(m);
+ cases.push({
+ id: `dop/${m.kind}-${slug(name)}`,
+ title: `DoP ${m.kind} · ${name}`,
+ motion: name,
+ presetId: `${m.kind}-${slug(name)}`,
+ ...(transition && { op: "flf2v" }),
+ ...(models && { models }),
+ inputs: { images: ["local/dop/start.png"], ...(transition && { endImage: "local/dop/end.png" }) },
+ demoInputs: { images: ["fixtures/start-frame.png"], ...(transition && { endImage: "fixtures/end-frame.png" }) },
+ ...(m.status === "local-only" && { engines: ["demo", "open"], note: "local-only LoRAs (civitai RentCivit): open engine only" }),
+ tags: [m.kind, m.status, ...(transition ? ["transition"] : [])],
+ });
+ }
+ }
+ // The camera moves the map v2 gives a pose or a camera LoRA (§7.3): Wan 2.2 Fun Camera on the GPU, LTX-2.3's camera
+ // LoRA (or LTX-2.5's move) in the cloud. Prompt-only (preset strength 0) turns the camera LoRA off.
+ const ids = new Set(cases.map((c) => c.id));
+ for (const m of research().recipes.motionsEffects) {
+ for (const name of m.presets) {
+ const lora = m.cameraLora?.[name];
+ const move = m.cameraMotion?.[name];
+ const pose = m.funCamera?.[name];
+ const id = `dop/${m.kind}-${slug(name)}`;
+ if ((!lora && !move && !pose) || ids.has(id) || !catalog[m.kind].has(name)) continue;
+ ids.add(id);
+ const transition = catalog.endFrames.has(name);
+ const cloud = move ? "ltx-2-5-fast" : lora ? "fuobe-dop-ltx" : "fuobe-dop";
+ cases.push({
+ id,
+ title: `DoP ${m.kind} · ${name} (camera)`,
+ motion: name,
+ presetId: `${m.kind}-${slug(name)}`,
+ ...(transition && { op: "flf2v" }),
+ ...(cloud !== "fuobe-dop" && { models: { open: ["fuobe-dop"], demo: ["fuobe-dop"], cloud: [cloud] } }),
+ inputs: { images: ["local/dop/start.png"], ...(transition && { endImage: "local/dop/end.png" }) },
+ demoInputs: { images: ["fixtures/start-frame.png"], ...(transition && { endImage: "fixtures/end-frame.png" }) },
+ ...(move && { params: { duration: 6 } }),
+ tags: [m.kind, m.status, "camera", ...(pose && !transition ? ["fun-camera"] : []), ...(lora ? ["camera-lora"] : []), ...(transition ? ["transition"] : [])],
+ note: [pose && !transition ? `GPU: Wan 2.2 Fun Camera "${pose}"` : "", lora ? `cloud: LTX-2.3 camera_lora ${lora}` : "", move ? `cloud: LTX-2.5 camera_motion ${move}` : ""].filter(Boolean).join(" · "),
+ });
+ }
+ }
+ return {
+ suite: {
+ $schema: "./case.schema.json",
+ suite: "dop",
+ title: "Fuobe DoP · camera motions and effects with LoRAs",
+ description: `${HEADER} Every motion and effect the research gives a LoRA (§7.2), on your start frame (local/dop/start.png, plus local/dop/end.png for transitions; a photo of a person on a bridge matches the prompt), on the Original that runs it: Fuobe DoP (Wan 2.2 on your GPU, fal's Wan 2.2 LoRA endpoint in the cloud), Fuobe DoP · LTX for the LTX-2.3 LoRAs, the open LTX-2.5 graph for the LTX-2.5 ones. Variants: the catalog preset as it ships (the map v2), its prompt without LoRAs (preset strength 0), the research's LoRAs at their listed strengths sent by the harness (the same request as the catalog's until the strengths are tuned), and the preset's words on a partner model (Kling 2.5 Turbo). Not in the catalog yet: ${later.length ? later.join(", ") : "none"}.`,
+ original: ["fuobe-dop", "fuobe-dop-ltx"],
+ kind: "video",
+ recipe: "motion",
+ targets: {
+ open: { models: ["fuobe-dop"], params: { duration: 5 } },
+ cloud: { models: ["fuobe-dop"], params: { duration: 5 } },
+ demo: { models: ["fuobe-dop"], params: { duration: 5 } },
+ },
+ defaults: {
+ seeds: [1001, 2002],
+ prompts: [{ id: "bridge", text: "a woman in a red coat on a city bridge at golden hour" }],
+ metrics: ["temporal", "clip"],
+ variant: "catalog",
+ candidate: "research",
+ timeoutSeconds: 2700,
+ },
+ variants: {
+ catalog: { description: "The catalog preset as it ships on Fuobe DoP (prompt template + the LoRA map v2)" },
+ "prompt-only": { description: "The preset's prompt without LoRAs (preset strength 0)", presetStrength: 0 },
+ research: { description: "The research's LoRA map v2 at the listed strengths on the preset's prompt", presetStrength: 0, loras: "recipe" },
+ partner: { description: "The preset's words on a partner model (Kling 2.5 Turbo), for reference", models: { cloud: ["kling-2-5-turbo"] }, engines: ["cloud"] },
+ },
+ cases,
+ },
+ later,
+ };
+ }
+
+ /** Fuobe's own Mix pairs (a move and an effect, research §7.5): the second preset's LoRAs stack on the first's model. */
+ const MIX_PAIRS = [
+ ["motion-overhead", "effect-building-explosion"],
+ ["motion-handheld", "effect-glitch"],
+ ["motion-robo-arm", "effect-money-rain"],
+ ["motion-dolly-in", "effect-hero-flight"],
+ // A camera LoRA in the cloud (LTX-2.3) with a Wan effect: the effect joins as words there.
+ ["motion-jib-up", "effect-freezing"],
+ ];
+
+ function dopMixSuite() {
+ const catalog = catalogPresetNames();
+ const name = (id) => [...catalog.motion, ...catalog.effect].find((n) => id.endsWith(`-${slug(n)}`) && (id.startsWith("motion-") ? catalog.motion.has(n) : catalog.effect.has(n)));
+ const cases = MIX_PAIRS.map(([first, second]) => {
+ const [a, b] = [name(first), name(second)];
+ if (!a || !b) throw new Error(`Mix pair ${first} + ${second}: not in the catalog`);
+ return {
+ id: `dop-mix/${slug(a)}--${slug(b)}`,
+ title: `Mix · ${a} + ${b}`,
+ presetId: first,
+ mix: { presetId: second, strength: 0.6 },
+ ...(first === "motion-jib-up" && { models: { open: ["fuobe-dop"], demo: ["fuobe-dop"], cloud: ["fuobe-dop-ltx"] } }),
+ inputs: { images: ["local/dop/start.png"] },
+ demoInputs: { images: ["fixtures/start-frame.png"] },
+ tags: ["mix"],
+ };
+ });
+ return {
+ $schema: "./case.schema.json",
+ suite: "dop-mix",
+ title: "Fuobe DoP · Mix (a move and an effect on one run)",
+ description: `${HEADER} Fuobe DoP's Mix on both engines: the second preset's LoRAs stack on the first's model, each scaled by its strength (0.6 here), and its words join the prompt. A LoRA for another base (a Wan effect on an LTX-2.3 camera move) joins as words only. Variants: the Mix, and the first preset alone.`,
+ original: ["fuobe-dop", "fuobe-dop-ltx"],
+ kind: "video",
+ targets: {
+ open: { models: ["fuobe-dop"], params: { duration: 5 } },
+ cloud: { models: ["fuobe-dop"], params: { duration: 5 } },
+ demo: { models: ["fuobe-dop"], params: { duration: 5 } },
+ },
+ defaults: {
+ seeds: [1001, 2002],
+ prompts: [{ id: "bridge", text: "a woman in a red coat on a city bridge at golden hour" }],
+ metrics: ["temporal", "clip"],
+ variant: "first",
+ candidate: "mix",
+ timeoutSeconds: 2700,
+ },
+ variants: {
+ mix: { description: "Both presets: the first at full strength, the second's LoRAs at 0.6" },
+ first: { description: "The first preset alone (no Mix)", mix: false },
+ },
+ cases,
+ };
+ }
+
+ const write = (name, data, check) => {
+ const file = path.join(CASES_DIR, name);
+ const text = `${JSON.stringify(data, null, 2)}\n`;
+ if (check) {
- const now = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
++ // A Windows checkout may have CRLF line endings: the same content.
++ const now = fs.existsSync(file) ? fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n") : "";
+ if (now !== text) throw new Error(`${path.relative(REPO_DIR, file)} is out of date: run node scripts/eval/gen-cases.mjs`);
+ return;
+ }
+ fs.writeFileSync(file, text);
+ console.log(`Wrote ${path.relative(REPO_DIR, file)}`);
+ };
+
+ export function generated() {
+ const dop = dopSuite();
+ return { "soul.json": soulSuite(), "soul-cinema.json": soulCinemaSuite(), "soul-hex.json": soulHexSuite(), "dop.json": dop.suite, "dop-mix.json": dopMixSuite(), "case.schema.json": schemaJson(), later: dop.later };
+ }
+
-if (import.meta.url === `file://${process.argv[1]}`) {
++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const check = process.argv.includes("--check");
+ const out = generated();
+ for (const name of ["soul.json", "soul-cinema.json", "soul-hex.json", "dop.json", "dop-mix.json", "case.schema.json"]) write(name, out[name], check);
+ console.log(`soul: ${out["soul.json"].cases.length} looks · dop: ${out["dop.json"].cases.length} presets · dop-mix: ${out["dop-mix.json"].cases.length} pairs${out.later.length ? ` (${out.later.length} research names not in the catalog yet)` : ""}`);
+ }
diff --cc scripts/eval/lib/covers.mjs
index 00000000,1da404b2..71dfd50a
mode 000000,100644..100644
--- a/scripts/eval/lib/covers.mjs
+++ b/scripts/eval/lib/covers.mjs
@@@ -1,0 -1,160 +1,355 @@@
+ // Real preset covers from measured runs (O8: "the renders become the preview media"). For each case of a
+ // run, the best render of the variant that earned it (the promoted candidate, or a variant you name, such
+ // as `catalog`: what ships today) is encoded small into public/previews/<suite>/ and listed in
+ // src/lib/preset-previews.generated.ts, which the gallery cards read instead of their procedural preview.
+ // Only Fuobe's own renders become covers: demo media never does, nor a render whose LoRAs aren't
+ // commercial. A person reviews the media and the generated file before committing them.
+ import { spawnSync } from "node:child_process";
+ import fs from "node:fs";
+ import path from "node:path";
+ import { promote } from "./compare.mjs";
+ import { METRIC_INFO } from "./metric-info.mjs";
+ import { REPO_DIR, safeName } from "./paths.mjs";
+ import { jobScores, loadRun } from "./report.mjs";
+
+ export const COVERS_DIR = path.join(REPO_DIR, "public", "previews");
+ export const MANIFEST_FILE = path.join(REPO_DIR, "src", "lib", "preset-previews.generated.ts");
+
-/** Longest side of a cover still, and of a cover clip (px); a clip's first seconds. */
++/** Longest side of a cover still, and of a cover clip (px); a clip's first seconds, at CLIP_FPS. */
+ const STILL_PX = 768;
+ const CLIP_PX = 512;
+ const CLIP_SECONDS = 4;
++const CLIP_FPS = 24;
++/** Frames at a clip's end crossfaded into its first ones: the cards play clips with `loop`, and this hides the jump. */
++const LOOP_FADE = 6;
+
+ const HEADER = `/**
+ * Real preset covers: renders from measured runs of the evaluation harness (scripts/eval, pnpm eval:covers),
+ * keyed by preset id (a DoP motion or effect: "effect-thunder-god") or Soul look id ("v1-general"). The gallery
+ * cards show them instead of the procedural preview. Generated by pnpm eval:covers: run it again rather than editing.
+ */
+ export interface PresetPreviewMedia {
+ /** A still (the clip's first frame for motions and effects), under /previews. */
+ poster: string;
+ /** A short muted clip, for motions and effects. */
+ video?: string;
+ /** Where it came from: the run, its engine, the model and variant that made it. */
+ run: string;
+ engine: string;
+ model: string;
+ variant: string;
+ }
+
+ export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = `;
+
-/** The manifest's entries as they stand (the JSON literal after the header). */
++/**
++ * The manifest's entries as they stand (the JSON literal after the header); none when there is no file yet. A
++ * file that can't be read as a manifest throws: writing over it would drop every other run's entries.
++ */
+ export function readManifest(file = MANIFEST_FILE) {
++ let text;
++ try {
++ text = fs.readFileSync(file, "utf8");
++ } catch (e) {
++ if (e?.code === "ENOENT") return {};
++ throw e;
++ }
+ try {
- const text = fs.readFileSync(file, "utf8");
+ const at = text.indexOf("export const PRESET_PREVIEWS");
- const json = text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, "");
- return JSON.parse(json);
- } catch {
- return {};
++ if (at < 0) throw new Error("no PRESET_PREVIEWS");
++ const entries = JSON.parse(text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, ""));
++ if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new Error("not an object");
++ return entries;
++ } catch (e) {
++ throw new Error(`${file} isn't a covers manifest pnpm eval:covers can read (${e.message}): fix or restore it before making covers`);
+ }
+ }
+
+ export function writeManifest(entries, file = MANIFEST_FILE) {
+ const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, `${HEADER}${JSON.stringify(sorted, null, 2)};\n`);
+ }
+
+ /** The preset a case's cover belongs to: a DoP preset id, a Soul look's Fuobe id, else the case id. */
+ function coverKey(row) {
+ if (row.recipe?.kind === "soul-look" && row.recipe.look?.slug) return row.recipe.look.slug;
+ return row.request?.presetId ?? row.caseId;
+ }
+
+ const mainOutput = (row) => (row.outputs ?? []).find((o) => (o.kind === "image" || o.kind === "video") && !["mask", "first-frame", "depth"].includes(o.role));
+
+ /** The best succeeded job of a case and variant on `metric` (the first one when nothing is scored). */
+ function bestJob(rows, metricsDoc, metric) {
+ const better = METRIC_INFO[metric]?.better === "lower" ? (a, b) => a < b : (a, b) => a > b;
+ let best = null;
+ let score = null;
+ for (const r of rows) {
+ if (!mainOutput(r)) continue;
+ const s = metric ? jobScores(r, metricsDoc)[metric] : undefined;
+ if (!best || (typeof s === "number" && (score == null || better(s, score)))) {
+ best = r;
+ score = typeof s === "number" ? s : score;
+ }
+ }
+ return best;
+ }
+
-/** ffmpeg, or why there's none. */
-function run(args) {
- const r = spawnSync(process.env.FUOBE_FFMPEG ?? "ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { encoding: "utf8" });
- if (r.error) throw new Error("eval:covers needs ffmpeg to make small covers (install it, or set FUOBE_FFMPEG)");
- if (r.status !== 0) throw new Error(`ffmpeg failed: ${(r.stderr || "").trim().split("\n").at(-1)}`);
++/** ffmpeg, or why there's none. `input` goes to its stdin; its stdout comes back (a Buffer). */
++function run(args, input) {
++ const r = spawnSync(process.env.FUOBE_FFMPEG ?? "ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { input, maxBuffer: 1 << 30 });
++ if (r.error?.code === "ENOENT") throw new Error("eval:covers needs ffmpeg to make small covers (install it, or set FUOBE_FFMPEG)");
++ if (r.error) throw r.error;
++ if (r.status !== 0) throw new Error(`ffmpeg failed: ${String(r.stderr ?? "").trim().split("\n").at(-1)}`);
++ return r.stdout;
++}
++
++/** A y4m stream (ffmpeg's yuv4mpegpipe, 4:2:0) as its header line and each frame's bytes. */
++function readY4m(buf) {
++ const nl = buf.indexOf(0x0a);
++ const header = buf.subarray(0, Math.max(nl, 0)).toString("latin1");
++ const w = Number(/ W(\d+)/.exec(header)?.[1]);
++ const h = Number(/ H(\d+)/.exec(header)?.[1]);
++ if (!header.startsWith("YUV4MPEG2") || !w || !h) throw new Error("ffmpeg didn't decode the clip");
++ const size = w * h + 2 * Math.ceil(w / 2) * Math.ceil(h / 2);
++ const frames = [];
++ for (let at = nl + 1; at < buf.length; ) {
++ // Each frame: "FRAME" (and any parameters) up to a newline, then its planes.
++ const start = buf.indexOf(0x0a, at) + 1;
++ if (start <= 0 || start + size > buf.length) break;
++ frames.push(buf.subarray(start, start + size));
++ at = start + size;
++ }
++ return { header, frames, luma: w * h };
++}
++
++/** How far apart two frames are: the mean difference of their luma (every 4th sample). */
++function lumaGap(a, b, luma) {
++ let sum = 0;
++ let n = 0;
++ for (let i = 0; i < luma; i += 4, n++) sum += Math.abs(a[i] - b[i]);
++ return n ? sum / n : 0;
++}
++
++/**
++ * Whether a clip loops already: going from its last frame back to its first is no bigger a step than most
++ * of its own (an orbit that ends where it starts). Such a clip is cut, not crossfaded.
++ * @param {Buffer[]} frames
++ * @param {number} luma bytes of luma at the start of each frame
++ */
++export function loopsAlready(frames, luma) {
++ if (frames.length < 3) return false;
++ const steps = frames.slice(1).map((f, i) => lumaGap(frames[i], f, luma)).sort((a, b) => a - b);
++ return lumaGap(frames.at(-1), frames[0], luma) <= Math.max(steps[Math.floor((steps.length - 1) * 0.9)], 1);
++}
++
++/**
++ * A loop without a seam: the first `fade` frames are dropped from the start and blended into the last `fade`
++ * instead, so the clip's end runs into its new beginning (the cards play clip covers with `loop`).
++ * @param {Buffer[]} frames
++ * @param {number} fade
++ */
++export function seamless(frames, fade) {
++ const n = frames.length;
++ if (!fade || n < 2 * fade) return frames;
++ const out = frames.slice(fade);
++ for (let k = 0; k < fade; k++) {
++ const a = (k + 1) / (fade + 1);
++ const tail = frames[n - fade + k];
++ const head = frames[k];
++ const blend = Buffer.allocUnsafe(tail.length);
++ for (let i = 0; i < blend.length; i++) blend[i] = Math.round(tail[i] * (1 - a) + head[i] * a);
++ out[n - 2 * fade + k] = blend;
++ }
++ return out;
+ }
+
-/** A still at most STILL_PX wide/tall, or a clip's first seconds at most CLIP_PX with its first frame as the poster. */
++/**
++ * A still at most STILL_PX wide/tall (a 4:2:0 JPEG), or a clip's first seconds at most CLIP_PX that loops
++ * without a jump (crossfaded, unless it loops already), with its first frame as the poster.
++ */
+ function encode(src, kind, destBase) {
+ const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;
+ if (kind === "video") {
- run(["-i", src, "-t", String(CLIP_SECONDS), "-an", "-vf", `${fit(CLIP_PX)},fps=24`, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-movflags", "+faststart", `${destBase}.mp4`]);
- run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-q:v", "4", `${destBase}.jpg`]);
++ // Decoded at CLIP_FPS: CLIP_SECONDS, plus the frames the crossfade takes back from the start.
++ const y4m = run(["-i", src, "-t", String(CLIP_SECONDS + LOOP_FADE / CLIP_FPS), "-an", "-sn", "-dn", "-vf", `${fit(CLIP_PX)},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);
++ const { header, frames, luma } = readY4m(y4m);
++ if (frames.length < 2) throw new Error(`${src} has no frames to make a clip of`);
++ const cut = frames.slice(0, CLIP_SECONDS * CLIP_FPS);
++ const looped = loopsAlready(cut, luma) ? cut : seamless(frames, Math.min(LOOP_FADE, Math.floor(frames.length / 4)));
++ const stream = Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...looped.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);
++ run(["-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-map_metadata", "-1", "-movflags", "+faststart", `${destBase}.mp4`], stream);
++ run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`]);
+ return { poster: `${destBase}.jpg`, video: `${destBase}.mp4` };
+ }
- run(["-i", src, "-vf", fit(STILL_PX), "-frames:v", "1", "-q:v", "3", `${destBase}.jpg`]);
++ run(["-i", src, "-vf", `${fit(STILL_PX)},format=yuvj420p`, "-frames:v", "1", "-q:v", "3", `${destBase}.jpg`]);
+ return { poster: `${destBase}.jpg` };
+ }
+
+ /**
+ * Make covers from a run.
+ * @param {string} dir the run folder
+ * @param {{ variant?: string, dryRun?: boolean, publicDir?: string, manifest?: string }} [opts]
+ * variant: take this variant's renders for every case (default: the promoted candidate's, promoted cases only)
+ * publicDir: the site's public folder (covers go to <publicDir>/previews/<suite>/); manifest: the generated file
+ */
+ export function makeCovers(dir, opts = {}) {
+ const L = loadRun(dir);
+ if (L.run.engine === "demo") throw new Error("A demo run's media is the demo provider's, not Fuobe's: it never becomes a cover");
+ const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
+ const outDir = path.join(publicDir, "previews", safeName(L.run.suite));
+ // The promote verdicts (as the run's scores and ratings stand now) say which cases earned a cover, and on which metric to pick the render.
+ const doc = promote(dir);
+ const byCase = new Map(doc.results.map((r) => [r.caseId, r]));
+ const variant = opts.variant ?? doc.candidate;
+ const picked = [];
+ const skipped = [];
+ for (const caseId of [...new Set(L.rows.map((r) => r.caseId))]) {
+ const verdict = byCase.get(caseId);
+ if (!opts.variant && verdict?.verdict !== "promote") {
+ skipped.push({ caseId, why: `${verdict?.verdict ?? "no verdict"}: only a promoted recipe's render becomes a cover (--variant <name> takes another variant's, such as what ships today)` });
+ continue;
+ }
+ const rows = L.rows.filter((r) => r.caseId === caseId && r.variant === variant && r.status === "succeeded");
+ // Licence: information on the cover (`licence`); with --commercial-only a render whose LoRAs can't be sold is left out.
+ const lib = new Map((rows[0]?.recipe?.loras ?? []).map((l) => [l.file, l]));
+ const blocked = (rows[0]?.recipe?.applied ?? []).filter((l) => lib.get(l.file)?.commercial === false);
+ const licence = rows[0]?.recipe?.commercialOk === false || blocked.length ? `non-commercial LoRA${blocked.length > 1 ? "s" : ""} ${blocked.map((l) => l.file).join(", ")}`.trim() : undefined;
+ if (licence && opts.commercialOnly) {
+ skipped.push({ caseId, why: `${licence} (--commercial-only)` });
+ continue;
+ }
+ const metric = verdict?.mainMetric ?? null;
+ const best = bestJob(rows, L.metrics, metric);
+ if (!best) {
+ skipped.push({ caseId, why: `no ${variant} render` });
+ continue;
+ }
+ picked.push({ caseId, key: coverKey(best), row: best, metric, score: metric ? (jobScores(best, L.metrics)[metric] ?? null) : null, ...(licence && { licence }) });
+ }
+ const result = { runId: L.run.runId, engine: L.run.engine, variant, covers: [], skipped, manifest: opts.manifest ?? MANIFEST_FILE, folder: outDir };
+ if (opts.dryRun) {
+ result.covers = picked.map((p) => ({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score, ...(p.licence && { licence: p.licence }) }));
+ return result;
+ }
+ if (picked.length) fs.mkdirSync(outDir, { recursive: true });
+ const manifest = readManifest(opts.manifest);
+ for (const p of picked) {
+ const out = mainOutput(p.row);
+ const files = encode(path.join(dir, out.file), out.kind, path.join(outDir, safeName(p.key)));
+ const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;
++ const before = manifest[p.key];
+ manifest[p.key] = { poster: web(files.poster), ...(files.video && { video: web(files.video) }), run: L.run.runId, engine: L.run.engine, model: p.row.model?.id ?? "", variant };
++ // A measured cover replaces any other (a masters cover in /previews/presets): its files go with it.
++ dropReplaced(before, manifest, publicDir);
+ result.covers.push({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score, ...(p.licence && { licence: p.licence }), ...manifest[p.key] });
+ }
+ if (picked.length) writeManifest(manifest, opts.manifest);
+ return result;
+ }
++
++/** Remove a replaced entry's files that no entry names any more (its cover now lives in another folder). */
++function dropReplaced(old, manifest, publicDir) {
++ if (!old) return;
++ const named = new Set(Object.values(manifest).flatMap((e) => [e.poster, e.video].filter(Boolean)));
++ for (const url of [old.poster, old.video]) {
++ const parts = typeof url === "string" ? url.split("/").filter(Boolean) : [];
++ if (named.has(url) || parts[0] !== "previews" || parts.includes("..")) continue;
++ fs.rmSync(path.join(publicDir, ...parts), { force: true });
++ }
++}
++
++/** What a masters folder holds for a preset: its rendered clip, else its start still. */
++const MASTER_CLIP = "clip.mp4";
++const MASTER_STILL = "start.png";
++
++const newer = (file, than) => {
++ try {
++ return fs.statSync(file).mtimeMs >= fs.statSync(than).mtimeMs;
++ } catch {
++ return false;
++ }
++};
++
++function readMeta(folder) {
++ try {
++ const meta = JSON.parse(fs.readFileSync(path.join(folder, "meta.json"), "utf8"));
++ return meta && typeof meta === "object" ? meta : {};
++ } catch {
++ return {};
++ }
++}
++
++/**
++ * Covers from rendered masters that aren't a run's (pnpm eval:covers --from-masters <dir>), such as the
++ * preview renders made in ComfyUI for the gallery. One folder per preset id: its clip.mp4 becomes a clip
++ * cover (the first 4 s, the first frame as its poster), else its start.png a still cover; the encoding is
++ * makeCovers'. Each cover records the provenance it's given: the run, engine, model (`videoModel` for a
++ * clip) and variant; a folder's meta.json can name its own `model` and `variant`. The manifest is merged:
++ * entries other runs wrote stay, and only the ids found here are replaced. An id whose cover another run
++ * made elsewhere (a measured eval cover, another suite's) is skipped, so a later masters run never undoes it;
++ * `replace` takes it over (and removes its files). Run it again as masters land: a cover newer than its master
++ * is kept (force makes it again), and a preset whose cover was a clip and is now a still loses the old clip.
++ * @param {string} dir the masters folder
++ * @param {{ run: string, engine?: string, model?: string, videoModel?: string, variant?: string, suite?: string,
++ * only?: string[], force?: boolean, replace?: boolean, dryRun?: boolean, publicDir?: string, manifest?: string }} opts
++ */
++export function coversFromMasters(dir, opts) {
++ if (!opts?.run) throw new Error("Covers from masters need a run name for their provenance (--run)");
++ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`No masters folder at ${dir}`);
++ const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
++ const outDir = path.join(publicDir, "previews", safeName(opts.suite ?? "presets"));
++ const engine = opts.engine ?? "comfyui";
++ const variant = opts.variant ?? "";
++ const only = opts.only?.length ? new Set(opts.only) : null;
++ const picked = [];
++ const skipped = [];
++ for (const id of fs.readdirSync(dir).sort()) {
++ const folder = path.join(dir, id);
++ if ((only && !only.has(id)) || !fs.statSync(folder).isDirectory()) continue;
++ if (safeName(id) !== id || id.startsWith("_")) {
++ skipped.push({ id, why: "not a preset id (folders are named by preset id, such as effect-set-on-fire)" });
++ continue;
++ }
++ const clip = path.join(folder, MASTER_CLIP);
++ const kind = fs.existsSync(clip) ? "video" : fs.existsSync(path.join(folder, MASTER_STILL)) ? "image" : null;
++ if (!kind) {
++ skipped.push({ id, why: `no ${MASTER_CLIP} or ${MASTER_STILL} yet` });
++ continue;
++ }
++ const meta = readMeta(folder);
++ const model = typeof meta.model === "string" ? meta.model : ((kind === "video" ? opts.videoModel : opts.model) ?? "");
++ picked.push({ id, kind, src: kind === "video" ? clip : path.join(folder, MASTER_STILL), model, variant: typeof meta.variant === "string" ? meta.variant : variant });
++ }
++ for (const id of only ?? []) if (!picked.some((p) => p.id === id) && !skipped.some((s) => s.id === id)) skipped.push({ id, why: "no folder" });
++ const result = { run: opts.run, engine, covers: [], skipped, manifest: opts.manifest ?? MANIFEST_FILE, folder: outDir };
++ const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;
++ const manifest = readManifest(opts.manifest);
++ // Another run's cover outside this suite's folder (a measured one, say) stays unless replace says otherwise.
++ const ours = picked.filter((p) => {
++ const cur = manifest[p.id];
++ if (!cur || opts.replace || String(cur.poster).startsWith(`${web(outDir)}/`)) return true;
++ skipped.push({ id: p.id, why: `its cover is ${cur.run || "another run"}'s (${cur.poster}): --replace takes it over` });
++ return false;
++ });
++ if (ours.length && !opts.dryRun) fs.mkdirSync(outDir, { recursive: true });
++ for (const p of ours) {
++ const base = path.join(outDir, safeName(p.id));
++ const files = { poster: `${base}.jpg`, ...(p.kind === "video" && { video: `${base}.mp4` }) };
++ // Up to date: the cover is newer than its master (and a clip's poster than the clip it's taken from).
++ const kept = !opts.force && (p.kind === "video" ? newer(files.video, p.src) && newer(files.poster, files.video) : newer(files.poster, p.src) && !fs.existsSync(`${base}.mp4`));
++ const entry = { poster: web(files.poster), ...(files.video && { video: web(files.video) }), run: opts.run, engine, model: p.model, variant: p.variant };
++ if (!opts.dryRun) {
++ if (!kept) {
++ encode(p.src, p.kind, base);
++ if (p.kind === "image") fs.rmSync(`${base}.mp4`, { force: true });
++ }
++ const before = manifest[p.id];
++ manifest[p.id] = entry;
++ dropReplaced(before, manifest, publicDir);
++ }
++ result.covers.push({ key: p.id, kind: p.kind, from: p.src, ...(kept && { kept: true }), ...entry });
++ }
++ if (ours.length && !opts.dryRun) writeManifest(manifest, opts.manifest);
++ return result;
++}
diff --cc src/app/(studio)/page.tsx
index 50d3ceb8,2904cc9b..baed863c
--- a/src/app/(studio)/page.tsx
+++ b/src/app/(studio)/page.tsx
@@@ -1,7 -1,7 +1,8 @@@
import { HomeView } from "@/components/home-view";
import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
-import { homeEffects, toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
+import { homeEffects } from "@/lib/preset-cards";
+ import { startQuotes, starterPriceLine } from "@/lib/starter-prices";
const HOME_MOTIONS = ["motion-crash-zoom-in", "motion-360-orbit", "motion-bullet-time", "motion-fpv-drone", "motion-dolly-zoom-in", "motion-snorricam"];
diff --cc src/app/(studio)/settings/about/page.tsx
index 00000000,d8284f9f..39550e03
mode 000000,100644..100644
--- a/src/app/(studio)/settings/about/page.tsx
+++ b/src/app/(studio)/settings/about/page.tsx
@@@ -1,0 -1,135 +1,136 @@@
+ import fs from "node:fs/promises";
+ import path from "node:path";
+ import { ArrowLeft, ExternalLink } from "lucide-react";
+ import type { Metadata } from "next";
+ import Link from "next/link";
+ import { LicencesView } from "@/components/licences-view";
+ import { PageHeader, PageShell } from "@/components/page-shell";
+ import { MODELS } from "@/lib/catalog";
+ import type { Manifest } from "@/lib/comfy";
+ import { FUOBE_REPO } from "@/lib/connections";
+ import { buildLicenceList } from "@/lib/licences";
+
+ export const metadata: Metadata = { title: "About & licences" };
+
+ /** A JSON file's contents, or null when it's missing or unreadable. */
+ async function readJson<T>(text: Promise<string>): Promise<T | null> {
+ try {
+ return JSON.parse(await text) as T;
+ } catch {
+ return null;
+ }
+ }
+
+ /** Fuobe's version and every open model's licence, from package.json, the ComfyUI manifest and the catalog. */
+ async function readAbout() {
+ "use cache";
+ // Each path is spelled out, so the build traces these two files, not the whole project.
+ const [pkg, manifest] = await Promise.all([
+ readJson<{ version?: string }>(fs.readFile(path.join(process.cwd(), "package.json"), "utf8")),
+ readJson<Manifest & { comfyuiVersion?: string }>(fs.readFile(path.join(process.cwd(), "workflows", "comfyui", "manifest.json"), "utf8")),
+ ]);
+ const workflows = manifest?.workflows ?? [];
+ return {
+ version: pkg?.version ?? "dev",
+ comfyui: manifest?.comfyuiVersion,
+ builtAt: manifest?.generatedAt?.slice(0, 10),
+ workflowCount: workflows.length,
+ list: buildLicenceList(
+ MODELS.map((m) => ({ id: m.id, name: m.name, vendor: m.vendor, kind: m.kind, hidden: m.hidden, routes: m.routes.map((r) => ({ provider: r.provider, endpoint: r.endpoint })) })),
+ workflows.map((w) => ({ id: w.id, title: w.title, capability: w.capability, license: w.license })),
+ ),
+ };
+ }
+
+ function Fact({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="min-w-0">
+ <dt className="text-[12px] text-muted-foreground">{label}</dt>
+ <dd className="mt-0.5 text-[14px] [overflow-wrap:anywhere]">{children}</dd>
+ </div>
+ );
+ }
+
+ export default async function Page() {
+ const about = await readAbout();
+ const { list } = about;
+ return (
+ <PageShell>
+ <Link href="/settings" className="mb-3 inline-flex items-center gap-1.5 rounded-md text-[13px] text-muted-foreground hover:text-foreground">
+ <ArrowLeft className="size-3.5" /> Settings
+ </Link>
+ <PageHeader
+ title="About & licences"
+ description="Fuobe's code is open source. The open models it runs on your GPU each have their own licence: most allow commercial use, some don't, and a few leave out some countries. Paid models follow the terms of the provider you connect."
+ />
+
+ <dl className="grid grid-cols-1 gap-4 rounded-2xl border p-5 sm:grid-cols-2 lg:grid-cols-4">
+ <Fact label="Fuobe">Version {about.version}</Fact>
+ <Fact label="Source code">
+ <a href={FUOBE_REPO} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text underline underline-offset-2">
+ GitHub <ExternalLink className="size-3" aria-hidden />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+ </Fact>
+ <Fact label="Open engine">
+ {about.workflowCount} ComfyUI workflows{about.comfyui ? `, built for ComfyUI ${about.comfyui}` : ""}
+ {about.builtAt ? <span className="text-muted-foreground"> · {about.builtAt}</span> : null}
+ </Fact>
+ <Fact label="Paid models">fal.ai and Replicate with your key: their terms and prices apply</Fact>
+ </dl>
+
+ {list.notices.length > 0 && (
+ <section aria-labelledby="notices" className="mt-8">
+ <h2 id="notices" className="text-[15px] font-semibold">
+ Notices
+ </h2>
+ <p className="mt-1 text-[13px] text-muted-foreground">Some licences ask the app that runs their model to say so.</p>
+ <ul className="mt-3 grid gap-2 sm:grid-cols-2">
+ {list.notices.map((n) => (
+ <li key={n.text} className="rounded-xl bg-muted/60 px-4 py-3">
+ <p className="text-[15px] font-semibold">{n.text}</p>
+ <p className="mt-0.5 text-[12px] text-muted-foreground [overflow-wrap:anywhere]">For {n.models.join(", ")}</p>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <section aria-labelledby="licences" className="mt-10">
+ <h2 id="licences" className="font-heading text-[24px] leading-tight">
+ Open model licences
+ </h2>
+ <p className="mt-1 mb-5 max-w-2xl text-[13px] text-muted-foreground">
+ {list.counts.all} models and workflows: {list.counts.clear} allow commercial use, {list.counts.conditions} with conditions (revenue limits or use rules), {list.counts["non-commercial"]}{" "}
+ non-commercial and {list.counts.territory} not available everywhere. Read the licence itself before you sell what you make; this list is a guide, not legal advice. Which of them this
+ install offers is yours to decide in{" "}
+ <Link href="/settings/models" className="text-brand-text underline underline-offset-2">
+ Models &amp; licences
+ </Link>
+ .
+ </p>
+ <LicencesView list={list} />
+ </section>
+
+ <section aria-labelledby="elsewhere" className="mt-10 border-t pt-6">
+ <h2 id="elsewhere" className="text-[15px] font-semibold">
+ Elsewhere
+ </h2>
+ <ul className="mt-2 list-disc space-y-1 pl-5 text-[13px] text-muted-foreground">
+ <li>
- Models you pull into Ollama for Assist and prompt enhancement carry their own licences: <code className="font-mono text-[12px]">ollama show &lt;model&gt; --license</code>.
++ Models you run in Ollama, LM Studio or Unsloth Studio for Assist and prompt enhancement carry their own licences: see each model&apos;s card, or{" "}
++ <code className="font-mono text-[12px]">ollama show &lt;model&gt; --license</code> in Ollama.
+ </li>
+ <li>The optional TRIBE v2 worker for the Virality page isn&apos;t bundled; its weights are CC BY-NC 4.0 (non-commercial).</li>
+ <li>
+ Each workflow&apos;s models, sizes and download links are on the{" "}
+ <Link href="/workflows" className="text-brand-text underline underline-offset-2">
+ Workflows
+ </Link>{" "}
+ page.
+ </li>
+ </ul>
+ </section>
+ </PageShell>
+ );
+ }
diff --cc src/app/api/status/route.ts
index 34eb19ee,5e51ffb4..71cdcf2b
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@@ -1,15 -1,15 +1,18 @@@
import { connection } from "next/server";
+import { aiHelper, localSummary } from "@/server/llm";
import { PROVIDERS } from "@/server/providers";
- import { probeComfy } from "@/server/providers/comfyui";
+ import { comfyRam, probeComfy } from "@/server/providers/comfyui";
+import { llmBackends } from "@/server/providers/llm";
- import { getSetting } from "@/server/settings";
+ import { nothingConnected, type EngineModeName } from "@/lib/connections";
+ import { getSetting, setSetting } from "@/server/settings";
+ import { offeredSummary } from "@/server/model-access";
- /** Which providers are usable right now — drives badges and the demo-mode banner. */
+ /** Which providers are usable right now — drives badges, the demo-mode notice and Home's first-run guide. */
export async function GET() {
await connection();
- const comfy = await probeComfy(true);
+ // Both asked first, so the llm provider's label and routing read fresh answers without waiting.
+ const [comfy, local] = await Promise.all([probeComfy(true), localSummary()]);
+ const ram = comfy ? comfyRam() : undefined;
const providers = Object.fromEntries(
Object.values(PROVIDERS).map((p) => [
p.id,
@@@ -19,9 -29,10 +32,12 @@@
return Response.json({
providers,
demoMode: getSetting("demoMode"),
- engineMode: getSetting("engineMode"),
+ engineMode,
cloudProvider: getSetting("cloudProvider"),
+ onboarded,
+ // Settings → Models & licences: the models switched off, so pickers leave them out (absent while everything is on).
+ ...(access && { access }),
+ // The text LLM: the AI helper setting, whether Claude takes text steps, and the local server (no keys).
+ llm: { helper: aiHelper(), claude: llmBackends({ endpoint: "auto" })[0] === "claude", ...local },
});
}
diff --cc src/components/assist/connectors-settings.tsx
index 00000000,bf61cb6d..8c942552
mode 000000,100644..100644
--- a/src/components/assist/connectors-settings.tsx
+++ b/src/components/assist/connectors-settings.tsx
@@@ -1,0 -1,269 +1,269 @@@
+ "use client";
+
+ import { AlertTriangle, Info, KeyRound, Loader2, Pencil, Plug, Plus, Trash2 } from "lucide-react";
+ import { useId, useState } from "react";
+ import { toast } from "sonner";
+ import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ } from "@/components/ui/alert-dialog";
+ import { Button } from "@/components/ui/button";
+ import { Checkbox } from "@/components/ui/checkbox";
+ import { Input } from "@/components/ui/input";
+ import { Label } from "@/components/ui/label";
+ import { Skeleton } from "@/components/ui/skeleton";
+ import { Switch } from "@/components/ui/switch";
+ import { checkConnectorUrl, MAX_CONNECTOR_NAME, MAX_CONNECTORS, parseToolList, type ConnectorView } from "@/lib/assist-connectors";
+ import { useConnectorActions, useConnectors } from "./hooks";
+
+ /**
+ * Settings → Assist connectors: remote MCP servers whose tools Claude may use in Assist chats. The
+ * browser sends a URL and token once and only ever gets them back masked; nothing here connects to
+ * the URL (Claude does, from Anthropic's servers).
+ */
+ export function ConnectorSettings({ claudeReady }: { claudeReady: boolean }) {
+ const list = useConnectors();
+ const [adding, setAdding] = useState(false);
+ const [editing, setEditing] = useState<string | null>(null);
+ const items = list.data ?? [];
+ const full = items.length >= MAX_CONNECTORS;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-start gap-2.5 rounded-xl bg-muted px-3 py-2.5 text-[13px] text-muted-foreground">
+ <Info className="mt-0.5 size-4 shrink-0" />
+ <div className="space-y-1.5">
+ <p>
+ Connectors work in Claude chats (Smart, or Manual with a Claude model){claudeReady ? "" : " — add an Anthropic API key above first"}. Claude reaches them from Anthropic&apos;s servers, so each needs a
- public https address. Chats on Ollama or the offline planner can&apos;t use them. Tool calls cost Claude tokens; the chat lists each connector tool Claude used.
++ public https address. Chats on a local model (Ollama, LM Studio or Unsloth Studio) or the offline planner can&apos;t use them. Tool calls cost Claude tokens; the chat lists each connector tool Claude used.
+ </p>
+ <p>
+ <span className="font-medium text-foreground">Connector tools run without asking.</span> Claude calls them inside its reply, so approval cards (Ask first) and auto-run&apos;s cost cap don&apos;t
+ cover them; Claude is told to check with you in chat before changing anything. Limit a connector to the tools you trust with <span className="font-medium text-foreground">Allowed tools</span>.
+ Scheduled tasks use connectors only when the task says so.
+ </p>
+ </div>
+ </div>
+ {list.isLoading ? (
+ <Skeleton className="h-16 rounded-xl" />
+ ) : items.length ? (
+ <ul className="divide-y rounded-xl border sm:w-[40rem] sm:max-w-full">
+ {items.map((c) =>
+ editing === c.id ? (
+ <li key={c.id} className="p-3">
+ <ConnectorForm connector={c} onDone={() => setEditing(null)} />
+ </li>
+ ) : (
+ <Row key={c.id} c={c} onEdit={() => setEditing(c.id)} />
+ ),
+ )}
+ </ul>
+ ) : (
+ !adding && <p className="text-[13px] text-muted-foreground">No connectors yet. Add one with its MCP server URL — the app&apos;s docs list it (often ending in /mcp).</p>
+ )}
+ {adding ? (
+ <div className="rounded-xl border p-3 sm:w-[40rem] sm:max-w-full">
+ <ConnectorForm onDone={() => setAdding(false)} />
+ </div>
+ ) : (
+ <Button size="sm" variant="secondary" disabled={full} onClick={() => setAdding(true)}>
+ <Plus /> {full ? `Up to ${MAX_CONNECTORS} connectors` : "Add a connector"}
+ </Button>
+ )}
+ </div>
+ );
+ }
+
+ function Row({ c, onEdit }: { c: ConnectorView; onEdit: () => void }) {
+ const actions = useConnectorActions();
+ const [deleting, setDeleting] = useState(false);
+ return (
+ <li className="flex items-start gap-3 px-3 py-2.5">
+ <Plug className="mt-1 size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-medium">{c.name}</p>
+ <p className="truncate font-mono text-[11px] text-muted-foreground" title={c.url}>
+ {c.url}
+ </p>
+ <p className="text-[11px] text-muted-foreground">
+ <KeyRound className="mr-1 inline size-3 align-[-2px]" aria-hidden />
+ {c.hasToken ? <span className="font-mono">{c.token}</span> : "No token"} · Claude sees it as <span className="font-mono">{c.slug}</span>
+ </p>
+ <p className="text-[11px] break-words text-muted-foreground">
+ {c.tools ? (
+ <>
+ Only: <span className="font-mono">{c.tools.join(", ")}</span>
+ </>
+ ) : (
+ "Every tool it lists"
+ )}
+ </p>
+ {c.warning && (
+ <p className="mt-1 flex items-start gap-1 text-[11px] text-amber-800 dark:text-amber-300">
+ <AlertTriangle className="mt-px size-3 shrink-0" aria-hidden /> {c.warning}
+ </p>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-0.5">
+ <Switch
+ checked={c.enabled}
+ onCheckedChange={(on) => void actions.update(c.id, { enabled: on }).catch((e) => toast.error((e as Error).message))}
+ aria-label={c.enabled ? `Switch off ${c.name}` : `Switch on ${c.name}`}
+ />
+ <Button size="icon" variant="ghost" className="size-8 text-muted-foreground" aria-label={`Edit ${c.name}`} onClick={onEdit}>
+ <Pencil className="size-3.5" />
+ </Button>
+ <Button size="icon" variant="ghost" className="size-8 text-muted-foreground hover:text-destructive" aria-label={`Delete ${c.name}`} onClick={() => setDeleting(true)}>
+ <Trash2 className="size-3.5" />
+ </Button>
+ </div>
+ <AlertDialog open={deleting} onOpenChange={setDeleting}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {c.name}?</AlertDialogTitle>
+ <AlertDialogDescription>Claude stops using its tools, and its token is deleted from this server. Chats that used it keep what it returned.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={() => void actions.remove(c.id).catch((e) => toast.error((e as Error).message))}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </li>
+ );
+ }
+
+ /** Add a connector, or edit one: an empty token field keeps the saved token. */
+ function ConnectorForm({ connector, onDone }: { connector?: ConnectorView; onDone: () => void }) {
+ const actions = useConnectorActions();
+ const ids = { name: useId(), url: useId(), token: useId(), hint: useId(), tools: useId(), toolsHint: useId() };
+ const [name, setName] = useState(connector?.name ?? "");
+ const [url, setUrl] = useState("");
+ const [token, setToken] = useState("");
+ const [tools, setTools] = useState(connector?.tools?.join(", ") ?? "");
+ const [dropToken, setDropToken] = useState(false);
+ const [busy, setBusy] = useState(false);
+ // The server enforces the http rule (it knows FUOBE_ALLOW_PRIVATE_URLS); here only the shape is checked.
+ const check = url.trim() ? checkConnectorUrl(url, true) : null;
+ const urlError = check && "error" in check ? check.error : null;
+ const toolList = parseToolList(tools);
+ const toolsError = "error" in toolList ? toolList.error : null;
+ const canSave = !!name.trim() && !toolsError && (connector ? !urlError : !!url.trim() && !urlError);
+
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!canSave) return;
+ setBusy(true);
+ try {
+ if (connector) {
+ await actions.update(connector.id, {
+ name: name.trim(),
+ ...(url.trim() && { url: url.trim() }),
+ ...(dropToken ? { token: "" } : token.trim() ? { token: token.trim() } : {}),
+ tools: tools.trim() || null,
+ });
+ toast.success("Connector saved", { duration: 1500 });
+ } else {
+ await actions.create({ name: name.trim(), url: url.trim(), ...(token.trim() && { token: token.trim() }), ...(tools.trim() && { tools: tools.trim() }) });
+ toast.success(`${name.trim()} connected`, { description: "Claude chats can use its tools from the next message.", duration: 2500 });
+ }
+ onDone();
+ } catch (err) {
+ toast.error((err as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <form onSubmit={save} className="space-y-3" aria-label={connector ? `Edit ${connector.name}` : "Add a connector"}>
+ <div className="grid grid-cols-[minmax(0,1fr)] gap-3 sm:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)]">
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.name} className="text-[13px]">
+ Name
+ </Label>
+ <Input id={ids.name} value={name} onChange={(e) => setName(e.target.value)} maxLength={MAX_CONNECTOR_NAME} placeholder="e.g. Notion" autoFocus />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.url} className="text-[13px]">
+ MCP server URL
+ </Label>
+ <Input
+ id={ids.url}
+ type="url"
+ inputMode="url"
+ autoComplete="off"
+ spellCheck={false}
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ placeholder={connector ? `Unchanged: ${connector.url}` : "https://mcp.example.com/mcp"}
+ aria-invalid={!!urlError}
+ aria-describedby={urlError ? ids.hint : undefined}
+ />
+ {urlError && (
+ <p id={ids.hint} className="text-[12px] text-destructive">
+ {urlError}
+ </p>
+ )}
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.token} className="text-[13px]">
+ Token <span className="font-normal text-muted-foreground">(optional)</span>
+ </Label>
+ <Input
+ id={ids.token}
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ value={token}
+ disabled={dropToken}
+ onChange={(e) => setToken(e.target.value)}
+ placeholder={connector?.hasToken ? `Saved (${connector.token}) — type a new one to replace it` : "The server's API key or access token"}
+ />
+ <p className="text-[12px] text-muted-foreground">Sent as an Authorization: Bearer header, by Anthropic, to this server only. Stored on this server like your other keys and never shown again.</p>
+ {connector?.hasToken && (
+ <label className="inline-flex items-center gap-2 text-[12px]">
+ <Checkbox checked={dropToken} onCheckedChange={(v) => setDropToken(v === true)} /> Remove the saved token
+ </label>
+ )}
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.tools} className="text-[13px]">
+ Allowed tools <span className="font-normal text-muted-foreground">(optional)</span>
+ </Label>
+ <Input
+ id={ids.tools}
+ autoComplete="off"
+ spellCheck={false}
+ value={tools}
+ onChange={(e) => setTools(e.target.value)}
+ placeholder="Every tool — or only these, e.g. search_pages, get_page"
+ aria-invalid={!!toolsError}
+ aria-describedby={ids.toolsHint}
+ className="font-mono text-[13px]"
+ />
+ <p id={ids.toolsHint} className={toolsError ? "text-[12px] text-destructive" : "text-[12px] text-muted-foreground"}>
+ {toolsError ??
+ "Tool names as the server lists them (its docs, or the chat's “Notion · search_pages” lines), separated by commas. Leave it empty to allow every tool; prefer read-only ones for scheduled tasks."}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button type="submit" size="sm" disabled={busy || !canSave}>
+ {busy && <Loader2 className="animate-spin" />} {connector ? "Save" : "Add connector"}
+ </Button>
+ <Button type="button" size="sm" variant="ghost" onClick={onDone}>
+ Cancel
+ </Button>
+ </div>
+ </form>
+ );
+ }
diff --cc src/components/command-palette.tsx
index 00000000,3788bbdf..9c6e07a8
mode 000000,100644..100644
--- a/src/components/command-palette.tsx
+++ b/src/components/command-palette.tsx
@@@ -1,0 -1,312 +1,312 @@@
+ "use client";
+
+ import { useQuery } from "@tanstack/react-query";
+ import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";
+ import { useRouter } from "next/navigation";
+ import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+ import { NAV } from "@/components/nav-items";
+ import { MediaThumb } from "@/components/studio/result-media";
+ import { CommandDialog, CommandEmpty, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";
+ import { Kbd } from "@/components/ui/kbd";
+ import { Command as CommandPrimitive } from "cmdk";
+ import { useEngineMode, useGenerations, useModelAccess } from "@/lib/api";
+ import type { Generation } from "@/lib/catalog/types";
+ import { indexEntries, KIND_LABELS, rankPalette, type PaletteEntry, type PaletteIndex, type PaletteKind } from "@/lib/command-search";
+ import { useModKey } from "@/lib/keys";
+ import { userTitle } from "@/lib/library";
+ import { cn } from "@/lib/utils";
+
+ // The viewer is only needed once a recent creation is opened from the palette.
+ const Viewer = lazy(() => import("@/components/studio/viewer").then((m) => ({ default: m.Viewer })));
+
+ interface PaletteState {
+ open: boolean;
+ setOpen: (open: boolean | ((open: boolean) => boolean)) => void;
+ }
+
+ const PaletteContext = createContext<PaletteState>({ open: false, setOpen: () => {} });
+
+ /** Opens and closes the ⌘K palette from anywhere in the app frame (the sidebar's Search row, the phone header, ⌘K). */
+ export const useCommandPalette = () => useContext(PaletteContext);
+
+ /** What had focus when the palette opened: it gets focus back when the palette closes without going anywhere. */
+ const returnFocus: { current: Element | null } = { current: null };
+
+ export function CommandPaletteProvider({ children }: { children: React.ReactNode }) {
+ const [open, setOpenState] = useState(false);
+ const openRef = useRef(false);
+ const setOpen = useCallback((v: boolean | ((open: boolean) => boolean)) => {
+ const next = typeof v === "function" ? v(openRef.current) : v;
+ if (next && !openRef.current) returnFocus.current = document.activeElement;
+ openRef.current = next;
+ setOpenState(next);
+ }, []);
+ const value = useMemo(() => ({ open, setOpen }), [open, setOpen]);
+ return <PaletteContext.Provider value={value}>{children}</PaletteContext.Provider>;
+ }
+
+ /** Settings sections the palette jumps to (ids in settings-form.tsx). */
+ const SETTINGS: { id: string; label: string; icon: LucideIcon; keywords: string; href?: string }[] = [
+ { id: "cloud", label: "API keys", icon: KeyRound, keywords: "fal replicate paid cloud connect" },
+ { id: "comfyui", label: "ComfyUI server", icon: Server, keywords: "open source gpu url connect local" },
+ { id: "engine", label: "Engine mode", icon: Cpu, keywords: "open source cloud both" },
+ { id: "loras", label: "LoRAs", icon: Layers, keywords: "lora folder civitai key looks motions effects download licence" },
+ {
+ id: "models",
+ label: "Models & licences",
+ icon: Scale,
+ keywords: "licence license commercial non-commercial switch off turn on admin providers node packs allow block",
+ href: "/settings/models",
+ },
- { id: "text-ai", label: "Prompt enhancement", icon: Sparkles, keywords: "claude ollama enhancer llm" },
++ { id: "text-ai", label: "AI helper", icon: Sparkles, keywords: "claude ollama lm studio unsloth local llm model enhancer prompt enhancement context" },
+ { id: "assist-connectors", label: "Assist connectors", icon: Plug, keywords: "mcp connector claude tools notion linear slack server token" },
+ { id: "notifications", label: "Notifications", icon: Bell, keywords: "browser done alerts" },
+ { id: "security", label: "Password and API tokens", icon: ShieldCheck, keywords: "security sign in mcp token" },
+ { id: "demo", label: "Demo mode", icon: Settings2, keywords: "placeholder free try" },
+ ];
+
+ const PAGES: (PaletteEntry & { icon: LucideIcon })[] = NAV.flatMap((g) =>
+ g.items.map((i) => ({ key: `page:${i.href}`, kind: "page" as const, label: i.label, hint: g.label, href: i.href, keywords: i.keywords, icon: i.icon })),
+ );
+ const SETTING_ENTRIES: (PaletteEntry & { icon: LucideIcon })[] = SETTINGS.map((s) => ({
+ key: `setting:${s.id}`,
+ kind: "setting",
+ label: s.label,
+ hint: "Settings",
+ href: s.href ?? `/settings#${s.id}`,
+ keywords: s.keywords,
+ icon: s.icon,
+ }));
+ // Icons as elements made once (a component picked during render would remount on every keystroke).
+ const iconEl = (Icon: LucideIcon) => <Icon className="text-muted-foreground" />;
+ const ICONS = new Map<string, React.ReactNode>([...PAGES, ...SETTING_ENTRIES].map((e) => [e.key, iconEl(e.icon)]));
+ const KIND_ICONS: Partial<Record<PaletteKind, React.ReactNode>> = { app: iconEl(LayoutGrid), motion: iconEl(Film), effect: iconEl(Wand2), model: iconEl(Clapperboard) };
+
+ function useDebounced<T>(value: T, ms: number): T {
+ const [v, setV] = useState(value);
+ useEffect(() => {
+ const t = setTimeout(() => setV(value), ms);
+ return () => clearTimeout(t);
+ }, [value, ms]);
+ return v;
+ }
+
+ // The hints are marked as shortcuts so CommandItem drops its check mark, which would share the row's free space with them.
+ function Row({ entry, onPick }: { entry: PaletteEntry; onPick: (e: PaletteEntry) => void }) {
+ return (
+ <CommandItem value={entry.key} onSelect={() => onPick(entry)} className="h-9 gap-2.5 text-[14px]">
+ {ICONS.get(entry.key) ?? KIND_ICONS[entry.kind] ?? KIND_ICONS.app}
+ <span className="min-w-0 truncate">{entry.label}</span>
+ {entry.hint && <span data-slot="command-shortcut" className="ml-auto shrink-0 truncate pl-2 text-[12px] text-muted-foreground max-sm:max-w-[40%]">{entry.hint}</span>}
+ </CommandItem>
+ );
+ }
+
+ function RecentRow({ g, onOpen }: { g: Generation; onOpen: (g: Generation) => void }) {
+ const title = userTitle(g);
+ return (
+ <CommandItem value={`recent:${g.id}`} onSelect={() => onOpen(g)} className="h-11 gap-2.5 text-[14px]">
+ <span className="relative size-8 shrink-0 overflow-hidden rounded-md bg-muted">{g.outputs[0] && <MediaThumb output={g.outputs[0]} g={g} />}</span>
+ <span className="min-w-0 truncate">{title}</span>
+ <span data-slot="command-shortcut" className="ml-auto shrink-0 pl-2 text-[12px] text-muted-foreground">{g.modelName}</span>
+ </CommandItem>
+ );
+ }
+
+ function Hints() {
+ const mod = useModKey();
+ return (
+ <div className="flex items-center gap-3 border-t px-3 py-2 text-[12px] text-muted-foreground [@media(hover:none)]:hidden">
+ <span className="flex items-center gap-1">
+ <Kbd>↑</Kbd>
+ <Kbd>↓</Kbd> to move
+ </span>
+ <span className="flex items-center gap-1">
+ <Kbd>↵</Kbd> to open
+ </span>
+ <span className="flex items-center gap-1">
+ <Kbd>Esc</Kbd> to close
+ </span>
+ <span className="ml-auto flex items-center gap-1">
+ <Kbd>{mod}</Kbd>
+ <Kbd>K</Kbd>
+ </span>
+ </div>
+ );
+ }
+
+ /** What the palette lists and searches; mounted only while it's open. */
+ function PaletteBody({ onPick, onOpenRecent, onClose }: { onPick: (e: PaletteEntry) => void; onOpenRecent: (g: Generation) => void; onClose: () => void }) {
+ const [q, setQ] = useState("");
+ // Not deferred: ranking ~900 entries takes a millisecond, and Enter must act on the list for what was typed.
+ const query = q;
+ const dq = useDebounced(q.trim(), 200);
+ const mode = useEngineMode();
+ const access = useModelAccess();
+ // The apps, motions, effects and models load on first open (and stay for the session).
+ const index = useQuery({
+ queryKey: ["palette-index"],
+ queryFn: async () => (await fetch("/api/search-index")).json() as Promise<PaletteIndex>,
+ staleTime: Infinity,
+ });
+ const recent = useGenerations({ q: dq || undefined, limit: 5, statuses: ["succeeded"] }, { keepPrevious: true });
+ const entries = useMemo(() => [...PAGES, ...SETTING_ENTRIES, ...(index.data ? indexEntries(index.data, mode, access) : [])], [index.data, mode, access]);
+ const groups = useMemo(() => rankPalette(entries, query), [entries, query]);
+ const recentItems = (recent.data ?? []).filter((g) => g.outputs[0]);
+ const searching = !!query.trim();
+ // cmdk keeps no selection once the rows change (shouldFilter is off): every new query starts on its
+ // best match, so Enter opens it; arrows move from there.
+ const best = searching ? (groups[0]?.entries[0]?.key ?? (recentItems[0] ? `recent:${recentItems[0].id}` : "")) : "new";
+ const [moved, setMoved] = useState<{ query: string; value: string } | null>(null);
+ const selected = moved?.query === query ? moved.value : best;
+
+ return (
+ <CommandPrimitive shouldFilter={false} loop value={selected} onValueChange={(value) => setMoved({ query, value })} label="Search Fuobe" className="flex flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground">
+ <div className="flex items-center gap-2 border-b px-3">
+ <CommandPrimitive.Input
+ value={q}
+ onValueChange={setQ}
+ autoFocus
+ placeholder="Search pages, apps, motions, effects, models…"
+ aria-label="Search Fuobe"
+ className="h-12 min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-subtle-foreground"
+ />
+ {index.isLoading && searching && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" aria-label="Loading the catalog" />}
+ {/* Touch screens have no Esc (and the hint row is hidden there): a visible way out. */}
+ <button
+ type="button"
+ onClick={onClose}
+ className="-mr-1 hidden h-8 shrink-0 items-center rounded-md px-2 text-[14px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground [@media(hover:none)]:inline-flex"
+ >
+ Cancel
+ </button>
+ </div>
+ <CommandList className="max-h-[min(60vh,440px)] p-1.5">
+ {searching ? (
+ <>
+ <CommandEmpty className="py-10 text-center text-[13px] text-muted-foreground">
+ {index.isLoading ? "Looking through apps, motions and models…" : `Nothing matches “${query.trim()}”.`}
+ </CommandEmpty>
+ {groups.map((g) => (
+ <CommandGroup key={g.kind} heading={g.label}>
+ {g.entries.map((e) => (
+ <Row key={e.key} entry={e} onPick={onPick} />
+ ))}
+ </CommandGroup>
+ ))}
+ {recentItems.length > 0 && (
+ <CommandGroup heading={KIND_LABELS.recent}>
+ {recentItems.map((g) => (
+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />
+ ))}
+ </CommandGroup>
+ )}
+ </>
+ ) : (
+ <>
+ <CommandGroup>
+ {/* Enter on an empty query keeps what ⌘K always did: a new creation. */}
+ <CommandItem value="new" onSelect={() => onPick({ key: "new", kind: "page", label: "New creation", href: "/" })} className="h-9 gap-2.5 text-[14px]">
+ <Plus className="text-muted-foreground" />
+ New creation
+ <span data-slot="command-shortcut" className="ml-auto text-[12px] text-muted-foreground">Home</span>
+ </CommandItem>
+ </CommandGroup>
+ {recentItems.length > 0 && (
+ <CommandGroup heading={KIND_LABELS.recent}>
+ {recentItems.map((g) => (
+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />
+ ))}
+ </CommandGroup>
+ )}
+ <CommandGroup heading={KIND_LABELS.page}>
+ {PAGES.map((e) => (
+ <Row key={e.key} entry={e} onPick={onPick} />
+ ))}
+ </CommandGroup>
+ <CommandGroup heading={KIND_LABELS.setting}>
+ {SETTING_ENTRIES.map((e) => (
+ <Row key={e.key} entry={e} onPick={onPick} />
+ ))}
+ </CommandGroup>
+ </>
+ )}
+ </CommandList>
+ <Hints />
+ </CommandPrimitive>
+ );
+ }
+
+ /**
+ * The ⌘K / Ctrl+K palette: every page, settings section, app, camera motion, effect and model, and
+ * your recent creations, with a forgiving search (src/lib/command-search.ts). Rendered once, in the
+ * app frame.
+ */
+ export function CommandPalette() {
+ const { open, setOpen } = useCommandPalette();
+ const router = useRouter();
+ const [viewing, setViewing] = useState<Generation | null>(null);
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "k") {
+ e.preventDefault();
+ setOpen((o) => !o);
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [setOpen]);
+
+ // Set when the palette closes onto something else (a page, the viewer): focus stays with that.
+ const leaving = useRef(false);
+ const pick = useCallback(
+ (e: PaletteEntry) => {
+ leaving.current = true;
+ setOpen(false);
+ router.push(e.href);
+ },
+ [router, setOpen],
+ );
+ const openRecent = useCallback(
+ (g: Generation) => {
+ leaving.current = true;
+ setOpen(false);
+ setViewing(g);
+ },
+ [setOpen],
+ );
+ const close = useCallback(() => setOpen(false), [setOpen]);
+ // Dismissed (Esc, Cancel, a click outside, ⌘K again): focus goes back to where it was, the
+ // composer you were typing in or the Search row, not to the top of the page.
+ const restoreFocus = useCallback((e: Event) => {
+ e.preventDefault();
+ const el = returnFocus.current;
+ returnFocus.current = null;
+ if (leaving.current) {
+ leaving.current = false;
+ return;
+ }
+ if (el instanceof HTMLElement && el.isConnected) el.focus({ preventScroll: true });
+ }, []);
+
+ return (
+ <>
+ <CommandDialog
+ open={open}
+ onOpenChange={setOpen}
+ title="Search Fuobe"
+ description="Go to a page, an app, a camera motion, an effect, a model, a settings section or a recent creation."
+ className={cn("top-[8vh] gap-0 p-0 sm:top-[14vh] sm:max-w-xl")}
+ onCloseAutoFocus={restoreFocus}
+ >
+ <PaletteBody onPick={pick} onOpenRecent={openRecent} onClose={close} />
+ </CommandDialog>
+ {viewing && (
+ <Suspense fallback={null}>
+ <Viewer generation={viewing} index={0} onClose={() => setViewing(null)} />
+ </Suspense>
+ )}
+ </>
+ );
+ }
diff --cc src/components/connect-field.tsx
index 00000000,3e170c3b..ec3628bd
mode 000000,100644..100644
--- a/src/components/connect-field.tsx
+++ b/src/components/connect-field.tsx
@@@ -1,0 -1,198 +1,223 @@@
+ "use client";
+
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
+ import { CheckCircle2, CircleAlert, Loader2, TriangleAlert } from "lucide-react";
+ import { useId, useState } from "react";
+ import { toast } from "sonner";
+ import { Button } from "@/components/ui/button";
+ import { Input } from "@/components/ui/input";
+ import { Label } from "@/components/ui/label";
+ import { saveSettings, testConnection, type ConnectionTest } from "@/lib/api";
+ import { settingProblem, type TestProvider } from "@/lib/connections";
+ import { cn } from "@/lib/utils";
+
+ export interface PublicSetting {
+ name: string;
+ value: string;
+ secret: boolean;
+ fromEnv: boolean;
+ isSet: boolean;
+ }
+
+ /** Every setting as the browser may see it (secrets masked). `enabled: false` waits (Home's guide, until the status says it's wanted). */
+ export function useSettings(enabled = true) {
+ return useQuery({
+ queryKey: ["settings"],
+ queryFn: async () => ((await (await fetch("/api/settings")).json()) as { settings: PublicSetting[] }).settings,
+ enabled,
+ });
+ }
+
+ interface Result extends ConnectionTest {
+ /** The typed values that didn't connect and weren't saved ("Save anyway" saves them). */
+ unsaved?: Record<string, string>;
+ saved?: boolean;
+ }
+
+ /**
+ * A key or address field with one button that does what it says: "Save & test" tests the typed value
+ * first and saves it once it connects (a value that doesn't connect is offered "Save anyway"); with
- * nothing typed it tests the saved one. Used by Settings and by Home's first-run guide.
++ * nothing typed it tests the saved one. Used by Settings and by Home's first-run guide. `saveOnly` is for a
++ * value no server can test on its own (the local model's context): its button saves what was typed.
+ */
+ export function ConnectField({
+ name,
+ setting,
+ provider,
+ label,
+ hint,
+ placeholder,
+ id,
+ idleLabel = "Test",
+ onConnected,
++ options,
+ className,
++ saveOnly = false,
+ }: {
+ name: string;
+ setting?: PublicSetting;
+ provider: TestProvider;
+ label: string;
+ hint?: React.ReactNode;
+ placeholder?: string;
+ /** Anchor for links to this field (/settings#fal). */
+ id?: string;
+ /** The button's words when nothing new was typed. */
+ idleLabel?: string;
+ /** After a green test (the first-run guide closes itself). */
+ onConnected?: (r: ConnectionTest) => void;
++ /** Suggestions to pick from (the models a local LLM server lists); any value can still be typed. */
++ options?: string[];
+ className?: string;
++ /** Save the typed value without a test (nothing to connect to). */
++ saveOnly?: boolean;
+ }) {
+ const qc = useQueryClient();
+ const inputId = useId();
+ const [draft, setDraft] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<Result | null>(null);
+ const secret = !!setting?.secret;
+ const saved = secret ? "" : (setting?.value ?? "");
+ const typed = draft !== null && draft.trim() !== saved.trim() ? draft.trim() : null;
+ const shown = draft ?? saved;
+ const problem = typed ? settingProblem(name, typed) : null;
- const canTest = typed !== null || !!setting?.isSet || !!setting?.value;
++ const canTest = saveOnly ? typed !== null && !problem : typed !== null || !!setting?.isSet || !!setting?.value;
+
+ const refresh = () => {
+ void qc.invalidateQueries({ queryKey: ["settings"] });
+ void qc.invalidateQueries({ queryKey: ["status"] });
++ // Settings → AI helper lists what each local LLM server answers with its saved URL, model and key.
++ void qc.invalidateQueries({ queryKey: ["llm"] });
+ };
+
+ const run = async () => {
+ if (busy || !canTest) return;
+ setBusy(true);
+ try {
++ if (saveOnly) {
++ await saveSettings({ [name]: typed ?? "" });
++ setDraft(null);
++ setResult(null);
++ refresh();
++ toast.success(`${label} saved`);
++ return;
++ }
+ const values = typed !== null ? { [name]: typed } : undefined;
+ const res = await testConnection(provider, values, name);
+ if (res.ok) {
+ // Connected: keep it. The first-run guide goes once the status sees a connection the engine
+ // mode generates with (the server remembers that), not for Ollama or an unused provider.
+ if (values) await saveSettings(values);
+ setDraft(null);
+ refresh();
+ onConnected?.(res);
+ }
+ setResult({ ...res, saved: res.ok && !!values, unsaved: !res.ok ? values : undefined });
+ } catch (e) {
+ setResult({ ok: false, detail: (e as Error).message });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const saveAnyway = async (values: Record<string, string>) => {
+ try {
+ await saveSettings(values);
+ setDraft(null);
+ setResult((r) => r && { ...r, unsaved: undefined, saved: true });
+ refresh();
+ toast.success("Saved — it didn't connect yet");
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ const clear = async () => {
+ try {
+ await saveSettings({ [name]: "" });
+ setDraft(null);
+ setResult(null);
+ refresh();
+ toast.success(`${label} cleared`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ return (
+ <div id={id} className={cn("min-w-0 scroll-mt-28 space-y-1.5", className)}>
+ <Label htmlFor={inputId} className="text-[13px]">
+ {label}
+ </Label>
+ <div className="flex flex-wrap gap-2">
+ <Input
+ id={inputId}
+ aria-describedby={`${inputId}-hint ${inputId}-result`}
+ aria-invalid={!!problem || (result ? !result.ok : undefined)}
+ autoComplete="off"
+ spellCheck={false}
+ type={secret ? "password" : "text"}
+ value={shown}
+ placeholder={secret && setting?.isSet ? setting.value : placeholder}
++ list={options?.length ? `${inputId}-list` : undefined}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ setResult(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void run();
+ }
+ }}
+ className="min-w-0 flex-1 basis-56 font-mono text-[13px]"
+ />
++ {!!options?.length && (
++ <datalist id={`${inputId}-list`}>
++ {options.map((o) => (
++ <option key={o} value={o} />
++ ))}
++ </datalist>
++ )}
+ <div className="flex shrink-0 gap-2">
- <Button size="sm" className="h-9" disabled={busy || !canTest} onClick={() => void run()} aria-label={`${typed !== null ? "Save and test" : idleLabel} ${label}`}>
++ <Button size="sm" className="h-9" disabled={busy || !canTest} onClick={() => void run()} aria-label={`${saveOnly ? "Save" : typed !== null ? "Save and test" : idleLabel} ${label}`}>
+ {busy && <Loader2 className="animate-spin" />}
- {typed !== null ? "Save & test" : idleLabel}
++ {saveOnly ? "Save" : typed !== null ? "Save & test" : idleLabel}
+ </Button>
+ {setting?.isSet && !setting.fromEnv && secret && typed === null && (
+ <Button size="sm" variant="ghost" className="h-9" aria-label={`Clear ${label}`} onClick={() => void clear()}>
+ Clear
+ </Button>
+ )}
+ </div>
+ </div>
+ {problem && (
+ <p className="flex items-start gap-1.5 text-[12px] text-foreground">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-warning" /> {problem}
+ </p>
+ )}
+ <div id={`${inputId}-result`} role="status" aria-live="polite" className="empty:hidden">
+ {result && (
+ <p className={cn("flex flex-wrap items-center gap-x-1.5 gap-y-1 text-[12px]", result.ok ? "text-success" : "text-destructive")}>
+ {result.ok ? <CheckCircle2 className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
+ <span className="min-w-0 break-words">
+ {result.ok ? `Connected${result.saved ? " and saved" : ""} · ${result.detail}` : result.saved ? `Saved, not connected yet · ${result.detail}` : result.detail}
+ </span>
+ {result.unsaved && (
+ <button type="button" onClick={() => void saveAnyway(result.unsaved!)} className="font-medium text-foreground underline underline-offset-2 hover:no-underline">
+ Save anyway
+ </button>
+ )}
+ </p>
+ )}
+ </div>
+ {hint !== undefined && (
+ <p id={`${inputId}-hint`} className="text-[12px] text-muted-foreground">
+ {setting?.fromEnv ? "Set from an environment variable; a value saved here wins. " : ""}
+ {hint}
+ </p>
+ )}
+ </div>
+ );
+ }
diff --cc src/components/model3d/model-card.tsx
index 00000000,9d486d2a..56e0485c
mode 000000,100644..100644
--- a/src/components/model3d/model-card.tsx
+++ b/src/components/model3d/model-card.tsx
@@@ -1,0 -1,245 +1,395 @@@
+ "use client";
+
-import { Box, Clapperboard, Download, ImageIcon, PersonStanding, Sparkles, Video } from "lucide-react";
++import { Box, Clapperboard, Download, ImageIcon, Loader2, Pause, PersonStanding, Play, Rotate3d, Sparkles, Video } from "lucide-react";
+ import Link from "next/link";
-import { createElement, useEffect, useState } from "react";
++import { createElement, useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
+ import { toast } from "sonner";
+ import { Button } from "@/components/ui/button";
+ import { uploadFile, useHydrated } from "@/lib/api";
+ import { animateSpinHref, animationName, model3dView, stillOf, type Model3dView } from "@/lib/av/model3d";
+ import type { Generation } from "@/lib/catalog/types";
+ import { cn } from "@/lib/utils";
++import { loadModelViewer, TURNTABLE_BACKDROP, useViewerSrc, viewerLook } from "./model-viewer";
+ import type { Model3dInfo } from "./model3d-studio";
+ import { RigDialog } from "./rig-dialog";
+ import { recordableType, recordTurntable } from "./turntable";
+
+ /** Downloads besides the main file, by the name the provider gave them. */
+ const FORMAT_LABEL: Record<string, string> = { rigged: "Rigged .glb", walking: "Walk .glb", running: "Run .glb", fbx: ".fbx", splat: "Splat" };
+ const formatLabel = (k: string) => FORMAT_LABEL[k] ?? `.${k}`;
+
+ /** What the viewer shows of a rig: the result itself, or one of Meshy's walk and run cycles. */
+ function rigClips(g: Generation, view: Model3dView): { key: string; label: string; url: string }[] {
+ if (!view.rigged || !view.glb) return [];
+ const animation = g.request.params?.animation;
+ const main = view.animated ? (typeof animation === "number" ? animationName(animation) : "Animation") : "Rigged";
+ return [
+ { key: "main", label: main, url: view.glb },
+ ...(["walking", "running"] as const).filter((k) => view.formats[k]).map((k) => ({ key: k, label: k === "walking" ? "Walk" : "Run", url: view.formats[k] })),
+ ];
+ }
+
+ /**
- * A finished 3D model: the GLB in an orbitable viewer (playing its animation when it has one), or a splat as its
- * orbit video or preview with the file to download; the turntable, Animate the spin and Rig & animate.
++ * A finished 3D model. The card plays its turntable (or shows its poster or photo); the orbitable viewer, and with it
++ * the GLB, loads only when "View in 3D" opens it: the web GLB when the server made one, else the original (a rig
++ * plays its animation). A splat shows its orbit video or picture with the file to download. Then the turntable,
++ * Animate the spin and Rig & animate.
+ */
+ export function ModelCard({ g, info, cloudAllowed }: { g: Generation; info: Record<string, Model3dInfo>; cloudAllowed: boolean }) {
+ const view = model3dView(g);
++ // "preview": the turntable or the still (a splat with an orbit video: the video). "3d": the viewer (a splat: its picture).
++ const [show, setShow] = useState<"preview" | "3d">("preview");
+ const [viewer, setViewer] = useState<HTMLElement | null>(null);
+ const [ready, setReady] = useState(false);
+ const [failed, setFailed] = useState(false);
++ const [loadedEl, setLoadedEl] = useState<HTMLElement | null>(null);
++ const loaded = !!viewer && loadedEl === viewer;
+ const [recording, setRecording] = useState<number | null>(null);
+ const [recorded, setRecorded] = useState<{ url: string; saved?: string } | null>(null);
+ const [rigging, setRigging] = useState(false);
++ const pendingRecord = useRef(false);
++ // "View in 3D" unmounts itself: focus moves to the viewer once it's there.
++ const focusViewer = useRef(false);
+ const hydrated = useHydrated();
+ const canRecord = hydrated && !!recordableType();
++ const clips = rigClips(g, view);
++ const [clipKey, setClipKey] = useState("main");
++ const rigClip = clips.find((c) => c.key === clipKey);
++ // The rig's walk and run cycles load as they are; the model itself as its web GLB, falling back to the original.
++ const original = rigClip?.url ?? view.glb;
++ const src = useViewerSrc(viewer, rigClip && rigClip.key !== "main" ? rigClip.url : view.web, original);
++ const onOriginal = src === original;
++ const open3d = show === "3d" && !!view.glb;
+ useEffect(() => {
- if (!view.glb) return;
++ if (!open3d) return;
+ let live = true;
- import("@google/model-viewer").then(
++ loadModelViewer().then(
+ () => live && setReady(true),
- () => live && setFailed(true),
++ () => {
++ if (!live) return;
++ pendingRecord.current = false;
++ setFailed(true);
++ },
+ );
+ return () => {
+ live = false;
+ };
- }, [view.glb]);
++ }, [open3d]);
+ // The recorded clip's blob URL lives until another recording replaces it (saving it doesn't change it).
+ const recordedUrl = recorded?.url;
+ useEffect(() => () => void (recordedUrl && URL.revokeObjectURL(recordedUrl)), [recordedUrl]);
- // The turntable that came with the model (TRELLIS.2, TripoSplat, demo) or the one recorded here, shown in place of the 3D view.
++ // The turntable the server rendered (open models), TripoSplat's orbit or the demo's, or the one recorded here.
+ const clip = view.turntable ?? recordedUrl;
- // A splat opens on its orbit video when it has one (the page doesn't draw splats).
- const [show, setShow] = useState<"3d" | "video">(view.splat && view.turntable ? "video" : "3d");
- const clips = rigClips(g, view);
- const [clipKey, setClipKey] = useState("main");
- const src = clips.find((c) => c.key === clipKey)?.url ?? view.glb;
- const record = async () => {
++ // What the card shows while the viewer is closed: the poster, else the photo it was made from.
++ const still = view.poster ?? view.photo;
++ // From words on the open engine: the Z-Image still the model was built from (a helper step the page hides).
++ const drawn = stillOf(g);
++ const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");
++ const label = g.modelName ?? "3D";
++ // Behind the viewer: the studio sweep the server's turntable and poster are on, so opening 3D doesn't jump.
++ const backdrop = view.material ? TURNTABLE_BACKDROP : undefined;
++ const startRecording = useCallback(
++ async (el: HTMLElement) => {
++ setRecording(0);
++ try {
++ const blob = await recordTurntable(el as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });
++ const url = URL.createObjectURL(blob);
++ setRecorded({ url });
++ // Keep it in the Library (Uploads) so it can go on to Edit video.
++ const asset = await uploadFile(new File([blob], `${name} turntable.webm`, { type: "video/webm" }));
++ setRecorded({ url, saved: asset.url });
++ toast.success("Turntable recorded — saved to your uploads");
++ } catch (e) {
++ toast.error((e as Error).message);
++ } finally {
++ setRecording(null);
++ }
++ },
++ [name],
++ );
++ useEffect(() => {
+ if (!viewer) return;
- setRecording(0);
- try {
- const blob = await recordTurntable(viewer as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });
- const url = URL.createObjectURL(blob);
- setRecorded({ url });
- // Keep it in the Library (Uploads) so it can go on to Edit video.
- const asset = await uploadFile(new File([blob], `${g.modelName ?? "model"} turntable.webm`, { type: "video/webm" }));
- setRecorded({ url, saved: asset.url });
- toast.success("Turntable recorded — saved to your uploads");
- } catch (e) {
- toast.error((e as Error).message);
- } finally {
- setRecording(null);
++ if (focusViewer.current) {
++ focusViewer.current = false;
++ // Its keyboard-focusable part (camera controls) is inside the shadow root.
++ (viewer.shadowRoot?.querySelector<HTMLElement>(".userInput") ?? viewer).focus({ preventScroll: true });
+ }
++ const onLoad = () => {
++ setLoadedEl(viewer);
++ if (pendingRecord.current) {
++ pendingRecord.current = false;
++ void startRecording(viewer);
++ }
++ };
++ // A model that can't load won't record either. (A web GLB that fails falls back to the original first.)
++ const onError = () => void (onOriginal && (pendingRecord.current = false));
++ viewer.addEventListener("load", onLoad);
++ viewer.addEventListener("error", onError);
++ return () => {
++ viewer.removeEventListener("load", onLoad);
++ viewer.removeEventListener("error", onError);
++ };
++ }, [viewer, startRecording, onOriginal]);
++ const switchTo = (v: "preview" | "3d") => {
++ // A recording asked for before the model loaded is off once the 3D view is closed.
++ if (v === "preview") pendingRecord.current = false;
++ setShow(v);
++ };
++ // Recording needs the 3D view: open it and start once the model has loaded.
++ const record = () => {
++ if (viewer && loaded) return void startRecording(viewer);
++ pendingRecord.current = true;
++ setShow("3d");
+ };
+ const spin = view.rigged ? null : animateSpinHref(view, recorded?.saved);
- const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");
+ const notices = info[g.modelId]?.notices ?? [];
+ // A rigged result rigs its source model again with another animation.
+ const rigSource = view.rigged ? (g.request.inputs?.model3d ?? view.glb) : view.glb;
- const splatPicture = view.splat && !(show === "video" && clip);
- // From words on the open engine: the Z-Image still the model was built from (a helper step the page hides).
- const still = stillOf(g);
++ // The radio buttons in the corner: the preview and the 3D view, a rig's clips, or a splat's video and picture.
++ // A rig's clip is picked by its key ("main", "walking", "running"); "3d" is the model itself.
++ const choices: { key: string; label: string; on: boolean }[] = view.splat
++ ? clip
++ ? [
++ { key: "preview", label: "Turntable", on: show === "preview" },
++ { key: "3d", label: "Preview", on: show === "3d" },
++ ]
++ : []
++ : view.glb
++ ? [
++ { key: "preview", label: clip ? "Turntable" : "Preview", on: show === "preview" },
++ ...(clips.length > 1
++ ? clips.map((c) => ({ key: c.key, label: c.label, on: show === "3d" && clipKey === c.key }))
++ : [{ key: "3d", label: "3D", on: show === "3d" }]),
++ ]
++ : [];
++ const pick = (key: string) => {
++ if (key === "preview") return switchTo("preview");
++ if (key !== "3d") setClipKey(key);
++ switchTo("3d");
++ };
++ const placeholder = view.splat ? (
++ view.poster ? (
++ // eslint-disable-next-line @next/next/no-img-element
++ <img src={view.poster} alt="The subject the splat was made from, cut out" loading="lazy" decoding="async" className="size-full object-contain p-4" />
++ ) : (
++ <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">
++ <div>
++ <Box className="mx-auto mb-2 size-8" aria-hidden />
++ Gaussian splat ready — download it below.
++ </div>
++ </div>
++ )
++ ) : still ? (
++ // eslint-disable-next-line @next/next/no-img-element
++ <img src={still} alt={`The ${label} model`} loading="lazy" decoding="async" className="size-full object-contain" />
++ ) : (
++ <div className="grid size-full place-items-center text-muted-foreground">
++ <Box className="size-8" aria-hidden />
++ </div>
++ );
+ return (
+ <article className="overflow-hidden rounded-2xl border bg-background shadow-soft">
- <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]">
- {show === "video" && clip ? (
- <video src={clip} controls loop muted playsInline autoPlay preload="metadata" aria-label={`Turntable of the ${g.modelName ?? "3D"} model`} className="size-full bg-media object-contain" />
- ) : splatPicture ? (
- view.poster ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={view.poster} alt="The subject the splat was made from, cut out" className="size-full object-contain p-4" />
- ) : (
- <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">
- <div>
- <Box className="mx-auto mb-2 size-8" aria-hidden />
- Gaussian splat ready — download it below.
- </div>
- </div>
- )
++ <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]" style={open3d && backdrop ? { background: backdrop } : undefined}>
++ {!open3d ? (
++ <>
++ {clip && show === "preview" ? <TurntableLoop src={clip} poster={still} label={`Turntable of the ${label} model`} /> : placeholder}
++ {view.glb && (
++ <Button
++ size="sm"
++ variant="secondary"
++ className="absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full shadow-soft"
++ onClick={() => {
++ focusViewer.current = true;
++ switchTo("3d");
++ }}
++ >
++ <Rotate3d className="size-3.5" /> View in 3D
++ </Button>
++ )}
++ </>
+ ) : failed ? (
+ <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">Couldn&apos;t load the 3D viewer — download the .glb to open it.</div>
+ ) : !ready || !src ? (
- <div className="grid size-full place-items-center text-muted-foreground">
- <Box className="size-8 animate-pulse" aria-hidden />
++ // The poster (or the photo) while the viewer loads: the same picture the viewer starts from.
++ <div className="relative size-full" role="status" aria-label="Loading the 3D viewer">
++ {placeholder}
++ <Loader2 className="absolute right-3 bottom-3 size-4 animate-spin text-muted-foreground" />
+ </div>
+ ) : (
+ createElement("model-viewer", {
- key: src,
++ // A rig's clips are separate files: each gets a fresh viewer.
++ key: original,
+ ref: setViewer,
+ src,
- poster: view.poster,
++ poster: still,
+ alt: `3D model made with ${g.modelName ?? "a 3D model"}`,
++ loading: "lazy",
++ reveal: "auto",
+ "camera-controls": "",
+ // A character that moves plays its animation; a still model turns.
+ ...(view.rigged ? { autoplay: "" } : { "auto-rotate": "" }),
- "shadow-intensity": "1",
- exposure: "1",
+ "touch-action": "pan-y",
+ "interaction-prompt": "none",
++ ...viewerLook(view.material),
+ style: { width: "100%", height: "100%", background: "transparent" },
+ })
+ )}
+ {recording !== null && (
+ <div className="absolute inset-x-3 bottom-3 rounded-full bg-background/90 px-3 py-1.5 text-[12px] font-medium shadow-soft" role="status">
+ Recording the turntable… {Math.round(recording * 100)}%
+ </div>
+ )}
+ {g.provider === "mock" && <span className="absolute top-3 left-3 rounded-full bg-highlight/40 px-2 py-0.5 text-[11px] font-medium">Demo</span>}
- {(clip || clips.length > 1) && recording === null && (
++ {choices.length > 1 && recording === null && (
+ <div role="radiogroup" aria-label="Show" className="absolute top-3 right-3 inline-flex max-w-[calc(100%-1.5rem)] flex-wrap justify-end rounded-full bg-background/85 p-0.5 shadow-soft backdrop-blur">
- {clips.length > 1
- ? clips.map((c) => (
- <button
- key={c.key}
- type="button"
- role="radio"
- aria-checked={show === "3d" && clipKey === c.key}
- onClick={() => {
- setShow("3d");
- setClipKey(c.key);
- }}
- className={cn("h-6 max-w-32 truncate rounded-full px-2.5 text-[11px] font-medium transition", show === "3d" && clipKey === c.key ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}
- >
- {c.label}
- </button>
- ))
- : (["3d", "video"] as const).map((v) => (
- <button
- key={v}
- type="button"
- role="radio"
- aria-checked={show === v}
- onClick={() => setShow(v)}
- className={cn("h-6 rounded-full px-2.5 text-[11px] font-medium transition", show === v ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}
- >
- {v === "3d" ? (view.splat ? "Preview" : "3D") : "Turntable"}
- </button>
- ))}
++ {choices.map((c) => (
++ <button
++ key={c.key}
++ type="button"
++ role="radio"
++ aria-checked={c.on}
++ onClick={() => pick(c.key)}
++ className={cn("h-6 max-w-32 truncate rounded-full px-2.5 text-[11px] font-medium transition", c.on ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}
++ >
++ {c.label}
++ </button>
++ ))}
+ </div>
+ )}
+ </div>
+ <div className="space-y-2 p-3">
+ <p className="truncate text-[13px] text-muted-foreground">
+ {g.modelName}
+ {g.prompt && !view.rigged ? ` · ${g.prompt}` : ""}
+ </p>
+ {view.splat && (
+ <p className="text-[12px] text-muted-foreground">
+ Fuobe doesn&apos;t draw splats yet: {clip ? "the turntable shows it turning" : "the picture is what the model saw"}. Open the .{view.splat.format} in a Gaussian-splat viewer (SuperSplat, for one) to look around it.
+ </p>
+ )}
+ <div className="flex flex-wrap gap-1.5">
+ {view.splat ? (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={view.splat.url} download={`${name}.${view.splat.format}`}>
+ <Download className="size-3.5" /> .{view.splat.format}
+ </a>
+ </Button>
+ ) : (
+ view.glb && (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={view.glb} download={`${name}.glb`}>
+ <Download className="size-3.5" /> .glb
+ </a>
+ </Button>
+ )
+ )}
+ {Object.entries(view.formats)
+ .filter(([k]) => k !== "glb")
+ .slice(0, 4)
+ .map(([k, url]) => (
+ <Button key={k} asChild variant="ghost" size="sm" className="rounded-full">
+ <a href={url} download>
+ {formatLabel(k)}
+ </a>
+ </Button>
+ ))}
- {still && (
++ {drawn && (
+ <Button asChild variant="ghost" size="sm" className="rounded-full">
- <a href={still} target="_blank" rel="noreferrer" aria-label="Open the still the model was built from">
++ <a href={drawn} target="_blank" rel="noreferrer" aria-label="Open the still the model was built from">
+ <ImageIcon className="size-3.5" /> Still
+ </a>
+ </Button>
+ )}
+ {clip ? (
+ <Button asChild variant="outline" size="sm" className="rounded-full">
+ <a href={clip} download={`${name} turntable.${view.turntable ? "mp4" : "webm"}`} aria-label="Download the turntable video">
+ <Video className="size-3.5" /> Turntable
+ </a>
+ </Button>
++ ) : view.rendering ? (
++ // The server renders it after the job (one at a time): it shows up here when it's done.
++ <Button variant="outline" size="sm" className="rounded-full" disabled>
++ <Loader2 className="size-3.5 animate-spin" /> {view.rendering.queued ? "Turntable queued" : `Rendering turntable… ${Math.round(view.rendering.progress * 100)}%`}
++ </Button>
+ ) : (
+ view.glb &&
+ !view.rigged && (
- <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!ready || !canRecord || recording !== null}>
++ <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!canRecord || recording !== null || failed}>
+ <Clapperboard className="size-3.5" /> Record turntable
+ </Button>
+ )
+ )}
+ {rigSource && !view.splat && g.op !== "splat" && (
+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => setRigging(true)}>
+ <PersonStanding className="size-3.5" /> {view.rigged ? "Another animation" : "Rig & animate"}
+ </Button>
+ )}
+ {spin && (
+ <Button asChild size="sm" className="rounded-full">
+ <Link href={spin} prefetch={false}>
+ <Sparkles className="size-3.5" /> Animate the spin
+ </Link>
+ </Button>
+ )}
+ </div>
+ {notices.length > 0 && <p className="text-[11px] text-muted-foreground">{notices.join(" · ")}</p>}
+ </div>
+ {rigSource && rigging && g.op !== "splat" && <RigDialog glb={rigSource} open={rigging} onOpenChange={setRigging} cloudAllowed={cloudAllowed} />}
+ </article>
+ );
+ }
++
++const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
++
++/** Whether the user prefers reduced motion (true until hydrated, so nothing moves before it's known). */
++function useReducedMotion(): boolean {
++ return useSyncExternalStore(
++ (cb) => {
++ const mq = window.matchMedia(REDUCED_MOTION);
++ mq.addEventListener("change", cb);
++ return () => mq.removeEventListener("change", cb);
++ },
++ () => window.matchMedia(REDUCED_MOTION).matches,
++ () => true,
++ );
++}
++
++/**
++ * A card's turntable loop: it loads and plays only while the card is on screen, not at all when the user
++ * prefers reduced motion (the poster shows instead), and has a pause / play button (WCAG 2.2.2).
++ */
++function TurntableLoop({ src, poster, label }: { src: string; poster?: string; label: string }) {
++ const ref = useRef<HTMLVideoElement>(null);
++ const [visible, setVisible] = useState(false);
++ const reduced = useReducedMotion();
++ // What the user chose with the button; until then, play unless they prefer reduced motion.
++ const [choice, setChoice] = useState<"play" | "pause" | null>(null);
++ const wanted = choice ? choice === "play" : !reduced;
++ const playing = visible && wanted;
++ useEffect(() => {
++ const el = ref.current;
++ if (!el || typeof IntersectionObserver === "undefined") return;
++ const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold: 0.5 });
++ io.observe(el);
++ return () => io.disconnect();
++ }, []);
++ useEffect(() => {
++ const el = ref.current;
++ if (!el) return;
++ if (playing) void el.play().catch(() => {});
++ else el.pause();
++ }, [playing]);
++ return (
++ <>
++ <video ref={ref} src={src} poster={poster} loop muted playsInline preload="none" aria-label={label} className="size-full bg-media object-contain" />
++ <button
++ type="button"
++ onClick={() => setChoice(wanted ? "pause" : "play")}
++ aria-label={wanted ? "Pause the turntable" : "Play the turntable"}
++ className="absolute right-3 bottom-3 grid size-7 place-items-center rounded-full bg-background/85 text-foreground shadow-soft backdrop-blur transition hover:bg-background"
++ >
++ {wanted ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}
++ </button>
++ </>
++ );
++}
diff --cc src/components/model3d/model3d-studio.tsx
index 5b818240,36eb6781..e6ab23cc
--- a/src/components/model3d/model3d-studio.tsx
+++ b/src/components/model3d/model3d-studio.tsx
@@@ -35,40 -164,166 +164,166 @@@ export function Model3dStudio({ info }
onError: (e) => toast.error((e as Error).message),
});
};
- const items = results.data ?? [];
+ const licence = modelId ? info[modelId]?.licence : undefined;
+ const items = (results.data ?? []).filter((g) => g.feature !== "image-to-3d-step");
+ const setSide = (s: ViewSide) => (v: SlotValue | null) => setViews((cur) => ({ ...cur, [s]: v }));
return (
<ToolShell title="Image to 3D">
- <ToolHero title="Your product, in 3D" subtitle="One clear photo → a textured 3D model (.glb) you can spin, download, record as a turntable and turn into a video." />
- <div className="mx-auto mt-8 grid max-w-[880px] gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
- <MediaDrop kind="image" value={photo} onChange={setPhoto} title="Add a product photo" hint="One object, plain background, well lit" compact />
- <Panel title="Model">
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="m3d-model" className="sr-only">
- Model
- </Label>
- <Select value={modelId} onValueChange={(v) => setPicked((p) => ({ ...p, [engine]: v }))}>
- <SelectTrigger id="m3d-model" className="h-9 w-full rounded-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MODELS_3D[engine].map((m) => (
- <SelectItem key={m.id} value={m.id}>
- {names[m.id] ?? m.id}
- </SelectItem>
+ <Suspense fallback={null}>
+ <UrlModel onModel={fromUrl} onMode={setMode} onRig={showRigHint} />
+ </Suspense>
+ <ToolHero title="Your product, in 3D" subtitle={HINTS[mode]} />
+ <ModePicker mode={mode} onChange={setMode} />
+ {rigHint && (
+ <p role="status" className="mx-auto mt-4 max-w-[880px] rounded-2xl border bg-brand-faint px-4 py-3 text-[13px] text-brand-text">
+ <PersonStanding className="mr-1.5 inline size-4 align-[-3px]" aria-hidden />
+ Rig &amp; animate works on a finished model: make one here
+ {items.length > 0 && (
+ <>
+ {" "}
+ or pick one under{" "}
+ <a href="#your-3d-models" className="font-medium underline underline-offset-2">
+ Your 3D models
+ </a>
+ </>
+ )}
+ , then press Rig &amp; animate on its card. Rigging runs on Meshy, in the cloud.
+ </p>
+ )}
+ <div className="mx-auto mt-6 grid max-w-[880px] gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
+ {mode === "multi" ? (
+ <Panel title="Photos of each side" aside={<span className="text-[12px] text-muted-foreground">{Object.keys(sides).length} of 4</span>}>
+ {/* Four 80 px slots in a row when the panel has room for them (22rem), two by two when it doesn't. */}
+ <div className="@container">
+ <div className="grid grid-cols-2 justify-items-center gap-2 @[22rem]:grid-cols-4">
+ {VIEW_SIDES.map((s) => (
+ <div key={s} className="flex flex-col items-center gap-1">
+ <MediaSlot label={SIDE_LABELS[s]} kind="image" value={views[s] ?? null} onChange={setSide(s)} required={s === "front"} size="lg" caption />
+ <span className="text-[11px] text-muted-foreground">{s === "front" ? "Needed" : "Optional"}</span>
+ </div>
))}
- </SelectContent>
- </Select>
- <p className="text-[12px] text-muted-foreground">{MODELS_3D[engine].find((m) => m.id === modelId)?.note}</p>
+ </div>
+ </div>
+ <p className="mt-3 text-[12px] text-muted-foreground">
+ The front and at least one more side. Same object, same distance and light in each; a plain background helps.
+ {engine === "open" && ` The open model puts each photo on the side you add it to. ${SIDES_HINT}`}
+ </p>
+ </Panel>
+ ) : mode === "text" ? (
+ <Panel title="Describe the object">
+ <Label htmlFor="m3d-text" className="sr-only">
+ Describe the object
+ </Label>
+ <Textarea
+ id="m3d-text"
+ value={text}
+ onChange={(e) => setText(e.target.value.slice(0, MAX_3D_PROMPT))}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) go();
+ }}
+ placeholder="A brass ship's lantern with a glass globe and a carry ring"
+ className="min-h-28 rounded-xl"
+ />
+ <p className="mt-2 text-[12px] text-muted-foreground">
+ One object: what it is, its material and colours.{engine === "open" && " Z-Image Turbo draws it on a plain background first; the finished model's card links to that still."}
+ </p>
+ </Panel>
+ ) : (
+ <div className="grid min-w-0 gap-3">
+ <MediaDrop
+ kind="image"
+ value={photo}
+ onChange={setPhoto}
+ title={mode === "objects" ? "Add a photo" : "Add a photo of the object"}
+ hint={mode === "objects" ? "A room, a shelf, a street: anything with the object in it" : "One object, plain background, well lit"}
+ compact
+ />
+ {mode === "objects" && (
+ <Panel title="What to take out">
+ <Label htmlFor="m3d-object" className="sr-only">
+ What to take out
+ </Label>
+ <Input
+ id="m3d-object"
+ value={object}
+ onChange={(e) => setObject(e.target.value.slice(0, 200))}
+ onKeyDown={(e) => e.key === "Enter" && go()}
+ placeholder="the green armchair"
+ className="h-9 rounded-full"
+ />
+ <p className="mt-2 text-[12px] text-muted-foreground">Name one thing, or several separated by commas. It&apos;s rebuilt where it stands; the rest of the photo is left out.</p>
+ </Panel>
+ )}
</div>
- <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>
- {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} Make it 3D
- </Button>
- <p className="mt-2 text-[12px] text-muted-foreground">
- {engine === "open" ? "Open models also get a turntable video, rendered after the model is made." : "Cloud models return the .glb; record a turntable right here in your browser."}
- </p>
+ )}
+ <Panel title="Model">
+ {!modelId ? (
+ <div className="space-y-3 text-[13px]">
+ <p className="text-muted-foreground">
- Pick an object runs on SAM 3D Objects, a cloud model; no open model rebuilds one named object yet. On the open engine, crop the photo to the object and use From an image: TRELLIS.2 cuts it out for you.
++ Pick an object runs on SAM 3D Objects, a cloud model; no open model rebuilds one named object yet. On the open engine, crop the photo to the object and use From an image: Pixal3D cuts it out for you.
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {cloudAllowed && (
+ <Button size="sm" className="rounded-full" onClick={() => setEngine("cloud")}>
+ Use the cloud
+ </Button>
+ )}
+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => setMode("image")}>
+ From an image
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="m3d-model" className="sr-only">
+ Model
+ </Label>
+ <Select value={modelId} onValueChange={(v) => setPicked((p) => ({ ...p, [`${mode}:${engine}`]: v }))}>
+ <SelectTrigger id="m3d-model" className="h-9 w-full rounded-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {choices.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {info[m.id]?.name ?? m.id}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-[12px] text-muted-foreground">{choices.find((m) => m.id === modelId)?.note}</p>
+ {!licence && info[modelId]?.notices.length > 0 && <p className="text-[12px] font-medium">{info[modelId].notices.join(" · ")}</p>}
+ {licence && (
+ <p className="text-[12px] text-muted-foreground">
+ Licence: {[licence.name, ...licence.flags].join(" · ")}
+ {licence.notices.length > 0 && <span className="font-medium text-foreground"> · {licence.notices.join(" · ")}</span>} ·{" "}
+ <Link href="/settings/about" className="underline underline-offset-2" prefetch={false}>
+ All licences
+ </Link>
+ </p>
+ )}
+ </div>
+ <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>
+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} {mode === "splat" ? "Make the splat" : "Make it 3D"}
+ </Button>
+ <p className="mt-2 text-[12px] text-muted-foreground" aria-live="polite">
+ {blocker ? `${blocker} · ` : ""}
+ {preview.isError ? (preview.error as Error).message : (price ?? "Working out the price…")}
+ </p>
+ <p className="mt-1 text-[12px] text-muted-foreground">
+ {mode === "splat"
+ ? engine === "open"
+ ? "TripoSplat cuts the subject out and renders an orbit video of the splat on your GPU."
+ : "TripoSplat cuts the subject out and returns a .ply splat to download."
+ : engine === "open"
- ? "TRELLIS.2 also renders a turntable video on your GPU."
++ ? "Open models also get a turntable video, rendered after the model is made."
+ : "Cloud models return the .glb; record a turntable right here in your browser."}
+ </p>
+ </>
+ )}
</Panel>
</div>
- <section className="mx-auto mt-12 max-w-[880px]" aria-labelledby="models3d">
+ <section id="your-3d-models" className="mx-auto mt-12 max-w-[880px] scroll-mt-6" aria-labelledby="models3d">
{(results.isLoading || items.length > 0) && (
<h3 id="models3d" className="mb-3 font-heading text-[22px]">
Your 3D models
diff --cc src/components/preset-header.tsx
index 279932ab,eec07112..6332e5f0
--- a/src/components/preset-header.tsx
+++ b/src/components/preset-header.tsx
@@@ -1,14 -1,26 +1,28 @@@
"use client";
import { Cloud, Cpu, Info, X } from "lucide-react";
- import { PresetPreview, useAutoplay } from "@/components/preset-preview";
+ import { useSyncExternalStore } from "react";
-import { PresetPreview } from "@/components/preset-preview";
++import { PresetPreview, useSaveData } from "@/components/preset-preview";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { Preset } from "@/lib/catalog/types";
-import { presetHowTo, presetRouteLines, previewFlip, toPresetCard } from "@/lib/preset-cards";
++// The covers manifest comes with toPresetCard: this component is loaded on its own (next/dynamic in studio-page.tsx).
+import { toPresetCard } from "@/lib/preset-card-data";
+import { presetHowTo, presetRouteLines, previewFlip } from "@/lib/preset-cards";
- import { PREVIEW_SIZES } from "@/lib/preview-media";
import { cn } from "@/lib/utils";
+ const REDUCED = "(prefers-reduced-motion: reduce)";
+ function useReducedMotion() {
+ return useSyncExternalStore(
+ (cb) => {
+ const mq = window.matchMedia(REDUCED);
+ mq.addEventListener("change", cb);
+ return () => mq.removeEventListener("change", cb);
+ },
+ () => window.matchMedia(REDUCED).matches,
+ () => true,
+ );
+ }
+
/**
* The card a studio shows above its composer while a preset (app, camera motion, effect) is active
* and the feed is still empty: the preview looping, the name, one line on what to do, the models it
@@@ -32,12 -44,12 +46,14 @@@ export function PresetHeader(
className?: string;
}) {
const card = toPresetCard(preset);
- const autoplay = useAutoplay();
+ const reduced = useReducedMotion();
++ // Not with Save-Data or on 2G either: a clip cover would download as soon as the studio opens.
++ const saveData = useSaveData();
const routes = presetRouteLines(preset, modelName);
return (
<div className={cn("mx-auto flex w-full max-w-[760px] items-center gap-3 rounded-2xl border bg-background p-2 pr-3 text-left shadow-soft", className)}>
<div className="relative aspect-[4/3] w-24 shrink-0 overflow-hidden rounded-xl bg-muted sm:w-32">
- <PresetPreview preview={card.preview} hue={card.hue} playing={autoplay} flip={previewFlip(card)} card={card} sizes={PREVIEW_SIZES.header} priority />
- <PresetPreview preview={card.preview} hue={card.hue} playing={!reduced} flip={previewFlip(card)} />
++ <PresetPreview preview={card.preview} hue={card.hue} playing={!reduced && !saveData} flip={previewFlip(card)} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-heading text-[19px] leading-snug">{preset.name}</p>
diff --cc src/components/preset-preview.tsx
index 091f80af,a8facb5b..5f72dff7
--- a/src/components/preset-preview.tsx
+++ b/src/components/preset-preview.tsx
@@@ -1,11 -1,8 +1,9 @@@
"use client";
import { memo, useEffect, useRef, useState, useSyncExternalStore } from "react";
- import { PreviewMedia } from "@/components/preview-media";
- import { useReducedMotion } from "@/hooks/use-reduced-motion";
import {
CAMERA_MOVES,
- fallbackPreview,
++ isCover,
LAYER_DEPTH,
LAYER_OFFSET,
moveVars,
@@@ -60,18 -51,6 +54,16 @@@ export function usePreviewPlayback<T ex
};
}
+const noSubscribe = () => () => {};
+
+/**
- * Whether a preview may play without being hovered (the preset header's loop): not when the user
- * prefers reduced motion, nor with Save-Data or on a 2G connection.
++ * Save-Data or a 2G connection (lib/preview-playback.ts): a preview that would play without being
++ * asked (the preset header's loop) stays on its poster. True before hydration, so nothing starts early.
+ */
- export function useAutoplay(): boolean {
- const reduced = useReducedMotion();
- const saveData = useSyncExternalStore(noSubscribe, store.saveData, () => true);
- return !reduced && !saveData;
++export function useSaveData(): boolean {
++ return useSyncExternalStore(noSubscribe, store.saveData, () => true);
+}
+
const layerVars = (l: PreviewLayer) => ({ "--d": LAYER_DEPTH[l], "--o": LAYER_OFFSET[l] }) as React.CSSProperties;
/** The other still a transition wipes to. */
@@@ -263,27 -242,54 +255,60 @@@ function Fx({ fx, scene }: { fx: NonNul
}
}
- /** The line diagram of a camera move (move-glyphs.ts), over a motion's resting frame until it plays. */
- function MoveGlyph({ move }: { move: CameraMove }) {
- return (
- <svg className="pv-glyph" viewBox="0 0 48 36" aria-hidden>
- {glyphFor(move).map((part, i) => (
- <path key={i} d={part.d} data-dashed={part.dashed || undefined} />
- ))}
- </svg>
- );
- }
-
/**
- * The procedural preview: a camera move over a layered sample still (motions) or an animated
- * treatment (effects, apps). At rest it shows the poster frame (and the treatment's still frame);
- * `playing` runs it. The depth layers a camera move needs are only mounted once the card first plays.
- * A preset's preview: a real clip when the catalog has one, otherwise the procedural version, a
- * camera move over a layered sample still (motions) or an animated treatment (effects, apps).
++ * A preset's preview: its real cover when it has one (a clip that plays, or a still), otherwise the
++ * procedural version, a camera move over a layered sample still (motions) or an animated treatment (effects, apps).
+ * At rest it shows the poster frame (and the treatment's still frame); `playing` runs it. The depth
+ * layers a camera move needs are only mounted once the card first plays.
*/
- function Procedural({ preview, hue, playing, flip }: { preview: ProceduralPreview; hue: number; playing: boolean; flip?: boolean }) {
+ export const PresetPreview = memo(function PresetPreview({
+ preview,
+ hue,
+ playing,
+ flip,
+ }: {
+ preview: Preview;
+ hue: number;
+ playing: boolean;
+ /** Mirror the still (see previewFlip). */
+ flip?: boolean;
+ }) {
+ const video = useRef<HTMLVideoElement>(null);
const [armed, setArmed] = useState(false);
if (playing && !armed) setArmed(true);
+ useEffect(() => {
+ const v = video.current;
+ if (!v) return;
+ if (playing) void v.play().catch(() => {});
+ else {
+ v.pause();
+ v.currentTime = 0;
+ }
+ }, [playing]);
+
+ if (preview.video)
+ return (
+ <video
+ ref={video}
+ src={preview.video}
+ poster={preview.poster}
+ muted
+ loop
+ playsInline
+ preload="none"
+ className="absolute inset-0 size-full object-cover"
+ aria-hidden
+ />
+ );
++
++ // A real cover that is a still: the card's image as rendered, without the procedural preview's tint,
++ // bleed or mirroring (and no move glyph: the picture shows the preset itself).
++ if (isCover(preview))
++ // eslint-disable-next-line @next/next/no-img-element
++ return <img src={preview.poster} alt="" draggable={false} loading="lazy" decoding="async" className="absolute inset-0 size-full object-cover" aria-hidden />;
const spec: MoveSpec | undefined = preview.move ? CAMERA_MOVES[preview.move] : undefined;
+ const glyph = preview.move ? glyphFor(preview.move) : undefined;
const style = { "--pv-hue": hue, ...(spec ? moveVars(spec) : {}) } as React.CSSProperties;
return (
<div
diff --cc src/components/settings-form.tsx
index e683aa1a,c4d8deaa..148b84a3
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@@ -1,34 -1,24 +1,26 @@@
"use client";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { CheckCircle2, Cloud, Cpu, ExternalLink, Info, Layers, Link2, Scale } from "lucide-react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
- import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2, RefreshCw } from "lucide-react";
- import { useEffect, useId, useState } from "react";
++import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Info, Layers, Link2, Loader2, RefreshCw, Scale } from "lucide-react";
+ import Link from "next/link";
+ import { useRouter } from "next/navigation";
+ import { useEffect, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
- import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
-import { ConnectField, useSettings } from "@/components/connect-field";
++import { ConnectField, useSettings, type PublicSetting } from "@/components/connect-field";
+ import { GetStarted } from "@/components/get-started";
+ import { LoraSettings } from "@/components/lora-settings";
+ import { useStatus, type StatusInfo } from "@/lib/api";
+ import { connectionSummary, ENGINE_MODE_LABEL, FAL_KEYS_URL, showFirstRun } from "@/lib/connections";
import { cn } from "@/lib/utils";
+ import { ConnectorSettings } from "@/components/assist/connectors-settings";
import { NotificationSettings } from "@/components/notification-settings";
import { SecuritySettings } from "@/components/security-settings";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
- interface PublicSetting {
- name: string;
- value: string;
- secret: boolean;
- fromEnv: boolean;
- isSet: boolean;
- }
-
- function useSettings() {
- return useQuery({
- queryKey: ["settings"],
- queryFn: async () => ((await (await fetch("/api/settings")).json()) as { settings: PublicSetting[] }).settings,
- });
- }
-
function Section({
id,
title,
@@@ -217,223 -148,61 +150,328 @@@ function ChoiceField(
);
}
+ /**
+ * What's connected, at a glance and always in view: one chip per connection (green when it works,
+ * each a link to its field) and the engine mode. Also opens the setup guide again.
+ */
+ function StatusStrip({ status, onGuide, guideOpen }: { status?: StatusInfo; onGuide: () => void; guideOpen: boolean }) {
+ return (
+ <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2.5 backdrop-blur sm:-mx-8 sm:px-8 md:top-0">
+ <nav aria-label="Connections" className="scrollbar-none -my-1 flex items-center gap-1.5 overflow-x-auto py-1">
+ {status ? (
+ <>
+ {connectionSummary(status).map((c) => (
+ <a
+ key={c.id}
+ href={c.href}
+ className={cn(
+ "inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border bg-background px-2.5 text-[12px] whitespace-nowrap transition-colors hover:bg-accent",
+ c.unused && "opacity-60",
+ )}
+ >
+ <span aria-hidden className={cn("size-1.5 rounded-full", c.ok ? "bg-success" : "bg-muted-foreground/50")} />
+ <span className="font-medium">{c.label}</span>
+ <span className="text-muted-foreground">{c.unused ? "Not used" : c.text}</span>
+ </a>
+ ))}
+ <a href="#engine" className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] whitespace-nowrap transition-colors hover:bg-accent">
+ <span className="text-muted-foreground">Engine</span>
+ <span className="font-medium">{ENGINE_MODE_LABEL[status.engineMode]}</span>
+ </a>
+ {!guideOpen && (
+ <button type="button" onClick={onGuide} className="inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap text-brand-text hover:bg-brand-faint">
+ Setup guide
+ </button>
+ )}
+ </>
+ ) : (
+ <Skeleton className="h-7 w-full max-w-xl rounded-full" />
+ )}
+ </nav>
+ </div>
+ );
+ }
+
+ function subscribeHash(cb: () => void) {
+ window.addEventListener("hashchange", cb);
+ return () => window.removeEventListener("hashchange", cb);
+ }
+
+type LocalKind = "ollama" | "lmstudio" | "unsloth" | "custom";
+
+/** A local LLM server as GET /api/llm reports it (no keys). */
+interface LocalServerStatus {
+ kind: LocalKind;
+ label: string;
+ url: string;
+ up: boolean;
+ auth: "none" | "ok" | "missing" | "rejected";
+ models: { id: string; name?: string; loaded?: boolean; context?: number | null; maxContext?: number | null }[];
+ model: string | null;
+ loaded: boolean | null;
+ context: number | null;
+ problem: string | null;
+ warning: string | null;
+ native?: boolean;
+}
+
+interface LocalLlmInfo {
+ provider: "auto" | LocalKind;
+ /** Settings' context, in tokens (0: the server's own). */
+ context: number;
+ /** The server text steps and Assist use now. */
+ active: LocalKind | null;
+ servers: LocalServerStatus[];
+}
+
+const LOCAL_SERVERS: { value: "auto" | LocalKind; title: string }[] = [
+ { value: "auto", title: "Automatic" },
+ { value: "ollama", title: "Ollama" },
+ { value: "lmstudio", title: "LM Studio" },
+ { value: "unsloth", title: "Unsloth Studio" },
+ { value: "custom", title: "Other" },
+];
+
+const code = (s: string) => <code className="font-mono text-[11px]">{s}</code>;
+
+/** Each server's settings and how to get it running. */
- const LOCAL_FIELDS: Record<LocalKind, { url: string; urlPlaceholder: string; model: string; modelHint: string; key?: string; keyLabel?: string; keyPlaceholder?: string; setup: React.ReactNode }> = {
++const LOCAL_FIELDS: Record<
++ LocalKind,
++ { url: string; urlPlaceholder: string; urlHint: string; model: string; modelPlaceholder?: string; modelHint: string; key?: string; keyLabel?: string; keyPlaceholder?: string; setup: React.ReactNode }
++> = {
+ ollama: {
+ url: "ollamaUrl",
+ urlPlaceholder: "http://127.0.0.1:11434",
++ urlHint: "Test checks Ollama answers and has the model.",
+ model: "ollamaModel",
- modelHint: "A model with tool calling for Assist, such as qwen3:8b.",
++ modelPlaceholder: "qwen3:8b",
++ modelHint: "A model with tool calling for Assist, such as qwen3:8b. Pull it first: ollama pull qwen3:8b",
+ setup: <>Install Ollama, then run {code("ollama pull qwen3:8b")}. Fuobe gives it the context below.</>,
+ },
+ lmstudio: {
+ url: "lmstudioUrl",
+ urlPlaceholder: "http://127.0.0.1:1234",
++ urlHint: "Test checks LM Studio answers and has the model.",
+ model: "lmstudioModel",
+ modelHint: "Empty: the loaded model, else one trained for tool use. A model that isn't loaded is loaded with the context below.",
+ key: "lmstudioToken",
+ keyLabel: "API token (only with Require Authentication on)",
+ setup: (
+ <>
+ In LM Studio, open Developer and start the server (or run {code("lms server start")}), and download a model in Discover (or {code("lms get qwen/qwen3-8b")}). Models without thinking (instruct models) answer faster. Without
+ Require Authentication, anyone on your network can use LM Studio&apos;s server.
+ </>
+ ),
+ },
+ unsloth: {
+ url: "unslothUrl",
+ urlPlaceholder: "http://127.0.0.1:8888",
++ urlHint: "Test checks Unsloth Studio answers and has a model loaded.",
+ model: "unslothModel",
+ modelHint: "Empty: the model loaded in Unsloth Studio.",
+ key: "unslothKey",
+ keyLabel: "API key",
+ keyPlaceholder: "sk-unsloth-…",
+ setup: (
+ <>
+ Start Unsloth Studio and load a model on its Chat page (Select model), then make a key: avatar → Settings → API → Create. Fuobe always turns Unsloth&apos;s server-side tools (Python, terminal, web search) off.
+ </>
+ ),
+ },
+ custom: {
+ url: "llmUrl",
+ urlPlaceholder: "http://127.0.0.1:8080/v1",
++ urlHint: "Test checks the server answers with a model list.",
+ model: "llmModel",
+ modelHint: "Empty: the first model the server lists.",
+ key: "llmKey",
+ keyLabel: "API key (optional)",
+ setup: <>Any OpenAI-compatible server: llama.cpp&apos;s llama-server, vLLM, Jan… Give its base URL as its docs do (it usually ends in {code("/v1")}).</>,
+ },
+};
+
+const k = (n: number) => `${Math.round(n / 1024)}k`;
+
+/** One line per server: the model it would use, or what's wrong. */
+function serverLine(s: LocalServerStatus): string {
+ if (!s.url) return "Not set up";
+ if (s.problem) return s.up ? s.problem : `Not running at ${s.url}`;
+ return [s.model, s.loaded ? "loaded" : s.loaded === false ? "loads on first use" : null, s.context ? `${k(s.context)} context` : null].filter(Boolean).join(" · ");
+}
+
++/** A tiny chat call to a local server (POST /api/llm), timed: proves the model answers, not only that the server is up. */
++function TryReply({ kind }: { kind: LocalKind }) {
++ const [res, setRes] = useState<{ ok: boolean; detail: string } | null>(null);
++ const m = useMutation({
++ mutationFn: async () =>
++ (await (await fetch("/api/llm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "test", kind }) })).json()) as { ok: boolean; detail: string },
++ onSuccess: setRes,
++ onError: (e: Error) => setRes({ ok: false, detail: e.message }),
++ });
++ return (
++ <div className="flex min-w-0 flex-wrap items-center gap-2">
++ <Button
++ variant="outline"
++ size="sm"
++ onClick={() => {
++ setRes(null);
++ m.mutate();
++ }}
++ disabled={m.isPending}
++ >
++ {m.isPending && <Loader2 className="animate-spin" />} Send a test message
++ </Button>
++ <span role="status" aria-live="polite" className="min-w-0">
++ {res && (
++ <span className={cn("inline-flex items-start gap-1 text-[12px] break-words", res.ok ? "text-success" : "text-destructive")}>
++ {res.ok ? <CheckCircle2 className="mt-0.5 size-3.5 shrink-0" /> : <CircleAlert className="mt-0.5 size-3.5 shrink-0" />}
++ {res.detail}
++ </span>
++ )}
++ </span>
++ </div>
++ );
++}
++
+/** Settings → AI helper → the local model server: pick one (or Automatic), see what each one answers, set its URL, model and key, and test it. */
+function LocalLlmSettings({ get, set }: { get: (n: string) => PublicSetting | undefined; set: (n: string) => (v: string) => void }) {
+ const qc = useQueryClient();
+ const llm = useQuery({
+ queryKey: ["llm"],
+ queryFn: async () => (await (await fetch("/api/llm")).json()) as LocalLlmInfo,
+ refetchInterval: 30_000,
+ });
+ const refresh = useMutation({
+ mutationFn: async () => (await (await fetch("/api/llm?refresh=1")).json()) as LocalLlmInfo,
+ onSuccess: (data) => qc.setQueryData(["llm"], data),
+ });
+ const reload = useMutation({
+ mutationFn: async (model: string | null) =>
+ (await (await fetch("/api/llm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "load", model }) })).json()) as { ok: boolean; detail: string },
+ onSuccess: (r) => {
+ if (r.ok) toast.success(r.detail);
+ else toast.error(r.detail);
+ refresh.mutate();
+ },
+ });
+ const provider = (get("llmProvider")?.value || "auto") as "auto" | LocalKind;
+ const [picked, setPicked] = useState<LocalKind | null>(null);
+ // Pinned: that server's settings. Automatic: the one clicked below, else the one in use.
+ const editing: LocalKind = provider !== "auto" ? provider : (picked ?? llm.data?.active ?? "ollama");
+ const status = llm.data?.servers.find((s) => s.kind === editing);
+ const f = LOCAL_FIELDS[editing];
+ const need = llm.data?.context ?? 0;
+ // Compared with the model's most when that's less: a reload can't give more than it.
+ const maxContext = status?.models.find((m) => m.id === status.model)?.maxContext;
+ const want = Math.min(need, maxContext || need);
+ const smallContext = editing === "lmstudio" && status?.native && status.loaded && !!status.context && !!want && status.context < want;
+ const shown = llm.data?.servers.filter((s) => provider === "auto" || s.kind === provider) ?? [];
+
+ return (
- <div className="space-y-4 rounded-xl border p-4">
++ <div className="min-w-0 space-y-4 rounded-xl border p-4">
+ <div className="space-y-1.5">
+ <p id="local-llm-label" className="text-[13px] font-medium">
+ Local model server
+ </p>
+ <div role="radiogroup" aria-labelledby="local-llm-label" onKeyDown={radioKeys} className="flex flex-wrap gap-1 rounded-xl bg-muted p-1">
+ {LOCAL_SERVERS.map((o) => (
+ <button
+ key={o.value}
+ type="button"
+ role="radio"
+ aria-checked={provider === o.value}
+ tabIndex={radioTab(provider === o.value)}
+ onClick={() => provider !== o.value && set("llmProvider")(o.value)}
+ className={cn("h-8 rounded-lg px-3 text-[13px] font-medium transition-colors", provider === o.value ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {o.title}
+ </button>
+ ))}
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ {provider === "auto" ? "Uses the first server that answers with a model, in this order: Ollama, LM Studio, Unsloth Studio, then the Other server." : "Only this server is used; the others are ignored."}
+ </p>
+ </div>
+
+ <div className="space-y-1">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[13px] font-medium">Found on this machine</p>
+ <Button variant="ghost" size="sm" className="h-7 px-2 text-[12px]" onClick={() => refresh.mutate()} disabled={refresh.isPending}>
+ {refresh.isPending ? <Loader2 className="animate-spin" /> : <RefreshCw />} Check again
+ </Button>
+ </div>
+ {llm.isLoading && <Skeleton className="h-16 w-full rounded-lg" />}
+ <ul className="space-y-0.5">
+ {shown.map((s) => (
+ <li key={s.kind}>
+ <button
+ type="button"
+ onClick={() => setPicked(s.kind)}
+ aria-pressed={editing === s.kind}
+ className={cn("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[12px] transition-colors hover:bg-accent", editing === s.kind && "bg-accent")}
+ >
+ <span className={cn("size-2 shrink-0 rounded-full", !s.problem ? "bg-success" : s.up ? "bg-warning" : "bg-subtle-foreground")} />
+ <span className="shrink-0 font-medium">{s.kind === "custom" ? "Other" : s.label}</span>
+ <span className="min-w-0 flex-1 truncate font-mono text-muted-foreground">{serverLine(s)}</span>
+ {llm.data?.active === s.kind && <span className="shrink-0 rounded-md bg-brand-faint px-1.5 py-0.5 text-[11px] text-brand-text">In use</span>}
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+
+ <div className="space-y-4 border-t pt-4">
+ <p className="text-[13px] font-medium">{editing === "custom" ? "Other server (OpenAI-compatible)" : (status?.label ?? LOCAL_SERVERS.find((o) => o.value === editing)?.title)}</p>
+ <p className="text-[12px] leading-relaxed text-muted-foreground">{f.setup}</p>
+ <div className="grid gap-4 sm:grid-cols-2">
- <Field key={`${editing}-url`} setting={get(f.url)} label="URL" placeholder={f.urlPlaceholder} onSave={set(f.url)} />
- <Field key={`${editing}-model`} setting={get(f.model)} label="Model" hint={f.modelHint} options={status?.models.map((m) => m.id)} onSave={set(f.model)} />
++ <ConnectField key={`${editing}-url`} name={f.url} setting={get(f.url)} provider="llm" label="URL" placeholder={f.urlPlaceholder} hint={f.urlHint} />
++ <ConnectField
++ key={`${editing}-model`}
++ name={f.model}
++ setting={get(f.model)}
++ provider="llm"
++ label="Model"
++ placeholder={f.modelPlaceholder}
++ hint={f.modelHint}
++ options={status?.models.map((m) => m.id)}
++ />
+ </div>
- {f.key && <Field key={`${editing}-key`} setting={get(f.key)} label={f.keyLabel ?? "API key"} placeholder={f.keyPlaceholder} onSave={set(f.key)} />}
++ {f.key && <ConnectField key={`${editing}-key`} name={f.key} setting={get(f.key)} provider="llm" label={f.keyLabel ?? "API key"} placeholder={f.keyPlaceholder} hint="Only sent to this server." />}
+ {status?.problem && status.up && <p className="text-[12px] text-warning">{status.problem}</p>}
+ {status?.problem && !status.up && <p className="text-[12px] text-muted-foreground">{status.problem}</p>}
+ {status?.warning && !status.problem && <p className="text-[12px] text-warning">{status.warning}</p>}
+ <div className="flex flex-wrap items-center gap-2">
- <TestButton url="/api/llm" body={{ action: "test", kind: editing }} />
++ <TryReply key={editing} kind={editing} />
+ {smallContext && (
+ <Button variant="outline" size="sm" onClick={() => reload.mutate(status?.model ?? null)} disabled={reload.isPending}>
+ {reload.isPending && <Loader2 className="animate-spin" />} Reload with {k(want)} context
+ </Button>
+ )}
+ </div>
+ </div>
+
- <Field
++ <ConnectField
++ name="llmContext"
+ setting={get("llmContext")}
++ provider="llm"
++ saveOnly
+ label="Context (tokens)"
+ placeholder="16384"
+ hint="How much text the local model reads at once: Ollama gets it as num_ctx, and LM Studio loads models with it. Assist needs about 16,384. 0 leaves it to the server."
- onSave={set("llmContext")}
+ />
+ <p className="text-[12px] text-muted-foreground">The local model shares the GPU with ComfyUI. A 4–8B model leaves room for generations.</p>
+ </div>
+ );
+}
+
- export function SettingsForm() {
+ export function SettingsForm({ prices }: { prices?: string }) {
const qc = useQueryClient();
+ const router = useRouter();
const settings = useSettings();
+ const status = useStatus().data;
+ // The setup guide on request: the strip's "Setup guide", or a link to /settings#get-started (Home's demo line).
+ const [guide, setGuide] = useState<boolean | null>(null);
+ const askedByLink = useSyncExternalStore(subscribeHash, () => window.location.hash === "#get-started", () => false);
const save = useMutation({
mutationFn: async (patch: Record<string, string>) =>
(await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) })).json(),
@@@ -562,32 -335,45 +605,43 @@@
</Section>
<Section
- id="ai"
- title="AI helper"
- description="The LLM that writes for Fuobe: the Enhance toggle, storyboards, translations and scripts, ad copy, brand research, and the Assist agent. Use Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server: fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude."
+ id="loras"
+ title="LoRAs · looks, motions and effects"
+ description="Looks, camera moves and effects add LoRA files to open models, on your GPU and in the cloud. Fuobe fetches the pinned version a run needs and shows each file's licence; what may run where is your call in Models & licences."
>
- <div className="space-y-1.5">
- <Label htmlFor="setting-enhancer" className="text-[13px]">
- Use
- </Label>
- {/* "ollama" is the old name of "local". */}
- <Select value={(get("enhanceProvider")?.value || "auto").replace(/^ollama$/, "local")} onValueChange={set("enhanceProvider")}>
- <SelectTrigger id="setting-enhancer" className="w-full max-w-80">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="auto">Automatic (Claude → local model → offline)</SelectItem>
- <SelectItem value="anthropic">Claude (Anthropic API)</SelectItem>
- <SelectItem value="local">Local model only (open source)</SelectItem>
- <SelectItem value="none">Offline rewriter</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <Field setting={get("anthropicKey")} label="Anthropic API key" placeholder="sk-ant-…" onSave={set("anthropicKey")} />
+ <LoraSettings folder={get("comfyLorasDir")} civitaiKey={get("civitaiKey")} />
+ </Section>
+
+ <Section
+ id="text-ai"
- title="Prompt enhancement · Claude or Ollama"
- description="The Enhance toggle rewrites short ideas into rich prompts, and storyboards split stories into frames. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. Claude also powers the Assist agent. In Open source only mode, Automatic skips Claude."
++ title="AI helper · Claude or a local model"
++ description="The LLM that writes for Fuobe: the Enhance toggle, storyboards, translations and scripts, ad copy, brand research, and the Assist agent. Use Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server: fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude. Save & test checks a key or address before saving it."
+ >
+ <ChoiceField
+ id="setting-enhancer"
- label="Enhancer"
- value={get("enhanceProvider")?.value || "auto"}
++ label="Use"
++ // "ollama" is the old name of "local".
++ value={(get("enhanceProvider")?.value || "auto").replace(/^ollama$/, "local")}
+ onChange={set("enhanceProvider")}
+ options={[
- { value: "auto", label: "Automatic", hint: "Claude when a key is set, then Ollama, then the offline rewriter." },
++ { value: "auto", label: "Automatic", hint: "Claude when a key is set, then a local model, then the offline rewriter." },
+ { value: "anthropic", label: "Claude", hint: "Claude through your Anthropic key (paid per use)." },
- { value: "ollama", label: "Ollama", hint: "A local, open-source model through Ollama. Claude is never called." },
++ { value: "local", label: "Local model only", hint: "A local, open-source model (Ollama, LM Studio, Unsloth Studio or your own server). Claude is never called." },
+ { value: "none", label: "Offline rewriter", hint: "Built-in rules, no LLM. Text steps (translate, write) are off." },
+ ]}
+ />
+ <ConnectField name="anthropicKey" setting={get("anthropicKey")} provider="llm" label="Anthropic API key" placeholder="sk-ant-…" hint="Test checks the key with a free model list call." />
- <div className="grid gap-4 sm:grid-cols-2">
- <ConnectField name="ollamaUrl" setting={get("ollamaUrl")} provider="llm" label="Ollama URL" placeholder="http://127.0.0.1:11434" hint="Test checks Ollama answers and has the model." />
- <ConnectField name="ollamaModel" setting={get("ollamaModel")} provider="llm" label="Ollama model" placeholder="qwen3:8b" hint="Pull it first: ollama pull qwen3:8b" />
- </div>
+ <LocalLlmSettings get={get} set={set} />
</Section>
+ <Section
+ id="assist-connectors"
+ title="Assist · connectors"
+ description="Give Claude in Assist the tools of your other apps — docs, tasks, CRM, analytics — through their MCP servers (a URL and, usually, a token). Only Claude chats use them."
+ >
+ <ConnectorSettings claudeReady={!!get("anthropicKey")?.isSet} />
+ </Section>
+
<Section
id="notifications"
title="Notifications"
diff --cc src/components/studio/feed.tsx
index ed845710,736366f7..0bc9d292
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@@ -35,12 -38,19 +38,21 @@@ export function tileRatio(g: Generation
export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
const { cancel } = useGenerationActions();
+ // The clock runs between the job's reports (a fal queue or Higgsfield may report rarely).
+ const now = useNow(1000);
const pct = g.progress != null ? Math.round(g.progress * 100) : null;
const label = g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…");
+ // When progress moved (not every poll: each one rewrites updatedAt) gives the pace, so the time left.
+ // Keyed by id: a chain's tile moves on to its next step's generation.
+ const report = g.status === "running" ? g.progress : null;
+ const [track, setTrack] = useState(() => ({ id: g.id, pace: notePace(null, g.updatedAt, report) }));
+ const pace = track.id === g.id ? notePace(track.pace, g.updatedAt, report) : notePace(null, g.updatedAt, report);
+ if (track.id !== g.id || pace !== track.pace) setTrack({ id: g.id, pace });
+ const left = pace.first && pace.last ? timeLeft(pace.first, pace.last, now) : null;
return (
- <div className="relative h-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
+ // max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would
+ // otherwise make the tile wider than its column and spill over the next card.
+ <div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
<div className="skeleton-sweep absolute inset-0 animate-skeleton" />
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3">
<div className="min-w-0">
diff --cc src/components/studio/result-media.tsx
index b619acf0,40394baa..5c539002
--- a/src/components/studio/result-media.tsx
+++ b/src/components/studio/result-media.tsx
@@@ -1,11 -1,12 +1,13 @@@
"use client";
- import { AudioLines, Box, FileText, Layers } from "lucide-react";
+ import { AudioLines, Box, Download, FileText, Film, Layers } from "lucide-react";
import { createElement, useEffect, useState } from "react";
+import { loadModelViewer, useViewerSrc, viewerLook } from "@/components/model3d/model-viewer";
- import { viewerGlb } from "@/lib/av/model3d";
- import type { Generation, OutputFile } from "@/lib/catalog/types";
- import { cuesOf, cueTime, isLayered, layerInfo, modelPreview, textOf } from "@/lib/output-actions";
+ import { FORMAT_INFO } from "@/lib/av/formats";
-import { splatFormatOf } from "@/lib/av/model3d";
++import { splatFormatOf, viewerGlb } from "@/lib/av/model3d";
+ import type { Generation, OutputFile, VideoFormat } from "@/lib/catalog/types";
+ import { extensionOf } from "@/lib/library";
+ import { cuesOf, cueTime, editOnlyFormat, isLayered, layerInfo, modelPreview, textOf, videoPoster } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
/** Any result as a tile picture: image, video (plays on hover), audio, text card, 3D preview. */
@@@ -165,13 -196,11 +197,15 @@@ export function LayersStack({ g, classN
export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }) {
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
+ const [viewer, setViewer] = useState<HTMLElement | null>(null);
+ const splat = splatFormatOf(output);
+ // The web GLB (meshopt, WebP) when the server made one, else (older results, or if it fails to load) the original.
+ const src = useViewerSrc(viewer, viewerGlb(output), output.url);
+ const material = (output.meta?.finish as { material?: unknown } | undefined)?.material;
useEffect(() => {
+ if (splat) return;
let live = true;
- import("@google/model-viewer").then(
+ loadModelViewer().then(
() => live && setReady(true),
() => live && setFailed(true),
);
@@@ -190,16 -220,14 +225,17 @@@
);
}
return createElement("model-viewer", {
- src: output.url,
+ ref: setViewer,
+ src,
poster,
alt: g.request.prompt || "3D model",
+ loading: "lazy",
+ reveal: "auto",
"camera-controls": "",
- "auto-rotate": "",
++ // A rigged character plays its animation; a still model turns.
+ ...(output.meta?.rigged === true ? { autoplay: "" } : { "auto-rotate": "" }),
- "shadow-intensity": "1",
- exposure: "1",
"touch-action": "pan-y",
+ ...viewerLook(typeof material === "string" ? material : undefined),
style: { width: "100%", height: "100%", background: "transparent" },
});
}
diff --cc src/lib/api.ts
index c77ab591,799e0ce8..d78a1a01
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@@ -772,18 -811,31 +811,43 @@@ export interface StatusInfo
demoMode: string;
engineMode: EngineMode;
cloudProvider: string;
+ /** The text LLM: Settings → AI helper, whether Claude takes text steps, and the local model server in use. */
+ llm?: {
+ helper: "auto" | "anthropic" | "local" | "none";
+ claude: boolean;
+ /** Settings' local server: "auto" or the one pinned. */
+ provider: string;
+ context: number;
+ local: { kind: string; label: string; url: string; model: string | null; loaded: boolean | null; context: number | null; warning: string | null } | null;
+ /** Why no local server can run, when one says. */
+ problem: string | null;
+ detected: { kind: string; label: string; url: string; up: boolean; auth: string; models: number; model: string | null; problem: string | null }[];
+ };
+ /** The first-run guide was put away, or something the engine mode generates with was connected once. */
+ onboarded?: boolean;
+ /** Settings → Models & licences: what is switched off (absent while everything is on). */
+ access?: AccessSummary;
+ }
+
+ /** A connection test's answer (POST /api/providers/test). */
+ export interface ConnectionTest {
+ ok: boolean;
+ detail: string;
+ }
+
+ /**
+ * Test a provider, with unsaved values (by setting name) in place of the saved ones when given.
+ * `field` is the setting being checked (the Anthropic key, Ollama's address…), so the test checks that one.
+ */
+ export async function testConnection(provider: TestProvider, values?: Record<string, string>, field?: string): Promise<ConnectionTest> {
+ const res = await fetch("/api/providers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, values, field }) });
+ const body = (await res.json().catch(() => null)) as ConnectionTest | null;
+ return body && typeof body.ok === "boolean" ? body : { ok: false, detail: `The test didn't answer (${res.status})` };
+ }
+
+ /** Save settings by name (PUT /api/settings); throws the server's message when a value isn't allowed. */
+ export async function saveSettings(patch: Record<string, string>): Promise<void> {
+ await json(await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) }));
}
export function useStatus() {
diff --cc src/lib/assist-schedule.ts
index 00000000,b700a0de..db0002c9
mode 000000,100644..100644
--- a/src/lib/assist-schedule.ts
+++ b/src/lib/assist-schedule.ts
@@@ -1,0 -1,288 +1,288 @@@
+ /**
+ * Assist's scheduled tasks (Supercomputer's "Scheduled Tasks"): a prompt that runs as a new chat on
+ * the server's clock — daily, on some weekdays, every N hours or once — in an IANA time zone.
+ * Pure, so the server's sweep and the schedule dialog's "Next run" preview share it.
+ *
+ * Clock changes: a time a spring-forward skips runs as much later as the clocks jumped (02:30 on
+ * the night the clocks go 02:00 → 03:00 runs at 03:30); a time a fall-back repeats runs once, the
+ * first time. "Every N hours" counts real hours, so it doesn't move with the clocks.
+ */
+
+ export type ScheduleRule =
+ /** Every day at a wall-clock time ("09:00"). */
+ | { kind: "daily"; time: string }
+ /** Some weekdays (0 = Sunday … 6 = Saturday) at a wall-clock time. */
+ | { kind: "weekly"; days: number[]; time: string }
+ /** Every N real hours, counted from `from` (when the task was saved). */
+ | { kind: "hours"; every: number; from: number }
+ /** Once, at a wall-clock date and time ("2026-10-30T14:00"). */
+ | { kind: "once"; at: string };
+
+ /** Ask first: the plan waits in the chat as an approval card. Auto: plans run up to `capUsd` per run. */
+ export type ScheduleApproval = "ask" | "auto";
+
+ export const SCHEDULE_HOURS = [1, 2, 3, 4, 6, 8, 12, 24, 48, 72, 168] as const;
+ export const MAX_SCHEDULE_HOURS = 168;
+ export const MAX_SCHEDULE_PROMPT = 4000;
+ /** The most a run may spend on its own, per run. */
+ export const MAX_SCHEDULE_CAP_USD = 500;
+ export const DEFAULT_SCHEDULE_CAP_USD = 2;
+
+ /** A scheduled task as the UI sees it. */
+ export interface ScheduleView {
+ id: string;
+ title: string;
+ prompt: string;
+ attachments: string[];
+ projectId: string | null;
+ rule: ScheduleRule;
+ tz: string;
+ approval: ScheduleApproval;
+ capUsd: number | null;
+ engine: "cloud" | "open";
- /** The mode choice runs start with (null: the default from Settings). */
- mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "ollama" | "offline"; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;
++ /** The mode choice runs start with (null: the default from Settings). The local agent is "local"; tasks saved before LM Studio and Unsloth Studio support say "ollama" (read as "local"). */
++ mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "local" | "ollama" | "offline"; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;
+ /** Whether runs may use the connectors in Settings (Claude runs only). Their tools run without asking, so it's off unless the task opts in. */
+ connectors: boolean;
+ paused: boolean;
+ /** When it runs next (null: paused, or a one-off that has run). */
+ nextRunAt: number | null;
+ lastRunAt: number | null;
+ last: ScheduleResult | null;
+ runs: number;
+ createdAt: number;
+ updatedAt: number;
+ }
+
+ /** How the last run went, read live from its chat. */
+ export interface ScheduleResult {
+ threadId: string | null;
+ /** running: still going; waiting: a plan waits for approval; done: finished; failed: an error stopped it; skipped: the run before was still going. */
+ status: "running" | "waiting" | "done" | "failed" | "skipped";
+ /** Results it started, a short reason, or the error. */
+ text: string;
+ }
+
+ const TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;
+ const LOCAL = /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;
+
+ /** Whether this runtime knows the IANA zone ("Europe/Berlin"). */
+ export function validTimeZone(tz: string): boolean {
+ if (!tz || tz.length > 64) return false;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /** The rule's problem in words, or null when it's valid. */
+ export function ruleError(rule: ScheduleRule): string | null {
+ switch (rule.kind) {
+ case "daily":
+ return TIME.test(rule.time) ? null : "Pick a time";
+ case "weekly":
+ if (!rule.days.length || rule.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6)) return "Pick at least one day";
+ return TIME.test(rule.time) ? null : "Pick a time";
+ case "hours":
+ return Number.isInteger(rule.every) && rule.every >= 1 && rule.every <= MAX_SCHEDULE_HOURS ? null : `Every 1 to ${MAX_SCHEDULE_HOURS} hours`;
+ case "once": {
+ const m = LOCAL.exec(rule.at);
+ if (!m) return "Pick a date and time";
+ const [, y, mo, d] = m.map(Number);
+ const date = new Date(Date.UTC(y, mo - 1, d));
+ return date.getUTCMonth() === mo - 1 && date.getUTCDate() === d ? null : "Pick a real date";
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Wall clocks in a time zone (Intl only: no time-zone library)
+
+ const formatters = new Map<string, Intl.DateTimeFormat>();
+ function formatter(tz: string): Intl.DateTimeFormat {
+ let f = formatters.get(tz);
+ if (!f) {
+ f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
+ formatters.set(tz, f);
+ }
+ return f;
+ }
+
+ export interface WallClock {
+ y: number;
+ mo: number;
+ d: number;
+ h: number;
+ mi: number;
+ /** 0 = Sunday. */
+ weekday: number;
+ }
+
+ function clockParts(ms: number, tz: string): WallClock & { s: number } {
+ const p = Object.fromEntries(formatter(tz).formatToParts(new Date(ms)).map((x) => [x.type, x.value]));
+ const y = Number(p.year);
+ const mo = Number(p.month);
+ const d = Number(p.day);
+ return { y, mo, d, h: Number(p.hour) % 24, mi: Number(p.minute), s: Number(p.second), weekday: new Date(Date.UTC(y, mo - 1, d)).getUTCDay() };
+ }
+
+ /** The date and time a clock in `tz` shows at the instant `ms`. */
+ export function wallClock(ms: number, tz: string): WallClock {
+ const { y, mo, d, h, mi, weekday } = clockParts(ms, tz);
+ return { y, mo, d, h, mi, weekday };
+ }
+
+ /** Minutes `tz` is ahead of UTC at the instant `ms`. */
+ function offsetMinutes(ms: number, tz: string): number {
+ const w = clockParts(ms, tz);
+ return Math.round((Date.UTC(w.y, w.mo - 1, w.d, w.h, w.mi, w.s) - Math.floor(ms / 1000) * 1000) / 60_000);
+ }
+
+ const sameWall = (ms: number, tz: string, y: number, mo: number, d: number, h: number, mi: number) => {
+ const w = wallClock(ms, tz);
+ return w.y === y && w.mo === mo && w.d === d && w.h === h && w.mi === mi;
+ };
+
+ /**
+ * The instant a clock in `tz` shows this date and time. A repeated time (fall-back) gives its first
+ * instant; a skipped one (spring-forward) gives the instant as late as the clocks jumped.
+ */
+ export function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number {
+ const guess = Date.UTC(y, mo - 1, d, h, mi);
+ const DAY = 86_400_000;
+ // The offsets a day either side cover any clock change near this time.
+ const before = offsetMinutes(guess - DAY, tz);
+ const after = offsetMinutes(guess + DAY, tz);
+ const candidates = [...new Set([guess - before * 60_000, guess - after * 60_000])].filter((t) => sameWall(t, tz, y, mo, d, h, mi));
+ if (candidates.length) return Math.min(...candidates);
+ // Skipped: read the time with the offset from before the jump.
+ return guess - before * 60_000;
+ }
+
+ const parseTime = (t: string) => t.split(":").map(Number) as [number, number];
+
+ /** The calendar day `k` days after y-mo-d. */
+ function addDays(y: number, mo: number, d: number, k: number): { y: number; mo: number; d: number; weekday: number } {
+ const t = new Date(Date.UTC(y, mo - 1, d + k));
+ return { y: t.getUTCFullYear(), mo: t.getUTCMonth() + 1, d: t.getUTCDate(), weekday: t.getUTCDay() };
+ }
+
+ /** When the rule runs next, strictly after `after` (null: a one-off whose time has passed, or a broken rule). */
+ export function nextRun(rule: ScheduleRule, tz: string, after: number): number | null {
+ if (ruleError(rule) || !validTimeZone(tz)) return null;
+ switch (rule.kind) {
+ case "hours": {
+ const period = rule.every * 3_600_000;
+ if (after < rule.from) return rule.from + period;
+ return rule.from + (Math.floor((after - rule.from) / period) + 1) * period;
+ }
+ case "once": {
+ const [, y, mo, d, h, mi] = LOCAL.exec(rule.at)!.map(Number);
+ const at = zonedToUtc(y, mo, d, h, mi, tz);
+ return at > after ? at : null;
+ }
+ case "daily":
+ case "weekly": {
+ const [h, mi] = parseTime(rule.time);
+ const today = wallClock(after, tz);
+ // A day back covers a time a clock change moved past midnight; 8 ahead covers a weekly rule.
+ for (let k = -1; k <= 8; k++) {
+ const day = addDays(today.y, today.mo, today.d, k);
+ if (rule.kind === "weekly" && !rule.days.includes(day.weekday)) continue;
+ const at = zonedToUtc(day.y, day.mo, day.d, h, mi, tz);
+ if (at > after) return at;
+ }
+ return null;
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Words
+
+ export const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
+ /** Monday first, as the day picker shows them. */
+ export const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
+
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+ function dayList(days: number[]): string {
+ const set = [...new Set(days)].sort((a, b) => WEEK_ORDER.indexOf(a as 0) - WEEK_ORDER.indexOf(b as 0));
+ if (set.length === 7) return "Every day";
+ if (set.length === 5 && [1, 2, 3, 4, 5].every((d) => set.includes(d))) return "Weekdays";
+ if (set.length === 2 && set.includes(0) && set.includes(6)) return "Weekends";
+ const names = set.map((d) => `${WEEKDAYS[d]}s`);
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
+ }
+
+ /** "Every day at 09:00", "Mondays and Thursdays at 18:30", "Every 6 hours", "Once, 30 Oct 2026 at 14:00". */
+ export function describeRule(rule: ScheduleRule): string {
+ switch (rule.kind) {
+ case "daily":
+ return `Every day at ${rule.time}`;
+ case "weekly":
+ return `${dayList(rule.days)} at ${rule.time}`;
+ case "hours":
+ return rule.every === 1 ? "Every hour" : rule.every % 24 === 0 && rule.every > 24 ? `Every ${rule.every / 24} days` : `Every ${rule.every} hours`;
+ case "once": {
+ const m = LOCAL.exec(rule.at);
+ if (!m) return "Once";
+ return `Once, ${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]} at ${m[4]}:${m[5]}`;
+ }
+ }
+ }
+
+ /** "Tue 28 Oct, 09:00" in the task's zone. */
+ export function formatWhen(ms: number, tz: string): string {
+ const w = wallClock(ms, tz);
+ return `${WEEKDAYS[w.weekday].slice(0, 3)} ${w.d} ${MONTHS[w.mo - 1]}, ${String(w.h).padStart(2, "0")}:${String(w.mi).padStart(2, "0")}`;
+ }
+
+ /** "in 5 min", "in 3 h", "in 2 days" (or "now" when it's due). */
+ export function untilText(ms: number, now: number): string {
+ const s = Math.round((ms - now) / 1000);
+ if (s < 60) return "now";
+ if (s < 3600) return `in ${Math.round(s / 60)} min`;
+ if (s < 86_400 * 2) return `in ${Math.round(s / 3600)} h`;
+ return `in ${Math.round(s / 86_400)} days`;
+ }
+
+ /** A short zone label: "Europe/Berlin (GMT+1)". */
+ export function zoneLabel(tz: string, at = Date.now()): string {
+ try {
+ const name = new Intl.DateTimeFormat("en-US", { timeZone: tz, timeZoneName: "shortOffset" }).formatToParts(new Date(at)).find((p) => p.type === "timeZoneName")?.value;
+ return name ? `${tz.replace(/_/g, " ")} (${name})` : tz;
+ } catch {
+ return tz;
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Spending: what a scheduled run may start on its own
+
+ /**
+ * Whether an auto-run plan priced `price` may start without asking, when this run has already
+ * spent `spent` of `cap` (both USD). No cap: anything runs (a chat with Ask first off). An unknown
+ * price, or one that would pass the cap, waits for the user, with the reason.
+ */
+ export function withinCap(cap: number | null, spent: number, price: number | null): { ok: true } | { ok: false; reason: string } {
+ if (cap === null) return { ok: true };
+ if (price === null) return { ok: false, reason: "its price isn't known in advance" };
+ if (spent + price > cap + 1e-9) {
+ const left = Math.max(0, cap - spent);
+ return { ok: false, reason: `it costs about $${price.toFixed(2)} and this run has $${left.toFixed(2)} left of its $${cap.toFixed(2)} cap` };
+ }
+ return { ok: true };
+ }
+
+ /**
+ * What a plan would really spend: demo jobs cost nothing and jobs that can't run don't start; null
+ * when a job that would run for real has no price.
+ */
+ export function spendOf(jobs: { costUsd: number | null; demo: boolean; error?: string }[]): number | null {
+ const real = jobs.filter((j) => !j.demo && !j.error);
+ if (real.some((j) => j.costUsd === null)) return null;
+ return Math.round(real.reduce((n, j) => n + (j.costUsd ?? 0), 0) * 1000) / 1000;
+ }
diff --cc src/lib/av/model3d.ts
index e557a600,5d4ac046..33bcc2b6
--- a/src/lib/av/model3d.ts
+++ b/src/lib/av/model3d.ts
@@@ -1,52 -1,183 +1,201 @@@
- import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+ import type { Engine, Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";
/**
- * Image to 3D / Product spin: which model, and what a finished job gives the viewer — the .glb (and its
- * lighter web GLB), a turntable video (the server renders one for open models when it can; otherwise the
- * page records one in the browser), a poster, the source photo — and where "Animate the spin" goes next.
+ * Image to 3D / Product spin: the modes (from an image, from several images, from text, pick an object, a splat),
- * which model each runs on per engine, and what a finished job gives the viewer — the .glb (or the splat), a
- * turntable video (TRELLIS.2 and TripoSplat render one; for models that return only a mesh the page records one
- * in the browser), a poster, the source photo — and where "Animate the spin" and "Rig & animate" go next.
++ * which model each runs on per engine, and what a finished job gives the viewer — the .glb (and its lighter web
++ * GLB) or the splat, a turntable video (the server renders one for open 3D models when it can, TripoSplat renders
++ * its own orbit; otherwise the page records one in the browser), a poster, the source photo — and where
++ * "Animate the spin" and "Rig & animate" go next.
*/
export const MODEL3D_FEATURE = "image-to-3d";
+ /** The helper steps of a chain (the open text-to-3D still): kept out of the page's results and the Library. */
+ export const MODEL3D_STEP_FEATURE = "image-to-3d-step";
- export const MODELS_3D: Record<Engine, { id: string; note: string }[]> = {
- cloud: [
- { id: "hunyuan-3d-3-1-pro", note: "Textured, game-ready · ≈ $0.38" },
- { id: "hunyuan-3d-3-1-rapid", note: "Faster single view · ≈ $0.23" },
- { id: "trellis-2", note: "Detailed geometry · ≈ $0.30" },
- { id: "tripo-h3-1", note: "Clean topology, PBR · ≈ $0.30" },
- { id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },
- ],
- open: [
- { id: "oss-pixal3d", note: "Most faithful to the photo · textured GLB + turntable video · 16 GB GPU" },
- { id: "oss-trellis2", note: "Fallback · textured GLB + turntable video · 16 GB GPU · MIT" },
- { id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },
- ],
+ export type Model3dMode = "image" | "multi" | "text" | "objects" | "splat";
+
+ export const MODEL3D_MODES: { id: Model3dMode; label: string; hint: string }[] = [
+ { id: "image", label: "From an image", hint: "One clear photo of one object" },
+ { id: "multi", label: "From several images", hint: "2–4 photos of the same object from different sides" },
+ { id: "text", label: "From text", hint: "Describe one object" },
+ { id: "objects", label: "Pick an object", hint: "Name what to take out of a photo" },
+ { id: "splat", label: "Splat", hint: "A Gaussian splat of the subject" },
+ ];
+
+ export interface Model3dChoice {
+ id: string;
+ note: string;
+ }
+
+ /** The models each mode offers, the default first. Pick an object has no open model (SAM 3D Objects is cloud only). */
+ export const MODELS_3D: Record<Model3dMode, Record<Engine, Model3dChoice[]>> = {
+ image: {
+ cloud: [
+ { id: "hunyuan-3d-3-1-pro", note: "Textured, game-ready · ≈ $0.38" },
+ { id: "hunyuan-3d-3-1-rapid", note: "Faster single view · ≈ $0.23" },
+ { id: "trellis-2", note: "Detailed geometry · ≈ $0.30" },
+ { id: "tripo-h3-1", note: "Clean topology, PBR · ≈ $0.30" },
+ { id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },
+ ],
+ open: [
- { id: "oss-trellis2", note: "Textured GLB + turntable video · 16 GB GPU · MIT" },
++ { id: "oss-pixal3d", note: "Most faithful to the photo · textured GLB + turntable video · 16 GB GPU" },
++ { id: "oss-trellis2", note: "Fallback · textured GLB + turntable video · 16 GB GPU · MIT" },
+ { id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },
+ ],
+ },
+ multi: {
+ cloud: [{ id: "meshy-7-1-multi", note: "Textured, from 2–4 photos · ≈ $1.20" }],
+ open: [{ id: "oss-trellis2-multi", note: "The front plus up to 3 sides · textured GLB + turntable · 16 GB GPU · MIT" }],
+ },
+ text: {
+ cloud: [{ id: "tripo-h3-1-text", note: "A textured model from words · ≈ $0.20" }],
+ open: [{ id: "oss-text-trellis2", note: "Draws the object, then builds it · textured GLB + turntable · 16 GB GPU" }],
+ },
+ objects: {
+ cloud: [{ id: "sam-3d-objects", note: "Rebuilds what you name, as it stands in the photo · ≈ $0.02" }],
+ open: [],
+ },
+ splat: {
+ cloud: [{ id: "triposplat", note: "The subject as a .ply splat · ≈ $0.05" }],
+ open: [{ id: "oss-triposplat", note: "The subject as a .spz splat + an orbit video · 8 GB GPU · MIT" }],
+ },
};
+ /**
+ * Notices cloud models need beside their results. The rule is the open engine's: a model that encodes the photo
+ * with DINOv3 carries "Built with DINOv3" wherever it runs, fal included. TripoSplat (its weights ship
+ * dino_v3_vit_h) and TRELLIS.2 (a DINOv3 ViT-L encoder, dino_v3_L_naf in Comfy-Org's repackage) do; Hunyuan3D,
+ * Tripo, Meshy and SAM 3D don't. Open models get theirs from their workflow's licence.
+ */
+ export const CLOUD_NOTICES: Record<string, string[]> = { triposplat: ["Built with DINOv3"], "trellis-2": ["Built with DINOv3"] };
+
+ /** Every model the page offers (⌘K's ?model= links land on its mode). */
+ export const ALL_MODELS_3D: Model3dChoice[] = Object.values(MODELS_3D).flatMap((m) => [...m.cloud, ...m.open]);
+
+ /** The mode and engine a model belongs to (a ?model= link). */
+ export function modeOf(id: string): { mode: Model3dMode; engine: Engine } | null {
+ for (const mode of Object.keys(MODELS_3D) as Model3dMode[]) {
+ for (const engine of ["cloud", "open"] as const) if (MODELS_3D[mode][engine].some((m) => m.id === id)) return { mode, engine };
+ }
+ return null;
+ }
+
+ /** The sides of an object, in the order the open multi-view graph takes them; the front is needed. */
+ export const VIEW_SIDES = ["front", "left", "back", "right"] as const;
+ export type ViewSide = (typeof VIEW_SIDES)[number];
+ export const SIDE_LABELS: Record<ViewSide, string> = { front: "Front", left: "Left side", back: "Back", right: "Right side" };
+ /**
+ * Left and right are the object's own, as Pixal3D's rig takes them (the left view's camera is 90° round from the
+ * front, on the side that is on your right as you face the front): said beside the slots.
+ */
+ export const SIDES_HINT = "Left and right are the object's own: facing its front, walk round to your right for its left side.";
+
+ /** What the user filled in: the photo (or photos by side), the words. */
+ export interface Model3dInput {
+ engine: Engine;
+ mode?: Model3dMode;
+ modelId?: string;
+ /** From an image, Pick an object, Splat. */
+ photo?: string;
+ /** From several images: the photos by side. */
+ views?: Partial<Record<ViewSide, string>>;
+ /** From text: the object; Pick an object: what to take out. */
+ prompt?: string;
+ }
+
+ /** The model for a mode and engine: the one picked when the mode offers it, else its default (null: none on that engine). */
+ export function model3dFor(mode: Model3dMode, engine: Engine, modelId?: string): string | null {
+ const list = MODELS_3D[mode][engine];
+ return (modelId && list.find((m) => m.id === modelId)?.id) || list[0]?.id || null;
+ }
+
+ export const MAX_3D_PROMPT = 600;
+ const NO_OPEN_OBJECTS = "Pick an object runs on SAM 3D Objects, a cloud model";
+
+ /** Why the request can't go yet, in the words the button shows (null: ready). */
+ export function model3dBlocker(i: Model3dInput): string | null {
+ const mode = i.mode ?? "image";
+ if (!model3dFor(mode, i.engine, i.modelId)) return NO_OPEN_OBJECTS;
+ if (mode === "multi") {
+ if (!i.views?.front) return "Add a photo of the front";
+ return VIEW_SIDES.filter((s) => i.views?.[s]).length < 2 ? "Add at least one more side" : null;
+ }
+ if (mode === "text") return i.prompt?.trim() ? null : "Describe the object";
+ if (!i.photo) return "Add a photo";
+ if (mode === "objects" && !i.prompt?.trim()) return "Name the object to take out";
+ return null;
+ }
+
+ /**
+ * The generation request for a mode. Several images go in side order (front, left, back, right); the open
+ * graph also gets their sides by name (params.extra.views), since a side may be missing. SAM 3D Objects
+ * always gets the words (its API reads "car" when there are none).
+ */
+ export function model3dRequest(i: Model3dInput): GenerationRequest {
+ const mode = i.mode ?? "image";
+ const modelId = model3dFor(mode, i.engine, i.modelId);
+ if (!modelId) throw new Error(NO_OPEN_OBJECTS);
+ const prompt = i.prompt?.trim().slice(0, MAX_3D_PROMPT) ?? "";
+ const base = { feature: MODEL3D_FEATURE, modelId };
+ const images = i.photo ? [i.photo] : [];
+ switch (mode) {
+ case "multi": {
+ const sides = VIEW_SIDES.filter((s) => i.views?.[s]);
+ return {
+ ...base,
+ op: "image-to-3d",
+ inputs: { images: sides.map((s) => i.views![s]!) },
+ ...(i.engine === "open" && { params: { extra: { views: [...sides] } } }),
+ };
+ }
+ case "text":
+ return { ...base, op: "text-to-3d", prompt };
+ case "objects":
+ return { ...base, op: "image-to-3d", prompt, inputs: { images } };
+ case "splat":
+ return { ...base, op: "splat", inputs: { images } };
+ default:
+ return { ...base, op: "image-to-3d", inputs: { images } };
+ }
+ }
+
+ /** The mode a job was made in (its card goes by it). */
+ export function modeOfRequest(r: Pick<GenerationRequest, "op" | "modelId" | "inputs">): Model3dMode {
+ if (r.op === "splat") return "splat";
+ if (r.op === "text-to-3d") return "text";
+ return modeOf(r.modelId)?.mode ?? ((r.inputs?.images?.length ?? 0) > 1 ? "multi" : "image");
+ }
+
+ /**
+ * The open text-to-3D still: one object, whole, centred on a plain background in soft light, which is
+ * what TRELLIS.2's cut-out and reconstruction want.
+ */
+ export function stillPromptFor3d(prompt: string): string {
+ const words = prompt.trim().replace(/[.\s]+$/, "");
+ return `${words}. A single object, whole and centred, seen from the front at eye level, on a plain light grey background, soft even studio light, no other objects, no text`;
+ }
+
+/**
+ * The GLB a viewer should load: the web GLB the server made after the job (meshopt geometry, WebP
+ * textures, pivot at the bottom; meta.web), else the original — results made before that keep working.
+ */
+export function viewerGlb(o: { url: string; meta?: Record<string, unknown> }): string {
+ const web = o.meta?.web;
+ return typeof web === "string" && web ? web : o.url;
+}
+
- export function model3dRequest(o: { engine: Engine; photo: string; modelId?: string }): GenerationRequest {
- const id = o.modelId && MODELS_3D[o.engine].some((m) => m.id === o.modelId) ? o.modelId : MODELS_3D[o.engine][0].id;
- return { feature: MODEL3D_FEATURE, modelId: id, op: "image-to-3d", inputs: { images: [o.photo] } };
- }
-
export interface Model3dView {
+ /** The original GLB (the download). */
glb?: string;
+ /** The GLB to show in a viewer: the web GLB when there is one, else `glb`. */
+ web?: string;
- /** A rendered turntable that came with the model (the server's render for open models, demo). */
+ /** A Gaussian splat (.ply / .spz / .ksplat), which the page doesn't draw: downloaded, with its turntable or preview shown. */
+ splat?: { url: string; format: string };
- /** A rendered turntable that came with the model (TRELLIS.2, TripoSplat on the open engine, demo). */
++ /** A rendered turntable that came with the model (the server's render for open 3D models, TripoSplat's orbit on the open engine, demo). */
turntable?: string;
+ /** The server is still rendering the turntable (after the job finished): waiting its turn, or how far (0-1). */
+ rendering?: { queued: boolean; progress: number };
+ /** The material class the server's finish read from the textures (matte, metal, mixed, unknown). */
+ material?: string;
poster?: string;
/** The product photo it was made from. */
photo?: string;
@@@ -65,12 -217,12 +237,15 @@@ export function model3dView(g: Pick<Gen
const formats: Record<string, string> = {};
const listed = meta.formats;
if (listed && typeof listed === "object") for (const [k, v] of Object.entries(listed as Record<string, unknown>)) if (typeof v === "string") formats[k.toLowerCase()] = v;
+ const format = splatFormatOf(mesh);
+ const splat = mesh && format ? { url: mesh.url, format } : undefined;
return {
- glb: mesh?.url,
- web: mesh ? viewerGlb(mesh) : undefined,
+ glb: splat ? undefined : mesh?.url,
++ web: mesh && !splat ? viewerGlb(mesh) : undefined,
+ splat,
turntable: str(meta.turntable) ?? str(meta.video) ?? video?.url,
+ rendering: pending ? { queued: finish.turntable === "queued", progress: typeof finish.turntableProgress === "number" ? finish.turntableProgress : 0 } : undefined,
+ material: str(finish.material),
poster: str(meta.preview) ?? str(meta.poster) ?? g.outputs.find((o) => o.kind === "image")?.url,
photo: g.request.inputs?.images?.[0],
formats,
diff --cc src/lib/catalog/models.ts
index 1ff72ec7,f4ce28c8..f7311a6a
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@@ -1040,20 -1242,53 +1242,66 @@@ const open: ModelDef[] =
options: {},
hidden: true,
}),
- // Product 3D, try-on. Every image-to-3D route on ComfyUI (Pixal3D, TRELLIS.2, Hunyuan3D 2.1) ends in the
+ // Faceless / Explainer "Frame by frame" and the Audio hub's Loop / extend and Join (r4/faceless-plus): core nodes, no model.
+ o({
+ id: "oss-ken-burns",
+ name: "Ken Burns",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "video",
+ tagline: "A slow pan and zoom over a still, up to 10 s a clip · no model, runs on CPU",
+ routes: [comfy("still-motion", "kenburns-still", "zoom + pan, eased or linear; 10 s per job, longer scenes are split and joined")],
+ options: { aspectRatios: VID_AR, resolutions: ["480p", "720p", "1080p"], maxImages: 1, promptless: true },
+ defaults: { aspectRatio: "16:9", resolution: "720p" },
+ hidden: true,
+ }),
+ o({
+ id: "oss-join-encoded",
+ name: "Join clips (copy)",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "video",
+ tagline: "Joins clips the open engine made, packet by packet: no decode, flat memory · CPU",
+ routes: [comfy("concat", "video-concat-encoded", "one loader per clip; the clips share one size and frame rate")],
+ options: {},
+ hidden: true,
+ }),
+ o({
+ id: "oss-audio-loop",
+ name: "Crossfade loop",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "audio",
+ tagline: "Extends a clip to any length up to 10 minutes, crossfading every seam and fading out at the end · CPU",
+ routes: [comfy("audio-loop", "audio-loop-crossfade", "equal-power seams; the fade curve is written per job")],
+ options: { promptless: true },
+ hidden: true,
+ }),
+ o({
+ id: "oss-audio-join",
+ name: "Crossfade join",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "audio",
+ tagline: "Clips one after another with a crossfade at every seam · CPU",
+ routes: [comfy("audio-join", "audio-join-crossfade", "every clip in one job")],
+ options: { maxAudios: 10, promptless: true },
+ hidden: true,
+ }),
- // Product 3D, try-on
++ // Product 3D, try-on. Every image-to-3D route on ComfyUI (Pixal3D, TRELLIS.2 from one photo or several, Hunyuan3D 2.1) ends in the
+ // server's finish (src/server/model3d-finish.ts): a web GLB and, when Chromium and ffmpeg are there, a
+ // CPU-rendered turntable video.
+ o({
+ id: "oss-pixal3d",
+ name: "Pixal3D",
- vendor: "Pixal3D",
++ vendor: "Tencent ARC",
+ family: "trellis",
+ kind: "model3d",
+ tagline: "A textured 3D model (.glb) that stays true to your photo (camera-aware), plus a turntable video · 16 GB GPU",
+ badges: ["new", "top"],
+ routes: [comfy("image-to-3d", "image-to-3d-pixal3d", "MoGe-2 camera → Pixal3D; ~250k triangles; web GLB + turntable made after the job")],
+ options: { seed: true },
+ }),
o({
id: "oss-trellis2",
name: "TRELLIS.2",
diff --cc src/lib/catalog/types.ts
index 82d3e498,d5c2460e..ed0a62c1
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@@ -235,8 -245,8 +245,8 @@@ export interface FocusPoint
y: number;
}
-/** "llm" runs text steps (translate, write) on the configured LLM (Claude or Ollama) inside the server. */
+/** "llm" runs text steps (translate, write) on the configured LLM (Claude or a local model) inside the server. */
- export type ProviderId = "fal" | "replicate" | "higgsfield" | "openai" | "google" | "comfyui" | "mock" | "local" | "llm";
+ export type ProviderId = "fal" | "replicate" | "openai" | "google" | "comfyui" | "mock" | "local" | "llm";
/** Duration encodings differ between APIs ("5" vs 5 vs "5s"). */
export interface DurationField {
diff --cc src/lib/connections.ts
index 00000000,ef08214a..c5d1fede
mode 000000,100644..100644
--- a/src/lib/connections.ts
+++ b/src/lib/connections.ts
@@@ -1,0 -1,188 +1,211 @@@
+ /**
+ * Connecting Fuobe to models, as pure logic shared by Settings, Home's first-run guide and the
+ * connection test route: which settings each provider's test reads, what a well-formed key or
+ * address looks like, when to offer the first-run guide, and each connection's one-line status.
+ */
+
+ export type TestProvider = "fal" | "replicate" | "comfyui" | "llm" | "civitai";
+
+ /** The settings each provider's connection test reads; an unsaved value for one of them can be tested before it's saved. */
+ export const PROVIDER_SETTINGS = {
+ fal: ["falKey"],
+ replicate: ["replicateToken"],
+ comfyui: ["comfyUrl", "comfyToken", "comfyIsolatedUrl"],
- llm: ["anthropicKey", "ollamaUrl", "ollamaModel", "enhanceProvider"],
++ // Claude, and the local model servers of Settings → AI helper (Ollama, LM Studio, Unsloth Studio, any OpenAI-compatible one).
++ llm: [
++ "anthropicKey",
++ "ollamaUrl",
++ "ollamaModel",
++ "enhanceProvider",
++ "llmProvider",
++ "lmstudioUrl",
++ "lmstudioModel",
++ "lmstudioToken",
++ "unslothUrl",
++ "unslothModel",
++ "unslothKey",
++ "llmUrl",
++ "llmModel",
++ "llmKey",
++ "llmContext",
++ ],
+ // Not a model provider: the key that downloads a recipe's civitai LoRAs (Settings → LoRAs).
+ civitai: ["civitaiKey"],
+ } as const satisfies Record<TestProvider, readonly string[]>;
+
+ export type ConnectionSetting = (typeof PROVIDER_SETTINGS)[TestProvider][number];
+
+ export const isTestProvider = (p: unknown): p is TestProvider => typeof p === "string" && Object.hasOwn(PROVIDER_SETTINGS, p);
+
+ /**
+ * The unsaved values a test request carries, kept to the settings that provider's test reads:
+ * `values` by setting name, or `value` for the provider's main one (its key, or ComfyUI's address).
+ */
+ export function candidateValues(provider: TestProvider, values?: unknown, value?: unknown): Partial<Record<ConnectionSetting, string>> {
+ const allowed: readonly ConnectionSetting[] = PROVIDER_SETTINGS[provider];
+ const out: Partial<Record<ConnectionSetting, string>> = {};
+ if (typeof value === "string") out[allowed[0]] = value.trim();
+ if (values && typeof values === "object") {
+ for (const [k, v] of Object.entries(values)) if (typeof v === "string" && allowed.includes(k as ConnectionSetting)) out[k as ConnectionSetting] = v.trim();
+ }
+ return out;
+ }
+
+ /** Where to get a civitai API key (Settings → LoRAs links to it). */
+ export const CIVITAI_KEYS_URL = "https://civitai.com/user/account";
+ /** Where to get a fal.ai key (the guide and Settings link to it). */
+ export const FAL_KEYS_URL = "https://fal.ai/dashboard/keys";
+ /** The ComfyUI address a local install listens on. */
+ export const DEFAULT_COMFY_URL = "http://127.0.0.1:8188";
+ /** Fuobe's source, for the install scripts and licences. */
+ export const FUOBE_REPO = "https://github.com/workingprototype/fuobe";
+ /** How to install ComfyUI with every node pack Fuobe's workflows use. */
+ export const COMFY_INSTALL_DOCS = `${FUOBE_REPO}/blob/main/scripts/comfy/README.md`;
+ export const COMFY_INSTALL_COMMAND = "bash scripts/comfy/install-comfyui.sh";
+
+ /** key_id:key_secret, both halves present and no spaces. */
+ const KEY_PAIR = /^[^\s:]+:[^\s:]+$/;
+
+ function addressProblem(v: string, example: string): string | null {
+ try {
+ const u = new URL(v);
+ return u.protocol === "http:" || u.protocol === "https:" ? null : `Use an http:// or https:// address, like ${example}`;
+ } catch {
+ return /^[\w.-]+(:\d+)?(\/\S*)?$/.test(v) ? `Add http:// in front: http://${v}` : `That isn't a web address — try ${example}`;
+ }
+ }
+
+ /**
+ * What's wrong with a value typed into a connection field, said the way to fix it; null when it
+ * looks right (or is empty, which clears it). A warning only: the test has the final word.
+ */
+ export function settingProblem(name: string, raw: string): string | null {
+ const v = raw.trim();
+ if (!v) return null;
+ switch (name) {
+ case "falKey":
+ if (KEY_PAIR.test(v)) return null;
+ return v.includes(":") ? "Both halves of key_id:key_secret are needed, without spaces — copy the key again" : "fal.ai keys look like key_id:key_secret — paste the whole key, with the part after the colon";
+ case "replicateToken":
+ return /^r8_\S+$/.test(v) ? null : "Replicate tokens start with r8_";
+ case "anthropicKey":
+ return /^sk-ant-\S+$/.test(v) ? null : "Anthropic keys start with sk-ant-";
+ case "comfyUrl":
+ return addressProblem(v, DEFAULT_COMFY_URL);
+ case "comfyIsolatedUrl":
+ return addressProblem(v, "http://127.0.0.1:8189");
+ case "ollamaUrl":
+ return addressProblem(v, "http://127.0.0.1:11434");
++ case "lmstudioUrl":
++ return addressProblem(v, "http://127.0.0.1:1234");
++ case "unslothUrl":
++ return addressProblem(v, "http://127.0.0.1:8888");
++ case "llmUrl":
++ return addressProblem(v, "http://127.0.0.1:8080/v1");
+ }
+ return null;
+ }
+
+ // ---------------------------------------------------------------------------
+ // What's connected
+
+ export type EngineModeName = "both" | "open" | "cloud";
+
+ export interface ConnectionState {
+ providers: Record<string, { configured: boolean } | undefined>;
+ engineMode: EngineModeName;
+ /** The first-run guide was put away, or something this engine mode uses was connected once (Settings → `onboarded`). */
+ onboarded?: boolean;
+ /** Settings → Demo mode: auto (a demo when no provider hosts the model), on (always a demo), off (never). */
+ demoMode?: string;
+ }
+
+ const CLOUD_PROVIDERS = ["fal", "replicate"] as const;
+
+ /** Whether a paid API and ComfyUI are connected. */
+ export function connectedEngines(s: ConnectionState): { cloud: boolean; open: boolean } {
+ return { cloud: CLOUD_PROVIDERS.some((p) => s.providers[p]?.configured), open: !!s.providers.comfyui?.configured };
+ }
+
+ /** Nothing this install's engine mode uses is connected, so every run is a demo. */
+ export function nothingConnected(s: ConnectionState): boolean {
+ const c = connectedEngines(s);
+ return s.engineMode === "open" ? !c.open : s.engineMode === "cloud" ? !c.cloud : !c.cloud && !c.open;
+ }
+
+ /** The first-run guide shows until something is connected or it was put away. Unknown status: not yet. */
+ export function showFirstRun(s: ConnectionState | undefined): boolean {
+ return !!s && !s.onboarded && nothingConnected(s);
+ }
+
+ /** What Home's Start runs in a mode: the studio's default model on each engine, the providers that host it, and one run's price on the paid one. */
+ export interface StartQuote {
+ cloud: { name: string; price: string; providers: string[] } | null;
+ open: { name: string; providers: string[] } | null;
+ }
+
+ const PROVIDER_LABEL: Record<string, string> = { fal: "fal.ai", replicate: "Replicate", comfyui: "ComfyUI" };
+
+ /**
+ * The line under Home's composer, before Start is pressed: the model it runs and its price, or why
+ * it runs a free demo (no key for a provider that hosts that model, the same rule the composer's
+ * "Demo" label follows), plus the other engine when that one would run it for real. Null when
+ * nothing is connected: Home's demo notice says so instead.
+ */
+ export function startLine(s: ConnectionState, quote: StartQuote | undefined, engine: "cloud" | "open", mode: "image" | "video" | "edit"): { text: string; other?: "cloud" | "open" } | null {
+ if (!quote || nothingConnected(s)) return null;
+ if (s.demoMode === "on") return { text: "Demo mode is on (Settings), so Start runs a free demo" };
+ const hosted = (q: { providers: string[] } | null) => !!q && q.providers.some((p) => s.providers[p]?.configured);
+ const otherEngine = engine === "open" ? "cloud" : "open";
+ const other = s.engineMode === "both" && hosted(quote[otherEngine]) ? otherEngine : undefined;
+ const then = mode === "edit" ? " after you add the photo" : "";
+ if (engine === "open" && quote.open && hosted(quote.open)) return { text: `Start runs ${quote.open.name} on your GPU${then} · Free` };
+ if (engine === "cloud" && quote.cloud && hosted(quote.cloud)) return { text: `Start runs ${quote.cloud.name}${then} · ${quote.cloud.price}` };
+ const q = quote[engine];
+ const connected = connectedEngines(s)[engine];
+ const hosts = q ? q.providers.map((p) => PROVIDER_LABEL[p] ?? p).join(" or ") : "";
+ let why: string;
+ if (!connected) why = engine === "open" ? "ComfyUI isn't connected" : "No paid API is connected";
+ else why = q ? `${q.name} needs ${engine === "open" ? hosts : `a ${hosts} key`}` : "No model is set for this";
+ return { text: `${why}, so Start ${s.demoMode === "off" ? "can't run it yet" : "runs a free demo"}`, ...(other && { other }) };
+ }
+
+ /**
+ * This browser's last answer to showFirstRun ("1" or "0"). Home paints the guide in its static
+ * shell, before the status is known, so it doesn't push the page down when it arrives; the
+ * pre-paint script hides it there when this browser already knows it isn't wanted.
+ */
+ export const FIRST_RUN_KEY = "fuobe:first-run";
+
+ /** Runs while Home's HTML is parsed: `<html data-first-run="0">` when the guide was put away here before. */
+ export const FIRST_RUN_SCRIPT = `(function(){try{if(localStorage.getItem("${FIRST_RUN_KEY}")==="0")document.documentElement.setAttribute("data-first-run","0")}catch(e){}})()`;
+
+ export const ENGINE_MODE_LABEL: Record<EngineModeName, string> = { both: "Open source + paid", open: "Open source only", cloud: "Paid APIs only" };
+
+ export interface ConnectionItem {
+ id: "fal" | "replicate" | "comfyui" | "llm";
+ label: string;
+ ok: boolean;
+ /** "Key set", "Online", "Off"… */
+ text: string;
+ /** The Settings section to jump to. */
+ href: string;
+ /** The engine mode doesn't use it. */
+ unused: boolean;
+ }
+
+ /** One line per connection for Settings' status strip, in the order the page lists them. */
+ export function connectionSummary(s: ConnectionState): ConnectionItem[] {
+ const key = (id: "fal" | "replicate", label: string): ConnectionItem => {
+ const ok = !!s.providers[id]?.configured;
+ return { id, label, ok, text: ok ? "Key set" : "Not set", href: `#${id}`, unused: s.engineMode === "open" };
+ };
+ const comfy = !!s.providers.comfyui?.configured;
+ const llm = !!s.providers.llm?.configured;
+ return [
+ key("fal", "fal.ai"),
+ key("replicate", "Replicate"),
+ { id: "comfyui", label: "ComfyUI", ok: comfy, text: comfy ? "Online" : "Offline", href: "#comfyui", unused: s.engineMode === "cloud" },
- { id: "llm", label: "Claude / Ollama", ok: llm, text: llm ? "On" : "Off", href: "#text-ai", unused: false },
++ { id: "llm", label: "AI helper", ok: llm, text: llm ? "On" : "Off", href: "#text-ai", unused: false },
+ ];
+ }
diff --cc src/lib/licences.ts
index 00000000,f1690323..58345042
mode 000000,100644..100644
--- a/src/lib/licences.ts
+++ b/src/lib/licences.ts
@@@ -1,0 -1,458 +1,465 @@@
+ /*
+ * The About & licences page: the licence of every open model Fuobe can run, from the ComfyUI
+ * manifest's `license` field and the catalog's open models, with the catches a person should
+ * know before using the results commercially (non-commercial, countries excluded, conditions)
+ * and the notices some licences ask the app to show ("Built with DINOv3").
+ *
+ * Licence texts follow the manifest's convention: NON-COMMERCIAL in capitals when the weights
+ * (or a node pack's code) may not be used commercially, "territory EXCLUDES …" for countries a
+ * licence leaves out, and `show "…"` for a notice the app must display. A lower-case mention
+ * ("Base/Large are CC-BY-NC, keep the small one") describes a variant Fuobe does not use.
+ */
+
+ export type LicenceFlag = "non-commercial" | "territory" | "conditions";
+
+ /** The parts of a catalog model the list needs (the page passes ModelDefs). */
+ export interface LicenceModelInput {
+ id: string;
+ name: string;
+ vendor: string;
+ kind: string;
+ hidden?: boolean;
+ routes: { provider: string; endpoint: string }[];
+ }
+
+ /** The parts of a manifest workflow the list needs. */
+ export interface LicenceWorkflowInput {
+ id: string;
+ title: string;
+ capability: string;
+ license?: string;
+ }
+
+ export interface LicenceRow {
+ /** The model id, or the workflow id for a workflow no model uses yet. */
+ id: string;
+ name: string;
+ /** The vendor, or "Workflow library" for a workflow no studio uses yet. */
+ by: string;
+ kind: string;
+ workflows: string[];
+ /** Distinct licence texts of its workflows. */
+ licences: string[];
+ flags: LicenceFlag[];
+ /** Who a territory-restricted licence leaves out ("the EU, UK and South Korea"). */
+ excludes?: string;
+ notices: string[];
+ /** True when a studio, app or helper step runs it; false for a workflow only in the library. */
+ inCatalog: boolean;
+ }
+
+ export interface LicenceList {
+ rows: LicenceRow[];
+ /** Catalog tools that run on ComfyUI's own nodes, with no model weights. */
+ noWeights: string[];
+ /** Library workflows with no model weights that no studio uses yet. */
+ noWeightsLibrary: number;
+ /** Each notice and the models that need it. */
+ notices: { text: string; models: string[] }[];
+ counts: { all: number; clear: number } & Record<LicenceFlag, number>;
+ }
+
+ /**
+ * Licences of the workflows whose manifest entries predate the `license` field (rounds 1–2),
+ * from docs/research/comfyui-oss.md and the model cards. First match wins.
+ */
+ export const EARLIER_LICENCES: [RegExp, string][] = [
+ [/^flux1-schnell/, "Apache-2.0 (FLUX.1 [schnell])"],
+ [
+ /^flux1-(dev|krea|kontext|fill)/,
+ "FLUX.1 [dev] Non-Commercial License: NON-COMMERCIAL (outputs may be used commercially per BFL's terms; running the model in production needs a BFL commercial licence)",
+ ],
+ [/^flux2-dev/, "FLUX [dev] Non-Commercial License (FLUX.2 [dev]): NON-COMMERCIAL"],
+ [/^qwen-image/, "Apache-2.0 (Qwen-Image 2512 / Qwen-Image-Edit, Lightning LoRAs, Qwen2.5-VL text encoder)"],
+ [/^z-image/, "Apache-2.0 (Z-Image Turbo)"],
+ [/^hidream-i1/, 'MIT (HiDream-I1); its Llama 3.1 8B text encoder is under the Llama 3.1 Community License (show "Built with Llama")'],
+ [/^sdxl/, "CreativeML OpenRAIL++-M (commercial use allowed, with use-based restrictions)"],
+ [/esrgan/, "BSD-3-Clause (Real-ESRGAN x4plus)"],
+ [/seedvr2/, "Apache-2.0 (SeedVR2)"],
+ [/^bg-remove-birefnet/, "MIT (BiRefNet)"],
+ [/^bg-remove-rmbg/, "BEN2 weights MIT (the pack's default); RMBG-2.0 in the same pack is CC-BY-NC-4.0 (non-commercial), keep BEN2; ComfyUI-RMBG code GPL-3.0"],
+ [/^face-swap-reactor/, "inswapper_128 weights (InsightFace): NON-COMMERCIAL, research use only; ReActor node MIT; GFPGAN Apache-2.0"],
+ [/^wan22-i2v-14b-lora/, "Apache-2.0 (Wan 2.2); a LoRA you add carries its own licence"],
+ [/^wan-animate/, "Apache-2.0 (Wan Animate 2, lightx2v)"],
+ [/^wan22-/, "Apache-2.0 (Wan 2.2, umT5, lightx2v)"],
+ [/^hunyuan15/, "Tencent Hunyuan Community License (territory EXCLUDES the EU, UK and South Korea)"],
+ [/^ltx2/, "LTX-2.x Community License (free, commercial use included, below US$10M annual revenue; a paid licence above); Gemma 3 text encoder under the Gemma Terms of Use"],
+ [/^infinitetalk/, "Apache-2.0 (InfiniteTalk, Wan 2.1, lightx2v)"],
+ [/^interpolate-film/, "Apache-2.0 (FILM)"],
+ [/^interpolate-rife/, "MIT (RIFE)"],
+ [/^music-ace-step/, "Apache-2.0 (ACE-Step 1.5)"],
+ [/^v2a-mmaudio/, "CC-BY-NC-4.0 (MMAudio weights: NON-COMMERCIAL)"],
+ [/^selftest-/, "n/a (no model; ComfyUI core nodes)"],
+ ];
+
+ export const UNKNOWN_LICENCE = "Not recorded yet: check the model card before using it commercially";
+
+ /** A workflow's licence: the manifest's, else the earlier table's, else unknown. */
+ export function workflowLicence(wf: Pick<LicenceWorkflowInput, "id" | "license">): string {
+ return wf.license?.trim() || EARLIER_LICENCES.find(([re]) => re.test(wf.id))?.[1] || UNKNOWN_LICENCE;
+ }
+
+ /** What a licence text means for using the results: its flags, the countries it leaves out, its notices. */
+ export function licenceTerms(text: string): { flags: LicenceFlag[]; excludes?: string; notices: string[]; noWeights: boolean } {
+ const noWeights = /^(n\/a|no model)\b/i.test(text.trim());
+ const nonCommercial = /NON-COMMERCIAL/.test(text) || /^CC-BY-NC/.test(text.trim());
+ const excludes = /\bEXCLUDES\s+([^);]+)/.exec(text)?.[1].trim();
+ const conditional = /Community License|OpenRAIL|Model Use License|CogVideoX License|SAM License|DINOv3 License|Terms of Use|free below|below US\$/i.test(text);
+ const flags: LicenceFlag[] = [];
+ if (nonCommercial) flags.push("non-commercial");
+ if (excludes) flags.push("territory");
+ if (conditional && !nonCommercial && !excludes) flags.push("conditions");
+ const notices = [...text.matchAll(/show (?:a |the )?"([^"]+)"/g)].map((m) => m[1]);
+ return { flags, excludes, notices, noWeights };
+ }
+
+ /** Workflow ids an endpoint names: one id, or a family (`video-concat-{n}`). */
+ function endpointIds(endpoint: string, workflows: LicenceWorkflowInput[]): string[] {
+ if (!endpoint.includes("{")) return [endpoint];
+ const re = new RegExp(`^${endpoint.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{[^}]+\}/g, "\\d+")}$`);
+ return workflows.filter((w) => re.test(w.id)).map((w) => w.id);
+ }
+
+ function rowFor(base: Omit<LicenceRow, "licences" | "flags" | "excludes" | "notices">, licences: string[]): LicenceRow & { noWeights: boolean } {
+ const terms = licences.map(licenceTerms);
+ const flags = (["non-commercial", "territory", "conditions"] as const).filter((f) => terms.some((t) => t.flags.includes(f)));
+ return {
+ ...base,
+ licences,
+ // A row with a stricter catch doesn't also say "conditions".
+ flags: flags.includes("conditions") && flags.length > 1 ? flags.filter((f) => f !== "conditions") : flags,
+ excludes: terms.find((t) => t.excludes)?.excludes,
+ notices: [...new Set(terms.flatMap((t) => t.notices))],
+ noWeights: terms.every((t) => t.noWeights),
+ };
+ }
+
+ /**
+ * Every open model and its licence: one row per catalog model that runs on ComfyUI (in catalog
+ * order), then the library's workflows no model uses yet. Tools with no weights are listed by
+ * name only; ComfyUI's self-tests are left out.
+ */
+ export function buildLicenceList(models: LicenceModelInput[], workflows: LicenceWorkflowInput[]): LicenceList {
+ const byId = new Map(workflows.map((w) => [w.id, w]));
+ const used = new Set<string>();
+ const rows: LicenceRow[] = [];
+ const noWeights: string[] = [];
+ let noWeightsLibrary = 0;
+ const add = (r: LicenceRow & { noWeights: boolean }) => {
+ const { noWeights: none, ...row } = r;
+ if (!none) rows.push(row);
+ else if (row.inCatalog) noWeights.push(row.name);
+ else noWeightsLibrary++;
+ };
+
+ for (const m of models) {
+ const ids = [...new Set(m.routes.filter((r) => r.provider === "comfyui").flatMap((r) => endpointIds(r.endpoint, workflows)))];
+ if (!ids.length || ids.every((id) => id.startsWith("selftest-"))) continue;
+ ids.forEach((id) => used.add(id));
+ const licences = [...new Set(ids.map((id) => workflowLicence(byId.get(id) ?? { id })))];
+ add(rowFor({ id: m.id, name: m.name, by: m.vendor, kind: m.kind, workflows: ids, inCatalog: true }, licences));
+ }
+ for (const w of workflows) {
+ if (used.has(w.id) || w.id.startsWith("selftest-")) continue;
+ add(rowFor({ id: w.id, name: w.title, by: "Workflow library", kind: w.capability, workflows: [w.id], inCatalog: false }, [workflowLicence(w)]));
+ }
+
+ const notices = new Map<string, string[]>();
+ for (const r of rows) for (const n of r.notices) notices.set(n, [...(notices.get(n) ?? []), r.name]);
+ const count = (f: LicenceFlag) => rows.filter((r) => r.flags.includes(f)).length;
+ return {
+ rows,
+ noWeights: [...new Set(noWeights)],
+ noWeightsLibrary,
+ notices: [...notices].map(([text, names]) => ({ text, models: names })),
+ counts: { all: rows.length, clear: rows.filter((r) => !r.flags.length).length, "non-commercial": count("non-commercial"), territory: count("territory"), conditions: count("conditions") },
+ };
+ }
+
+ const KIND_LABEL: Record<string, string> = { image: "Image", video: "Video", audio: "Audio", text: "Text", model3d: "3D" };
+
+ /** A model's media kind, or a library workflow's capability, in words. */
+ export function kindLabel(kind: string): string {
+ return (
+ KIND_LABEL[kind] ??
+ kind
+ .replace(/-/g, " ")
+ .replace(/\b(vfx|ocr|tts|sfx|v2a|v2v|t2v|i2v|t2i|flf2v|3d)\b/g, (a) => a.toUpperCase())
+ .replace(/^\w/, (c) => c.toUpperCase())
+ );
+ }
+
+ export const FLAG_LABEL: Record<LicenceFlag, string> = {
+ "non-commercial": "Non-commercial",
+ territory: "Not everywhere",
+ conditions: "Conditions apply",
+ };
+
+ // ---------------------------------------------------------------------------
+ // Licence classes (Settings → Models & licences). The owner's decision of 2026-10-27: licences are
+ // information, never a gate. Every model, LoRA and node pack carries its licence as data, sorted into a
+ // class an admin can switch off; everything is on by default.
+
+ export type LicenceClass = "commercial" | "conditions" | "regions" | "non-commercial" | "research" | "paid-api" | "unknown";
+
+ /** In the order Settings lists them: the freest first, then the cloud's, then what isn't recorded. */
+ export const LICENCE_CLASSES: LicenceClass[] = ["commercial", "conditions", "regions", "non-commercial", "research", "paid-api", "unknown"];
+
+ export const CLASS_LABEL: Record<LicenceClass, string> = {
+ commercial: "Commercial use allowed",
+ conditions: "Commercial use with conditions",
+ regions: "Restricted regions",
+ "non-commercial": "Non-commercial",
+ research: "Research only",
+ "paid-api": "Proprietary paid API",
+ unknown: "Licence unknown",
+ };
+
+ /** What a class means, in one line (the section headers in Settings). */
+ export const CLASS_HINT: Record<LicenceClass, string> = {
+ commercial: "Open licences that let you sell what you make (Apache-2.0, MIT, BSD) and tools with no model weights.",
+ conditions: "Commercial use is allowed within limits: a revenue ceiling, registration, attribution or use rules.",
+ regions: "The licence leaves out some countries or regions.",
+ "non-commercial": "The weights or code may not be used commercially without another licence.",
+ research: "Released for research only.",
+ "paid-api": "Closed or hosted models you pay for per run, under the provider's and the vendor's terms.",
+ unknown: "No licence is recorded yet: check the model card or repository.",
+ };
+
+ /** A model's, LoRA's or node pack's licence, as information. */
+ export interface LicenceInfo {
+ /** The licence's name ("Apache-2.0", "FLUX.1 [dev] Non-Commercial License", "fal.ai · paid API"). */
+ name: string;
+ /** Where to read it: the licence text, or the model card / repository that states it. */
+ url?: string;
+ class: LicenceClass;
+ /** Restricted regions: who it leaves out ("the EU, UK and South Korea"). */
+ excludes?: string;
+ /** One line: the licence as recorded (what it covers, its catches). */
+ note: string;
+ /** Notices the app must show ("Built with DINOv3"). */
+ notices?: string[];
+ }
+
+ /** How strict a class is, for a model whose parts carry several licences (the strictest one counts). */
+ const STRICTNESS: Record<LicenceClass, number> = { commercial: 0, "paid-api": 1, conditions: 2, unknown: 3, regions: 4, "non-commercial": 5, research: 6 };
+
+ export const stricter = (a: LicenceClass, b: LicenceClass): LicenceClass => (STRICTNESS[b] > STRICTNESS[a] ? b : a);
+
+ const SPDX = (id: string) => `https://spdx.org/licenses/${id}.html`;
+
+ /**
+ * Licences by name, with the class each one puts a model in and where to read it. Order matters: a text
+ * names a model's licence by the first entry of its class it mentions (a text with Apache-2.0 weights and
+ * the CogVideoX base is the CogVideoX License's).
+ */
+ const KNOWN: { re: RegExp; name: string; class: LicenceClass; url?: string }[] = [
+ { re: /FLUX\.1 \[dev\] Non-Commercial License|FLUX\.1 \[dev\] base is NON-COMMERCIAL/, name: "FLUX.1 [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.1-dev" },
+ { re: /FLUX \[dev\] Non-Commercial License/, name: "FLUX [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.2-dev" },
+ { re: /inswapper/, name: "InsightFace inswapper (research only)", class: "research", url: "https://github.com/deepinsight/insightface" },
+ { re: /CC-BY-NC-SA-4\.0/, name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0") },
+ { re: /CC[- ]BY[- ]NC(?:[- ]4\.0)?\b/, name: "CC BY-NC 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-4.0") },
+ { re: /Tencent Hunyuan 3D 2\.1 Community License/, name: "Tencent Hunyuan 3D 2.1 Community License", class: "regions" },
+ { re: /Tencent Hunyuan Community License/, name: "Tencent Hunyuan Community License", class: "regions" },
+ { re: /CogVideoX License/, name: "CogVideoX License", class: "conditions" },
+ { re: /LTX-2(?:\.x)? Community License/, name: "LTX-2 Community License", class: "conditions" },
+ { re: /Stability AI Community License|Stability Community License/, name: "Stability AI Community License", class: "conditions", url: "https://stability.ai/community-license-agreement" },
+ { re: /Krea 2 Community License/, name: "Krea 2 Community License", class: "conditions" },
+ { re: /IndexTTS-2 Model Use License/, name: "bilibili IndexTTS-2 Model Use License", class: "conditions" },
+ { re: /Llama 3\.1 Community License/, name: "Llama 3.1 Community License", class: "conditions", url: "https://www.llama.com/llama3_1/license/" },
+ { re: /DINOv3 License/, name: "DINOv3 License", class: "conditions" },
+ // Before SAM's: the H3 workflows' text names both, and the territory catch is the one that counts.
+ { re: /MiniMax H3 Community License/, name: "MiniMax H3 Community License", class: "regions", url: "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/42ed227ee7df40d41602854ae760620d6eb651fe/LICENSE" },
+ { re: /SAM License/, name: "Meta SAM License", class: "conditions" },
+ { re: /OpenRAIL\+\+-M/, name: "CreativeML OpenRAIL++-M", class: "conditions" },
+ { re: /OpenRAIL-M/, name: "CreativeML OpenRAIL-M", class: "conditions", url: SPDX("CreativeML-OpenRAIL-M") },
+ { re: /Gemma Terms of Use/, name: "Gemma Terms of Use", class: "conditions", url: "https://ai.google.dev/gemma/terms" },
+ { re: /Apache[- ]2\.0/, name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0") },
+ { re: /\bMIT\b/, name: "MIT", class: "commercial", url: SPDX("MIT") },
+ { re: /BSD-3-Clause/, name: "BSD-3-Clause", class: "commercial", url: SPDX("BSD-3-Clause") },
+ ];
+
+ /** ComfyUI's own licence: the tools with no model weights run on its nodes. */
+ const COMFYUI_REPO = "https://github.com/comfyanonymous/ComfyUI";
+
+ /** A Hugging Face download's repository page, where its licence is stated. */
+ export function modelCardOf(url: string | undefined): string | undefined {
+ const m = url && /^https:\/\/huggingface\.co\/([^/]+\/[^/]+)\/(?:resolve|blob)\//.exec(url);
+ return m ? `https://huggingface.co/${m[1]}` : undefined;
+ }
+
+ /**
+ * What a recorded licence text means as information: its class, a short name, where to read it. `cards` are
+ * the model downloads it covers (the largest first): their Hugging Face page is the link when the licence
+ * has no page of its own.
+ */
+ export function licenceInfo(text: string, cards: string[] = []): LicenceInfo {
+ const terms = licenceTerms(text);
+ const card = cards.map(modelCardOf).find(Boolean);
+ if (text === UNKNOWN_LICENCE) return { name: "Not recorded", class: "unknown", note: text, ...(card && { url: card }) };
+ if (terms.noWeights) return { name: "No model weights", class: "commercial", url: COMFYUI_REPO, note: `${text.replace(/^n\/a \((.*)\)$/, "$1")}: ComfyUI's own nodes (GPL-3.0) or FFmpeg` };
+ const cls: LicenceClass = terms.flags.includes("non-commercial")
+ ? /research (?:use )?only/i.test(text)
+ ? "research"
+ : "non-commercial"
+ : terms.flags.includes("territory")
+ ? "regions"
+ : terms.flags.includes("conditions")
+ ? "conditions"
+ : "commercial";
+ const found = KNOWN.filter((k) => k.re.test(text));
+ const named = found.find((k) => k.class === cls) ?? found[0];
+ const name = named?.name ?? text.split(/[(;:]/)[0].trim();
+ // The licence's own text when it has a page, else the model card that states it.
+ const url = named?.url ?? card;
+ return { name, class: cls, note: text, ...(url && { url }), ...(terms.excludes && { excludes: terms.excludes }), ...(terms.notices.length && { notices: terms.notices }) };
+ }
+
+ /** Several licences as one (a model running several workflows, a chain): the strictest class names it. */
+ export function mergeLicences(infos: LicenceInfo[]): LicenceInfo {
+ if (infos.length <= 1) return infos[0] ?? { name: "Not recorded", class: "unknown", note: UNKNOWN_LICENCE };
+ const lead = infos.reduce((a, b) => (STRICTNESS[b.class] > STRICTNESS[a.class] ? b : a));
+ const notes = [...new Set(infos.map((i) => i.note))];
+ const notices = [...new Set(infos.flatMap((i) => i.notices ?? []))];
+ return { ...lead, note: notes.join(" · "), ...(notices.length && { notices }) };
+ }
+
+ /** Where a provider shows a hosted model (its page states the model's licence and the provider's terms). */
+ export function providerPage(provider: string, endpoint: string): string | undefined {
+ if (provider === "fal") return `https://fal.ai/models/${endpoint}`;
+ if (provider === "replicate") return `https://replicate.com/${endpoint.split(":")[0]}`;
+ if (provider === "llm") return "https://www.anthropic.com/legal/commercial-terms";
+ return undefined;
+ }
+
+ export const PROVIDER_NAME: Record<string, string> = {
+ fal: "fal.ai",
+ replicate: "Replicate",
+ comfyui: "ComfyUI (your GPU)",
- llm: "Claude or Ollama",
++ llm: "Claude or a local model",
+ local: "Your browser",
+ openai: "OpenAI",
+ google: "Google",
+ };
+
+ /** A model on a paid API: the provider's and the vendor's terms (a closed model, or open weights the provider hosts). */
+ export function paidApiLicence(vendor: string, routes: { provider: string; endpoint: string }[]): LicenceInfo {
+ const providers = [...new Set(routes.map((r) => r.provider))];
+ const names = providers.map((p) => PROVIDER_NAME[p] ?? p);
+ const first = routes[0];
+ const url = first && providerPage(first.provider, first.endpoint);
+ return {
+ name: `Paid API · ${names.join(", ")}`,
+ class: "paid-api",
+ note: `${vendor}'s model through ${names.join(" or ")} on your key: you pay per run, under the provider's terms and the model's own (the provider's page states both)`,
+ ...(url && { url }),
+ };
+ }
+
-/** Text steps: Claude through the Anthropic key, else the Ollama model; on the open engine, Ollama only. */
-export function llmLicence(endpoint: string, ollamaModel = "qwen3:8b"): LicenceInfo {
++/**
++ * Text steps: Claude through the Anthropic key, else the local model; on the open engine, the local model only.
++ * `model` is the one the local server in use runs ("" when it picks one later), `server` names that server.
++ */
++export function llmLicence(endpoint: string, model = "qwen3:8b", server = "Ollama"): LicenceInfo {
+ if (endpoint !== "ollama") {
+ return {
- name: "Paid API · Anthropic (or Ollama)",
++ name: "Paid API · Anthropic (or a local model)",
+ class: "paid-api",
+ url: "https://www.anthropic.com/legal/commercial-terms",
- note: "Claude through your Anthropic key, under Anthropic's commercial terms; with no key, the Ollama model on your machine",
++ note: "Claude through your Anthropic key, under Anthropic's commercial terms; with no key, the local model on your machine (Ollama, LM Studio or Unsloth Studio)",
+ };
+ }
+ const known: [RegExp, string, LicenceClass, string?][] = [
+ [/^qwen/i, "Apache-2.0", "commercial", SPDX("Apache-2.0")],
+ [/^(mistral|mixtral)/i, "Apache-2.0", "commercial", SPDX("Apache-2.0")],
+ [/^(phi|deepseek)/i, "MIT", "commercial", SPDX("MIT")],
+ [/^gemma/i, "Gemma Terms of Use", "conditions", "https://ai.google.dev/gemma/terms"],
+ [/^llama/i, "Llama Community License", "conditions", "https://www.llama.com/"],
+ ];
- const hit = known.find(([re]) => re.test(ollamaModel));
- const note = `The Ollama model this install uses (${ollamaModel}); another model carries its own licence: ollama show <model> --license`;
++ // LM Studio and Unsloth name a model by publisher ("google/gemma-3-12b", "unsloth/Qwen3-8B-GGUF"): the last part names the family.
++ const family = model.split("/").pop() ?? "";
++ const hit = family ? known.find(([re]) => re.test(family)) : undefined;
++ const note = model
++ ? `The model this install's text steps use on ${server} (${model}); another model carries its own licence (its model card, or ollama show <model> --license)`
++ : `${server} hasn't said which model it runs yet; that model carries its own licence (its model card)`;
+ return hit ? { name: hit[1], class: hit[2], note, ...(hit[3] && { url: hit[3] }) } : { name: "Not recorded", class: "unknown", note };
+ }
+
+ /** Tools that run in the browser (colour grade, ad compositing): Fuobe's own code. */
+ export const BROWSER_LICENCE: LicenceInfo = { name: "Fuobe (open source)", class: "commercial", note: "Runs in your browser with Fuobe's own code: no model weights, nothing sent anywhere" };
+
+ // ---------------------------------------------------------------------------
+ // ComfyUI node packs: the code a workflow loads beside ComfyUI (scripts/comfy/install-comfyui.sh and
+ // install-isolated-worker.sh), from the research (docs/research/comfyui-oss*.json) and the manifest's licence
+ // notes. A pack whose repository has no LICENSE file is recorded as unknown.
+
+ export interface NodePack {
+ name: string;
+ repo: string;
+ licence: LicenceInfo;
+ /** Installed on the isolated worker (install-isolated-worker.sh), not the main ComfyUI. */
+ worker?: "isolated";
+ }
+
+ const pack = (name: string, repo: string, licence: Omit<LicenceInfo, "url"> & { url?: string }, worker?: "isolated"): NodePack => ({
+ name,
+ repo,
+ licence: { url: repo, ...licence },
+ ...(worker && { worker }),
+ });
+ const GPL: Omit<LicenceInfo, "note"> = { name: "GPL-3.0", class: "commercial", url: SPDX("GPL-3.0-only") };
+ const NO_FILE = (extra = "") => ({ name: "Not recorded", class: "unknown" as const, note: `The repository has no LICENSE file${extra}` });
+
+ export const NODE_PACKS: NodePack[] = [
+ pack("ComfyUI-WanVideoWrapper", "https://github.com/kijai/ComfyUI-WanVideoWrapper", { name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0"), note: "Code Apache-2.0; the Wan weights it loads are Apache-2.0" }),
+ pack("ComfyUI-VideoHelperSuite", "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite", { ...GPL, note: "Video loading and saving; GPL-3.0 code, like ComfyUI" }),
+ pack("ComfyUI-KJNodes", "https://github.com/kijai/ComfyUI-KJNodes", { ...GPL, note: "Utility nodes (GrowMaskWithBlur, resizing); GPL-3.0 code, like ComfyUI" }),
+ pack("ComfyUI-SeedVR2_VideoUpscaler", "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler", { name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0"), note: "SeedVR2 upscaling; code and weights Apache-2.0" }),
+ pack("ComfyUI-Frame-Interpolation", "https://github.com/Fannovel16/ComfyUI-Frame-Interpolation", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "RIFE and FILM frame interpolation; MIT code" }),
+ pack("ComfyUI-RMBG", "https://github.com/1038lab/ComfyUI-RMBG", { ...GPL, note: "Background removal; GPL-3.0 code. Fuobe uses BEN2 (MIT); RMBG-2.0 in the same pack is CC BY-NC 4.0" }),
+ pack("ComfyUI-ReActor", "https://github.com/Gourieff/ComfyUI-ReActor", { name: "MIT (per the research)", class: "commercial", note: "Face swap node; the inswapper_128 weights it loads are for non-commercial research only" }),
+ pack("ComfyUI-MMAudio", "https://github.com/kijai/ComfyUI-MMAudio", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the MMAudio weights it loads are CC BY-NC 4.0 (non-commercial)" }),
+ pack("ComfyUI_Fill-ChatterBox", "https://github.com/filliptm/ComfyUI_Fill-ChatterBox", NO_FILE("; the Chatterbox weights are MIT")),
+ pack("ComfyUI-IndexTTS2", "https://github.com/snicolast/ComfyUI-IndexTTS2", NO_FILE("; the IndexTTS-2 weights have their own Model Use License")),
+ pack("ComfyUI-Video-Depth-Anything", "https://github.com/yuvraj108c/ComfyUI-Video-Depth-Anything", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; Fuobe loads the Apache-2.0 Small model (Base and Large are CC BY-NC 4.0)" }),
+ pack("ComfyUI-MelBandRoFormer", "https://github.com/kijai/ComfyUI-MelBandRoFormer", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the MelBand RoFormer weights are MIT" }),
+ pack("ComfyUI-QwenASR", "https://github.com/1038lab/ComfyUI-QwenASR", { ...GPL, note: "Qwen3-ASR transcription; GPL-3.0 code, Apache-2.0 weights" }),
+ pack("ComfyUI-HunyuanVideo-Foley", "https://github.com/phazei/ComfyUI-HunyuanVideo-Foley", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the HunyuanVideo-Foley weights leave out the EU, UK and South Korea" }),
+ pack("ComfyUI-ToSVG", "https://github.com/Yanick112/ComfyUI-ToSVG", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "VTracer vectorising; MIT. The pack also imports PyMuPDF (AGPL-3.0) for a node Fuobe doesn't use" }),
+ pack("ComfyUI-Whisper", "https://github.com/yuvraj108c/ComfyUI-Whisper", { name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0"), note: "Word-timed captions in one job; non-commercial code (the author asks to be contacted for commercial use). The Whisper weights are MIT" }),
+ pack("ComfyUI-LatentSyncWrapper", "https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper", NO_FILE("; the LatentSync 1.6 weights are CreativeML OpenRAIL++-M"), "isolated"),
+ pack("ComfyUI-ThinkSound_Wrapper", "https://github.com/ShmuelRonen/ComfyUI-ThinkSound_Wrapper", NO_FILE("; the ThinkSound weights are Apache-2.0"), "isolated"),
+ // Genjutsu's Character swap (docs/research/openjutsu-6.md §7): Akatz Labs' packs, pinned in install-comfyui.sh.
+ pack("h3_character_swap", "https://github.com/akatz-labs/h3-character-swap-tool/tree/0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b/worker_nodes/h3_character_swap", {
+ ...GPL,
+ note: "MiniMax H3 character swap nodes (Akatz Labs); GPL-3.0 code, a modified NVIDIA INT8 kernel inside is Apache-2.0. The MiniMax H3 weights it runs leave out the US, the EU, the UK and South Korea",
+ }),
+ pack("h3-relay", "https://github.com/akatz-ai/h3-relay/tree/e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220", {
+ ...GPL,
+ note: "H3 Relay 2.0 (Sendy Software LLC and contributors); GPL-3.0 code, vendored Context Loop and Spectrum GPL-3.0. Opt-in (H3_RELAY=1): it registers HTTP routes when it loads",
+ }),
+ ];
+
+ export const nodePack = (name: string): NodePack | undefined => NODE_PACKS.find((p) => p.name === name);
+
+ /** The parts of a LoRA's licence snapshot the class needs (src/lib/catalog/types.ts LoraLicence). */
+ interface LoraLicenceLike {
+ commercial: boolean;
+ hostedOk: boolean;
+ snapshotDate?: string;
+ name?: string;
+ }
+
+ /**
+ * A LoRA's licence as information: commercial and hostable, commercial on your GPU only (civitai lists no
+ * "Rent": a condition), non-commercial, or not recorded. `page` is its model card.
+ */
+ export function loraLicenceInfo(l: LoraLicenceLike | undefined, page?: string, extra?: string): LicenceInfo {
+ if (!l) return { name: "Your own", class: "commercial", note: "A LoRA you trained or added yourself", ...(page && { url: page }) };
+ const recorded = l.name?.trim();
+ const unknown = !recorded || /unspecified|no licen[cs]e|check (?:the )?card/i.test(recorded);
+ const cls: LicenceClass = unknown && !l.commercial ? "unknown" : !l.commercial ? "non-commercial" : !l.hostedOk ? "conditions" : "commercial";
+ const what = !l.commercial ? "Outputs may not be sold" : l.hostedOk ? "Commercial use, on your GPU and in the cloud" : "Commercial use on your GPU; the licence doesn't allow running it on another hosted service";
+ const note = [what, recorded && `licence as read: ${recorded}`, l.snapshotDate && `read ${l.snapshotDate}`, extra].filter(Boolean).join(" · ");
+ return { name: unknown ? "Not recorded" : (KNOWN.find((k) => k.re.test(recorded!))?.name ?? recorded!), class: cls, note, ...(page && { url: page }) };
+ }
diff --cc src/lib/preset-card-data.ts
index 9a2aeba3,00000000..736522af
mode 100644,000000..100644
--- a/src/lib/preset-card-data.ts
+++ b/src/lib/preset-card-data.ts
@@@ -1,40 -1,0 +1,21 @@@
+/**
- * A gallery card's data from a full catalog preset, rendered preview media included (the card
- * types and procedural previews are in preset-cards.ts). This is the one module that reads the
- * media manifest, so it's kept apart: whatever client code uses from a module ships in every client
- * chunk that holds it, and preset-cards.ts is in the galleries', home's, shorts' and mixed media's
- * chunks, which only need the hash on each card. Server pages (home, motions, effects, apps) import
- * this; on the client only the preset header does, in its own lazily loaded chunk (studio-page.tsx).
++ * A preset's card as the galleries and the preset header show it: the slim card data (preset-cards.ts) with
++ * its real cover when it has one (preset-previews.generated.ts, pnpm eval:covers), else the procedural preview.
++ *
++ * The only module that reads the covers manifest, which lists every cover with its provenance. Import it from
++ * server pages, or from a component loaded on its own (next/dynamic, like the preset header): a client module
++ * that imports it ships the whole manifest in every chunk it is in. tests/preset-cards.test.ts checks the importers.
+ */
- import PREVIEW_MEDIA from "./catalog/preview-media.generated.json";
+import type { Preset } from "./catalog/types";
- import { clip, lookHue, motionMove, proceduralPreview, type PresetCardData, type PresetPreview } from "./preset-cards";
- import { mediaHash, type PreviewManifest } from "./preview-media";
++import { presetCard, proceduralPreview, previewScene, type PresetCardData, type PresetPreview } from "./preset-cards";
++import { PRESET_PREVIEWS } from "./preset-previews.generated";
+
- const MEDIA: PreviewManifest = PREVIEW_MEDIA;
-
- /**
- * A preset's card preview: its rendered media when the manifest lists it (just the hash, and a
- * motion's move for its glyph), else the procedural one.
- */
+export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
- const media = mediaHash(MEDIA, p.id);
- if (!media) return proceduralPreview(p);
- return { media, ...(p.type === "motion" ? { move: motionMove(p) } : {}) };
++ // A real cover, rendered and measured by the evaluation harness (pnpm eval:covers), replaces the procedural one.
++ const real = PRESET_PREVIEWS[p.id];
++ if (real) return { poster: real.poster, ...(real.video && { video: real.video }), scene: previewScene(p) };
++ return proceduralPreview(p);
+}
+
+/** What a gallery card needs, and nothing else. */
- export function toPresetCard(p: Preset): PresetCardData {
- return {
- id: p.id,
- name: p.name,
- description: clip(p.description, 100),
- category: p.category,
- icon: p.look.icon,
- hue: lookHue(p.look),
- ...(p.badges?.includes("top") ? { top: true as const } : {}),
- cloud: !!p.cloud,
- open: !!p.open,
- preview: previewFor(p),
- };
- }
++export const toPresetCard = (p: Preset): PresetCardData => presetCard(p, previewFor(p));
diff --cc src/lib/preset-cards.ts
index f693638e,5aac597c..56d1d668
--- a/src/lib/preset-cards.ts
+++ b/src/lib/preset-cards.ts
@@@ -1,16 -1,14 +1,16 @@@
/**
- * Slim preset card data for the galleries, and the previews shown on each card.
+ * Slim preset card data for the galleries, and the procedural previews shown on each card.
*
* Gallery pages are server components: they map the full catalog `Preset` (prompt templates,
- * routes, LoRA URLs, parity notes) to `PresetCardData` with toPresetCard() (preset-card-data.ts),
- * so only what a card shows reaches the browser. A preset with rendered media (public/previews, see
- * preview-media.ts) sends only its hash; every other card gets a procedural preview: a camera move
- * over a bundled layered still for motions, a per-category animated treatment for effects and apps.
- * The procedural preview is also what a card with media falls back to when its files don't load.
- * Pure module, safe on both sides. It doesn't import the media manifest: client code imports this
- * module all over, so the manifest would ship in each of those chunks (tests/preview-media.test.ts).
+ * routes, LoRA URLs, parity notes) to `PresetCardData` here, so only what a card shows reaches
+ * the browser. A preset with a real cover (a measured render, see preset-previews.generated.ts) shows
+ * it; the others get a procedural preview: a camera move over a bundled layered still for motions, a
+ * per-category animated treatment for effects and apps. Pure module, safe on both sides.
++ *
++ * The covers manifest is read in preset-card-data.ts (previewFor, toPresetCard), not here: client
++ * components import this module, and would carry the whole manifest into every chunk they are in.
*/
import type { Preset } from "./catalog/types";
-import { PRESET_PREVIEWS } from "./preset-previews.generated";
/** Bundled sample stills (public/samples/previews, see scripts/gen-preview-scenes.mjs). */
export type PreviewScene = "landscape" | "portrait" | "city" | "product";
@@@ -174,11 -172,11 +174,11 @@@ export const FX =
] as const;
export type PreviewFx = (typeof FX)[number];
- /** A camera move over a bundled layered still (motions), or an animated treatment over one (effects, apps). */
- export interface ProceduralPreview {
- media?: undefined;
+ export interface PresetPreview {
/** Still shown before (and under) the preview. */
poster: string;
- /** A real example clip, once one exists: played instead of the procedural preview. */
++ /** A real cover's clip (preset-previews.generated.ts), played instead of the procedural preview. */
+ video?: string;
scene: PreviewScene;
move?: CameraMove;
fx?: PreviewFx;
@@@ -397,8 -380,11 +382,9 @@@ export function previewScene(p: Pick<Pr
return pick(p.id, ["portrait", "landscape", "city", "portrait"] as const);
}
- export function proceduralPreview(p: Pick<Preset, "id" | "type" | "name" | "category">): ProceduralPreview {
-export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
++/** The procedural preview (a preset without a real cover): a camera move for motions, a treatment for effects and apps. */
++export function proceduralPreview(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
const scene = previewScene(p);
- // A real cover, rendered and measured by the evaluation harness (pnpm eval:covers), replaces the procedural one.
- const real = PRESET_PREVIEWS[p.id];
- if (real) return { poster: real.poster, ...(real.video && { video: real.video }), scene };
return {
poster: scenePoster(scene),
scene,
@@@ -406,22 -392,13 +392,19 @@@
};
}
+/**
- * The procedural preview of a card whose media doesn't load. Card data only carries the media's
- * hash, so the client works it out again from the id (which says the type), name and category.
++ * Whether a preview is a real cover (preset-previews.generated.ts) rather than a procedural one: every
++ * procedural preview carries a camera move (motions) or a treatment (effects, apps), a cover neither.
+ */
- export function fallbackPreview(c: Pick<PresetCardData, "id" | "name" | "category">): ProceduralPreview {
- const type: Preset["type"] = c.id.startsWith("motion-") ? "motion" : c.id.startsWith("effect-") ? "effect" : "app";
- return proceduralPreview({ ...c, type });
- }
++export const isCover = (p: Pick<PresetPreview, "move" | "fx">) => !p.move && !p.fx;
+
/**
* Whether a card shows its still mirrored, so neighbouring treatments on the same still differ.
-- * Never for camera moves (a pan left must still go left). Derived from the id on the client, so it
-- * costs nothing in the gallery payload.
++ * Never for camera moves (a pan left must still go left), nor for a real cover (shown as rendered).
++ * Derived from the id on the client, so it costs nothing in the gallery payload.
*/
--export function previewFlip(c: { id: string; preview: Pick<PresetPreview, "move"> }): boolean {
-- return !c.preview.move && ((stableHash(c.id) >>> 3) & 1) === 1;
++export function previewFlip(c: { id: string; preview: Pick<PresetPreview, "move" | "fx"> }): boolean {
++ return !!c.preview.fx && ((stableHash(c.id) >>> 3) & 1) === 1;
}
/** The hue a preset's look was built from (`oklch(L C <hue>)`), for tinting its preview. */
@@@ -437,6 -414,22 +420,22 @@@ export function clip(s: string, max: nu
return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), max * 0.6)).replace(/[\s,;:.–—-]+$/, "")}…`;
}
-/** What a gallery card needs, and nothing else. */
-export function toPresetCard(p: Preset): PresetCardData {
++/** What a gallery card needs, and nothing else, with the preview it shows (toPresetCard in preset-card-data.ts picks it). */
++export function presetCard(p: Preset, preview: PresetPreview): PresetCardData {
+ return {
+ id: p.id,
+ name: p.name,
+ description: clip(p.description, 100),
+ category: p.category,
+ icon: p.look.icon,
+ hue: lookHue(p.look),
+ ...(p.badges?.includes("top") ? { top: true as const } : {}),
+ cloud: !!p.cloud,
+ open: !!p.open,
- preview: previewFor(p),
++ preview,
+ };
+ }
+
/**
* A showcase row: one preset per category (its "top" one when it has one), in catalog order, so
* the row shows `n` different kinds of effect instead of the first category's six.
diff --cc src/proxy.ts
index 3d776662,570a4570..84b777be
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@@ -63,7 -113,6 +113,7 @@@ export function proxy(request: NextRequ
export const config = {
// Everything except build assets and the public folder's own files: the favicon, the demo
- // samples, the preset cards' preview media, vendored scripts (the 3D viewer's meshopt decoder)
- // and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.
- // samples and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.
- matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|samples/|[^/]+\\.svg$).*)"],
++ // samples, the preset covers, vendored scripts (the 3D viewer's meshopt decoder) and the SVGs at
++ // the root. Generated SVGs under /api/files stay behind sign-in.
+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|samples/|previews/|vendor/|[^/]+\\.svg$).*)"],
};
diff --cc src/server/assist/agent.ts
index 1704ea4a,3b5967e5..fed4cf3e
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@@ -29,7 -28,7 +30,8 @@@ import
import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
+import { activeLocal, aiHelper, chatLocal, emptyReply, localLabel, localProblem, pinnedKind, toChatMessages, type Ready } from "../llm";
+ import { offeredDefault } from "../model-access";
import { engineMode, getSetting } from "../settings";
import { getSkill } from "../skills";
import { readRef } from "../storage";
@@@ -420,10 -450,21 +456,22 @@@ export async function resolveMode(choic
return { mode: "manual", agent: "offline", model: null, effort: null };
}
+ /** The connectors Claude gets in this chat: none on other agents, or in a scheduled run that leaves them off. */
+ const chatConnectors = (s: State): Connector[] => (s.thread.agent === "claude" && s.ext.connectors ? activeConnectors() : []);
+
-/** Connectors need Claude: a chat on Ollama or the offline planner (that would otherwise use them) says so once. */
++/** Connectors need Claude: a chat on a local model or the offline planner (that would otherwise use them) says so once. */
+ function connectorNote(s: State): void {
+ if (s.thread.agent === "claude" || !s.ext.connectors || s.thread.items.some((i) => i.role === "notice" && i.text.startsWith(CONNECTOR_NOTE))) return;
+ const names = activeConnectors().map((c) => c.name);
+ if (!names.length) return;
- push(s, { role: "notice", tone: "info", text: `${CONNECTOR_NOTE} (${names.slice(0, 3).join(", ")}${names.length > 3 ? "…" : ""}); this chat runs on ${s.thread.agent === "ollama" ? "a local model" : "the offline planner"}, so it can't use them.` });
++ push(s, { role: "notice", tone: "info", text: `${CONNECTOR_NOTE} (${names.slice(0, 3).join(", ")}${names.length > 3 ? "…" : ""}); this chat runs on ${s.thread.agent === "local" ? "a local model" : "the offline planner"}, so it can't use them.` });
+ }
+ const CONNECTOR_NOTE = "Connectors work in Claude chats";
+
export function createThread(opts: {
engine: Engine;
- agent: AssistThread["agent"];
+ /** "ollama" is the local agent's old name. */
+ agent: AssistThread["agent"] | "ollama";
autoApprove?: boolean;
title?: string;
projectId?: string | null;
@@@ -434,11 -482,25 +489,25 @@@
const now = Date.now();
if (opts.projectId && !getProject(opts.projectId)) throw new Error("That project doesn't exist anymore");
const s: State = {
- thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: opts.agent, engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },
+ thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: normalizeAgent(opts.agent) ?? "offline", engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },
messages: [],
pending: null,
- ext: { projectId: opts.projectId ?? null, mode: opts.mode ?? null, model: opts.model ?? null, effort: opts.effort ?? null, skills: [], context: null, sent: null },
+ ext: {
+ projectId: opts.projectId ?? null,
+ mode: opts.mode ?? null,
+ model: opts.model ?? null,
+ effort: opts.effort ?? null,
+ skills: [],
+ context: null,
+ sent: null,
+ scheduleId: opts.scheduleId ?? null,
+ capUsd: opts.capUsd ?? null,
+ spentUsd: 0,
+ connectors: opts.connectors !== false,
+ },
};
+ if (opts.note) push(s, { role: "notice", tone: "info", text: opts.note });
+ connectorNote(s);
save(s);
if (opts.projectId) touchProject(opts.projectId);
return s.thread;
diff --cc src/server/assist/schedules.ts
index 00000000,d5ae19ed..6c80143f
mode 000000,100644..100644
--- a/src/server/assist/schedules.ts
+++ b/src/server/assist/schedules.ts
@@@ -1,0 -1,390 +1,396 @@@
+ import "server-only";
+ import { nanoid } from "nanoid";
-import { threadTitle, type AssistItem, type AssistModeChoice } from "@/lib/assist";
++import { normalizeAgent, threadTitle, type AssistItem, type AssistModeChoice } from "@/lib/assist";
+ import {
+ DEFAULT_SCHEDULE_CAP_USD,
+ describeRule,
+ formatWhen,
+ nextRun,
+ ruleError,
+ validTimeZone,
+ type ScheduleApproval,
+ type ScheduleResult,
+ type ScheduleRule,
+ type ScheduleView,
+ } from "@/lib/assist-schedule";
+ import { formatCost } from "@/lib/format";
+ import { db } from "../db";
+ import { addMessage, createThread, getThread, resolveMode, run, type ModelCall } from "./agent";
+ import { getProject } from "./projects";
+
+ /**
+ * Assist's scheduled tasks. A task is a prompt with a rule (daily, weekly, every N hours, once) in a
+ * time zone; each run is a new chat (in the task's project, when it has one) that the server's sweep
+ * starts — `ensureScheduleRunner()`, started at boot by src/instrumentation.ts, checks every 30 s.
+ *
+ * Approval per task: "ask" runs the chat until its first plan, which then waits as an approval card
+ * (no generation starts until the user approves); "auto" lets plans start on their own while they fit
+ * the task's cost cap for that run, and leaves the rest waiting (see withinCap and the agent's step()).
+ * Custom MCP connectors are off in runs unless the task opts in (`connectors`): their tools run inside
+ * Claude's reply, where neither mode can hold them back.
+ * A run the server missed (it was off) happens once when it's back, not once per missed time.
+ */
+
+ export class ScheduleError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+ }
+
+ const SWEEP_MS = 30_000;
+ /** The first sweep after boot. */
+ const BOOT_SWEEP_MS = 5_000;
+ /** At most this many tasks start in one sweep; the rest start on the next. */
+ const PER_SWEEP = 10;
+
+ interface Row {
+ id: string;
+ title: string;
+ prompt: string;
+ attachments_json: string;
+ project_id: string | null;
+ rule_json: string;
+ tz: string;
+ approval: ScheduleApproval;
+ cap_usd: number | null;
+ connectors: number;
+ engine: "cloud" | "open";
+ mode_json: string | null;
+ paused: number;
+ next_run_at: number | null;
+ last_run_at: number | null;
+ last_thread_id: string | null;
+ last_status: ScheduleResult["status"] | null;
+ last_text: string | null;
+ runs: number;
+ created_at: number;
+ updated_at: number;
+ }
+
+ /** A rule as the dialog sends it: "every N hours" gets its start (`from`) here. */
+ export type RuleInput = ScheduleRule extends infer R ? (R extends { kind: "hours" } ? Omit<R, "from"> & { from?: number } : R) : never;
+
+ export interface ScheduleInput {
+ title: string;
+ prompt: string;
+ attachments?: string[];
+ projectId?: string | null;
+ rule: RuleInput;
+ tz: string;
+ approval: ScheduleApproval;
+ capUsd?: number | null;
+ engine: "cloud" | "open";
+ mode?: AssistModeChoice | null;
+ /** Whether runs may use the connectors in Settings (off unless set). */
+ connectors?: boolean;
+ paused?: boolean;
+ }
+
+ const getRow = (id: string) => db().prepare("SELECT * FROM assist_schedules WHERE id = ?").get(id) as Row | undefined;
+
+ /**
+ * How the last run went. A run that made a chat is read from the chat itself (so an approval given
+ * later shows); a skip, a failure to start or a pause (no chat of its own: last_thread_id is cleared
+ * then) shows the stored reason.
+ */
+ function resultOf(r: Row): ScheduleResult | null {
+ if (!r.last_status) return null;
+ const stored: ScheduleResult = { threadId: r.last_thread_id, status: r.last_status, text: r.last_text ?? "" };
+ if (r.last_status === "skipped" || !r.last_thread_id) return stored;
+ const view = getThread(r.last_thread_id);
+ // The chat was deleted: what was stored stands, but a run that never reported back isn't still going.
+ if (!view) {
+ const lost = stored.status === "running" || stored.status === "waiting";
+ return { threadId: null, status: lost ? "failed" : stored.status, text: lost ? CHAT_DELETED : stored.text };
+ }
+ return { threadId: r.last_thread_id, ...summarize(view.thread.status, view.thread.items) };
+ }
+
+ const CHAT_DELETED = "Its chat was deleted";
+
+ /** A chat's outcome in a few words: still going, a plan waiting, an error, or what it made. */
+ export function summarize(status: "idle" | "running" | "waiting", items: AssistItem[]): Omit<ScheduleResult, "threadId"> {
+ if (status === "running") return { status: "running", text: "Working…" };
+ if (status === "waiting") {
+ const card = items.findLast((i) => i.role === "approval");
+ const price = card?.role === "approval" ? (card.totalUsd === null ? "" : ` (${card.totalUsd === 0 ? "free" : formatCost(card.totalUsd)})`) : "";
+ return { status: "waiting", text: `A plan waits for your approval${price}` };
+ }
+ const lastUser = items.findLastIndex((i) => i.role === "user");
+ const after = items.slice(lastUser + 1);
+ const error = after.findLast((i) => i.role === "notice" && i.tone === "error");
+ if (error?.role === "notice" && !after.slice(after.indexOf(error) + 1).some((i) => i.role === "assistant")) return { status: "failed", text: error.text };
+ const made = items.reduce((n, i) => n + (i.role === "generations" ? i.ids.length : 0), 0);
+ const said = after.findLast((i) => i.role === "assistant");
+ const text = made ? `Started ${made} result${made === 1 ? "" : "s"}` : said?.role === "assistant" ? said.text.replace(/\s+/g, " ").slice(0, 140) : "Finished";
+ return { status: "done", text };
+ }
+
++/** A task's stored mode choice. Tasks saved before LM Studio and Unsloth Studio support say agent "ollama": shown as "local", as runs read it. */
++function modeOf(json: string): ScheduleView["mode"] {
++ const m = JSON.parse(json) as NonNullable<ScheduleView["mode"]>;
++ return m.agent ? { ...m, agent: normalizeAgent(m.agent) ?? m.agent } : m;
++}
++
+ function toView(r: Row): ScheduleView {
+ return {
+ id: r.id,
+ title: r.title,
+ prompt: r.prompt,
+ attachments: JSON.parse(r.attachments_json) as string[],
+ projectId: r.project_id,
+ rule: JSON.parse(r.rule_json) as ScheduleRule,
+ tz: r.tz,
+ approval: r.approval,
+ capUsd: r.cap_usd,
+ engine: r.engine,
- mode: r.mode_json ? (JSON.parse(r.mode_json) as ScheduleView["mode"]) : null,
++ mode: r.mode_json ? modeOf(r.mode_json) : null,
+ connectors: !!r.connectors,
+ paused: !!r.paused,
+ nextRunAt: r.paused ? null : r.next_run_at,
+ lastRunAt: r.last_run_at,
+ last: resultOf(r),
+ runs: r.runs,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+ }
+
+ /** Tasks, soonest first (paused ones last). `project`: one project's; null: those outside projects. */
+ export function listSchedules(f: { project?: string | null } = {}): ScheduleView[] {
+ const where = f.project === null ? "WHERE project_id IS NULL" : f.project ? "WHERE project_id = ?" : "";
+ const rows = db()
+ .prepare(`SELECT * FROM assist_schedules ${where} ORDER BY paused, next_run_at IS NULL, next_run_at, created_at DESC LIMIT 200`)
+ .all(...(f.project ? [f.project] : [])) as Row[];
+ return rows.map(toView);
+ }
+
+ export function getSchedule(id: string): ScheduleView | null {
+ const r = getRow(id);
+ return r ? toView(r) : null;
+ }
+
+ function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omit<Row, "id" | "last_run_at" | "last_thread_id" | "last_status" | "last_text" | "runs" | "created_at"> {
+ if (!validTimeZone(input.tz)) throw new ScheduleError("Pick a time zone");
+ if (input.projectId && !getProject(input.projectId)) throw new ScheduleError("That project doesn't exist anymore", 404);
+ const before = prev ? (JSON.parse(prev.rule_json) as ScheduleRule) : null;
+ // "Every N hours" counts from when it was set up; an unchanged one keeps counting from then.
+ const rule: ScheduleRule =
+ input.rule.kind === "hours"
+ ? { kind: "hours", every: input.rule.every, from: before?.kind === "hours" && before.every === input.rule.every ? before.from : (input.rule.from ?? now) }
+ : (input.rule as ScheduleRule);
+ const bad = ruleError(rule);
+ if (bad) throw new ScheduleError(bad);
+ const paused = input.paused ?? !!prev?.paused;
+ const ruleJson = JSON.stringify(rule);
+ // An edit that leaves when it runs alone (a rename, a new prompt) keeps the next time, even one that
+ // is due and not yet swept; a new rule or zone, or resuming, picks it from now.
+ const unchanged = prev && !prev.paused && !paused && prev.next_run_at !== null && prev.rule_json === ruleJson && prev.tz === input.tz;
+ const next = unchanged ? prev.next_run_at : nextRun(rule, input.tz, now);
+ if (next === null && !paused) throw new ScheduleError(rule.kind === "once" ? "That time has passed — pick a later one" : "This schedule never runs");
+ const cap = input.approval === "auto" ? (input.capUsd ?? DEFAULT_SCHEDULE_CAP_USD) : null;
+ return {
+ title: input.title.trim().slice(0, 80) || threadTitle(input.prompt),
+ prompt: input.prompt.trim(),
+ attachments_json: JSON.stringify(input.attachments ?? []),
+ project_id: input.projectId ?? null,
+ rule_json: ruleJson,
+ tz: input.tz,
+ approval: input.approval,
+ cap_usd: cap === null ? null : Math.round(cap * 100) / 100,
+ connectors: (input.connectors ?? !!prev?.connectors) ? 1 : 0,
+ engine: input.engine,
+ mode_json: input.mode ? JSON.stringify(input.mode) : null,
+ paused: paused ? 1 : 0,
+ next_run_at: next,
+ updated_at: now,
+ };
+ }
+
+ export function createSchedule(input: ScheduleInput, now = Date.now()): ScheduleView {
+ const row: Row = { id: nanoid(10), ...checked(input, undefined, now), last_run_at: null, last_thread_id: null, last_status: null, last_text: null, runs: 0, created_at: now };
+ db()
+ .prepare(
+ `INSERT INTO assist_schedules (id, title, prompt, attachments_json, project_id, rule_json, tz, approval, cap_usd, connectors, engine, mode_json, paused,
+ next_run_at, last_run_at, last_thread_id, last_status, last_text, runs, created_at, updated_at)
+ VALUES (@id, @title, @prompt, @attachments_json, @project_id, @rule_json, @tz, @approval, @cap_usd, @connectors, @engine, @mode_json, @paused,
+ @next_run_at, @last_run_at, @last_thread_id, @last_status, @last_text, @runs, @created_at, @updated_at)`,
+ )
+ .run(row);
+ ensureScheduleRunner();
+ return toView(row);
+ }
+
+ /** Edit any part; pausing keeps the task, resuming picks the next time from now, and an edit that leaves the timing alone keeps it. */
+ export function updateSchedule(id: string, patch: Partial<ScheduleInput>, now = Date.now()): ScheduleView | null {
+ const r = getRow(id);
+ if (!r) return null;
+ const current = toView(r);
+ const merged: ScheduleInput = {
+ title: patch.title ?? current.title,
+ prompt: patch.prompt ?? current.prompt,
+ attachments: patch.attachments ?? current.attachments,
+ projectId: patch.projectId !== undefined ? patch.projectId : current.projectId,
+ rule: patch.rule ?? current.rule,
+ tz: patch.tz ?? current.tz,
+ approval: patch.approval ?? current.approval,
+ capUsd: patch.capUsd !== undefined ? patch.capUsd : current.capUsd,
+ engine: patch.engine ?? current.engine,
+ mode: patch.mode !== undefined ? patch.mode : (current.mode as AssistModeChoice | null),
+ connectors: patch.connectors ?? current.connectors,
+ paused: patch.paused ?? current.paused,
+ };
+ const next = { ...r, ...checked(merged, r, now) };
+ db()
+ .prepare(
+ `UPDATE assist_schedules SET title = @title, prompt = @prompt, attachments_json = @attachments_json, project_id = @project_id, rule_json = @rule_json,
+ tz = @tz, approval = @approval, cap_usd = @cap_usd, connectors = @connectors, engine = @engine, mode_json = @mode_json, paused = @paused,
+ next_run_at = @next_run_at, updated_at = @updated_at WHERE id = @id`,
+ )
+ .run(next);
+ return toView(next);
+ }
+
+ /** Delete the task; the chats its runs made stay. */
+ export function deleteSchedule(id: string): boolean {
+ return db().prepare("DELETE FROM assist_schedules WHERE id = ?").run(id).changes > 0;
+ }
+
+ function record(id: string, fields: Partial<Pick<Row, "last_run_at" | "last_thread_id" | "last_status" | "last_text" | "paused">> & { addRun?: boolean }): void {
+ const { addRun, ...set } = fields;
+ const cols = Object.keys(set).map((k) => `${k} = @${k}`);
+ if (addRun) cols.push("runs = runs + 1");
+ db()
+ .prepare(`UPDATE assist_schedules SET ${cols.join(", ")} WHERE id = @id`)
+ .run({ id, ...set });
+ }
+
+ /** A chat one of this task's runs started that is still working (a run interrupted by a restart isn't). */
+ function runningChat(id: string): string | null {
+ const rows = db()
+ .prepare("SELECT s.thread_id AS id FROM assist_thread_state s JOIN assist_threads t ON t.id = s.thread_id WHERE s.schedule_id = ? AND t.status = 'running'")
+ .all(id) as { id: string }[];
+ return rows.find((r) => getThread(r.id)?.thread.status === "running")?.id ?? null;
+ }
+
+ /**
+ * What starting a run came to: a new chat (`threadId`, with `done` settling when the agent stops),
+ * or none and why — `busy` (the run before is still going), `paused` (its project is gone) or
+ * `failed` (the chat couldn't be started) — with the text the Scheduled page shows.
+ */
+ export type ScheduleStart = { threadId: string; done: Promise<void> } | { threadId: null; done: Promise<void>; reason: "busy" | "paused" | "failed"; message: string };
+
+ /**
+ * Start one run of a task: a new chat with the task's prompt, in its project, on its engine and mode,
+ * asking first or auto-running within its cap, with connectors only when the task allows them.
+ * Resolves once the chat exists; `done` settles when the agent stops (a finished reply, or a plan
+ * waiting for approval).
+ */
+ export async function startSchedule(id: string, o: { now?: number; model?: ModelCall; manual?: boolean } = {}): Promise<ScheduleStart> {
+ const now = o.now ?? Date.now();
+ const r = getRow(id);
+ if (!r) throw new ScheduleError("No such scheduled task", 404);
+ const none = (reason: "busy" | "paused" | "failed", message: string): ScheduleStart => ({ threadId: null, done: Promise.resolve(), reason, message });
+ if (runningChat(id)) {
+ // A scheduled time that passes while the last run works is recorded; a Run now click just gets the answer.
+ if (!o.manual) record(id, { last_status: "skipped", last_text: `Skipped at ${formatWhen(now, r.tz)}: the run before was still going` });
+ return none("busy", "The last run is still going — try again when it stops");
+ }
+ // A failure without a chat of its own clears last_thread_id, so the reason shows instead of the previous run's chat.
+ if (r.project_id && !getProject(r.project_id)) {
+ const message = "Its project was deleted — edit the task to pick another";
+ record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, paused: 1 });
+ return none("paused", message);
+ }
+ const rule = JSON.parse(r.rule_json) as ScheduleRule;
+ const mode = r.mode_json ? (JSON.parse(r.mode_json) as AssistModeChoice) : undefined;
+ const cap = r.approval === "auto" ? (r.cap_usd ?? DEFAULT_SCHEDULE_CAP_USD) : null;
+ const how = cap === null ? "plans wait for your approval" : cap === 0 ? "only free plans run on their own" : `plans up to ${formatCost(cap)} run on their own`;
+ let threadId: string;
+ try {
+ const m = await resolveMode(mode);
+ const uses = !!r.connectors && m.agent === "claude";
+ const t = createThread({
+ engine: r.engine,
+ agent: m.agent,
+ autoApprove: r.approval === "auto",
+ title: `${r.title} · ${formatWhen(now, r.tz)}`,
+ projectId: r.project_id,
+ mode: m.mode,
+ model: m.model,
+ effort: m.effort,
+ scheduleId: r.id,
+ capUsd: cap,
+ connectors: !!r.connectors,
+ note: `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}${uses ? " · connectors on (their tools run without asking)" : ""}.${m.note ? ` ${m.note}` : ""}`,
+ });
+ threadId = t.id;
+ addMessage(t.id, r.prompt, JSON.parse(r.attachments_json) as string[]);
+ } catch (e) {
+ const message = (e as Error).message || "The run couldn't start";
+ record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, addRun: true });
+ return none("failed", message);
+ }
+ record(id, { last_run_at: now, last_thread_id: threadId, last_status: "running", last_text: "Working…", addRun: true });
+ const done = run(threadId, o.model)
+ .catch((e: Error) => console.warn(`[fuobe] scheduled task ${id} failed: ${e.message}`))
+ .finally(() => {
+ // Only while this run is still the task's last (a pause since then keeps its reason).
+ const view = getThread(threadId);
+ const s = view ? summarize(view.thread.status, view.thread.items) : { status: "failed" as const, text: CHAT_DELETED };
+ db()
+ .prepare("UPDATE assist_schedules SET last_status = ?, last_text = ? WHERE id = ? AND last_thread_id = ?")
+ .run(s.status, s.text, id, threadId);
+ });
+ return { threadId, done };
+ }
+
+ /**
+ * Start every task that is due at `now`. Each task's next time is claimed first (a compare-and-set
+ * on next_run_at), so two sweeps never start the same run. Resolves when the started runs settle.
+ */
+ export async function sweepSchedules(now = Date.now(), o: { model?: ModelCall } = {}): Promise<string[]> {
+ const due = db().prepare("SELECT * FROM assist_schedules WHERE paused = 0 AND next_run_at IS NOT NULL AND next_run_at <= ? ORDER BY next_run_at LIMIT ?").all(now, PER_SWEEP) as Row[];
+ const started: string[] = [];
+ const runs: Promise<void>[] = [];
+ for (const r of due) {
+ const next = nextRun(JSON.parse(r.rule_json) as ScheduleRule, r.tz, now);
+ const claimed = db().prepare("UPDATE assist_schedules SET next_run_at = ? WHERE id = ? AND next_run_at = ? AND paused = 0").run(next, r.id, r.next_run_at).changes;
+ if (!claimed) continue;
+ const begun = await startSchedule(r.id, { now, model: o.model }).catch((e: Error) => {
+ record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });
+ return null;
+ });
+ if (begun?.threadId) started.push(begun.threadId);
+ if (begun) runs.push(begun.done);
+ }
+ await Promise.all(runs);
+ return started;
+ }
+
+ declare global {
+ var __fuobeScheduleRunner: { tick: () => void; timer: NodeJS.Timeout } | undefined;
+ }
+
+ const tick = () => void sweepSchedules().catch((e: Error) => console.warn(`[fuobe] schedule sweep failed: ${e.message}`));
+
+ /**
+ * Start the 30 s sweep (once per process: at boot, and when a task is created). At boot (`soon`) the
+ * first sweep also runs a few seconds in, so a run missed while the server was off doesn't wait for
+ * the first interval.
+ */
+ export function ensureScheduleRunner(o: { soon?: boolean } = {}): void {
+ const cur = globalThis.__fuobeScheduleRunner;
+ if (cur) {
+ // After a dev hot reload, point the timer at this module's code.
+ cur.tick = tick;
+ return;
+ }
+ const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };
+ state.timer.unref?.();
+ globalThis.__fuobeScheduleRunner = state;
+ if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();
+ }
diff --cc src/server/assist/schemas.ts
index 739a74b9,01917f3e..0b4ff703
--- a/src/server/assist/schemas.ts
+++ b/src/server/assist/schemas.ts
@@@ -1,5 -1,6 +1,6 @@@
import { z } from "zod";
-import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, PROJECT_COLORS } from "@/lib/assist";
+import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, normalizeAgent, PROJECT_COLORS } from "@/lib/assist";
+ import { MAX_SCHEDULE_CAP_USD, MAX_SCHEDULE_HOURS, MAX_SCHEDULE_PROMPT } from "@/lib/assist-schedule";
export const AssistMessage = z.object({
text: z.string().trim().min(1).max(8000),
diff --cc src/server/assist/tools.ts
index 8aa829f8,0a3e02ef..9727ab0f
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@@ -6,11 -9,13 +9,13 @@@ import { currentModelId } from "@/lib/c
import { OPERATION_LABELS, type ChainSlot, type GenerationRequest, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";
import { type PlannedJob, totalCost } from "@/lib/assist";
import { STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
+ import { loraFamily, runsSomewhere, TRAINING_FAMILIES } from "@/lib/catalog/training";
+ import type { ElementLora } from "@/lib/catalog/elements";
import { createPipeline } from "../chains";
import { listElements } from "../elements";
- import { createGenerations, getGeneration, listGenerations, outputKind, previewChained, previewGeneration } from "../generations";
+ import { createGenerations, currentRequest, getGeneration, listGenerations, outputKind, previewChained, previewGeneration } from "../generations";
import { provider } from "../providers";
-import { llmBackends } from "../providers/llm";
+import { llmBackends, llmLabel } from "../providers/llm";
import { engineMode } from "../settings";
import { readRef } from "../storage";
import { katanaTool } from "../katana";
@@@ -39,10 -44,26 +44,26 @@@ function summarize(m: ModelDef)
id: m.id,
name: m.name,
vendor: m.vendor,
- engine: m.engine === "open" ? (local ? `open source (${llmLabel({ endpoint: "ollama" })}, on this machine)` : "open source (ComfyUI)") : local ? `Claude (or ${llmLabel({ endpoint: "ollama" })} when no key is set)` : "paid cloud API",
+ engine: dualEngine(m)
+ ? "Fuobe Original: open source on your GPU (ComfyUI) or hosted open weights in the cloud (pass engine to pick one)"
+ : m.engine === "open"
+ ? local
- ? "open source (Ollama, on this machine)"
++ ? `open source (${llmLabel({ endpoint: "ollama" })}, on this machine)`
+ : "open source (ComfyUI)"
+ : local
- ? "Claude (or Ollama when no key is set)"
++ ? `Claude (or ${llmLabel({ endpoint: "ollama" })} when no key is set)`
+ : "paid cloud API",
about: m.tagline,
does: [...new Set(m.routes.map((r) => r.op))].map((op) => `${op} (${OPERATION_LABELS[op]})`),
- price: m.engine === "open" ? (local ? "free (your machine)" : "free (your GPU)") : m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}` : "unknown",
+ price: dualEngine(m)
+ ? `free on your GPU; in the cloud ${m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.withLoras ? ` ($${m.pricing.withLoras} with LoRAs)` : ""}` : "priced per run"}`
+ : m.engine === "open"
+ ? local
+ ? "free (your machine)"
+ : "free (your GPU)"
+ : m.pricing
+ ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}`
+ : "unknown",
connected: configured,
...(o.aspectRatios && { aspectRatios: o.aspectRatios }),
...(o.resolutions && { resolutions: o.resolutions }),
diff --cc src/server/chains.ts
index f87ef2e7,a4b73289..fce5c461
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@@ -1,12 -1,16 +1,17 @@@
import "server-only";
import { nanoid } from "nanoid";
import { getModel, supportsOp } from "@/lib/catalog";
+ import { MODEL3D_STEP_FEATURE, stillPromptFor3d } from "@/lib/av/model3d";
+ import { chainTiming, frameTimes, planKeyframeClips, spread } from "@/lib/catalog/keyframes";
+ import { onEngine } from "@/lib/catalog/engines";
import { routesFor } from "@/lib/catalog/plan";
- import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
+ import type { ChainSlot, Engine, Generation, GenerationRequest, LoraRef, ModelDef, ModelRoute, Operation } from "@/lib/catalog/types";
import { db } from "./db";
- import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
+ import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained, previewGeneration } from "./generations";
import { provider } from "./providers";
+import { llmLabel } from "./providers/llm";
+ import { loadManifest } from "./providers/comfyui";
+ import { offeredRoutes, requireOffered } from "./model-access";
/**
* Multi-step jobs built from chained generations: each step waits for the ones it needs and
@@@ -22,10 -26,12 +27,12 @@@ interface ModeStep
label: string;
modelId: string;
op: Operation;
+ /** The engine a Fuobe Original's step runs on (its routes there are the ones checked). */
+ engine?: Engine;
}
-/** Who can run a model's operation, as Settings names them ("fal.ai", "Claude or Ollama"). */
-export const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? "Claude or Ollama" : provider(r.provider).label)))].join(" or ");
+/** Who can run a model's operation, as Settings names them ("fal.ai", "Claude or LM Studio"). */
+export const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? llmLabel(r) : provider(r.provider).label)))].join(" or ");
/**
* A chain must not mix paid and demo steps: a demo join of paid clips (or a paid step fed a demo
diff --cc src/server/content-factory.ts
index 00000000,eb9b7584..93ed38f7
mode 000000,100644..100644
--- a/src/server/content-factory.ts
+++ b/src/server/content-factory.ts
@@@ -1,0 -1,881 +1,905 @@@
+ import "server-only";
+ import { nanoid } from "nanoid";
+ import { z } from "zod";
+ import { getModel } from "@/lib/catalog";
+ import {
+ BRIEF_SYSTEM,
+ briefCostUsd,
+ briefRequest,
+ CF_LENGTH_VALUES,
+ claudeMessage,
+ claudePlan,
+ episodeTopic,
+ getPreset,
+ MAX_BRIEF_FRAMES,
+ MAX_EPISODES,
+ MAX_PROMPT,
+ MAX_REFERENCE_SECONDS,
+ noMediaMessage,
+ offlineBrief,
+ offlineSeries,
+ OPEN_REFERENCE_SECONDS,
+ pageMedia,
+ parseBrief,
+ parseSeries,
+ PLATFORM_LABEL,
+ referenceLink,
+ seriesBrief,
+ seriesPrice,
+ seriesSettings,
+ SERIES_SYSTEM,
+ type AnimationStyleId,
+ type ClaudePrompt,
+ type ReferencePlatform,
+ type SeriesAnalysis,
+ type SeriesCard,
+ type SeriesEpisodePlan,
+ type SeriesEstimate,
+ type SeriesReference,
+ type SeriesSettings,
+ type SeriesView,
+ type StyleBrief,
+ } from "@/lib/catalog/content-factory";
+ import { genreInfo, pickerData, type ChannelSettings, type EpisodeSettings, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";
+ import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+ import { probeMedia } from "@/lib/media-probe";
+ import { authEnabled } from "./auth";
+ import { db } from "./db";
+ import { llmText, llmTextBackend, type LlmImage } from "./enhance";
+ import { askLlm, createChannel, createEpisode, deleteChannel, estimateEpisode, FacelessError, getChannel, handle as facelessHandle, listEpisodes, VoiceSchema } from "./faceless";
+ import { cancelGeneration, createGenerations, getGeneration, previewGeneration } from "./generations";
++import type { JsonSpec } from "./llm";
+ import { fetchRemote, RemoteFetchError } from "./remote-fetch";
+ import { engineMode } from "./settings";
+ import { readRef, saveFile } from "./storage";
+ import { probeWebm } from "./webm-probe";
+
++/** BRIEF_SYSTEM's JSON as a schema, so a local model answers with a brief rather than prose (Claude reads the prompt). */
++const S = { type: "string" };
++const N = { type: "number" };
++const oneOf = (...values: string[]) => ({ type: "string", enum: values });
++const objectOf = (properties: Record<string, unknown>) => ({ type: "object", properties, required: Object.keys(properties), additionalProperties: false });
++const BRIEF_SCHEMA: JsonSpec = {
++ name: "style_brief",
++ schema: objectOf({
++ format: S,
++ hook: S,
++ pacing: objectOf({ average_shot_seconds: N, description: S }),
++ shots: { type: "array", items: S },
++ visual_style: objectOf({ medium: S, palette: S, lighting: S, texture: S }),
++ animation_style: oneOf("Fully animated", "Seamless motion video", "Scene by scene video", "Frame by frame"),
++ narration: objectOf({ tone: S, words_per_minute: N, language: S }),
++ music: objectOf({ genre: S, mood: S, energy: oneOf("low", "medium", "high") }),
++ captions: objectOf({ style: S, position: oneOf("top", "center", "bottom") }),
++ aspect_ratio: oneOf("9:16", "16:9"),
++ topic_ideas: { type: "array", items: S, minItems: 5, maxItems: 5 },
++ }),
++};
++
+ /*
+ * Content Factory on the server: a series (a reference clip, a preset or nothing; the style brief read
+ * from it; the planned episodes) whose episodes are Faceless episodes in a channel of its own. Nothing is
+ * forked from Faceless: the series makes a channel with the brief in its settings, and every episode is
+ * createEpisode with the brief applied (src/lib/catalog/faceless.ts reads EpisodeSettings.brief).
+ *
+ * Reading a reference:
+ * - cloud: extract-frames (fal, about one frame a second, at most 20 sent on) and Scribe v2's transcript run
+ * as generations; when both are done Claude (llmText, with the frames as pictures) writes the brief.
+ * - open: one generation, oss-reference-brief (reference-brief-gemma4 on ComfyUI: Gemma 4 E4B watches the
+ * first 30 s at a frame a second and hears the sound), whose answer is the brief.
+ * Whatever can't be read (demo mode, no LLM, an answer that isn't a brief) gives way to the offline brief
+ * from the clip's shape, length and narration pace, with a note that says so.
+ *
+ * The step generations live in the generations table (they survive restarts); the brief is written by
+ * whoever reads the series first once they're done (seriesView), in this process.
+ */
+
+ export class NeedsUpload extends FacelessError {
+ constructor(message: string) {
+ super(message, 422);
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Rows
+
+ interface SeriesData {
+ name: string | null;
+ prompt: string;
+ reference: SeriesReference | null;
+ analysis: SeriesAnalysis | null;
+ brief: StyleBrief | null;
+ settings: SeriesSettings | null;
+ plan: SeriesEpisodePlan[];
+ /** Its episodes in series order (they're often made in the same millisecond). */
+ episodeIds?: string[];
+ }
+
+ interface SeriesRow {
+ id: string;
+ channel_id: string | null;
+ data_json: string;
+ created_at: number;
+ updated_at: number;
+ }
+
+ const seriesRow = (id: string) => db().prepare("SELECT * FROM content_series WHERE id = ?").get(id) as SeriesRow | undefined;
+ const dataOf = (r: SeriesRow) => JSON.parse(r.data_json) as SeriesData;
+
+ function mustRow(id: string): SeriesRow {
+ const r = seriesRow(id);
+ if (!r) throw new FacelessError("Series not found", 404);
+ return r;
+ }
+
+ function save(id: string, data: SeriesData, channelId?: string | null): void {
+ const now = Date.now();
+ if (channelId !== undefined) db().prepare("UPDATE content_series SET data_json = ?, channel_id = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), channelId, now, id);
+ else db().prepare("UPDATE content_series SET data_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), now, id);
+ }
+
+ /** Change a series' data in place (a re-read, so a brief written or edited meanwhile isn't lost). */
+ function patch(id: string, fn: (d: SeriesData) => SeriesData | void, channelId?: string | null): SeriesData | null {
+ const r = seriesRow(id);
+ if (!r) return null;
+ const d = dataOf(r);
+ const next = fn(d) ?? d;
+ save(id, next, channelId);
+ return next;
+ }
+
+ declare global {
+ var __fuobeContentRuns: Set<string> | undefined;
+ }
+ /** Series a "Generate here" or "Next episode" is planning or starting right now (this process). */
+ const running = () => (globalThis.__fuobeContentRuns ??= new Set<string>());
+
+ /**
+ * One run at a time per series, claimed before anything awaits: planning asks the LLM for up to 25 s, and a
+ * second click (or Enter) meanwhile would otherwise make a second channel and bill every episode twice.
+ */
+ function claim(id: string, busy: string): () => void {
+ if (running().has(id)) throw new FacelessError(busy, 409);
+ running().add(id);
+ return () => void running().delete(id);
+ }
+
+ /** Drafts are kept this long (the composer's clip across reloads); "Generate here" makes them series. */
+ const DRAFT_MS = 3 * 24 * 60 * 60 * 1000;
+
+ /** Old drafts that never ran, and series whose channel was deleted in Faceless Studio (their episodes went with it). */
+ function pruneSeries(): void {
+ const drafts = db().prepare("SELECT * FROM content_series WHERE channel_id IS NULL AND updated_at < ?").all(Date.now() - DRAFT_MS) as SeriesRow[];
+ const orphans = db()
+ .prepare("SELECT s.* FROM content_series s LEFT JOIN faceless_channels c ON c.id = s.channel_id WHERE s.channel_id IS NOT NULL AND c.id IS NULL")
+ .all() as SeriesRow[];
+ for (const r of [...drafts, ...orphans]) {
+ if (running().has(r.id)) continue;
+ for (const g of Object.values(dataOf(r).analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
+ db().prepare("DELETE FROM content_series WHERE id = ?").run(r.id);
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // The reference: an upload, a link (fetched through the SSRF-safe fetchRemote), or a preset
+
+ const MAX_CLIP_BYTES = 200 * 1024 * 1024;
+ const VIDEO_TYPE = /^video\/(mp4|quicktime|webm|x-m4v)$/;
+
+ /** Length and shape from the clip's own header (MP4/MOV or WebM), when it says. */
+ function clipFacts(data: Buffer): Pick<SeriesReference, "seconds" | "width" | "height" | "fps"> {
+ const info = probeMedia(data);
+ if (info?.hasVideo) return { seconds: info.videoDuration ?? info.duration, width: info.width, height: info.height, fps: info.fps };
+ const webm = probeWebm(data);
+ return webm ? { seconds: webm.duration, width: webm.width, height: webm.height, fps: webm.fps } : {};
+ }
+
+ const round1 = (n: number | undefined) => (n === undefined || !Number.isFinite(n) ? undefined : Math.round(n * 10) / 10);
+
+ async function saveClip(data: Buffer, contentType: string, name: string): Promise<Pick<SeriesReference, "url" | "seconds" | "width" | "height" | "fps">> {
+ const facts = clipFacts(data);
+ const url = saveFile({ data, contentType, name, source: "upload" }).url;
+ return { url, seconds: round1(facts.seconds), width: facts.width, height: facts.height, fps: round1(facts.fps) };
+ }
+
+ /** What a fetched clip really is (its bytes over the server's word): MP4, MOV or WebM, with a file name to match. */
+ export function clipType(data: Buffer, said = ""): { contentType: string; name: string } {
+ const head = data.subarray(0, 64);
+ if (head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3) return { contentType: "video/webm", name: "reference.webm" };
+ if (head.length >= 12 && head.toString("latin1", 4, 8) === "ftyp" && head.toString("latin1", 8, 12) === "qt ") return { contentType: "video/quicktime", name: "reference.mov" };
+ if (head.length >= 8 && head.toString("latin1", 4, 8) === "ftyp") return { contentType: "video/mp4", name: "reference.mp4" };
+ if (said === "video/webm") return { contentType: said, name: "reference.webm" };
+ if (said === "video/quicktime") return { contentType: said, name: "reference.mov" };
+ return { contentType: "video/mp4", name: "reference.mp4" };
+ }
+
+ /** A video behind a link, or null when the answer isn't one. */
+ async function fetchClip(url: string): Promise<{ data: Buffer; contentType: string; name: string } | null> {
+ const res = await fetchRemote(url, { maxBytes: MAX_CLIP_BYTES, timeoutMs: 90_000 });
+ const type = res.contentType?.split(";")[0].trim().toLowerCase() ?? "";
+ if (VIDEO_TYPE.test(type) || (type === "application/octet-stream" && clipFacts(res.data).seconds)) return { data: res.data, ...clipType(res.data, type) };
+ return null;
+ }
+
+ /** The file name in a link's path, as a title ("my%20clip.mp4" → "my clip.mp4"); a malformed escape is kept as written. */
+ export function linkTitle(url: string): string | undefined {
+ const raw = new URL(url).pathname.split("/").pop() ?? "";
+ let name = raw;
+ try {
+ name = decodeURIComponent(raw);
+ } catch {
+ // "%E0%A4%A" isn't UTF-8: the raw name still says which clip it was.
+ }
+ return name.slice(0, 120) || undefined;
+ }
+
+ const FETCH_FAILED = "Fuobe couldn't fetch that link. Check it opens in a private window, or upload the clip instead.";
+
+ /** A pasted link → the clip saved here, with the page's title and picture (fetched only through fetchRemote). */
+ async function readLink(raw: string): Promise<SeriesReference> {
+ const checked = referenceLink(raw);
+ if ("error" in checked) throw new FacelessError(checked.error);
+ const { url, platform } = checked;
+ // YouTube never hands its files out; a page from the platforms may (an og:video), so they're tried.
+ if (platform === "youtube") throw new NeedsUpload(noMediaMessage(platform));
+ const ref: SeriesReference = { kind: "link", link: url, platform };
+ try {
+ if (platform === "direct") {
+ const title = linkTitle(url);
+ const clip = await fetchClip(url);
+ if (!clip) throw new NeedsUpload(noMediaMessage(platform));
+ return { ...ref, ...(await saveClip(clip.data, clip.contentType, clip.name)), ...(title && { title }) };
+ }
+ const page = await fetchRemote(url, { maxBytes: 3 * 1024 * 1024, timeoutMs: 15_000 });
+ const type = page.contentType?.split(";")[0].trim().toLowerCase() ?? "";
+ if (VIDEO_TYPE.test(type)) {
+ const t = clipType(page.data, type);
+ return { ...ref, ...(await saveClip(page.data, t.contentType, t.name)) };
+ }
+ const media = pageMedia(page.data.toString("utf8"), page.url);
+ if (!media.video) throw new NeedsUpload(noMediaMessage(platform));
+ const clip = await fetchClip(media.video);
+ if (!clip) throw new NeedsUpload(noMediaMessage(platform));
+ const saved = await saveClip(clip.data, clip.contentType, clip.name);
+ let thumbnail: string | undefined;
+ if (media.image) {
+ try {
+ const img = await fetchRemote(media.image, { maxBytes: 4 * 1024 * 1024, timeoutMs: 8000 });
+ const t = img.contentType?.split(";")[0] ?? "";
+ if (/^image\/(jpeg|png|webp|gif)$/.test(t)) thumbnail = saveFile({ data: img.data, contentType: t, name: "reference-thumbnail.jpg", source: "upload" }).url;
+ } catch {
+ // The card shows the clip itself.
+ }
+ }
+ return { ...ref, ...saved, ...(media.title && { title: media.title }), ...(thumbnail && { thumbnail }) };
+ } catch (e) {
+ if (e instanceof FacelessError) throw e;
+ // A private address is refused with its own words; anything else (a 404, a timeout, a login wall) reads the same.
+ throw new NeedsUpload(e instanceof RemoteFetchError && /private network|this machine/.test(e.message) ? e.message : FETCH_FAILED);
+ }
+ }
+
+ /** An uploaded clip (already in this install's files). */
+ async function readUpload(url: string, title?: string): Promise<SeriesReference> {
+ if (!url.startsWith("/api/files/")) throw new FacelessError("Upload the clip first");
+ let file: Awaited<ReturnType<typeof readRef>>;
+ try {
+ file = await readRef(url);
+ } catch {
+ throw new FacelessError("That upload is gone — add the clip again");
+ }
+ if (!file.contentType.startsWith("video/")) throw new FacelessError("Add a video clip (MP4, MOV or WebM) as the reference");
+ const facts = clipFacts(file.data);
+ return { kind: "upload", url, title: title?.trim().slice(0, 120) || file.name, seconds: round1(facts.seconds), width: facts.width, height: facts.height, fps: round1(facts.fps) };
+ }
+
+ export type ReferenceInput = { kind: "upload"; url: string; title?: string } | { kind: "link"; link: string } | { kind: "preset"; presetId: string };
+
+ async function resolveReference(input: ReferenceInput): Promise<SeriesReference> {
+ if (input.kind === "upload") return readUpload(input.url, input.title);
+ if (input.kind === "link") return readLink(input.link);
+ const p = getPreset(input.presetId);
+ if (!p) throw new FacelessError("That preset isn't there any more — pick another");
+ return { kind: "preset", presetId: p.id, title: p.name };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Reading the reference into a brief
+
+ const STEP_LABEL = { frames: "Reference frames", transcript: "Reference transcript", brief: "Reference brief" } as const;
+
+ const engineAllowed = (engine: Engine) => engineMode() === "both" || engineMode() === engine;
+ function checkEngine(engine: Engine): void {
+ if (!engineAllowed(engine)) throw new FacelessError(engine === "open" ? "This install is set to paid cloud APIs only (Settings → Engine mode)" : "This install is set to open source only (Settings → Engine mode)");
+ }
+
+ function request(ref: SeriesReference, key: keyof typeof STEP_LABEL, r: Omit<GenerationRequest, "feature">): GenerationRequest {
+ return { feature: "content-factory", ...r, step: { label: STEP_LABEL[key], index: 0, of: 1 }, batchTitle: `Content Factory · ${ref.title ?? "reference"}` } as GenerationRequest;
+ }
+
+ /** Every Nth frame for about one a second, at most MAX_BRIEF_FRAMES over the clip (extract-frames counts frames). */
+ export function frameInterval(seconds: number | undefined, fps: number | undefined): number {
+ const secs = Math.max(1, Math.min(MAX_REFERENCE_SECONDS, seconds ?? 30));
+ const rate = fps && fps > 0 && fps <= 240 ? fps : 30;
+ const frames = Math.max(1, Math.min(MAX_BRIEF_FRAMES, Math.round(secs)));
+ return Math.max(1, Math.min(300, Math.round((secs * rate) / frames)));
+ }
+
+ /** The step generations for one read of the clip (none can start: the offline brief, with why). */
+ function startSteps(ref: SeriesReference, engine: Engine): { steps: SeriesAnalysis["steps"]; costUsd: number | null; demo: boolean; error?: string } {
+ const steps: SeriesAnalysis["steps"] = {};
+ let cost = 0;
+ let demo = false;
+ const errors: string[] = [];
+ const run = (key: keyof typeof STEP_LABEL, r: GenerationRequest) => {
+ try {
+ const p = previewGeneration(r);
+ const g = createGenerations(r)[0];
+ steps[key] = g.id;
+ cost += p.costUsd ?? 0;
+ demo ||= p.demo;
+ } catch (e) {
+ errors.push((e as Error).message);
+ }
+ };
+ if (engine === "open") {
+ run("brief", request(ref, "brief", { modelId: "oss-reference-brief", op: "write", inputs: { video: ref.url }, params: { duration: Math.min(OPEN_REFERENCE_SECONDS, ref.seconds ?? OPEN_REFERENCE_SECONDS) } }));
+ } else {
+ // JPEG, not fal's default PNG: a full-HD PNG frame can weigh 3 MB, and Claude takes 32 MB a request.
+ run("frames", request(ref, "frames", { modelId: "extract-frames", op: "extract-frames", inputs: { video: ref.url }, params: { frameInterval: frameInterval(ref.seconds, ref.fps), extra: { output_format: "jpg", quality: 80 } } }));
+ run("transcript", request(ref, "transcript", { modelId: "scribe-v2", op: "transcribe", inputs: { video: ref.url }, params: { ...(ref.seconds && { duration: ref.seconds, sourceDuration: ref.seconds }) } }));
+ }
+ return { steps, costUsd: engine === "open" ? 0 : Math.round(cost * 1000) / 1000, demo, ...(errors.length && !Object.keys(steps).length && { error: errors[0] }) };
+ }
+
+ function beginAnalysis(id: string, ref: SeriesReference, engine: Engine): SeriesAnalysis {
+ const started = startSteps(ref, engine);
+ if (started.error) {
+ // Nothing can read the clip on this engine right now: the brief from its header, and why.
+ return { engine, status: "ready", steps: {}, offline: true, note: `${started.error}. This brief comes from the clip's shape and length only — fix that and read it again.`, costUsd: 0 };
+ }
+ return { engine, status: "reading", steps: started.steps, stage: engine === "open" ? "Gemma 4 is watching the clip…" : "Reading the frames and the words…", costUsd: started.costUsd, demo: started.demo };
+ }
+
+ declare global {
+ var __fuobeContentBriefs: Map<string, Promise<void>> | undefined;
+ }
+ const writing = () => (globalThis.__fuobeContentBriefs ??= new Map<string, Promise<void>>());
+
+ /** Wait for a series' brief to be written (tests). */
+ export const briefWritten = (id: string) => writing().get(id) ?? Promise.resolve();
+
+ const done = (g: Generation | null) => !g || g.status === "succeeded" || g.status === "failed" || g.status === "canceled";
+ const textOf = (g: Generation | null) => (g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "text") : undefined);
+ const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
+
+ /** Up to `n` items spread evenly over a list (first and last kept). */
+ export function spread<T>(list: T[], n: number): T[] {
+ if (list.length <= n) return list;
+ if (n <= 1) return list.slice(0, 1);
+ return Array.from({ length: n }, (_, i) => list[Math.round((i * (list.length - 1)) / (n - 1))]);
+ }
+
+ const IMAGE_TYPE = /^image\/(jpeg|png|gif|webp)$/;
+
+ /** Claude takes images of up to 5 MB each (as base64, 4/3 of the file) in a request of up to 32 MB. */
+ export const MAX_FRAME_BYTES = 3_750_000;
+ /** All the frames of one request together, as files: about 20 MB as base64, well inside the request limit. */
+ export const FRAME_BUDGET_BYTES = 15_000_000;
+
+ /** The frames that fit the request: none over the per-image limit, then fewer (still spread over the clip) until they fit the budget. */
+ export function fitFrames<T extends { data: Buffer }>(frames: T[], budget = FRAME_BUDGET_BYTES, each = MAX_FRAME_BYTES): T[] {
+ const ok = frames.filter((f) => f.data.length <= each);
+ const total = (list: T[]) => list.reduce((n, f) => n + f.data.length, 0);
+ for (let n = ok.length; n > 0; n--) {
+ const picked = spread(ok, n);
+ if (total(picked) <= budget) return picked;
+ }
+ return [];
+ }
+
+ async function framesOf(g: Generation | null): Promise<LlmImage[]> {
+ if (g?.status !== "succeeded") return [];
+ const outs = g.outputs.filter((o) => o.kind === "image" && !o.meta?.demo);
+ const picked = spread(
+ [...outs].sort((a, b) => Number(a.meta?.index ?? 0) - Number(b.meta?.index ?? 0)),
+ MAX_BRIEF_FRAMES,
+ );
+ const images: LlmImage[] = [];
+ for (const o of picked) {
+ try {
+ const f = await readRef(o.url);
+ if (IMAGE_TYPE.test(f.contentType)) images.push({ data: f.data, contentType: f.contentType });
+ } catch {
+ // A frame that can't be read is left out.
+ }
+ }
+ return fitFrames(images);
+ }
+
+ async function writeBrief(id: string): Promise<void> {
+ const r = seriesRow(id);
+ if (!r) return;
+ const d = dataOf(r);
+ const a = d.analysis;
+ const ref = d.reference;
+ if (!a || a.status !== "reading" || !ref) return;
+ const base = offlineBrief({ seconds: ref.seconds, width: ref.width, height: ref.height, title: ref.title });
+ const header = ref.width && ref.height ? { aspect: base.aspect } : {};
+ let brief: StyleBrief = base;
+ let note: string | undefined;
+ let offline = false;
+
+ if (a.engine === "open") {
+ const g = getGeneration(a.steps.brief ?? "", { includeDeleted: true });
+ const out = textOf(g);
+ const parsed = out && !out.meta?.demo ? parseBrief(out.text ?? "", base) : null;
+ if (parsed) brief = { ...parsed.brief, ...header };
+ else {
+ offline = true;
+ note = out?.meta?.demo
+ ? "Demo brief — start ComfyUI (with Gemma 4 E4B) to read the clip for real. This one comes from the clip's shape and length."
+ : g?.status === "failed"
+ ? `Gemma 4 couldn't read the clip (${g.error ?? "it failed"}). This brief comes from the clip's shape and length — read it again to retry.`
+ : "Gemma 4's answer wasn't a brief. This one comes from the clip's shape and length — read it again to retry.";
+ }
+ } else {
+ const framesGen = getGeneration(a.steps.frames ?? "", { includeDeleted: true });
+ const wordsGen = getGeneration(a.steps.transcript ?? "", { includeDeleted: true });
+ const words = textOf(wordsGen);
+ const cues = words && !words.meta?.demo && Array.isArray(words.meta?.cues) ? (words.meta.cues as TimedText[]) : [];
+ const frames = await framesOf(framesGen);
+ const fallback = offlineBrief({ seconds: ref.seconds, width: ref.width, height: ref.height, cues, title: ref.title });
+ brief = fallback;
+ const demo = (framesGen?.outputs.some((o) => o.meta?.demo) ?? false) || !!words?.meta?.demo;
+ if (!frames.length && !cues.length) {
+ offline = true;
+ note = demo
+ ? "Demo brief — connect fal and Claude in Settings to read the clip for real. This one comes from the clip's shape and length."
+ : `The clip couldn't be read (${framesGen?.error ?? wordsGen?.error ?? "no frames or words came back"}). This brief comes from its shape and length — read it again to retry.`;
+ } else if (!llmTextBackend()) {
+ offline = true;
+ note = "No LLM is connected (Settings → AI helper), so this brief comes from the clip's shape, length and narration pace.";
+ } else {
+ const transcript = cues.map((c) => `[${mmss(c.start)}] ${c.text.trim()}`).join("\n");
+ const user = briefRequest({ seconds: ref.seconds, width: ref.width, height: ref.height, frames: frames.length, transcript, title: ref.title });
+ // A text-only Ollama model can't take pictures: it answers from the words then.
- const answer = (await llmText(BRIEF_SYSTEM, user, frames)) ?? (frames.length && llmTextBackend() === "ollama" ? await llmText(BRIEF_SYSTEM, user) : null);
++ const json = { json: BRIEF_SCHEMA };
++ const answer = (await llmText(BRIEF_SYSTEM, user, frames, json)) ?? (frames.length && llmTextBackend() === "ollama" ? await llmText(BRIEF_SYSTEM, user, json) : null);
+ const parsed = answer ? parseBrief(answer, fallback) : null;
+ if (parsed) brief = { ...parsed.brief, ...header };
+ else {
+ offline = true;
+ note = "The LLM didn't answer with a brief, so this one comes from the clip's shape, length and narration pace — read it again to retry.";
+ }
+ }
+ }
+ patch(id, (cur) => {
+ // Read again (or deleted) meanwhile: that read wins.
+ if (cur.analysis?.status !== "reading" || JSON.stringify(cur.analysis.steps) !== JSON.stringify(a.steps)) return;
+ cur.brief = brief;
+ cur.analysis = { ...cur.analysis, status: "ready", stage: undefined, offline: offline || undefined, note };
+ });
+ }
+
+ /** Moves a reading series on: the steps' progress, then the brief once they're all done. */
+ function advance(id: string, d: SeriesData): SeriesData {
+ const a = d.analysis;
+ if (!a || a.status !== "reading") return d;
+ const gens = Object.values(a.steps).map((g) => getGeneration(g, { includeDeleted: true }));
+ if (!gens.every(done)) {
+ const running = gens.find((g) => g && !done(g));
+ return { ...d, analysis: { ...a, stage: running?.status === "queued" ? "Waiting for its turn…" : a.stage } };
+ }
+ if (!writing().has(id)) {
+ const job = writeBrief(id)
+ .catch((e: Error) => {
+ patch(id, (cur) => {
+ if (cur.analysis?.status === "reading") cur.analysis = { ...cur.analysis, status: "failed", stage: undefined, error: e.message || "Couldn't write the brief" };
+ });
+ })
+ .finally(() => writing().delete(id));
+ writing().set(id, job);
+ }
+ return { ...d, analysis: { ...a, stage: a.engine === "open" ? "Writing the brief…" : "Claude is writing the brief…" } };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Series
+
+ /** Episode 1 first: the series' own in plan order, then any made in Faceless Studio's channel page, oldest first. */
+ function inOrder<T extends { id: string; createdAt: number }>(cards: T[], ids: string[]): T[] {
+ const at = new Map(ids.map((id, i) => [id, i]));
+ const rank = (c: T) => at.get(c.id) ?? ids.length;
+ return [...cards].sort((a, b) => rank(a) - rank(b) || a.createdAt - b.createdAt);
+ }
+
+ function toView(r: SeriesRow, d: SeriesData): SeriesView {
+ const channel = r.channel_id ? getChannel(r.channel_id) : null;
+ return {
+ id: r.id,
+ name: d.name ?? channel?.name ?? null,
+ prompt: d.prompt,
+ reference: d.reference,
+ analysis: d.analysis,
+ brief: d.brief,
+ settings: d.settings,
+ plan: d.plan,
+ channel,
+ made: !!r.channel_id,
+ episodes: channel ? inOrder(listEpisodes({ channelId: channel.id, limit: 200 }), d.episodeIds ?? []) : [],
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+ }
+
+ export function seriesView(id: string): SeriesView {
+ const r = mustRow(id);
+ return toView(r, advance(id, dataOf(r)));
+ }
+
+ /** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */
+ export async function createSeries(input: { reference: ReferenceInput | null; engine: Engine; prompt?: string }): Promise<SeriesView> {
+ checkEngine(input.engine);
+ pruneSeries();
+ const reference = input.reference ? await resolveReference(input.reference) : null;
+ const id = nanoid(10);
+ const now = Date.now();
+ const preset = reference?.kind === "preset" ? getPreset(reference.presetId) : undefined;
+ const data: SeriesData = { name: null, prompt: input.prompt?.trim().slice(0, MAX_PROMPT) ?? "", reference, analysis: null, brief: preset ? preset.brief : null, settings: null, plan: [] };
+ if (preset) data.analysis = { engine: input.engine, status: "ready", steps: {}, costUsd: 0 };
+ db().prepare("INSERT INTO content_series (id, channel_id, data_json, created_at, updated_at) VALUES (?, NULL, ?, ?, ?)").run(id, JSON.stringify(data), now, now);
+ if (reference?.url) {
+ data.analysis = beginAnalysis(id, reference, input.engine);
+ if (data.analysis.status === "ready") data.brief = offlineBrief({ seconds: reference.seconds, width: reference.width, height: reference.height, title: reference.title });
+ save(id, data);
+ }
+ return seriesView(id);
+ }
+
+ /** Read the reference again (after an offline brief, a failure, or on the other engine). */
+ export async function rereadSeries(id: string, engine: Engine): Promise<SeriesView> {
+ checkEngine(engine);
+ const r = mustRow(id);
+ const d = dataOf(r);
+ if (!d.reference?.url) throw new FacelessError("This series has no clip to read — add one first");
+ for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
+ d.analysis = beginAnalysis(id, d.reference, engine);
+ if (d.analysis.status === "ready") d.brief = offlineBrief({ seconds: d.reference.seconds, width: d.reference.width, height: d.reference.height, title: d.reference.title });
+ save(id, d);
+ return seriesView(id);
+ }
+
+ export const BriefSchema = z.object({
+ format: z.string().max(400),
+ hook: z.string().max(400),
+ shotSeconds: z.number().min(1).max(30),
+ pacing: z.string().max(400),
+ shots: z.array(z.string().max(120)).max(12),
+ look: z.string().max(600),
+ styleId: z.string().max(60),
+ animation: z.enum(["fully-animated", "seamless", "scene-by-scene", "frame-by-frame"]),
+ voice: z.object({ tone: z.string().max(200), wordsPerMinute: z.number().min(60).max(300).optional(), language: z.string().max(40).optional() }),
+ music: z.object({ mood: z.string().max(300), energy: z.enum(["low", "medium", "high"]).optional() }),
+ captions: z.object({ style: z.string().max(200), position: z.enum(["top", "center", "bottom"]), words: z.number().int().min(1).max(8) }),
+ aspect: z.enum(["9:16", "16:9"]),
+ topics: z.array(z.string().max(200)).max(12),
+ });
+
+ /** Edit the brief by hand, or rename the series. */
+ export function updateSeries(id: string, p: { brief?: StyleBrief; name?: string }): SeriesView {
+ const r = mustRow(id);
+ const d = dataOf(r);
+ if (p.brief) {
+ if (d.analysis?.status === "reading") throw new FacelessError("Wait for the brief to be read first", 409);
+ d.brief = p.brief;
+ }
+ if (p.name !== undefined) d.name = p.name.trim().slice(0, 60) || null;
+ save(id, d);
+ return seriesView(id);
+ }
+
+ /** Deletes a series with its channel; `draftOnly` (the composer letting go of a clip) leaves a made series alone. */
+ export async function deleteSeries(id: string, o: { draftOnly?: boolean } = {}): Promise<void> {
+ const r = mustRow(id);
+ if (running().has(id)) throw new FacelessError("Its episodes are being planned — delete it once they've started", 409);
+ if (o.draftOnly && r.channel_id) return;
+ const d = dataOf(r);
+ for (const g of Object.values(d.analysis?.steps ?? {})) void cancelGeneration(g).catch(() => {});
+ if (r.channel_id && getChannel(r.channel_id)) await deleteChannel(r.channel_id);
+ db().prepare("DELETE FROM content_series WHERE id = ?").run(id);
+ }
+
+ /** Series that have been made (drafts that never ran stay out of the list). */
+ export function listSeries(): SeriesCard[] {
+ const rows = db().prepare("SELECT * FROM content_series WHERE channel_id IS NOT NULL ORDER BY updated_at DESC LIMIT 100").all() as SeriesRow[];
+ return rows.flatMap((r) => {
+ const channel = getChannel(r.channel_id!);
+ if (!channel) return [];
+ const d = dataOf(r);
+ const eps = inOrder(listEpisodes({ channelId: channel.id, limit: 200 }), d.episodeIds ?? []);
+ const first = eps.find((e) => e.still) ?? eps[0];
+ return [
+ {
+ id: r.id,
+ name: d.name ?? channel.name,
+ prompt: d.prompt,
+ channelId: channel.id,
+ episodes: eps.length,
+ done: eps.filter((e) => e.status === "done").length,
+ rendering: eps.filter((e) => e.status === "rendering" || e.status === "writing").length,
+ poster: first?.still ?? null,
+ thumbnail: d.reference?.thumbnail ?? null,
+ styleId: channel.settings.styleId,
+ aspect: channel.settings.aspect,
+ updatedAt: r.updated_at,
+ },
+ ];
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Settings, prices and the plan
+
+ export interface SeriesInput {
+ prompt: string;
+ settings: SeriesSettings;
+ /** The narrator: null on the open engine until a sample is added; left out, one is picked for the brief's tone. */
+ voice?: NarratorVoice | null;
+ subtitles?: boolean;
+ music?: boolean;
+ }
+
+ function briefFor(o: { seriesId?: string; presetId?: string; brief?: StyleBrief }): StyleBrief {
+ if (o.brief) return o.brief;
+ if (o.seriesId) {
+ const d = dataOf(mustRow(o.seriesId));
+ if (d.brief) return d.brief;
+ if (d.analysis?.status === "reading") throw new FacelessError("The reference is still being read — a moment", 409);
+ }
+ const p = o.presetId ? getPreset(o.presetId) : undefined;
+ if (p) return p.brief;
+ throw new FacelessError("Add a reference or pick a preset style first");
+ }
+
+ const voices = () => pickerData(getModel).voices;
+
+ export function episodeSettings(input: SeriesInput, brief: StyleBrief): EpisodeSettings {
+ const s = input.settings;
+ if (!CF_LENGTH_VALUES.includes(s.length)) throw new FacelessError("Choose one of the offered lengths (30 sec to 5 min)");
+ return seriesSettings({
+ engine: s.engine,
+ length: s.length,
+ animation: s.animation,
+ aspect: s.aspect,
+ brief,
+ genre: genreInfo(s.genre),
+ ...(input.voice !== undefined && { voice: input.voice }),
+ voices: voices(),
+ subtitles: input.subtitles,
+ music: input.music,
+ });
+ }
+
+ /** What reading a minute of reference costs here (fal frames + Scribe v2 + Claude; nothing on the open engine or as a demo). */
+ function analysisPerMinute(engine: Engine): number {
+ if (engine === "open") return 0;
+ try {
+ const frames = previewGeneration({ feature: "content-factory", modelId: "extract-frames", op: "extract-frames", inputs: { video: "/api/files/estimate.mp4" }, params: { frameInterval: 90 } });
+ const words = previewGeneration({ feature: "content-factory", modelId: "scribe-v2", op: "transcribe", inputs: { video: "/api/files/estimate.mp4" }, params: { duration: 60, sourceDuration: 60 } });
+ if (frames.demo && words.demo) return 0;
+ return briefCostUsd({ seconds: 60, framesUsd: frames.costUsd ?? 0, transcribePerMinute: words.costUsd ?? 0, claude: llmTextBackend() === "claude" });
+ } catch {
+ return 0;
+ }
+ }
+
+ /** The whole series' price before anything runs: one episode at the brief's pace, times the episodes. */
+ export function estimateSeries(input: SeriesInput & { seriesId?: string; presetId?: string; brief?: StyleBrief }): SeriesEstimate {
+ const s = input.settings;
+ const perMinute = analysisPerMinute(s.engine);
+ let brief: StyleBrief;
+ let pending = false;
+ try {
+ brief = briefFor(input);
+ } catch {
+ const row = input.seriesId ? seriesRow(input.seriesId) : undefined;
+ const d = row ? dataOf(row) : null;
+ pending = d?.analysis?.status === "reading";
+ // Still reading: what the clip's length and shape already say (the price comes again with the brief).
+ // No reference yet: the default look, so the composer always shows a price.
+ brief = pending && d?.reference ? offlineBrief({ seconds: d.reference.seconds, width: d.reference.width, height: d.reference.height }) : getPreset("what-if")!.brief;
+ }
+ const settings = episodeSettings(input, brief);
+ const est = estimateEpisode({ kind: "faceless", settings, genre: s.genre });
+ return {
+ price: seriesPrice(est.estimate, s.episodes),
+ demo: est.demo,
+ seconds: est.seconds,
+ scenes: est.blocks,
+ ...(est.error && { error: est.error }),
+ ...(est.notes && { notes: est.notes }),
+ analysisPerMinute: perMinute,
+ ...(pending && { briefPending: true }),
+ };
+ }
+
+ const PLAN_TIMEOUT_MS = 25_000;
+
+ /** Episode titles: the engine's LLM when it answers in time, else the genre's beats around the prompt. */
+ async function planEpisodes(o: { prompt: string; settings: SeriesSettings; brief: StyleBrief; count: number; previous: string[]; next?: string }): Promise<{ name: string | null; episodes: SeriesEpisodePlan[] }> {
+ const genre = genreInfo(o.settings.genre);
+ if (o.count === 1 && !o.previous.length && !o.next?.trim()) return { name: null, episodes: offlineSeries(o.prompt, genre.id, 1) };
+ const answer = await askLlm(o.settings.engine, SERIES_SYSTEM, seriesBrief({ prompt: o.prompt, genre, count: o.count, format: o.brief.format, previous: o.previous, next: o.next }), { timeoutMs: PLAN_TIMEOUT_MS });
+ const parsed = answer ? parseSeries(answer) : null;
+ const got = (parsed?.episodes ?? []).slice(0, o.count);
+ const fill = offlineSeries(o.prompt, genre.id, o.count - got.length, o.previous.length + got.length);
+ // Without the LLM, the next episode is what the user said happens in it.
+ const episodes = [...got, ...fill].map((e, i) => (i === 0 && !got.length && o.next?.trim() ? { ...e, synopsis: o.next.trim().slice(0, 400) } : e));
+ return { name: parsed?.name ?? null, episodes };
+ }
+
+ const COULDNT_PLAN = "Couldn't plan your episodes. You weren't charged, so it's safe to try again.";
+
+ function startEpisodes(o: { channelId: string; prompt: string; plan: SeriesEpisodePlan[]; earlier: string[]; settings: EpisodeSettings; review: boolean; series: boolean }): string[] {
+ const titles = [...o.earlier];
+ const ids: string[] = [];
+ o.plan.forEach((ep) => {
+ const topic = episodeTopic(o.prompt, ep, { number: titles.length + 1, earlier: titles, series: o.series });
+ const made = createEpisode({ kind: "faceless", channelId: o.channelId, topic, settings: o.settings, autoRender: !o.review, saveLook: false, ...(o.series && { title: ep.title }) });
+ ids.push(made.id);
+ titles.push(ep.title);
+ });
+ return ids;
+ }
+
+ /** "Generate here": plan the episodes, make the series' channel, and start every episode (rendered straight after its script unless `review`). */
+ export async function generateSeries(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {
+ const r = mustRow(id);
+ if (r.channel_id) throw new FacelessError("This series is made — add episodes from its page", 409);
+ const release = claim(id, "This series is being made — a moment");
+ try {
+ return await generateClaimed(id, input);
+ } finally {
+ release();
+ }
+ }
+
+ async function generateClaimed(id: string, input: SeriesInput & { review?: boolean }): Promise<SeriesView> {
+ checkEngine(input.settings.engine);
+ const prompt = input.prompt.trim();
+ if (!prompt) throw new FacelessError("Say what the video is about");
+ const brief = briefFor({ seriesId: id });
+ const settings = episodeSettings(input, brief);
+ const est = estimateEpisode({ kind: "faceless", settings, genre: input.settings.genre });
+ if (est.error) throw new FacelessError(est.error);
+ const count = Math.max(1, Math.min(MAX_EPISODES, Math.round(input.settings.episodes)));
+ let plan: { name: string | null; episodes: SeriesEpisodePlan[] };
+ let channelId: string;
+ try {
+ plan = await planEpisodes({ prompt, settings: input.settings, brief, count, previous: [] });
+ const channelSettings: ChannelSettings = {
+ engine: settings.engine,
+ styleId: settings.styleId,
+ styleRefs: [],
+ voice: settings.voice,
+ aspect: settings.aspect,
+ subtitles: settings.subtitles,
+ music: settings.music,
+ animation: settings.animation,
+ length: settings.length,
+ ...(settings.brief && { brief: settings.brief }),
+ };
+ const channel = await createChannel({ idea: prompt, genre: input.settings.genre, engine: settings.engine, ...(plan.name && { name: plan.name }), avatar: false, settings: channelSettings });
+ channelId = channel.id;
+ } catch (e) {
+ if (e instanceof FacelessError) throw e;
+ throw new FacelessError(COULDNT_PLAN, 500);
+ }
+ // Seen as made from here on (a second click gets "This series is made"); a brief edited meanwhile is kept.
+ patch(id, (cur) => ({ ...cur, name: plan.name, prompt, settings: { ...input.settings, episodes: count }, plan: plan.episodes }), channelId);
+ const ids = startEpisodes({ channelId, prompt, plan: plan.episodes, earlier: [], settings, review: !!input.review, series: count > 1 });
+ patch(id, (cur) => ({ ...cur, episodeIds: ids }));
+ return seriesView(id);
+ }
+
+ /** "Next episode": plan more after the ones already made, the first one following what the user says happens in it. */
+ export async function addEpisodes(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {
+ mustRow(id);
+ const release = claim(id, "Episodes are being added to this series — a moment");
+ try {
+ return await addClaimed(id, input);
+ } finally {
+ release();
+ }
+ }
+
+ async function addClaimed(id: string, input: { count: number; next?: string; review?: boolean }): Promise<SeriesView> {
+ const r = mustRow(id);
+ const d = dataOf(r);
+ const channel = r.channel_id ? getChannel(r.channel_id) : null;
+ if (!channel || !d.settings || !d.brief) throw new FacelessError("Make the series first", 409);
+ checkEngine(channel.settings.engine);
+ const count = Math.max(1, Math.min(MAX_EPISODES, Math.round(input.count)));
+ const settings = episodeSettings({ prompt: d.prompt, settings: { ...d.settings, engine: channel.settings.engine }, voice: channel.settings.voice, subtitles: channel.settings.subtitles, music: channel.settings.music }, d.brief);
+ const est = estimateEpisode({ kind: "faceless", settings, genre: d.settings.genre });
+ if (est.error) throw new FacelessError(est.error);
+ const previous = d.plan.map((e) => e.title);
+ const more = await planEpisodes({ prompt: d.prompt, settings: d.settings, brief: d.brief, count, previous, next: input.next }).catch(() => {
+ throw new FacelessError(COULDNT_PLAN, 500);
+ });
+ const ids = startEpisodes({ channelId: channel.id, prompt: d.prompt, plan: more.episodes, earlier: previous, settings, review: !!input.review, series: true });
+ // Read again before writing: a brief edited while the episodes were planned is kept.
+ patch(id, (cur) => {
+ const plan = [...cur.plan, ...more.episodes];
+ return { ...cur, plan, settings: { ...(cur.settings ?? d.settings!), episodes: plan.length }, episodeIds: [...(cur.episodeIds ?? []), ...ids] };
+ });
+ return seriesView(id);
+ }
+
+ // ---------------------------------------------------------------------------
+ // "Generate in Claude"
+
+ /** The engine Fuobe's MCP tools run on (src/server/mcp.ts: the cloud unless the install is open source only). */
+ const mcpEngine = (): Engine => (engineMode() === "open" ? "open" : "cloud");
+
+ export function claudePrompt(input: SeriesInput & { seriesId?: string; presetId?: string }): ClaudePrompt {
+ const brief = briefFor(input);
+ const s = input.settings;
+ const d = input.seriesId ? dataOf(mustRow(input.seriesId)) : null;
+ const ref = d?.reference;
+ const reference = ref && ref.kind !== "preset" ? `${ref.title ? `“${ref.title}”` : "clip"}${ref.platform ? ` (${PLATFORM_LABEL[ref.platform as ReferencePlatform]})` : ""}` : null;
+ const engine = mcpEngine();
+ const voice = engine === "cloud" && input.voice?.kind === "preset" ? input.voice.id : null;
+ const voiceSample = engine === "open" && input.voice?.kind === "sample" ? input.voice.url : null;
+ const animation = s.animation as AnimationStyleId;
+ const message = claudeMessage({ prompt: input.prompt, brief, length: s.length, episodes: s.episodes, animation, genre: genreInfo(s.genre), aspect: s.aspect, engine, voice, voiceSample, reference });
+ const plan = claudePlan({ length: s.length, brief, animation });
+ const engineNote =
+ s.engine === engine
+ ? undefined
+ : engine === "open"
+ ? "Claude's runs use the open-source engine (your ComfyUI): this install is set to Open source only."
+ : engineMode() === "both"
+ ? "Claude's runs use the cloud engine and your paid providers, not your GPU: Fuobe's MCP server follows Settings → Engine mode, which is set to both. Set it to Open source only to run them on your ComfyUI, or use Generate here."
+ : "Claude's runs use the cloud engine and your paid providers: this install is set to paid cloud APIs only.";
+ return { message, bytes: new TextEncoder().encode(message).length, needsToken: authEnabled(), engine, ...(engineNote && { engineNote }), parts: plan.parts, partSeconds: plan.partSeconds };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Schemas and the API's error shape
+
+ export const SeriesSettingsSchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ length: z.number().int().min(15).max(600),
+ episodes: z.number().int().min(1, "At least one episode").max(MAX_EPISODES, `Up to ${MAX_EPISODES} episodes at a time`),
+ animation: z.enum(["fully-animated", "seamless", "scene-by-scene", "frame-by-frame"]),
+ genre: z.enum(["education", "history", "kids", "storytelling"]),
+ aspect: z.enum(["9:16", "16:9"]),
+ });
+
+ export const SeriesInputSchema = z.object({
+ prompt: z.string().max(MAX_PROMPT, `Keep it under ${MAX_PROMPT} characters`),
+ settings: SeriesSettingsSchema,
+ voice: VoiceSchema.nullable().optional(),
+ subtitles: z.boolean().optional(),
+ music: z.boolean().optional(),
+ });
+
+ export const ReferenceSchema = z.union([
+ z.object({ kind: z.literal("upload"), url: z.string().startsWith("/api/files/").max(500), title: z.string().max(200).optional() }),
+ z.object({ kind: z.literal("link"), link: z.string().max(2000) }),
+ z.object({ kind: z.literal("preset"), presetId: z.string().max(60) }),
+ ]);
+
+ /** The faceless API's `{ error }` responses, plus `needsUpload` when a link gave no clip. */
+ export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {
+ try {
+ return await fn();
+ } catch (e) {
+ if (e instanceof NeedsUpload) return Response.json({ error: e.message, needsUpload: true }, { status: e.status });
+ return facelessHandle(() => {
+ throw e;
+ });
+ }
+ }
diff --cc src/server/enhance.ts
index 77852139,1a4552d1..3f1183a1
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@@ -49,39 -60,46 +61,59 @@@ async function viaClaude(system: string
return text || null;
}
-async function viaOllama(system: string, user: string, images: LlmImage[] = []): Promise<string | null> {
- const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model: getSetting("ollamaModel"),
- stream: false,
- think: false,
- messages: [
- { role: "system", content: system },
- // A vision model (qwen3-vl, gemma3…) reads the pictures; a text-only one answers from the words.
- { role: "user", content: user, ...(images.length && { images: images.map((i) => i.data.toString("base64")) }) },
- ],
- }),
- signal: AbortSignal.timeout(images.length ? 180_000 : 60_000),
+export interface LlmTextOptions {
+ /** The JSON Schema the answer follows on a local model (Claude follows the prompt); see JsonSpec. */
+ json?: JsonSpec;
- /** How long to wait (default: 60 s, or 3 minutes when the local model isn't loaded yet). */
++ /** How long to wait (default: 60 s, or 3 minutes with pictures or when the local model isn't loaded yet). */
+ timeoutMs?: number;
++ /** The open engine: a local model, never Claude (the AI helper set to Offline still means none). */
++ ollamaOnly?: boolean;
+}
+
- /** The local model in use, thinking off where the server allows it. */
- async function viaLocal(system: string, user: string, opts: LlmTextOptions): Promise<string | null> {
++/** The local model in use (Ollama, LM Studio, Unsloth Studio or the custom server), thinking off where the server allows it. */
++async function viaLocal(system: string, user: string, images: LlmImage[], opts: LlmTextOptions): Promise<string | null> {
+ const ready = await activeLocal();
+ if (!ready) return null;
+ const r = await chatLocal(ready, {
+ messages: [
+ { role: "system", content: system },
- { role: "user", content: user },
++ // A vision model (qwen3-vl, gemma3…) reads the pictures; a text-only one answers from the words.
++ { role: "user", content: user, ...(images.length && { images: images.map((i) => ({ data: i.data.toString("base64"), contentType: i.contentType })) }) },
+ ],
+ think: false,
+ json: opts.json,
- timeoutMs: opts.timeoutMs ?? (ready.status.loaded === false ? 180_000 : 60_000),
++ timeoutMs: opts.timeoutMs ?? (images.length || ready.status.loaded === false ? 180_000 : 60_000),
});
- if (!res.ok) throw new Error(`ollama ${res.status}`);
- const j = (await res.json()) as { message?: { content?: string } };
- return j.message?.content?.replace(/<think>[\s\S]*?<\/think>/g, "").trim() || null;
+ return r.text || null;
}
-/** Which LLM llmText would ask right now (Claude is the one that costs money). */
+/**
- * One-shot text from whichever LLM this install allows: Claude (when a key is set, and never
- * on "open source only" installs unless picked explicitly), else a local model. Null when none.
++ * Which LLM llmText would ask right now (Claude is the one that costs money). "ollama" means a local
++ * model, whichever server runs it (Ollama, LM Studio, Unsloth Studio or the custom one: Settings → AI helper).
+ */
- export async function llmText(system: string, user: string, opts: LlmTextOptions = {}): Promise<string | null> {
+ export function llmTextBackend(): "claude" | "ollama" | null {
- const choice = getSetting("enhanceProvider");
+ const choice = aiHelper();
if (choice === "none") return null;
- const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));
- if (useClaude) return viaClaude(system, user).catch(() => null);
- return viaLocal(system, user, opts).catch(() => null);
+ if (choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"))) return "claude";
- return choice === "ollama" || choice === "auto" ? "ollama" : null;
++ return "ollama";
+ }
+
+ /**
+ * One-shot text from whichever LLM this install allows: Claude (when a key is set, and never
- * on "open source only" installs unless picked explicitly), else a local Ollama. Null when none.
- * `images` go along for a model that can see them (Content Factory's reference frames).
++ * on "open source only" installs unless picked explicitly), else a local model. Null when none.
++ * `images` go along for a model that can see them (Content Factory's reference frames); `json`
++ * holds a local model to a schema. Takes (system, user, opts) or (system, user, images, opts).
+ */
-export async function llmText(system: string, user: string, images: LlmImage[] = [], o: { ollamaOnly?: boolean } = {}): Promise<string | null> {
- // The open engine never calls a paid API: Ollama, unless the AI helper is off.
- const backend = o.ollamaOnly && llmTextBackend() === "claude" ? "ollama" : llmTextBackend();
++export async function llmText(system: string, user: string, opts?: LlmTextOptions): Promise<string | null>;
++export async function llmText(system: string, user: string, images?: LlmImage[], opts?: LlmTextOptions): Promise<string | null>;
++export async function llmText(system: string, user: string, a: LlmImage[] | LlmTextOptions = [], b: LlmTextOptions = {}): Promise<string | null> {
++ const images: LlmImage[] = Array.isArray(a) ? a : [];
++ const opts: LlmTextOptions = Array.isArray(a) ? b : a;
++ // The open engine never calls a paid API: a local model, unless the AI helper is off.
++ const backend = opts.ollamaOnly && llmTextBackend() === "claude" ? "ollama" : llmTextBackend();
+ if (backend === "claude") return viaClaude(system, user, images).catch(() => null);
- if (backend === "ollama") return viaOllama(system, user, images).catch(() => null);
++ if (backend === "ollama") return viaLocal(system, user, images, opts).catch(() => null);
+ return null;
}
/** Deterministic fallback so the toggle always does something useful offline. */
@@@ -96,6 -114,23 +128,23 @@@ export function heuristicEnhance(prompt
return `${p}. Highly detailed, natural skin and material texture, cinematic lighting, thoughtful composition, shot on a full-frame camera with a 50mm lens, shallow depth of field.`;
}
+ /** Fuobe Soul's enhancer (research §4.2): the user's words grown into one scene; the look adds the style itself. */
+ const SOUL_SYSTEM =
+ "You expand a short image prompt into one vivid scene of 60 to 120 words for a photographic image model. Keep every word and idea the user wrote. " +
+ "Add only what a photographer would decide: subject, wardrobe, pose, place, light, lens and film stock. Don't name an art style, filter or colour grade, and don't add text, signs or watermarks. " +
+ "Answer with the prompt only: plain sentences, no quotes, no lists, no preamble.";
+
+ /**
- * Soul's words, expanded when an LLM is available (Claude or Ollama); otherwise the user's own words, since the
++ * Soul's words, expanded when an LLM is available (Claude or a local model); otherwise the user's own words, since the
+ * look already says how the picture should look (the generic offline rewrite would fight it).
+ */
+ export async function enhanceSoulWords(words: string): Promise<string> {
+ const w = words.trim();
+ if (!w || w.split(/\s+/).length >= 60) return words;
+ const out = (await llmText(SOUL_SYSTEM, w))?.trim().replace(/^["“]|["”]$/g, "").replace(/[.\s]+$/, "");
+ return out && out.length > w.length ? out : words;
+ }
+
export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
return (await llmText(SYSTEM, instruction(prompt, kind, op))) ?? heuristicEnhance(prompt, kind, op);
}
diff --cc src/server/faceless.ts
index 8a634fff,6826abcb..2d0ed04f
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@@ -216,10 -214,12 +220,12 @@@ const TOPICS_TIMEOUT_MS = 25_000
/** One answer from the engine's text model, or null (no LLM, AI helper off, demo mode on, or it failed: `onError` hears why). */
export async function askLlm(engine: Engine, system: string, user: string, o: AskOptions = {}): Promise<string | null> {
if (getSetting("demoMode") === "on") return null;
- const model = getModel(ENGINE_MODELS[engine].write);
+ // A text model switched off in Settings → Models & licences gives way to the offline wording, like no LLM at all.
+ const found = getModel(ENGINE_MODELS[engine].write);
+ const model = found && offeredModel(found);
const route = model?.routes.find((r) => r.op === "write");
if (!model || !route) return null;
- await probeOllama();
+ await probeLocal();
if (!llmBackends(route).length) return null;
const llm = provider("llm");
try {
@@@ -588,8 -604,9 +610,9 @@@ async function writeScript(id: string,
reference: channel?.reference ? [channel.reference.title, channel.reference.author && `by ${channel.reference.author}`].filter(Boolean).join(" ") || channel.reference.url : undefined,
sources: textSources,
auto,
+ style: s.brief?.script,
});
- const answer = await askLlm(s.engine, scriptSystem, brief, ask);
+ const answer = await askLlm(s.engine, scriptSystem, brief, { ...ask, json: scriptSchema(auto ? null : scenes) });
const parsed = answer ? parseScript(answer) : null;
if (parsed?.blocks.length) {
script = { source: "ai", title: parsed.title ?? undefined, blocks: parsed.blocks };
diff --cc src/server/generations.ts
index 1f6673f4,63a5462a..7862eab9
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@@ -24,17 -40,21 +40,22 @@@ import
import { db } from "./db";
import { listElements } from "./elements";
import { pollTrainings } from "./training";
- import { createExtendChain, createShotFilm } from "./chains";
- import { enhancePrompt } from "./enhance";
+ import { createExtendChain, createKeyframeFilm, createRelitClip, createShotFilm, createStillTo3d } from "./chains";
+ import { enhancePrompt, enhanceSoulWords } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
- import { provider } from "./providers";
- import { probeComfy } from "./providers/comfyui";
+ import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
+ import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
+ import { graphLoras } from "@/lib/catalog/character-swap";
+ import { ensureLorasOnComfy, prepareCloudLoras, withoutUnreachableCivitai } from "./loras";
+ import { offeredLoras, offeredRoutes, requireOffered } from "./model-access";
-import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
+import { llmBackends, llmLabel, llmMissing, llmUsesClaude, probeLocal } from "./providers/llm";
import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
+ import { mediaFacts } from "./media-facts";
+import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
- import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";
+ import { fetchRemoteToFile } from "./remote-fetch";
+ import { adoptFile, contentTypeFor, deleteAsset, readRef, saveFile, scratchDir } from "./storage";
interface Row {
id: string;
@@@ -425,16 -544,46 +547,46 @@@ function prepare(original: GenerationRe
plan = { ...plan, jobs: plan.jobs * plan.perJobOutputs, perJobOutputs: 1, params: { ...plan.params, numOutputs: 1 } };
}
const providerId: ProviderId = demo ? "mock" : route.provider;
- // A text step that runs on Ollama is free; only Claude costs money.
+ // A text step that runs on a local model is free; only Claude costs money.
const free = demo || (route.provider === "llm" && !llmUsesClaude(route));
- return { req, plan, route, demo, providerId, cost: free ? 0 : estimateCost(plan.model, plan.params, 1) };
+ const withLoras = fitted.loras.length > 0 && !!route.loraEndpoint;
+ const unreachable = asked.filter((l) => !reachable.loras.includes(l));
+ // Priced for the clip the route makes: Replicate's Wan 2.2 fast makes 5 s when 3 s was asked.
+ const priced = made !== undefined && plan.params.duration !== undefined ? { ...plan.params, duration: Math.round(made * 2) / 2 } : plan.params;
+ return { req, plan, route, demo, providerId, notes, asked, unreachable, switchedOff: access.dropped, cost: free ? 0 : estimateCost(plan.model, priced, 1, plan.op, withLoras) };
}
+ /** Operations whose clip length is the duration picked (made, or added by extend), not an input video's. */
+ const MADE_LENGTH_OPS = new Set<Operation>(["t2v", "i2v", "flf2v", "ref2v", "extend", "keyframes"]);
+
/** What a request would run as — model, operation, job count and cost — without starting it. */
- export function previewGeneration(req: GenerationRequest) {
- const { plan, demo, providerId, cost } = prepare(req);
- return { model: plan.model, op: plan.op, jobs: plan.jobs, outputs: plan.jobs * plan.perJobOutputs, demo, providerId, costUsd: cost === null ? null : cost * plan.jobs };
+ export function previewGeneration(asked: GenerationRequest) {
+ const moved = currentRequest(asked);
+ const prepared = prepare(moved.request);
+ const { plan, route, demo, providerId, cost, asked: askedLoras, unreachable, switchedOff } = prepared;
+ const notes = moved.note ? [moved.note, ...prepared.notes] : prepared.notes;
+ const fitted = routeLoras(route, askedLoras.filter((l) => !unreachable.includes(l)));
+ const loras = {
+ ...fitted,
+ dropped: [...switchedOff, ...unreachable.map((l) => ({ file: l.file, reason: "it downloads from civitai, which needs your civitai key (Settings → LoRAs)" })), ...fitted.dropped],
+ };
+ return {
+ model: plan.model,
+ op: plan.op,
+ jobs: plan.jobs,
+ outputs: plan.jobs * plan.perJobOutputs,
+ demo,
+ providerId,
+ costUsd: cost === null ? null : cost * plan.jobs,
+ // The engine it runs on (a Fuobe Original picks one per request).
+ engine: plan.model.engine,
+ // What the route runs (the evaluation harness records it): the provider endpoint, the final prompt and the LoRAs it loads.
+ route: { provider: route.provider, endpoint: loras.applied.length && route.provider !== "comfyui" && route.loraEndpoint ? route.loraEndpoint : route.endpoint },
+ prompt: plan.prompt,
+ loras,
+ ...(notes.length && { notes }),
+ };
}
/** Preview a step that will wait for `deps` earlier steps: validated with placeholders in its chain slots, as createGenerations does. */
@@@ -654,17 -982,34 +985,34 @@@ async function advanceDependents(): Pro
let handedOff = false;
try {
// The planned op (r.op), not request.op: a translate whose op was inferred still gets the cue list.
- const values = await Promise.all(deps.map((d, i) => chainValue(pickOutput(JSON.parse(d!.outputs_json) as OutputFile[], slots[i]), slots[i], r.op)));
+ const values = await Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op)));
const missing = values.findIndex((u) => !u);
if (missing >= 0) {
- update(r.id, { status: "failed", error: `${earlier} has no ${slotNoun(slots[missing])} to use`, message: null, completed_at: Date.now() });
+ fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);
continue;
}
- // Routing reads cached reachability: make sure it's fresh for local engines.
+ // Routing reads cached reachability: make sure it's fresh for local engines. An Original counts with the routes of
+ // the engine it runs on, ComfyUI taken as answering: one on the cloud doesn't use it, so doesn't wait for it.
const model = getModel(request.modelId);
- if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();
+ const runs = model && dualEngine(model) ? onEngine(model, pickEngine(model, request.engine, engineMode(), () => true)) : model;
+ if (runs?.routes.some((x) => x.provider === "comfyui") && !(await probeComfy()) && deps.some((d) => d!.provider === "comfyui")) {
+ // The earlier steps ran for real on ComfyUI: one missed check (a server busy finishing them, or restarting)
+ // mustn't make this one a demo, which chainMode fails. Look again at once (one forced look a sweep), then wait
+ // for the next sweeps (COMFY_WAIT from the first miss) before chainMode has its say.
+ const first = comfyWaits().get(r.id);
+ const back = first === undefined && (await (lookedAgain ??= probeComfy(true)));
+ if (!back && first === undefined) {
+ comfyWaits().set(r.id, Date.now());
+ update(r.id, { message: "Waits for ComfyUI to answer" });
+ continue;
+ }
+ if (!back && Date.now() - first! < COMFY_WAIT.ms) continue;
+ }
+ comfyWaits().delete(r.id);
- if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
+ if (model?.routes.some((x) => x.provider === "llm")) await probeLocal();
- const original = withChainInputs(request, values as string[]);
+ // Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
+ const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
+ const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
const prepared = prepare(original);
const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);
if (mode.error) throw new Error(mode.error);
@@@ -970,14 -1356,13 +1362,21 @@@ async function pollOne(r: Row): Promise
console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);
}
}
+ // Fuobe Soul: what follows in the browser (the look's grade, an overlay, Soul Cinema's 21:9 crop), on each image;
+ // API clients read it as meta.
+ const post = soulPostSteps(r.model_id, r.preset_id, soulKind(r.model_id) ? requestAspect(r.request_json) : undefined);
+ if (post) for (const [i, o] of outputs.entries()) if (o.kind === "image") outputs[i] = { ...o, meta: { ...o.meta, ...post } };
+ // Fuobe DoP's colour-grade effects: the grade the browser applies to the clip (the result's "Apply the grade" step).
+ const grade = isDop(r.model_id) && r.preset_id ? getPreset(r.preset_id)?.grade : undefined;
+ if (grade) for (const [i, o] of outputs.entries()) if (o.kind === "video") outputs[i] = { ...o, meta: { ...o.meta, grade } };
+ // An image-to-3D GLB from ComfyUI gets the server's finish first (the web GLB, seconds): the outputs are
+ // stored now and the row stays running until it's done, so a restart resumes it from them. The turntable
+ // is rendered after the job has succeeded (src/server/model3d-finish.ts).
+ if (modelToFinish(r, outputs) >= 0) {
+ update(r.id, { outputs_json: JSON.stringify(outputs), external_meta_json: JSON.stringify({ ...ctx.meta, finishing: true }), message: "Finishing the 3D model" });
+ resumeFinish({ ...r, outputs_json: JSON.stringify(outputs) });
+ return;
+ }
update(r.id, {
status: "succeeded",
outputs_json: JSON.stringify(outputs),
@@@ -1094,8 -1490,50 +1552,51 @@@ export async function cancelGeneration(
.cancel?.(pollContext(r, model))
.catch(() => {});
}
+ stopModelFinish(id);
update(id, { status: "canceled", completed_at: Date.now(), message: null });
+ // Steps waiting only to feed this one are dropped too (nothing was spent on them).
+ dropUnused(depIds(r.depends_on));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Fuobe Soul's post steps (the look's grade and overlay), made in the browser when the result arrives.
+
+ /** The aspect ratio a stored request asked for (Soul Cinema's 21:9 is made at 16:9 and cropped). */
+ function requestAspect(json: string): string | undefined {
+ try {
+ return (JSON.parse(json) as GenerationRequest).params?.aspectRatio;
+ } catch {
+ return undefined;
+ }
+ }
+
+ export class FinishError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+ }
+
+ /**
+ * Keep the finished picture of a Soul result in place of the raw one: the raw one stays as meta.original (its
+ * file is still the generation's), meta.finished marks it done. The first finished copy wins: another tab's
+ * answer is 409, and an output with nothing left to do is refused.
+ */
+ export function finishOutput(id: string, index: number, png: Buffer): Generation {
+ const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row | undefined;
+ if (!r) throw new FinishError("Not found", 404);
+ if (r.status !== "succeeded") throw new FinishError("The result isn't ready yet", 409);
+ const outputs = JSON.parse(r.outputs_json) as OutputFile[];
+ const o = outputs[index];
+ if (!o || !Number.isInteger(index)) throw new FinishError("No such output", 404);
+ if (o.meta?.finished) throw new FinishError("Already finished", 409);
+ if (!finishSteps(o)) throw new FinishError("This output has no grade or overlay to apply", 400);
+ const asset = saveFile({ data: png, contentType: "image/png", name: `${id}-${index}-finished.png`, source: "generation", generationId: id });
+ outputs[index] = { ...o, url: asset.url, assetId: asset.id, contentType: "image/png", meta: { ...o.meta, finished: true, original: o.url } };
+ update(id, { outputs_json: JSON.stringify(outputs) });
+ return getGeneration(id, { includeDeleted: true })!;
}
// ---------------------------------------------------------------------------
diff --cc src/server/genjutsu.ts
index 00000000,a42a3158..ce91ef58
mode 000000,100644..100644
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@@ -1,0 -1,587 +1,589 @@@
+ import "server-only";
+ import { z } from "zod";
+ import { getModel } from "@/lib/catalog";
+ import { onEngine } from "@/lib/catalog/engines";
+ import {
+ ANCHOR_MODELS,
+ anchorModel,
+ CHARACTER_GPU,
+ CHARACTER_LIMITS,
+ CHARACTER_SWAP,
+ characterLicenceLine,
+ cutWarning,
+ h3Windows,
+ swapLoraRef,
+ SWAP_LORAS,
+ TURBO_LORA,
+ windowPlan,
+ type CharacterOptions,
+ } from "@/lib/catalog/character-swap";
+ import { ACCESS_PLACE } from "@/lib/model-access";
+ import {
+ chooseMaker,
+ cutsInPart,
+ GENJUTSU,
+ genjutsuProblem,
+ genjutsuTitle,
+ makersFor,
+ MODE_TARGETS,
+ planGenjutsu,
+ planMakerPieces,
+ qualityFor,
+ makerStepUsd,
+ resolutionWords,
+ SOURCE_LABELS,
+ type GenjutsuLook,
+ type GenjutsuMode,
+ type GenjutsuPlanInput,
+ type GenjutsuTarget,
+ type GenjutsuTier,
+ type Maker,
+ type MakerSource,
+ } from "@/lib/catalog/genjutsu";
+ import { MASK_TRACKER, REMOVE_TOOLS, scalePoints, wholeClip, type RemoveRange, type RemoveSource } from "@/lib/catalog/remove-object";
+ import { planSegments, type PlanStep } from "@/lib/catalog/shorts";
+ import type { Engine, Generation, PixelPoint, ProviderId } from "@/lib/catalog/types";
+ import { silenceWriter } from "./canvas";
+ import { createPipeline } from "./chains";
+ import { llmText, llmTextBackend } from "./enhance";
+ import { createGenerations, previewChained } from "./generations";
++import { localLabel } from "./llm";
+ import { isOffered, offeredLoras, offeredModel } from "./model-access";
+ import { provider } from "./providers";
+ import { probeOllama } from "./providers/llm";
+ import { pointsFromPaint } from "./remove-object";
+ import { engineMode, getSetting } from "./settings";
+ import { probeSource, ShortsError } from "./shorts";
+ import { readRef } from "./storage";
+
+ /**
+ * Fuobe Genjutsu (/genjutsu): plans, prices and starts a Motion transfer, Character swap, Object swap, Restyle or Insert
+ * (src/lib/catalog/genjutsu.ts) as one pipeline of ordinary generations: feature "genjutsu" for the finished video,
+ * "genjutsu-step" for the cuts, tracks, anchor frames, pieces and joins. No table of its own: the page's history is a
+ * feed, and a setup travels as a code (encodeSetup), not a row. No Higgsfield model runs here.
+ */
+
+ export { ShortsError as GenjutsuError };
+
+ export interface GenjutsuBody {
+ engine: Engine;
+ mode: GenjutsuMode;
+ /** The model picked (defaults per engine and mode: the Fuobe Original). */
+ modelId?: string;
+ /** Lite ("standard") or the full Original ("high"). */
+ tier?: GenjutsuTier;
+ quality?: string;
+ target?: GenjutsuTarget;
+ /** Object swap: what goes. */
+ subject?: string;
+ /** Guidance (Character swap: your direction). */
+ prompt?: string;
+ points?: PixelPoint[];
+ /** The picture the points or the paint were made on (the first frame the browser showed). */
+ frame?: { width: number; height: number };
+ mask?: string;
+ references?: string[];
+ look?: GenjutsuLook;
+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };
+ range?: RemoveRange;
+ seed?: number;
+ /** Character swap's settings. */
+ character?: CharacterOptions;
+ /** Hard cuts the browser found in the clip (seconds), for the "one continuous shot" warning. */
+ cuts?: number[];
+ }
+
+ const fileUrl = z.string().startsWith("/api/files/").max(500);
+ const seconds = z.number().finite().min(0).max(3600);
+ const point = z.object({ x: z.number().finite().min(0).max(20000), y: z.number().finite().min(0).max(20000), label: z.enum(["positive", "negative"]).optional() });
+ const look = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("preset"), id: z.string().max(80) }),
+ z.object({ kind: z.literal("soul"), id: z.string().max(80) }),
+ z.object({ kind: z.literal("custom"), images: z.array(fileUrl).max(GENJUTSU.maxLookImages), words: z.string().max(300).optional() }),
+ ]);
+ const character = z.object({
+ who: z.enum(["largest", "leftmost", "rightmost", "index"]).optional(),
+ index: z.number().int().min(0).max(CHARACTER_SWAP.maxPeople - 1).optional(),
+ subject: z.string().max(120).optional(),
+ maskGrow: z.number().int().min(0).max(256).optional(),
+ anchor: z.boolean().optional(),
+ anchorModel: z.enum(["gpt-image-2-5-sunburst", "nano-banana-pro", "oss-qwen-edit"]).optional(),
+ description: z.string().max(CHARACTER_SWAP.maxDescriptionChars).optional(),
+ speech: z.enum(["character", "other", "offscreen", "none"]).optional(),
+ dialogue: z.string().max(2000).optional(),
+ lora: z.enum(["v1.5", "v1", "none"]).optional(),
+ audioGuide: z.boolean().optional(),
+ useMask: z.boolean().optional(),
+ windowFrames: z.number().int().min(22).max(362).optional(),
+ historyFrames: z.number().int().min(0).max(341).optional(),
+ });
+
+ /** The body of /api/genjutsu (and /estimate). */
+ export const GenjutsuBodySchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ mode: z.enum(["motion", "character", "swap", "restyle", "insert"]),
+ modelId: z.string().max(80).optional(),
+ tier: z.enum(["standard", "high"]).optional(),
+ quality: z.enum(["480p", "720p", "768p", "1080p"]).optional(),
+ target: z.enum(["type", "click", "paint"]).optional(),
+ subject: z.string().max(300).optional(),
+ prompt: z.string().max(GENJUTSU.maxPromptChars).optional(),
+ points: z.array(point).max(GENJUTSU.maxPoints).optional(),
+ frame: z.object({ width: z.number().int().positive().max(20000), height: z.number().int().positive().max(20000) }).optional(),
+ mask: fileUrl.optional(),
+ references: z.array(fileUrl).max(GENJUTSU.maxReferences).optional(),
+ look: look.optional(),
+ source: z.object({
+ url: fileUrl,
+ name: z.string().max(200).optional(),
+ duration: z.number().finite().positive().max(3600).optional(),
+ fps: z.number().finite().positive().max(240).optional(),
+ width: z.number().int().positive().max(20000).optional(),
+ height: z.number().int().positive().max(20000).optional(),
+ hasAudio: z.boolean().optional(),
+ }),
+ range: z.object({ start: seconds, end: seconds }).optional(),
+ seed: z.number().int().min(0).max(2 ** 48).optional(),
+ character: character.optional(),
+ cuts: z.array(seconds).max(200).optional(),
+ /** A client nonce for one submit: a repeat gets the first answer (see once()). */
+ requestId: z.string().trim().min(8).max(64).optional(),
+ });
+
+ /** The estimate is asked for before uploads finish: any URL stands in. */
+ export const GenjutsuEstimateSchema = GenjutsuBodySchema.extend({
+ source: GenjutsuBodySchema.shape.source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }),
+ mask: z.string().max(500).optional(),
+ references: z.array(z.string().max(500)).max(GENJUTSU.maxReferences).optional(),
+ });
+
+ const mustMatchMode = (engine: Engine) => {
+ const mode = engineMode();
+ if (mode !== "both" && mode !== engine) {
+ throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);
+ }
+ };
+
+ interface Planned {
+ input: GenjutsuPlanInput;
+ maker: Maker;
+ notes: string[];
+ }
+
+ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<Planned> {
+ mustMatchMode(body.engine);
+ const picked = chooseMaker({
+ engine: body.engine,
+ mode: body.mode,
+ target: body.target,
+ tier: body.tier,
+ look: body.look,
+ modelId: body.modelId,
+ offered: (id) => isOffered(id, body.engine),
+ });
+ if ("problem" in picked) throw new ShortsError(picked.problem, 422);
+ const maker = picked.maker;
+ // The header's facts win over what the browser read (the estimate runs before the upload is read).
+ const info = opts.probe ? await probeSource(body.source.url) : {};
+ const source: RemoveSource = {
+ url: body.source.url,
+ duration: info.duration ?? body.source.duration,
+ fps: info.fps ?? body.source.fps,
+ width: info.width ?? body.source.width,
+ height: info.height ?? body.source.height,
+ // Sound we couldn't read counts as none (putting it back would fail after the work was paid for).
+ hasAudio: opts.probe ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),
+ };
+ // Character swap's part defaults to the first 15 s (Openjutsu's Length); the other modes take up to 30 s.
+ const longest = body.mode === "character" ? CHARACTER_SWAP.maxSeconds : GENJUTSU.maxSeconds;
+ const range = body.range ?? (source.duration ? { start: 0, end: Math.min(source.duration, longest) } : null);
+ if (!range) throw new ShortsError("Reading the clip… try again in a moment");
+ const target = MODE_TARGETS[body.mode].length ? (body.target ?? MODE_TARGETS[body.mode][0]) : undefined;
+ const references = body.references ?? [];
+ const clicks = (body.points ?? []).filter((p) => p.label !== "negative").length;
+ const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look, seed: body.seed, character: body.character });
+ if (problem) throw new ShortsError(problem, 422);
+ const switched = body.mode === "character" && maker.h3 ? characterSwitches(maker, body.character ?? {}) : { character: body.character, notes: [] };
+
+ // Clicks on the first frame, in the clip's pixels; paint is followed from its deepest points (SAM 3.1 on fal).
+ let points: PixelPoint[] | undefined;
+ const size = source.width && source.height ? { width: source.width, height: source.height } : null;
+ if (target === "click") points = body.frame && size ? scalePoints(body.points!.slice(0, GENJUTSU.maxPoints), body.frame, size) : body.points;
+ const pieces = planMakerPieces(maker, source, range);
+ // Restyle on Fuobe's looks runs in the Shorts chain's segments (the open Original and partners).
+ const shortsChain = body.mode === "restyle" && maker.looks === "fuobe" && !(maker.engine === "cloud" && maker.source === "original");
+ const n = (shortsChain ? planSegments(range, maker.engine).length : pieces.length) || 1;
+ const tracksPaint = maker.engine === "cloud" && body.mode === "swap" && target === "paint" && (maker.source === "original" || n > 1);
+ if (tracksPaint) points = opts.probe ? await pointsFromPaint(body.mask!, source, "Paint over what to swap first") : [{ x: 1, y: 1, label: "positive" }];
+
+ const notes = [...switched.notes, ...notesFor({ ...body, character: switched.character }, maker, source, range, n, references.length)];
+ const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
+ const title = genjutsuTitle({ mode: body.mode, subject: body.subject, look: body.look });
+ return {
+ maker,
+ notes,
+ input: {
+ engine: body.engine,
+ mode: body.mode,
+ maker,
+ title: name ? `${title} · ${name}` : title,
+ source,
+ range,
+ quality: body.quality ?? (body.mode === "character" ? CHARACTER_SWAP.defaultQuality : GENJUTSU.defaultQuality),
+ references,
+ target,
+ subject: body.subject?.trim() || undefined,
+ prompt: body.prompt?.trim() || undefined,
+ points,
+ mask: target === "paint" ? body.mask : undefined,
+ look: body.look,
+ ...(body.seed !== undefined ? { seed: body.seed } : {}),
+ ...(body.mode === "character" ? { character: switched.character ?? {} } : {}),
+ },
+ };
+ }
+
+ /**
+ * The Character swap with what Settings → Models & licences switched off taken out: the first-frame model (the next one
+ * that is on, else no first frame) and the swap LoRA (on your GPU H3 runs without it; fal's route needs one). Turbo off
+ * on the open engine stops the run: the 8-step graph can't go without it.
+ */
+ function characterSwitches(m: Maker, c: CharacterOptions): { character: CharacterOptions; notes: string[] } {
+ const notes: string[] = [];
+ let out = c;
+ if (m.h3?.anchor && c.anchor !== false) {
+ const wanted = anchorModel(m.engine, c.anchorModel);
+ if (!isOffered(wanted.id, m.engine)) {
+ const next = ANCHOR_MODELS[m.engine].find((a) => isOffered(a.id, m.engine));
+ out = next ? { ...out, anchorModel: next.id } : { ...out, anchor: false };
+ notes.push(next ? `${wanted.label} is switched off in ${ACCESS_PLACE}: ${next.label} makes the first frame` : `The first-frame models are switched off in ${ACCESS_PLACE}: the swap runs without a first frame`);
+ }
+ }
+ const lora = c.lora ?? "v1.5";
+ if (lora !== "none" && offeredLoras([swapLoraRef(lora)]).dropped.length) {
+ if (m.engine === "cloud") throw new ShortsError(`The swap LoRA (${SWAP_LORAS[lora].label}) is switched off in ${ACCESS_PLACE}, and fal's H3 route needs one — turn it on, or pick the other release`, 422);
+ out = { ...out, lora: "none" };
+ notes.push(`The swap LoRA is switched off in ${ACCESS_PLACE}: H3 runs with the Turbo LoRA alone`);
+ }
+ if (m.engine === "open" && offeredLoras([TURBO_LORA]).dropped.length) throw new ShortsError(`The H3 Turbo LoRA is switched off in ${ACCESS_PLACE}, and the Character swap's 8-step graph needs it — turn it on to run it on your GPU`, 422);
+ return { character: out, notes };
+ }
+
+ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: RemoveRange, n: number, refs: number): string[] {
+ const notes: string[] = [];
+ const name = getModel(m.id)?.name ?? m.label;
+ const fps = source.fps ?? 30;
+ const fuobeLook = body.mode === "restyle" && m.looks === "fuobe";
+ const len = range.end - range.start;
+ if (body.mode === "character" && m.h3) {
+ const c = body.character ?? {};
+ if (m.engine === "open") {
+ const plan = windowPlan(c.windowFrames, c.historyFrames);
+ const windows = h3Windows(len, plan.window, plan.history);
+ notes.push(
+ windows > 1
+ ? `MiniMax H3 swaps it in ${windows} windows of up to ${plan.window} frames at 24 fps, each continuing from the ${plan.history} frames before it; the clip's sound stays`
+ : `MiniMax H3 swaps it in one window of up to ${plan.window} frames at 24 fps; the clip's sound stays`,
+ );
+ // One prompt for the whole part: past H3's trained range (~362 frames) the pack itself says quality is unverified.
+ if (len > CHARACTER_SWAP.maxSeconds + 0.05) notes.push("Past 15 s is beyond what H3 was trained on: quality there is unverified");
+ } else if (n > 1) notes.push(`fal's H3 takes up to 15 s a call: the part runs as ${n} pieces, joined with the clip's own sound. Each piece starts fresh (no history between them), so a seam can show where they meet`);
+ if (m.engine === "cloud" && !source.hasAudio) notes.push("Your clip has no sound, and neither will the result: fal's H3 makes a soundtrack of its own, which is replaced with silence");
+ if (m.h3.anchor && c.anchor !== false) {
+ const am = anchorModel(m.engine, c.anchorModel);
+ 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");
+ 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));
+ if (warn) notes.push(warn);
+ notes.push(characterLicenceLine(m.engine, m.id));
+ } else if (body.mode === "character") {
+ notes.push(m.id === "h3-max-recast" ? characterLicenceLine(m.engine, m.id) : `${SOURCE_LABELS[m.source]}: ${m.note}`);
+ const warn = m.id === "h3-max-recast" ? null : cutWarning(cutsInPart(body.cuts, range));
+ if (warn) notes.push(warn);
+ }
+ if (n > 1 && body.mode !== "character") {
+ if (m.engine === "open" && m.window) {
+ notes.push(`${name} works on ${m.window.cap} frames at a time (${(m.window.cap / fps).toFixed(1)} s of this clip): it runs as ${n} windows, joined with the clip's own sound. Seams between windows aren't tested on a GPU yet`);
+ } else if (fuobeLook) {
+ notes.push(`${name} restyles ${m.engine === "open" ? "5 s" : m.window ? `${m.window.cap} frames (${(m.window.cap / fps).toFixed(1)} s of this clip)` : "up to 10 s"} at a time: the clip runs as ${n} segments, joined with its own sound`);
+ } else {
+ const limit = m.window ? `${m.window.cap} frames (${(m.window.cap / fps).toFixed(1)} s of this clip)` : `${m.maxSeconds} s`;
+ notes.push(`${name} takes up to ${limit} a call: the clip runs as ${n} pieces, joined with its own sound. Seams between pieces aren't tested yet`);
+ }
+ }
+ if (body.mode !== "restyle" && refs > m.refs.max) notes.push(m.refs.max === 1 ? `${name} uses your first reference image` : `${name} takes ${m.refs.max} references — your first ${m.refs.max} go`);
+ if (fuobeLook && refs) notes.push("Restyle changes the whole shot: character references aren't used — try Motion transfer or Character swap for a character");
+ if (fuobeLook && body.look?.kind === "custom" && m.readsLookImages && body.look.images.length > m.readsLookImages) notes.push(`${name} reads ${m.readsLookImages} of your look's images`);
+ if (fuobeLook && body.look?.kind === "soul" && m.source === "original") notes.push("The Soul look's LoRAs restyle the first frame (Fuobe Soul's edit); every frame then follows it");
+ const quality = body.quality ?? (body.mode === "character" ? CHARACTER_SWAP.defaultQuality : GENJUTSU.defaultQuality);
+ const res = resolutionWords(m, quality);
+ if (res) notes.push(`${name} ${res}${m.qualities ? "" : " (it has no resolution setting)"}`);
+ if (m.id === "wan-22-vace-inpaint") {
+ notes.push(body.mode === "insert" ? "The spot stays where you painted it for the whole shot — best with a still or slow camera" : "Only the area you marked changes; SAM 3.1 follows it through the selection when it runs as pieces or you clicked");
+ }
+ if (m.source === "original" && body.mode === "swap" && m.engine === "cloud") notes.push("SAM 3.1 follows what you named, clicked or painted through the selection; Wan VACE paints your reference into its mask");
+ if (m.billFps && m.engine === "cloud" && source.fps && source.fps > m.billFps + 0.5) notes.push(`fal bills this clip's ${Math.round(source.fps)} fps as ${(source.fps / m.billFps).toFixed(1)}× its length (video seconds at ${m.billFps} fps)`);
+ if (m.id === "oss-vace-insert") notes.push("The spot stays where you painted it for the whole shot — best with a still or slow camera");
+ if (m.people && body.mode === "swap") notes.push(`${name} swaps the person on camera — for objects, pick Fuobe Genjutsu or Kling O3`);
+ if (m.engine === "open" && body.mode !== "character") {
+ if (m.modes.includes("motion")) notes.push("Wan Animate 2 needs a 24 GB GPU · Apache-2.0");
+ else if (m.window) notes.push(`Wan 2.1 VACE 14B needs a 24 GB GPU · Apache-2.0${body.mode === "swap" ? " (SAM 3.1: Meta's SAM License)" : ""}`);
+ }
+ if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");
+ return notes;
+ }
+
+ const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });
+
+ /** The helper steps in words, for a run that can't have them (they run on fal; the open ones on ComfyUI). */
+ const HELPER_WORDS: Record<string, string> = {
+ [REMOVE_TOOLS.cloud.cut]: "cutting the clip",
+ [REMOVE_TOOLS.cloud.join]: "joining the pieces",
+ [REMOVE_TOOLS.cloud.mux]: "putting the sound back",
+ [MASK_TRACKER]: "following what you marked",
+ "extract-frame": "taking the first frame",
+ "scale-video": "fitting the clip",
+ "gpt-image-2-5-sunburst": "the first frame with your character",
+ "nano-banana-pro": "the first frame with your character",
+ };
+
+ /** The providers a step's model runs its operation on, on the step's engine (any one of them will do). */
+ const providersOf = (s: PlanStep): ProviderId[] => {
+ const m = getModel(s.request.modelId);
+ const routes = m ? (s.request.engine ? onEngine(m, s.request.engine) : m).routes : [];
+ return [...new Set(routes.filter((r) => !s.request.op || r.op === s.request.op).map((r) => r.provider))];
+ };
+
+ const listWords = (xs: string[]) => (xs.length < 2 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} and ${xs[xs.length - 1]}`);
+ const cap = (t: string) => (t ? t[0].toUpperCase() + t.slice(1) : t);
+
+ interface StepMode {
+ step: PlanStep;
+ /** It would run as a demo (no provider for it), or can't run at all (demo mode off). */
+ demo: boolean;
+ }
+
+ /**
+ * A run is all real or all a demo (chainMode in src/server/generations.ts): a real step after a demo one runs as a demo
+ * too, a demo step after a real one fails, both after the paid steps were made. So when only some of the steps have a
+ * provider — Replicate's P-Video without fal for the cuts and joins, say — name the missing key (and the way around
+ * it) before anything is paid for.
+ */
+ function mixProblem(modes: StepMode[], cannot: boolean, input: GenjutsuPlanInput): string | null {
+ const missing = modes.filter((x) => x.demo);
+ if (!missing.length || (!cannot && missing.length === modes.length)) return null;
+ const m = input.maker;
+ const makerName = getModel(m.id)?.name ?? m.label;
+ const own = missing.filter((x) => x.step.request.modelId === m.id);
+ const helpers = missing.filter((x) => x.step.request.modelId !== m.id);
+ const ids = (xs: StepMode[]) => [...new Set(xs.flatMap((x) => providersOf(x.step)))];
+ const label = (xs: ProviderId[]) => xs.map((id) => provider(id).label).join(" or ");
+ const [ownIds, helperIds] = [ids(own), ids(helpers)];
+ const parts: string[] = [];
+ if (own.length) parts.push(`${makerName} runs on ${label(ownIds)}`);
+ if (helpers.length) {
+ const jobs = [...new Set(helpers.map((x) => HELPER_WORDS[x.step.request.modelId] ?? getModel(x.step.request.modelId)?.name ?? x.step.request.modelId))];
+ parts.push(`${own.length ? listWords(jobs) : cap(listWords(jobs))} ${jobs.length > 1 ? "run" : "runs"} on ${label(helperIds)}`);
+ }
+ // The fewest keys that cover it: one provider both need, else one for each.
+ const both = ownIds.filter((id) => helperIds.includes(id));
+ const key = !own.length ? `a ${label(helperIds)} key` : !helpers.length ? `a ${label(ownIds)} key` : both.length ? `a ${label(both.slice(0, 1))} key` : `a ${label(helperIds)} key and a ${label(ownIds)} key`;
+ const around = own.length ? otherModel(input) : undefined;
+ return `${parts.join(", and ")} — add ${key} in Settings → API keys${around ? `, or ${around}` : ""}`;
+ }
+
+ /** Another model for the same job that runs with the keys set now (the way around a missing key). */
+ function otherModel(input: GenjutsuPlanInput): string | undefined {
+ const runs = (id: string) => {
+ const m = getModel(id);
+ return !!m && isOffered(id, input.engine) && onEngine(m, input.engine).routes.some((r) => provider(r.provider).isConfigured());
+ };
+ const other = makersFor(input.engine, input.mode, input.target).find((x) => x.id !== input.maker.id && x.pair !== input.maker.id && runs(x.id));
+ return other ? `pick ${other.label}` : undefined;
+ }
+
+ /** Whether a step's model has no route it could run on now (demo mode off: it would refuse). */
+ const unrunnable = (s: PlanStep) => !providersOf(s).some((id) => provider(id).isConfigured());
+
+ /** What the steps cost together (null when a price is unknown) and whether they would run as a demo. */
+ function price(steps: PlanStep[], input: GenjutsuPlanInput): { costUsd: number | null; demo: boolean; providers: ProviderId[]; tokenBilled: string[] } {
+ let cost: number | null = 0;
+ const modes: StepMode[] = [];
+ const providers = new Set<ProviderId>();
+ // Steps fal bills by tokens (the Sunburst first frame): left out of the total, and named.
+ const tokenBilled = new Set<string>();
+ let cannot = false;
+ for (const s of steps) {
+ let p: ReturnType<typeof previewChained>;
+ try {
+ p = previewChained(withChain(s), s.after?.length ?? 0);
+ } catch (e) {
+ // Demo mode off and no key for it: said with the other missing keys below.
+ if (unrunnable(s)) {
+ cannot = true;
+ modes.push({ step: s, demo: true });
+ continue;
+ }
+ throw new ShortsError((e as Error).message, 422);
+ }
+ modes.push({ step: s, demo: p.demo });
+ providers.add(p.providerId);
+ // Kling O3's edit price isn't the catalog's: the planner's table.
+ const own = p.demo ? null : makerStepUsd(s.request.modelId, s.request.params);
+ const usd = own ?? p.costUsd;
+ const tokens = usd === null ? ANCHOR_MODELS.cloud.find((m) => m.id === s.request.modelId && m.tokens) : undefined;
+ if (tokens) {
+ tokenBilled.add(`${tokens.label}'s first frame is billed by tokens (${tokens.tokens}) and isn't in the price`);
+ continue;
+ }
+ cost = cost === null || usd === null ? null : cost + usd;
+ }
+ const problem = mixProblem(modes, cannot, input);
+ if (problem) throw new ShortsError(problem, 422);
+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo: modes.some((x) => x.demo), providers: [...providers], tokenBilled: [...tokenBilled] };
+ }
+
+ export interface GenjutsuEstimate {
+ costUsd: number | null;
+ demo: boolean;
+ /** Where the steps run ("mock" for demo steps). */
+ providers: ProviderId[];
+ /** The model that runs (the default, or the one picked), its tier and where it comes from. */
+ modelId: string;
+ modelName: string;
+ source: MakerSource;
+ tier?: GenjutsuTier;
+ /** The resolution it is asked for (none: it keeps the clip's size). */
+ quality?: string;
+ pieces: number;
+ seconds: number;
+ steps: number;
+ notes: string[];
+ /** Character swap: anchor frames made, the limits, and the GPU the open route was tested on. */
+ anchors?: number;
+ limits?: string[];
+ gpu?: { weightsGb: number; tested: string; advice: string; speed: string };
+ }
+
+ export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEstimate> {
+ const { input, maker, notes } = await planInput(body, { probe: false });
+ let plan: ReturnType<typeof planGenjutsu>;
+ try {
+ plan = planGenjutsu(input);
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+ const character = body.mode === "character";
+ const { tokenBilled, ...cost } = price(plan.steps, input);
+ return {
+ ...cost,
+ modelId: maker.id,
+ modelName: getModel(maker.id)?.name ?? maker.label,
+ source: maker.source,
+ ...(maker.tier ? { tier: maker.tier } : {}),
+ ...(qualityFor(maker, input.quality) ? { quality: qualityFor(maker, input.quality) } : {}),
+ pieces: plan.pieces,
+ seconds: Math.round((input.range.end - input.range.start) * 100) / 100,
+ steps: plan.steps.length,
+ notes: cost.demo ? notes : [...notes, ...tokenBilled],
+ ...(plan.anchors !== undefined ? { anchors: plan.anchors } : {}),
+ ...(character ? { limits: [...CHARACTER_LIMITS] } : {}),
+ ...(character && maker.h3 && maker.engine === "open" ? { gpu: { ...CHARACTER_GPU } } : {}),
+ };
+ }
+
+ /** Start it; returns the finished video's generation (the other steps wait for each other). */
+ export async function createGenjutsu(body: GenjutsuBody): Promise<{ final: Generation; items: Generation[] }> {
+ const { input } = await planInput(body, { probe: true });
+ try {
+ const plan = planGenjutsu(input);
+ // The same check as the estimate: nothing starts when only some of the steps have a provider.
+ price(plan.steps, input);
+ // A silent clip's cloud swap ends on silence: its WAV is written now (silenceRef, as Canvas mutes a clip).
+ const withSilence = silenceWriter();
+ const p = createPipeline(plan.steps.map((s) => ({ ...s, request: withSilence(s.request) })));
+ return { final: p.byKey[plan.final], items: p.items };
+ } catch (e) {
+ if (e instanceof ShortsError) throw e;
+ throw new ShortsError((e as Error).message, 422);
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Character swap helpers: "Describe my character" and the part's words (Akatz Labs' description and transcript)
+
+ const DESCRIBE_SYSTEM =
+ "You describe a character from one reference picture for a video model that will put them into a scene. Say only who they are and what they wear: " +
+ "apparent age range, build, face, hair, skin tone, clothing, shoes, accessories and their colours. No pose, background, lighting, camera or art style, " +
+ "no names, no guesses about personality. One plain sentence under 60 words, starting with \"a\" or \"an\", no quotes, no preamble.";
+
+ export const DescribeSchema = z.object({ engine: z.enum(["cloud", "open"]), image: z.string().startsWith("/api/files/").max(500) });
+
+ /**
+ * "Describe my character": the engine's text model looks at the character picture and writes the description the
- * prompt and the anchor brief carry (Akatz Labs found generic prompts weak). Cloud: Claude, else Ollama; your GPU:
- * Ollama with a vision model. A text model switched off in Settings → Models & licences doesn't answer.
++ * prompt and the anchor brief carry (Akatz Labs found generic prompts weak). Cloud: Claude, else a local model; your
++ * GPU: a local vision model (Ollama, LM Studio or Unsloth Studio). A text model switched off in Settings → Models &
++ * licences doesn't answer.
+ */
+ export async function describeCharacter(body: z.infer<typeof DescribeSchema>): Promise<{ description: string }> {
+ mustMatchMode(body.engine);
+ const textModel = getModel(body.engine === "open" ? "oss-text-llm" : "text-llm");
+ if (!textModel || !offeredModel(textModel)) throw new ShortsError(`The text model is switched off in ${ACCESS_PLACE} — describe your character in your own words`, 422);
- // Ollama is asked on your GPU's engine (and when no Anthropic key is set): it has to be running.
++ // A local model is asked on your GPU's engine (and when no Anthropic key is set): its server has to be running.
+ const backend = llmTextBackend();
- const ollama = backend === "ollama" || (backend === "claude" && body.engine === "open");
- if (getSetting("demoMode") === "on" || !backend || (ollama && !(await probeOllama()))) {
- throw new ShortsError("Describing needs a text model: add an Anthropic key, or run Ollama with a vision model (Settings → AI helper)", 422);
++ const local = backend === "ollama" || (backend === "claude" && body.engine === "open");
++ if (getSetting("demoMode") === "on" || !backend || (local && !(await probeOllama()))) {
++ throw new ShortsError("Describing needs a text model: add an Anthropic key, or run a vision model in Ollama, LM Studio or Unsloth Studio (Settings → AI helper)", 422);
+ }
+ let file: Awaited<ReturnType<typeof readRef>>;
+ try {
+ file = await readRef(body.image);
+ } catch {
+ throw new ShortsError("Couldn't read the character picture — add it again", 422);
+ }
+ if (!/^image\/(png|jpeg|webp|gif)$/.test(file.contentType)) throw new ShortsError("Describe works on a PNG, JPEG or WebP picture", 422);
+ const answer = await llmText(DESCRIBE_SYSTEM, "Describe the character in this picture.", [{ data: file.data, contentType: file.contentType }], { ollamaOnly: body.engine === "open" });
+ const description = answer
+ ?.replace(/^["“'\s]+|["”'\s]+$/g, "")
+ .replace(/\s+/g, " ")
+ .replace(/[.\s]+$/, "")
+ .slice(0, CHARACTER_SWAP.maxDescriptionChars);
- if (!description) throw new ShortsError(body.engine === "open" ? "Ollama didn't describe the picture — it needs a vision model (qwen3-vl, gemma3…)" : "The text model didn't answer — try again, or describe your character in your own words", 422);
++ if (!description) throw new ShortsError(body.engine === "open" ? `${cap(localLabel())} didn't describe the picture — it needs a vision model (qwen3-vl, gemma3…)` : "The text model didn't answer — try again, or describe your character in your own words", 422);
+ return { description };
+ }
+
+ /** The transcriber per engine (Fuobe's Transcribe studio's defaults). */
+ export const TRANSCRIBERS: Record<Engine, string> = { cloud: "scribe-v2", open: "oss-qwen3-asr" };
+
+ export const TranscribeSchema = z.object({
+ engine: z.enum(["cloud", "open"]),
+ source: z.object({ url: z.string().startsWith("/api/files/").max(500), duration: z.number().finite().positive().max(3600).optional() }),
+ });
+
+ /**
+ * The clip's words, for "What's said": one transcription of the whole clip (word-timed cues), so any part picked
+ * afterwards takes its own lines from it in the browser (partWords). A Genjutsu step: it stays out of the page's feed.
+ */
+ export function transcribeClip(body: z.infer<typeof TranscribeSchema>): { id: string; modelId: string } {
+ mustMatchMode(body.engine);
+ const modelId = TRANSCRIBERS[body.engine];
+ if (!isOffered(modelId, body.engine)) throw new ShortsError(`${getModel(modelId)?.name ?? modelId} is switched off in ${ACCESS_PLACE} — type the words instead`, 422);
+ const seconds = body.source.duration;
+ try {
+ const [g] = createGenerations({
+ feature: GENJUTSU.stepFeature,
+ batchTitle: "Genjutsu · the clip's words",
+ modelId,
+ op: "transcribe",
+ inputs: { video: body.source.url },
+ ...(seconds ? { params: { duration: seconds, sourceDuration: seconds } } : {}),
+ step: { label: "The clip's words", index: 0, of: 1 },
+ });
+ return { id: g.id, modelId };
+ } catch (e) {
+ throw new ShortsError((e as Error).message, 422);
+ }
+ }
diff --cc src/server/llm/index.ts
index 5198bb42,00000000..4d2ca365
mode 100644,000000..100644
--- a/src/server/llm/index.ts
+++ b/src/server/llm/index.ts
@@@ -1,268 -1,0 +1,302 @@@
+import "server-only";
+import { errorDetail, httpError, keyMessage, rejectsJson, unreachableError } from "./errors";
+import { healToolCalls } from "./messages";
+import { cached, forget, refresh, refreshSync, statusOf, tokens } from "./probe";
+import { allLocalServers, authHeaders, cap, LOCAL_LABELS, llmContext, localServer, localServers, openaiBase, pinnedKind } from "./servers";
+import type { ChatRequest, ChatResult, LocalKind, LocalServer, LocalStatus } from "./types";
+import { ollamaBody, openaiBody, parseOllama, parseOpenai } from "./wire";
+
+export { aiHelper, cap, llmContext, localServer, localServers, LOCAL_LABELS, pinnedKind } from "./servers";
+export { emptyReply } from "./errors";
+export { toChatMessages } from "./messages";
+export type * from "./types";
+
+/** A server that can take calls now, with what its probe found. */
+export interface Ready {
+ server: LocalServer;
+ status: LocalStatus;
+}
+
+/**
+ * The first server that can take calls. With more than one, a server that has the model comes first:
+ * Ollama answers (so counts as ready) even with nothing pulled, and mustn't take every call from an
+ * LM Studio that has a model.
+ */
+const pick = (servers: LocalServer[]): Ready | null => {
+ const need = llmContext();
+ const ready = servers.flatMap((server) => {
+ const status = statusOf(server, need);
+ return status && !status.problem ? [{ server, status }] : [];
+ });
+ return ready.find((r) => r.server.kind !== "ollama" || r.status.warning == null) ?? ready[0] ?? null;
+};
+
+/** Ask the local servers (answers kept 15 s; `force` asks now). True when one can take calls. */
+export async function probeLocal(force = false): Promise<boolean> {
+ const servers = localServers();
+ await refresh(servers, force);
+ return !!pick(servers);
+}
+
+/** The server a call goes to now: the first ready one in Settings' order (asks first when the answers are old). */
+export async function activeLocal(force = false): Promise<Ready | null> {
+ await probeLocal(force);
+ return pick(localServers());
+}
+
+/**
+ * The same, synchronously, for routing. The first look at a server waits for a real answer (a step
+ * posted right after boot must not fall back to demo text while the server is up); later looks use
+ * the cached one and refresh it in the background.
+ */
+export function localReady(): Ready | null {
+ const servers = localServers();
+ const unknown = servers.filter((s) => !cached(s));
+ if (unknown.length) refreshSync(unknown);
+ if (servers.some((s) => cached(s)?.stale)) void refresh(servers).catch(() => {});
+ return pick(servers);
+}
+
+/** What the local model is called in messages: the pinned server, the one in use, or "a local model". Never waits. */
+export function localLabel(): string {
+ const pinned = pinnedKind();
+ return pinned ? LOCAL_LABELS[pinned] : (pick(localServers())?.server.label ?? "a local model");
+}
+
++/**
++ * The model local text steps run on now, for its licence: the ready server's (cached answers only: never
++ * asks), else the model the pinned server is set to, else Ollama's. `model` is "" when the server picks one.
++ */
++export function localModelInUse(): { label: string; model: string } {
++ const ready = pick(localServers());
++ if (ready?.status.model) return { label: ready.server.label, model: ready.status.model };
++ const s = localServer(pinnedKind() ?? "ollama");
++ return { label: s.label, model: s.model };
++}
++
+/** What to connect, in a sentence: the pinned server, or any of the three. */
+export const localWhat = (): string => {
+ const pinned = pinnedKind();
+ return pinned ? LOCAL_LABELS[pinned] : "a local model (Ollama, LM Studio or Unsloth Studio)";
+};
+
+/**
+ * Why no local model can run, when a server says (it needs a key, has no model loaded): the pinned
+ * server's reason, or in Automatic the first server that answers but can't run. Null otherwise.
+ */
+export function localProblem(): string | null {
+ const need = llmContext();
+ const pinned = pinnedKind();
+ for (const s of localServers()) {
+ const st = statusOf(s, need);
+ if (st?.problem && (st.up || pinned)) return st.problem;
+ }
+ return null;
+}
+
+/** Every server's status for Settings (all four, whatever is pinned). */
+export async function localStatuses(force = false): Promise<LocalStatus[]> {
+ const servers = allLocalServers();
+ await refresh(servers, force);
+ const need = llmContext();
+ return servers.map((s) => statusOf(s, need)!);
+}
+
+// ---------------------------------------------------------------------------
+// LM Studio: loading a model with the context Fuobe needs
+
+declare global {
+ var __fuobeLmLoads: Map<string, Promise<{ model: string; context: number | null; seconds: number | null }>> | undefined;
+}
+const loads = () => (globalThis.__fuobeLmLoads ??= new Map());
+
+/** POST /api/v1/models/load; concurrent calls for one model share the load. */
+function loadLmStudio(s: LocalServer, model: string, context: number) {
+ const key = `${s.url}|${model}`;
+ let p = loads().get(key);
+ if (!p) {
+ p = (async () => {
+ const res = await fetch(`${s.url}/api/v1/models/load`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify({ model, context_length: context, echo_load_config: true }),
+ signal: AbortSignal.timeout(300_000),
+ }).catch((e: unknown) => {
+ throw unreachableError(s, e);
+ });
+ if (res.status === 401 || res.status === 403) throw new Error(keyMessage(s));
+ if (!res.ok) throw new Error(`LM Studio couldn't load ${model} with ${tokens(context)} tokens of context: ${errorDetail(await res.text())}. Free some GPU memory (ComfyUI shares it), pick a smaller model, or lower the context in Settings → AI helper.`);
+ const j = (await res.json().catch(() => ({}))) as { load_time_seconds?: number; load_config?: { context_length?: number } };
+ // The next status shows it loaded, so it isn't loaded twice.
+ await refresh([s], true);
+ return { model, context: j.load_config?.context_length ?? context, seconds: j.load_time_seconds ?? null };
+ })().finally(() => loads().delete(key));
+ loads().set(key, p);
+ }
+ return p;
+}
+
+/**
+ * LM Studio's chat endpoint can't set the context, and loading a model on demand (JIT) uses the
+ * app's default (often 4k–8k: too small for Assist's tools). So a model that isn't loaded yet is
+ * loaded first with the context from Settings. A model the user loaded is left as it is.
+ */
+async function prepareLmStudio(s: LocalServer, status: LocalStatus, model: string): Promise<void> {
+ const need = llmContext();
+ // The latest answers, not the caller's snapshot: a job that started before its first call loaded
+ // the model must not load it again for every later call.
+ const now = statusOf(s, need) ?? status;
+ if (!now.native || !need) return;
+ const m = now.models.find((x) => x.id === model) ?? now.models.find((x) => model.startsWith(`${x.id}@`));
+ if (!m || m.loaded) return;
+ await loadLmStudio(s, model, Math.min(need, m.maxContext || need));
+}
+
+/** Settings → "Reload with 16k context": unloads LM Studio's copies of the model, then loads it with the context from Settings. */
+export async function reloadLmStudio(model?: string | null): Promise<{ model: string; context: number | null; seconds: number | null }> {
+ const s = localServer("lmstudio");
+ await refresh([s], true);
+ const status = statusOf(s, llmContext());
+ if (!status?.up) throw new Error(status?.problem ?? "LM Studio isn't running");
+ if (!status.native) throw new Error("Loading a model from Fuobe needs LM Studio 0.4 or later. Load it in LM Studio with a larger context instead.");
+ const want = model || status.model;
+ const m = status.models.find((x) => x.id === want);
+ if (!want || !m) throw new Error(`LM Studio has no model called ${want ?? "that"}`);
+ for (const id of m.instances ?? []) {
+ await fetch(`${s.url}/api/v1/models/unload`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify({ instance_id: id }),
+ signal: AbortSignal.timeout(60_000),
+ }).catch(() => null);
+ }
+ const need = llmContext() || 16384;
+ return loadLmStudio(s, want, Math.min(need, m.maxContext || need));
+}
+
+// ---------------------------------------------------------------------------
+// One call
+
+/**
+ * The model a call names: the request's, Settings', or the one the probe picked. Unsloth: none, so
+ * its loaded model answers. LM Studio: the probe's, which is the model's key when Settings names it
+ * by its display name.
+ */
+function modelFor(r: Ready, req: ChatRequest): string | null {
+ if (req.model) return req.model;
+ if (r.server.kind === "unsloth") return r.server.model || null;
+ if (r.server.kind === "lmstudio") return r.status.model || r.server.model || null;
+ return r.server.model || r.status.model;
+}
+
+/**
+ * One chat call to a local server (not streamed). With `json`, a server that rejects structured
+ * output is asked again without it (the prompts ask for JSON too). With `tools`, calls the model
+ * wrote as text are read back. Throws messages that say how to fix the server; a reply with no
+ * text is returned as it is (see emptyReply).
+ */
+export async function chatLocal(r: Ready, req: ChatRequest): Promise<ChatResult> {
+ const s = r.server;
+ const model = modelFor(r, req);
+ if (s.kind === "lmstudio" && model) await prepareLmStudio(s, r.status, model);
+ const signal = req.signal ? AbortSignal.any([req.signal, AbortSignal.timeout(req.timeoutMs)]) : AbortSignal.timeout(req.timeoutMs);
+ const url = s.kind === "ollama" ? `${s.url}/api/chat` : `${openaiBase(s)}/chat/completions`;
+ const send = (withJson: boolean) =>
+ fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify(s.kind === "ollama" ? ollamaBody(req, model ?? s.model, llmContext(), withJson) : openaiBody(s.kind, req, model, withJson)),
+ signal,
+ }).catch((e: unknown) => {
+ if (req.signal?.aborted) throw e;
+ // It was up a moment ago: look again before routing sends it more.
+ if ((e as Error)?.name !== "TimeoutError") forget(s);
+ throw unreachableError(s, e);
+ });
+ let res = await send(true);
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ if (req.json && rejectsJson(s.kind, res.status, body)) res = await send(false);
+ else throw httpError(s, res.status, body, model);
+ if (!res.ok) throw httpError(s, res.status, await res.text().catch(() => ""), model);
+ }
+ let j: unknown;
+ try {
+ j = await res.json();
+ } catch (e) {
+ if (req.signal?.aborted) throw e;
+ if ((e as Error)?.name === "TimeoutError") throw unreachableError(s, e);
+ throw new Error(`${cap(s.label)} sent an answer Fuobe couldn't read`);
+ }
+ const answer = model ?? r.status.model ?? s.label;
+ const out = s.kind === "ollama" ? parseOllama(j as Parameters<typeof parseOllama>[0], answer) : parseOpenai(j as Parameters<typeof parseOpenai>[0], answer);
+ if (req.tools?.length && !out.toolCalls.length && out.text) {
+ const healed = healToolCalls(out.text, new Set(req.tools.map((t) => t.name)));
+ if (healed.calls.length) return { ...out, text: healed.text, toolCalls: healed.calls, stop: "tool_use" };
+ }
+ return out;
+}
+
+/** Settings → Test: a tiny call to the server text steps would use (or the one named), timed. */
+export async function testLocal(kind?: LocalKind | null): Promise<{ ok: boolean; detail: string; ms?: number; model?: string }> {
+ const servers = kind ? [localServer(kind)] : localServers();
+ await refresh(servers, true);
+ const ready = pick(servers);
+ if (!ready) {
+ const need = llmContext();
+ const said = servers.map((s) => statusOf(s, need)).find((st) => st?.problem && (st.up || servers.length === 1));
+ return { ok: false, detail: said?.problem ?? "No local model server is answering. Start Ollama, LM Studio or Unsloth Studio, or set your server's URL." };
+ }
+ const t0 = Date.now();
+ try {
+ const r = await chatLocal(ready, { messages: [{ role: "user", content: "Reply with the word OK." }], think: false, maxTokens: 16, timeoutMs: 300_000 });
+ const ms = Date.now() - t0;
+ const note = r.text ? "" : " (it was still thinking: models that think first answer more slowly)";
+ return { ok: true, ms, model: r.model, detail: `${cap(ready.server.label)} answered in ${(ms / 1000).toFixed(1)} s with ${r.model}${note}` };
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+}
+
++/**
++ * Settings → Save & test for a local server's URL, model or key: does it answer, and has it the model
++ * Settings names? Reads its model list only (no call, nothing loaded), so it is quick. Without
++ * `kind`: the server text steps would use.
++ */
++export async function checkLocal(kind?: LocalKind | null): Promise<{ ok: boolean; detail: string }> {
++ const servers = kind ? [localServer(kind)] : localServers();
++ await refresh(servers, true);
++ const need = llmContext();
++ const ready = pick(servers);
++ if (!ready) {
++ const said = servers.map((s) => statusOf(s, need)).find((st) => st?.problem && (st.up || servers.length === 1));
++ return { ok: false, detail: said?.problem ?? `Nothing answers at ${servers.map((s) => s.url).join(", ")}. Start Ollama, LM Studio or Unsloth Studio, or set your server's URL.` };
++ }
++ const { server, status } = ready;
++ // Ollama answers without the model too (a call would name it): here that is a failed check.
++ if (server.kind === "ollama" && status.warning) {
++ return { ok: false, detail: status.models.length ? `Ollama answers, but ${server.model} isn't pulled — run: ollama pull ${server.model}` : status.warning };
++ }
++ const detail = `${cap(server.label)} · ${status.model ?? "its loaded model"} ready`;
++ return { ok: true, detail: status.warning ? `${detail} · ${status.warning}` : detail };
++}
++
+/** What /api/status says about the local model (no keys). */
+export async function localSummary() {
+ const servers = localServers();
+ await refresh(servers);
+ const need = llmContext();
+ const ready = pick(servers);
+ return {
+ provider: pinnedKind() ?? "auto",
+ context: need,
+ local: ready
+ ? { kind: ready.server.kind, label: ready.server.label, url: ready.server.url, model: ready.status.model, loaded: ready.status.loaded, context: ready.status.context, warning: ready.status.warning }
+ : null,
+ problem: ready ? null : localProblem(),
+ detected: servers.map((s) => {
+ const st = statusOf(s, need)!;
+ return { kind: s.kind, label: s.label, url: s.url, up: st.up, auth: st.auth, models: st.models.length, model: st.model, problem: st.problem };
+ }),
+ };
+}
diff --cc src/server/llm/servers.ts
index c8b8a611,00000000..3cc52e6e
mode 100644,000000..100644
--- a/src/server/llm/servers.ts
+++ b/src/server/llm/servers.ts
@@@ -1,65 -1,0 +1,77 @@@
+import "server-only";
- import { getSetting, parseContext } from "../settings";
++import { getSetting, isCandidate, parseContext, savedSetting, type SettingName } from "../settings";
+import { LOCAL_KINDS, type LocalKind, type LocalServer } from "./types";
+
+export const LOCAL_LABELS: Record<LocalKind, string> = { ollama: "Ollama", lmstudio: "LM Studio", unsloth: "Unsloth Studio", custom: "your local server" };
+
+/** "your local server" at the start of a sentence. */
+export const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
+/** Settings → AI helper. The old value "ollama" means a local model only, whichever server runs it. */
+export function aiHelper(): "auto" | "anthropic" | "local" | "none" {
+ const v = getSetting("enhanceProvider");
+ return v === "ollama" ? "local" : (v as "auto" | "anthropic" | "local" | "none");
+}
+
+/** The local server Settings pins (null: Automatic). */
+export function pinnedKind(): LocalKind | null {
+ const v = getSetting("llmProvider");
+ return v === "auto" ? null : (v as LocalKind);
+}
+
+/** Tokens of context the local model should have; 0 leaves it to the server. A value that isn't a size gets 16384. */
+export function llmContext(): number {
+ return parseContext(getSetting("llmContext")) ?? 16384;
+}
+
+/** The server root: no trailing slash, and no /v1 (or Ollama's /api) pasted from an example. */
+const root = (url: string) =>
+ url
+ .trim()
+ .replace(/\/+$/, "")
+ .replace(/\/(?:api\/v[01]|v1|api)$/i, "");
+
++/** The custom server's URL as given, without a trailing slash. */
++const customRoot = (url: string) => url.trim().replace(/\/+$/, "");
++
++/**
++ * A server's key. During Save & test of an address that isn't the saved one, the saved key stays with
++ * the server it was saved for (as ComfyUI's token does): only a key typed for this test goes to the new address.
++ */
++function keyFor(urlName: SettingName, keyName: SettingName, norm: (url: string) => string): string {
++ if (isCandidate(urlName) && !isCandidate(keyName) && norm(getSetting(urlName)) !== norm(savedSetting(urlName))) return "";
++ return getSetting(keyName);
++}
++
+export function localServer(kind: LocalKind): LocalServer {
+ const label = LOCAL_LABELS[kind];
+ if (kind === "ollama") return { kind, label, url: root(getSetting("ollamaUrl")), model: getSetting("ollamaModel").trim(), key: "" };
- if (kind === "lmstudio") return { kind, label, url: root(getSetting("lmstudioUrl")), model: getSetting("lmstudioModel").trim(), key: getSetting("lmstudioToken") };
- if (kind === "unsloth") return { kind, label, url: root(getSetting("unslothUrl")), model: getSetting("unslothModel").trim(), key: getSetting("unslothKey") };
- return { kind, label, url: getSetting("llmUrl").trim().replace(/\/+$/, ""), model: getSetting("llmModel").trim(), key: getSetting("llmKey") };
++ if (kind === "lmstudio") return { kind, label, url: root(getSetting("lmstudioUrl")), model: getSetting("lmstudioModel").trim(), key: keyFor("lmstudioUrl", "lmstudioToken", root) };
++ if (kind === "unsloth") return { kind, label, url: root(getSetting("unslothUrl")), model: getSetting("unslothModel").trim(), key: keyFor("unslothUrl", "unslothKey", root) };
++ return { kind, label, url: customRoot(getSetting("llmUrl")), model: getSetting("llmModel").trim(), key: keyFor("llmUrl", "llmKey", customRoot) };
+}
+
+/** The servers text steps and Assist may use, in the order they're tried: the pinned one, or all (the custom one when it has a URL). */
+export function localServers(): LocalServer[] {
+ const pinned = pinnedKind();
+ if (pinned) return [localServer(pinned)];
+ return LOCAL_KINDS.map(localServer).filter((s) => s.kind !== "custom" || s.url);
+}
+
+/** Every server, for Settings (the custom one even without a URL). */
+export const allLocalServers = (): LocalServer[] => LOCAL_KINDS.map(localServer);
+
+/**
+ * Where the OpenAI-compatible API lives. LM Studio and Unsloth: {root}/v1. A custom URL is an OpenAI
+ * "base URL" as the server's docs give it (http://host:8080/v1); a bare host gets /v1 added.
+ */
+export function openaiBase(s: LocalServer): string {
+ if (s.kind !== "custom") return `${s.url}/v1`;
+ try {
+ return new URL(s.url).pathname.replace(/\/+$/, "") ? s.url : `${s.url}/v1`;
+ } catch {
+ return `${s.url}/v1`;
+ }
+}
+
+export const authHeaders = (s: LocalServer): Record<string, string> => (s.key ? { Authorization: `Bearer ${s.key}` } : {});
diff --cc src/server/llm/types.ts
index 4907237e,00000000..4d9bc738
mode 100644,000000..100644
--- a/src/server/llm/types.ts
+++ b/src/server/llm/types.ts
@@@ -1,110 -1,0 +1,112 @@@
+/**
+ * Local LLM servers: Ollama (its own API), LM Studio, Unsloth Studio, and any other
+ * OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…). One layer serves text steps,
+ * llmText() and the Assist agent; the request and response shapes here are neutral (OpenAI-like).
+ */
+
+export type LocalKind = "ollama" | "lmstudio" | "unsloth" | "custom";
+
+/** The order Automatic tries them in: Ollama first, so installs that had it keep it. */
+export const LOCAL_KINDS: LocalKind[] = ["ollama", "lmstudio", "unsloth", "custom"];
+
+export interface LocalServer {
+ kind: LocalKind;
+ /** "Ollama", "LM Studio", "Unsloth Studio", or "your local server" for the custom one. */
+ label: string;
+ /** No trailing slash. Ollama, LM Studio and Unsloth: the server root (a pasted /v1 is dropped). Custom: as given. */
+ url: string;
+ /** The model picked in Settings ("" = Fuobe picks). */
+ model: string;
+ /** Bearer token; never leaves the server. */
+ key: string;
+}
+
+export interface LocalModel {
+ id: string;
+ name?: string;
+ /** In memory now (LM Studio, Unsloth). */
+ loaded?: boolean;
+ /** LM Studio: trained for tool calling. */
+ tools?: boolean;
+ /** LM Studio: thinks before answering by default. */
+ reasoning?: boolean;
+ /** Context of the loaded copy, in tokens. */
+ context?: number | null;
+ maxContext?: number | null;
+ /** LM Studio: ids of its loaded copies (to unload before a reload). */
+ instances?: string[];
+}
+
+export interface LocalStatus {
+ kind: LocalKind;
+ label: string;
+ url: string;
+ /** Something answered at the URL (for Unsloth: Unsloth Studio itself). */
+ up: boolean;
+ auth: "none" | "ok" | "missing" | "rejected";
+ /** Chat models only (no embedding, speech or image models). */
+ models: LocalModel[];
+ /** The model a call uses now (Unsloth: the loaded one; null: none to use). */
+ model: string | null;
+ /** Whether that model is in memory (null: the server doesn't say). */
+ loaded: boolean | null;
+ /** Its context window in tokens, when known. */
+ context: number | null;
+ /** Why it can't run, in the user's words (null = ready). */
+ problem: string | null;
+ /** Ready, but worth knowing: a small context, a model that thinks first, a model that may be missing. */
+ warning: string | null;
+ /** LM Studio's own API answered, so Fuobe can load a model with the context it needs. */
+ native?: boolean;
+ at: number;
+}
+
+export interface ChatToolCall {
+ id: string;
+ name: string;
+ input: unknown;
+}
+
+export interface ChatMessage {
+ role: "system" | "user" | "assistant" | "tool";
+ content: string;
+ toolCalls?: ChatToolCall[];
+ /** Tool results: the call they answer (OpenAI). */
+ toolCallId?: string;
+ /** Tool results: the tool's name (Ollama). */
+ toolName?: string;
++ /** User turns: pictures for a model that can see (base64, JPEG, PNG, GIF or WebP); a text-only model answers from the words. */
++ images?: { data: string; contentType: string }[];
+}
+
+/** A JSON Schema the answer must follow (root object or array), or "object" for any JSON object. */
+export type JsonSpec = { name: string; schema: Record<string, unknown> } | "object";
+
+export interface ChatTool {
+ name: string;
+ description?: string;
+ parameters: unknown;
+}
+
+export interface ChatRequest {
+ messages: ChatMessage[];
+ /** Overrides the server's model for this call (Assist's Manual mode). */
+ model?: string | null;
+ tools?: ChatTool[];
+ json?: JsonSpec;
+ /** false: ask the server not to think (one-shot text). Undefined: the server's default (Assist). */
+ think?: boolean;
+ maxTokens?: number;
+ timeoutMs: number;
+ signal?: AbortSignal;
+}
+
+export interface ChatResult {
+ /** The answer, with <think> blocks removed (reasoning fields are ignored). */
+ text: string;
+ toolCalls: ChatToolCall[];
+ stop: "end" | "tool_use" | "length";
+ model: string;
+ /** The reply carried reasoning (thinking) besides the answer. */
+ thought: boolean;
+}
diff --cc src/server/llm/wire.ts
index 1cab5bd1,00000000..80458d0e
mode 100644,000000..100644
--- a/src/server/llm/wire.ts
+++ b/src/server/llm/wire.ts
@@@ -1,143 -1,0 +1,150 @@@
+import "server-only";
+import { customAlphabet } from "nanoid";
+import type { ChatMessage, ChatRequest, ChatResult, ChatToolCall, JsonSpec, LocalKind } from "./types";
+
+/*
+ * Request bodies and answers for the two wires, as pure functions: Ollama's own /api/chat (it has
+ * num_ctx, think and a schema in `format`), and OpenAI's /v1/chat/completions for LM Studio,
+ * Unsloth Studio and any other OpenAI-compatible server, with small differences per server.
+ */
+
+/** Tool-call ids as strict chat templates (Mistral's) want them: nine letters and digits. */
+export const newToolId = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 9);
+
+/** The answer without its thinking: <think>…</think>, a closing tag whose opening one was in the prompt, a thought cut off. */
+export function stripThink(s: string): string {
+ let t = s.replace(/<think>[\s\S]*?<\/think>/gi, "");
+ const close = t.search(/<\/think>/i);
+ if (close >= 0) t = t.slice(close + "</think>".length);
+ return t.replace(/<think>[\s\S]*$/i, "").trim();
+}
+
+/** Tool arguments: an object, or a JSON string (a broken one reaches the tool as INVALID_JSON, which tells the model what to fix). */
+export function toolInput(args: unknown): unknown {
+ if (typeof args !== "string") return args ?? {};
+ if (!args.trim()) return {};
+ try {
+ return JSON.parse(args);
+ } catch {
+ return { INVALID_JSON: args };
+ }
+}
+
+const toolList = (req: ChatRequest) => req.tools?.map((t) => ({ type: "function", function: { name: t.name, description: t.description ?? "", parameters: t.parameters } }));
+
+// ---------------------------------------------------------------------------
+// Ollama: POST {url}/api/chat
+
+export function ollamaBody(req: ChatRequest, model: string, context: number, withJson = true): Record<string, unknown> {
+ const tools = toolList(req);
+ return {
+ model,
+ stream: false,
+ ...(req.think === false && { think: false }),
+ messages: req.messages.map((m) => ({
+ role: m.role,
+ content: m.content,
+ ...(m.toolCalls?.length && { tool_calls: m.toolCalls.map((c) => ({ function: { name: c.name, arguments: c.input } })) }),
+ ...(m.toolName && { tool_name: m.toolName }),
++ ...(m.images?.length && { images: m.images.map((i) => i.data) }),
+ })),
+ ...(tools?.length && { tools }),
+ ...(withJson && req.json && { format: req.json === "object" ? "json" : req.json.schema }),
+ ...((context > 0 || req.maxTokens) && { options: { ...(context > 0 && { num_ctx: context }), ...(req.maxTokens && { num_predict: req.maxTokens }) } }),
+ };
+}
+
+interface OllamaReply {
+ model?: string;
+ message?: { content?: string; thinking?: string; tool_calls?: { function?: { name?: string; arguments?: unknown } }[] };
+ done_reason?: string;
+}
+
+export function parseOllama(j: OllamaReply, model: string): ChatResult {
+ const raw = j.message?.content ?? "";
+ const toolCalls: ChatToolCall[] = (j.message?.tool_calls ?? []).flatMap((c) => (c.function?.name ? [{ id: newToolId(), name: c.function.name, input: toolInput(c.function.arguments) }] : []));
+ return {
+ text: stripThink(raw),
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : j.done_reason === "length" ? "length" : "end",
+ model: j.model || model,
+ thought: !!j.message?.thinking || /<\/think>/i.test(raw),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// OpenAI-compatible: POST {base}/chat/completions
+
++type WirePart = { type: "text"; text: string } | { type: "image_url"; image_url: { url: string } };
++
+type WireMessage =
- | { role: "system" | "user"; content: string }
++ | { role: "system" | "user"; content: string | WirePart[] }
+ | { role: "assistant"; content: string | null; tool_calls?: { id: string; type: "function"; function: { name: string; arguments: string } }[] }
+ | { role: "tool"; tool_call_id: string; content: string };
+
+function wireMessage(m: ChatMessage): WireMessage {
+ if (m.role === "assistant") {
+ const calls = m.toolCalls ?? [];
+ return calls.length
+ ? { role: "assistant", content: m.content || null, tool_calls: calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) } })) }
+ : { role: "assistant", content: m.content };
+ }
+ if (m.role === "tool") return { role: "tool", tool_call_id: m.toolCallId ?? "", content: m.content };
++ // Pictures as data URLs before the words (OpenAI's vision format, which LM Studio and llama-server read).
++ if (m.role === "user" && m.images?.length) {
++ return { role: "user", content: [...m.images.map((i): WirePart => ({ type: "image_url", image_url: { url: `data:${i.contentType};base64,${i.data}` } })), { type: "text", text: m.content }] };
++ }
+ return { role: m.role, content: m.content };
+}
+
+/**
+ * `response_format` per server. A schema goes as json_schema everywhere, with `strict` except on
+ * LM Studio (its docs send `"strict": "true"`, a string; LM Studio builds a grammar from the schema
+ * either way, so it's left out); "any object" is json_object, except on LM Studio, which only documents
+ * json_schema, so it gets the schema of any object.
+ */
+export function responseFormat(kind: LocalKind, json: JsonSpec): Record<string, unknown> {
+ if (json === "object") return kind === "lmstudio" ? { type: "json_schema", json_schema: { name: "answer", schema: { type: "object" } } } : { type: "json_object" };
+ return { type: "json_schema", json_schema: { name: json.name, ...(kind !== "lmstudio" && { strict: true }), schema: json.schema } };
+}
+
+/**
+ * The request body. `model` null leaves the field out: Unsloth Studio then answers with the model
+ * loaded in it. Unsloth also gets enable_tools:false on every call, so a prompt never runs its
+ * server-side Python, shell or web search (Fuobe's prompts carry text from the web).
+ */
+export function openaiBody(kind: LocalKind, req: ChatRequest, model: string | null, withJson = true): Record<string, unknown> {
+ const tools = toolList(req);
+ return {
+ ...(model && { model }),
+ messages: req.messages.map(wireMessage),
+ stream: false,
+ ...(tools?.length && { tools, tool_choice: "auto" }),
+ ...(withJson && req.json && { response_format: responseFormat(kind, req.json) }),
+ ...(req.maxTokens && { max_tokens: req.maxTokens }),
+ ...(kind === "unsloth" && { enable_tools: false, ...(req.think === false && { enable_thinking: false }) }),
+ };
+}
+
+interface OpenAiReply {
+ model?: string;
+ choices?: {
+ finish_reason?: string | null;
+ message?: { content?: string | null; reasoning_content?: string | null; reasoning?: string | null; tool_calls?: { id?: string; function?: { name?: string; arguments?: unknown } }[] | null };
+ }[];
+}
+
+export function parseOpenai(j: OpenAiReply, model: string): ChatResult {
+ const choice = j.choices?.[0];
+ const msg = choice?.message;
+ const raw = typeof msg?.content === "string" ? msg.content : "";
+ // Fuobe makes its own ids: the server's may be any shape ("call_…", digits, or none).
+ const toolCalls: ChatToolCall[] = (msg?.tool_calls ?? []).flatMap((c) => (c?.function?.name ? [{ id: newToolId(), name: c.function.name, input: toolInput(c.function.arguments) }] : []));
+ return {
+ text: stripThink(raw),
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : choice?.finish_reason === "length" ? "length" : "end",
+ model: j.model || model,
+ thought: !!(msg?.reasoning_content || msg?.reasoning) || /<\/think>/i.test(raw),
+ };
+}
diff --cc src/server/model-access.ts
index 00000000,e64753b4..1cb6a440
mode 000000,100644..100644
--- a/src/server/model-access.ts
+++ b/src/server/model-access.ts
@@@ -1,0 -1,356 +1,373 @@@
+ import "server-only";
+ import { getPreset, MODELS } from "@/lib/catalog";
+ import { CHARACTER_LORAS, characterLora } from "@/lib/catalog/character-swap";
+ import { onEngine, providerEngine } from "@/lib/catalog/engines";
+ import { LORA_LIBRARY, MOTION_EFFECT_LORAS } from "@/lib/catalog/lora-library.generated";
+ import { libraryEntry, loraName } from "@/lib/catalog/loras";
+ import { OSS_LORAS, type OssLora } from "@/lib/catalog/oss-loras.generated";
+ import type { Engine, LoraRef, ModelDef, ModelRoute } from "@/lib/catalog/types";
+ import type { ManifestWorkflow } from "@/lib/comfy";
+ import {
+ BROWSER_LICENCE,
+ CLASS_HINT,
+ CLASS_LABEL,
+ LICENCE_CLASSES,
+ llmLicence,
+ licenceInfo,
+ loraLicenceInfo,
+ mergeLicences,
+ modelCardOf,
+ NODE_PACKS,
+ paidApiLicence,
+ PROVIDER_NAME,
+ workflowLicence,
+ type LicenceInfo,
+ } from "@/lib/licences";
+ import {
+ accessSummary as summarize,
+ ACCESS_PLACE,
+ applyChange,
+ gateModel,
+ offMessage,
+ offSwitches,
+ parseAccess,
+ routeOff,
+ switchLabel,
+ type AccessChange,
+ type AccessList,
+ type AccessSummary,
+ type LoraInfo,
+ type ModelEntry,
+ type FactsOf,
+ type ModelAccess,
+ } from "@/lib/model-access";
+ import { db } from "./db";
++import { localModelInUse } from "./llm";
+ import { loadManifest } from "./providers/comfyui";
-import { getSetting } from "./settings";
+
+ /**
+ * Settings → Models & licences on the server: the switches (one settings row, JSON), each route's licence and
+ * node packs (the ComfyUI manifest for open routes, the provider's terms for paid ones), and the checks every
+ * run, listing and automatic pick goes through. Licences are information; only the admin's switches turn
+ * anything off, and everything is on by default.
+ */
+
+ const KEY = "models.access";
+
-let cached: { raw: string | null; access: ModelAccess } | null = null;
++let cached: { raw: string | null; llm: string; access: ModelAccess } | null = null;
+
-/** The switches in effect (the same object while they don't change, so gated model views stay cached). */
++/** The local text model as the licence reads it ("LM Studio|google/gemma-3-12b"). */
++const llmKey = () => {
++ const m = localModelInUse();
++ return `${m.label}|${m.model}`;
++};
++
++/**
++ * The switches in effect (the same object while they don't change, so gated model views stay cached). With a
++ * licence class off, another local text model makes a new object too: its licence decides whether the class
++ * switch reaches the text model.
++ */
+ export function readAccess(): ModelAccess {
+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(KEY) as { value: string } | undefined;
+ const raw = row?.value ?? null;
- if (!cached || cached.raw !== raw) cached = { raw, access: parseAccess(raw) };
++ if (!cached || cached.raw !== raw) cached = { raw, llm: "", access: parseAccess(raw) };
++ if (cached.access.classes.length) {
++ const llm = llmKey();
++ if (cached.llm !== llm) cached = { raw, llm, access: parseAccess(raw) };
++ }
+ return cached.access;
+ }
+
+ export function saveAccess(next: ModelAccess): ModelAccess {
+ const raw = JSON.stringify(next);
+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(KEY, raw);
+ return readAccess();
+ }
+
+ /** Flip switches in one write (read, change, write inside one transaction). */
+ export function changeAccess(changes: AccessChange[]): ModelAccess {
+ return db().transaction(() => saveAccess(changes.reduce(applyChange, readAccess())))();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Licences and node packs per route
+
+ /** Workflow ids a ComfyUI endpoint names: one id, or a family (`video-concat-{n}`). */
+ function workflowsOf(endpoint: string, all: ManifestWorkflow[]): ManifestWorkflow[] {
+ if (!endpoint.includes("{")) return all.filter((w) => w.id === endpoint);
+ const re = new RegExp(`^${endpoint.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{[^}]+\}/g, "\\d+")}$`);
+ return all.filter((w) => re.test(w.id));
+ }
+
+ let factsCache: { manifest: object; byEndpoint: Map<string, { licence: LicenceInfo; packs: string[]; workflows: string[] }> } | null = null;
+
+ /** An open route's licence (its workflows' weights, the strictest one naming it), node packs and workflow ids. */
+ function comfyFacts(endpoint: string): { licence: LicenceInfo; packs: string[]; workflows: string[] } {
+ const manifest = loadManifest();
+ if (factsCache?.manifest !== manifest) factsCache = { manifest, byEndpoint: new Map() };
+ const hit = factsCache.byEndpoint.get(endpoint);
+ if (hit) return hit;
+ const wfs = workflowsOf(endpoint, manifest.workflows);
+ const largestFirst = (w: ManifestWorkflow) => [...w.models].sort((a, b) => (b.sizeGb ?? 0) - (a.sizeGb ?? 0)).flatMap((m) => (m.url ? [m.url] : []));
+ const facts = {
+ licence: wfs.length ? mergeLicences(wfs.map((w) => licenceInfo(workflowLicence(w), largestFirst(w)))) : licenceInfo(workflowLicence({ id: endpoint })),
+ packs: [...new Set(wfs.flatMap((w) => w.customNodes.map((n) => n.name)))],
+ workflows: wfs.map((w) => w.id),
+ };
+ factsCache.byEndpoint.set(endpoint, facts);
+ return facts;
+ }
+
+ /** A route's licence: the weights' for ComfyUI, the provider's terms for a paid API, Fuobe's own code in the browser. */
+ export function routeLicence(route: ModelRoute, model: Pick<ModelDef, "vendor">): LicenceInfo {
+ if (route.provider === "comfyui") return comfyFacts(route.endpoint).licence;
+ if (route.provider === "local") return BROWSER_LICENCE;
- if (route.provider === "llm") return llmLicence(route.endpoint, getSetting("ollamaModel"));
++ if (route.provider === "llm") {
++ const local = localModelInUse();
++ return llmLicence(route.endpoint, local.model, local.label);
++ }
+ return paidApiLicence(model.vendor, [route]);
+ }
+
+ export const factsOf: FactsOf = (route, model) => ({
+ class: routeLicence(route, model).class,
+ packs: route.provider === "comfyui" ? comfyFacts(route.endpoint).packs : [],
+ });
+
+ // ---------------------------------------------------------------------------
+ // The checks
+
+ /** The model as this install offers it (only its routes that are on), or undefined when it is off. */
+ export function offeredModel(m: ModelDef): ModelDef | undefined {
+ return gateModel(m, readAccess(), factsOf);
+ }
+
+ /** Listings (the API, Assist, MCP, the CLI): only what is on, each model with the routes that are on. */
+ export function offeredModels(list: ModelDef[]): ModelDef[] {
+ const access = readAccess();
+ return list.flatMap((m) => gateModel(m, access, factsOf) ?? []);
+ }
+
+ /** Why a model is off, as the refusal names it ("…turned off in Settings → Models & licences (fal.ai is switched off)"). */
+ export function offReason(m: ModelDef, routes?: ModelRoute[]): string {
+ return offMessage(m.name, offSwitches(m, readAccess(), factsOf, routes));
+ }
+
+ /**
+ * The model a run may use, refusing one that is off with a message naming the switch. `engine` (an Original's
+ * engine asked for) refuses that engine when only its routes are off.
+ */
+ export function requireOffered(m: ModelDef, engine?: Engine): ModelDef {
+ const view = offeredModel(m);
+ if (!view) throw new Error(offReason(m));
+ if (engine && m.engines?.includes(engine) && !view.engines?.includes(engine) && view.engine !== engine) {
+ throw new Error(offReason(m, onEngine(m, engine).routes).replace(m.name, `${m.name} ${engine === "open" ? "on your GPU" : "in the cloud"}`));
+ }
+ return view;
+ }
+
+ /** The routes of these that are on (a run's candidates); throws naming the switches when none is. */
+ export function offeredRoutes(m: ModelDef, routes: ModelRoute[]): ModelRoute[] {
+ const access = readAccess();
+ const on = routes.filter((r) => !routeOff(m, r, access, factsOf));
+ if (routes.length && !on.length) throw new Error(offReason(m, routes));
+ return on;
+ }
+
+ /** Whether a model id is offered (an unknown id is not). */
+ export function isOffered(id: string | undefined, engine?: Engine): boolean {
+ const m = id ? MODELS.find((x) => x.id === id) : undefined;
+ const view = m && offeredModel(m);
+ return !!view && (!engine || !m!.engines || (view.engines ?? [view.engine]).includes(engine));
+ }
+
+ /**
+ * A studio's default among its own models (Shorts' restyle models, a Layers tool's): the first that is on, else
+ * the first (its run then refuses, naming the switch to turn back on).
+ */
+ export function firstOn(ids: readonly string[], engine?: Engine): string | undefined {
+ return ids.find((id) => isOffered(id, engine)) ?? ids[0];
+ }
+
+ /**
+ * A default that is on, else the next model that is on and does the same job on this engine (same kind, an
+ * operation in common, not a hidden helper), else the default itself: a run of it then refuses, naming the switch
+ * to turn back on. Assist's own picks and the studios' defaults in /api/models go through it.
+ */
+ export function offeredDefault(id: string | undefined, engine: Engine): string | undefined {
+ if (!id || isOffered(id, engine)) return id;
+ const own = MODELS.find((m) => m.id === id);
+ if (!own) return id;
+ const ops = new Set(onEngine(own, engine).routes.map((r) => r.op));
+ const next = MODELS.find((m) => !m.hidden && m.id !== id && m.kind === own.kind && isOffered(m.id, engine) && onEngine(offeredModel(m)!, engine).routes.some((r) => ops.has(r.op) && providerEngine(r.provider) === engine));
+ return next?.id ?? id;
+ }
+
+ /** The summary the browser filters its pickers with (undefined while everything is on). */
+ export function offeredSummary(): AccessSummary | undefined {
+ return summarize(MODELS, readAccess(), factsOf);
+ }
+
+ // ---------------------------------------------------------------------------
+ // LoRAs
+
+ /** A LoRA's licence: the ref's snapshot, else the library's; a LoRA with neither is the user's own. */
+ export function loraLicence(l: Pick<LoraRef, "file" | "url" | "licence">): LicenceInfo {
+ // The Character swap's LoRAs carry MiniMax H3's own terms (restricted regions), or Turbo's Apache-2.0.
+ const h3 = characterLora(l.file);
+ if (h3) return characterLoraLicence(h3);
+ const e = libraryEntry(l);
+ return loraLicenceInfo(l.licence ?? e?.licence, e?.page);
+ }
+
+ /** A Character swap LoRA's licence as the list shows it (its own recorded terms, its pinned model card). */
+ function characterLoraLicence(l: (typeof CHARACTER_LORAS)[number]): LicenceInfo {
+ const { name, class: cls, url, excludes, notices, note } = l.licence;
+ return { name, class: cls, url: modelCardOf(l.url) ?? url, note, ...(excludes && { excludes }), ...(notices?.length && { notices }) };
+ }
+
+ /**
+ * The LoRAs a run may load: one switched off, or whose licence class is, is left out (the plan's notes say
+ * which switch). With "keep GPU-only LoRAs on your GPU" on, each LoRA is marked so a cloud route leaves the ones
+ * licensed for the user's GPU only out (src/lib/catalog/loras.ts localOnly).
+ */
+ export function offeredLoras(loras: LoraRef[]): { loras: LoraRef[]; notes: string[]; dropped: { file: string; reason: string }[] } {
+ const access = readAccess();
+ const dropped: { file: string; reason: string }[] = [];
+ const kept: LoraRef[] = [];
+ for (const l of loras) {
+ // The user's own LoRAs (a trained @character, no licence recorded) aren't anyone's licensed work: only their own switch counts.
+ const own = !l.licence && !libraryEntry(l);
+ const reason = access.loras.includes(l.file) ? "it is switched off" : !own && access.classes.includes(loraLicence(l).class) ? "its licence class is switched off" : undefined;
+ if (reason) dropped.push({ file: l.file, reason: `${reason} in ${ACCESS_PLACE}` });
+ else kept.push(access.keepGpuOnlyLoras ? { ...l, keepOnGpu: true } : l);
+ }
+ const notes = dropped.length ? [`${dropped.map((d) => loraName({ file: d.file })).join(", ")} ${dropped.length > 1 ? "are" : "is"} left out: turned off in ${ACCESS_PLACE}`] : [];
+ return { loras: kept, notes, dropped };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Settings → Models & licences: everything with its licence and its switch
+
+ const isOpenRoute = (r: ModelRoute) => providerEngine(r.provider) === "open";
+
+ /** A model's licence as the list shows it: the open half names it, the cloud half is said beside it. */
+ export function modelLicence(m: ModelDef): { licence: LicenceInfo; cloud?: LicenceInfo; packs: string[] } {
+ const open = m.routes.filter(isOpenRoute);
+ const cloud = m.routes.filter((r) => !isOpenRoute(r));
+ const packs = [...new Set(open.flatMap((r) => (r.provider === "comfyui" ? comfyFacts(r.endpoint).packs : [])))];
+ const openLicence = open.length ? mergeLicences([...new Map(open.map((r) => [r.endpoint, routeLicence(r, m)])).values()]) : undefined;
+ const cloudRoutes = cloud.filter((r) => r.provider !== "llm");
+ const cloudLicence = cloudRoutes.length ? paidApiLicence(m.vendor, cloudRoutes) : cloud.length ? routeLicence(cloud[0], m) : undefined;
+ if (openLicence) return { licence: openLicence, ...(cloudLicence && { cloud: cloudLicence }), packs };
+ return { licence: cloudLicence ?? { name: "Not recorded", class: "unknown", note: "" }, packs };
+ }
+
+ /** The presets a map key names: a map v2 preset id, or a round-1 slug (the motion, effect or app it matches). */
+ const presetsOf = (key: string) => (getPreset(key) ? [getPreset(key)!] : ["motion", "effect", "app"].flatMap((k) => getPreset(`${k}-${key}`) ?? []));
+
+ /** A map LoRA's name as its download names it: the Hugging Face repo ("Remade-AI/Crane_up" → "Crane up"), else its file. */
+ function mapLoraName(l: OssLora): string {
+ const repo = l.url && /^https:\/\/huggingface\.co\/[^/]+\/([^/]+)\//.exec(l.url)?.[1];
+ return (repo || l.file.replace(/\.safetensors$/i, "")).replace(/[_-]+/g, " ").trim();
+ }
+
+ /**
+ * Every LoRA a run can load, with its licence: the library's, then the preset LoRA map's files that aren't
+ * library files (the round-1 Wan LoRAs camera motions and effects load), their licence as the map records it.
+ */
+ function loraRows(access: ModelAccess): LoraInfo[] {
+ const rows: LoraInfo[] = LORA_LIBRARY.map((e) => {
+ const row = MOTION_EFFECT_LORAS.find((r) => r.loras.includes(e.key));
+ const hold = row?.status === "licence-hold" ? "The research holds this licence: its Hugging Face and civitai pages disagree" : undefined;
+ return { file: e.file, name: e.name, group: e.group, base: e.base, licence: loraLicenceInfo(e.licence, e.page, hold), on: !access.loras.includes(e.file) };
+ });
+ const map = new Map<string, { ref: OssLora; keys: string[] }>();
+ for (const [key, refs] of Object.entries(OSS_LORAS)) {
+ for (const ref of refs) {
+ if (libraryEntry(ref)) continue;
+ const hit = map.get(ref.file);
+ if (hit) hit.keys.push(key);
+ else map.set(ref.file, { ref, keys: [key] });
+ }
+ }
+ for (const [file, { ref, keys }] of map) {
+ const presets = [...new Map(keys.flatMap(presetsOf).map((p) => [p.id, p])).values()];
+ const motion = presets.length ? presets.every((p) => p.id.startsWith("motion-")) : keys.every((k) => k.startsWith("motion-"));
+ const used = presets.length ? `In the preset LoRA map: ${presets.map((p) => p.name).join(", ")}` : "In the preset LoRA map";
+ rows.push({ file, name: mapLoraName(ref), group: motion ? "motion" : "effect", base: ref.base, licence: loraLicenceInfo(ref.licence, modelCardOf(ref.url), used), on: !access.loras.includes(file) });
+ }
+ // The LoRAs the Character swap's graphs load (and fal's route takes): Akatz Labs' swap LoRA and lightx2v's Turbo.
+ for (const l of CHARACTER_LORAS) rows.push({ file: l.file, name: l.name, group: "adapter", base: "MiniMax H3", licence: characterLoraLicence(l), on: !access.loras.includes(l.file) });
+ return rows;
+ }
+
+ /**
+ * Whether a switch names something this install has (a model, a provider in use, a node pack, a LoRA the
+ * library or the preset map loads): the settings API refuses a typo rather than storing a switch that does nothing.
+ */
+ export function knownSwitch(kind: "model" | "provider" | "pack" | "lora", id: string): boolean {
+ switch (kind) {
+ case "model":
+ return MODELS.some((m) => m.id === id);
+ case "provider":
+ return MODELS.some((m) => m.routes.some((r) => r.provider === id));
+ case "pack":
+ return NODE_PACKS.some((p) => p.name === id);
+ case "lora":
+ return LORA_LIBRARY.some((e) => e.file === id) || Object.values(OSS_LORAS).some((refs) => refs.some((r) => r.file === id)) || !!characterLora(id);
+ }
+ }
+
+ export function accessList(): AccessList {
+ const access = readAccess();
+ const models: ModelEntry[] = MODELS.map((m) => {
+ const { licence, cloud, packs } = modelLicence(m);
+ const others = { ...access, models: access.models.filter((x) => x !== m.id) };
+ const off = m.routes.map((r) => routeOff(m, r, others, factsOf)).filter((s): s is NonNullable<typeof s> => !!s);
+ const labels = [...new Set(off.map(switchLabel))];
+ const all = off.length === m.routes.length;
+ return {
+ id: m.id,
+ name: m.name,
+ vendor: m.vendor,
+ kind: m.kind,
+ ...(m.hidden && { hidden: true as const }),
+ engines: m.engines ?? [m.engine],
+ providers: [...new Set(m.routes.map((r) => r.provider))],
+ licence,
+ ...(cloud && { cloud }),
+ packs,
+ on: !access.models.includes(m.id),
+ offBy: all ? labels : [],
+ partly: all ? [] : labels,
+ };
+ });
+ const count = (f: (e: ModelEntry) => boolean) => models.filter(f).length;
+ const routeClasses = (id: string) => {
+ const m = MODELS.find((x) => x.id === id)!;
+ return new Set(m.routes.map((r) => factsOf(r, m).class));
+ };
+ const classesOf = new Map(models.map((e) => [e.id, routeClasses(e.id)]));
+ const loras = loraRows(access);
+ return {
+ access,
+ classes: LICENCE_CLASSES.map((id) => ({
+ id,
+ label: CLASS_LABEL[id],
+ hint: CLASS_HINT[id],
+ models: count((e) => classesOf.get(e.id)!.has(id)),
+ loras: loras.filter((l) => l.licence.class === id).length,
+ on: !access.classes.includes(id),
+ })),
+ providers: [...new Set(MODELS.flatMap((m) => m.routes.map((r) => r.provider)))].map((id) => ({
+ id,
+ label: PROVIDER_NAME[id] ?? id,
+ models: count((e) => e.providers.includes(id)),
+ on: !access.providers.includes(id),
+ })),
+ packs: NODE_PACKS.map((p) => ({ ...p, models: count((e) => e.packs.includes(p.name)), on: !access.packs.includes(p.name) })),
+ models,
+ loras,
+ };
+ }
diff --cc src/server/providers/llm.ts
index f8fd5fae,9eb9207c..34d9d5d8
--- a/src/server/providers/llm.ts
+++ b/src/server/providers/llm.ts
@@@ -4,7 -5,6 +4,7 @@@ import { nanoid } from "nanoid"
import { getModel } from "@/lib/catalog";
import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";
import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";
- import { aiHelper, chatLocal, emptyReply, localLabel, localProblem, localReady, localWhat, probeLocal, type JsonSpec, type Ready } from "../llm";
++import { aiHelper, chatLocal, checkLocal, emptyReply, LOCAL_LABELS, localLabel, localProblem, localReady, localServers, localWhat, pinnedKind, probeLocal, type JsonSpec, type LocalKind, type Ready } from "../llm";
import { engineMode, getSetting } from "../settings";
import { toDataUri } from "../storage";
import { comfyProvider } from "./comfyui";
@@@ -362,12 -391,36 +362,53 @@@ async function runJob(op: string, input
return [textOutput(done.join("\n\n"), null, { language: lang })];
}
+ /** Is the Anthropic key accepted? Listing one model costs nothing. */
+ async function testClaude(): Promise<{ ok: boolean; detail: string }> {
+ try {
+ await new Anthropic({ apiKey: getSetting("anthropicKey") }).models.list({ limit: 1 }, { timeout: 15_000, maxRetries: 0 });
+ return { ok: true, detail: "Claude key accepted" };
+ } catch (e) {
+ if (e instanceof Anthropic.AuthenticationError) return { ok: false, detail: "Anthropic rejected the key (401)" };
+ if (e instanceof Anthropic.PermissionDeniedError) return { ok: false, detail: "That Anthropic key can't use the API (403)" };
+ if (e instanceof Anthropic.APIError && e.status) return { ok: false, detail: `Anthropic answered ${e.status}: ${e.message}` };
+ return { ok: false, detail: `Can't reach Anthropic (${(e as Error).message})` };
+ }
+ }
+
-/** Does Ollama answer, and has it pulled the model Settings names? */
-async function testOllama(): Promise<{ ok: boolean; detail: string }> {
- const model = getSetting("ollamaModel");
- try {
- const res = await fetch(`${ollamaUrl()}/api/tags`, { signal: AbortSignal.timeout(3000) });
- if (!res.ok) return { ok: false, detail: `Ollama answered HTTP ${res.status}` };
- const names = (((await res.json()) as { models?: { name?: string }[] }).models ?? []).map((m) => m.name ?? "");
- const has = names.some((n) => n === model || n === `${model}:latest` || n.split(":")[0] === model);
- return has ? { ok: true, detail: `Ollama · ${model} ready` } : { ok: false, detail: `Ollama answers, but ${model} isn't pulled — run: ollama pull ${model}` };
- } catch (e) {
- return { ok: false, detail: `Can't reach Ollama at ${ollamaUrl()} (${(e as Error).message})` };
- }
-}
++/** The local server each of its settings belongs to: Save & test checks that server. */
++const LOCAL_FOCUS: Partial<Record<string, LocalKind>> = {
++ ollamaUrl: "ollama",
++ ollamaModel: "ollama",
++ lmstudioUrl: "lmstudio",
++ lmstudioModel: "lmstudio",
++ lmstudioToken: "lmstudio",
++ unslothUrl: "unsloth",
++ unslothModel: "unsloth",
++ unslothKey: "unsloth",
++ llmUrl: "custom",
++ llmModel: "custom",
++ llmKey: "custom",
++};
++
++/** "Ollama, LM Studio or Unsloth Studio", or the server Settings pins. */
++const localNames = () => {
++ const pinned = pinnedKind();
++ return pinned ? LOCAL_LABELS[pinned] : "Ollama, LM Studio or Unsloth Studio";
++};
++
++/** Where the local servers were looked for, for "nothing answers at …". */
++const localUrls = () =>
++ localServers()
++ .map((s) => s.url)
++ .filter(Boolean)
++ .join(", ");
+
export const llmProvider: ProviderAdapter = {
id: "llm",
- label: "Claude or Ollama",
+ /** "Claude or LM Studio": the local server in use (or pinned), "a local model" when none answers. */
+ get label() {
+ return llmLabel({ endpoint: "auto" });
+ },
isConfigured: () => llmBackends({ endpoint: "auto" }).length > 0,
// Text steps read their text from the prompt; files aren't sent anywhere.
@@@ -406,9 -456,34 +447,38 @@@
jobs().delete(externalId);
},
- async test() {
+ /**
- * Checks each LLM text steps would use: Claude's key (a free model list call) and that Ollama has
- * its model. Checking the Anthropic key itself (focus) always asks Anthropic, also when text steps
- * run on Ollama (Open source only, or the Enhancer set to Ollama): Assist can still use the key.
- * Checking Ollama's address or model asks Ollama.
++ * Checks each LLM text steps would use: Claude's key (a free model list call) and that the local
++ * server answers with its model. Checking the Anthropic key itself (focus) always asks Anthropic,
++ * also when text steps run on a local model (Open source only, or the AI helper set to Local):
++ * Assist can still use the key. Checking a local server's URL, model or key asks that server.
+ */
+ async test(opts) {
+ if (opts?.focus === "anthropicKey") {
+ if (!getSetting("anthropicKey")) return { ok: false, detail: "No Anthropic key set" };
+ const claude = await testClaude();
+ // A good key that text steps don't use: say where they run, so green doesn't read as "Claude rewrites prompts".
- const choice = getSetting("enhanceProvider");
++ const choice = aiHelper();
+ let elsewhere: string | null = null;
- if (choice === "none") elsewhere = "text steps are off (Enhancer: Offline rewriter)";
- else if (choice === "ollama") elsewhere = "text steps use Ollama (Enhancer)";
- else if (choice === "auto" && engineMode() === "open") elsewhere = "Open source only mode keeps text steps on Ollama";
++ if (choice === "none") elsewhere = "text steps are off (AI helper: Offline rewriter)";
++ else if (choice === "local" || (choice === "auto" && engineMode() === "open")) {
++ await probeLocal();
++ elsewhere = choice === "local" ? `text steps use ${localLabel()} (AI helper)` : `Open source only mode keeps text steps on ${localLabel()}`;
++ }
+ return claude.ok && elsewhere ? { ok: true, detail: `${claude.detail} · ${elsewhere}` } : claude;
+ }
- if (opts?.focus === "ollamaUrl" || opts?.focus === "ollamaModel") return testOllama();
- if (getSetting("enhanceProvider") === "none") return { ok: false, detail: "Text steps are off (Enhancer: Offline rewriter)" };
- await probeOllama(true);
++ const kind = opts?.focus ? LOCAL_FOCUS[opts.focus] : undefined;
++ if (kind) return checkLocal(kind);
++ if (aiHelper() === "none") return { ok: false, detail: "Text steps are off (AI helper: Offline rewriter)" };
+ await probeLocal(true);
const b = llmBackends({ endpoint: "auto" });
- return b.length ? { ok: true, detail: `Text steps run on ${b.map((x) => backendLabel(x)).join(", then ")}` } : { ok: false, detail: llmMissing({ endpoint: "auto" }) };
+ if (!b.length) {
- return { ok: false, detail: engineMode() === "open" && getSetting("anthropicKey") ? `Open source only mode skips Claude, and Ollama doesn't answer at ${ollamaUrl()}` : `Add an Anthropic key, or start Ollama (nothing answers at ${ollamaUrl()})` };
++ const why = localProblem() ?? `nothing answers at ${localUrls()}`;
++ return { ok: false, detail: engineMode() === "open" && getSetting("anthropicKey") ? `Open source only mode skips Claude, and no local model can run: ${why}` : `Add an Anthropic key, or start ${localNames()} (${why})` };
+ }
- const checks = await Promise.all(b.map((x) => (x === "claude" ? testClaude() : x === "ollama" ? testOllama() : Promise.resolve({ ok: true, detail: BACKEND_LABEL[x] }))));
++ const checks = await Promise.all(b.map((x) => (x === "claude" ? testClaude() : x === "local" ? checkLocal() : Promise.resolve({ ok: true, detail: backendLabel(x) }))));
+ const detail = checks.map((c) => c.detail).join(" · ");
+ // Fine when the first one works (the rest are fallbacks); otherwise say what failed.
- return { ok: checks[0].ok, detail: b.length > 1 && checks[0].ok ? `Text steps run on ${b.map((x) => BACKEND_LABEL[x]).join(", then ")} · ${detail}` : detail };
++ return { ok: checks[0].ok, detail: b.length > 1 && checks[0].ok ? `Text steps run on ${b.map((x) => backendLabel(x)).join(", then ")} · ${detail}` : detail };
},
};
diff --cc src/server/settings.ts
index e6ee4c9e,c691914e..ac62d665
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@@ -41,39 -44,41 +45,63 @@@ export const SETTINGS =
aiToolkitDatasetDir: { key: "aitk.datasetDir", env: "AI_TOOLKIT_DATASET_DIR" },
/** "auto" = demo outputs only when the chosen provider is not configured. */
demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "auto", options: ["auto", "on", "off"] },
- enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "ollama", "none"] },
+ /** Settings → AI helper: Claude, a local model, or offline. "ollama" is the old name of "local" and still means it. */
+ enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "local", "ollama", "none"] },
+ /** Which local model server: "auto" uses the first that answers (Ollama, LM Studio, Unsloth Studio, then the custom URL). */
+ llmProvider: { key: "llm.provider", env: "FUOBE_LLM_PROVIDER", default: "auto", options: ["auto", "ollama", "lmstudio", "unsloth", "custom"] },
ollamaUrl: { key: "ollama.url", env: "OLLAMA_URL", default: "http://127.0.0.1:11434" },
ollamaModel: { key: "ollama.model", env: "OLLAMA_MODEL", default: "qwen3:8b" },
+ lmstudioUrl: { key: "lmstudio.url", env: "LMSTUDIO_URL", default: "http://127.0.0.1:1234" },
+ /** Empty: a loaded model, else one trained for tool use. */
+ lmstudioModel: { key: "lmstudio.model", env: "LMSTUDIO_MODEL" },
+ /** Only when LM Studio's "Require Authentication" is on (LM_API_TOKEN also works). */
+ lmstudioToken: { key: "lmstudio.token", env: ["LMSTUDIO_API_TOKEN", "LM_API_TOKEN"], secret: true },
+ unslothUrl: { key: "unsloth.url", env: "UNSLOTH_URL", default: "http://127.0.0.1:8888" },
+ /** Empty: the model loaded in Unsloth Studio. */
+ unslothModel: { key: "unsloth.model", env: "UNSLOTH_MODEL" },
+ /** An sk-unsloth-… key (UNSLOTH_STUDIO_AUTH_TOKEN also works); empty for keyless access. */
+ unslothKey: { key: "unsloth.key", env: ["UNSLOTH_API_KEY", "UNSLOTH_STUDIO_AUTH_TOKEN"], secret: true },
+ /** Any other OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…): its base URL. */
+ llmUrl: { key: "llm.url", env: "FUOBE_LLM_URL" },
+ llmModel: { key: "llm.model", env: "FUOBE_LLM_MODEL" },
+ llmKey: { key: "llm.key", env: "FUOBE_LLM_API_KEY", secret: true },
+ /** Tokens of context the local model gets (Ollama's num_ctx; LM Studio loads models with it). 0 = the server's own setting. */
+ llmContext: { key: "llm.context", env: "FUOBE_LLM_CONTEXT", default: "16384" },
+ /** "1" once the first-run guide was put away, or /api/status first saw something the engine mode generates with connected: Home stops offering it. */
+ onboarded: { key: "onboarding.done", default: "0", options: ["0", "1"] },
} satisfies Record<string, SettingDef>;
export type SettingName = keyof typeof SETTINGS;
+/** The first of a setting's env vars that is set. */
+const envValue = (def: SettingDef): string | undefined => [def.env ?? []].flat().map((n) => process.env[n]).find((v) => !!v);
+
+ /** Unsaved values a connection test runs with (withCandidates), in place of the saved ones. */
+ const candidates = new AsyncLocalStorage<Partial<Record<SettingName, string>>>();
+
+ /**
+ * Run `fn` as if these settings were saved: Settings' "Save & test" tests a typed key or URL before
+ * writing it. An empty value reads as unset (the environment variable or the default). Nothing is stored.
+ */
+ export function withCandidates<T>(values: Partial<Record<SettingName, string>>, fn: () => T): T {
+ return candidates.run(values, fn);
+ }
+
+ /** Inside withCandidates: whether `name` is being tried with an unsaved value. */
+ export function isCandidate(name: SettingName): boolean {
+ return candidates.getStore()?.[name] !== undefined;
+ }
+
+ /** The value in effect without the unsaved ones (saved, environment or default), also inside withCandidates. */
+ export function savedSetting(name: SettingName): string {
+ return candidates.exit(() => getSetting(name));
+ }
+
export function getSetting(name: SettingName): string {
const def: SettingDef = SETTINGS[name];
- const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined;
+ const candidate = candidates.getStore()?.[name];
+ const row = candidate !== undefined ? { value: candidate.trim() } : (db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined);
- const value = row && row.value !== "" ? row.value : def.env && process.env[def.env] ? process.env[def.env]! : (def.default ?? "");
+ const value = row && row.value !== "" ? row.value : (envValue(def) ?? def.default ?? "");
// An invalid env/db value falls back to the default instead of breaking routing.
if (def.options && !def.options.includes(value)) return def.default ?? "";
return value;
diff --cc tests/assist-schedules.test.ts
index 00000000,5829a331..570bcc86
mode 000000,100644..100644
--- a/tests/assist-schedules.test.ts
+++ b/tests/assist-schedules.test.ts
@@@ -1,0 -1,361 +1,369 @@@
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+ import type Anthropic from "@anthropic-ai/sdk";
+
+ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+ vi.setConfig({ testTimeout: 60_000 });
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-sched-"));
+ 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";
+
+ // No real 30 s sweep in this process: the fixtures' times are due by the real clock too, and a sweep
+ // with Date.now() would start extra runs. A runner that is already "running" (its timer cleared) keeps
+ // ensureScheduleRunner from starting one; the first test checks that saving a task starts it.
+ const stubTimer = setInterval(() => {}, 60_000);
+ clearInterval(stubTimer);
+ globalThis.__fuobeScheduleRunner = { tick: () => {}, timer: stubTimer };
+
+ const { setSetting } = await import("@/server/settings");
+ const agent = await import("@/server/assist/agent");
+ const tools = await import("@/server/assist/tools");
+ const sched = await import("@/server/assist/schedules");
+ const projects = await import("@/server/assist/projects");
+ const { db } = await import("@/server/db");
+ const { spendOf } = await import("@/lib/assist-schedule");
+ const connectors = await import("@/server/assist/connectors");
+ const listRoute = await import("@/app/api/assist/schedules/route");
+ const oneRoute = await import("@/app/api/assist/schedules/[scheduleId]/route");
+ const runRoute = await import("@/app/api/assist/schedules/[scheduleId]/run/route");
+
+ type Block = Anthropic.Beta.BetaContentBlock;
+ const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;
+ const generateCall = (id: string, input: unknown) => ({ type: "tool_use", id, name: "generate", input }) as unknown as Block;
+ const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason) => ({ content, stop_reason: stop, stop_details: null }) as Anthropic.Beta.BetaMessage;
+ const job = (prompt: string) => ({ summary: prompt, jobs: [{ model_id: "nano-banana-pro", prompt }] });
+
+ /** A model that makes one generate call per turn listed, then says it's done; it records what it saw. */
+ function scripted(...prompts: string[]) {
+ const seen: { system: string; messages: string; connectors?: string[] }[] = [];
+ let n = 0;
+ const call: import("@/server/assist/agent").ModelCall = async ({ system, messages, connectors }) => {
+ seen.push({ system: system.turn, messages: JSON.stringify(messages), connectors: connectors?.map((c) => c.slug) });
+ const p = prompts[n++];
+ return p ? reply([text("On it."), generateCall(`toolu_${n}`, job(p))], "tool_use") : reply([text("Done — your ad is rendering.")], "end_turn");
+ };
+ return { call, seen };
+ }
+
+ const T = (s: string) => Date.parse(s);
+ const base = { prompt: "Make today's perfume ad", tz: "UTC", engine: "cloud" as const, approval: "ask" as const };
+ const threadOf = (id: string) => agent.getThread(id)!.thread;
+
+ beforeAll(() => setSetting("demoMode", "auto"));
+ afterEach(() => {
+ setSetting("falKey", "");
+ db().prepare("DELETE FROM assist_schedules").run();
+ });
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ describe("scheduled tasks", () => {
++ it("show a task saved with the old Ollama agent as a local-model task", () => {
++ const s = sched.createSchedule({ ...base, title: "Old local", mode: { mode: "manual", agent: "local", model: "qwen3:8b" }, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
++ expect(s.mode).toMatchObject({ mode: "manual", agent: "local" });
++ db().prepare("UPDATE assist_schedules SET mode_json = json_set(mode_json, '$.agent', 'ollama') WHERE id = ?").run(s.id);
++ expect(sched.getSchedule(s.id)!.mode).toEqual({ mode: "manual", agent: "local", model: "qwen3:8b" });
++ sched.deleteSchedule(s.id);
++ });
++
+ it("are checked when saved: the zone, a time that has passed, the project", () => {
+ const now = T("2026-10-27T08:00:00Z");
+ expect(() => sched.createSchedule({ ...base, title: "x", tz: "Mars/Base", rule: { kind: "daily", time: "09:00" } }, now)).toThrow("Pick a time zone");
+ expect(() => sched.createSchedule({ ...base, title: "x", rule: { kind: "once", at: "2026-10-26T09:00" } }, now)).toThrow(/passed/);
+ expect(() => sched.createSchedule({ ...base, title: "x", projectId: "nope", rule: { kind: "daily", time: "09:00" } }, now)).toThrow(/project/);
+ // Saving a task makes sure the sweep is running (it also starts at boot).
+ const stub = globalThis.__fuobeScheduleRunner;
+ globalThis.__fuobeScheduleRunner = undefined;
+ const s = sched.createSchedule({ ...base, title: "Every 6h", rule: { kind: "hours", every: 6 } }, now);
+ expect(globalThis.__fuobeScheduleRunner).toBeDefined();
+ clearInterval(globalThis.__fuobeScheduleRunner!.timer);
+ globalThis.__fuobeScheduleRunner = stub;
+ expect(s.rule).toEqual({ kind: "hours", every: 6, from: now });
+ expect(s.connectors).toBe(false);
+ expect(s.nextRunAt).toBe(now + 6 * 3_600_000);
+ // Ask first has no cap; auto gets the default unless one is given.
+ expect(s.capUsd).toBeNull();
+ expect(sched.createSchedule({ ...base, title: "auto", approval: "auto", rule: { kind: "daily", time: "09:00" } }, now).capUsd).toBe(2);
+ // Pausing hides the next run; resuming picks it from now; an unchanged "every N hours" keeps counting from its start.
+ const paused = sched.updateSchedule(s.id, { paused: true }, now + 1000)!;
+ expect(paused).toMatchObject({ paused: true, nextRunAt: null });
+ const resumed = sched.updateSchedule(s.id, { paused: false }, now + 7 * 3_600_000)!;
+ expect(resumed.nextRunAt).toBe(now + 12 * 3_600_000);
+ expect(sched.updateSchedule(s.id, { rule: { kind: "hours", every: 2 } }, now + 7 * 3_600_000)!.nextRunAt).toBe(now + 9 * 3_600_000);
+ });
+
+ it("the routes validate the body and say what's wrong", async () => {
+ const bad = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ ...base, title: "x", rule: { kind: "daily", time: "9am" } }) }));
+ expect(bad.status).toBe(400);
+ expect((await bad.json()).error).toBe("Pick a time");
+ const ok = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ ...base, title: "Daily", rule: { kind: "weekly", days: [1, 3], time: "09:00" } }) }));
+ expect(ok.status).toBe(201);
+ const created = await ok.json();
+ expect((await (await listRoute.GET(new Request("http://x/api/assist/schedules?project=none"))).json()).items).toHaveLength(1);
+ const ctx = { params: Promise.resolve({ scheduleId: created.id }) };
+ expect(await (await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ paused: true }) }), ctx)).json()).toMatchObject({ paused: true });
+ expect((await oneRoute.DELETE(new Request("http://x"), ctx)).status).toBe(204);
+ expect((await oneRoute.GET(new Request("http://x"), ctx)).status).toBe(404);
+ });
+ });
+
+ describe("the sweep (fake clock)", () => {
+ it("starts what's due, once, as a new chat — and moves the task to its next time", async () => {
+ const s = sched.createSchedule({ ...base, title: "Perfume ad", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ expect(s.nextRunAt).toBe(T("2026-10-27T09:00:00Z"));
+ const m = scripted("A perfume ad");
+ expect(await sched.sweepSchedules(T("2026-10-27T08:59:59Z"), { model: m.call })).toEqual([]);
+ // Two sweeps at once (a hot reload's second timer): one run.
+ const [a, b] = await Promise.all([sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: m.call }), sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: m.call })]);
+ expect([...a, ...b]).toHaveLength(1);
+ const view = sched.getSchedule(s.id)!;
+ expect(view).toMatchObject({ runs: 1, lastRunAt: T("2026-10-27T09:00:30Z"), nextRunAt: T("2026-10-28T09:00:00Z") });
+ const t = threadOf([...a, ...b][0]);
+ expect(t).toMatchObject({ title: "Perfume ad · Tue 27 Oct, 09:00", scheduleId: s.id, autoApprove: false });
+ expect(t.items[0]).toMatchObject({ role: "notice", text: expect.stringMatching(/^Scheduled run of “Perfume ad” · Every day at 09:00 · plans wait for your approval/) });
+ expect(t.items[1]).toMatchObject({ role: "user", text: "Make today's perfume ad" });
+ // The model was told nobody is watching.
+ expect(m.seen[0].system).toMatch(/scheduled run of the task “Perfume ad” \(Every day at 09:00, UTC/);
+ expect(m.seen[0].system).toMatch(/don't ask questions/);
+ });
+
+ it("a run the server missed while it was off happens once, then the next time is from now", async () => {
+ const s = sched.createSchedule({ ...base, title: "Missed", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const started = await sched.sweepSchedules(T("2026-10-30T12:00:00Z"), { model: scripted().call });
+ expect(started).toHaveLength(1);
+ expect(sched.getSchedule(s.id)).toMatchObject({ runs: 1, nextRunAt: T("2026-10-31T09:00:00Z") });
+ expect(await sched.sweepSchedules(T("2026-10-30T12:00:01Z"), { model: scripted().call })).toEqual([]);
+ });
+
+ it("a one-off runs once, then has no next time; paused tasks don't run", async () => {
+ const once = sched.createSchedule({ ...base, title: "Once", rule: { kind: "once", at: "2026-10-27T10:00" } }, T("2026-10-27T08:00:00Z"));
+ const paused = sched.createSchedule({ ...base, title: "Paused", paused: true, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ expect(await sched.sweepSchedules(T("2026-10-27T10:00:00Z"), { model: scripted().call })).toHaveLength(1);
+ expect(sched.getSchedule(once.id)).toMatchObject({ runs: 1, nextRunAt: null, last: { status: "done", text: "Done — your ad is rendering." } });
+ expect(sched.getSchedule(paused.id)).toMatchObject({ runs: 0, paused: true });
+ expect(await sched.sweepSchedules(T("2026-10-29T10:00:00Z"), { model: scripted().call })).toEqual([]);
+ });
+
+ it("skips a run while the one before is still going", async () => {
+ const s = sched.createSchedule({ ...base, title: "Slow", rule: { kind: "hours", every: 1 } }, T("2026-10-27T08:00:00Z"));
+ let release!: () => void;
+ const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("Finally.")], "end_turn"))));
+ const first = sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: slow });
+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));
+ expect(await sched.sweepSchedules(T("2026-10-27T10:00:00Z"), { model: scripted().call })).toEqual([]);
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "skipped", text: expect.stringMatching(/the run before was still going/) });
+ release();
+ await first;
+ expect(sched.getSchedule(s.id)).toMatchObject({ runs: 1, last: { status: "done", text: "Finally." } });
+ });
+
+ it("a task whose project was deleted pauses and says why", async () => {
+ const p = projects.createProject({ name: "Launch" });
+ const s = sched.createSchedule({ ...base, title: "In a project", projectId: p.id, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ // Runs inside the project.
+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted().call });
+ expect(threadOf(id).projectId).toBe(p.id);
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "done" });
+ projects.deleteProject(p.id);
+ // The reason shows, not the last run's chat (which finished fine).
+ expect(sched.getSchedule(s.id)).toMatchObject({ projectId: null, paused: true, nextRunAt: null, last: { threadId: null, status: "failed", text: "Paused: its project was deleted" } });
+ expect(await sched.sweepSchedules(T("2026-10-28T09:00:00Z"), { model: scripted().call })).toEqual([]);
+ });
+
+ it("a project that vanished before a start: Run now says why, and so does the task", async () => {
+ const p = projects.createProject({ name: "Gone" });
+ const s = sched.createSchedule({ ...base, title: "Orphan", projectId: p.id, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const [first] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted().call });
+ expect(first).toBeTruthy();
+ // Removed behind deleteProject's back (another process, a restore): the start finds no project.
+ db().prepare("DELETE FROM assist_projects WHERE id = ?").run(p.id);
+ const res = await runRoute.POST(new Request("http://x", { method: "POST" }), { params: Promise.resolve({ scheduleId: s.id }) });
+ expect(res.status).toBe(422);
+ expect(await res.json()).toMatchObject({ threadId: null, reason: "paused", error: "Its project was deleted — edit the task to pick another" });
+ expect(sched.getSchedule(s.id)).toMatchObject({ paused: true, last: { threadId: null, status: "failed", text: "Its project was deleted — edit the task to pick another" } });
+ });
+
+ it("Run now: 202 with the new chat; 409 while the last run is still going", async () => {
+ const s = sched.createSchedule({ ...base, title: "Now", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const ctx = { params: Promise.resolve({ scheduleId: s.id }) };
+ let release!: () => void;
+ const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("Made it.")], "end_turn"))));
+ const begun = await sched.startSchedule(s.id, { model: slow });
+ expect(begun.threadId).toBeTruthy();
+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));
+ const busy = await runRoute.POST(new Request("http://x", { method: "POST" }), ctx);
+ expect(busy.status).toBe(409);
+ expect(await busy.json()).toMatchObject({ threadId: null, reason: "busy" });
+ // The click isn't recorded as a skipped run: the task still shows the run that's going.
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: begun.threadId, status: "running" });
+ release();
+ await begun.done;
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: begun.threadId, status: "done", text: "Made it." });
+ expect((await runRoute.POST(new Request("http://x", { method: "POST" }), { params: Promise.resolve({ scheduleId: "nope" }) })).status).toBe(404);
+ });
+
+ it("a run whose chat is deleted doesn't stay 'running'", async () => {
+ const s = sched.createSchedule({ ...base, title: "Deleted chat", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ // A run the server lost track of (it restarted mid-run): stored as running.
+ const t = agent.createThread({ engine: "cloud", agent: "offline", scheduleId: s.id });
+ db().prepare("UPDATE assist_schedules SET last_thread_id = ?, last_status = 'running', last_text = 'Working…', last_run_at = ? WHERE id = ?").run(t.id, T("2026-10-27T09:00:00Z"), s.id);
+ agent.deleteThread(t.id);
+ expect(sched.getSchedule(s.id)!.last).toEqual({ threadId: null, status: "failed", text: "Its chat was deleted" });
+ // A finished run whose chat is deleted keeps what it reported, without the link.
+ const begun = await sched.startSchedule(s.id, { model: scripted().call });
+ await begun.done;
+ agent.deleteThread(begun.threadId!);
+ expect(sched.getSchedule(s.id)!.last).toEqual({ threadId: null, status: "done", text: "Done — your ad is rendering." });
+ });
+
+ it("an edit that leaves the timing alone keeps a due run; a new time or zone doesn't", async () => {
+ const s = sched.createSchedule({ ...base, title: "Due", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ // Renamed at 09:00:10, before the sweep at 09:00:30: the 09:00 run still happens.
+ expect(sched.updateSchedule(s.id, { title: "Due (renamed)", prompt: "A new prompt" }, T("2026-10-27T09:00:10Z"))!.nextRunAt).toBe(T("2026-10-27T09:00:00Z"));
+ expect(await sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: scripted().call })).toHaveLength(1);
+ expect(sched.getSchedule(s.id)!.nextRunAt).toBe(T("2026-10-28T09:00:00Z"));
+ // A new time is counted from now.
+ expect(sched.updateSchedule(s.id, { rule: { kind: "daily", time: "10:00" } }, T("2026-10-27T09:30:00Z"))!.nextRunAt).toBe(T("2026-10-27T10:00:00Z"));
+ expect(sched.updateSchedule(s.id, { tz: "Europe/Berlin" }, T("2026-10-27T09:30:00Z"))!.nextRunAt).toBe(T("2026-10-28T09:00:00Z"));
+ });
+
+ it("the runner started at boot sweeps a few seconds in, then every 30 s", () => {
+ vi.useFakeTimers();
+ const stub = globalThis.__fuobeScheduleRunner;
+ globalThis.__fuobeScheduleRunner = undefined;
+ try {
+ sched.ensureScheduleRunner({ soon: true });
+ const runner = globalThis.__fuobeScheduleRunner!;
+ const ticks = vi.fn();
+ runner.tick = ticks;
+ vi.advanceTimersByTime(5_000);
+ expect(ticks).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(25_000);
+ expect(ticks).toHaveBeenCalledTimes(2);
+ // A second call (a hot reload) keeps the one timer.
+ sched.ensureScheduleRunner({ soon: true });
+ expect(globalThis.__fuobeScheduleRunner).toBe(runner);
+ clearInterval(runner.timer);
+ } finally {
+ globalThis.__fuobeScheduleRunner = stub;
+ vi.useRealTimers();
+ }
+ });
+ });
+
+ describe("approval and the cost cap", () => {
+ it("ask first: the plan waits as an approval card, and nothing runs", async () => {
+ const s = sched.createSchedule({ ...base, title: "Ask", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted("A perfume ad").call });
+ const t = threadOf(id);
+ expect(t.status).toBe("waiting");
+ expect(t.items.filter((i) => i.role === "approval")).toHaveLength(1);
+ expect(t.items.some((i) => i.role === "generations")).toBe(false);
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "waiting", text: expect.stringMatching(/^A plan waits for your approval/) });
+ // Approving it later shows in the task's last result.
+ await agent.answerApproval(id, true);
+ await agent.run(id, scripted().call);
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "done", text: "Started 1 result" });
+ });
+
+ it("auto-run: a plan within the cap starts on its own (demo runs cost nothing)", async () => {
+ const s = sched.createSchedule({ ...base, title: "Auto", approval: "auto", capUsd: 0, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted("A perfume ad").call });
+ const t = threadOf(id);
+ expect(t).toMatchObject({ status: "idle", autoApprove: true, capUsd: 0, spentUsd: 0 });
+ expect(t.items.some((i) => i.role === "approval")).toBe(false);
+ expect(t.items.filter((i) => i.role === "generations")).toHaveLength(1);
+ expect(t.items[0]).toMatchObject({ text: expect.stringMatching(/only free plans run on their own/) });
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "done" });
+ });
+
+ it("auto-run: what fits runs and counts against the cap; the plan that would pass it waits, with the reason", async () => {
+ setSetting("falKey", "fal-test-key");
+ const realFetch = globalThis.fetch;
+ // The paid job that fits is queued for fal; no request may leave this test.
+ globalThis.fetch = (async () => new Response("offline", { status: 503 })) as typeof fetch;
+ try {
+ const price = spendOf(tools.planFor("generate", job("x"), { engine: "cloud" }).jobs)!;
+ expect(price).toBeGreaterThan(0);
+ const cap = Math.round(price * 1.5 * 100) / 100;
+ const s = sched.createSchedule({ ...base, title: "Capped", approval: "auto", capUsd: cap, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const m = scripted("First ad", "Second ad");
+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m.call });
+ const t = threadOf(id);
+ expect(m.seen[0].system).toMatch(new RegExp(`Auto-run is on up to \\$${cap.toFixed(2)}`));
+ expect(t).toMatchObject({ status: "waiting", spentUsd: price, capUsd: cap });
+ expect(t.items.filter((i) => i.role === "generations")).toHaveLength(1);
+ const card = t.items.find((i) => i.role === "approval");
+ expect(card).toMatchObject({ status: "pending", summary: "Second ad" });
+ const left = (cap - price).toFixed(2);
+ expect(t.items.at(-1)).toMatchObject({ role: "notice", text: `Waiting for you: it costs about $${price.toFixed(2)} and this run has $${left} left of its $${cap.toFixed(2)} cap. Auto-run only starts what fits the cap.` });
+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "waiting" });
+ } finally {
+ globalThis.fetch = realFetch;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ }
+ });
+
+ it("an ordinary chat with auto-run on has no cap", async () => {
+ setSetting("falKey", "fal-test-key");
+ const t = agent.createThread({ engine: "cloud", agent: "offline", autoApprove: true });
+ expect(threadOf(t.id).capUsd).toBeUndefined();
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () => new Response("offline", { status: 503 })) as typeof fetch;
+ try {
+ agent.addMessage(t.id, "go");
+ await agent.run(t.id, scripted("One", "Two").call);
+ expect(threadOf(t.id).items.filter((i) => i.role === "generations")).toHaveLength(2);
+ expect(threadOf(t.id).items.some((i) => i.role === "approval")).toBe(false);
+ } finally {
+ globalThis.fetch = realFetch;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ }
+ });
+ });
+
+ describe("connectors in scheduled runs", () => {
+ afterEach(() => {
+ setSetting("anthropicKey", "");
+ for (const c of connectors.listConnectors()) connectors.deleteConnector(c.id);
+ });
+
+ it("are off unless the task allows them; when on, Claude is told they run without asking", async () => {
+ setSetting("anthropicKey", "sk-ant-test");
+ connectors.createConnector({ name: "Slack", url: "https://mcp.slack.example.com/mcp", token: "xoxb-0123456789abcdefghij" });
+ const off = sched.createSchedule({ ...base, title: "No connectors", mode: { mode: "smart" }, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ const m1 = scripted();
+ const [a] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m1.call });
+ expect(threadOf(a).agent).toBe("claude");
+ expect(m1.seen[0].connectors).toBeUndefined();
+ expect(m1.seen[0].system).not.toMatch(/Connected apps/);
+ expect(threadOf(a).items[0]).toMatchObject({ text: expect.not.stringMatching(/connectors on/) });
+ sched.deleteSchedule(off.id);
+
+ const on = sched.createSchedule({ ...base, title: "With Slack", mode: { mode: "smart" }, connectors: true, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));
+ expect(on.connectors).toBe(true);
+ const m2 = scripted();
+ const [b] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m2.call });
+ expect(m2.seen[0].connectors).toEqual(["slack"]);
+ expect(m2.seen[0].system).toMatch(/Connected apps \(custom MCP connectors\): Slack\. Their tools run the moment you call them/);
+ // Ask first: nothing that depends on unapproved results goes out.
+ expect(m2.seen[0].system).toMatch(/plans here wait for the user's approval/);
+ expect(threadOf(b).items[0]).toMatchObject({ text: expect.stringMatching(/connectors on \(their tools run without asking\)/) });
+ // Turning it off again applies to the next run.
+ expect(sched.updateSchedule(on.id, { connectors: false })!.connectors).toBe(false);
+ });
+
+ it("an ordinary Claude chat in Ask first is told to check before a connector changes anything", async () => {
+ setSetting("anthropicKey", "sk-ant-test");
+ connectors.createConnector({ name: "Linear", url: "https://mcp.linear.example.com/mcp" });
+ const t = agent.createThread({ engine: "cloud", agent: "claude", mode: "smart" });
+ agent.addMessage(t.id, "What's on my board?");
+ const m = scripted();
+ await agent.run(t.id, m.call);
+ expect(m.seen[0].connectors).toEqual(["linear"]);
+ expect(m.seen[0].system).toMatch(/approval cards and the cost cap don't cover them/);
+ expect(m.seen[0].system).toMatch(/say what you'll do and wait for the user's OK in chat/);
+ });
+ });
diff --cc tests/av-tools.test.ts
index ed2d2c32,ada1fa8b..c802dda2
--- a/tests/av-tools.test.ts
+++ b/tests/av-tools.test.ts
@@@ -107,9 -107,9 +107,9 @@@ describe("caption style → burn params
describe("3D viewer data flow", () => {
it("asks the engine's 3D model for the photo; an unknown pick falls back to the default", () => {
expect(model3dRequest({ engine: "cloud", photo: "p.png" })).toEqual({ feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d", inputs: { images: ["p.png"] } });
- expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-trellis2");
+ expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-pixal3d");
expect(model3dRequest({ engine: "cloud", photo: "p.png", modelId: "tripo-h3-1" }).modelId).toBe("tripo-h3-1");
- for (const m of [...MODELS_3D.cloud, ...MODELS_3D.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);
+ for (const m of [...MODELS_3D.image.cloud, ...MODELS_3D.image.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);
});
it("a cloud GLB with formats and a preview → viewer, downloads, and Animate the spin from the photo", () => {
diff --cc tests/connections.test.ts
index 00000000,dc7e9652..21a5bff9
mode 000000,100644..100644
--- a/tests/connections.test.ts
+++ b/tests/connections.test.ts
@@@ -1,0 -1,279 +1,279 @@@
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ import { afterAll, describe, expect, it, vi } from "vitest";
+ import { candidateValues, connectionSummary, FIRST_RUN_KEY, FIRST_RUN_SCRIPT, isTestProvider, nothingConnected, settingProblem, showFirstRun, type ConnectionState } from "@/lib/connections";
+
+ /** Settings' "Save & test", the first-run guide's rule and the connection status strip (R4-02, R4-03, R4-33). */
+
+ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connections-"));
+ 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.FAL_KEY;
+ delete process.env.ANTHROPIC_API_KEY;
+ const { POST: testRoute } = await import("@/app/api/providers/test/route");
+ const { GET: statusRoute } = await import("@/app/api/status/route");
+ const { getSetting, setSetting, withCandidates } = await import("@/server/settings");
+ const { starterPriceLine } = await import("@/lib/starter-prices");
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ /** Answer fetches by URL prefix (status, JSON body); remembers each request's URL and headers. */
+ async function withFetch<T>(answers: Record<string, [number, unknown]>, fn: () => Promise<T>) {
+ const real = globalThis.fetch;
+ const seen: { url: string; auth?: string }[] = [];
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(input instanceof Request ? input.headers : init?.headers);
+ seen.push({ url, auth: headers.get("authorization") ?? headers.get("x-api-key") ?? undefined });
+ const hit = Object.keys(answers).find((k) => url.startsWith(k));
+ if (!hit) throw new TypeError("fetch failed");
+ const [status, body] = answers[hit];
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ try {
+ return { result: await fn(), seen };
+ } finally {
+ globalThis.fetch = real;
+ }
+ }
+
+ const post = async (body: unknown) => {
+ const res = await testRoute(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify(body) }));
+ return { status: res.status, body: (await res.json()) as { ok: boolean; detail: string } };
+ };
+
+ describe("key and address checks", () => {
+ it("wants fal.ai keys as key_id:key_secret", () => {
+ expect(settingProblem("falKey", "1a2b3c-uuid:9f8e7d6c")).toBeNull();
+ expect(settingProblem("falKey", "fal_abcdef")).toMatch(/key_id:key_secret/);
+ expect(settingProblem("falKey", "abc:")).toMatch(/Both halves/);
+ expect(settingProblem("falKey", "abc: def")).toMatch(/Both halves/);
+ // Empty clears the key: nothing to warn about.
+ expect(settingProblem("falKey", " ")).toBeNull();
+ });
+
+ it("knows the other keys' shapes and wants web addresses for servers", () => {
+ expect(settingProblem("replicateToken", "abc")).toMatch(/r8_/);
+ expect(settingProblem("replicateToken", "r8_abc")).toBeNull();
+ expect(settingProblem("anthropicKey", "sk-ant-api03-x")).toBeNull();
+ expect(settingProblem("anthropicKey", "sk-proj-x")).toMatch(/sk-ant-/);
+ expect(settingProblem("comfyUrl", "http://127.0.0.1:8188")).toBeNull();
+ expect(settingProblem("comfyUrl", "127.0.0.1:8188")).toBe("Add http:// in front: http://127.0.0.1:8188");
+ expect(settingProblem("ollamaUrl", "ftp://box")).toMatch(/http:\/\//);
+ expect(settingProblem("comfyUrl", "not a url")).toMatch(/isn't a web address/);
+ expect(settingProblem("ollamaModel", "anything")).toBeNull();
+ });
+
+ it("keeps a test's unsaved values to the settings that provider reads", () => {
+ expect(isTestProvider("fal")).toBe(true);
+ expect(isTestProvider("mock")).toBe(false);
+ expect(isTestProvider("toString")).toBe(false);
+ expect(candidateValues("fal", undefined, " a:b ")).toEqual({ falKey: "a:b" });
+ expect(candidateValues("comfyui", { comfyUrl: "http://x:8188", falKey: "no", comfyToken: 5 })).toEqual({ comfyUrl: "http://x:8188" });
+ expect(candidateValues("llm", { ollamaModel: "llama3" })).toEqual({ ollamaModel: "llama3" });
+ });
+ });
+
+ describe("first-run guide and status strip", () => {
+ const state = (configured: string[], engineMode: ConnectionState["engineMode"] = "both", onboarded = false): ConnectionState => ({
+ providers: Object.fromEntries(["fal", "replicate", "comfyui", "llm", "mock"].map((p) => [p, { configured: configured.includes(p) || p === "mock" }])),
+ engineMode,
+ onboarded,
+ });
+
+ it("shows the guide until something the engine mode uses is connected, or it was put away", () => {
+ expect(showFirstRun(undefined)).toBe(false);
+ expect(showFirstRun(state([]))).toBe(true);
+ expect(showFirstRun(state(["fal"]))).toBe(false);
+ expect(showFirstRun(state(["comfyui"]))).toBe(false);
+ expect(showFirstRun(state([], "both", true))).toBe(false);
+ // An LLM alone makes nothing.
+ expect(showFirstRun(state(["llm"]))).toBe(true);
+ // A key doesn't help an open-source-only install, nor ComfyUI a paid-only one.
+ expect(nothingConnected(state(["fal"], "open"))).toBe(true);
+ expect(nothingConnected(state(["comfyui"], "cloud"))).toBe(true);
+ expect(nothingConnected(state(["replicate"], "cloud"))).toBe(false);
+ });
+
+ it("hides Home's shell guide before the first paint only where this browser put it away", () => {
+ const run = (stored: string | null | Error) => {
+ const attrs: Record<string, string> = {};
+ const localStorage = {
+ getItem: (k: string) => {
+ if (stored instanceof Error) throw stored;
+ return k === FIRST_RUN_KEY ? stored : null;
+ },
+ };
+ const document = { documentElement: { setAttribute: (k: string, v: string) => (attrs[k] = v) } };
+ new Function("localStorage", "document", FIRST_RUN_SCRIPT)(localStorage, document);
+ return attrs["data-first-run"];
+ };
+ expect(run("0")).toBe("0");
+ // A first visit, or a guide still wanted: the shell keeps it, so it doesn't push the page down later.
+ expect(run(null)).toBeUndefined();
+ expect(run("1")).toBeUndefined();
+ // Storage blocked (a private window): nothing breaks.
+ expect(run(new Error("denied"))).toBeUndefined();
+ });
+
+ it("says what each connection is doing, and which ones the mode doesn't use", () => {
+ const s = connectionSummary(state(["replicate", "comfyui"], "open"));
+ expect(s.map((c) => [c.id, c.text, c.ok, c.unused])).toEqual([
+ ["fal", "Not set", false, true],
+ ["replicate", "Key set", true, true],
+ ["comfyui", "Online", true, false],
+ ["llm", "Off", false, false],
+ ]);
+ expect(s.map((c) => c.href)).toEqual(["#fal", "#replicate", "#comfyui", "#text-ai"]);
+ });
+
+ it("quotes a first image and clip on the default paid models", () => {
+ expect(starterPriceLine()).toMatch(/^Nano Banana Pro ≈ \$[\d.]+ an image · Seedance 2\.5 ≈ \$[\d.]+ a 5 s clip$/);
+ });
+ });
+
+ describe("POST /api/providers/test with unsaved values", () => {
+ it("tests a typed fal.ai key without saving it, and says what a key looks like when it's rejected", async () => {
+ setSetting("falKey", "saved-id:saved-secret");
+ const ok = await withFetch({ "https://queue.fal.run/": [404, { detail: "Request not found" }] }, () => post({ provider: "fal", value: "new-id:new-secret" }));
+ expect(ok.result.body).toEqual({ ok: true, detail: "Key accepted" });
+ expect(ok.seen[0].auth).toBe("Key new-id:new-secret");
+ expect(getSetting("falKey")).toBe("saved-id:saved-secret");
+
+ const bad = await withFetch({ "https://queue.fal.run/": [401, { detail: "Unauthorized" }] }, () => post({ provider: "fal", values: { falKey: "fal_only_half" } }));
+ expect(bad.result.body.ok).toBe(false);
+ expect(bad.result.body.detail).toMatch(/^Key rejected \(401\) — fal\.ai keys look like key_id:key_secret/);
+ // A proxy or an outage isn't a verdict on the key.
+ const blocked = await withFetch({ "https://queue.fal.run/": [405, {}] }, () => post({ provider: "fal", value: "new-id:new-secret" }));
+ expect(blocked.result.body).toEqual({ ok: false, detail: "Couldn't check the key: fal.ai answered 405. Try again in a moment" });
+ // Without values it tests the saved key.
+ const saved = await withFetch({ "https://queue.fal.run/": [404, {}] }, () => post({ provider: "fal" }));
+ expect(saved.seen[0].auth).toBe("Key saved-id:saved-secret");
+ setSetting("falKey", "");
+ });
+
+ it("tests a ComfyUI address before it's saved, and says so when nothing answers", async () => {
+ const stats = { system: { comfyui_version: "0.41.0" }, devices: [{ name: "cpu", vram_total: 0 }] };
+ const ok = await withFetch({ "http://10.1.2.3:8188/system_stats": [200, stats] }, () => post({ provider: "comfyui", value: "http://10.1.2.3:8188/" }));
+ expect(ok.result.body).toEqual({ ok: true, detail: "ComfyUI 0.41.0 · cpu" });
+ expect(getSetting("comfyUrl")).toBe("http://127.0.0.1:9");
+ const down = await withFetch({}, () => post({ provider: "comfyui", values: { comfyUrl: "http://10.9.9.9:8188" } }));
+ expect(down.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/^Can't reach ComfyUI at http:\/\/10\.9\.9\.9:8188/) });
+ });
+
+ it("keeps the saved ComfyUI token with the server it was saved for", async () => {
+ const stats = { system: { comfyui_version: "0.41.0" }, devices: [{ name: "cpu", vram_total: 0 }] };
+ setSetting("comfyToken", "saved-secret-token");
+ const answers = { "http://10.1.2.3:8188/system_stats": [200, stats], "http://127.0.0.1:9/system_stats": [200, stats], "http://10.1.2.4:8189/system_stats": [200, stats] } as Record<string, [number, unknown]>;
+ // A new address gets no token unless one is typed with it.
+ const other = await withFetch(answers, () => post({ provider: "comfyui", value: "http://10.1.2.3:8188" }));
+ expect(other.result.body.ok).toBe(true);
+ expect(other.seen.map((r) => r.auth)).toEqual([undefined]);
+ const typed = await withFetch(answers, () => post({ provider: "comfyui", values: { comfyUrl: "http://10.1.2.3:8188", comfyToken: "typed-token" } }));
+ expect(typed.seen.map((r) => r.auth)).toEqual(["Bearer typed-token"]);
+ // The saved server, typed again or not, still gets it.
+ const same = await withFetch(answers, () => post({ provider: "comfyui", value: "http://127.0.0.1:9/" }));
+ expect(same.seen.map((r) => r.auth)).toEqual(["Bearer saved-secret-token"]);
+ const saved = await withFetch(answers, () => post({ provider: "comfyui" }));
+ expect(saved.seen.map((r) => r.auth)).toEqual(["Bearer saved-secret-token"]);
+ // The isolated worker's address is tested on its own, and a new one gets no token either.
+ const iso = await withFetch(answers, () => post({ provider: "comfyui", values: { comfyIsolatedUrl: "http://10.1.2.4:8189" } }));
+ expect(iso.result.body).toEqual({ ok: true, detail: "isolated worker: ComfyUI 0.41.0 · cpu" });
+ expect(iso.seen).toEqual([{ url: "http://10.1.2.4:8189/system_stats", auth: undefined }]);
+ const isoDown = await withFetch(answers, () => post({ provider: "comfyui", values: { comfyIsolatedUrl: "http://10.1.2.5:8189" } }));
+ expect(isoDown.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/isolated ComfyUI worker at http:\/\/10\.1\.2\.5:8189 doesn't answer/) });
+ setSetting("comfyToken", "");
+ });
+
+ it("checks a typed Anthropic key with Anthropic, also when text steps run on Ollama", async () => {
+ const tags = { models: [{ name: "qwen3:8b" }] };
+ const rejectedKey = { "https://api.anthropic.com/v1/models": [401, { type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } }], "http://127.0.0.1:9/api/tags": [200, tags] } as Record<string, [number, unknown]>;
+ const goodKey = { "https://api.anthropic.com/v1/models": [200, { data: [], has_more: false }], "http://127.0.0.1:9/api/tags": [200, tags] } as Record<string, [number, unknown]>;
+ for (const [mode, enhancer, note] of [
+ ["open", "auto", "Open source only mode keeps text steps on Ollama"],
- ["both", "ollama", "text steps use Ollama (Enhancer)"],
++ ["both", "ollama", "text steps use Ollama (AI helper)"],
+ ] as const) {
+ setSetting("engineMode", mode);
+ setSetting("enhanceProvider", enhancer);
+ const bogus = await withFetch(rejectedKey, () => post({ provider: "llm", values: { anthropicKey: "sk-ant-bogus-key-123" } }));
+ expect(bogus.result.body, mode).toEqual({ ok: false, detail: "Anthropic rejected the key (401)" });
+ const good = await withFetch(goodKey, () => post({ provider: "llm", values: { anthropicKey: "sk-ant-good" }, field: "anthropicKey" }));
+ expect(good.result.body, mode).toEqual({ ok: true, detail: `Claude key accepted · ${note}` });
+ }
+ // The saved key, checked from its own field (nothing typed).
+ setSetting("anthropicKey", "sk-ant-saved");
+ const saved = await withFetch(rejectedKey, () => post({ provider: "llm", field: "anthropicKey" }));
+ expect(saved.result.body).toEqual({ ok: false, detail: "Anthropic rejected the key (401)" });
+ expect(saved.seen.some((r) => r.auth === "sk-ant-saved")).toBe(true);
+ // A field another provider owns is ignored: the whole text-step check runs.
+ const ollamaField = await withFetch(rejectedKey, () => post({ provider: "llm", field: "falKey" }));
+ expect(ollamaField.result.body.detail).toMatch(/Ollama/);
+ for (const n of ["engineMode", "enhanceProvider", "anthropicKey"] as const) setSetting(n, "");
+ });
+
+ it("tests Ollama's address and model, and an Anthropic key, for text steps", async () => {
+ const tags = { models: [{ name: "qwen3:8b" }] };
+ const ready = await withFetch({ "http://10.0.0.5:11434/api/tags": [200, tags] }, () => post({ provider: "llm", values: { ollamaUrl: "http://10.0.0.5:11434" } }));
+ expect(ready.result.body).toEqual({ ok: true, detail: "Ollama · qwen3:8b ready" });
+ const missing = await withFetch({ "http://10.0.0.5:11434/api/tags": [200, tags] }, () => post({ provider: "llm", values: { ollamaUrl: "http://10.0.0.5:11434", ollamaModel: "llama3.3" } }));
+ expect(missing.result.body).toEqual({ ok: false, detail: "Ollama answers, but llama3.3 isn't pulled — run: ollama pull llama3.3" });
+ const none = await withFetch({}, () => post({ provider: "llm" }));
+ expect(none.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/Add an Anthropic key, or start Ollama/) });
+
+ const rejected = await withFetch(
+ { "https://api.anthropic.com/v1/models": [401, { type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } }] },
+ () => post({ provider: "llm", values: { anthropicKey: "sk-ant-wrong" } }),
+ );
+ expect(rejected.result.body).toEqual({ ok: false, detail: "Anthropic rejected the key (401)" });
+ expect(rejected.seen.some((r) => r.url.startsWith("https://api.anthropic.com/v1/models") && r.auth === "sk-ant-wrong")).toBe(true);
+ const accepted = await withFetch({ "https://api.anthropic.com/v1/models": [200, { data: [{ id: "claude-opus-5-5", type: "model" }], has_more: false }] }, () =>
+ post({ provider: "llm", values: { anthropicKey: "sk-ant-good" } }),
+ );
+ expect(accepted.result.body).toEqual({ ok: true, detail: "Claude key accepted" });
+ expect(getSetting("anthropicKey")).toBe("");
+ });
+
+ it("refuses unknown providers and values a setting doesn't allow", async () => {
+ expect((await post({ provider: "mock" })).status).toBe(400);
+ expect((await post({ provider: "llm", values: { enhanceProvider: "gpt" } })).body).toMatchObject({ ok: false, detail: expect.stringMatching(/enhanceProvider must be one of/) });
+ });
+
+ it("reads candidates only inside the test", () => {
+ setSetting("ollamaModel", "qwen3:8b");
+ expect(withCandidates({ ollamaModel: "llama3" }, () => getSetting("ollamaModel"))).toBe("llama3");
+ // An empty candidate reads as unset: the environment or the default.
+ expect(withCandidates({ ollamaModel: "" }, () => getSetting("ollamaModel"))).toBe("qwen3:8b");
+ expect(getSetting("ollamaModel")).toBe("qwen3:8b");
+ });
+ });
+
+ describe("GET /api/status", () => {
+ const onboarded = async () => ((await (await statusRoute()).json()) as { onboarded: boolean }).onboarded;
+
+ it("says whether the first-run guide was put away", async () => {
+ expect(await onboarded()).toBe(false);
+ setSetting("onboarded", "1");
+ expect(await onboarded()).toBe(true);
+ setSetting("onboarded", "");
+ });
+
+ it("remembers the first connection the engine mode generates with, so an offline day doesn't bring the guide back", async () => {
+ // Claude makes nothing by itself, and a fal.ai key doesn't serve an open-source-only install.
+ setSetting("anthropicKey", "sk-ant-x");
+ expect(await onboarded()).toBe(false);
+ setSetting("engineMode", "open");
+ setSetting("falKey", "id:secret");
+ expect(await onboarded()).toBe(false);
+ expect(getSetting("onboarded")).toBe("0");
+ setSetting("engineMode", "");
+ expect(await onboarded()).toBe(true);
+ expect(getSetting("onboarded")).toBe("1");
+ // The key goes (or ComfyUI is offline one morning): the guide stays put away.
+ setSetting("falKey", "");
+ expect(await onboarded()).toBe(true);
+ for (const n of ["anthropicKey", "onboarded"] as const) setSetting(n, "");
+ });
+ });
diff --cc tests/covers-from-masters.test.ts
index 00000000,00000000..ae7d5d25
new file mode 100644
--- /dev/null
+++ b/tests/covers-from-masters.test.ts
@@@ -1,0 -1,0 +1,150 @@@
++import { spawnSync } from "node:child_process";
++import fs from "node:fs";
++import os from "node:os";
++import path from "node:path";
++import { afterAll, describe, expect, it } from "vitest";
++
++/** pnpm eval:covers --from-masters: rendered masters (one folder per preset id) become covers, merged into the manifest. */
++type Entry = { poster: string; video?: string; run: string; engine: string; model: string; variant: string };
++type Cover = Entry & { key: string; kind: "image" | "video"; from: string; kept?: true };
++const covers = (await import("../scripts/eval/lib/covers.mjs")) as unknown as {
++ coversFromMasters: (dir: string, opts: Record<string, unknown>) => { covers: Cover[]; skipped: { id: string; why: string }[] };
++ readManifest: (file: string) => Record<string, Entry>;
++ writeManifest: (entries: Record<string, Entry>, file: string) => void;
++ seamless: (frames: Buffer[], fade: number) => Buffer[];
++ loopsAlready: (frames: Buffer[], luma: number) => boolean;
++};
++const { coversFromMasters, loopsAlready, readManifest, seamless, writeManifest } = covers;
++
++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-covers-masters-"));
++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
++
++const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
++const SAMPLES = path.join(process.cwd(), "public", "samples");
++
++function master(root: string, id: string, files: Record<string, string>) {
++ fs.mkdirSync(path.join(root, id), { recursive: true });
++ for (const [name, from] of Object.entries(files)) fs.copyFileSync(from, path.join(root, id, name));
++}
++
++/** A small PNG still, made from a sample clip's first frame. */
++function still(): string {
++ const png = path.join(dir, "still.png");
++ if (!fs.existsSync(png)) spawnSync("ffmpeg", ["-v", "error", "-y", "-i", path.join(SAMPLES, "demo-landscape.mp4"), "-frames:v", "1", png]);
++ return png;
++}
++
++const PROVENANCE = { run: "comfyui-previews-test", engine: "comfyui", model: "ideogram4", videoModel: "minimax-h3", variant: "lean-json" };
++
++describe("covers from masters", () => {
++ it("needs a run name and a masters folder", () => {
++ expect(() => coversFromMasters(dir, {})).toThrow(/--run/);
++ expect(() => coversFromMasters(path.join(dir, "nope"), { run: "r" })).toThrow(/No masters folder/);
++ });
++
++ it("dry run: a clip where there is one, else the start still; folders without either are skipped; nothing is written", () => {
++ const masters = path.join(dir, "dry");
++ master(masters, "effect-set-on-fire", { "clip.mp4": path.join(SAMPLES, "demo-portrait.mp4"), "start.png": path.join(SAMPLES, "previews", "portrait.svg") });
++ master(masters, "app-headshot-generator", { "start.png": path.join(SAMPLES, "previews", "portrait.svg") });
++ master(masters, "motion-still-rendering", {});
++ const manifest = path.join(dir, "dry-manifest.ts");
++ const r = coversFromMasters(masters, { ...PROVENANCE, dryRun: true, publicDir: path.join(dir, "dry-public"), manifest });
++ expect(r.covers.map((c) => [c.key, !!c.video, c.model])).toEqual([
++ ["app-headshot-generator", false, "ideogram4"],
++ ["effect-set-on-fire", true, "minimax-h3"],
++ ]);
++ expect(r.covers[1]).toMatchObject({ poster: "/previews/presets/effect-set-on-fire.jpg", video: "/previews/presets/effect-set-on-fire.mp4", run: "comfyui-previews-test", engine: "comfyui", variant: "lean-json" });
++ expect(r.skipped).toEqual([{ id: "motion-still-rendering", why: "no clip.mp4 or start.png yet" }]);
++ expect(fs.existsSync(manifest)).toBe(false);
++ expect(fs.existsSync(path.join(dir, "dry-public"))).toBe(false);
++ });
++
++ it.runIf(hasFfmpeg)("encodes small covers and merges them into the manifest, keeping other runs' entries; runs again cheaply", () => {
++ const masters = path.join(dir, "masters");
++ const pub = path.join(dir, "public");
++ const out = path.join(pub, "previews", "presets");
++ const manifest = path.join(dir, "manifest.ts");
++ // An earlier eval run's cover, and an earlier masters cover that this run replaces.
++ const measured = { poster: "/previews/dop/effect-thunder-god.jpg", video: "/previews/dop/effect-thunder-god.mp4", run: "r1", engine: "open", model: "oss-wan22-14b", variant: "research" };
++ writeManifest({ "effect-thunder-god": measured, "app-headshot-generator": { poster: "/previews/presets/old.jpg", run: "old", engine: "comfyui", model: "x", variant: "y" } }, manifest);
++ master(masters, "effect-set-on-fire", { "clip.mp4": path.join(SAMPLES, "demo-portrait.mp4") });
++ master(masters, "app-headshot-generator", { "start.png": still() });
++ // A folder's meta.json can name the model that made it.
++ fs.writeFileSync(path.join(masters, "app-headshot-generator", "meta.json"), JSON.stringify({ model: "krea2-realism" }));
++
++ const r = coversFromMasters(masters, { ...PROVENANCE, publicDir: pub, manifest });
++ expect(r.covers).toHaveLength(2);
++ const m = readManifest(manifest);
++ expect(Object.keys(m)).toEqual(["app-headshot-generator", "effect-set-on-fire", "effect-thunder-god"]);
++ expect(m["effect-thunder-god"]).toEqual(measured);
++ expect(m["app-headshot-generator"]).toEqual({ poster: "/previews/presets/app-headshot-generator.jpg", run: "comfyui-previews-test", engine: "comfyui", model: "krea2-realism", variant: "lean-json" });
++ expect(m["effect-set-on-fire"]).toEqual({ poster: "/previews/presets/effect-set-on-fire.jpg", video: "/previews/presets/effect-set-on-fire.mp4", run: "comfyui-previews-test", engine: "comfyui", model: "minimax-h3", variant: "lean-json" });
++ // Still: at most 768 px; clip: at most 512 px and 4 s, no audio.
++ const probe = (f: string) => JSON.parse(spawnSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,width,height:format=duration", "-of", "json", path.join(out, f)], { encoding: "utf8" }).stdout);
++ const s = probe("app-headshot-generator.jpg").streams[0];
++ expect(Math.max(s.width, s.height)).toBeLessThanOrEqual(768);
++ // 4:2:0, not the 4:4:4 a PNG source would give: about a third smaller.
++ const pix = spawnSync("ffprobe", ["-v", "error", "-show_entries", "stream=pix_fmt", "-of", "csv=p=0", path.join(out, "app-headshot-generator.jpg")], { encoding: "utf8" }).stdout.trim();
++ expect(pix).toBe("yuvj420p");
++ const v = probe("effect-set-on-fire.mp4");
++ expect(v.streams.map((x: { codec_type: string }) => x.codec_type)).toEqual(["video"]);
++ expect(Math.max(v.streams[0].width, v.streams[0].height)).toBeLessThanOrEqual(512);
++ expect(Number(v.format.duration)).toBeLessThanOrEqual(4.1);
++
++ // Again: nothing changed, so nothing is encoded; the manifest is the same.
++ const before = fs.readFileSync(manifest, "utf8");
++ const again = coversFromMasters(masters, { ...PROVENANCE, publicDir: pub, manifest });
++ expect(again.covers.every((c) => c.kept)).toBe(true);
++ expect(fs.readFileSync(manifest, "utf8")).toBe(before);
++
++ // A preset whose clip goes away becomes a still cover and loses its old clip; --only touches just that id.
++ fs.rmSync(path.join(masters, "effect-set-on-fire", "clip.mp4"));
++ fs.copyFileSync(still(), path.join(masters, "effect-set-on-fire", "start.png"));
++ const only = coversFromMasters(masters, { ...PROVENANCE, publicDir: pub, manifest, only: ["effect-set-on-fire"] });
++ expect(only.covers.map((c) => c.key)).toEqual(["effect-set-on-fire"]);
++ expect(readManifest(manifest)["effect-set-on-fire"]).toEqual({ poster: "/previews/presets/effect-set-on-fire.jpg", run: "comfyui-previews-test", engine: "comfyui", model: "ideogram4", variant: "lean-json" });
++ expect(fs.existsSync(path.join(out, "effect-set-on-fire.mp4"))).toBe(false);
++ expect(readManifest(manifest)["effect-thunder-god"]).toEqual(measured);
++
++ // A master for a preset whose cover a measured run made: kept, and listed, unless --replace.
++ const dop = path.join(pub, "previews", "dop");
++ fs.mkdirSync(dop, { recursive: true });
++ for (const ext of ["jpg", "mp4"]) fs.writeFileSync(path.join(dop, `effect-thunder-god.${ext}`), "x");
++ master(masters, "effect-thunder-god", { "start.png": still() });
++ const held = coversFromMasters(masters, { ...PROVENANCE, publicDir: pub, manifest, only: ["effect-thunder-god"] });
++ expect(held.covers).toEqual([]);
++ expect(held.skipped).toEqual([{ id: "effect-thunder-god", why: "its cover is r1's (/previews/dop/effect-thunder-god.jpg): --replace takes it over" }]);
++ expect(readManifest(manifest)["effect-thunder-god"]).toEqual(measured);
++ const replaced = coversFromMasters(masters, { ...PROVENANCE, publicDir: pub, manifest, only: ["effect-thunder-god"], replace: true });
++ expect(replaced.covers.map((c) => c.key)).toEqual(["effect-thunder-god"]);
++ expect(readManifest(manifest)["effect-thunder-god"]).toMatchObject({ poster: "/previews/presets/effect-thunder-god.jpg", run: "comfyui-previews-test" });
++ expect(fs.readdirSync(dop)).toEqual([]);
++ });
++
++ it("reads a missing manifest as empty, and stops at one it can't read rather than write over it", () => {
++ expect(readManifest(path.join(dir, "no-such-manifest.ts"))).toEqual({});
++ const broken = path.join(dir, "broken-manifest.ts");
++ fs.writeFileSync(broken, 'export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = {\n "app-x": { "poster": ');
++ expect(() => readManifest(broken)).toThrow(/isn't a covers manifest/);
++ const masters = path.join(dir, "masters-broken");
++ master(masters, "app-headshot-generator", { "start.png": path.join(SAMPLES, "previews", "portrait.svg") });
++ expect(() => coversFromMasters(masters, { ...PROVENANCE, dryRun: true, manifest: broken })).toThrow(/isn't a covers manifest/);
++ });
++
++ it("makes a clip loop without a jump: its last frames fade into its first, which it then starts after (unless it loops already)", () => {
++ const frames = Array.from({ length: 20 }, (_, i) => Buffer.from([i * 10, i * 10]));
++ const out = seamless(frames, 4);
++ expect(out).toHaveLength(16);
++ // It starts at the 5th frame; the last four are blended from the old end towards the first four.
++ expect(out[0]).toEqual(frames[4]);
++ expect(out.slice(12).map((b) => b[0])).toEqual([128, 106, 84, 62]);
++ // So looping (last frame back to the first) is a step like those of the fade, not the plain clip's jump from 190 to 0.
++ const steps = out.map((b, i) => Math.abs(b[0] - out[(i + 1) % out.length][0]));
++ expect(Math.max(...steps)).toBe(22);
++ expect(seamless(frames, 0)).toBe(frames);
++ // A clip that ends where it starts (an orbit holding the same picture) loops already: it is cut, not crossfaded.
++ const orbit = [100, 100, 100, 110, 120, 130, 140, 130, 120, 110, 100, 100, 100].map((v) => Buffer.alloc(8, v));
++ expect(loopsAlready(orbit, 8)).toBe(true);
++ expect(loopsAlready(frames, 2)).toBe(false);
++ });
++});
diff --cc tests/licences.test.ts
index 00000000,374772cb..a13c351c
mode 000000,100644..100644
--- a/tests/licences.test.ts
+++ b/tests/licences.test.ts
@@@ -1,0 -1,86 +1,86 @@@
+ import fs from "node:fs";
+ import path from "node:path";
+ import { describe, expect, it } from "vitest";
+ import { MODELS } from "@/lib/catalog";
+ import type { Manifest } from "@/lib/comfy";
+ import { buildLicenceList, kindLabel, licenceTerms, UNKNOWN_LICENCE, workflowLicence } from "@/lib/licences";
+
+ /** The About & licences page (R4-53): every open model's licence, its catches and notices. */
+
+ const manifest = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows", "comfyui", "manifest.json"), "utf8")) as Manifest;
+ const wf = (id: string) => manifest.workflows.find((w) => w.id === id) ?? { id };
+ const terms = (id: string) => licenceTerms(workflowLicence(wf(id)));
+
+ describe("licences", () => {
+ it("knows the licence of every workflow in the library", () => {
+ const unknown = manifest.workflows.filter((w) => workflowLicence(w) === UNKNOWN_LICENCE).map((w) => w.id);
+ expect(unknown).toEqual([]);
+ });
+
+ it("flags non-commercial weights and code, but not a variant Fuobe keeps away from", () => {
+ for (const id of ["v2a-mmaudio", "style-ref-uso-flux1", "captions-whisper-burnin", "flux1-dev-t2i", "flux2-dev-t2i", "face-swap-reactor", "flux1-kontext-dev-edit"]) {
+ expect(terms(id).flags, id).toContain("non-commercial");
+ }
+ // "DA3-LARGE / GIANT are CC-BY-NC, do not swap them in": the graph uses the Apache-2.0 one.
+ for (const id of ["video-depth-da3", "video-depth-vda-small", "bg-remove-rmbg", "z-image-turbo-t2i", "wan22-t2v-14b"]) {
+ expect(terms(id).flags, id).not.toContain("non-commercial");
+ }
+ });
+
+ it("reads every capitalised or leading NC mention in the manifest as non-commercial", () => {
+ // Any other lower-case mention must name a variant the graph doesn't use; list it here when one is added.
+ const variants = new Set(["video-depth-da3", "video-depth-vda-small", "bg-remove-rmbg"]);
+ for (const w of manifest.workflows) {
+ const text = workflowLicence(w);
+ if (!/non-commercial|CC-BY-NC/i.test(text) || variants.has(w.id)) continue;
+ expect(licenceTerms(text).flags, w.id).toContain("non-commercial");
+ }
+ });
+
+ it("names the countries a licence leaves out, and the conditions of community licences", () => {
+ expect(terms("hunyuan15-t2v-720p")).toMatchObject({ flags: ["territory"], excludes: "the EU, UK and South Korea" });
+ expect(terms("sfx-hunyuan-foley").flags).toEqual(["territory"]);
+ for (const id of ["ltx25-t2v", "style-ref-krea2", "sfx-stable-audio-3-small", "tts-indextts2", "sdxl-t2i"]) expect(terms(id).flags, id).toEqual(["conditions"]);
+ expect(terms("bg-remove-birefnet").flags).toEqual([]);
+ expect(terms("video-trim")).toMatchObject({ flags: [], noWeights: true });
+ });
+
+ it("finds the notices a licence asks the app to show", () => {
+ expect(terms("image-to-splat-triposplat").notices).toEqual(["Built with DINOv3"]);
+ expect(terms("hidream-i1-dev-t2i").notices).toEqual(["Built with Llama"]);
+ expect(licenceTerms('MIT; the app must show a "Built with X" notice').notices).toEqual(["Built with X"]);
+ });
+
+ it("lists every open catalog model once, in or out of the weights list", () => {
+ const list = buildLicenceList(MODELS, manifest.workflows);
+ const open = MODELS.filter((m) => m.routes.some((r) => r.provider === "comfyui") && !m.id.startsWith("oss-selftest"));
+ const listed = new Set([...list.rows.filter((r) => r.inCatalog).map((r) => r.name), ...list.noWeights]);
+ for (const m of open) expect(listed.has(m.name), m.id).toBe(true);
+ expect(list.rows.find((r) => r.id === "oss-flux2-dev")).toMatchObject({ workflows: ["flux2-dev-t2i", "flux2-dev-multiref"], flags: ["non-commercial"] });
+ // Join clips names a family of workflows (video-concat-{n}); none of them has weights.
+ expect(list.noWeights).toContain("Join clips");
+ // Library workflows without weights are only counted (their titles are long descriptions).
+ expect(list.noWeights.every((n) => MODELS.some((m) => m.name === n))).toBe(true);
+ expect(list.noWeightsLibrary).toBeGreaterThan(0);
+ expect(list.rows.some((r) => r.id.startsWith("selftest"))).toBe(false);
+ // Workflows no studio uses yet are listed after the catalog's models.
+ const firstLibrary = list.rows.findIndex((r) => !r.inCatalog);
+ expect(list.rows.slice(firstLibrary).every((r) => !r.inCatalog)).toBe(true);
+ expect(list.counts.all).toBe(list.rows.length);
+ expect(list.counts.clear + list.counts["non-commercial"] + list.counts.territory + list.counts.conditions).toBeGreaterThanOrEqual(list.rows.length);
+ });
+
+ it("names kinds and capabilities in words", () => {
+ expect([kindLabel("model3d"), kindLabel("scene-3d"), kindLabel("ocr"), kindLabel("remove-object")]).toEqual(["3D", "Scene 3D", "OCR", "Remove object"]);
+ });
+
+ it("collects notices with the models that need them", () => {
+ const list = buildLicenceList(MODELS, manifest.workflows);
+ expect(list.notices.find((n) => n.text === "Built with Llama")?.models).toEqual(["HiDream-I1 Dev"]);
+ expect(list.notices.find((n) => n.text === "Built with DINOv3")?.models.length).toBeGreaterThan(0);
- // TripoSplat and TRELLIS.2 (single and multi-view) encode with DINOv3; without them, no notice.
- expect(list.notices.find((n) => n.text === "Built with DINOv3")?.models).toEqual(expect.arrayContaining(["TripoSplat", "TRELLIS.2", "TRELLIS.2 Multi-view"]));
- const without = buildLicenceList(MODELS, manifest.workflows.filter((w) => !/triposplat|trellis2/.test(w.id)));
++ // TripoSplat, Pixal3D and TRELLIS.2 (single and multi-view) encode with DINOv3; without them, no notice.
++ expect(list.notices.find((n) => n.text === "Built with DINOv3")?.models).toEqual(expect.arrayContaining(["TripoSplat", "Pixal3D", "TRELLIS.2", "TRELLIS.2 Multi-view"]));
++ const without = buildLicenceList(MODELS, manifest.workflows.filter((w) => !/triposplat|trellis2|pixal3d/.test(w.id)));
+ expect(without.notices.some((n) => n.text === "Built with DINOv3")).toBe(false);
+ });
+ });
diff --cc tests/local-llm.test.ts
index f85e16d3,00000000..ff11ca27
mode 100644,000000..100644
--- a/tests/local-llm.test.ts
+++ b/tests/local-llm.test.ts
@@@ -1,748 -1,0 +1,822 @@@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type Anthropic from "@anthropic-ai/sdk";
+import type { Generation } from "@/lib/catalog/types";
+
+/*
+ * Local LLM servers besides Ollama: LM Studio, Unsloth Studio and any OpenAI-compatible server
+ * (llama.cpp's llama-server here). The wire builders and parsers are tested on their own; then
+ * stand-in servers on this machine answer Fuobe's real code paths (Enhance, a storyboard split, a
+ * text step, an Assist chat with a tool call, /api/status and /api/llm).
+ */
+
+vi.setConfig({ testTimeout: 60_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-local-llm-"));
+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";
+// Keys from this machine's environment must not reach the stand-ins.
+for (const k of ["LM_API_TOKEN", "LMSTUDIO_API_TOKEN", "UNSLOTH_API_KEY", "UNSLOTH_STUDIO_AUTH_TOKEN", "FUOBE_LLM_URL", "FUOBE_LLM_API_KEY", "FUOBE_LLM_PROVIDER", "FUOBE_ENHANCE_PROVIDER"]) delete process.env[k];
+
+const { parseContext, publicSettings, setSetting, validateSetting } = await import("@/server/settings");
+const local = await import("@/server/llm");
+const wire = await import("@/server/llm/wire");
+const messages = await import("@/server/llm/messages");
+const { interpret } = await import("@/server/llm/probe");
+const { httpError, rejectsJson } = await import("@/server/llm/errors");
+const llm = await import("@/server/providers/llm");
+const gens = await import("@/server/generations");
+const { enhancePrompt, llmText } = await import("@/server/enhance");
+const { splitStory } = await import("@/server/storyboard");
+const agent = await import("@/server/assist/agent");
+
+type Body = Record<string, unknown> & { messages?: { role: string; content: string | null; tool_calls?: { id: string; type: string; function: { name: string; arguments: string } }[]; tool_call_id?: string }[] };
+interface Seen {
+ method: string;
+ url: string;
+ auth?: string;
+ body: Body;
+}
+
+/** A stand-in HTTP server on a free port: `handle` answers each request (JSON), every request is kept in `seen`. */
+function stub(handle: (r: Seen, res: http.ServerResponse) => unknown) {
+ const seen: Seen[] = [];
+ const server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", async () => {
+ const r: Seen = { method: req.method ?? "GET", url: req.url ?? "/", auth: req.headers.authorization, body: raw ? (JSON.parse(raw) as Body) : {} };
+ seen.push(r);
+ const out = await handle(r, res);
+ if (out === undefined || res.writableEnded) return;
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify(out));
+ });
+ });
+ const s = {
+ seen,
+ url: "",
+ chats: () => seen.filter((r) => r.url.endsWith("/chat/completions") || r.url === "/api/chat").map((r) => r.body),
+ start: () => new Promise<void>((done) => server.listen(0, "127.0.0.1", () => ((s.url = `http://127.0.0.1:${(server.address() as { port: number }).port}`), done()))),
+ close: () => server.close(),
+ };
+ return s;
+}
+
+const fail = (res: http.ServerResponse, status: number, body: unknown) => {
+ res.statusCode = status;
+ return body;
+};
+
+/** An OpenAI chat.completion with one choice. */
+const completion = (message: Record<string, unknown>, finish = "stop", model = "qwen/qwen3-8b") =>
+ ({
+ id: "chatcmpl-1",
+ object: "chat.completion",
+ model,
+ choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
+ }) as unknown as Parameters<typeof wire.parseOpenai>[0];
+
+const lastUser = (b: Body) => (b.messages ?? []).filter((m) => m.role === "user").at(-1)?.content ?? "";
+const systemOf = (b: Body) => (b.messages?.[0]?.role === "system" ? (b.messages[0].content ?? "") : "");
+
+/** "[1] Hello" lines back as "[1] (lang) Hello", like the stand-in Ollama in llm.test.ts. */
+function translate(b: Body, tag: string): string {
+ const lang = /into (\w+)/.exec(systemOf(b))?.[1] ?? "??";
+ const user = lastUser(b);
+ return /^\[\d+\]/.test(user)
+ ? user
+ .split("\n")
+ .map((l) => l.replace(/^\[(\d+)\]\s*/, (_, n) => `[${n}] (${lang}·${tag}) `))
+ .join("\n")
+ : `(${lang}·${tag}) ${user}`;
+}
+
+/**
+ * A stand-in LM Studio 0.4: its own model list (one LLM trained for tool use, one embedding model),
+ * load and unload, the OpenAI model list and chat completions with tools, JSON schemas and thinking.
+ */
+function lmStudio(opts: { token?: string; loaded?: number } = {}) {
+ const state = { context: opts.loaded ?? null as number | null, loads: [] as Body[], unloads: [] as Body[], aborted: 0 };
+ const s = stub((r, res) => {
+ if (opts.token && r.auth !== `Bearer ${opts.token}`) return fail(res, 401, { error: "Unauthorized: this server requires an API token" });
+ if (r.url === "/api/v1/models") {
+ return {
+ models: [
+ {
+ type: "llm",
+ publisher: "qwen",
+ key: "qwen/qwen3-8b",
+ display_name: "Qwen3 8B",
+ loaded_instances: state.context ? [{ id: "qwen/qwen3-8b", config: { context_length: state.context } }] : [],
+ max_context_length: 32768,
+ format: "gguf",
+ capabilities: { vision: false, trained_for_tool_use: true },
+ },
+ { type: "embedding", publisher: "nomic-ai", key: "text-embedding-nomic-embed-text-v1.5", loaded_instances: [], max_context_length: 2048, format: "gguf" },
+ ],
+ };
+ }
+ if (r.url === "/v1/models") return { object: "list", data: [{ id: "qwen/qwen3-8b" }, { id: "text-embedding-nomic-embed-text-v1.5" }] };
+ if (r.url === "/api/v1/models/load") {
+ state.loads.push(r.body);
+ state.context = r.body.context_length as number;
+ return { type: "llm", instance_id: r.body.model, load_time_seconds: 2.5, status: "loaded", load_config: { context_length: r.body.context_length } };
+ }
+ if (r.url === "/api/v1/models/unload") {
+ state.unloads.push(r.body);
+ state.context = null;
+ return { instance_id: r.body.instance_id };
+ }
+ if (r.url !== "/v1/chat/completions") return fail(res, 404, { error: "Unexpected endpoint" });
+ const b = r.body;
+ const user = lastUser(b);
+ if (user.includes("OVERFLOW")) {
+ return fail(res, 400, { error: "Trying to keep the first 9000 tokens when context the overflows. However, the model is loaded with context length of only 4096 tokens, which is not enough. Try to load the model with a larger context length" });
+ }
+ if (user.includes("THINK FOREVER")) return completion({ content: "", reasoning_content: "Let me think about this for a very long time…" }, "length");
+ if (user.includes("SLOW")) {
+ res.on("close", () => !res.writableEnded && state.aborted++);
+ return undefined;
+ }
+ if (b.tools) {
+ // Assist: look up models first, answer once the tool's result is back.
+ if (!b.messages?.some((m) => m.role === "tool")) {
+ return completion({ content: "Let me look.", tool_calls: [{ id: "call_8f2", type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } }] }, "tool_calls");
+ }
+ return completion({ content: "Nano Banana Pro is a great pick.", reasoning_content: "The search found it." });
+ }
+ const format = b.response_format as { json_schema?: { name?: string; schema?: { minItems?: number } } } | undefined;
+ if (format?.json_schema?.name === "frames") {
+ const n = format.json_schema.schema?.minItems ?? 1;
+ return completion({ content: JSON.stringify(Array.from({ length: n }, (_, i) => `Frame ${i + 1}: the fox crosses the snowfield, wide shot, dusk light`)) });
+ }
+ if (systemOf(b).startsWith("You rewrite short creative ideas")) {
+ return completion({ content: "<think>Add light and lens.</think>A red fox trotting through deep snow at golden hour, low angle, 85mm lens, soft rim light.", reasoning_content: "hidden" });
+ }
+ return completion({ content: translate(b, "lms") });
+ });
+ return Object.assign(s, { state });
+}
+
+/** A stand-in Unsloth Studio: liveness without a key, everything under /v1 with one. */
+function unslothStudio(key = "sk-unsloth-test") {
+ return stub((r, res) => {
+ if (r.url === "/api/liveness") return { status: "alive", service: "Unsloth UI Backend", desktop_protocol_version: 1 };
+ if (r.auth !== `Bearer ${key}`) return fail(res, 401, { error: { message: "Invalid or missing API key", type: "invalid_request_error", code: "invalid_api_key" } });
+ if (r.url === "/v1/models") {
+ return {
+ object: "list",
+ data: [
+ { id: "unsloth/Qwen3-8B-GGUF", object: "model", owned_by: "unsloth", loaded: true, context_length: 16384, status: { value: "loaded" } },
+ { id: "unsloth/gemma-3-12b-it-GGUF", object: "model", owned_by: "unsloth", loaded: false, status: { value: "unloaded" } },
+ { id: "unsloth/orpheus-3b-0.1-ft-GGUF", object: "model", task: "text-to-speech", loaded: false },
+ ],
+ };
+ }
+ if (r.url === "/v1/chat/completions") return completion({ content: translate(r.body, "unsloth"), reasoning_content: null }, "stop", "unsloth/Qwen3-8B-GGUF");
+ return fail(res, 404, { detail: "Not Found" });
+ });
+}
+
+/** A stand-in llama-server: one model, and no structured output. */
+function llamaServer() {
+ return stub((r, res) => {
+ if (r.url === "/v1/models") return { object: "list", data: [{ id: "gemma-3-4b-it-Q4_K_M.gguf", object: "model", owned_by: "llamacpp" }] };
+ if (r.url !== "/v1/chat/completions") return fail(res, 404, { error: { code: 404, message: "File Not Found", type: "not_found_error" } });
+ if (r.body.response_format) return fail(res, 400, { error: { code: 400, message: "Unsupported response_format: json_schema", type: "invalid_request_error" } });
+ return completion({ content: '```json\n{"reply": "Sure — four ads coming up.", "make": null}\n```' }, "stop", "gemma-3-4b-it-Q4_K_M.gguf");
+ });
+}
+
+/** A stand-in Ollama (its own API), for the order Automatic picks servers in. */
+function ollama(models = [{ name: "qwen3:8b" }]) {
+ return stub((r) => (r.url === "/api/tags" ? { models } : { model: "qwen3:8b", message: { role: "assistant", content: "(ollama) ok" }, done_reason: "stop" }));
+}
+
+const servers: { close: () => void }[] = [];
+async function started<T extends { start: () => Promise<void>; close: () => void }>(s: T): Promise<T> {
+ await s.start();
+ servers.push(s);
+ return s;
+}
+
+async function settle(id: string, ms = 30_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+const SETTINGS = ["llmProvider", "lmstudioUrl", "lmstudioModel", "lmstudioToken", "unslothUrl", "unslothModel", "unslothKey", "llmUrl", "llmModel", "llmKey", "llmContext", "enhanceProvider", "anthropicKey", "engineMode"] as const;
+
+beforeAll(() => setSetting("demoMode", "off"));
+beforeEach(() => {
+ for (const k of SETTINGS) setSetting(k, "");
+ setSetting("ollamaUrl", "");
+});
+afterAll(() => {
+ for (const s of servers) s.close();
+ // Windows keeps the open SQLite file locked until the worker exits.
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+// ---------------------------------------------------------------------------
+
+describe("the OpenAI wire", () => {
+ const tools = [{ name: "search_models", description: "Find models", parameters: { type: "object", properties: { kind: { type: "string" } } } }];
+
+ it("sends tools, tool calls with string arguments and tool results with their call's id", () => {
+ const body = wire.openaiBody(
+ "lmstudio",
+ {
+ messages: [
+ { role: "system", content: "sys" },
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "", toolCalls: [{ id: "Ab3dE5gH9", name: "search_models", input: { kind: "image" } }] },
+ { role: "tool", toolCallId: "Ab3dE5gH9", toolName: "search_models", content: '{"models":[]}' },
+ ],
+ tools,
+ timeoutMs: 1,
+ },
+ "qwen/qwen3-8b",
+ );
+ expect(body).toMatchObject({ model: "qwen/qwen3-8b", stream: false, tool_choice: "auto", tools: [{ type: "function", function: { name: "search_models", description: "Find models", parameters: tools[0].parameters } }] });
+ const msgs = body.messages as Record<string, unknown>[];
+ expect(msgs[2]).toEqual({ role: "assistant", content: null, tool_calls: [{ id: "Ab3dE5gH9", type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } }] });
+ expect(msgs[3]).toEqual({ role: "tool", tool_call_id: "Ab3dE5gH9", content: '{"models":[]}' });
+ // Nothing a server doesn't need: no JSON format, no token cap, no Unsloth extras.
+ expect(body).not.toHaveProperty("response_format");
+ expect(body).not.toHaveProperty("max_tokens");
+ expect(body).not.toHaveProperty("enable_tools");
+ });
+
+ it("asks each server for JSON the way it understands, and keeps Unsloth's server-side tools off", () => {
+ const schema = { name: "ads", schema: { type: "object", properties: { ads: { type: "array" } } } };
+ const req = { messages: [{ role: "user" as const, content: "x" }], json: schema, think: false, timeoutMs: 1 };
+ expect(wire.openaiBody("lmstudio", req, "m").response_format).toEqual({ type: "json_schema", json_schema: { name: "ads", schema: schema.schema } });
+ expect(wire.openaiBody("unsloth", req, null).response_format).toEqual({ type: "json_schema", json_schema: { name: "ads", strict: true, schema: schema.schema } });
+ expect(wire.responseFormat("lmstudio", "object")).toEqual({ type: "json_schema", json_schema: { name: "answer", schema: { type: "object" } } });
+ expect(wire.responseFormat("custom", "object")).toEqual({ type: "json_object" });
+ // A server that can't do it: the same call without.
+ expect(wire.openaiBody("custom", req, "m", false)).not.toHaveProperty("response_format");
+ // Unsloth: the loaded model answers (no model named), thinking off for one-shot text, server-side tools always off.
+ const unsloth = wire.openaiBody("unsloth", req, null);
+ expect(unsloth).not.toHaveProperty("model");
+ expect(unsloth).toMatchObject({ enable_tools: false, enable_thinking: false });
+ expect(wire.openaiBody("unsloth", { ...req, think: undefined }, null)).toMatchObject({ enable_tools: false });
+ expect(wire.openaiBody("unsloth", { ...req, think: undefined }, null)).not.toHaveProperty("enable_thinking");
+ });
+
+ it("reads answers: thinking dropped, tool calls parsed, the stop reason mapped", () => {
+ const a = wire.parseOpenai(completion({ content: "<think>plan</think>Done.", reasoning_content: "more" }), "m");
+ expect(a).toMatchObject({ text: "Done.", toolCalls: [], stop: "end", thought: true, model: "qwen/qwen3-8b" });
+ const b = wire.parseOpenai(
+ completion({ content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "generate", arguments: '{"summary":"x"}' } }, { id: "2", function: { name: "generate", arguments: "{jobs: [" } }] }, "tool_calls"),
+ "m",
+ );
+ expect(b.stop).toBe("tool_use");
+ expect(b.toolCalls.map((c) => c.input)).toEqual([{ summary: "x" }, { INVALID_JSON: "{jobs: [" }]);
+ // Fuobe's own ids, nine letters and digits (strict templates want them; Claude accepts them).
+ expect(b.toolCalls.every((c) => /^[A-Za-z0-9]{9}$/.test(c.id))).toBe(true);
+ expect(wire.parseOpenai(completion({ content: "", reasoning_content: "hmm" }, "length"), "m")).toMatchObject({ text: "", stop: "length", thought: true });
+ // A template that opened <think> in the prompt leaves only the closing tag; a cut-off thought leaves nothing.
+ expect(wire.stripThink("weighing options</think>\n\nThe answer.")).toBe("The answer.");
+ expect(wire.stripThink("Answer first.<think>and then a thought that never")).toBe("Answer first.");
+ });
+
+ it("keeps Ollama's own wire: num_ctx, think, a schema as `format`, tool names on results", () => {
+ const body = wire.ollamaBody(
+ {
+ messages: [
+ { role: "system", content: "s" },
+ { role: "assistant", content: "", toolCalls: [{ id: "x", name: "search_models", input: { kind: "image" } }] },
+ { role: "tool", toolName: "search_models", content: "{}" },
+ ],
+ json: { name: "t", schema: { type: "object" } },
+ think: false,
+ timeoutMs: 1,
+ },
+ "qwen3:8b",
+ 16384,
+ );
+ expect(body).toMatchObject({ model: "qwen3:8b", stream: false, think: false, format: { type: "object" }, options: { num_ctx: 16384 } });
+ expect((body.messages as Record<string, unknown>[])[1]).toEqual({ role: "assistant", content: "", tool_calls: [{ function: { name: "search_models", arguments: { kind: "image" } } }] });
+ expect((body.messages as Record<string, unknown>[])[2]).toEqual({ role: "tool", content: "{}", tool_name: "search_models" });
+ expect(wire.ollamaBody({ messages: [], json: "object", timeoutMs: 1 }, "m", 0)).toMatchObject({ format: "json" });
+ expect(wire.ollamaBody({ messages: [], timeoutMs: 1 }, "m", 0)).not.toHaveProperty("options");
+ const r = wire.parseOllama({ message: { content: "<think>x</think>Hi", tool_calls: [{ function: { name: "generate", arguments: { a: 1 } } }] }, done_reason: "stop" }, "qwen3:8b");
+ expect(r).toMatchObject({ text: "Hi", stop: "tool_use", toolCalls: [{ name: "generate", input: { a: 1 } }] });
+ });
+});
+
+describe("Assist history for strict chat templates", () => {
+ type Param = Anthropic.Beta.BetaMessageParam;
+ const system = { stable: "You are Fuobe Assist.", turn: "Today is Friday." };
+ const history = [
+ { role: "user", content: [{ type: "text", text: "Make a fox." }, { type: "image", source: { type: "url", url: "/api/files/a.png" } }] },
+ { role: "assistant", content: [{ type: "thinking", thinking: "…", signature: "s" }, { type: "text", text: "Looking." }, { type: "tool_use", id: "toolu_01AbCdEfGhIjKlMnOp", name: "search_models", input: { kind: "image" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01AbCdEfGhIjKlMnOp", content: [{ type: "text", text: '{"models":[]}' }, { type: "image", source: { type: "base64", media_type: "image/png", data: "AA" } }] }] },
+ { role: "system", content: "Context update: auto-run is on." },
+ { role: "assistant", content: [{ type: "tool_use", id: "toolu_02", name: "generate", input: { summary: "x" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_02", is_error: true, content: "Invalid input: jobs" }, { type: "text", text: "Try again." }] },
+ { role: "system", content: "Context update: a memory was saved." },
+ ] as unknown as Param[];
+
+ it("has one system message, folds context updates into user turns and keeps call ids matched", () => {
+ const out = messages.toChatMessages(system, history, "lmstudio");
+ expect(out.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool", "user", "assistant", "tool", "user"]);
+ expect(out.filter((m) => m.role === "system")).toHaveLength(1);
+ expect(out[0].content).toBe("You are Fuobe Assist.\n\nToday is Friday.");
+ // Images stay out (the user's text lists their URLs); a tool's image reads as a note.
+ expect(out[1].content).toBe("Make a fox.");
+ expect(out[3].content).toBe('{"models":[]}\n[image omitted]');
+ // After tool results, the update is a user turn of its own; after the user's words, it joins them.
+ expect(out[4].content).toBe(`${messages.CONTEXT_UPDATE_LABEL}\nContext update: auto-run is on.`);
+ expect(out[6]).toMatchObject({ role: "tool", content: "Error: Invalid input: jobs" });
+ expect(out[7].content).toBe(`Try again.\n\n${messages.CONTEXT_UPDATE_LABEL}\nContext update: a memory was saved.`);
+ // Thinking dropped; nine-character ids, the same on the call and its result, and stable.
+ expect(out[2]).toMatchObject({ content: "Looking.", toolCalls: [{ name: "search_models", input: { kind: "image" } }] });
+ const id = out[2].toolCalls![0].id;
+ expect(id).toMatch(/^[A-Za-z0-9]{9}$/);
+ expect(out[3].toolCallId).toBe(id);
+ expect(messages.wireId("toolu_01AbCdEfGhIjKlMnOp")).toBe(id);
+ expect(out[5].toolCalls![0].id).toBe(out[6].toolCallId);
+ expect(messages.wireId("Ab3dE5gH9")).toBe("Ab3dE5gH9");
+ });
+
+ it("gives Ollama the history as before: system context updates, tool names on results", () => {
+ const out = messages.toChatMessages(system, history, "ollama");
+ expect(out.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool", "system", "assistant", "tool", "user", "system"]);
+ expect(out[3]).toMatchObject({ toolName: "search_models", toolCallId: "toolu_01AbCdEfGhIjKlMnOp" });
+ });
+
+ it("reads tool calls a model wrote as text, for the offered tools only", () => {
+ const names = new Set(["search_models", "generate"]);
+ const hermes = messages.healToolCalls('Sure.\n<tool_call>\n{"name": "search_models", "arguments": {"kind": "video"}}\n</tool_call>', names);
+ expect(hermes).toMatchObject({ text: "Sure.", calls: [{ name: "search_models", input: { kind: "video" } }] });
+ const lms = messages.healToolCalls('[TOOL_REQUEST]{"name": "generate", "arguments": {"summary": "fox"}}[END_TOOL_REQUEST]', names);
+ expect(lms).toMatchObject({ text: "", calls: [{ name: "generate", input: { summary: "fox" } }] });
+ // Llama 3 writes "parameters"; a fenced reply that is only the call counts too.
+ expect(messages.healToolCalls('```json\n{"name": "search_models", "parameters": {"kind": "audio"}}\n```', names).calls).toMatchObject([{ input: { kind: "audio" } }]);
+ // Not a tool we offered, or not a call at all: the text stays.
+ expect(messages.healToolCalls('<tool_call>{"name": "rm", "arguments": {}}</tool_call>', names)).toMatchObject({ calls: [], text: '<tool_call>{"name": "rm", "arguments": {}}</tool_call>' });
+ expect(messages.healToolCalls('{"name": "Fox", "colour": "red"}', names).calls).toEqual([]);
+ });
+});
+
+describe("reading a server's answers", () => {
+ const server = (kind: "ollama" | "lmstudio" | "unsloth" | "custom", over: Partial<{ url: string; model: string; key: string }> = {}) => ({ kind, label: local.LOCAL_LABELS[kind], url: "http://127.0.0.1:1234", model: "", key: "", ...over });
+
+ it("LM Studio: chat models only, a loaded one first, warnings for a small context, problems that say what to do", () => {
+ const models = (loaded: number | null, extra: unknown[] = []) => ({
+ native: {
+ status: 200,
+ body: {
+ models: [
+ { type: "embedding", key: "nomic-embed", loaded_instances: [{ id: "nomic-embed", config: { context_length: 2048 } }] },
+ { type: "llm", key: "google/gemma-3-12b", loaded_instances: [], max_context_length: 131072, capabilities: { trained_for_tool_use: false } },
+ { type: "llm", key: "qwen/qwen3-8b", loaded_instances: loaded ? [{ id: "qwen/qwen3-8b", config: { context_length: loaded } }] : [], max_context_length: 40960, capabilities: { trained_for_tool_use: true, reasoning: { allowed_options: ["off", "on"], default: "on" } } },
+ ...extra,
+ ],
+ },
+ },
+ });
+ const ready = interpret(server("lmstudio"), models(16384), 16384, 0);
+ expect(ready).toMatchObject({ up: true, problem: null, model: "qwen/qwen3-8b", loaded: true, context: 16384, native: true });
+ expect(ready.models.map((m) => m.id)).toEqual(["google/gemma-3-12b", "qwen/qwen3-8b"]);
+ expect(ready.warning).toMatch(/thinks before it answers/);
+ // Nothing loaded: the one trained for tool use.
+ expect(interpret(server("lmstudio"), models(null), 16384, 0)).toMatchObject({ model: "qwen/qwen3-8b", loaded: false, problem: null });
+ expect(interpret(server("lmstudio"), models(4096), 16384, 0).warning).toMatch(/loaded with 4,096 tokens of context; Assist and long texts need about 16,384\. Reload it with 16k context/);
+ expect(interpret(server("lmstudio", { model: "mistral/ministral-8b" }), models(null), 16384, 0).problem).toMatch(/LM Studio has no model called mistral\/ministral-8b.*lms get mistral\/ministral-8b/);
+ expect(interpret(server("lmstudio", { model: "qwen/qwen3-8b@q4_k_m" }), models(null), 16384, 0)).toMatchObject({ problem: null, model: "qwen/qwen3-8b@q4_k_m" });
+ expect(interpret(server("lmstudio"), { native: { status: 200, body: { models: [] } } }, 16384, 0).problem).toMatch(/no chat models downloaded yet.*lms get/);
+ expect(interpret(server("lmstudio"), { native: { status: 401, body: {} }, openai: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ up: true, auth: "missing", problem: expect.stringMatching(/Manage Tokens/) });
+ expect(interpret(server("lmstudio", { key: "bad" }), { native: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ auth: "rejected", problem: expect.stringMatching(/rejected the API token/) });
+ expect(interpret(server("lmstudio"), { native: { error: "ECONNREFUSED" }, openai: { error: "ECONNREFUSED" } }, 16384, 0).problem).toBe(
+ "LM Studio isn't running at http://127.0.0.1:1234. Start LM Studio's local server and load a model: in LM Studio, Developer → Start server (or run `lms server start`).",
+ );
+ // Before 0.4: the OpenAI list, embeddings dropped.
+ expect(interpret(server("lmstudio"), { native: { status: 404, body: {} }, openai: { status: 200, body: { data: [{ id: "text-embedding-x" }, { id: "llama-3.2-3b-instruct" }] } } }, 16384, 0)).toMatchObject({ problem: null, native: false, model: "llama-3.2-3b-instruct", loaded: null });
+ });
+
+ it("Unsloth Studio: itself (not Jupyter), its key, a loaded chat model", () => {
+ const live = { status: 200, body: { status: "alive", service: "Unsloth UI Backend" } };
+ const rows = { status: 200, body: { data: [{ id: "unsloth/tts", task: "text-to-speech", loaded: true }, { id: "unsloth/Qwen3-8B-GGUF", loaded: false }] } };
+ expect(interpret(server("unsloth"), { live: { status: 200, body: { status: "ok" } }, openai: rows }, 16384, 0).problem).toMatch(/Something else answers at .*not Unsloth Studio/);
+ expect(interpret(server("unsloth"), { live, openai: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ auth: "missing", problem: expect.stringMatching(/avatar → Settings → API → Create.*sk-unsloth-/) });
+ expect(interpret(server("unsloth", { key: "sk-unsloth-x" }), { live, openai: rows }, 16384, 0)).toMatchObject({ up: true, problem: expect.stringMatching(/no model loaded.*Chat page/) });
+ const loaded = { status: 200, body: { data: [{ id: "unsloth/Qwen3-8B-GGUF", loaded: true, context_length: 8192 }] } };
+ expect(interpret(server("unsloth", { key: "sk-unsloth-x" }), { live, openai: loaded }, 16384, 0)).toMatchObject({ problem: null, model: "unsloth/Qwen3-8B-GGUF", loaded: true, warning: expect.stringMatching(/8,192 tokens.*Load it in Unsloth Studio with a larger context/) });
+ expect(interpret(server("unsloth", { model: "unsloth/Qwen3-8B-GGUF:Q4_K_M" }), { live, openai: loaded }, 16384, 0)).toMatchObject({ problem: null, model: "unsloth/Qwen3-8B-GGUF:Q4_K_M" });
+ });
+
+ it("another OpenAI-compatible server: its URL, its first model; Ollama: up whenever it answers", () => {
+ expect(interpret(server("custom", { url: "" }), {}, 16384, 0).problem).toMatch(/Set the server's URL/);
+ expect(interpret(server("custom"), { openai: { status: 200, body: { data: [{ id: "bge-embed" }, { id: "Qwen3-8B" }] } } }, 16384, 0)).toMatchObject({ problem: null, model: "Qwen3-8B" });
+ expect(interpret(server("custom"), { openai: { status: 200, body: { data: [] } } }, 16384, 0).problem).toMatch(/lists no models/);
+ expect(interpret(server("ollama", { model: "qwen3:8b" }), { tags: { status: 200, body: { models: [] } } }, 16384, 0)).toMatchObject({ up: true, problem: null, model: "qwen3:8b", warning: expect.stringMatching(/ollama pull qwen3:8b/) });
+ });
+
+ it("LM Studio: a display name finds the model and calls use its key; a model's most context ends the reload advice", () => {
+ const native = (loaded: number | null, max: number) => ({
+ native: {
+ status: 200,
+ body: { models: [{ type: "llm", key: "qwen/qwen3-8b", display_name: "Qwen3 8B", loaded_instances: loaded ? [{ id: "qwen/qwen3-8b", config: { context_length: loaded } }] : [], max_context_length: max }] },
+ },
+ });
+ expect(interpret(server("lmstudio", { model: "Qwen3 8B" }), native(null, 40960), 16384, 0)).toMatchObject({ problem: null, model: "qwen/qwen3-8b" });
+ // Loaded at its most (8k): no "Reload with 16k" (it would load 8k again), just what it can hold.
+ const full = interpret(server("lmstudio"), native(8192, 8192), 16384, 0);
+ expect(full.warning).toMatch(/handles only 8,192 tokens of context/);
+ expect(full.warning).not.toMatch(/Reload/);
+ expect(interpret(server("lmstudio"), native(4096, 8192), 16384, 0).warning).toMatch(/loaded with 4,096 tokens.*Reload it with 8k context/);
+ });
+
+ it("reads context sizes as people write them, and finds keys under their other env names", () => {
+ expect(["16384", "16,384", "16 384", "16_384", "16k", "16K"].map(parseContext)).toEqual([16384, 16384, 16384, 16384, 16384, 16384]);
+ expect(parseContext("0")).toBe(0);
+ for (const bad of ["16", "1000", "abc", "-1", ""]) expect(parseContext(bad)).toBeNull();
+ expect(() => validateSetting("llmContext", "16")).toThrow(/at least 2048/);
+ expect(() => validateSetting("llmContext", "16,384")).not.toThrow();
+ setSetting("llmContext", "32k");
+ expect(local.llmContext()).toBe(32768);
+ setSetting("llmContext", "");
+ expect(local.llmContext()).toBe(16384);
+ process.env.LM_API_TOKEN = "lm-alias-token-1234";
+ process.env.UNSLOTH_STUDIO_AUTH_TOKEN = "sk-unsloth-alias-5678";
+ try {
+ const shown = Object.fromEntries(publicSettings().map((s) => [s.name, s]));
+ expect(shown.lmstudioToken).toMatchObject({ isSet: true, fromEnv: true, value: "lm-a••••1234" });
+ expect(shown.unslothKey).toMatchObject({ isSet: true, fromEnv: true, value: "sk-u••••5678" });
+ expect(local.localServer("lmstudio").key).toBe("lm-alias-token-1234");
+ } finally {
+ delete process.env.LM_API_TOKEN;
+ delete process.env.UNSLOTH_STUDIO_AUTH_TOKEN;
+ }
+ });
+
+ it("reads Unsloth Studio's nested error bodies", () => {
+ const uns = server("unsloth");
+ const nested = (message: string, code?: string) => JSON.stringify({ detail: { error: { message, type: "invalid_request_error", ...(code && { code }) } } });
+ expect(httpError(uns, 400, nested("Request has 20000 tokens, more than the 8192 the model was loaded with.", "context_length_exceeded"), null).message).toBe(
+ "This is longer than the model's context on Unsloth Studio. Load it in Unsloth Studio with a larger context, or use shorter text.",
+ );
+ expect(httpError(uns, 400, nested("Too long", "context_length_exceeded"), null).message).toMatch(/^This is longer than the model's context/);
+ expect(httpError(uns, 502, nested("llama-server stopped"), null).message).toBe("Unsloth Studio returned 502: llama-server stopped");
+ expect(httpError(uns, 500, JSON.stringify({ detail: { message: "Backend busy" } }), null).message).toBe("Unsloth Studio returned 500: Backend busy");
+ });
+
+ it("turns failed calls into what to do about them", () => {
+ const lms = server("lmstudio");
+ expect(httpError(lms, 400, JSON.stringify({ error: "Trying to keep the first 9000 tokens when context the overflows. However, the model is loaded with context length of only 4096 tokens" }), "qwen/qwen3-8b").message).toBe(
+ "This is longer than qwen/qwen3-8b's context (4096 tokens) on LM Studio. Reload it with 16k context (Settings → AI helper) or a larger one in LM Studio, or use shorter text.",
+ );
+ expect(httpError(lms, 404, JSON.stringify({ error: { message: "Model 'x/y' not found" } }), "x/y").message).toMatch(/LM Studio has no model called x\/y — download it in LM Studio \(or run `lms get x\/y`\)/);
+ expect(httpError(server("unsloth"), 400, JSON.stringify({ detail: "No model loaded. Load a model first, or enable Model auto-switch (Settings > API)." }), null).message).toMatch(/^Unsloth Studio has no model loaded — load one on its Chat page/);
+ expect(httpError(server("unsloth"), 401, "{}", null).message).toMatch(/^Unsloth Studio needs an API key/);
+ expect(httpError(server("custom"), 500, "boom", "m").message).toBe("Your local server returned 500: boom");
+ expect(httpError(server("ollama"), 404, JSON.stringify({ error: "model 'qwen3:8b' not found" }), "qwen3:8b").message).toBe("Ollama doesn't have qwen3:8b yet — run `ollama pull qwen3:8b`");
+ expect(rejectsJson("custom", 400, "Unsupported response_format: json_schema")).toBe(true);
+ expect(rejectsJson("custom", 500, "model crashed")).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Against stand-in servers, through Fuobe's own code paths
+
+describe("LM Studio", () => {
++ it("checks a typed address and model before Settings saves them (Save & test), and sends pictures as data URLs", async () => {
++ const lms = await started(lmStudio({ loaded: 16384 }));
++ const { POST } = await import("@/app/api/providers/test/route");
++ const check = async (body: unknown) => (await (await POST(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify(body) }))).json()) as { ok: boolean; detail: string };
++ expect(await check({ provider: "llm", values: { lmstudioUrl: lms.url } })).toEqual({ ok: true, detail: "LM Studio · qwen/qwen3-8b ready" });
++ expect(await check({ provider: "llm", values: { lmstudioUrl: lms.url, lmstudioModel: "nope/model" }, field: "lmstudioModel" })).toMatchObject({ ok: false, detail: expect.stringMatching(/^LM Studio has no model called nope\/model/) });
++ // Nothing was saved.
++ expect(local.localServer("lmstudio").url).not.toBe(lms.url);
++ // A picture for a model that can see (Content Factory's frames, Describe my character).
++ setSetting("llmProvider", "lmstudio");
++ setSetting("lmstudioUrl", lms.url);
++ await local.probeLocal(true);
++ await llmText("Describe.", "What is in the picture?", [{ data: Buffer.from("png-bytes"), contentType: "image/png" }]);
++ expect(lms.chats().at(-1)!.messages![1].content).toEqual([
++ { type: "image_url", image_url: { url: `data:image/png;base64,${Buffer.from("png-bytes").toString("base64")}` } },
++ { type: "text", text: "What is in the picture?" },
++ ]);
++ });
++
+ it("runs Enhance on the model it loads with 16k context, once, and drops the thinking", async () => {
+ const lms = await started(lmStudio());
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", `${lms.url}/v1`); // a URL pasted from an example: /v1 is dropped
+ expect(await local.probeLocal(true)).toBe(true);
+ const text = await enhancePrompt("a fox in snow", "image", "t2i");
+ expect(text).toBe("A red fox trotting through deep snow at golden hour, low angle, 85mm lens, soft rim light.");
+ // Not loaded yet: loaded first with the context Assist needs (the chat endpoint can't set it).
+ expect(lms.state.loads).toEqual([{ model: "qwen/qwen3-8b", context_length: 16384, echo_load_config: true }]);
+ const [chat] = lms.chats();
+ expect(chat).toMatchObject({ model: "qwen/qwen3-8b", stream: false, messages: [{ role: "system" }, { role: "user", content: "Rewrite this as a text-to-image prompt:\n\na fox in snow" }] });
+ expect(chat).not.toHaveProperty("tools");
+ expect(lms.seen.every((r) => r.auth === undefined)).toBe(true);
+ // Loaded now: no second load.
+ await enhancePrompt("a cat on a roof", "image", "t2i");
+ expect(lms.state.loads).toHaveLength(1);
+ expect(lms.chats()).toHaveLength(2);
+ });
+
+ it("loads the model once for a whole text step, however many calls it makes", async () => {
+ const lms = await started(lmStudio());
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ // 35 cues: a batch of 30, then one of 5, on a model that isn't loaded when the step starts.
+ const cues = Array.from({ length: 35 }, (_, i) => ({ start: i * 2, end: i * 2 + 1.5, text: `Line ${i + 1}` }));
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: JSON.stringify(cues), params: { targetLanguage: "German" } });
+ const done = await settle(g.id);
+ expect(done.status, done.error ?? "").toBe("succeeded");
+ expect(done.outputs[0].meta?.cues).toEqual(cues.map((c) => ({ ...c, text: `(German·lms) ${c.text}` })));
+ expect(lms.chats()).toHaveLength(2);
+ expect(lms.state.loads).toHaveLength(1);
+ });
+
+ it("splits a storyboard with a JSON schema of exactly n frames", async () => {
+ const lms = await started(lmStudio({ loaded: 32768 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const scenes = await splitStory("A fox crosses a snowfield at dusk and finds its den.", 3);
+ expect(scenes).toHaveLength(3);
+ expect(scenes[0]).toMatch(/^Frame 1: the fox crosses/);
+ expect(lms.chats()[0].response_format).toEqual({ type: "json_schema", json_schema: { name: "frames", schema: { type: "array", items: { type: "string" }, minItems: 3, maxItems: 3 } } });
+ expect(lms.state.loads).toHaveLength(0);
+ });
+
+ it("runs an Assist chat: tools offered, one tool call run, its result sent back under the same id", async () => {
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ expect(await agent.resolveAgent()).toBe("local");
+ const can = await agent.availability();
+ expect(can.local).toEqual({ kind: "lmstudio", label: "LM Studio", ok: true, models: ["qwen/qwen3-8b"], model: "qwen/qwen3-8b" });
+ const t = agent.createThread({ engine: "open", agent: "local" });
+ agent.addMessage(t.id, "Which image model should I use?");
+ await agent.run(t.id);
+ const [first, second] = lms.chats();
+ expect(lms.chats()).toHaveLength(2);
+ expect(first.model).toBe("qwen/qwen3-8b");
+ expect((first.tools as { function: { name: string } }[]).map((x) => x.function.name)).toEqual(expect.arrayContaining(["search_models", "generate"]));
+ expect(first.messages!.map((m) => m.role)).toEqual(["system", "user"]);
+ const sent = second.messages!;
+ expect(sent.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool"]);
+ const call = sent[2].tool_calls![0];
+ expect(call).toMatchObject({ type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } });
+ expect(call.id).toMatch(/^[A-Za-z0-9]{9}$/);
+ expect(sent[3].tool_call_id).toBe(call.id);
+ expect(JSON.parse(sent[3].content!).models.length).toBeGreaterThan(0);
+ const items = agent.getThread(t.id)!.thread.items;
+ expect(items.find((i) => i.role === "assistant")).toMatchObject({ text: "Let me look." });
+ expect(items.at(-1)).toMatchObject({ role: "assistant", text: "Nano Banana Pro is a great pick." });
+ expect(agent.getThread(t.id)!.thread.status).toBe("idle");
+ });
+
+ it("sends its token when Require Authentication is on, and says what to do without one", async () => {
+ const lms = await started(lmStudio({ token: "lms-secret-1234", loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ expect(await local.probeLocal(true)).toBe(false);
+ expect(llm.llmBackends({ endpoint: "ollama", op: "write" })).toEqual([]);
+ expect(llm.llmMissing({ endpoint: "ollama", op: "write" })).toMatch(/^Connect LM Studio in Settings to run this model \(open-source text runs on your own machine\)\. LM Studio wants an API token/);
+ setSetting("lmstudioToken", "lms-secret-1234");
+ expect(await local.probeLocal(true)).toBe(true);
+ expect(await llmText("Reply.", "hello")).toBe("(??·lms) hello");
+ expect(lms.seen.at(-1)!.auth).toBe("Bearer lms-secret-1234");
+ });
+
++ it("keeps each saved token or key with the server it was saved for when Save & test tries a new address", async () => {
++ const saved = await started(lmStudio({ loaded: 16384 }));
++ const other = await started(lmStudio({ loaded: 16384 }));
++ const { POST } = await import("@/app/api/providers/test/route");
++ const check = (body: unknown) => POST(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify(body) }));
++ setSetting("lmstudioUrl", saved.url);
++ setSetting("lmstudioToken", "saved-lmstudio-secret");
++ setSetting("unslothKey", "saved-unsloth-secret");
++ setSetting("llmKey", "saved-cloud-key");
++ // A new address gets no saved secret, whichever server it is for.
++ await check({ provider: "llm", values: { lmstudioUrl: other.url } });
++ await check({ provider: "llm", values: { unslothUrl: other.url } });
++ await check({ provider: "llm", values: { llmUrl: other.url } });
++ expect(other.seen.length).toBeGreaterThan(0);
++ expect(other.seen.filter((r) => r.auth)).toEqual([]);
++ // A key typed with the new address goes to it.
++ await check({ provider: "llm", values: { lmstudioUrl: other.url, lmstudioToken: "typed-token" } });
++ expect(other.seen.at(-1)!.auth).toBe("Bearer typed-token");
++ // The saved server, typed again (with /v1 pasted) or not, still gets its own.
++ await check({ provider: "llm", values: { lmstudioUrl: `${saved.url}/v1` } });
++ expect(saved.seen.at(-1)!.auth).toBe("Bearer saved-lmstudio-secret");
++ expect(local.localServer("lmstudio").key).toBe("saved-lmstudio-secret");
++ });
++
+ it("explains a context overflow and a model that spent its reply thinking; a dead server, how to start it", async () => {
+ const lms = await started(lmStudio({ loaded: 4096 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const ready = (await local.activeLocal())!;
+ expect(ready.status.warning).toMatch(/4,096 tokens of context/);
+ const ask = (content: string) => local.chatLocal(ready, { messages: [{ role: "user", content }], timeoutMs: 10_000 });
+ await expect(ask("OVERFLOW")).rejects.toThrow(/longer than qwen\/qwen3-8b's context \(4096 tokens\) on LM Studio\. Reload it with 16k context/);
+ const r = await ask("THINK FOREVER");
+ expect(r).toMatchObject({ text: "", stop: "length", thought: true });
+ expect(local.emptyReply(ready.server, r).message).toBe("qwen/qwen3-8b on LM Studio spent its whole reply thinking. Turn thinking off for it, or pick a model that doesn't think first.");
+ // The text step says the same instead of "no text".
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "THINK FOREVER" });
+ expect((await settle(g.id)).error).toMatch(/spent its whole reply thinking/);
+ lms.close();
+ await expect(ask("hello")).rejects.toThrow(/^Couldn't reach LM Studio at http:\/\/127\.0\.0\.1:\d+ \(ECONNREFUSED\)\. Start LM Studio's local server and load a model/);
+ });
+
+ it("reloads a model loaded with too little context (Settings → Reload) through /api/llm, without keys in the answers", async () => {
+ const lms = await started(lmStudio({ loaded: 4096 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ setSetting("lmstudioToken", "");
+ const route = await import("@/app/api/llm/route");
+ const before = (await (await route.GET(new Request("http://x/api/llm?refresh=1"))).json()) as { active: string; servers: { kind: string; context: number; warning: string }[] };
+ expect(before.active).toBe("lmstudio");
+ expect(before.servers.map((s) => s.kind)).toEqual(["ollama", "lmstudio", "unsloth", "custom"]);
+ expect(before.servers[1]).toMatchObject({ context: 4096, warning: expect.stringMatching(/Reload it with 16k context/) });
+ const res = (await (await route.POST(new Request("http://x/api/llm", { method: "POST", body: JSON.stringify({ action: "load" }) }))).json()) as { ok: boolean; detail: string };
+ expect(res).toMatchObject({ ok: true, detail: "LM Studio loaded qwen/qwen3-8b with 16,384 tokens of context in 2.5 s" });
+ expect(lms.state.unloads).toEqual([{ instance_id: "qwen/qwen3-8b" }]);
+ expect(lms.state.loads).toEqual([{ model: "qwen/qwen3-8b", context_length: 16384, echo_load_config: true }]);
+ const test = (await (await route.POST(new Request("http://x/api/llm", { method: "POST", body: JSON.stringify({ action: "test", kind: "lmstudio" }) }))).json()) as { ok: boolean; detail: string };
+ expect(test).toMatchObject({ ok: true, detail: expect.stringMatching(/^LM Studio answered in \d+\.\d s with qwen\/qwen3-8b/) });
+ expect(lms.chats().at(-1)).toMatchObject({ max_tokens: 16, messages: [{ role: "user", content: "Reply with the word OK." }] });
+ });
+
+ it("stops a text step's call when the step is canceled", async () => {
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "SLOW please" });
+ for (let i = 0; i < 100 && !lms.chats().length; i++) await new Promise((r) => setTimeout(r, 50));
+ expect(lms.chats()).toHaveLength(1);
+ const { db } = await import("@/server/db");
+ const handedOver = () => !!(db().prepare("SELECT external_id FROM generations WHERE id = ?").get(g.id) as { external_id: string | null }).external_id;
+ for (let i = 0; i < 50 && !handedOver(); i++) await new Promise((r) => setTimeout(r, 50));
+ await gens.cancelGeneration(g.id);
+ for (let i = 0; i < 100 && !lms.state.aborted; i++) await new Promise((r) => setTimeout(r, 50));
+ expect(lms.state.aborted).toBe(1);
+ expect(gens.getGeneration(g.id)!.status).toBe("canceled");
+ });
+});
+
+describe("Unsloth Studio", () => {
+ it("needs its key; with it, translates subtitles on the loaded model with thinking and server-side tools off", async () => {
+ const un = await started(unslothStudio());
+ setSetting("llmProvider", "unsloth");
+ setSetting("unslothUrl", un.url);
+ expect(await local.probeLocal(true)).toBe(false);
+ expect(llm.llmMissing({ endpoint: "auto" })).toMatch(/^Connect Claude or Unsloth Studio in Settings to run this model\. Unsloth Studio needs an API key: in Unsloth Studio, avatar → Settings → API → Create/);
+ // Keyless at first (Unsloth's keyless access may be on): no Authorization header was sent.
+ expect(un.seen.find((r) => r.url === "/v1/models")?.auth).toBeUndefined();
+ const keyless = un.seen.length;
+ setSetting("unslothKey", "sk-unsloth-test");
+ expect(await local.probeLocal(true)).toBe(true);
+ expect(llm.llmProvider.label).toBe("Claude or Unsloth Studio");
+ const cues = JSON.stringify([
+ { start: 0, end: 1.5, text: "Hello there." },
+ { start: 2, end: 3.5, text: "Two\nlines." },
+ ]);
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: cues, params: { targetLanguage: "Spanish" } });
+ expect(g).toMatchObject({ provider: "llm", costUsd: 0 });
+ const done = await settle(g.id);
+ expect(done.status, done.error ?? "").toBe("succeeded");
+ expect(done.outputs[0].meta?.cues).toEqual([
+ { start: 0, end: 1.5, text: "(Spanish·unsloth) Hello there." },
+ { start: 2, end: 3.5, text: "(Spanish·unsloth) Two\nlines." },
+ ]);
+ const [chat] = un.chats();
+ expect(chat).toMatchObject({ enable_tools: false, enable_thinking: false, stream: false });
+ expect(chat).not.toHaveProperty("model");
+ // With the key, every call but the liveness check carries it.
+ expect(un.seen.slice(keyless).filter((r) => r.url !== "/api/liveness").map((r) => r.auth)).toEqual(expect.arrayContaining(["Bearer sk-unsloth-test"]));
+ expect(un.seen.slice(keyless).filter((r) => r.url !== "/api/liveness").every((r) => r.auth === "Bearer sk-unsloth-test")).toBe(true);
+ expect(un.seen.filter((r) => r.url === "/api/liveness").every((r) => r.auth === undefined)).toBe(true);
+ // The speech model isn't offered for chat.
+ expect((await local.activeLocal())!.status.models.map((m) => m.id)).toEqual(["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-12b-it-GGUF"]);
+ });
+});
+
+describe("another OpenAI-compatible server (llama-server)", () => {
+ it("asks again without JSON when the server can't do it, and uses the model it lists", async () => {
+ const ls = await started(llamaServer());
+ setSetting("llmProvider", "custom");
+ setSetting("llmUrl", ls.url); // no /v1: added
+ expect(await local.probeLocal(true)).toBe(true);
+ const text = await llmText("You are an ad strategist. Answer with JSON.", "Make ads", { json: { name: "reply", schema: { type: "object" } } });
+ expect(text).toMatch(/"reply": "Sure — four ads coming up\."/);
+ const [withJson, without] = ls.chats();
+ expect(withJson).toMatchObject({ model: "gemma-3-4b-it-Q4_K_M.gguf", response_format: { type: "json_schema", json_schema: { name: "reply", strict: true } } });
+ expect(without).not.toHaveProperty("response_format");
+ expect(ls.seen.filter((r) => r.method === "POST").map((r) => r.url)).toEqual(["/v1/chat/completions", "/v1/chat/completions"]);
+ expect(llm.llmProvider.label).toBe("Claude or your local server");
+ });
+});
+
+describe("Automatic", () => {
+ it("uses the first ready server in order (Ollama first, as before), and /api/status says which, without secrets", async () => {
+ const ol = await started(ollama());
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("lmstudioUrl", lms.url);
+ setSetting("lmstudioToken", "lms-never-shown-5678");
+ setSetting("ollamaUrl", ol.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("ollama");
+ expect(llm.llmProvider.label).toBe("Claude or Ollama");
+ // Ollama stops: LM Studio takes over.
+ setSetting("ollamaUrl", "http://127.0.0.1:9");
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ expect(llm.llmProvider.label).toBe("Claude or LM Studio");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["local"]);
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "text-llm", op: "write", prompt: "A tagline" });
+ expect(g.costUsd).toBe(0);
+ expect((await settle(g.id)).outputs[0].text).toBe("(??·lms) A tagline");
+ const { GET } = await import("@/app/api/status/route");
+ const raw = await (await GET()).text();
+ expect(raw).not.toContain("lms-never-shown-5678");
+ const status = JSON.parse(raw) as { providers: { llm: { label: string; configured: boolean } }; llm: { helper: string; local: { kind: string; model: string; context: number }; detected: { kind: string; up: boolean }[] } };
+ expect(status.providers.llm).toEqual({ label: "Claude or LM Studio", configured: true });
+ expect(status.llm).toMatchObject({ helper: "auto", claude: false, provider: "auto", local: { kind: "lmstudio", label: "LM Studio", model: "qwen/qwen3-8b", loaded: true, context: 16384 } });
+ expect(status.llm.detected.map((d) => [d.kind, d.up])).toEqual([
+ ["ollama", false],
+ ["lmstudio", true],
+ ["unsloth", false],
+ ]);
+ // The old "ollama" AI-helper value still means local-only.
+ setSetting("enhanceProvider", "ollama");
+ expect(local.aiHelper()).toBe("local");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["local"]);
+ });
+
+ it("passes over an Ollama with no models for an LM Studio that has one, and uses Ollama alone as before", async () => {
+ const empty = await started(ollama([]));
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("ollamaUrl", empty.url);
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ // An Ollama without the configured model is passed over too.
+ const other = await started(ollama([{ name: "llama3.2:3b" }]));
+ setSetting("ollamaUrl", other.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ // No other server: Ollama still takes calls (and names the missing model when one fails).
+ setSetting("lmstudioUrl", "http://127.0.0.1:9");
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("ollama");
+ });
+});
++
++describe("the open text model's licence", () => {
++ it("is the licence of the model the local server in use runs, LM Studio and Unsloth ids included", async () => {
++ const { changeAccess, offeredModel, routeLicence } = await import("@/server/model-access");
++ const { getModel } = await import("@/lib/catalog");
++ const m = getModel("oss-text-llm")!;
++ const route = m.routes[0];
++ // Nothing answers: Ollama's model setting, as before.
++ expect(routeLicence(route, m)).toMatchObject({ name: "Apache-2.0", class: "commercial", note: expect.stringContaining("on Ollama (qwen3:8b)") });
++ // LM Studio pinned with a Gemma model: Gemma's terms, also with the publisher in front of the name.
++ setSetting("llmProvider", "lmstudio");
++ setSetting("lmstudioModel", "google/gemma-3-12b");
++ expect(routeLicence(route, m)).toMatchObject({ name: "Gemma Terms of Use", class: "conditions", note: expect.stringContaining("on LM Studio (google/gemma-3-12b)") });
++ // So switching off "Commercial use with conditions" reaches it, and a model with another licence brings it back.
++ changeAccess([{ kind: "class", id: "conditions", on: false }]);
++ try {
++ expect(offeredModel(m)).toBeUndefined();
++ setSetting("lmstudioModel", "qwen/qwen3-8b");
++ expect(offeredModel(m)).toBe(m);
++ } finally {
++ changeAccess([{ kind: "class", id: "conditions", on: true }]);
++ }
++ // The model a ready server reports wins over the setting (Unsloth: the loaded one).
++ const uns = await started(unslothStudio());
++ setSetting("llmProvider", "unsloth");
++ setSetting("unslothUrl", uns.url);
++ setSetting("unslothKey", "sk-unsloth-test");
++ await local.probeLocal(true);
++ expect(routeLicence(route, m)).toMatchObject({ name: "Apache-2.0", note: expect.stringContaining("on Unsloth Studio (unsloth/Qwen3-8B-GGUF)") });
++ });
++});
diff --cc tests/model3d-finish.test.ts
index ba64b219,00000000..458dd687
mode 100644,000000..100644
--- a/tests/model3d-finish.test.ts
+++ b/tests/model3d-finish.test.ts
@@@ -1,368 -1,0 +1,368 @@@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { Document, getBounds, NodeIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+import { MeshoptDecoder } from "meshoptimizer";
+import sharp from "sharp";
+import { describe, expect, it, vi } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import { model3dRequest, model3dView, MODELS_3D, viewerGlb } from "@/lib/av/model3d";
+import { modelPreview } from "@/lib/output-actions";
+import type { OutputFile } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 120_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-3d-finish-"));
+process.env.FUOBE_DATA_DIR = dir;
+const { saveFile } = await import("@/server/storage");
+const { finishModel, lastJsonLine, modelToFinish, pendingTurntable, startTurntable, withTurntable } = await import("@/server/model3d-finish");
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until<T>(f: () => T | undefined | null | false, ms = 30_000): Promise<T> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await sleep(50);
+ }
+}
+
+const root = process.cwd();
+type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+const graph = (id: string) => JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", `${id}.json`), "utf8")) as Graph;
+const manifest = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string; bindings: Record<string, unknown>; outputs: { node: string; kind: string }[]; defaults: Record<string, unknown>; validated: boolean }[] };
+const byClass = (g: Graph, c: string) => Object.entries(g).filter(([, n]) => n.class_type === c);
+const one = (g: Graph, c: string) => {
+ const found = byClass(g, c);
+ expect(found, c).toHaveLength(1);
+ return found[0];
+};
+const link = (v: unknown) => (Array.isArray(v) ? String(v[0]) : null);
+
+describe("image-to-3D graphs", () => {
+ for (const id of ["image-to-3d-pixal3d", "image-to-3d-trellis2"]) {
+ it(`${id}: remesh solid, decimate to 250k, bake from the dense mesh, no in-graph turntable`, () => {
+ const g = graph(id);
+ const [remeshId, remesh] = one(g, "RemeshMesh");
+ expect(remesh.inputs).toMatchObject({ resolution: 768, sign_mode: "solid", "sign_mode.fill": 20, band: 1, smooth_iters: 20 });
+ const [decId, dec] = one(g, "DecimateMesh");
+ expect(dec.inputs).toMatchObject({ target_face_count: 250000, placement_mode: "midpoint" });
+ expect(link(dec.inputs.mesh)).toBe(remeshId);
+ // DecimateMesh sits between RemeshMesh and MeshSmoothNormals; the UVs are unwrapped on the decimated mesh.
+ const [smoothId] = byClass(g, "MeshSmoothNormals").find(([, n]) => link(n.inputs.mesh) === decId)!;
+ const [unwrapId, unwrap] = one(g, "UnwrapMesh");
+ expect(link(unwrap.inputs.mesh)).toBe(smoothId);
+ const [, normal] = one(g, "BakeNormalMapFromMesh");
+ const [, ao] = one(g, "BakeAmbientOcclusion");
+ expect(normal.inputs).toMatchObject({ resolution: 2048 });
+ expect(ao.inputs).toMatchObject({ resolution: 1024 });
+ for (const bake of [normal, ao]) {
+ expect(link(bake.inputs.high_poly)).toBe(remeshId);
+ expect(link(bake.inputs.low_poly)).toBe(unwrapId);
+ }
+ for (const c of ["RotateMesh", "RenderMesh", "CreateVideo", "SaveVideo"]) expect(byClass(g, c), c).toHaveLength(0);
+ // Samplers as the template: structure 12, shape 20, upsample 12, texture 12; upsample to 1536.
+ expect(byClass(g, "KSampler").map(([, n]) => n.inputs.steps).sort()).toEqual([12, 12, 12, 20]);
+ expect(Number(one(g, "Trellis2UpsampleStage")[1].inputs.target_resolution)).toBe(1536);
+ // The BiRefNet cut-out feeds the crop.
+ const [cutId] = one(g, "RemoveBackground");
+ expect(link(one(g, "ImageCropToMask")[1].inputs.masks)).toBe(cutId);
+
+ const m = manifest.workflows.find((w) => w.id === id)!;
+ expect(m.validated).toBe(true);
+ expect(m.outputs).toEqual([{ node: "322", kind: "model3d" }]);
+ expect(Object.keys(m.bindings).sort()).toEqual(["filenamePrefix", "image", "seed", "textureSize"]);
+ expect(m.defaults).toEqual({ textureSize: 4096 });
+ });
+ }
+
+ it("Pixal3D: MoGe-2 camera -> horizontal FOV -> Pixal3D conditioning, crop pad 1.1", () => {
+ const g = graph("image-to-3d-pixal3d");
+ const [loaderId, loader] = one(g, "LoadMoGeModel");
+ expect(loader.inputs.model_name).toBe("moge_2_vitl_normal_fp16.safetensors");
+ const [mogeId, moge] = one(g, "MoGeInference");
+ expect(moge.inputs.resolution_level).toBe(9);
+ expect(link(moge.inputs.moge_model)).toBe(loaderId);
+ const [fovId, fov] = one(g, "MoGeGeometryToFOV");
+ expect(fov.inputs).toMatchObject({ axis: "horizontal", unit: "degrees" });
+ expect(link(fov.inputs.moge_geometry)).toBe(mogeId);
+ const [, cond] = one(g, "Pixal3DConditioning");
+ expect(link(cond.inputs.camera_angle_x)).toBe(fovId);
+ expect(one(g, "UNETLoader")[1].inputs.unet_name).toBe("pixal3d_int8_convrot.safetensors");
+ expect(one(g, "ImageCropToMask")[1].inputs).toMatchObject({ width: 1024, height: 1024, pad_factor: 1.1 });
+ expect(byClass(g, "Trellis2Conditioning")).toHaveLength(0);
+ });
+
+ it("TRELLIS.2 (the fallback): its own UNet and conditioning, crop pad 1.0", () => {
+ const g = graph("image-to-3d-trellis2");
+ expect(one(g, "UNETLoader")[1].inputs.unet_name).toBe("trellis_2_int8_convrot.safetensors");
+ expect(one(g, "ImageCropToMask")[1].inputs).toMatchObject({ width: 1024, height: 1024, pad_factor: 1 });
+ expect(byClass(g, "Pixal3DConditioning")).toHaveLength(0);
+ one(g, "Trellis2Conditioning");
+ });
+});
+
+describe("image-to-3D routes", () => {
+ it("Pixal3D is the default open model; TRELLIS.2 stays as the fallback", () => {
- expect(MODELS_3D.open.map((m) => m.id).slice(0, 2)).toEqual(["oss-pixal3d", "oss-trellis2"]);
++ expect(MODELS_3D.image.open.map((m) => m.id).slice(0, 2)).toEqual(["oss-pixal3d", "oss-trellis2"]);
+ expect(model3dRequest({ engine: "open", photo: "p.png" }).modelId).toBe("oss-pixal3d");
+ expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "oss-trellis2" }).modelId).toBe("oss-trellis2");
+ expect(getModel("oss-pixal3d")?.routes[0]).toMatchObject({ provider: "comfyui", endpoint: "image-to-3d-pixal3d", op: "image-to-3d" });
+ expect(getModel("oss-trellis2")?.routes[0]).toMatchObject({ provider: "comfyui", endpoint: "image-to-3d-trellis2", op: "image-to-3d" });
+ expect(getPreset("app-image-to-3d")?.open?.modelId).toBe("oss-pixal3d");
+ });
+
+ it("viewers load the web GLB; results made before it fall back to the original", () => {
+ expect(viewerGlb({ url: "/api/files/raw.glb", meta: { web: "/api/files/web.glb" } })).toBe("/api/files/web.glb");
+ expect(viewerGlb({ url: "/api/files/raw.glb" })).toBe("/api/files/raw.glb");
+ expect(viewerGlb({ url: "/api/files/raw.glb", meta: { web: "" } })).toBe("/api/files/raw.glb");
+ const request = model3dRequest({ engine: "open", photo: "/api/files/p.png" });
+ const finished = model3dView({
+ outputs: [
+ { url: "/api/files/raw.glb", kind: "model3d", meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp" } },
+ { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable" } },
+ ],
+ request,
+ });
+ expect(finished).toMatchObject({ glb: "/api/files/raw.glb", web: "/api/files/web.glb", turntable: "/api/files/turn.mp4", poster: "/api/files/poster.webp" });
+ // An old TRELLIS.2 result: its own 12 fps turntable, no web GLB.
+ const old = model3dView({ outputs: [{ url: "/api/files/old.glb", kind: "model3d" }, { url: "/api/files/old.mp4", kind: "video", meta: { role: "turntable" } }], request });
+ expect(old).toMatchObject({ glb: "/api/files/old.glb", web: "/api/files/old.glb", turntable: "/api/files/old.mp4" });
+ // Gallery tiles play the turntable or show the poster, never the GLB.
+ const mesh: OutputFile = { url: "/api/files/raw.glb", kind: "model3d", meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp" } };
+ expect(modelPreview({ outputs: [mesh, { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable" } }] }, mesh)).toEqual({
+ poster: "/api/files/poster.webp",
+ video: "/api/files/turn.mp4",
+ });
+ });
+
+ it("the meshopt decoder is served from this origin, the same file as the installed package", () => {
+ const vendored = fs.readFileSync(path.join(root, "public/vendor/meshopt_decoder.js"), "utf8");
+ expect(vendored).toBe(fs.readFileSync(path.join(root, "node_modules/meshoptimizer/meshopt_decoder.cjs"), "utf8"));
+ // A classic script (model-viewer loads it with a <script> tag): no ES module syntax.
+ expect(vendored).not.toMatch(/^\s*export\s/m);
+ });
+});
+
+describe("the server's 3D finish", () => {
+ const glbOut = (o: Partial<OutputFile> = {}): OutputFile => ({ url: "/api/files/outputs/x.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "a1", ...o });
+
+ it("finishes the GLB of image-to-3D jobs from ComfyUI only", () => {
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut()])).toBe(0);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [{ url: "/v.mp4", kind: "video" }, glbOut()])).toBe(1);
+ expect(modelToFinish({ provider: "mock", op: "image-to-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "fal", op: "image-to-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "scene-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut({ meta: { finish: { version: 1 } } })])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut({ contentType: "model/ply", url: "/x.ply" })])).toBe(-1);
+ });
+
+ it("reads the scripts' JSON result line", () => {
+ expect(lastJsonLine("some log\n{\"a\":1}\n")).toEqual({ a: 1 });
+ expect(lastJsonLine("no json")).toBeNull();
+ });
+
+ /** A textured box whose origin is off-centre (like Pixal3D's), with a given baked roughness / metallic. */
+ async function boxGlb(file: string, rough: number, metal: number) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const p: number[] = [];
+ const uv: number[] = [];
+ const idx: number[] = [];
+ // 6 faces, 4 vertices each, centred at (2, 3, -1), size 1.
+ const faces = [
+ [[0, 0, 1], [1, 0, 0], [0, 1, 0]],
+ [[0, 0, -1], [-1, 0, 0], [0, 1, 0]],
+ [[1, 0, 0], [0, 0, -1], [0, 1, 0]],
+ [[-1, 0, 0], [0, 0, 1], [0, 1, 0]],
+ [[0, 1, 0], [1, 0, 0], [0, 0, -1]],
+ [[0, -1, 0], [1, 0, 0], [0, 0, 1]],
+ ];
+ for (const [n, u, v] of faces) {
+ const base = p.length / 3;
+ for (const [su, sv] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
+ p.push(2 + 0.5 * (n[0] + su * u[0] + sv * v[0]), 3 + 0.5 * (n[1] + su * u[1] + sv * v[1]), -1 + 0.5 * (n[2] + su * u[2] + sv * v[2]));
+ uv.push((su + 1) / 2, (sv + 1) / 2);
+ }
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
+ }
+ const prim = doc
+ .createPrimitive()
+ .setAttribute("POSITION", doc.createAccessor().setType("VEC3").setArray(new Float32Array(p)).setBuffer(buffer))
+ .setAttribute("TEXCOORD_0", doc.createAccessor().setType("VEC2").setArray(new Float32Array(uv)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType("SCALAR").setArray(new Uint32Array(idx)).setBuffer(buffer));
+ const png = (r: number, g: number, b: number) => sharp({ create: { width: 64, height: 64, channels: 3, background: { r, g, b } } }).png().toBuffer();
+ const material = doc
+ .createMaterial()
+ .setBaseColorTexture(doc.createTexture().setImage(new Uint8Array(await png(200, 150, 100))).setMimeType("image/png"))
+ .setMetallicRoughnessTexture(doc.createTexture().setImage(new Uint8Array(await png(255, Math.round(rough * 255), Math.round(metal * 255)))).setMimeType("image/png"))
+ .setMetallicFactor(1)
+ .setRoughnessFactor(1);
+ prim.setMaterial(material);
+ doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(prim)));
+ await new NodeIO().write(file, doc);
+ }
+
+ async function readWeb(file: string) {
+ await MeshoptDecoder.ready;
+ const doc = await new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder }).read(file);
+ const mat = doc.getRoot().listMaterials()[0];
+ const mr = mat.getMetallicRoughnessTexture()!;
+ const { data, info } = await sharp(Buffer.from(mr.getImage()!)).raw().toBuffer({ resolveWithObject: true });
+ const px = (k: number) => data[k];
+ return {
+ extensions: doc.getRoot().listExtensionsUsed().map((e) => e.extensionName).sort(),
+ mime: mr.getMimeType(),
+ bounds: getBounds(doc.getRoot().listScenes()[0]),
+ rough: px(1) / 255,
+ metal: px(2) / 255,
+ channels: info.channels,
+ };
+ }
+
+ const script = path.join(root, "scripts/model3d/finish-glb.mjs");
+ const finishCli = (input: string, output: string, ...extra: string[]) => {
+ const r = spawnSync(process.execPath, [script, "--in", input, "--out", output, ...extra], { encoding: "utf8" });
+ expect(r.status, r.stderr).toBe(0);
+ return lastJsonLine<{ material: string; triangles: number; roughFloor: number; noMetal: boolean }>(r.stdout)!;
+ };
+
+ it("matte: roughness floor 0.8, metal off, pivot at the bottom centre, meshopt + WebP", async () => {
+ const raw = path.join(dir, "matte.glb");
+ const web = path.join(dir, "matte-web.glb");
+ await boxGlb(raw, 0.25, 0);
+ const stats = finishCli(raw, web);
+ expect(stats).toMatchObject({ material: "matte", triangles: 12, roughFloor: 0.8, noMetal: true });
+ const out = await readWeb(web);
+ expect(out.extensions).toEqual(expect.arrayContaining(["EXT_meshopt_compression", "EXT_texture_webp"]));
+ expect(out.mime).toBe("image/webp");
+ expect(out.rough).toBeGreaterThanOrEqual(0.78);
+ expect(out.metal).toBeLessThan(0.02);
+ // center --pivot below: the bottom sits on y = 0, centred in x and z.
+ expect(out.bounds.min[1]).toBeCloseTo(0, 2);
+ expect((out.bounds.min[0] + out.bounds.max[0]) / 2).toBeCloseTo(0, 2);
+ expect((out.bounds.min[2] + out.bounds.max[2]) / 2).toBeCloseTo(0, 2);
+ });
+
+ it("metal: no roughness floor, metal kept; a material can be forced", async () => {
+ const raw = path.join(dir, "metal.glb");
+ await boxGlb(raw, 0.1, 1);
+ const web = path.join(dir, "metal-web.glb");
+ expect(finishCli(raw, web)).toMatchObject({ material: "metal", roughFloor: 0, noMetal: false });
+ const out = await readWeb(web);
+ expect(out.rough).toBeLessThan(0.15);
+ expect(out.metal).toBeGreaterThan(0.95);
+ expect(finishCli(raw, path.join(dir, "forced.glb"), "--material", "matte")).toMatchObject({ material: "matte" });
+ });
+
+ it("finishModel adds the web GLB, keeps the raw GLB as the download and queues the turntable; no Chromium skips it, not a failure", async () => {
+ const raw = path.join(dir, "job.glb");
+ await boxGlb(raw, 0.3, 0);
+ const asset = saveFile({ data: fs.readFileSync(raw), contentType: "model/gltf-binary", source: "generation", generationId: "g3d" });
+ const before: OutputFile[] = [{ url: asset.url, kind: "model3d", contentType: asset.contentType, assetId: asset.id }];
+ const messages: string[] = [];
+ const after = await finishModel("g3d", before, { op: "image-to-3d", provider: "comfyui", onMessage: (m) => messages.push(m) });
+ expect(after).toHaveLength(1);
+ expect(after[0].url).toBe(asset.url);
+ const meta = after[0].meta as { web: string; finish: { version: number; material: string; triangles: number; turntable: string; webAsset: string } };
+ expect(meta.web).toMatch(/^\/api\/files\/.+\.glb$/);
+ expect(meta.web).not.toBe(asset.url);
+ expect(meta.finish).toMatchObject({ version: 2, material: "matte", triangles: 12, turntable: "queued" });
+ expect(meta.finish.webAsset).toBeTruthy();
+ // The job succeeds now; the turntable is rendered after.
+ expect(messages).toEqual(["Finishing the 3D model"]);
+ // Not finished twice.
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, after)).toBe(-1);
+ expect(pendingTurntable(after)).toBe(0);
+
+ // The turntable step on a server without Chromium: skipped, stored on the finished job, nothing added.
+ const saved = process.env.FUOBE_CHROMIUM;
+ process.env.FUOBE_CHROMIUM = path.join(dir, "no-such-chromium.exe");
+ let stored: OutputFile[] = after;
+ const states: string[] = [];
+ try {
+ startTurntable("g3d", {
+ read: () => stored,
+ write: (o) => {
+ stored = o;
+ states.push(String((o[0].meta!.finish as { turntable: string }).turntable));
+ },
+ });
+ await until(() => states.some((w) => w.startsWith("skipped")));
+ } finally {
+ if (saved === undefined) delete process.env.FUOBE_CHROMIUM;
+ else process.env.FUOBE_CHROMIUM = saved;
+ }
+ expect(states[0]).toBe("rendering");
+ expect(stored).toHaveLength(1);
+ expect(stored[0].meta).toMatchObject({ web: meta.web });
+ expect(pendingTurntable(stored)).toBe(-1);
+ });
+
+ it("a turntable for a job deleted meanwhile stores nothing; a missing web GLB says so", async () => {
+ const writes: OutputFile[][] = [];
+ const queued: OutputFile[] = [{ url: "/api/files/x.glb", kind: "model3d", assetId: "m-x", meta: { finish: { version: 2, turntable: "queued", webAsset: "no-such-asset" } } }];
+ startTurntable("g-gone", { read: () => null, write: (o) => void writes.push(o) });
+ await sleep(200);
+ expect(writes).toEqual([]);
+ let stored = queued;
+ startTurntable("g-noweb", { read: () => stored, write: (o) => void (stored = o) });
+ await until(() => pendingTurntable(stored) < 0);
+ expect((stored[0].meta!.finish as { turntable: string }).turntable).toBe("failed: the web GLB is missing");
+ });
+
+ it("withTurntable: progress while rendering, then the video and the poster; an old in-graph turntable gives way", () => {
+ const request = model3dRequest({ engine: "open", photo: "p.png" });
+ const mesh: OutputFile = { url: "/api/files/raw.glb", kind: "model3d", assetId: "m1", meta: { web: "/api/files/web.glb", finish: { version: 2, material: "metal", turntable: "queued" } } };
+ const old: OutputFile = { url: "/api/files/old.mp4", kind: "video", meta: { role: "turntable" } };
+ expect(model3dView({ outputs: [mesh], request }).rendering).toEqual({ queued: true, progress: 0 });
+ const rendering = withTurntable([mesh, old], "m1", { state: "rendering", progress: 0.4 });
+ expect(rendering[0].meta).toMatchObject({ web: "/api/files/web.glb", finish: { version: 2, turntable: "rendering", turntableProgress: 0.4 } });
+ expect(pendingTurntable(rendering)).toBe(0);
+ expect(model3dView({ outputs: rendering, request }).rendering).toEqual({ queued: false, progress: 0.4 });
+ const video: OutputFile = { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable", fps: 24, frames: 96 } };
+ const done = withTurntable(rendering, "m1", { state: "done", video, poster: "/api/files/poster.webp" });
+ expect(done).toEqual([{ ...mesh, meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp", finish: { version: 2, material: "metal", turntable: "done" } } }, video]);
+ expect(pendingTurntable(done)).toBe(-1);
+ expect(model3dView({ outputs: done, request })).toMatchObject({ turntable: "/api/files/turn.mp4", poster: "/api/files/poster.webp", rendering: undefined, material: "metal" });
+ // Another model output is left alone.
+ expect(withTurntable([mesh], "other", { state: "done" })).toEqual([mesh]);
+ });
+
+ it("a GLB with no material, or one at the glTF defaults, becomes a matte dielectric (not three.js's dark metal)", async () => {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const tri = () =>
+ doc
+ .createPrimitive()
+ .setAttribute("POSITION", doc.createAccessor().setType("VEC3").setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0])).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType("SCALAR").setArray(new Uint32Array([0, 1, 2])).setBuffer(buffer));
+ const bare = tri();
+ const defaults = tri().setMaterial(doc.createMaterial("defaults"));
+ const chosen = tri().setMaterial(doc.createMaterial("chosen").setMetallicFactor(1).setRoughnessFactor(0.2));
+ doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(bare).addPrimitive(defaults).addPrimitive(chosen)));
+ const raw = path.join(dir, "shape.glb");
+ await new NodeIO().write(raw, doc);
+ const web = path.join(dir, "shape-web.glb");
+ expect(finishCli(raw, web)).toMatchObject({ material: "unknown" });
+ await MeshoptDecoder.ready;
+ const out = await new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder }).read(web);
+ const prims = out.getRoot().listMeshes().flatMap((m) => m.listPrimitives());
+ expect(prims.every((p) => !!p.getMaterial())).toBe(true);
+ const mats = out.getRoot().listMaterials().map((m) => [m.getMetallicFactor(), m.getRoughnessFactor()]);
+ // The bare and default ones are matte; one that was set on purpose is kept.
+ expect(mats).toEqual(expect.arrayContaining([[0, 0.8], [1, 0.2]]));
+ expect(mats).not.toContainEqual([1, 1]);
+ });
+
+ it("a GLB the script can't read keeps the raw result", async () => {
+ const asset = saveFile({ data: Buffer.from("not a glb"), contentType: "model/gltf-binary", source: "generation", generationId: "g-bad" });
+ const before: OutputFile[] = [{ url: asset.url, kind: "model3d", contentType: asset.contentType, assetId: asset.id }];
+ const after = await finishModel("g-bad", before, { op: "image-to-3d", provider: "comfyui" });
+ expect(after[0].url).toBe(asset.url);
+ expect((after[0].meta as { web?: string }).web).toBeUndefined();
+ expect((after[0].meta as { finish: { error: string } }).finish.error).toMatch(/^web GLB/);
+ });
+});
diff --cc tests/model3d.test.ts
index 00000000,59fc5aec..5d28a21d
mode 000000,100644..100644
--- a/tests/model3d.test.ts
+++ b/tests/model3d.test.ts
@@@ -1,0 -1,396 +1,396 @@@
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
+ import type { Model3dChoice, Model3dMode } from "@/lib/av/model3d";
+
+ /**
+ * Image to 3D's modes (r4/3d-plus): the plan per mode and engine, the cloud payloads (SAM 3D's prompt is
+ * always sent), the outputs the cards read, the open multi-view and splat bindings, the open text-to-3D chain
+ * and Rig & animate.
+ */
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-model3d-"));
+ process.env.FUOBE_DATA_DIR = dir;
+ process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+ const { setSetting } = await import("@/server/settings");
+ const gens = await import("@/server/generations");
+ const { db } = await import("@/server/db");
+ const { collectOutputs, getWorkflow, prepareWorkflow, viewSlots } = await import("@/server/providers/comfyui");
+ const { getModel, getPreset } = await import("@/lib/catalog");
+ const { estimateCost, planGeneration } = await import("@/lib/catalog/plan");
+ const { buildPayload, extractOutputs } = await import("@/lib/catalog/payload");
+ const { dropBranch } = await import("@/lib/comfy");
+ const m3d = await import("@/lib/av/model3d");
+
+ beforeAll(() => setSetting("demoMode", "auto"));
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ const plan = (req: Parameters<typeof planGeneration>[0]) => planGeneration(req, getModel, getPreset);
+ const photo = "/api/files/uploads/p.png";
+ const views = { front: "/api/files/f.png", left: "/api/files/l.png", back: "/api/files/b.png" };
+
+ describe("modes: which model and operation each runs, per engine", () => {
+ const cases: [Model3dMode, "cloud" | "open", string, string][] = [
+ ["image", "cloud", "hunyuan-3d-3-1-pro", "image-to-3d"],
- ["image", "open", "oss-trellis2", "image-to-3d"],
++ ["image", "open", "oss-pixal3d", "image-to-3d"],
+ ["multi", "cloud", "meshy-7-1-multi", "image-to-3d"],
+ ["multi", "open", "oss-trellis2-multi", "image-to-3d"],
+ ["text", "cloud", "tripo-h3-1-text", "text-to-3d"],
+ ["text", "open", "oss-text-trellis2", "text-to-3d"],
+ ["objects", "cloud", "sam-3d-objects", "image-to-3d"],
+ ["splat", "cloud", "triposplat", "splat"],
+ ["splat", "open", "oss-triposplat", "splat"],
+ ];
+ it.each(cases)("%s on %s → %s (%s)", (mode, engine, modelId, op) => {
+ const input = { engine, mode, photo, views, prompt: "a red leather armchair" };
+ expect(m3d.model3dBlocker(input)).toBeNull();
+ const req = m3d.model3dRequest(input);
+ expect(req).toMatchObject({ feature: "image-to-3d", modelId, op });
+ const p = plan(req);
+ expect([p.model.id, p.op, p.model.engine]).toEqual([modelId, op, engine]);
+ expect(p.jobs).toBe(1);
+ expect(m3d.modeOfRequest(req)).toBe(mode);
+ expect(m3d.modeOf(modelId)).toEqual({ mode, engine });
+ });
+
+ it("every model the page offers is in the catalog with its mode's operation", () => {
+ const ops: Record<Model3dMode, string> = { image: "image-to-3d", multi: "image-to-3d", text: "text-to-3d", objects: "image-to-3d", splat: "splat" };
+ for (const [mode, byEngine] of Object.entries(m3d.MODELS_3D) as [Model3dMode, Record<string, Model3dChoice[]>][]) {
+ for (const [engine, list] of Object.entries(byEngine)) {
+ for (const c of list) {
+ const m = getModel(c.id);
+ expect(m?.engine, c.id).toBe(engine);
+ expect(m?.routes.some((r) => r.op === ops[mode]), c.id).toBe(true);
+ }
+ }
+ }
+ expect(getModel(m3d.RIG_MODEL)?.routes[0]).toMatchObject({ op: "rig-3d", provider: "fal", endpoint: "fal-ai/meshy/rigging" });
+ // TripoSplat encodes with DINOv3 on fal too: its results carry the notice.
+ expect(m3d.CLOUD_NOTICES.triposplat).toEqual(["Built with DINOv3"]);
+ // TRELLIS.2 encodes with DINOv3 ViT-L on fal too, as on the open engine.
+ expect(m3d.CLOUD_NOTICES["trellis-2"]).toEqual(["Built with DINOv3"]);
+ expect(Object.keys(m3d.CLOUD_NOTICES).every((id) => getModel(id)?.engine === "cloud")).toBe(true);
+ });
+
+ it("says which way round the sides go", () => {
+ expect(m3d.SIDES_HINT).toMatch(/object's own/);
+ expect(m3d.SIDES_HINT).toMatch(/your right for its left/);
+ });
+
+ it("says what is missing, and that Pick an object is cloud only", () => {
+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "image" })).toBe("Add a photo");
+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "multi", views: { left: "l.png", back: "b.png" } })).toBe("Add a photo of the front");
+ expect(m3d.model3dBlocker({ engine: "open", mode: "multi", views: { front: "f.png" } })).toBe("Add at least one more side");
+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "text", prompt: " " })).toBe("Describe the object");
+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "objects", photo })).toBe("Name the object to take out");
+ expect(m3d.model3dBlocker({ engine: "open", mode: "objects", photo, prompt: "lamp" })).toMatch(/cloud model/);
+ expect(() => m3d.model3dRequest({ engine: "open", mode: "objects", photo, prompt: "lamp" })).toThrow(/cloud model/);
+ // An unknown pick falls back to the mode's default.
+ expect(m3d.model3dRequest({ engine: "open", mode: "splat", photo, modelId: "triposplat" }).modelId).toBe("oss-triposplat");
+ });
+
+ it("sends several photos in side order; the open graph also gets their sides by name", () => {
+ const sides = { front: "f.png", back: "b.png", right: "r.png" };
+ expect(m3d.model3dRequest({ engine: "cloud", mode: "multi", views: sides })).toEqual({ feature: "image-to-3d", modelId: "meshy-7-1-multi", op: "image-to-3d", inputs: { images: ["f.png", "b.png", "r.png"] } });
+ expect(m3d.model3dRequest({ engine: "open", mode: "multi", views: sides }).params).toEqual({ extra: { views: ["front", "back", "right"] } });
+ // Meshy multi-view and the open graph need two photos.
+ expect(() => plan({ feature: "x", modelId: "meshy-7-1-multi", op: "image-to-3d", inputs: { images: ["f.png"] } })).toThrow();
+ expect(() => plan({ feature: "x", modelId: "oss-trellis2-multi", op: "image-to-3d", inputs: { images: ["f.png"] } })).toThrow();
+ });
+
+ it("refuses SAM 3D Objects without words and a text model without a description", () => {
+ expect(() => plan({ feature: "x", modelId: "sam-3d-objects", op: "image-to-3d", prompt: "", inputs: { images: [photo] } })).toThrow(/Name the objects/);
+ expect(() => plan({ feature: "x", modelId: "tripo-h3-1-text", op: "text-to-3d", prompt: "" })).toThrow();
+ });
+ });
+
+ describe("cloud payloads", () => {
+ const route = (id: string) => getModel(id)!.routes[0];
+
+ it("SAM 3D Objects: the words always go (the API reads “car” without them), with a textured GLB", () => {
+ const req = m3d.model3dRequest({ engine: "cloud", mode: "objects", photo, prompt: " the green lamp " });
+ expect(req.prompt).toBe("the green lamp");
+ const p = plan(req);
+ const body = buildPayload(route("sam-3d-objects").map!, { prompt: p.prompt, images: ["https://fal.test/p.png"], seed: 4 });
+ expect(body).toEqual({ prompt: "the green lamp", image_url: "https://fal.test/p.png", seed: 4, export_textured_glb: true });
+ });
+
+ it("Meshy multi-view: the photos as image_urls; Tripo text: the words as the prompt", () => {
+ expect(buildPayload(route("meshy-7-1-multi").map!, { prompt: "", images: ["a.png", "b.png"] })).toMatchObject({ image_urls: ["a.png", "b.png"] });
+ expect(buildPayload(route("tripo-h3-1-text").map!, { prompt: "a brass lantern", seed: 9 })).toMatchObject({ prompt: "a brass lantern", model_seed: 9 });
+ });
+
+ it("TripoSplat: a .ply splat of the photo, with the number of Gaussians picked", () => {
+ const body = buildPayload(route("triposplat").map!, { prompt: "", images: ["https://fal.test/p.png"], extra: { num_gaussians: 131072 } });
+ expect(body).toEqual({ image_url: "https://fal.test/p.png", output_format: "ply", num_gaussians: 131072 });
+ });
+
+ it("Meshy rigging: the model's URL, and a preset turns animation on; it costs $0.12 more", () => {
+ const rig = getModel(m3d.RIG_MODEL)!;
+ const animated = m3d.rigRequest({ glb: "/api/files/m.glb", animation: 30 });
+ expect(animated).toEqual({ feature: "image-to-3d", modelId: "meshy-rigging", op: "rig-3d", inputs: { model3d: "/api/files/m.glb" }, params: { animation: 30 } });
+ expect(plan(animated).op).toBe("rig-3d");
+ expect(buildPayload(rig.routes[0].map!, { prompt: "", model3d: "https://fal.test/m.glb", animation: 30 })).toEqual({ model_url: "https://fal.test/m.glb", animation_action_id: 30, enable_animation: true });
+ expect(buildPayload(rig.routes[0].map!, { prompt: "", model3d: "https://fal.test/m.glb" })).toEqual({ model_url: "https://fal.test/m.glb" });
+ expect(estimateCost(rig, {}, 1, "rig-3d")).toBe(0.2);
+ expect(estimateCost(rig, { animation: 30 }, 1, "rig-3d")).toBe(0.32);
+ // Only Meshy's preset numbers go.
+ expect(m3d.rigRequest({ glb: "m.glb", animation: 697 }).params).toBeUndefined();
+ expect(m3d.animationId("92")).toBe(92);
+ expect(m3d.animationId("9.5")).toBeNull();
+ expect(m3d.animationName(30)).toBe("Casual walk");
+ expect(m3d.animationName(92)).toBe("Preset 92");
+ expect(() => plan({ feature: "x", modelId: "meshy-rigging", op: "rig-3d" })).toThrow(/3D model to rig/);
+ });
+ });
+
+ describe("what the cards show", () => {
+ const view = (outputs: ReturnType<typeof extractOutputs>, request = m3d.model3dRequest({ engine: "cloud", mode: "splat", photo })) =>
+ m3d.model3dView({ outputs: outputs.map((o) => ({ ...o, meta: o.meta ?? {} })) as never, request });
+
+ it("a cloud splat is a download with the cut-out as its poster, not a GLB for the viewer", () => {
+ const outs = extractOutputs({ model_mesh: { url: "https://fal.test/x/splat.ply" }, preprocessed_image: { url: "https://fal.test/x/seen.png" } }, "splat");
+ expect(view(outs)).toMatchObject({ glb: undefined, splat: { url: "https://fal.test/x/splat.ply", format: "ply" }, poster: "https://fal.test/x/seen.png" });
+ });
+
+ it("an open splat (.spz) brings its orbit video", () => {
+ const v = m3d.model3dView({
+ outputs: [
+ { url: "/api/files/g/s.spz", kind: "model3d", meta: { role: "splat", format: "spz" } },
+ { url: "/api/files/g/orbit.mp4", kind: "video", meta: { role: "turntable" } },
+ ] as never,
+ request: m3d.model3dRequest({ engine: "open", mode: "splat", photo }),
+ });
+ expect(v).toMatchObject({ splat: { url: "/api/files/g/s.spz", format: "spz" }, turntable: "/api/files/g/orbit.mp4", glb: undefined });
+ // The demo's splat is a GLB the viewer shows.
+ expect(m3d.model3dView({ outputs: [{ url: "sample:demo-model.glb", kind: "model3d", meta: { splat: true, format: "glb" } }] as never, request: { feature: "x", modelId: "y", op: "splat" } as never })).toMatchObject({ glb: "sample:demo-model.glb", splat: undefined });
+ });
+
+ it("tells a splat from a GLB by its format or extension (the Library's viewer goes by it too)", () => {
+ expect(m3d.splatFormatOf({ url: "/api/files/outputs/a.spz" })).toBe("spz");
+ expect(m3d.splatFormatOf({ url: "https://fal.test/x.ply?sig=1" })).toBe("ply");
+ expect(m3d.splatFormatOf({ url: "/api/files/outputs/a.bin", meta: { format: "KSPLAT" } })).toBe("ksplat");
+ expect(m3d.splatFormatOf({ url: "/api/files/outputs/a.glb" })).toBeUndefined();
+ expect(m3d.splatFormatOf({ url: "sample:demo-model.glb", meta: { format: "glb", splat: true } })).toBeUndefined();
+ expect(m3d.splatFormatOf(undefined)).toBeUndefined();
+ });
+
+ it("a model made from words links to the still it was built from, once the step ran", () => {
+ const step = { feature: "image-to-3d", modelId: "oss-trellis2", op: "image-to-3d" as const, prompt: "a lantern", chain: [{ slot: "images" as const, position: "first" as const }] };
+ expect(m3d.stillOf({ request: { ...step, inputs: { images: ["/api/files/still.png"] }, chainFilled: true } })).toBe("/api/files/still.png");
+ expect(m3d.stillOf({ request: step })).toBeUndefined();
+ expect(m3d.stillOf({ request: m3d.model3dRequest({ engine: "open", mode: "image", photo }) })).toBeUndefined();
+ });
+
+ it("SAM 3D Objects: the GLB in the viewer, its splat as a download", () => {
+ const outs = extractOutputs({ model_glb: { url: "https://fal.test/o.glb" }, gaussian_splat: { url: "https://fal.test/o.ply" } }, "image-to-3d");
+ expect(view(outs, m3d.model3dRequest({ engine: "cloud", mode: "objects", photo, prompt: "lamp" }))).toMatchObject({ glb: "https://fal.test/o.glb", formats: { splat: "https://fal.test/o.ply" } });
+ });
+
+ it("a rig plays the animated GLB, with the rigged one and the walk and run cycles to download", () => {
+ const outs = extractOutputs(
+ {
+ rigged_character_glb: { url: "https://fal.test/rig.glb" },
+ animation_glb: { url: "https://fal.test/anim.glb" },
+ animation_fbx: { url: "https://fal.test/anim.fbx" },
+ basic_animations: { walking_glb: { url: "https://fal.test/walk.glb" }, running_glb: { url: "https://fal.test/run.glb" } },
+ },
+ "rig-3d",
+ );
+ expect(view(outs, m3d.rigRequest({ glb: "/api/files/m.glb", animation: 22 }))).toMatchObject({
+ glb: "https://fal.test/anim.glb",
+ rigged: true,
+ animated: true,
+ formats: { fbx: "https://fal.test/anim.fbx", rigged: "https://fal.test/rig.glb", walking: "https://fal.test/walk.glb", running: "https://fal.test/run.glb" },
+ });
+ });
+ });
+
+ describe("the extra files are kept", () => {
+ it("a rig's walk and run cycles and FBX, SAM 3D's splat and the preview become files of the generation", async () => {
+ const http = await import("node:http");
+ const server = http.createServer((req, res) => {
+ if (req.url === "/gone.glb") return void res.writeHead(404).end();
+ res.setHeader("content-type", "application/octet-stream");
+ res.end(Buffer.from(`file ${req.url}`));
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const at = (p: string) => `http://127.0.0.1:${(server.address() as { port: number }).port}${p}`;
+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";
+ try {
+ const outs = extractOutputs(
+ {
+ rigged_character_glb: { url: at("/rig.glb") },
+ animation_glb: { url: at("/anim.glb") },
+ animation_fbx: { url: at("/anim.fbx") },
+ basic_animations: { walking_glb: { url: at("/walk.glb") }, running_glb: { url: at("/gone.glb") } },
+ },
+ "rig-3d",
+ );
+ const kept = await gens.persistArtifacts(outs[0].meta, "genrig", outs[0].url);
+ const formats = kept?.formats as Record<string, string>;
+ expect(formats.walking).toMatch(/^\/api\/files\/outputs\/.+\.glb$/);
+ expect(formats.rigged).toMatch(/^\/api\/files\/outputs\/.+\.glb$/);
+ expect(formats.fbx).toMatch(/^\/api\/files\/outputs\/.+\.fbx$/);
+ // Gone at the provider: the link stays.
+ expect(formats.running).toBe(at("/gone.glb"));
+ expect(kept).toMatchObject({ rigged: true, animated: true });
+ const file = path.join(dir, "files", decodeURIComponent(formats.walking.slice("/api/files/".length)));
+ expect(fs.readFileSync(file, "utf8")).toBe("file /walk.glb");
+
+ const sam = extractOutputs({ model_glb: { url: at("/o.glb") }, gaussian_splat: { url: at("/o.ply") }, thumbnail: { url: at("/o.png") } }, "image-to-3d");
+ const samKept = await gens.persistArtifacts(sam[0].meta, "gensam", sam[0].url);
+ expect((samKept?.formats as Record<string, string>).splat).toMatch(/^\/api\/files\/outputs\/.+\.ply$/);
+ expect(samKept?.preview).toMatch(/^\/api\/files\/outputs\//);
+ // A format that is the main file itself is left to persistOutput (it isn't fetched twice).
+ const same = await gens.persistArtifacts({ formats: { glb: at("/o.glb"), obj: at("/o.obj") } }, "gensame", at("/o.glb"));
+ expect(same?.formats).toMatchObject({ glb: at("/o.glb"), obj: expect.stringMatching(/^\/api\/files\//) });
+ } finally {
+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+ server.close();
+ }
+ });
+ });
+
+ describe("open engine: multi-view TRELLIS.2 (image-to-3d-trellis2-multiview)", () => {
+ const manifest = getWorkflow("image-to-3d-trellis2-multiview").manifest;
+ const prep = (images: string[], extra?: Record<string, unknown>) =>
+ prepareWorkflow("image-to-3d-trellis2-multiview", { prompt: "", images, extra }, { generationId: "gen-mv", op: "image-to-3d", upload: async (_d, _t, n) => `up_${n}` });
+
+ it("is a validated workflow with a licence that asks for the DINOv3 notice", () => {
+ expect(manifest).toMatchObject({ capability: "image-to-3d", validated: true });
+ expect(manifest.license).toMatch(/Built with DINOv3/);
+ expect(manifest.outputs).toEqual([{ node: "372", kind: "model3d" }, { node: "702", kind: "video", role: "turntable" }]);
+ });
+
+ it("puts each photo on its side and leaves the missing side out of the graph", async () => {
+ const { workflow } = await prep(["f.png", "b.png"], { views: ["front", "back"] });
+ expect(workflow["360"].inputs.image).toBe("f.png");
+ expect(workflow["362"].inputs.image).toBe("b.png");
+ // Left and right: their loaders, cut-outs and crops are gone, and the rig doesn't read them.
+ for (const id of ["361", "363", "348", "349", "352", "353"]) expect(workflow[id], id).toBeUndefined();
+ expect(Object.keys(workflow["324"].inputs).sort()).toEqual(["back", "clip_vision_model", "fov", "front"]);
+ expect(workflow["324"].inputs.front).toEqual(["312", 0]);
+ // The shared cut-out model and the outputs stay.
+ expect(workflow["193"]).toBeDefined();
+ expect(workflow["372"].inputs.filename_prefix).toBe("fuobe/gen-mv");
+ expect(workflow["702"].inputs.filename_prefix).toBe("fuobe/gen-mv");
+ });
+
+ it("measures the photos' field of view on the front crop (MoGe), unless one is given", async () => {
+ const { workflow } = await prep(["f.png", "b.png"], { views: ["front", "back"] });
+ // Pixal3D reads the views' horizontal FOV from MoGe 2 run on the front's cut-out crop, not the rig's fixed 20°.
+ expect(workflow["324"].inputs.fov).toEqual(["382", 0]);
+ expect(workflow["382"]).toMatchObject({ class_type: "MoGeGeometryToFOV", inputs: { moge_geometry: ["381", 0], axis: "horizontal", unit: "degrees" } });
+ expect(workflow["381"]).toMatchObject({ class_type: "MoGeInference", inputs: { image: ["312", 0], fov_x_degrees: 0 } });
+ expect(manifest.models.map((m) => m.file)).toContain("moge_2_vitl_normal_fp16.safetensors");
+ // A rendered turnaround sheet: fovX fixes MoGe's lens, which the FOV node passes on.
+ const sheet = await prep(["f.png", "l.png"], { views: ["front", "left"], fovX: 20 });
+ expect(sheet.workflow["381"].inputs.fov_x_degrees).toBe(20);
+ expect(sheet.workflow["324"].inputs.fov).toEqual(["382", 0]);
+ });
+
+ it("takes the photos in side order when they aren't named, and all four sides", async () => {
+ const { workflow } = await prep(["f.png", "l.png", "b.png", "r.png"]);
+ expect(["360", "361", "362", "363"].map((id) => workflow[id].inputs.image)).toEqual(["f.png", "l.png", "b.png", "r.png"]);
+ expect(Object.keys(workflow["324"].inputs).sort()).toEqual(["back", "clip_vision_model", "fov", "front", "left", "right"]);
+ });
+
+ it("needs the front, and one photo per named side", async () => {
+ await expect(prep(["l.png", "b.png"], { views: ["left", "back"] })).rejects.toThrow("Add a photo of the front");
+ await expect(prep(["f.png", "b.png"], { views: ["front"] })).rejects.toThrow(/2 photos but 1 side/);
+ await expect(prep(["f.png", "x.png"], { views: ["front", "top"] })).rejects.toThrow(/front, left, back, right/);
+ await expect(prep(["f.png", "x.png"], { views: ["front", "front"] })).rejects.toThrow(/Two photos of the front/);
+ expect(viewSlots({ sides: ["front", "left"], into: "X" }, ["a", "b"], undefined)).toEqual({ image: "a", image2: "b" });
+ });
+
+ it("dropBranch refuses a branch that doesn't end in the named node", () => {
+ const wf = { "1": { class_type: "LoadImage", inputs: { image: "a.png" } }, "2": { class_type: "SaveImage", inputs: { images: ["1", 0] } } };
+ expect(dropBranch(wf, "1", "Pixal3DMultiViewConditioning")).toBeNull();
+ expect(dropBranch(wf, "9", "Pixal3DMultiViewConditioning")).toBeNull();
+ });
+ });
+
+ describe("open engine: TripoSplat (image-to-splat-triposplat)", () => {
+ it("binds the photo, the Gaussians picked and the defaults (cut-out on, .spz)", async () => {
+ const m = getModel("oss-triposplat")!;
+ expect(m.routes).toEqual([expect.objectContaining({ op: "splat", provider: "comfyui", endpoint: "image-to-splat-triposplat" })]);
+ const { workflow } = await prepareWorkflow("image-to-splat-triposplat", { prompt: "", images: ["p.png"], extra: { numGaussians: 131072 } }, { generationId: "gen-sp", op: "splat", upload: async () => "x" });
+ expect(workflow["99"].inputs.image).toBe("p.png");
+ expect(workflow["88:55"].inputs.num_gaussians).toBe(131072);
+ expect(workflow["88:35"].inputs.switch).toBe(true);
+ expect(workflow["92"].inputs.format).toBe("spz");
+ });
+
+ it("names the splat's format and type, and keeps the orbit video as the turntable", () => {
+ const file = (filename: string) => ({ filename, subfolder: "fuobe", type: "output" });
+ const outs = collectOutputs(
+ { status: { status_str: "success", completed: true }, outputs: { "51": { "3d": [file("gen-sp_00001_.spz")] }, "42": { images: [file("gen-sp_00001_.mp4")], animated: [true] } } },
+ getWorkflow("image-to-splat-triposplat").manifest,
+ );
+ expect(outs.map((o) => [o.kind, o.contentType, o.meta])).toEqual([
+ ["model3d", "model/x-spz", { role: "splat", format: "spz" }],
+ ["video", undefined, { role: "turntable" }],
+ ]);
+ });
+ });
+
+ describe("open engine: text to 3D as a Z-Image Turbo still, then TRELLIS.2", () => {
+ async function settle(id: string, ms = 40_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+ }
+
+ it("is free and runs as two steps: the still (a helper step) and the model made from it", async () => {
+ const req = m3d.model3dRequest({ engine: "open", mode: "text", prompt: "A brass lantern." });
+ expect(gens.previewGeneration(req)).toMatchObject({ op: "text-to-3d", costUsd: 0 });
+ const [built, still] = gens.createGenerations(req);
+ expect(still).toMatchObject({ feature: "image-to-3d-step", modelId: "oss-z-image-turbo", op: "t2i" });
+ expect(still.prompt).toMatch(/^A brass lantern\. A single object, whole and centred/);
+ expect(built).toMatchObject({ feature: "image-to-3d", modelId: "oss-trellis2", op: "image-to-3d", status: "queued" });
+ expect(built.batchId).toBe(still.batchId);
+ const dep = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(built.id) as { depends_on: string }).depends_on;
+ expect(dep).toBe(still.id);
+ const done = await settle(built.id);
+ expect(done.status).toBe("succeeded");
+ expect(done.outputs.some((o) => o.kind === "model3d")).toBe(true);
+ expect(done.request.inputs?.images?.length).toBe(1);
+ // Its card links to the still.
+ expect(m3d.stillOf(done)).toBe(done.request.inputs?.images?.[0]);
+ }, 60_000);
+
+ it("runs as the same two steps when the request leaves op out (Assist, MCP, the API)", () => {
+ const steps = gens.createGenerations({ feature: "image-to-3d", modelId: "oss-text-trellis2", prompt: "a brass lantern" });
+ expect(steps.map((g) => [g.modelId, g.op])).toEqual([
+ ["oss-trellis2", "image-to-3d"],
+ ["oss-z-image-turbo", "t2i"],
+ ]);
+ // A photo sent along has no place in this route: the model is built from the still alone.
+ const [built] = gens.createGenerations({ feature: "image-to-3d", modelId: "oss-text-trellis2", prompt: "a brass lantern", inputs: { images: ["/api/files/p.png"] } });
+ expect(built.request.inputs?.images).toBeUndefined();
+ expect(built.request.chain).toEqual([{ slot: "images", position: "first" }]);
+ });
+
+ it("can't wait for another step's words, and says so in 3D terms", () => {
+ expect(() => gens.createGenerations({ feature: "image-to-3d", modelId: "oss-text-trellis2", op: "text-to-3d", prompt: "{text}", chain: [{ slot: "prompt" }] }, { dependsOn: "x" })).toThrow(
+ /draws the object first, then builds it in 3D/,
+ );
+ });
+
+ it("needs the words", () => {
+ expect(() => gens.createGenerations({ feature: "image-to-3d", modelId: "oss-text-trellis2", op: "text-to-3d", prompt: " " })).toThrow();
+ });
+
+ it("writes the still prompt for a clean cut-out", () => {
+ expect(m3d.stillPromptFor3d(" a ceramic teapot... ")).toBe(
+ "a ceramic teapot. A single object, whole and centred, seen from the front at eye level, on a plain light grey background, soft even studio light, no other objects, no text",
+ );
+ });
+ });
diff --cc tests/preset-cards.test.ts
index 62389cc2,bd574bd2..6032b463
--- a/tests/preset-cards.test.ts
+++ b/tests/preset-cards.test.ts
@@@ -1,12 -1,15 +1,19 @@@
import { describe, expect, it, vi } from "vitest";
- import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
- import { previewFor, toPresetCard } from "@/lib/preset-card-data";
+ import { APPS, EFFECTS, getPreset, MOTIONS } from "@/lib/catalog";
+
-// One measured cover (pnpm eval:covers writes this file), for a preset id the catalog doesn't have.
++// One measured cover (pnpm eval:covers writes this file) and one still cover (pnpm eval:covers --from-masters), for preset ids the catalog doesn't have.
+ vi.mock("@/lib/preset-previews.generated", () => ({
- PRESET_PREVIEWS: { "effect-measured-cover": { poster: "/previews/dop/effect-measured-cover.jpg", video: "/previews/dop/effect-measured-cover.mp4", run: "r", engine: "open", model: "oss-wan22-14b", variant: "research" } },
++ PRESET_PREVIEWS: {
++ "effect-measured-cover": { poster: "/previews/dop/effect-measured-cover.jpg", video: "/previews/dop/effect-measured-cover.mp4", run: "r", engine: "open", model: "oss-wan22-14b", variant: "research" },
++ "app-still-cover": { poster: "/previews/presets/app-still-cover.jpg", run: "comfyui-previews-2026-10", engine: "comfyui", model: "ideogram4", variant: "lean-json" },
++ },
+ }));
import {
appFx,
CAMERA_MOVES,
effectFx,
- fallbackPreview,
FX,
++ isCover,
LAYER_BLEED,
layerTransform,
lookHue,
@@@ -15,20 -18,15 +22,15 @@@
PREVIEW_LAYERS,
presetHowTo,
presetRouteLines,
- proceduralPreview,
- previewFor,
++ previewFlip,
searchText,
- toPresetCard,
type CameraMove,
type MoveSpec,
type PreviewLayer,
} from "@/lib/preset-cards";
++import { previewFor, toPresetCard } from "@/lib/preset-card-data";
import type { Preset } from "@/lib/catalog/types";
- // Rendered media here: every effect, and one camera motion. Apps and the other motions have none.
- vi.mock("@/lib/catalog/preview-media.generated.json", async () => {
- const { EFFECTS } = await import("@/lib/catalog");
- return { default: { effects: Object.fromEntries(EFFECTS.map((e) => [e.id, "0123abcd"])), motions: { "motion-crash-zoom-in": "89abcdef" } } };
- });
-
const byName = (list: Preset[], name: string) => {
const p = list.find((x) => x.name === name);
if (!p) throw new Error(`no preset named ${name}`);
@@@ -311,3 -296,13 +300,28 @@@ describe("preset how-to line", () =>
expect(presetHowTo({ type: "app", userPrompt: "none", inputs: [] })).toBe("Press Generate — no inputs needed.");
});
});
+
+ describe("real covers", () => {
+ it("a preset with a measured cover shows that clip and its poster instead of the procedural preview", () => {
+ const measured = previewFor({ id: "effect-measured-cover", type: "effect", name: "Measured", category: "Elements" });
+ expect(measured).toMatchObject({ poster: "/previews/dop/effect-measured-cover.jpg", video: "/previews/dop/effect-measured-cover.mp4" });
+ expect(measured.fx).toBeUndefined();
+ // The others keep their procedural preview.
+ expect(previewFor({ id: "effect-other", type: "effect", name: "Other", category: "Elements" }).video).toBeUndefined();
+ });
++
++ it("a still cover is the card's image: no clip, no move or treatment, never mirrored", () => {
++ const still = previewFor({ id: "app-still-cover", type: "app", name: "Still", category: "Identity" });
++ expect(still).toStrictEqual({ poster: "/previews/presets/app-still-cover.jpg", scene: "portrait" });
++ expect(isCover(still)).toBe(true);
++ // Whatever its id hashes to, a cover is shown as rendered.
++ for (const id of ["app-still-cover", "a", "b", "c", "d", "e", "f"]) expect(previewFlip({ id, preview: still })).toBe(false);
++ });
++
++ it("no procedural preview counts as a cover, and only treatments mirror", () => {
++ const all = [...APPS, ...MOTIONS, ...EFFECTS].map(toPresetCard);
++ for (const c of all) expect(isCover(c.preview), c.id).toBe(false);
++ expect(all.filter((c) => c.preview.move).some((c) => previewFlip(c))).toBe(false);
++ expect(all.filter((c) => c.preview.fx).some((c) => previewFlip(c))).toBe(true);
++ });
+ });
diff --cc tests/preset-covers.test.ts
index 00000000,00000000..cc4960b3
new file mode 100644
--- /dev/null
+++ b/tests/preset-covers.test.ts
@@@ -1,0 -1,0 +1,85 @@@
++import fs from "node:fs";
++import path from "node:path";
++import { describe, expect, it } from "vitest";
++import nextConfig from "../next.config";
++import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
++import { SOUL_LOOK_CARDS } from "@/lib/catalog/soul-looks.generated";
++import { toPresetCard } from "@/lib/preset-card-data";
++import { isCover } from "@/lib/preset-cards";
++import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";
++
++/*
++ * The real covers manifest (src/lib/preset-previews.generated.ts, written by pnpm eval:covers) against the files
++ * in public/previews, unmocked: an entry committed without its files, or files without their entry, fails here
++ * rather than as broken images on the cards. tests/preset-cards.test.ts covers the logic with a mocked manifest.
++ */
++
++const root = process.cwd();
++const entries = Object.entries(PRESET_PREVIEWS);
++
++describe("the preset covers manifest", () => {
++ it("lists catalog presets (or Soul looks) only, in the order the generator writes them", () => {
++ const ids = new Set([...APPS, ...MOTIONS, ...EFFECTS].map((p) => p.id).concat(SOUL_LOOK_CARDS.map((l) => l.id)));
++ const keys = entries.map(([k]) => k);
++ expect(keys).toEqual([...keys].sort((a, b) => a.localeCompare(b)));
++ for (const k of keys) expect(ids.has(k), `${k} is a preset or Soul look`).toBe(true);
++ });
++
++ it("points every entry at a JPEG poster (and an MP4 clip) that exists and isn't empty, with its provenance", () => {
++ for (const [id, e] of entries) {
++ expect(e.poster, id).toMatch(/^\/previews\/[a-z0-9-]+\/[^/]+\.jpg$/);
++ if (e.video !== undefined) expect(e.video, id).toMatch(/^\/previews\/[a-z0-9-]+\/[^/]+\.mp4$/);
++ for (const url of [e.poster, e.video].filter((u): u is string => !!u)) {
++ expect(fs.statSync(path.join(root, "public", url), { throwIfNoEntry: false })?.size, url).toBeGreaterThan(0);
++ }
++ expect(typeof e.run === "string" && e.run.length > 0, `${id} names its run`).toBe(true);
++ expect(typeof e.engine === "string" && e.engine.length > 0, `${id} names its engine`).toBe(true);
++ }
++ });
++
++ it("leaves no cover file in public/previews that no entry names", () => {
++ const named = new Set(entries.flatMap(([, e]) => [e.poster, e.video].filter(Boolean)));
++ const dir = path.join(root, "public", "previews");
++ const files = fs.existsSync(dir) ? fs.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => /\.(jpg|mp4)$/.test(f)) : [];
++ const orphans = files.map((f) => `/previews/${f.replaceAll("\\", "/")}`).filter((u) => !named.has(u));
++ expect(orphans).toEqual([]);
++ });
++
++ it("shows each cover on its card, and keeps the effects gallery's card data under 80 KB with them", () => {
++ for (const p of [...APPS, ...MOTIONS, ...EFFECTS]) {
++ const c = toPresetCard(p);
++ const e = PRESET_PREVIEWS[p.id];
++ expect(isCover(c.preview), p.id).toBe(!!e);
++ if (e) expect([c.preview.poster, c.preview.video], p.id).toEqual([e.poster, e.video]);
++ }
++ expect(JSON.stringify(EFFECTS.map(toPresetCard)).length).toBeLessThan(80_000);
++ });
++
++ it("is read only on the server and in the preset header's own chunk", () => {
++ // Client chunks keep whatever client code uses from a module. preset-cards.ts is in the galleries',
++ // home's, shorts' and mixed media's chunks, so importing the manifest there (or preset-card-data.ts,
++ // which does) would ship it to all of them. A new importer belongs here only if it's a server page
++ // or loaded on its own (next/dynamic), like the preset header.
++ const importers = (spec: RegExp) =>
++ fs
++ .readdirSync(path.join(root, "src"), { recursive: true, encoding: "utf8" })
++ .filter((f) => /\.tsx?$/.test(f) && spec.test(fs.readFileSync(path.join(root, "src", f), "utf8")))
++ .map((f) => f.replaceAll("\\", "/"))
++ .sort();
++ expect(importers(/from "[^"]*preset-previews\.generated"/)).toEqual(["lib/preset-card-data.ts"]);
++ expect(importers(/from "[^"]*preset-card-data"/)).toEqual([
++ "app/(studio)/apps/page.tsx",
++ "app/(studio)/effects/page.tsx",
++ "app/(studio)/motions/page.tsx",
++ "app/(studio)/page.tsx",
++ "components/preset-header.tsx",
++ ]);
++ const header = fs.readFileSync(path.join(root, "src", "components", "studio", "studio-page.tsx"), "utf8");
++ expect(header).toMatch(/dynamic\(\(\) => import\("@\/components\/preset-header"\)/);
++ });
++
++ it("serves the covers with a day's cache, revalidated in the background (their names stay when a cover is made again)", async () => {
++ const rules = await nextConfig.headers!();
++ expect(rules).toContainEqual({ source: "/previews/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=604800" }] });
++ });
++});
diff --cc tests/runtime-auth.test.ts
index b7bd0cc8,6455d5cc..2dfb30de
--- a/tests/runtime-auth.test.ts
+++ b/tests/runtime-auth.test.ts
@@@ -155,8 -155,6 +155,9 @@@ describe("proxy matcher (C13)", () =>
expect(matches("/library")).toBe(true);
expect(matches("/next.svg")).toBe(false);
expect(matches("/samples/demo-model.glb")).toBe(false);
- expect(matches("/previews/effects/effect-set-on-fire.0123abcd.480.avif")).toBe(false);
+ expect(matches("/vendor/meshopt_decoder.js")).toBe(false);
++ expect(matches("/previews/presets/effect-set-on-fire.jpg")).toBe(false);
++ expect(matches("/previews/presets/motion-fpv-drone.mp4")).toBe(false);
expect(matches("/favicon.ico")).toBe(false);
expect(matches("/_next/static/chunks/a.js")).toBe(false);
});
diff --cc tests/shell-logic.test.ts
index 179e3ba9,c396a66e..85eeec73
--- a/tests/shell-logic.test.ts
+++ b/tests/shell-logic.test.ts
@@@ -13,17 -12,17 +12,18 @@@ import
interleaveByCategory,
motionMove,
previewFlip,
- previewFor,
stableHash,
- toPresetCard,
type CameraMove,
} from "@/lib/preset-cards";
-import { createPlaybackStore, MIN_VISIBLE, type PlaybackEnv } from "@/lib/preview-playback";
++import { previewFor, toPresetCard } from "@/lib/preset-card-data";
+import { browserPlaybackEnv, createPlaybackStore, HOVER_INTENT, MIN_VISIBLE, SCROLL_SETTLE, type PlaybackEnv } from "@/lib/preview-playback";
import { pageAfter, progressiveStart, syncProgressive } from "@/lib/progressive";
import { storyboardName } from "@/lib/storyboard-board";
const toasts = vi.hoisted(() => ({ ok: [] as string[], error: [] as string[] }));
vi.mock("sonner", () => ({ toast: Object.assign((m: string) => void toasts.ok.push(m), { error: (m: string) => void toasts.error.push(m) }) }));
- // The procedural previews are what these tests look at: no preset has rendered media here.
- vi.mock("@/lib/catalog/preview-media.generated.json", () => ({ default: {} }));
++// The procedural previews are what these tests look at: no preset has a real cover here.
++vi.mock("@/lib/preset-previews.generated", () => ({ PRESET_PREVIEWS: {} }));
import { capabilityGroup, usedByIndex } from "@/lib/workflow-usage";
describe("workflow 'used by' index", () => {
diff --cc workflows/comfyui/manifest.json
index 00485977,088b9e51..fdbee776
--- a/workflows/comfyui/manifest.json
+++ b/workflows/comfyui/manifest.json
@@@ -10651,59 -10783,271 +10783,271 @@@
}
],
"defaults": {
- "textureSize": 4096
+ "width": 832,
+ "height": 480,
+ "frames": 1000,
+ "steps": 4,
+ "startStep": 2,
+ "audioScale": 1.5,
+ "fps": 25
+ },
+ "limits": {
+ "maxWidth": 1280,
+ "maxHeight": 1280,
+ "dimensionMultiple": 16,
+ "maxFrames": 1000
},
- "limits": {},
"models": [
{
- "file": "moge_2_vitl_normal_fp16.safetensors",
- "folder": "geometry_estimation",
- "url": "https://huggingface.co/Comfy-Org/MoGe/resolve/main/geometry_estimation/moge_2_vitl_normal_fp16.safetensors",
- "sizeGb": 0.66
- },
- {
- "file": "dino_v3_L_naf_fp32.safetensors",
- "folder": "clip_vision",
- "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors",
- "sizeGb": 1.22
+ "file": "Wan2_1-InfiniteTalk_Single_Q8.gguf",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Kijai/WanVideo_comfy_GGUF/resolve/main/InfiniteTalk/Wan2_1-InfiniteTalk_Single_Q8.gguf",
+ "sizeGb": 2.65
},
{
- "file": "pixal3d_int8_convrot.safetensors",
+ "file": "wan2.1-i2v-14b-480p-Q8_0.gguf",
"folder": "diffusion_models",
- "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/diffusion_models/pixal3d_int8_convrot.safetensors",
- "sizeGb": 5.58
+ "url": "https://huggingface.co/city96/Wan2.1-I2V-14B-480P-gguf/resolve/main/wan2.1-i2v-14b-480p-Q8_0.gguf",
+ "sizeGb": 18.14
},
{
- "file": "trellis_2_shape_vae_bf16.safetensors",
+ "file": "Wan2_1_VAE_bf16.safetensors",
"folder": "vae",
- "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",
- "sizeGb": 1.1
+ "url": "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Wan2_1_VAE_bf16.safetensors",
+ "sizeGb": 0.25
},
{
- "file": "trellis_2_texture_vae_bf16.safetensors",
- "folder": "vae",
- "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",
- "sizeGb": 0.95
+ "file": "lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16.safetensors",
+ "sizeGb": 0.74
},
{
- "file": "birefnet.safetensors",
- "folder": "background_removal",
- "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",
- "sizeGb": 0.44
+ "file": "clip_vision_h.safetensors",
+ "folder": "clip_vision",
+ "url": "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/clip_vision/clip_vision_h.safetensors",
+ "sizeGb": 1.26
+ },
+ {
+ "file": "umt5-xxl-enc-bf16.safetensors",
+ "folder": "text_encoders",
+ "url": "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/umt5-xxl-enc-bf16.safetensors",
+ "sizeGb": 11.36
}
],
- "customNodes": [],
- "vramGb": 16,
- "license": "Pixal3D weights, DINOv3-NAF and TRELLIS VAEs as repackaged by Comfy-Org (licence not reviewed yet); MoGe-2 and BiRefNet as in their own entries",
- "validated": true,
- "notes": "Template 3d_pixal3d_trellis2_image_to_model, Pixal3D branch (the default image-to-3D route): MoGe-2 (geometry_estimation/moge_2_vitl_normal_fp16, resolution_level 9) estimates the camera from the cut-out, MoGeGeometryToFOV (horizontal, degrees) -> Pixal3DConditioning (camera_angle_x) with the DINOv3 encoder, UNet pixal3d_int8_convrot; ImageCropToMask pad_factor 1.1 (as the node asks for Pixal3D). BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23 (RTX 5090, the same graph run end to end): 114-185 s per object, 25-35 MB raw GLB at ~250k triangles (was 8M triangles / 317 MB before the decimate step), web GLB 1.6-3.6 MB; more faithful to the photo than TRELLIS.2 (209-238 s). The origin is the camera-aligned volume centre, hence the pivot fix. Surfaces can show faint planar facets from the shape decode (no graph setting removes them)."
- },
+ "customNodes": [
+ {
+ "name": "ComfyUI-KJNodes",
+ "repo": "https://github.com/kijai/ComfyUI-KJNodes"
+ },
+ {
+ "name": "ComfyUI-VideoHelperSuite",
+ "repo": "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite"
+ },
+ {
+ "name": "ComfyUI-WanVideoWrapper",
+ "repo": "https://github.com/kijai/ComfyUI-WanVideoWrapper"
+ }
+ ],
+ "vramGb": 24,
+ "license": "Apache-2.0 (Wan 2.1, InfiniteTalk, lightx2v)",
+ "validated": true,
+ "notes": "Same model files as infinitetalk-wanwrapper (no new download). The source frames are VAE-encoded and only the last steps are re-denoised (steps 4, startStep 2), so camera, background and body stay; mouth, head and upper body follow the new audio. 81-frame windows until the audio ends. Changed from the research graph: VHS_LoadVideo gets only custom_width (height 0 keeps the source's proportions, no squashing) and ImageResizeKJv2 crops to width x height, which the provider takes from the source's own shape (aspect ratio \"auto\", read from the MP4 header) at the chosen resolution; frames (num_frames and VHS frame_load_cap) = the voice's length at 25 fps, at most 1000 (40 s): the provider refuses a longer voice instead of cutting it. Pass the clean dubbed voice, then mux the background with video-mux-audio.",
+ "autoDownloads": [
+ "DownloadAndLoadWav2VecModel fetches TencentGameMate/chinese-wav2vec2-base (0.38 GB) on first run"
+ ]
+ },
{
- "id": "image-to-3d-trellis2",
- "title": "Image to textured 3D (TRELLIS.2, PBR GLB, ~250k triangles; fallback to Pixal3D)",
+ "id": "lipsync-latentsync16",
+ "title": "Lip re-sync, mouth only: LatentSync 1.6 (isolated worker)",
+ "capability": "lipsync",
+ "file": "lipsync-latentsync16.json",
+ "source": "hand-built (scripts/comfy/hand-built/lipsync-latentsync16.json)",
+ "bindings": {
+ "video": [
+ {
+ "node": "1",
+ "input": "video"
+ }
+ ],
+ "audio": [
+ {
+ "node": "2",
+ "input": "audio"
+ }
+ ],
+ "lengthMode": [
+ {
+ "node": "3",
+ "input": "mode"
+ }
+ ],
+ "seed": [
+ {
+ "node": "4",
+ "input": "seed"
+ }
+ ],
+ "lipsExpression": [
+ {
+ "node": "4",
+ "input": "lips_expression"
+ }
+ ],
+ "steps": [
+ {
+ "node": "4",
+ "input": "inference_steps"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "5",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "5",
+ "kind": "video"
+ }
+ ],
+ "defaults": {
+ "steps": 20,
+ "lipsExpression": 1.5,
+ "lengthMode": "loop_to_audio"
+ },
+ "limits": {},
+ "models": [],
+ "customNodes": [
+ {
+ "name": "ComfyUI-LatentSyncWrapper",
+ "repo": "https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper"
+ },
+ {
+ "name": "ComfyUI-VideoHelperSuite",
+ "repo": "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite"
+ }
+ ],
+ "vramGb": 20,
+ "license": "LatentSync 1.6 weights CreativeML OpenRAIL++-M (commercial use with use-based restrictions); wrapper code has no LICENSE file",
+ "validated": true,
+ "notes": "Re-renders only the mouth (512x512 face crop): identity, background and camera are untouched. VideoLengthAdjuster: normal (pad audio, trim video), pingpong / loop_to_audio (extend the picture when the dub is longer). 25 fps; needs a visible, mostly frontal face. ISOLATED WORKER: at import the wrapper overrides TMPDIR and folder_paths temp handling for the whole process, rmtree()s a temp folder next to ComfyUI and pip-installs packages at node init, so run it on a separate ComfyUI (scripts/comfy/README.md).",
+ "autoDownloads": [
+ "LatentSyncNode snapshot_downloads ByteDance/LatentSync-1.6 (latentsync_unet.pt 5.07 GB, whisper/tiny.pt 0.08 GB), stabilityai/sd-vae-ft-mse (0.33 GB) and the s3fd face detector (0.09 GB) on first run"
+ ],
+ "worker": "isolated"
+ },
+ {
+ "id": "video-mux-audio",
+ "title": "Add a soundtrack: new voice + background stem mixed onto a video (picture stream-copied)",
+ "capability": "mux",
+ "file": "video-mux-audio.json",
+ "source": "hand-built (scripts/comfy/hand-built/video-mux-audio.json)",
+ "bindings": {
+ "video": [
+ {
+ "node": "1",
+ "input": "file"
+ }
+ ],
+ "audio": [
+ {
+ "node": "3",
+ "input": "audio"
+ }
+ ],
+ "audio2": [
+ {
+ "node": "4",
+ "input": "audio"
+ }
+ ],
+ "backgroundVolumeDb": [
+ {
+ "node": "5",
+ "input": "volume"
+ }
+ ],
+ "duration": [
+ {
+ "node": "9",
+ "input": "duration"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "8",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "8",
+ "kind": "video"
+ }
+ ],
+ "defaults": {
+ "duration": 60,
+ "backgroundVolumeDb": 0
+ },
+ "limits": {},
+ "models": [],
+ "customNodes": [],
+ "vramGb": 0,
+ "license": "n/a (no model)",
+ "validated": true,
+ "notes": "audio = the new voice (Chatterbox dub, narration), audio2 = the background stem of dub-prepare-separate-transcribe or a music bed (backgroundVolumeDb, e.g. -12 under narration). Both are mixed over EmptyAudio of the video's length (duration: the provider reads it from the MP4 header), because AudioMerge cuts audio2 to audio1's length. Concatenate Video with complete_audio copies the video stream packet by packet (no decode, no re-encode: lossless, constant memory) and encodes only the new AAC soundtrack. Video length is unchanged. Without audio2 the provider uses video-mux-audio-replace. Runs on CPU (verified end to end through Fuobe; +0.02 GB RAM for a 900-frame clip)."
+ },
+ {
+ "id": "video-mux-audio-replace",
+ "title": "Replace a video's soundtrack with one audio track",
+ "capability": "mux",
+ "file": "video-mux-audio-replace.json",
+ "source": "hand-built (scripts/comfy/hand-built/video-mux-audio-replace.json)",
+ "bindings": {
+ "video": [
+ {
+ "node": "1",
+ "input": "file"
+ }
+ ],
+ "audio": [
+ {
+ "node": "3",
+ "input": "audio"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "8",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "8",
+ "kind": "video"
+ }
+ ],
+ "defaults": {},
+ "limits": {},
+ "models": [],
+ "customNodes": [],
+ "vramGb": 0,
+ "license": "n/a (no model)",
+ "validated": true,
+ "notes": "LoadVideo + LoadAudio -> Concatenate Video (complete_audio) -> SaveVideo: the picture is stream-copied, only the new soundtrack is encoded. The single-track variant of video-mux-audio (voice-over, narration, music). A soundtrack longer than the video is cut at the video's end. Runs on CPU (verified end to end through Fuobe)."
+ },
+ {
- "id": "image-to-3d-trellis2",
- "title": "Image to textured 3D (TRELLIS.2, PBR GLB) + a 36-view turntable video",
++ "id": "image-to-3d-pixal3d",
++ "title": "Image to textured 3D (Pixal3D, PBR GLB, ~250k triangles)",
"capability": "image-to-3d",
-- "file": "image-to-3d-trellis2.json",
-- "source": "hand-built (scripts/comfy/hand-built/image-to-3d-trellis2.json)",
++ "file": "image-to-3d-pixal3d.json",
++ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-pixal3d.json)",
"bindings": {
"image": [
{
@@@ -10739,79 -11089,228 +11083,316 @@@
{
"node": "322",
"input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "322",
+ "kind": "model3d"
+ }
+ ],
+ "defaults": {
+ "textureSize": 4096
+ },
+ "limits": {},
+ "models": [
++ {
++ "file": "moge_2_vitl_normal_fp16.safetensors",
++ "folder": "geometry_estimation",
++ "url": "https://huggingface.co/Comfy-Org/MoGe/resolve/main/geometry_estimation/moge_2_vitl_normal_fp16.safetensors",
++ "sizeGb": 0.66
++ },
+ {
+ "file": "dino_v3_L_naf_fp32.safetensors",
+ "folder": "clip_vision",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors",
+ "sizeGb": 1.22
+ },
+ {
- "file": "trellis_2_int8_convrot.safetensors",
++ "file": "pixal3d_int8_convrot.safetensors",
+ "folder": "diffusion_models",
- "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/diffusion_models/trellis_2_int8_convrot.safetensors",
- "sizeGb": 5.25
++ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/diffusion_models/pixal3d_int8_convrot.safetensors",
++ "sizeGb": 5.58
+ },
+ {
+ "file": "trellis_2_shape_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",
+ "sizeGb": 1.1
+ },
+ {
+ "file": "trellis_2_texture_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",
+ "sizeGb": 0.95
+ },
+ {
+ "file": "birefnet.safetensors",
+ "folder": "background_removal",
+ "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",
+ "sizeGb": 0.44
+ }
+ ],
+ "customNodes": [],
+ "vramGb": 16,
- "license": "MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet)",
++ "license": "MIT (Pixal3D weights by TencentARC, as the multi-view weights; TRELLIS.2 VAEs as repackaged by Comfy-Org, BiRefNet, microsoft/MoGe 2); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License (royalty-free, commercial use allowed; the app must show a \"Built with DINOv3\" notice)",
+ "validated": true,
- "notes": "Template 3d_pixal3d_trellis2_image_to_model, TRELLIS.2 branch (the fallback image-to-3D route; Pixal3D is the default): Trellis2Conditioning with the DINOv3 encoder, UNet trellis_2_int8_convrot; ImageCropToMask pad_factor 1.0. BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23: 209-238 s, 28-43 MB raw GLB at ~250k triangles. The 36-view RotateMesh + RenderMesh turntable (unlit, aliased, 12 fps) was removed."
++ "notes": "Template 3d_pixal3d_trellis2_image_to_model, Pixal3D branch (the default image-to-3D route): MoGe-2 (geometry_estimation/moge_2_vitl_normal_fp16, resolution_level 9) estimates the camera from the cut-out, MoGeGeometryToFOV (horizontal, degrees) -> Pixal3DConditioning (camera_angle_x) with the DINOv3 encoder, UNet pixal3d_int8_convrot; ImageCropToMask pad_factor 1.1 (as the node asks for Pixal3D). BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23 (RTX 5090, the same graph run end to end): 114-185 s per object, 25-35 MB raw GLB at ~250k triangles (was 8M triangles / 317 MB before the decimate step), web GLB 1.6-3.6 MB; more faithful to the photo than TRELLIS.2 (209-238 s). The origin is the camera-aligned volume centre, hence the pivot fix. Surfaces can show faint planar facets from the shape decode (no graph setting removes them)."
+ },
+ {
- "id": "image-to-3d-hunyuan3d-21",
- "title": "Image to 3D shape: Hunyuan3D 2.1 (native, untextured GLB; territory-restricted licence)",
++ "id": "image-to-3d-trellis2",
++ "title": "Image to textured 3D (TRELLIS.2, PBR GLB, ~250k triangles; fallback to Pixal3D)",
+ "capability": "image-to-3d",
- "file": "image-to-3d-hunyuan3d-21.json",
- "source": "hand-built (scripts/comfy/hand-built/image-to-3d-hunyuan3d-21.json)",
++ "file": "image-to-3d-trellis2.json",
++ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-trellis2.json)",
+ "bindings": {
+ "image": [
+ {
- "node": "2",
++ "node": "122",
+ "input": "image"
+ }
+ ],
+ "seed": [
+ {
- "node": "7",
++ "node": "3",
++ "input": "seed"
+ },
+ {
- "node": "702",
++ "node": "12",
++ "input": "seed"
++ },
++ {
++ "node": "18",
++ "input": "seed"
++ },
++ {
++ "node": "23",
+ "input": "seed"
+ }
+ ],
- "steps": [
++ "textureSize": [
+ {
- "node": "7",
++ "node": "288",
++ "input": "value"
++ }
++ ],
++ "filenamePrefix": [
++ {
++ "node": "322",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "322",
+ "kind": "model3d"
- },
- {
- "node": "702",
- "kind": "video",
- "role": "turntable"
+ }
+ ],
+ "defaults": {
- "textureSize": 4096,
- "turntableFps": 12
++ "textureSize": 4096
+ },
+ "limits": {},
+ "models": [
+ {
+ "file": "dino_v3_L_naf_fp32.safetensors",
+ "folder": "clip_vision",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors",
+ "sizeGb": 1.22
+ },
+ {
+ "file": "trellis_2_int8_convrot.safetensors",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/diffusion_models/trellis_2_int8_convrot.safetensors",
+ "sizeGb": 5.25
+ },
+ {
+ "file": "trellis_2_shape_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",
+ "sizeGb": 1.1
+ },
+ {
+ "file": "trellis_2_texture_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",
+ "sizeGb": 0.95
+ },
+ {
+ "file": "birefnet.safetensors",
+ "folder": "background_removal",
+ "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",
+ "sizeGb": 0.44
+ }
+ ],
+ "customNodes": [],
+ "vramGb": 16,
+ "license": "MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License (royalty-free, commercial use allowed; the app must show a \"Built with DINOv3\" notice)",
+ "validated": true,
- "notes": "Template 3d_pixal3d_trellis2_image_to_model: BiRefNet cut-out -> crop to mask -> TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB (Save3DAdvanced, history ui \"3d\"). The graph adds a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps."
++ "notes": "Template 3d_pixal3d_trellis2_image_to_model, TRELLIS.2 branch (the fallback image-to-3D route; Pixal3D is the default): Trellis2Conditioning with the DINOv3 encoder, UNet trellis_2_int8_convrot; ImageCropToMask pad_factor 1.0. BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23: 209-238 s, 28-43 MB raw GLB at ~250k triangles. The 36-view RotateMesh + RenderMesh turntable (unlit, aliased, 12 fps) was removed."
+ },
+ {
+ "id": "image-to-3d-trellis2-multiview",
+ "title": "Photos of 2-4 sides to textured 3D (Pixal3D multi-view on TRELLIS.2, PBR GLB) + a 36-view turntable video",
+ "capability": "image-to-3d",
+ "file": "image-to-3d-trellis2-multiview.json",
+ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-trellis2-multiview.json)",
+ "bindings": {
+ "image": [
+ {
+ "node": "360",
+ "input": "image"
+ }
+ ],
+ "image2": [
+ {
+ "node": "361",
+ "input": "image"
+ }
+ ],
+ "image3": [
+ {
+ "node": "362",
+ "input": "image"
+ }
+ ],
+ "image4": [
+ {
+ "node": "363",
+ "input": "image"
+ }
+ ],
+ "seed": [
+ {
+ "node": "3",
+ "input": "seed"
+ },
+ {
+ "node": "12",
+ "input": "seed"
+ },
+ {
+ "node": "18",
+ "input": "seed"
+ },
+ {
+ "node": "23",
+ "input": "seed"
+ }
+ ],
+ "textureSize": [
+ {
+ "node": "288",
+ "input": "value"
+ }
+ ],
+ "turntableFps": [
+ {
+ "node": "701",
+ "input": "fps"
+ }
+ ],
+ "fovX": [
+ {
+ "node": "381",
+ "input": "fov_x_degrees"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "372",
+ "input": "filename_prefix"
+ },
+ {
+ "node": "702",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "372",
+ "kind": "model3d"
+ },
+ {
+ "node": "702",
+ "kind": "video",
+ "role": "turntable"
+ }
+ ],
+ "defaults": {
+ "textureSize": 4096,
+ "turntableFps": 12,
+ "fovX": 0
+ },
+ "limits": {},
+ "models": [
+ {
+ "file": "dino_v3_L_naf_fp32.safetensors",
+ "folder": "clip_vision",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors",
+ "sizeGb": 1.22
+ },
+ {
+ "file": "trellis_2_shape_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",
+ "sizeGb": 1.1
+ },
+ {
+ "file": "trellis_2_texture_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",
+ "sizeGb": 0.95
+ },
+ {
+ "file": "birefnet.safetensors",
+ "folder": "background_removal",
+ "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",
+ "sizeGb": 0.44
+ },
+ {
+ "file": "pixal3d_multiview_int8_convrot.safetensors",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/diffusion_models/pixal3d_multiview_int8_convrot.safetensors",
+ "sizeGb": 5.58
+ },
+ {
+ "file": "moge_2_vitl_normal_fp16.safetensors",
+ "folder": "geometry_estimation",
+ "url": "https://huggingface.co/Comfy-Org/MoGe/resolve/main/geometry_estimation/moge_2_vitl_normal_fp16.safetensors",
+ "sizeGb": 0.66
+ }
+ ],
+ "customNodes": [],
+ "vramGb": 16,
+ "license": "MIT (Pixal3D multi-view weights by TencentARC, TRELLIS.2 VAEs as repackaged by Comfy-Org, BiRefNet, microsoft/MoGe 2); the dino_v3_L_naf image encoder is DINOv3 ViT-L under the DINOv3 License (royalty-free, commercial use allowed; the app must show a \"Built with DINOv3\" notice)",
+ "validated": true,
- "notes": "Template 3d_pixal3d_multi_views (2026-09-09) with the turnaround-sheet loader and its crops replaced by one upload per side: image = front, image2 = left, image3 = back, image4 = right (Pixal3DMultiViewConditioning, a fixed orbit rig 90 degrees apart, Z up: the left view is the object's own left, the camera at +90 degrees azimuth from the front, i.e. the photographer walks to their right; every side but the front is optional and the provider drops the branch of a side with no photo). Each side: BiRefNet cut-out -> crop to mask (1024, pad 1.1) -> the view. Then TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) on Pixal3D multi-view -> decimate to 700k faces -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB. The same 36-view turntable as image-to-3d-trellis2. The views' horizontal field of view as framed (Pixal3DMultiViewConditioning.fov) is measured on the front crop: MoGe 2 (LoadMoGeModel -> MoGeInference -> MoGeGeometryToFOV, horizontal, degrees), as the node's tooltip says for photos and as the official single-view template 3d_pixal3d_trellis2_image_to_model feeds Pixal3DConditioning; the multi-view template keeps the rig value 20, which suits rendered turnaround sheets but not phone photos, whose crops are usually wider. fovX (degrees, 0 = estimate, the default) fixes MoGe's lens instead, so MoGeGeometryToFOV passes it on (20 for a generated turnaround sheet). Weights: pixal3d_multiview_int8_convrot 5.58 GB + moge_2_vitl_normal_fp16 0.66 GB + the TRELLIS.2 VAEs, DINOv3-NAF and BiRefNet the single-view graph already uses. VRAM unverified (as the single-view graph: 16 GB). Validated by /prompt only."
++ "notes": "Template 3d_pixal3d_multi_views (2026-09-09) with the turnaround-sheet loader and its crops replaced by one upload per side: image = front, image2 = left, image3 = back, image4 = right (Pixal3DMultiViewConditioning, a fixed orbit rig 90 degrees apart, Z up: the left view is the object's own left, the camera at +90 degrees azimuth from the front, i.e. the photographer walks to their right; every side but the front is optional and the provider drops the branch of a side with no photo). Each side: BiRefNet cut-out -> crop to mask (1024, pad 1.1) -> the view. Then TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) on Pixal3D multi-view -> decimate to 700k faces -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB, plus a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps; the Fuobe server then finishes the GLB (web GLB as meta.web) and, when Chromium and ffmpeg are there, replaces that turntable with its CPU render (src/server/model3d-finish.ts). The views' horizontal field of view as framed (Pixal3DMultiViewConditioning.fov) is measured on the front crop: MoGe 2 (LoadMoGeModel -> MoGeInference -> MoGeGeometryToFOV, horizontal, degrees), as the node's tooltip says for photos and as the official single-view template 3d_pixal3d_trellis2_image_to_model feeds Pixal3DConditioning; the multi-view template keeps the rig value 20, which suits rendered turnaround sheets but not phone photos, whose crops are usually wider. fovX (degrees, 0 = estimate, the default) fixes MoGe's lens instead, so MoGeGeometryToFOV passes it on (20 for a generated turnaround sheet). Weights: pixal3d_multiview_int8_convrot 5.58 GB + moge_2_vitl_normal_fp16 0.66 GB + the TRELLIS.2 VAEs, DINOv3-NAF and BiRefNet the single-view graph already uses. VRAM unverified (as the single-view graph: 16 GB). Validated by /prompt only."
+ },
+ {
+ "id": "image-to-3d-hunyuan3d-21",
+ "title": "Image to 3D shape: Hunyuan3D 2.1 (native, untextured GLB; territory-restricted licence)",
+ "capability": "image-to-3d",
+ "file": "image-to-3d-hunyuan3d-21.json",
+ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-hunyuan3d-21.json)",
+ "bindings": {
+ "image": [
+ {
+ "node": "2",
+ "input": "image"
+ }
+ ],
+ "seed": [
+ {
+ "node": "7",
+ "input": "seed"
+ }
+ ],
+ "steps": [
+ {
+ "node": "7",
"input": "steps"
}
],
diff --cc workflows/comfyui/object_info.subset.json
index dc0e0fc0,5bd8b3cc..0d46c6fa
--- a/workflows/comfyui/object_info.subset.json
+++ b/workflows/comfyui/object_info.subset.json
@@@ -11341,46 -12100,139 +12100,207 @@@
"essentials_category": null,
"has_intermediate_output": false
},
- "PreviewAny": {
++ "Pixal3DConditioning": {
+ "input": {
+ "required": {
- "source": [
- "*",
- {}
++ "clip_vision_model": [
++ "CLIP_VISION",
++ {
++ "tooltip": "DINOv3 ViT-L/16 ClipVision."
++ }
++ ],
++ "image": [
++ "IMAGE",
++ {
++ "tooltip": "Preprocessed image from ImageCropToMask (pad_factor=1.1 for Pixal3D)."
++ }
++ ],
++ "camera_angle_x": [
++ "FLOAT",
++ {
++ "display_name": "fov",
++ "tooltip": "Horizontal FOV in degrees. Wire a MoGeGeometryToFOV (axis='horizontal', unit='degrees') for a per-image FoV (matches upstream default).",
++ "default": 49.13,
++ "min": 1,
++ "max": 170,
++ "step": 0.01
++ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
- "source"
++ "clip_vision_model",
++ "image",
++ "camera_angle_x"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
- "STRING"
++ "CONDITIONING",
++ "CONDITIONING"
+ ],
+ "output_is_list": [
++ false,
+ false
+ ],
+ "output_name": [
- "STRING"
++ "positive",
++ "negative"
+ ],
- "name": "PreviewAny",
- "display_name": "Preview as Text",
- "description": "Preview any input value as text.",
- "python_module": "comfy_extras.nodes_preview_any",
- "category": "utilities",
- "output_node": true,
- "has_intermediate_output": false,
- "search_aliases": [
- "preview",
- "preview text",
- "show output",
- "inspect",
- "debug",
- "print value",
- "show text"
- ]
++ "output_tooltips": [
++ null,
++ null
++ ],
++ "output_matchtypes": null,
++ "name": "Pixal3DConditioning",
++ "display_name": "Pixal3D Conditioning",
++ "description": "",
++ "python_module": "comfy_extras.nodes_trellis2",
++ "category": "model/conditioning/trellis",
++ "output_node": false,
++ "deprecated": false,
++ "experimental": false,
++ "dev_only": false,
++ "api_node": false,
++ "price_badge": null,
++ "search_aliases": null,
++ "essentials_category": null,
++ "has_intermediate_output": false
++ },
+ "Pixal3DMultiViewConditioning": {
+ "input": {
+ "required": {
+ "clip_vision_model": [
+ "CLIP_VISION",
+ {
+ "tooltip": "DINOv3 ViT-L/16 ClipVision with bundled NAF weights."
+ }
+ ],
+ "fov": [
+ "FLOAT",
+ {
+ "tooltip": "Horizontal FOV in degrees of the views as framed: 20 for rig renders and most multi-view generators, or MoGeGeometryToFOV on one of the views for photos.",
+ "default": 20,
+ "min": 1,
+ "max": 170,
+ "step": 0.01,
+ "round": false
+ }
+ ]
+ },
+ "optional": {
+ "front": [
+ "IMAGE",
+ {
+ "tooltip": "Square view of the object's front side, with alpha or on a black background, framed like the rig: the object spans about 1/1.1 of the frame at its widest, the same scale in every view. The first connected view (front, left, back, right order) is the front the mesh is posed to."
+ }
+ ],
+ "left": [
+ "IMAGE",
+ {
+ "tooltip": "Square view of the object's left side, with alpha or on a black background, framed like the rig: the object spans about 1/1.1 of the frame at its widest, the same scale in every view. The first connected view (front, left, back, right order) is the front the mesh is posed to."
+ }
+ ],
+ "back": [
+ "IMAGE",
+ {
+ "tooltip": "Square view of the object's back side, with alpha or on a black background, framed like the rig: the object spans about 1/1.1 of the frame at its widest, the same scale in every view. The first connected view (front, left, back, right order) is the front the mesh is posed to."
+ }
+ ],
+ "right": [
+ "IMAGE",
+ {
+ "tooltip": "Square view of the object's right side, with alpha or on a black background, framed like the rig: the object spans about 1/1.1 of the frame at its widest, the same scale in every view. The first connected view (front, left, back, right order) is the front the mesh is posed to."
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "clip_vision_model",
+ "fov"
+ ],
+ "optional": [
+ "front",
+ "left",
+ "back",
+ "right"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "CONDITIONING",
+ "CONDITIONING"
+ ],
+ "output_is_list": [
+ false,
+ false
+ ],
+ "output_name": [
+ "positive",
+ "negative"
+ ],
+ "output_tooltips": [
+ null,
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "Pixal3DMultiViewConditioning",
+ "display_name": "Pixal3D Multi-View Conditioning",
+ "description": "",
+ "python_module": "comfy_extras.nodes_trellis2",
+ "category": "model/conditioning/trellis",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
+ "PreviewAny": {
+ "input": {
+ "required": {
+ "source": [
+ "*",
+ {}
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "source"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "STRING"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "STRING"
+ ],
+ "name": "PreviewAny",
+ "display_name": "Preview as Text",
+ "description": "Preview any input value as text.",
+ "python_module": "comfy_extras.nodes_preview_any",
+ "category": "utilities",
+ "output_node": true,
+ "has_intermediate_output": false,
+ "search_aliases": [
+ "preview",
+ "preview text",
+ "show output",
+ "inspect",
+ "debug",
+ "print value",
+ "show text"
+ ]
},
"PrimitiveBoolean": {
"input": {