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.

Split soundtrack: a visitor's price check never calls a GPU

Claudeeda169f5d03c
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4e1fddb2..3efa7168 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -140,7 +140,7 @@ Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and
- **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`).
- **Round 5 part 1: route settings, LoRA slots, voices, product shots.** `submit()` puts a route's `extra` under the run's own `params.extra` (Fuobe Speak's `SPEAK_GRAPH` on `infinitetalk-wanwrapper`: 15 motion frames, 25 steps, shift 10, cfg 5, audio cfg 5, `unipc`, colour match `reinhard`). A route with `loraSlot` puts the run's one LoRA in a wrapper graph's own LoRA loader (Fuobe Speak's FusioniX in kijai's `WanVideoLoraSelect`); another route on that graph (InfiniteTalk Long) still refuses a LoRA. A talking avatar, like a lip re-sync, renders as long as its voice (`params.sourceDuration`, else the voice's header) up to the graph's frame cap, 1000 frames (40 s) on the wrapper graph, and a longer voice is refused, not cut (InfiniteTalk Long, on the same graph, used to stop at the graph's 500-frame default, 20 s). Fuobe Marketing Image's Standalone shot (`params.extra.productShot` with exactly one photo) moves from `qwen-image-edit-2511-multi` to `product-shot-qwen-edit-2509` (`PRODUCT_SHOT_GRAPH`). `injectLoras` (`src/lib/comfy.ts`) no longer adds a LoRA the graph already loads, for every graph.
- **Round 5 part 1 (fixes-5): reachability shared with Ollama.** The busy-vs-down rules above moved to `src/server/providers/reach.ts` (`hostPort`, `takesConnection`, `ask`, `checkReach`, `sharedCheck`, `reachSync`), which Ollama's check now uses too (see LLM provider). `REACH` is exported from there, and one map of running checks (`globalThis.__fuobeReachChecks`) replaces `__fuobeComfyProbe`; `probeComfy` and `probeComfySync` keep their behaviour (`tests/comfy-reach.test.ts`).
- - **Round 5 part 2: soundtrack splits and asked sizes.** On `separate-soundtrack-dbs`, `prepareWorkflow()` binds `separationModel` to the model asked for, else the host's pick (`dbsModelFor` in `src/lib/av/split.ts`: DBS-TIGER on a CUDA device, DBS-BSRNN on a CPU, the other one when the pick isn't on disk). The device comes from `/system_stats` (`comfyDevice`, kept a minute) and the models on disk from `GET /models/dbs`, which ComfyUI-DBS registers (`comfyDbsModels`, read fresh at submit); a model that isn't there is refused in words, never sent. `channels` is mono or each channel (`dbsChannelsFor`), and a source with more than 2 channels (the header's count, else `params.extra.sourceChannels`) is split in mono with a mono Music & effects (`dbsSurroundBed`), because ComfyUI saves at most 2 channels. A canvas the request names (`params.extra.width` / `height`: a layout's, Soul's exact sizes) is fitted to the graph's grid and maximum side with its shape kept (`fitCanvas` in `src/lib/comfy.ts`), as the cloud's `sizeValue` fits it, so both engines render one size. Upload headers carry the channel count (`MediaInfo.channels`: WAV, FLAC, MP3 and an MP4 / MOV's first sound track in `src/lib/media-probe.ts`; WebM / Matroska in `src/server/webm-probe.ts`). The manifest's outputs gain the stems `music` and `effects` and the role `report` (a node's own account of the run).
+ - **Round 5 part 2: soundtrack splits and asked sizes.** On `separate-soundtrack-dbs`, `prepareWorkflow()` binds `separationModel` to the model asked for, else the host's pick (`dbsModelFor` in `src/lib/av/split.ts`: DBS-TIGER on a CUDA device, DBS-BSRNN on a CPU, the other one when the pick isn't on disk). The device comes from `/system_stats` (`comfyDevice`, kept a minute) and the models on disk from `GET /models/dbs`, which ComfyUI-DBS registers (`comfyDbsModels`, read fresh at submit; callers that arrive while either request is on its way share it); a model that isn't there is refused in words, never sent. `channels` is mono or each channel (`dbsChannelsFor`), and a source with more than 2 channels (the header's count, else `params.extra.sourceChannels`) is split in mono with a mono Music & effects (`dbsSurroundBed`), because ComfyUI saves at most 2 channels. A canvas the request names (`params.extra.width` / `height`: a layout's, Soul's exact sizes) is fitted to the graph's grid and maximum side with its shape kept (`fitCanvas` in `src/lib/comfy.ts`), as the cloud's `sizeValue` fits it, so both engines render one size. Upload headers carry the channel count (`MediaInfo.channels`: WAV, FLAC, MP3 and an MP4 / MOV's first sound track in `src/lib/media-probe.ts`; WebM / Matroska in `src/server/webm-probe.ts`). The manifest's outputs gain the stems `music` and `effects` and the role `report` (a node's own account of the run).
- **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. 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. Since round 5 part 1 a `face-mosaic` job returns a demo picture with no masks. Since round 5 part 2 a `separate-audio` job on `separate-soundtrack-dbs` returns four stems (voice, music, effects and background, voice first). A request with `demo: true` (a skill's free dry run) goes to this provider whatever Settings → Demo mode says (see Pipelines).
@@ -382,7 +382,7 @@ Each studio keeps its data and pure planner in `src/lib/`, its server module in
| **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, which since round 5 part 1 includes the Original restyle steps of `planFuobeRestyle`, the Soul-look first frame and the partner cloud restyle steps), 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); since round 5 part 1 SDR to HDR (`ltx-2-3-hdr`) switches to `fal-ai/ltx-2.3-quality/hdr/lora` when the run carries LoRAs (up to 3) | 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, Split soundtrack** (`/audio/loop`, `/audio/join`, since round 5 part 2 `/audio/split`) | `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); since round 5 part 2 (DBS D1) `lib/av/split.ts`: `planSplit` (one job on `oss-dbs-separate`, open engine only: DBS is hosted nowhere and the owner chose no stand-in model, so the cloud engine says so, `CLOUD_SPLIT_PROBLEM`), `planRemux` (a mix put back on its video: `oss-mux`, or fal's `merge-audio-video` in the cloud), the host's pick and time (`hostPick`, `splitTime` from measured CPU speeds), the mixer's maths (Dialogue, Music, Effects and Music & effects; levels −24 to +6 dB, solo, mute, five `PRESETS`) and Export mix's 16-bit WAV in 16 MB parts up to 2 GiB (`mixPlan`, `mixPart`) | `audio-tools.ts`: each clip's length read from its own header, the plan priced step by step, one `createPipeline` run; since round 5 part 2 the tools `split` (refused on an install set to paid APIs only, and for a file whose header says it has no sound; its preview adds the host's device, the DBS models on its disk, its pick and the time, and refuses a model the host doesn't have) and `remux`, with headers read through main's `storedMedia` (`storage.ts`: only the header, cached by the file, and in a visitor's price check only the visitor's own files; Split soundtrack also asks it for WebM and AVI headers, `otherHeaderInfo` in `media-facts.ts`), never whole, so files over 2 GiB work; `mix-export.ts` (`receiveMixPart`) appends Export mix's parts to a scratch file without holding the mix in memory and turns the last part into an upload in the Library. The export route skips the sign-in proxy, which holds 4 MB of a body at most: like main's routes that take a file, it runs the proxy's checks itself (`gateAsProxy`) and reads no more than a part (`readBodyWithin`) | `POST /api/audio-tools` (`?preview=1` plans and prices; tools `split` and `remux` since round 5 part 2), `POST /api/audio-tools/export` (round 5 part 2: a part as the body, `?offset=`, `&id=` from the first part's answer, `&last=1&name=` on the last, which answers 201 with the asset) | `components/audio-tools/*` (since round 5 part 2 `split-tool.tsx`: the split, the mixer, Your splits, Export mix, Put back on the video); any audio result gets "Loop / extend" and, since round 5 part 2, "Split soundtrack", as does a clip, and a clip made with its sound (`v2a`, `mux`, `lipsync`, `trim`, `captions`) offers Split soundtrack instead of Add sound as a next step (`SOUNDED_VIDEO_OPS` in `output-actions.ts`) |
+| **Audio hub: Loop / extend, Join, Split soundtrack** (`/audio/loop`, `/audio/join`, since round 5 part 2 `/audio/split`) | `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); since round 5 part 2 (DBS D1) `lib/av/split.ts`: `planSplit` (one job on `oss-dbs-separate`, open engine only: DBS is hosted nowhere and the owner chose no stand-in model, so the cloud engine says so, `CLOUD_SPLIT_PROBLEM`), `planRemux` (a mix put back on its video: `oss-mux`, or fal's `merge-audio-video` in the cloud), the host's pick and time (`hostPick`, `splitTime` from measured CPU speeds), the mixer's maths (Dialogue, Music, Effects and Music & effects; levels −24 to +6 dB, solo, mute, five `PRESETS`) and Export mix's 16-bit WAV in 16 MB parts up to 2 GiB (`mixPlan`, `mixPart`) | `audio-tools.ts`: each clip's length read from its own header, the plan priced step by step, one `createPipeline` run; since round 5 part 2 the tools `split` (refused on an install set to paid APIs only, and for a file whose header says it has no sound; its preview adds the host's device, the DBS models on its disk, its pick and the time, and refuses a model the host doesn't have; a visitor's preview calls no GPU: an account's device is what its last status check read, `lastGpuDevice` in `account-gpu.ts`, and its run checks the models) and `remux`, with headers read through main's `storedMedia` (`storage.ts`: only the header, cached by the file, and in a visitor's price check only the visitor's own files; Split soundtrack also asks it for WebM and AVI headers, `otherHeaderInfo` in `media-facts.ts`), never whole, so files over 2 GiB work; `mix-export.ts` (`receiveMixPart`) appends Export mix's parts to a scratch file without holding the mix in memory and turns the last part into an upload in the Library. The export route skips the sign-in proxy, which holds 4 MB of a body at most: like main's routes that take a file, it runs the proxy's checks itself (`gateAsProxy`) and reads no more than a part (`readBodyWithin`) | `POST /api/audio-tools` (`?preview=1` plans and prices; tools `split` and `remux` since round 5 part 2), `POST /api/audio-tools/export` (round 5 part 2: a part as the body, `?offset=`, `&id=` from the first part's answer, `&last=1&name=` on the last, which answers 201 with the asset) | `components/audio-tools/*` (since round 5 part 2 `split-tool.tsx`: the split, the mixer, Your splits, Export mix, Put back on the video); any audio result gets "Loop / extend" and, since round 5 part 2, "Split soundtrack", as does a clip, and a clip made with its sound (`v2a`, `mux`, `lipsync`, `trim`, `captions`) offers Split soundtrack instead of Add sound as a next step (`SOUNDED_VIDEO_OPS` in `output-actions.ts`) |
| **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; since round 5 part 2 its frames can come from earlier steps, as the turnaround's drawn sides do) | `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) |
| **Turnaround video** (on a Character Sheet result, Cinema's Soul Cast results and a character's page; round 5 part 2, N7-6) | `catalog/turnaround.ts` (see Catalog): `planTurnaround` draws the sides nobody has a picture of first, from the front, with the Angles app's route (and a front from a sheet that has none), then films: on the GPU Frames mode's Wan 2.2 14B chain with the views at 0, ¼, ½, ¾ and the end of the clip (the drawn sides placed with `ChainSlot.at`) and joined; in the cloud H3 Max reference to video (the views as Image 1…n, starting and ending on the front; the default with 2 or more views or a sheet), FLUX 3 Max keyframes, or H3 Max camera controls from the front alone (`cameraWords`) | `turnaround.ts`: `TurnaroundSchema` and `TurnaroundBodySchema`, `turnaroundRun` (a character is a person whatever the client says: its run needs Soul ID's consent line unless its training recorded one, `consentOnFile` in `training.ts`), `previewTurnaround` (each step checked on this install: keys, demo, Settings → Models & licences, the engine mode; the GPU it needs), `createTurnaround` (a real person's steps all carry `GenerationRequest.consentAt`; one batch through `runTurnaroundSteps`; the answer names the film as `final`). No table: history is the feed | `POST /api/turnaround` (`?preview=1` plans and prices; `once()` on `requestId`), `POST /api/turnaround/estimate` (the evaluation harness's path); Cinema's generate with action `turnaround` | `components/turnaround/turnaround-dialog.tsx` (`TurnaroundButton`: five picture slots, "Draw the missing sides", route, length, shape, price and consent) on a finished sheet (`fashion/character-sheet.tsx`), Soul Cast results (`cinema/soul-builders.tsx`) and as Fly around on a character's page (`element-studio.tsx`) |
| **Storyboard** (`/storyboard`; Popcorn looks and prices since round 5 part 1, O13) | `catalog/storyboard.ts` (above: `planStoryboard`, `STORYBOARD_MODELS`, `STORYBOARD_PARTNERS`, the look and the 21:9 crop); `src/lib/storyboard-board.ts` (`filmReady`: "Make the film" waits until the browser has graded and cropped a look board's frames, or gave up, `finishGaveUp` in `soul-finish.ts`) | `storyboard.ts`: `StoryboardBodySchema` (shared by the run and its estimate: `look`, `lookStrength`, `partner`), `estimateStoryboard` (each frame priced on its own model, which Assist's `create_storyboard` now uses too), the film's shape from `frame.crop`; `pollOne` writes the look's finish meta on every frame (see Structured outputs) | `POST /api/storyboards` (`look`, `lookStrength`, `partner: "nano-banana-pro"`), `POST /api/storyboards/estimate` (`{costUsd, demo, frames, models}`) | `storyboard-view.tsx`: the Look chip with a "No look" state (`look-chip.tsx`'s `none`), the price and frame count next to Generate (disabled while the estimate errs), and in the cloud a "Frames made on" choice of Fuobe or Nano Banana Pro. A 4-frame cloud board is priced under $0.20 in the tests (Nano Banana Pro: about $0.60) |
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index efe509cd..a614ae90 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -73,7 +73,7 @@ The owner's own words on engines, SAM Audio, accounts and the PR #14 calls are i
- changes to the library or projects go in `LIBRARY_CHANGES` (403 `code: "library"` for an account). Settings, keys and tokens stay the owner's. The owner's lists come back empty for a visitor, and a visitor is never told whether one of the owner's records exists.
- only the owner's runs reach the install's keys or GPU. An account's studio generations run on its own ComfyUI through `POST /api/generations`; other runs answer `connect-gpu`, then `own-gpu-tool`. An account's run reads only its own files (`src/server/tenant.ts`, `src/server/account-inputs.ts`).
- the sign-in proxy holds at most 4 MB of a request body (main, 10-31; `next.config.ts`), and a bigger one reaches the route cut short: a route that takes a large file takes an uploaded file's reference. A route that must take a file itself skips the proxy the way main's do (the matcher in `src/proxy.ts`, then `gateAsProxy` and `readBodyWithin` or `readFormWithin` from `src/server/direct-gate.ts`, and a row in `tests/request-body-limits.test.ts`), as Split soundtrack's Export mix does
- - a price check reads a stored file only through `storedMedia` (`src/server/storage.ts`): only its header, and in a visitor's price check only the visitor's own files
+ - a price check reads a stored file only through `storedMedia` (`src/server/storage.ts`): only its header, and in a visitor's price check only the visitor's own files. A visitor's price check never calls a GPU either (main allows the server to call an account's address a few times a minute): Split soundtrack's reads an account's device from its last status check (`lastGpuDevice` in `src/server/account-gpu.ts`), and the run checks the models on its disk
- add new routes to those rules, and test them in the style of `tests/public-signup.test.ts`, `tests/public-signup-tools.test.ts` and `tests/account-*.test.ts`
- new ComfyUI workflows and node packs go into the pre-flight's requirement index (`packs.json`, `model-pins.json`, then `node scripts/comfy/build-requirements.mjs`), and new studios and tools get a row on the `/connect` board (`STUDIO_ROWS` in `src/server/gpu/tools.ts`)
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 1fe07e35..bf719f65 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -35,7 +35,8 @@ reverse proxy; see below), and so may each account. A price check reads only the
it names, and only of the asker's own files: a guest owns none. Nor does a price check reveal the
owner's library: the turnaround video's price check (`/api/turnaround/estimate`, or
`/api/turnaround?preview=1`) answers 404 "Character not found" for any character a visitor names,
-whether it exists or not.
+whether it exists or not. A price check never calls a GPU either: Split soundtrack's price check
+takes an account's GPU type from the status strip's last check and asks the GPU nothing.
## Accounts
diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsx
index a2dc1464..0c976951 100644
--- a/src/components/audio-tools/split-tool.tsx
+++ b/src/components/audio-tools/split-tool.tsx
@@ -629,6 +629,8 @@ function Mixer({ stems, source, engine }: { stems: Stem[]; source: Source; engin
// The tool
const money = (p: AudioToolPreview) => (p.demo ? "Demo · free" : "Free · runs on your ComfyUI");
+/** Where the time estimate is for: the host's device when it said; else a CPU's, the figures the estimate then uses. */
+const onDevice = (device?: string) => (device === "cuda" ? "on your GPU" : device ? "on your CPU" : "on a CPU");
/** What each model is, shown under the choice (not only on hover). */
const MODEL_HINTS: Record<SplitQuality, string> = {
@@ -757,7 +759,7 @@ export function SplitSoundtrackTool({ tabs }: { tabs?: React.ReactNode }) {
onChange={(v) => setQuality(v)}
options={(["fast", "best"] as const).map((q) => ({ value: q, label: `${QUALITY_LABELS[q]}${p?.installed && !p.installed.includes(q) ? " · not installed" : ""}`, hint: MODEL_HINTS[q] }))}
/>
- {!quality && p?.hostPick && <span className="text-[12px] text-muted-foreground">picked for your {p.device === "cuda" ? "GPU" : "CPU"}</span>}
+ {!quality && p?.hostPick && p.device && <span className="text-[12px] text-muted-foreground">picked for your {p.device === "cuda" ? "GPU" : "CPU"}</span>}
</div>
<p className="text-[12px] text-muted-foreground sm:pl-[4.5rem]">{MODEL_HINTS[picked]}</p>
{channels === 1 ? null : channels && channels > 2 ? (
@@ -800,7 +802,7 @@ export function SplitSoundtrackTool({ tabs }: { tabs?: React.ReactNode }) {
) : p ? (
<>
<span className="font-mono text-foreground">{money(p)}</span>
- {p.estimate && !p.demo ? ` · ${durationWords(p.estimate)} on your ${p.device === "cuda" ? "GPU" : "CPU"}` : ""}
+ {p.estimate && !p.demo ? ` · ${durationWords(p.estimate)} ${onDevice(p.device)}` : ""}
</>
) : (
"Checking…"
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 53f8922e..c3cd6561 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -117,6 +117,18 @@ export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: b
return check;
}
+/**
+ * The device type ("cuda", "cpu", "mps"…) of an account's ComfyUI as its last status check read it (the start of
+ * /system_stats devices[0].name: "cuda:0 NVIDIA …"), without asking it again; undefined when no check of its saved
+ * address has read one. A price check reads this and never calls the GPU (Split soundtrack's pick and time).
+ */
+export function lastGpuDevice(id: string): string | undefined {
+ const gpu = accountGpu(id);
+ const hit = globalThis.__fuobeAccountGpus?.get(id);
+ if (!gpu || hit?.url !== gpu.url) return undefined;
+ return /^[a-z]+/i.exec(hit.info.device ?? "")?.[0].toLowerCase();
+}
+
/** What a visitor's status strip shows (GET /api/status): its own GPU, never the install's providers, servers or Demo mode. */
export interface VisitorView {
kind: "guest" | "account";
diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.ts
index 1d0d063f..62533d03 100644
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@ -3,11 +3,13 @@ import { z } from "zod";
import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";
import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, splitTime } from "@/lib/av/split";
import type { Engine, Generation } from "@/lib/catalog/types";
+import { lastGpuDevice } from "./account-gpu";
import { createPipeline } from "./chains";
import { previewChained } from "./generations";
-import { comfyDbsModels, comfyDevice } from "./providers/comfyui";
+import { comfyDbsModels, comfyDevice, ownGpu } from "./providers/comfyui";
import { engineMode } from "./settings";
import { storedMedia } from "./storage";
+import { tenant, tenantAccount } from "./tenant";
/**
* The Audio hub's Loop / extend, Join and Split soundtrack tools on the server: each clip's length is read from its own
@@ -154,7 +156,16 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToo
if (body.tool === "split") {
// How long it takes on this host: its device (asked once a minute), the model it would use (one it has on disk) and
// how many passes. A model the host doesn't have is refused here, before the run, with how to install it.
- const [device, installed] = demo ? [undefined, undefined] : await Promise.all([comfyDevice().catch(() => undefined), comfyDbsModels().catch(() => undefined)]);
+ // A visitor's price check (a guest's, or an account's on its own GPU) never calls a GPU, as main's price checks
+ // don't (the server calls an account's address a few times a minute at most): an account's device is what its last
+ // status check read (lastGpuDevice), a guest has none, and the run checks the models on the GPU's disk.
+ const visitor = !!tenant() || !!ownGpu();
+ const account = tenantAccount();
+ const [device, installed] = demo
+ ? [undefined, undefined]
+ : visitor
+ ? [account ? lastGpuDevice(account) : undefined, undefined]
+ : await Promise.all([comfyDevice().catch(() => undefined), comfyDbsModels().catch(() => undefined)]);
if (body.quality && installed && !installed.includes(DBS_MODELS[body.quality])) throw new AudioToolError(missingDbs(DBS_MODELS[body.quality], installed));
const pick = hostPick(device, installed);
const quality = body.quality ?? pick;
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 0bb07327..196b39d6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -581,6 +581,21 @@ export async function probeComfy(force = false): Promise<boolean> {
return sharedCheck("comfy", url, () => checkComfy(url));
}
+declare global {
+ /** comfyDevice's and comfyDbsModels' requests on their way, by path and address. */
+ var __fuobeComfyAsks: Map<string, Promise<unknown>> | undefined;
+}
+
+/** One request at a time per path and address: callers that arrive while it is on its way share its answer. */
+function oneAsk<T>(key: string, ask: () => Promise<T>): Promise<T> {
+ const asks = (globalThis.__fuobeComfyAsks ??= new Map());
+ const going = asks.get(key);
+ if (going) return going as Promise<T>;
+ const p = ask().finally(() => asks.delete(key));
+ asks.set(key, p);
+ return p;
+}
+
declare global {
/** The torch device each ComfyUI address reported last (GET /system_stats devices[0].type), and when. */
var __fuobeComfyDevice: Map<string, { type?: string; at: number }> | undefined;
@@ -596,10 +611,12 @@ export async function comfyDevice(worker: ComfyWorker = "main"): Promise<string
const cache = (globalThis.__fuobeComfyDevice ??= new Map());
const hit = cache.get(url);
if (hit && Date.now() - hit.at < 60_000) return hit.type;
- const s = await comfyJson<{ devices?: { type?: unknown }[] }>("/system_stats", worker).catch(() => undefined);
- const type = typeof s?.devices?.[0]?.type === "string" ? (s.devices[0].type as string) : undefined;
- if (s) cache.set(url, { type, at: Date.now() });
- return type;
+ return oneAsk(`/system_stats ${url}`, async () => {
+ const s = await comfyJson<{ devices?: { type?: unknown }[] }>("/system_stats", worker).catch(() => undefined);
+ const type = typeof s?.devices?.[0]?.type === "string" ? (s.devices[0].type as string) : undefined;
+ if (s) cache.set(url, { type, at: Date.now() });
+ return type;
+ });
}
declare global {
@@ -618,10 +635,12 @@ export async function comfyDbsModels(worker: ComfyWorker = "main", maxAgeMs = 10
const cache = (globalThis.__fuobeComfyDbs ??= new Map());
const hit = cache.get(url);
if (hit && Date.now() - hit.at < maxAgeMs) return hit.models;
- const files = await comfyJson<unknown>("/models/dbs", worker).catch(() => undefined);
- const models = Array.isArray(files) ? installedDbs(files.filter((f): f is string => typeof f === "string")) : undefined;
- cache.set(url, { models, at: Date.now() });
- return models;
+ return oneAsk(`/models/dbs ${url}`, async () => {
+ const files = await comfyJson<unknown>("/models/dbs", worker).catch(() => undefined);
+ const models = Array.isArray(files) ? installedDbs(files.filter((f): f is string => typeof f === "string")) : undefined;
+ cache.set(url, { models, at: Date.now() });
+ return models;
+ });
}
/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */
diff --git a/tests/comfy-dbs.test.ts b/tests/comfy-dbs.test.ts
index dde520c5..a39ebaaa 100644
--- a/tests/comfy-dbs.test.ts
+++ b/tests/comfy-dbs.test.ts
@@ -14,7 +14,7 @@ import type { MediaInfo } from "@/lib/media-probe";
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-dbs-"));
process.env.FUOBE_DATA_DIR = tmp;
process.env.COMFYUI_URL = "http://comfy.test:8188";
-const { collectOutputs, comfyDbsModels, prepareWorkflow } = await import("@/server/providers/comfyui");
+const { collectOutputs, comfyDbsModels, comfyDevice, prepareWorkflow } = await import("@/server/providers/comfyui");
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
const root = path.resolve(__dirname, "..");
@@ -230,6 +230,33 @@ describe("which DBS models the host has (GET /models/dbs)", () => {
globalThis.__fuobeComfyDbs = undefined;
}
});
+
+ it("asks once while a request is on its way: callers that arrive meanwhile share its answer, the device's too", async () => {
+ globalThis.__fuobeComfyDbs = undefined;
+ globalThis.__fuobeComfyDevice = undefined;
+ const asked: string[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ asked.push(new URL(url).pathname);
+ await new Promise((r) => setTimeout(r, 50));
+ return url.endsWith("/models/dbs") ? Response.json(["DBS-BSRNN-DnR/config.json", "DBS-BSRNN-DnR/model.safetensors"]) : Response.json({ devices: [{ type: "cpu" }] });
+ }),
+ );
+ try {
+ const [models, devices] = await Promise.all([Promise.all(Array.from({ length: 10 }, () => comfyDbsModels("main", 0))), Promise.all(Array.from({ length: 10 }, () => comfyDevice()))]);
+ expect(models.every((m) => m?.join() === "DBS-BSRNN-DnR")).toBe(true);
+ expect(devices.every((d) => d === "cpu")).toBe(true);
+ expect(asked.sort()).toEqual(["/models/dbs", "/system_stats"]);
+ // Once answered, a run asks afresh.
+ await comfyDbsModels("main", 0);
+ expect(asked.filter((a) => a === "/models/dbs")).toHaveLength(2);
+ } finally {
+ vi.unstubAllGlobals();
+ globalThis.__fuobeComfyDbs = undefined;
+ globalThis.__fuobeComfyDevice = undefined;
+ }
+ });
});
describe("a finished DBS job's outputs", () => {
diff --git a/tests/price-check-reads.test.ts b/tests/price-check-reads.test.ts
index af48404b..f420db79 100644
--- a/tests/price-check-reads.test.ts
+++ b/tests/price-check-reads.test.ts
@@ -1,4 +1,6 @@
import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -23,6 +25,9 @@ const { videoLength } = await import("@/server/dub");
const { resetRates } = await import("@/server/rate");
const { proxy } = await import("@/proxy");
const dubRoute = await import("@/app/api/dub/route");
+const audioRoute = await import("@/app/api/audio-tools/route");
+const { gpuState } = await import("@/server/account-gpu");
+const { splitTime } = await import("@/lib/av/split");
const MP4 = fs.readFileSync(path.join(import.meta.dirname, "fixtures", "shorts-12s.mp4"));
@@ -145,6 +150,88 @@ describe("H-3: price checks read only the header of the asker's own files", () =
});
});
+describe("a Split soundtrack price check never calls a GPU (main: an account's address a few times a minute at most)", () => {
+ /** A stand-in for an account's ComfyUI (a CUDA host with both DBS models) that counts what it is asked. */
+ async function standInGpu() {
+ const hits: Record<string, number> = {};
+ const server = http.createServer((req, res) => {
+ const at = (req.url ?? "").split("?")[0];
+ hits[at] = (hits[at] ?? 0) + 1;
+ const files = ["DBS-BSRNN-DnR/config.json", "DBS-BSRNN-DnR/model.safetensors", "DBS-TIGER-DnR/config.json", "DBS-TIGER-DnR/model.safetensors"];
+ const body =
+ at === "/system_stats"
+ ? { system: { comfyui_version: "0.41.0" }, devices: [{ name: "cuda:0 NVIDIA GeForce RTX 4090 : cudaMallocAsync", type: "cuda", vram_total: 24 * 2 ** 30 }] }
+ : at === "/models/dbs"
+ ? files
+ : null;
+ res.writeHead(body ? 200 : 404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(body));
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
+ const port = (server.address() as AddressInfo).port;
+ return { hits, port, url: `http://127.0.0.1:${port}`, close: () => new Promise<void>((r) => server.close(() => r())) };
+ }
+ const price = (body: unknown, session: string) =>
+ audioRoute.POST(
+ new Request("http://localhost:3000/api/audio-tools?preview=1", {
+ method: "POST",
+ headers: { "content-type": "application/json", cookie: `${auth.SESSION_COOKIE}=${session}` },
+ body: JSON.stringify(body),
+ }),
+ );
+
+ it("an account's: its GPU is asked nothing; the pick and the time come from what its last status check read", async () => {
+ const gpu = await standInGpu();
+ const g = globalThis as { __fuobeComfyDevice?: unknown; __fuobeComfyDbs?: unknown; __fuobeAccountGpus?: unknown };
+ g.__fuobeComfyDevice = g.__fuobeComfyDbs = g.__fuobeAccountGpus = undefined;
+ globalThis.__fuobeTestGpuPort = gpu.port;
+ auth.setAccountGpu(a, { url: gpu.url });
+ auth.setAccountGpu(b, { url: gpu.url });
+ try {
+ const sessionA = auth.createSession(a).value;
+ const mine = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload", accountId: a }).url;
+ const split = { tool: "split", engine: "open", media: mine, kind: "audio" };
+ // No status check yet: a CPU's pick and time, no device, no models.
+ for (let i = 0; i < 20; i++) {
+ const r = await price(split, sessionA);
+ expect(r.status).toBe(200);
+ const p = await r.json();
+ expect(p).toMatchObject({ demo: false, hostPick: "fast", length: 30, channels: 1 });
+ expect(p.device).toBeUndefined();
+ expect(p.installed).toBeUndefined();
+ expect(p.estimate).toEqual(splitTime({ seconds: 30, quality: "fast", mode: "mono", channels: 1 }));
+ }
+ expect(gpu.hits).toEqual({});
+ // The status strip asks it (main's check, at most every 30 s): from then on the price check knows it is a CUDA GPU.
+ await gpuState(a, auth.accountGpu(a)!);
+ expect(gpu.hits).toEqual({ "/system_stats": 1 });
+ delete gpu.hits["/system_stats"];
+ const all = await Promise.all(Array.from({ length: 10 }, () => price({ ...split, stereo: true }, sessionA)));
+ for (const r of all) {
+ const p = await r.json();
+ expect(p).toMatchObject({ hostPick: "best", device: "cuda" });
+ expect(p.installed).toBeUndefined();
+ expect(p.estimate).toEqual(splitTime({ seconds: 30, quality: "best", mode: "each channel", channels: 1, device: "cuda" }));
+ }
+ expect(gpu.hits).toEqual({});
+ // Another account on the same address hasn't been checked: its price check knows nothing of it, and asks nothing.
+ const theirs = saveFile({ data: wav(10), contentType: "audio/wav", source: "upload", accountId: b }).url;
+ const pb = await (await price({ tool: "split", engine: "open", media: theirs, kind: "audio" }, auth.createSession(b).value)).json();
+ expect(pb).toMatchObject({ hostPick: "fast", length: 10 });
+ expect(pb.device).toBeUndefined();
+ // A guest: an account's file is gone to it, and nothing is asked.
+ expect((await price(split, "")).status).toBe(422);
+ expect(gpu.hits).toEqual({});
+ } finally {
+ auth.setAccountGpu(a, null);
+ auth.setAccountGpu(b, null);
+ g.__fuobeAccountGpus = undefined;
+ globalThis.__fuobeTestGpuPort = undefined;
+ await gpu.close();
+ }
+ });
+});
+
describe("H-2: the ad multiplier's price check keeps nothing a request sends", () => {
it("refuses a file path over 500 characters, in every studio body that takes one", () => {
const long = `/api/files/${"a".repeat(600)}`;