The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Originals O3: review fixes: a demo never replaces a Soul ID, LoRA copies in the background
Claude4b4323d7e4af
diff --git a/docs/research/fuobe-originals-recipes-5.md b/docs/research/fuobe-originals-recipes-5.mdindex 6767bf4d..6730b405 100644--- a/docs/research/fuobe-originals-recipes-5.md+++ b/docs/research/fuobe-originals-recipes-5.md@@ -148,7 +148,7 @@ Extra fields that matter:The data each fal trainer wants is a zip URL: Z-Image Turbo v2 and Qwen 2512 take `image_data_url` with `001.jpg` + `001.txt` caption pairs and a `default_caption`; Wan 2.2 and LTX-2.3 take `training_data_url` (images and/or videos with same-name `.txt` captions) and a `trigger_phrase`. The Wan 2.2 I2V trainer returns a single `lora_file` (whether fal applies it to both experts is **unverified**: pass it with `transformer: both`).-*Updated 2026-10-27 (o/soul-id): licences are information, not gates (the owner's decision of 2026-10-27).* Soul ID now trains on every image base above that has a hosted LoRA model, with the weights' licence shown next to the price: FLUX.1 [dev] (`fal-ai/flux-lora-portrait-trainer` → `fal-ai/flux-lora`, `fal-ai/flux-krea-lora`), FLUX.2 [dev] (`fal-ai/flux-2-trainer-v2` → `fal-ai/flux-2/lora`), FLUX.2 [klein] 4B and 9B (their base trainers → `fal-ai/flux-2/klein/4b/lora`, `fal-ai/flux-2/klein/9b/lora`) and Krea 2 (`fal-ai/krea-2-trainer` → `fal-ai/krea-2/turbo/lora`); the "not for Originals" roles in the table are superseded (the JSON keeps them as `roleBefore`). `scripts/fetch-hosted-schemas.py --trainers` read each fal trainer's response schema on 2026-10-27 and recorded where its LoRA comes back (`trainers[].loraOutput`): `diffusers_lora_file` for most, `lora_file` for Krea 2, Qwen-Image (2508) and the Wan / LTX video trainers, and a pair for `fal-ai/wan-22-image-trainer` (`diffusers_lora_file` + `high_noise_lora`, so Wan 2.2 image Soul IDs need a two-LoRA element and are not offered yet). The FLUX portrait and Krea 2 trainers take `images_data_url` (the same `001.jpg` + `001.txt` zip; captions win, `trigger_phrase` fills in) rather than `image_data_url`. The five hosted LoRA endpoints' inputs were read the same day (`hostedLoraEndpoints[].inputs`). AI-Toolkit (README and `extensions_built_in/diffusion_models`, read 2026-10-27) trains FLUX.1 [dev] (`arch: flux`), FLUX.2 [dev] (`flux2`), FLUX.2 [klein] base 4B / 9B (`flux2_klein_4b` / `flux2_klein_9b`), Qwen-Image 2512 (`qwen_image`), Krea 2 (`krea2`) and Z-Image Turbo; whether a LoRA trained on a klein *base* model behaves the same on the distilled klein endpoint is **unverified**.+*Updated 2026-10-27 (o/soul-id): licences are information, not gates (the owner's decision of 2026-10-27).* Soul ID now trains on every image base above that has a hosted LoRA model, with the weights' licence shown next to the price: FLUX.1 [dev] (`fal-ai/flux-lora-portrait-trainer` → `fal-ai/flux-lora`, `fal-ai/flux-krea-lora`), FLUX.2 [dev] (`fal-ai/flux-2-trainer-v2` → `fal-ai/flux-2/lora`), FLUX.2 [klein] 4B and 9B (their base trainers → `fal-ai/flux-2/klein/4b/lora`, `fal-ai/flux-2/klein/9b/lora`) and Krea 2 (`fal-ai/krea-2-trainer` → `fal-ai/krea-2/turbo/lora`); the "not for Originals" roles in the table are superseded (the JSON keeps them as `roleBefore`). `scripts/fetch-hosted-schemas.py --trainers` read each fal trainer's response schema on 2026-10-27 and recorded where its LoRA comes back (`trainers[].loraOutput`): `diffusers_lora_file` for most, `lora_file` for Krea 2, Qwen-Image (2508) and the Wan / LTX video trainers, and a pair for `fal-ai/wan-22-image-trainer` (`diffusers_lora_file` + `high_noise_lora`, so Wan 2.2 image Soul IDs need a two-LoRA element and are not offered yet). The FLUX portrait and Krea 2 trainers take `images_data_url` (the same `001.jpg` + `001.txt` zip; captions win, `trigger_phrase` fills in) rather than `image_data_url`. The five hosted LoRA endpoints' inputs were read the same day (`hostedLoraEndpoints[].inputs`). AI-Toolkit (README and `extensions_built_in/diffusion_models`, read 2026-10-27) trains FLUX.1 [dev] (`arch: flux`), FLUX.2 [dev] (`flux2`), FLUX.2 [klein] base 4B / 9B (`flux2_klein_4b` / `flux2_klein_9b`), Qwen-Image 2512 (`qwen_image`), Krea 2 (`krea2`) and Z-Image Turbo; whether a LoRA trained on a klein *base* model behaves the same on the distilled klein endpoint is **unverified**. The FLUX.2 [dev] and klein trainers take `output_lora_format` (`fal` by default, or `comfy`: "Dictates the naming scheme for the output weights", `fal-ai/flux-2-trainer-v2` schema read 2026-10-27); Fuobe asks for `comfy` where the family also runs on ComfyUI (FLUX.2 [dev]), the same key names an AI-Toolkit LoRA has, and keeps fal's default for the cloud-only klein families. Whether fal's FLUX.2 LoRA endpoints load `comfy`-named weights is **unverified** (their schemas only say a LoRA is "a URL, HuggingFace repo ID or local path"); a GPU-trained FLUX.2 LoRA sent to fal relies on the same.### 3.4 Downloading LoRAsdiff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.pyindex f16b382c..27013c36 100644--- a/scripts/gen-cloud-models.py+++ b/scripts/gen-cloud-models.py@@ -1827,6 +1827,14 @@ for m in M:}if m["badges"]:d["badges"] = m["badges"]+ # The open weights' licence, from the hosted LoRA endpoint the model runs on or with (hostedLoraEndpoints): data the+ # admin reads in Settings, never a gate (the owner's decision of 2026-10-27).+ lic = next((HOSTED_LORA[(r["provider"], ep)] for r in routes for ep in (r["endpoint"], r.get("loraEndpoint"))+ if ep and HOSTED_LORA.get((r["provider"], ep), {}).get("baseLicence")), None)+ if lic:+ d["licence"] = {"licence": lic["baseLicence"], "commercial": lic.get("commercialWeights"),+ **({"note": lic["licenceNote"]} if lic.get("licenceNote") else {}),+ **({"checked": lic["checked"]} if lic.get("checked") else {})}defaults = {k: v for k, v in m["defaults"].items()}# Drop defaults the model can't take.if "aspectRatio" in defaults and defaults["aspectRatio"] not in opts.get("aspectRatios", [defaults["aspectRatio"]]):diff --git a/src/components/photodump/subject.tsx b/src/components/photodump/subject.tsxindex 4e9ac0d4..deea829c 100644--- a/src/components/photodump/subject.tsx+++ b/src/components/photodump/subject.tsx@@ -24,7 +24,8 @@ export function identityLabel(el: StudioElement): string {/** The character-creation copy (src/lib/catalog/training.ts SOUL_ID_COPY, Higgsfield's rules): saving is the consent. */const CREATE_COPY = {...SOUL_ID_COPY,- consent: `By clicking Save character, ${SOUL_ID_COPY.consent.charAt(0).toLowerCase()}${SOUL_ID_COPY.consent.slice(1)}`,+ // The line starts with "I consent", which stays a capital I mid-sentence.+ consent: `By clicking Save character, ${SOUL_ID_COPY.consent}`,} as const;const MAX_PHOTOS = SOUL_ID_PHOTOS.max;diff --git a/src/components/train-dialog.tsx b/src/components/train-dialog.tsxindex 8b65b10c..b1ca9925 100644--- a/src/components/train-dialog.tsx+++ b/src/components/train-dialog.tsx@@ -141,9 +141,10 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioElconst originals = families.filter((f) => TRAINING_FAMILIES[f].original);const more = families.filter((f) => !TRAINING_FAMILIES[f].original);const busyAny = q.data?.items.some((t) => t.status === "queued" || t.status === "running");- // "Retrain for Fuobe Soul" on a Higgsfield Soul ID: the first option that can run now.+ // "Retrain for Fuobe Soul" on a Higgsfield Soul ID: the first option that can run now. Once a real Fuobe Soul LoRA+ // is trained, the old Soul ID is only there to remove.const retrainTarget = targets.find((t) => t.family === "z-image-turbo" && !t.blocker && !t.demo) ?? targets.find((t) => t.family === "z-image-turbo" && !t.blocker);-+ const replaced = hasFamily("z-image-turbo");const anyTrained = families.some((g) => hasFamily(g));/** One family: its models, its licence (information), and where it trains with each one's price first. */@@ -198,7 +199,8 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioEl</div>{!busy && (t.blocker || t.demo) && (<p className="mt-2 text-[12px] text-muted-foreground">- {t.blocker ?? (t.provider === "fal" ? "No fal.ai key yet: this runs as a demo and trains nothing." : "No AI-Toolkit set up yet: this runs as a demo and trains nothing.")}{" "}+ {t.blocker ??+ `${t.provider === "fal" ? "No fal.ai key yet" : "No AI-Toolkit set up yet"}: this runs as a demo and trains nothing${hasFamily(f) ? ", and the Soul ID you trained stays" : ""}.`}{" "}<Link href="/settings" className="text-brand-text underline underline-offset-2">Open Settings</Link>@@ -298,20 +300,28 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioEl);})}{legacy.map((l) => (- <div key={identityKey(l)} className="flex flex-wrap items-center gap-2 rounded-lg border border-warning/40 px-3 py-2 text-[13px]">- <AlertTriangle className="size-4 shrink-0 text-warning" />- <span className="min-w-0 flex-1">+ <div key={identityKey(l)} className={cn("flex flex-wrap items-center gap-2 rounded-lg border px-3 py-2 text-[13px]", !replaced && "border-warning/40")}>+ {replaced ? <CircleCheck className="size-4 shrink-0 text-muted-foreground" /> : <AlertTriangle className="size-4 shrink-0 text-warning" />}+ {/* Wide enough to read on a phone: the buttons wrap under it there. */}+ <span className="min-w-0 flex-1 basis-48"><span className="block font-medium">Higgsfield Soul ID</span>- <span className="block text-[12px] text-muted-foreground">It can't be exported. Retrain on the same photos for Fuobe Soul.</span>+ <span className="block text-[12px] text-muted-foreground">+ {replaced ? "Your Fuobe Soul ID replaces it: remove it when you no longer need it." : "It can't be exported. Retrain on the same photos for Fuobe Soul."}+ </span></span>- <Button- size="sm"- variant="secondary"- disabled={!retrainTarget || !!tooFew || (person && !consent) || start.isPending || busyAny}- onClick={() => retrainTarget && start.mutate(retrainTarget.id)}- >- <RotateCcw /> Retrain for Fuobe Soul- </Button>+ {!replaced && (+ <Button+ size="sm"+ variant="secondary"+ disabled={!retrainTarget || !!tooFew || (person && !consent) || start.isPending || busyAny}+ onClick={() => retrainTarget && start.mutate(retrainTarget.id)}+ >+ <RotateCcw /> Retrain for Fuobe Soul+ </Button>+ )}+ <button onClick={() => void remove(l)} className="shrink-0 p-1 text-muted-foreground hover:text-destructive" aria-label="Remove the Higgsfield Soul ID">+ <Trash2 className="size-3.5" />+ </button></div>))}</section>diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.tsindex 187536ca..3d69e183 100644--- a/src/lib/catalog/cloud-models.generated.ts+++ b/src/lib/catalog/cloud-models.generated.ts@@ -1830,6 +1830,12 @@ export const CLOUD_MODELS: ModelDef[] = ["badges": ["fast"],+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Z-Image Turbo / base weights are Apache-2.0 (HF Tongyi-MAI/Z-Image-Turbo, Tongyi-MAI/Z-Image)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "1:1"},@@ -1901,6 +1907,12 @@ export const CLOUD_MODELS: ModelDef[] = [],"maxOutputs": 4},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Qwen-Image / 2512 / Edit 2509 / 2511 / Layered are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "1:1"},@@ -2003,6 +2015,12 @@ export const CLOUD_MODELS: ModelDef[] = ["maxOutputs": 4,"maxImages": 10},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Qwen-Image / 2512 / Edit 2509 / 2511 / Layered are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "1:1"},@@ -2075,6 +2093,12 @@ export const CLOUD_MODELS: ModelDef[] = ["maxOutputs": 4,"maxImages": 10},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Qwen-Image / 2512 / Edit 2509 / 2511 / Layered are Apache-2.0",+ "checked": "2026-10-23"+ },"pricing": {"unit": "megapixel","usd": 0.035@@ -2180,6 +2204,12 @@ export const CLOUD_MODELS: ModelDef[] = ["badges": ["fast"],+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "FLUX.2 [klein] 4B is Apache-2.0 (HF black-forest-labs/FLUX.2-klein-4B)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "1:1"},@@ -2249,6 +2279,12 @@ export const CLOUD_MODELS: ModelDef[] = ["4:5"]},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Wan 2.1 / 2.2 weights are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "16:9"},@@ -2315,6 +2351,12 @@ export const CLOUD_MODELS: ModelDef[] = [],"maxOutputs": 4},+ "licence": {+ "licence": "FLUX.1 [dev] Non-Commercial License",+ "commercial": false,+ "note": "Weights are non-commercial; the fal page says 'All generated images are cleared for commercial use' (fal's licence, not the weights')",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4"},@@ -2381,6 +2423,12 @@ export const CLOUD_MODELS: ModelDef[] = [],"maxOutputs": 4},+ "licence": {+ "licence": "FLUX.1 [dev] Non-Commercial License",+ "commercial": false,+ "note": "Weights are non-commercial; the fal page says 'All generated images are cleared for commercial use' (fal's licence, not the weights')",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4"},@@ -2448,6 +2496,12 @@ export const CLOUD_MODELS: ModelDef[] = [],"maxOutputs": 4},+ "licence": {+ "licence": "FLUX [dev] Non-Commercial License",+ "commercial": false,+ "note": "Weights are non-commercial; fal marks the hosted endpoint 'Commercial use'",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4"},@@ -2518,6 +2572,12 @@ export const CLOUD_MODELS: ModelDef[] = ["badges": ["fast"],+ "licence": {+ "licence": "FLUX Non-Commercial License",+ "commercial": false,+ "note": "FLUX.2 [klein] 9B weights are non-commercial; fal's page marks its own API output 'Commercial use'",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4"},@@ -2588,6 +2648,12 @@ export const CLOUD_MODELS: ModelDef[] = ["badges": ["fast"],+ "licence": {+ "licence": "Krea 2 Community License (gated, revenue tiers)",+ "commercial": null,+ "note": "Free for individuals and small teams; an enterprise tier above Krea's thresholds (round-1 research). Not a default for Originals",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4"},@@ -6679,6 +6745,12 @@ export const CLOUD_MODELS: ModelDef[] = ["endFrame": true,"maxImages": 1},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Wan 2.1 / 2.2 weights are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "16:9","duration": 5,@@ -6918,6 +6990,12 @@ export const CLOUD_MODELS: ModelDef[] = ["badges": ["audio"],+ "licence": {+ "licence": "LTX-2 / LTX-2.x Community License",+ "commercial": true,+ "note": "Free for companies under US$10M annual revenue; above that a paid licence (github.com/Lightricks/LTX-2 LICENSE-2, LICENSE-2_x, section 2.1)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "16:9","duration": 5,@@ -16843,6 +16921,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = ["maxOutputs": 4,"maxImages": 1},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Z-Image Turbo / base weights are Apache-2.0 (HF Tongyi-MAI/Z-Image-Turbo, Tongyi-MAI/Z-Image)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4","resolution": "720p"@@ -16970,6 +17054,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = ["seed": true,"maxOutputs": 4},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Qwen-Image / 2512 / Edit 2509 / 2511 / Layered are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "3:4","resolution": "720p"@@ -17188,6 +17278,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = ["seed": true,"maxOutputs": 4},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Z-Image Turbo / base weights are Apache-2.0 (HF Tongyi-MAI/Z-Image-Turbo, Tongyi-MAI/Z-Image)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "16:9","resolution": "720p"@@ -17369,6 +17465,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = [],"maxImages": 1},+ "licence": {+ "licence": "Apache-2.0",+ "commercial": true,+ "note": "Wan 2.1 / 2.2 weights are Apache-2.0",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "auto","duration": 5,@@ -17520,6 +17622,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = [],"maxImages": 1},+ "licence": {+ "licence": "LTX-2 / LTX-2.x Community License",+ "commercial": true,+ "note": "Free for companies under US$10M annual revenue; above that a paid licence (github.com/Lightricks/LTX-2 LICENSE-2, LICENSE-2_x, section 2.1)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "auto","duration": 5,@@ -17996,6 +18104,12 @@ export const ORIGINAL_CLOUD: ModelDef[] = ["badges": ["audio"],+ "licence": {+ "licence": "LTX-2 / LTX-2.x Community License",+ "commercial": true,+ "note": "Free for companies under US$10M annual revenue; above that a paid licence (github.com/Lightricks/LTX-2 LICENSE-2, LICENSE-2_x, section 2.1)",+ "checked": "2026-10-23"+ },"defaults": {"aspectRatio": "16:9","duration": 5,diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 14e6d12c..74d402f7 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -14,7 +14,7 @@ import type {import { chainGapProblem, chainTiming, FIRST_AT_ZERO, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";import { cloudPath, fitLoras, gated, localOnly, loraCapacity, needsToken, routeLoraField, triggerOf } from "./loras";import { numFramesValue, sizeValue } from "./payload";-import { CINEMA_CROP, soulKind, soulMegapixels, soulRecipe, soulSize, type SoulOverlay } from "./soul";+import { characterScale, CINEMA_CROP, soulKind, soulMegapixels, soulRecipe, soulSize, type SoulOverlay } from "./soul";/** Infer the operation from what the user attached. */export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs" | "params">): Operation {@@ -240,9 +240,15 @@ export function planGeneration(// The user's own LoRAs (an @character's trained identity) go first: on an API that takes so many, the first// ones win, so a look's or motion's LoRAs give way to them (fitLoras).let soulPlan: Plan["soul"];+ // The character strength (Fuobe's setting, never the provider's) scales the user's own LoRAs on every model.+ const extra = params.extra ?? {};+ const charStrength = typeof extra.characterStrength === "number" ? extra.characterStrength : undefined;+ if ("characterStrength" in extra) {+ const rest = { ...extra };+ delete rest.characterStrength;+ params = { ...params, extra: Object.keys(rest).length ? rest : undefined };+ }if (soul) {- const extra = params.extra ?? {};- const charStrength = typeof extra.characterStrength === "number" ? extra.characterStrength : undefined;const r = soulRecipe(soul, prompt, { look: req.presetId, strength: req.presetStrength, userLoras: req.loras, characterStrength: charStrength });prompt = r.prompt;loras = r.loras;@@ -255,13 +261,11 @@ export function planGeneration(...(r.grade && { grade: r.grade }),...(r.overlay && { overlay: r.overlay }),};- // characterStrength is Fuobe's setting, not the provider's.- if ("characterStrength" in extra) {- const rest = { ...extra };- delete rest.characterStrength;- params = { ...params, extra: Object.keys(rest).length ? rest : undefined };- }- } else if (req.loras?.length) loras = [...req.loras, ...loras];+ } else if (req.loras?.length) {+ // An @character's trained LoRA on FLUX, klein, Krea or any other model: at the character strength's scale, as on Soul.+ const own = charStrength === undefined ? req.loras : req.loras.map((l) => ({ ...l, strength: characterScale(charStrength) }));+ loras = [...own, ...loras];+ }// A LoRA at strength 0 changes nothing: leave it out, so preset strength 0 is the preset's prompt alone (and its file isn't needed).const kept = loras.filter((l) => (l.strength ?? 1) !== 0);// Its trigger word goes with it: an open motion's template starts with its LoRA's trigger ("e13c7r1c electricitydiff --git a/src/lib/catalog/training.ts b/src/lib/catalog/training.tsindex c2c9a7a6..68bb434e 100644--- a/src/lib/catalog/training.ts+++ b/src/lib/catalog/training.ts@@ -76,6 +76,8 @@ export interface TrainingTarget {provider: TrainingProvider;family: TrainingFamily;kinds: TrainingKind[];+ /** Only these kinds of element (FLUX's portrait trainer crops to faces: people only); every kind of its training kinds when unset. */+ onlyFor?: ElementKind[];/** fal: the hosted trainer's endpoint (HOSTED_TRAINERS). */trainer?: string;steps: number;@@ -334,6 +336,7 @@ export const TRAINING_TARGETS: TrainingTarget[] = [provider: "fal",family: "flux1-dev",kinds: ["subject"],+ onlyFor: ["character"],trainer: "fal-ai/flux-lora-portrait-trainer",steps: 2500,description: `fal's FLUX portrait trainer: it crops to the face and trains at several sizes. ${TO_FAL}`,@@ -417,8 +420,12 @@ export const getTrainingTarget = (id: string) => TRAINING_TARGETS.find((t) => t./** A style element trains as a style; characters, places and objects as subjects. */export const trainingKind = (kind: ElementKind): TrainingKind => (kind === "style" ? "style" : "subject");+/** This target trains this kind of element: its training kind, and the element kinds it's limited to (people for a face trainer). */+export const trainsKind = (t: Pick<TrainingTarget, "kinds" | "onlyFor">, kind: ElementKind): boolean =>+ kind !== "voice" && t.kinds.includes(trainingKind(kind)) && (!t.onlyFor || t.onlyFor.includes(kind));+/** The targets an element of this kind can train on, in the dialog's order. */-export const targetsFor = (kind: ElementKind): TrainingTarget[] => (kind === "voice" ? [] : TRAINING_TARGETS.filter((t) => t.kinds.includes(trainingKind(kind))));+export const targetsFor = (kind: ElementKind): TrainingTarget[] => TRAINING_TARGETS.filter((t) => trainsKind(t, kind));/** Only a person needs the consent line (biometric data). */export const needsConsent = (kind: ElementKind): boolean => kind === "character";@@ -484,8 +491,19 @@ export function identityFor(loras: ElementLora[], model: Pick<ModelDef, "id" | "return fits.sort((a, b) => Number(b.engine === model.engine) - Number(a.engine === model.engine) || (b.trainedAt ?? 0) - (a.trainedAt ?? 0))[0];}-/** How the Train dialog names one of an element's LoRAs to remove it: its file, its Soul ID, or its model. */-export const identityKey = (l: Pick<ElementLora, "file" | "referenceId" | "modelId">): string => l.file || l.referenceId || l.modelId;+/**+ * How the Train dialog names one of an element's LoRAs to remove it: a Higgsfield Soul ID by its id, a trained LoRA by+ * its family and file (one file attached for two families is two LoRAs).+ */+export const identityKey = (l: Pick<ElementLora, "file" | "referenceId" | "modelId" | "family">): string =>+ l.referenceId || `${loraFamily(l) ?? l.modelId}:${l.file || l.modelId}`;++/** A trained LoRA some run can use (not a demo's stand-in or a Higgsfield Soul ID, and on an engine where its family has a model). */+export function runsSomewhere(l: Pick<ElementLora, "file" | "url" | "own" | "referenceId" | "demo" | "family" | "modelId">): boolean {+ const fam = loraFamily(l);+ const lead = fam ? TRAINING_FAMILIES[fam].lead : { open: l.modelId, cloud: l.modelId };+ return (!!lead.open && usableOn(l, "open")) || (!!lead.cloud && usableOn(l, "cloud"));+}/** The families an element has a trained LoRA for. */export const trainedFamilies = (loras: ElementLora[]): TrainingFamily[] => [...new Set(loras.map(loraFamily).filter((f): f is TrainingFamily => !!f))];@@ -526,6 +544,10 @@ export function falTrainingInput(t: TrainingTarget, zipUrl: string, caption: strif (trigger && f.trigger_phrase) body.trigger_phrase = trigger;else if (trigger && f.trigger_word) body.trigger_word = trigger;if (f.learning_rate && t.learningRate !== undefined) body.learning_rate = t.learningRate;+ // The FLUX.2 trainers name the LoRA's weights fal's way unless asked ("Dictates the naming scheme for the output+ // weights", schema read 2026-10-27): a family that also runs on ComfyUI gets ComfyUI's names, the same file an+ // AI-Toolkit training makes, which Fuobe sends to fal for cloud runs too.+ if (f.output_lora_format?.enum?.includes("comfy") && TRAINING_FAMILIES[t.family].lead.open) body.output_lora_format = "comfy";for (const [k, v] of Object.entries(t.extra ?? {})) if (f[k] && (!f[k].enum || f[k].enum.includes(v as string | number))) body[k] = v;return body;}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex d0e42545..738cb5c5 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -590,6 +590,18 @@ export interface Pricing {animationUsd?: number;}+/** A model's weights licence, as read in the research: information, never a gate (the owner's decision of 2026-10-27). */+export interface ModelLicence {+ /** As written ("FLUX.1 [dev] Non-Commercial License"). */+ licence: string;+ /** The weights allow selling outputs: true, false (non-commercial) or null (a revenue tier decides). */+ commercial: boolean | null;+ /** What else the research noted (fal's own terms for its hosted outputs). */+ note?: string;+ /** When it was read (YYYY-MM-DD). */+ checked?: string;+}+export interface ModelDef {id: string;name: string;@@ -605,6 +617,11 @@ export interface ModelDef {pricing?: Pricing;/** Trained identities this model accepts by id (Higgsfield Soul ID). */identity?: { provider: "higgsfield"; version: "v1" | "v2" | "cinema" };+ /**+ * The licence of the open weights a hosted model runs (generated from the research), as information: nothing is+ * hidden or refused for it; the admin turns models on or off in Settings.+ */+ licence?: ModelLicence;/*** A Fuobe Original that runs on both engines: its routes cover ComfyUI and the hosted open weights on fal /* Replicate. `engine` is the one it shows first; a request picks one with GenerationRequest.engine, anddiff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsindex 3e3c3741..3d6a87b2 100644--- a/src/server/assist/tools.ts+++ b/src/server/assist/tools.ts@@ -7,6 +7,8 @@ import { dualEngine, runsOn } from "@/lib/catalog/engines";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";@@ -115,6 +117,12 @@ const searchModels = defineTool({// ---------------------------------------------------------------------------// list_elements+/** The models an element's trained LoRA runs on: its family's (a LoRA from before O3 names its one model). */+const familyModels = (l: ElementLora): string[] => {+ const f = loraFamily(l);+ return f ? TRAINING_FAMILIES[f].models : [l.modelId];+};+const listElementsTool = defineTool({name: "list_elements",description:@@ -130,7 +138,9 @@ const listElementsTool = defineTool({kind: e.kind,description: e.description,referencePhotos: e.references.length,- trainedFor: e.loras.map((l) => l.modelId),+ // The models its trained LoRAs run on (every model of each family), from LoRAs a run can use: not a demo+ // training's stand-in or an old Higgsfield Soul ID.+ trainedFor: [...new Set(e.loras.filter(runsSomewhere).flatMap((l) => familyModels(l)))],})),),items: [{ id: "", role: "tool", text: `Checked your elements (${els.length})` }],diff --git a/src/server/loras.ts b/src/server/loras.tsindex a6f9e681..5c9d5738 100644--- a/src/server/loras.ts+++ b/src/server/loras.ts@@ -426,9 +426,10 @@ export function ownCopy(file: string): string | null {*/export async function keepTrainedLora(file: string, from: { path?: string; url?: string }): Promise<string> {const dest = lorasPath(TRAINED_DIR, file);- fs.mkdirSync(path.dirname(dest), { recursive: true });+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });if (from.path) {- if (path.resolve(from.path) !== dest) fs.copyFileSync(from.path, dest);+ // Asynchronous: a LoRA of a few hundred MB doesn't hold up the server while it copies.+ if (path.resolve(from.path) !== dest) await fs.promises.copyFile(from.path, dest);return dest;}if (!from.url) throw new LoraError(`Nowhere to copy ${file} from`);diff --git a/src/server/training.ts b/src/server/training.tsindex a2e9b9c1..a00a95ee 100644--- a/src/server/training.ts+++ b/src/server/training.ts@@ -20,6 +20,7 @@ import {trainedLoraUrl,trainingCaption,trainingKind,+ trainsKind,triggerFor,type TrainingFamily,type TrainingTarget,@@ -85,6 +86,10 @@ interface Meta {photos?: number;/** When the person's consent was confirmed (characters only). */consentAt?: number;+ /** The LoRA's file name (fuobe/<handle>-<id>.safetensors), once trained. */+ file?: string;+ /** Fuobe's own copy of a hosted trainer's LoRA: downloading in the background, kept, or not kept (the trainer's URL serves). */+ keep?: "pending" | "kept" | "failed";}const metaOf = (r: Pick<Row, "meta_json">): Meta => JSON.parse(r.meta_json ?? "{}") as Meta;@@ -175,6 +180,7 @@ export function startTraining(elementId: string, targetId: string, opts: { conseif (!target.kinds.includes(trainingKind(el.kind))) {throw new Error(trainingKind(el.kind) === "style" ? `${el.name} is a style: pick a style training` : `That training is for styles: pick a character training for ${el.name}`);}+ if (!trainsKind(target, el.kind)) throw new Error(`That training is for ${target.onlyFor?.join(" and ")}s only: pick another one for ${el.name}`);if (needsConsent(el.kind) && !opts.consent) throw new Error(SOUL_ID_COPY.needsConsent);const images = photosOf(el);const few = photosBlocker(images.length, el.name);@@ -244,13 +250,16 @@ function settleElement(elementId: string) {/*** Put a trained LoRA on the element. A retrain replaces the earlier LoRA of the same family (and the per-model LoRAs* from before O3 that family covers); another family's LoRA stays (Fuobe Soul and Fuobe Soul HD side by side).+ * A demo's stand-in never replaces a real LoRA: it goes on only where the family has none. Returns whether it went on.*/-function addIdentity(elementId: string, lora: ElementLora) {+function addIdentity(elementId: string, lora: ElementLora): boolean {const el = getElement(elementId);- if (!el) return;+ if (!el) return false;const fam = lora.family;const covered = (l: ElementLora) => !l.referenceId && (fam ? (l.family ?? familyOfModel(l.modelId)) === fam : l.modelId === lora.modelId);+ if (lora.demo && el.loras.some((l) => covered(l) && !l.demo)) return false;updateElement(elementId, { loras: [...el.loras.filter((l) => !covered(l)), lora] });+ return true;}/** A trained LoRA's file in ComfyUI's loras folder (and Fuobe's copy): one name per training, so a retrain never reuses a cached one. */@@ -346,6 +355,8 @@ export async function pollTrainings(): Promise<void> {.all(Date.now() - STALE_TRAINING_MS) as Row[];for (const r of stale) if (!submittingTrainings().has(r.id)) fail(r.id, r.element_id, "Interrupted before it reached the trainer — start it again");for (const r of db().prepare("SELECT * FROM trainings WHERE provider = 'higgsfield' AND status IN ('queued','running')").all() as Row[]) fail(r.id, r.element_id, RETIRED_SOUL_ID);+ // Copies of hosted LoRAs a restart cut off: start them again.+ for (const r of db().prepare(`SELECT * FROM trainings WHERE status = 'succeeded' AND meta_json LIKE '%"keep":"pending"%'`).all() as Row[]) keepInBackground(r);const rows = db().prepare("SELECT * FROM trainings WHERE status = 'running' AND external_id IS NOT NULL").all() as Row[];await Promise.all(rows.map((r) =>@@ -357,6 +368,47 @@ export async function pollTrainings(): Promise<void> {);}+/** Downloads of hosted trainers' LoRAs into Fuobe's folder, by training id (shared across hot reloads). */+declare global {+ var __fuobeLoraKeeps: Map<string, Promise<void>> | undefined;+}+const keeping = (): Map<string, Promise<void>> => (globalThis.__fuobeLoraKeeps ??= new Map());++/** Wait for the LoRA copies still downloading (tests, and a clean shutdown). */+export async function trainedCopiesSettled(): Promise<void> {+ while (keeping().size) await Promise.all([...keeping().values()]);+}++function setKeep(id: string, keep: Meta["keep"], message?: string | null) {+ const r = db().prepare("SELECT meta_json FROM trainings WHERE id = ?").get(id) as Pick<Row, "meta_json"> | undefined;+ if (!r) return;+ update(id, { meta_json: JSON.stringify({ ...metaOf(r), keep }), ...(message !== undefined && { message }) });+}++/**+ * Fuobe's own copy of a LoRA a hosted trainer made (fal's storage isn't forever), downloaded in the background so the+ * runner's polling never waits on it (a FLUX LoRA is hundreds of MB). Until it lands, fal's URL serves cloud runs and+ * the GPU downloads it from there; once it lands the element's LoRA is marked as Fuobe's own.+ */+function keepInBackground(r: Pick<Row, "id" | "element_id" | "meta_json">) {+ if (keeping().has(r.id)) return;+ const meta = metaOf(r);+ const el = getElement(r.element_id);+ const lora = el?.loras.find((l) => l.file === meta.file && l.url);+ if (!el || !lora?.url || !meta.file) return setKeep(r.id, "failed");+ const { file, url } = { file: meta.file, url: lora.url };+ const job = keepTrainedLora(file, { url })+ .then(() => {+ recordTrainedMirror(file, "fal", url);+ const now = getElement(r.element_id);+ if (now) updateElement(r.element_id, { loras: now.loras.map((l) => (l.file === file && l.url === url ? { ...l, own: true as const } : l)) });+ setKeep(r.id, "kept");+ })+ .catch((e) => setKeep(r.id, "failed", `The LoRA is on fal, but Fuobe couldn't keep a copy (${(e as Error).message}): your GPU downloads it from fal when a run needs it`))+ .finally(() => keeping().delete(r.id));+ keeping().set(r.id, job);+}+/** The LoRA a finished training puts on the element. */function trainedLora(r: Row, t: TrainingTarget, file: string, fields: Partial<ElementLora>): ElementLora {return {@@ -383,9 +435,15 @@ async function pollOne(r: Row) {if (r.provider === "demo") {const p = Math.min(1, (Date.now() - r.created_at) / DEMO_TRAINING_MS);if (p < 1) return update(r.id, { progress: p, message: `Demo training · step ${Math.round(p * t.steps)}/${t.steps}` });- // Nothing real was trained: the element keeps working from its photos.- addIdentity(r.element_id, trainedLora(r, t, file, { demo: true }));- return done(r, "Demo: no LoRA was trained. Add a fal.ai key or your AI-Toolkit in Settings, then train again");+ // Nothing real was trained: the element keeps working from its photos, or from the real LoRA it already has.+ const added = addIdentity(r.element_id, trainedLora(r, t, file, { demo: true }));+ const fam = TRAINING_FAMILIES[t.family].name;+ return done(+ r,+ added+ ? "Demo: no LoRA was trained. Add a fal.ai key or your AI-Toolkit in Settings, then train again"+ : `Demo: no LoRA was trained, so the ${fam} Soul ID you trained before stays. Add a fal.ai key or your AI-Toolkit in Settings to retrain`,+ );}if (r.provider === "fal") {@@ -401,20 +459,15 @@ async function pollOne(r: Row) {const out = (await falFetch(meta.responseUrl!)) as Record<string, unknown>;const url = trainedLoraUrl(t, out);if (!url) return fail(r.id, r.element_id, `No LoRA in fal's response: ${JSON.stringify(out).slice(0, 200)}`);- // Fuobe keeps its own copy (fal's storage isn't forever): open runs copy it into ComfyUI, cloud runs send it again- // once fal's copy is old. fal's URL serves cloud runs until then.- update(r.id, { message: "Saving the LoRA" });- let message: string | null = null;- let own = false;- try {- await keepTrainedLora(file, { url });- own = true;- } catch (e) {- message = `The LoRA is on fal, but Fuobe couldn't keep a copy (${(e as Error).message}): your GPU downloads it from fal when a run needs it`;- }+ // The LoRA runs at once from fal's URL (cloud runs use it, the GPU downloads it); Fuobe's own copy follows in the+ // background (keepInBackground), for when fal's copy is gone.recordTrainedMirror(file, "fal", url);- addIdentity(r.element_id, trainedLora(r, t, file, { url, ...(own && { own: true as const }) }));- return done(r, message);+ addIdentity(r.element_id, trainedLora(r, t, file, { url }));+ const finished = { ...r, meta_json: JSON.stringify({ ...meta, file, keep: "pending" }) };+ update(r.id, { meta_json: finished.meta_json });+ done(r);+ keepInBackground(finished);+ return;}// AI-Toolkit@@ -433,23 +486,25 @@ async function pollOne(r: Row) {const latest = files.at(-1);if (!latest) return fail(r.id, r.element_id, "AI-Toolkit finished but saved no .safetensors file");const lorasDir = getSetting("comfyLorasDir");- let message: string | null = null;- let own = false;- if (fs.existsSync(latest)) {- // Fuobe's copy (for cloud runs and safe keeping), then ComfyUI's.- await keepTrainedLora(file, { path: latest });- own = true;- if (lorasDir) {- const dest = lorasPath(lorasDir, file);- fs.mkdirSync(path.dirname(dest), { recursive: true });- fs.copyFileSync(latest, dest);+ const fam = TRAINING_FAMILIES[t.family];+ if (!fs.existsSync(latest)) {+ // AI-Toolkit runs on another machine: the file has to be copied by hand. A family with no model on the GPU runs+ // only in the cloud, which needs Fuobe to have the file: nothing goes on the element until it's attached here.+ if (!fam.lead.open) {+ return done(r, `AI-Toolkit saved the LoRA on its own machine (${latest}). ${fam.name} runs only in the cloud, so Fuobe needs the file: copy it into the LoRA folder on this machine (Settings → LoRAs) as ${file}, then attach it under Train anywhere`);}- } else {- // AI-Toolkit runs on another machine: the file has to be copied by hand.- message = `Copy ${latest} to ComfyUI/models/loras/${file}`;+ addIdentity(r.element_id, trainedLora(r, t, file, {}));+ return done(r, `Copy ${latest} to ComfyUI/models/loras/${file}`);+ }+ // Fuobe's copy (for cloud runs and safe keeping), then ComfyUI's.+ await keepTrainedLora(file, { path: latest });+ if (lorasDir) {+ const dest = lorasPath(lorasDir, file);+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });+ await fs.promises.copyFile(latest, dest);}- addIdentity(r.element_id, trainedLora(r, t, file, own ? { own: true } : {}));- return done(r, message);+ addIdentity(r.element_id, trainedLora(r, t, file, { own: true }));+ return done(r);}function done(r: Row, message: string | null = null) {@@ -504,6 +559,7 @@ export async function attachLora(elementId: string, input: { file: string; triggconst file = input.file.trim().replace(/^\/+/, "");if (!/\.safetensors$/.test(file) || file.includes("..")) throw new Error("Enter the LoRA's file name inside ComfyUI/models/loras, ending in .safetensors");const family = input.family ?? "z-image-turbo";+ const fam = TRAINING_FAMILIES[family];const dir = getSetting("comfyLorasDir");let own = !!ownCopy(file);if (!own && dir) {@@ -518,6 +574,10 @@ export async function attachLora(elementId: string, input: { file: string; triggown = true;}}+ // A family with no model on the GPU runs only in the cloud, from Fuobe's copy of the file.+ if (!own && !fam.lead.open) {+ throw new Error(`${fam.name} runs only in the cloud, so Fuobe needs the file itself: put ${file} in the LoRA folder on this machine (Settings → LoRAs), then attach it again`);+ }addIdentity(elementId, {engine: "open",modelId: familyLead(family, "open"),diff --git a/tests/soul-id-runtime.test.ts b/tests/soul-id-runtime.test.tsindex 1c1fae0f..b281eb51 100644--- a/tests/soul-id-runtime.test.ts+++ b/tests/soul-id-runtime.test.ts@@ -5,7 +5,7 @@ import path from "node:path";import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { onEngine } from "@/lib/catalog/engines";import { getModel } from "@/lib/catalog";-import { identityFor, SOUL_ID_COPY } from "@/lib/catalog/training";+import { identityFor, identityKey, SOUL_ID_COPY } from "@/lib/catalog/training";// fal's storage upload goes through its client: the dataset zip and a LoRA sent to fal land here instead.const uploads = vi.hoisted(() => [] as { data: Buffer; type: string; name?: string }[]);@@ -27,7 +27,7 @@ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soul-id-"));process.env.FUOBE_DATA_DIR = dir;const { db } = await import("@/server/db");const { createElement, getElement, updateElement } = await import("@/server/elements");-const { startTraining, pollTrainings, listTrainings, trainingKit, attachLora, RETIRED_SOUL_ID } = await import("@/server/training");+const { startTraining, pollTrainings, listTrainings, trainingKit, attachLora, trainedCopiesSettled, RETIRED_SOUL_ID } = await import("@/server/training");const { ensureLorasOnComfy, prepareCloudLoras, listLoraCopies, TRAINED_DIR } = await import("@/server/loras");const { setSetting } = await import("@/server/settings");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -59,7 +59,9 @@ beforeEach(() => {setSetting("engineMode", "both");setSetting("demoMode", "auto");});-afterEach(() => {+afterEach(async () => {+ // LoRA copies still downloading in the background finish on the fake network.+ await trainedCopiesSettled();globalThis.fetch = realFetch;});@@ -89,6 +91,9 @@ describe("starting a Soul ID training", () => {it("refuses too few photos, the wrong kind of training and a Higgsfield target", () => {const few = character(3);expect(() => startTraining(few.id, "fal-z-image", { consent: true })).toThrow(/at least 5 photos/);+ // FLUX's portrait trainer crops to a face: a place doesn't train on it.+ const room = createElement({ name: "Loft", kind: "location", references: photos(6) });+ expect(() => startTraining(room.id, "fal-flux1-portrait")).toThrow(/for characters only/);const el = character();expect(() => startTraining(el.id, "fal-z-image-style", { consent: true })).toThrow(/for styles/);expect(() => startTraining(el.id, "soul-id-v2", { consent: true })).toThrow(/Unknown training target/);@@ -154,6 +159,7 @@ describe("a finished training", () => {const { id, el } = running({ target: "fal-z-image", provider: "fal", externalId: "req-2", meta: { statusUrl: "https://queue.fal.test/s/2", responseUrl: "https://queue.fal.test/r/2", family: "z-image-turbo" } });await pollTrainings();expect(listTrainings(el.id).find((t) => t.id === id)).toMatchObject({ status: "succeeded", message: null });+ await trainedCopiesSettled();const after = getElement(el.id)!;expect(after.status).toBe("ready");const l = after.loras[0];@@ -175,6 +181,61 @@ describe("a finished training", () => {expect(getElement(el.id)!.loras.map((x) => x.family)).toEqual(["qwen-image-2512", "z-image-turbo"]);});+ it("finishes a fal training without waiting for Fuobe's copy of the LoRA, which follows in the background", async () => {+ const LORA = Buffer.from("big-lora".repeat(64));+ let release = () => {};+ routes["https://queue.fal.test/s/bg"] = () => json({ status: "COMPLETED" });+ routes["https://queue.fal.test/r/bg"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/bg.safetensors" } });+ // The download hangs until released: the runner's poll must not wait on it.+ routes["https://v3.fal.media/files/bg.safetensors"] = (c) =>+ c.method === "HEAD" ? new Response(null, { status: 200 }) : (new Promise<Response>((resolve) => (release = () => resolve(new Response(LORA, { headers: { "content-length": String(LORA.length) } })))) as unknown as Response);+ const { id, el } = running({ target: "fal-flux2-dev", provider: "fal", externalId: "req-bg", meta: { statusUrl: "https://queue.fal.test/s/bg", responseUrl: "https://queue.fal.test/r/bg", family: "flux2-dev" } });+ await pollTrainings();+ expect(listTrainings(el.id).find((t) => t.id === id)).toMatchObject({ status: "succeeded" });+ expect(getElement(el.id)!.status).toBe("ready");+ const before = getElement(el.id)!.loras[0];+ expect(before).toMatchObject({ family: "flux2-dev", url: "https://v3.fal.media/files/bg.safetensors" });+ expect(before.own).toBeUndefined();+ // It already runs on both engines from fal's URL; the next poll doesn't start a second copy.+ expect(identityFor([before], getModel("oss-flux2-dev")!)).toBe(before);+ await pollTrainings();+ await wait(() => calls.some((c) => c.url === "https://v3.fal.media/files/bg.safetensors" && c.method === "GET"));+ release();+ await trainedCopiesSettled();+ const after = getElement(el.id)!.loras[0];+ expect(after).toMatchObject({ own: true, url: before.url });+ expect(fs.readFileSync(path.join(TRAINED_DIR, after.file))).toEqual(LORA);+ expect(calls.filter((c) => c.url === "https://v3.fal.media/files/bg.safetensors" && c.method === "GET")).toHaveLength(1);+ });++ it("starts again a LoRA copy a restart cut off, and says so when it can't be kept", async () => {+ const el = character();+ const file = "fuobe/restart-abc123.safetensors";+ updateElement(el.id, { loras: [{ engine: "cloud", modelId: "fuobe-soul", family: "z-image-turbo", file, url: "https://v3.fal.media/files/restart.safetensors", trigger: "t" }] });+ const insert = (id: string) =>+ db()+ .prepare(`INSERT INTO trainings (id, element_id, target, provider, status, external_id, meta_json, trigger_word, created_at, updated_at) VALUES (?, ?, 'fal-z-image', 'fal', 'succeeded', 'r', ?, 't', ?, ?)`)+ .run(id, el.id, JSON.stringify({ file, keep: "pending" }), Date.now(), Date.now());+ insert("trestart1");+ routes["https://v3.fal.media/files/restart.safetensors"] = () => new Response(Buffer.from("restart"), { headers: { "content-length": "7" } });+ await pollTrainings();+ await trainedCopiesSettled();+ expect(getElement(el.id)!.loras[0].own).toBe(true);+ expect(JSON.parse((db().prepare("SELECT meta_json FROM trainings WHERE id = 'trestart1'").get() as { meta_json: string }).meta_json).keep).toBe("kept");+ // fal's copy gone: the training says the GPU fetches it from fal, and it isn't tried again.+ updateElement(el.id, { loras: [{ engine: "cloud", modelId: "fuobe-soul", family: "z-image-turbo", file: "fuobe/gone-abc123.safetensors", url: "https://v3.fal.media/files/gone.safetensors", trigger: "t" }] });+ db()+ .prepare(`INSERT INTO trainings (id, element_id, target, provider, status, external_id, meta_json, trigger_word, created_at, updated_at) VALUES ('trestart2', ?, 'fal-z-image', 'fal', 'succeeded', 'r', ?, 't', ?, ?)`)+ .run(el.id, JSON.stringify({ file: "fuobe/gone-abc123.safetensors", keep: "pending" }), Date.now(), Date.now());+ await pollTrainings();+ await trainedCopiesSettled();+ expect(listTrainings(el.id).find((t) => t.id === "trestart2")?.message).toMatch(/couldn't keep a copy/);+ const tries = calls.filter((c) => c.url.includes("gone.safetensors")).length;+ await pollTrainings();+ await trainedCopiesSettled();+ expect(calls.filter((c) => c.url.includes("gone.safetensors"))).toHaveLength(tries);+ });+it("reads Krea 2's LoRA from lora_file and records it for Krea 2's hosted LoRA model", async () => {routes["https://queue.fal.test/s/k"] = () => json({ status: "COMPLETED" });routes["https://queue.fal.test/r/k"] = () => json({ lora_file: { url: "https://v3.fal.media/files/krea.safetensors" }, config_file: { url: "https://v3.fal.media/files/c.json" } });@@ -236,6 +297,40 @@ describe("a finished training", () => {expect(identityFor([l], onEngine(getModel("fuobe-soul")!, "cloud"))).toBeUndefined();});+ it("never lets a demo retrain replace a real Soul ID of the family", async () => {+ // GPU trained for real; no fal key, demo mode auto: the cloud card's Retrain runs as a demo.+ setSetting("falKey", "");+ const { el } = running({ target: "fal-z-image", provider: "demo", externalId: "demo", age: 9_000 });+ const real = { engine: "open" as const, modelId: "fuobe-soul", family: "z-image-turbo" as const, target: "aitk-z-image", file: "fuobe/real-abc123.safetensors", trigger: "mayafz", own: true as const, trainedAt: 1 };+ updateElement(el.id, { loras: [real] });+ await pollTrainings();+ expect(getElement(el.id)!.loras).toEqual([real]);+ expect(listTrainings(el.id)[0].message).toMatch(/Fuobe Soul and Soul Cinema Soul ID you trained before stays/);+ expect(identityFor(getElement(el.id)!.loras, onEngine(getModel("fuobe-soul")!, "open"))).toEqual(real);+ // The same through the API's own path: a demo started now, finished later.+ const t = startTraining(el.id, "fal-z-image", { consent: true });+ expect(t.provider).toBe("demo");+ db().prepare("UPDATE trainings SET created_at = ? WHERE id = ?").run(Date.now() - 9_000, t.id);+ await pollTrainings();+ expect(getElement(el.id)!.loras).toEqual([real]);+ });++ it("puts nothing on the element when a remote AI-Toolkit trains a family that runs only in the cloud, and says how to bring the file", async () => {+ routes["http://aitk.test/api/jobs?id=job-k4"] = () => json({ job: { status: "completed" } });+ routes["http://aitk.test/api/jobs/job-k4/files"] = () => json({ files: [{ path: "/elsewhere/output/maya_000002000.safetensors" }] });+ const { id, el } = running({ target: "aitk-flux2-klein-4b", provider: "ai-toolkit", externalId: "job-k4" });+ await pollTrainings();+ expect(getElement(el.id)!.loras).toEqual([]);+ expect(listTrainings(el.id).find((t) => t.id === id)).toMatchObject({ status: "succeeded", message: expect.stringMatching(/FLUX\.2 \[klein\] 4B runs only in the cloud, so Fuobe needs the file/) });+ // A family with a GPU model still gets the LoRA, to copy into ComfyUI by hand.+ routes["http://aitk.test/api/jobs?id=job-z"] = () => json({ job: { status: "completed" } });+ routes["http://aitk.test/api/jobs/job-z/files"] = () => json({ files: [{ path: "/elsewhere/output/maya_z.safetensors" }] });+ const z = running({ target: "aitk-z-image", provider: "ai-toolkit", externalId: "job-z" });+ await pollTrainings();+ expect(getElement(z.el.id)!.loras[0]).toMatchObject({ engine: "open", family: "z-image-turbo" });+ expect(listTrainings(z.el.id)[0].message).toMatch(/^Copy \/elsewhere\/output\/maya_z\.safetensors to ComfyUI/);+ });+it("retires a Higgsfield Soul ID training that was still running", async () => {const { id, el } = running({ target: "soul-id-v2", provider: "higgsfield", externalId: "hf-ref" });await pollTrainings();@@ -280,5 +375,17 @@ describe("training anywhere", () => {expect(flux).toMatchObject({ modelId: "oss-flux1-dev", own: true });expect(identityFor([flux], getModel("oss-flux1-krea")!)).toBe(flux);expect(identityFor([flux], getModel("flux-1-dev-lora-cloud")!)).toBe(flux);+ // Removing the FLUX one in the Train dialog keeps the Z-Image one with the same file.+ const route = await import("@/app/api/elements/[id]/route");+ const res = await route.PATCH(+ new Request("http://x", { method: "PATCH", body: JSON.stringify({ removeIdentities: [identityKey(flux)] }) }),+ { params: Promise.resolve({ id: el.id }) } as Parameters<typeof route.PATCH>[1],+ );+ expect(res.status).toBe(200);+ expect(getElement(el.id)!.loras.map((l) => l.family)).toEqual(["z-image-turbo"]);+ // A cloud-only family needs the file here to send it: a name alone can't run anywhere.+ await expect(attachLora(el.id, { file: "mine/elsewhere.safetensors", trigger: "t", family: "flux2-klein-4b" })).rejects.toThrow(/runs only in the cloud, so Fuobe needs the file/);+ await attachLora(el.id, { file: "mine/maya.safetensors", trigger: "t", family: "flux2-klein-4b" });+ expect(getElement(el.id)!.loras.find((l) => l.family === "flux2-klein-4b")).toMatchObject({ own: true, modelId: "flux-2-klein-4b-cloud" });});});diff --git a/tests/training.test.ts b/tests/training.test.tsindex 53dae93e..974ec2c3 100644--- a/tests/training.test.ts+++ b/tests/training.test.ts@@ -18,7 +18,9 @@ import {getTrainer,getTrainingTarget,identityFor,+ identityKey,loraFamily,+ runsSomewhere,needsConsent,photosBlocker,photoTips,@@ -129,8 +131,13 @@ describe("Fuobe Soul ID targets (build plan O3)", () => {"fal-flux2-klein-9b","fal-krea-2",]);- // The portrait trainer crops to a face: no style on it. Fuobe Soul's style trains on fal's Z-Image trainer.+ // The portrait trainer crops to a face: no style on it, and no place or object either (they train on FLUX.1 on the GPU).+ // Fuobe Soul's style trains on fal's Z-Image trainer.expect(targetsFor("style").map((t) => t.id)).not.toContain("fal-flux1-portrait");+ for (const kind of ["location", "prop"] as const) {+ expect(targetsFor(kind).map((t) => t.id)).not.toContain("fal-flux1-portrait");+ expect(targetsFor(kind).map((t) => t.id)).toContain("aitk-flux1-dev");+ }expect(targetsFor("style").map((t) => t.id).slice(0, 2)).toEqual(["aitk-z-image", "fal-z-image-style"]);expect(targetsFor("voice")).toEqual([]);expect(needsConsent("character")).toBe(true);@@ -160,7 +167,15 @@ describe("Fuobe Soul ID targets (build plan O3)", () => {// Trainers that take the zip in images_data_url and a trigger phrase instead of a default caption.expect(falTrainingInput(getTrainingTarget("fal-flux1-portrait")!, "z", "photo of mayafz", "mayafz")).toEqual({ images_data_url: "z", steps: 2500, trigger_phrase: "mayafz" });expect(falTrainingInput(getTrainingTarget("fal-krea-2")!, "z", "photo of mayafz", "mayafz")).toEqual({ images_data_url: "z", steps: 1000, trigger_phrase: "mayafz", resolution: 1024 });- expect(falTrainingInput(getTrainingTarget("fal-flux2-dev")!, "z", "photo of mayafz", "mayafz")).toEqual({ image_data_url: "z", steps: 1000, default_caption: "photo of mayafz" });+ // FLUX.2 [dev] also runs on ComfyUI: its LoRA comes back with ComfyUI's key names. The cloud-only klein families keep fal's.+ expect(falTrainingInput(getTrainingTarget("fal-flux2-dev")!, "z", "photo of mayafz", "mayafz")).toEqual({+ image_data_url: "z",+ steps: 1000,+ default_caption: "photo of mayafz",+ output_lora_format: "comfy",+ });+ expect(falTrainingInput(getTrainingTarget("fal-flux2-klein-9b")!, "z", "photo of mayafz")).not.toHaveProperty("output_lora_format");+ expect(falTrainingInput(getTrainingTarget("fal-flux2-klein-4b")!, "z", "photo of mayafz")).not.toHaveProperty("output_lora_format");expect(datasetName(0, "jpg")).toBe("001.jpg");expect(datasetName(11, "txt")).toBe("012.txt");});@@ -203,6 +218,13 @@ describe("Fuobe Soul ID targets (build plan O3)", () => {const body = buildPayload(route.map!, { prompt: "x", loras: [{ file: "fuobe/m.safetensors", url: "https://x/m.safetensors", strength: 0.9 }] });expect(body.loras, id).toEqual([{ path: "https://x/m.safetensors", scale: 0.9 }]);}+ // Each carries its weights' licence as data for Settings (information, never a gate).+ expect(getModel("flux-1-dev-lora-cloud")!.licence).toMatchObject({ licence: "FLUX.1 [dev] Non-Commercial License", commercial: false });+ expect(getModel("flux-2-dev-lora-cloud")!.licence).toMatchObject({ licence: "FLUX [dev] Non-Commercial License", commercial: false });+ expect(getModel("flux-2-klein-9b-lora-cloud")!.licence).toMatchObject({ commercial: false });+ expect(getModel("krea-2-turbo-lora-cloud")!.licence).toMatchObject({ licence: expect.stringMatching(/Krea 2 Community/), commercial: null });+ expect(getModel("flux-1-krea-lora-cloud")!.licence?.note).toMatch(/non-commercial/);+ expect(getModel("z-image-turbo-cloud")!.licence).toMatchObject({ licence: "Apache-2.0", commercial: true });});it("switches hosted Z-Image to its LoRA endpoint only when a LoRA URL is present", () => {@@ -293,6 +315,36 @@ describe("a Soul ID on every model of its family, on both engines", () => {it("never uses a demo training or a Higgsfield Soul ID", () => {expect(identityFor([lora({ demo: true, url: "x" })], cloudSoul)).toBeUndefined();expect(identityFor([{ engine: "cloud", modelId: "fuobe-soul", file: "", trigger: "", referenceId: "ref" }], cloudSoul)).toBeUndefined();+ // What Assist reports as trained: only LoRAs some run can use.+ expect(runsSomewhere(lora({ demo: true, url: "x" }))).toBe(false);+ expect(runsSomewhere(lora({ modelId: "soul-2", family: undefined, file: "", referenceId: "ref" }))).toBe(false);+ expect(runsSomewhere(lora({ url: "x" }))).toBe(true);+ // A GPU LoRA without Fuobe's copy, for a family that runs only in the cloud: nothing can run it.+ expect(runsSomewhere(lora({ engine: "open", modelId: "flux-2-klein-4b-cloud", family: "flux2-klein-4b" }))).toBe(false);+ expect(runsSomewhere(lora({ engine: "open", modelId: "flux-2-klein-4b-cloud", family: "flux2-klein-4b", own: true }))).toBe(true);+ });++ it("names one file attached for two families as two LoRAs, so removing one keeps the other", () => {+ const z = lora({ file: "mine/maya.safetensors", own: true });+ const flux = lora({ file: "mine/maya.safetensors", own: true, modelId: "oss-flux1-dev", family: "flux1-dev" });+ expect(identityKey(z)).not.toBe(identityKey(flux));+ expect([z, flux].filter((l) => ![identityKey(flux)].includes(identityKey(l)))).toEqual([z]);+ expect(identityKey(lora({ modelId: "soul-2", family: undefined, file: "", referenceId: "ref-1" }))).toBe("ref-1");+ });++ it("scales an @character's LoRA by the character strength on FLUX too, and never sends the setting to the provider", () => {+ const flux = getModel("flux-1-dev-lora-cloud")!;+ const el = maya([lora({ url: "https://v3.fal.media/maya.safetensors", own: true, modelId: "flux-1-dev-lora-cloud", family: "flux1-dev" })]);+ const { request } = applyMentions({ feature: "image", modelId: flux.id, prompt: "@Maya on a beach" }, flux, [el]);+ const plan = planGeneration({ ...request, params: { extra: { characterStrength: 0.5 } } }, getModel, getPreset);+ expect(plan.loras[0]).toMatchObject({ file: "fuobe/maya-abc123.safetensors", strength: 0.8 });+ expect(plan.params.extra?.characterStrength).toBeUndefined();+ // The server sends Fuobe's own LoRA by the copy it picks (prepareCloudLoras sets hostedUrl).+ const body = buildPayload(flux.routes[0].map!, { ...plan.params, prompt: plan.prompt, loras: plan.loras.map((l) => ({ ...l, hostedUrl: l.url })) });+ expect(body.loras).toEqual([{ path: "https://v3.fal.media/maya.safetensors", scale: 0.8 }]);+ expect(body).not.toHaveProperty("characterStrength");+ // Without the setting the LoRA keeps its own strength.+ expect(planGeneration(request, getModel, getPreset).loras[0].strength).toBe(1);});it("puts the @character's LoRA first on Fuobe Soul, at the character strength's scale", () => {