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.

Models & licences: every model, LoRA and node pack carries its licence, and admin switches decide what runs

Claudef618a96c2b71
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 4af517ac..5a8f1f94 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -264,14 +264,7 @@ export function planGeneration(
} else if (req.loras?.length) loras = [...req.loras, ...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 electricity
- // effect. …", see withOssLoras), which means nothing to the model without the LoRA.
- const keptTriggers = new Set(kept.map((l) => l.trigger).filter(Boolean));
- for (const l of loras) {
- if ((l.strength ?? 1) !== 0 || !l.trigger || keptTriggers.has(l.trigger)) continue;
- const lead = [". ", ", ", " "].map((sep) => l.trigger + sep).find((t) => prompt.startsWith(t));
- if (lead) prompt = prompt.slice(lead.length);
- }
+ prompt = withoutTriggers(prompt, loras.filter((l) => !kept.includes(l)), kept);
loras = kept;
// Multi-shot: the clip is as long as its shots, and models without per-shot prompts get them written out.
@@ -571,6 +564,21 @@ export function pricingAt(p: Pricing, now = Date.now()): Pricing {
*/
const CLIP_LENGTH_OPS = new Set<Operation>(["upscale-video", "interpolate", "sdr-to-hdr", "export-video"]);
+/**
+ * A prompt without the trigger words of LoRAs a run leaves out: an open motion's template starts with its LoRA's
+ * trigger ("e13c7r1c electricity effect. …", see withOssLoras), which means nothing to the model without the LoRA.
+ * A trigger a kept LoRA shares stays.
+ */
+export function withoutTriggers(prompt: string, dropped: Pick<LoraRef, "trigger">[], kept: Pick<LoraRef, "trigger">[]): string {
+ const keptTriggers = new Set(kept.map((l) => l.trigger).filter(Boolean));
+ for (const l of dropped) {
+ if (!l.trigger || keptTriggers.has(l.trigger)) continue;
+ const lead = [". ", ", ", " "].map((sep) => l.trigger + sep).find((t) => prompt.startsWith(t));
+ if (lead) prompt = prompt.slice(lead.length);
+ }
+ return prompt;
+}
+
/**
* Which of a plan's LoRAs a route really applies, and why the others are left out: ComfyUI loads every file
* (injectLoras); a cloud route carries the ones fitLoras keeps (the licence allows hosting, there is a URL to
@@ -581,7 +589,7 @@ export function routeLoras(route: Pick<ModelRoute, "provider" | "map" | "loraEnd
const applied = fitLoras(loras, route).loras;
const field = routeLoraField(route);
const why = (l: LoraRef) => {
- if (localOnly(l)) return "its licence doesn't allow hosting, so it runs only on your GPU";
+ if (localOnly(l)) return "it is licensed for your GPU only, and Settings → Models & licences keeps such LoRAs off the cloud";
if (gated(l) && !l.hostedUrl) return "it is in a gated Hugging Face repo, so it runs only on your GPU";
if (!cloudPath(l) && !needsToken(l.url)) return "no URL to send to the LoRA endpoint";
if (!field) return "this route takes no LoRAs";
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 340e22cc..b02b2acc 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -741,6 +741,11 @@ export interface LoraRef {
*/
version?: string;
licence?: LoraLicence;
+ /**
+ * Set by the server on a run's LoRAs while Settings → Models & licences keeps LoRAs licensed for your GPU only
+ * off the cloud: a cloud route then leaves such a LoRA out (localOnly). Without it they are sent like any other.
+ */
+ keepOnGpu?: true;
}
/** Scale limits of a LoRA field. */
diff --git a/src/lib/licences.ts b/src/lib/licences.ts
index c9173d00..32a937e4 100644
--- a/src/lib/licences.ts
+++ b/src/lib/licences.ts
@@ -194,3 +194,255 @@ export const FLAG_LABEL: Record<LicenceFlag, string> = {
territory: "Not everywhere",
conditions: "Conditions apply",
};
+
+// ---------------------------------------------------------------------------
+// Licence classes (Settings → Models & licences). The owner's decision of 2026-10-27: licences are
+// information, never a gate. Every model, LoRA and node pack carries its licence as data, sorted into a
+// class an admin can switch off; everything is on by default.
+
+export type LicenceClass = "commercial" | "conditions" | "regions" | "non-commercial" | "research" | "paid-api" | "unknown";
+
+/** In the order Settings lists them: the freest first, then the cloud's, then what isn't recorded. */
+export const LICENCE_CLASSES: LicenceClass[] = ["commercial", "conditions", "regions", "non-commercial", "research", "paid-api", "unknown"];
+
+export const CLASS_LABEL: Record<LicenceClass, string> = {
+ commercial: "Commercial use allowed",
+ conditions: "Commercial use with conditions",
+ regions: "Restricted regions",
+ "non-commercial": "Non-commercial",
+ research: "Research only",
+ "paid-api": "Proprietary paid API",
+ unknown: "Licence unknown",
+};
+
+/** What a class means, in one line (the section headers in Settings). */
+export const CLASS_HINT: Record<LicenceClass, string> = {
+ commercial: "Open licences that let you sell what you make (Apache-2.0, MIT, BSD) and tools with no model weights.",
+ conditions: "Commercial use is allowed within limits: a revenue ceiling, registration, attribution or use rules.",
+ regions: "The licence leaves out some countries or regions.",
+ "non-commercial": "The weights or code may not be used commercially without another licence.",
+ research: "Released for research only.",
+ "paid-api": "Closed or hosted models you pay for per run, under the provider's and the vendor's terms.",
+ unknown: "No licence is recorded yet: check the model card or repository.",
+};
+
+/** A model's, LoRA's or node pack's licence, as information. */
+export interface LicenceInfo {
+ /** The licence's name ("Apache-2.0", "FLUX.1 [dev] Non-Commercial License", "fal.ai · paid API"). */
+ name: string;
+ /** Where to read it: the licence text, or the model card / repository that states it. */
+ url?: string;
+ class: LicenceClass;
+ /** Restricted regions: who it leaves out ("the EU, UK and South Korea"). */
+ excludes?: string;
+ /** One line: the licence as recorded (what it covers, its catches). */
+ note: string;
+ /** Notices the app must show ("Built with DINOv3"). */
+ notices?: string[];
+}
+
+/** How strict a class is, for a model whose parts carry several licences (the strictest one counts). */
+const STRICTNESS: Record<LicenceClass, number> = { commercial: 0, "paid-api": 1, conditions: 2, unknown: 3, regions: 4, "non-commercial": 5, research: 6 };
+
+export const stricter = (a: LicenceClass, b: LicenceClass): LicenceClass => (STRICTNESS[b] > STRICTNESS[a] ? b : a);
+
+const SPDX = (id: string) => `https://spdx.org/licenses/${id}.html`;
+
+/**
+ * Licences by name, with the class each one puts a model in and where to read it. Order matters: a text
+ * names a model's licence by the first entry of its class it mentions (a text with Apache-2.0 weights and
+ * the CogVideoX base is the CogVideoX License's).
+ */
+const KNOWN: { re: RegExp; name: string; class: LicenceClass; url?: string }[] = [
+ { re: /FLUX\.1 \[dev\] Non-Commercial License|FLUX\.1 \[dev\] base is NON-COMMERCIAL/, name: "FLUX.1 [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.1-dev" },
+ { re: /FLUX \[dev\] Non-Commercial License/, name: "FLUX [dev] Non-Commercial License", class: "non-commercial", url: "https://huggingface.co/black-forest-labs/FLUX.2-dev" },
+ { re: /inswapper/, name: "InsightFace inswapper (research only)", class: "research", url: "https://github.com/deepinsight/insightface" },
+ { re: /CC-BY-NC-SA-4\.0/, name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0") },
+ { re: /CC[- ]BY[- ]NC(?:[- ]4\.0)?\b/, name: "CC BY-NC 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-4.0") },
+ { re: /Tencent Hunyuan 3D 2\.1 Community License/, name: "Tencent Hunyuan 3D 2.1 Community License", class: "regions" },
+ { re: /Tencent Hunyuan Community License/, name: "Tencent Hunyuan Community License", class: "regions" },
+ { re: /CogVideoX License/, name: "CogVideoX License", class: "conditions" },
+ { re: /LTX-2(?:\.x)? Community License/, name: "LTX-2 Community License", class: "conditions" },
+ { re: /Stability AI Community License|Stability Community License/, name: "Stability AI Community License", class: "conditions", url: "https://stability.ai/community-license-agreement" },
+ { re: /Krea 2 Community License/, name: "Krea 2 Community License", class: "conditions" },
+ { re: /IndexTTS-2 Model Use License/, name: "bilibili IndexTTS-2 Model Use License", class: "conditions" },
+ { re: /Llama 3\.1 Community License/, name: "Llama 3.1 Community License", class: "conditions", url: "https://www.llama.com/llama3_1/license/" },
+ { re: /DINOv3 License/, name: "DINOv3 License", class: "conditions" },
+ { re: /SAM License/, name: "Meta SAM License", class: "conditions" },
+ { re: /OpenRAIL\+\+-M/, name: "CreativeML OpenRAIL++-M", class: "conditions" },
+ { re: /OpenRAIL-M/, name: "CreativeML OpenRAIL-M", class: "conditions", url: SPDX("CreativeML-OpenRAIL-M") },
+ { re: /Gemma Terms of Use/, name: "Gemma Terms of Use", class: "conditions", url: "https://ai.google.dev/gemma/terms" },
+ { re: /Apache[- ]2\.0/, name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0") },
+ { re: /\bMIT\b/, name: "MIT", class: "commercial", url: SPDX("MIT") },
+ { re: /BSD-3-Clause/, name: "BSD-3-Clause", class: "commercial", url: SPDX("BSD-3-Clause") },
+];
+
+/** ComfyUI's own licence: the tools with no model weights run on its nodes. */
+const COMFYUI_REPO = "https://github.com/comfyanonymous/ComfyUI";
+
+/** A Hugging Face download's repository page, where its licence is stated. */
+export function modelCardOf(url: string | undefined): string | undefined {
+ const m = url && /^https:\/\/huggingface\.co\/([^/]+\/[^/]+)\/(?:resolve|blob)\//.exec(url);
+ return m ? `https://huggingface.co/${m[1]}` : undefined;
+}
+
+/**
+ * What a recorded licence text means as information: its class, a short name, where to read it. `cards` are
+ * the model downloads it covers (the largest first): their Hugging Face page is the link when the licence
+ * has no page of its own.
+ */
+export function licenceInfo(text: string, cards: string[] = []): LicenceInfo {
+ const terms = licenceTerms(text);
+ const card = cards.map(modelCardOf).find(Boolean);
+ if (text === UNKNOWN_LICENCE) return { name: "Not recorded", class: "unknown", note: text, ...(card && { url: card }) };
+ if (terms.noWeights) return { name: "No model weights", class: "commercial", url: COMFYUI_REPO, note: `${text.replace(/^n\/a \((.*)\)$/, "$1")}: ComfyUI's own nodes (GPL-3.0) or FFmpeg` };
+ const cls: LicenceClass = terms.flags.includes("non-commercial")
+ ? /research (?:use )?only/i.test(text)
+ ? "research"
+ : "non-commercial"
+ : terms.flags.includes("territory")
+ ? "regions"
+ : terms.flags.includes("conditions")
+ ? "conditions"
+ : "commercial";
+ const found = KNOWN.filter((k) => k.re.test(text));
+ const named = found.find((k) => k.class === cls) ?? found[0];
+ const name = named?.name ?? text.split(/[(;:]/)[0].trim();
+ // The licence's own text when it has a page, else the model card that states it.
+ const url = named?.url ?? card;
+ return { name, class: cls, note: text, ...(url && { url }), ...(terms.excludes && { excludes: terms.excludes }), ...(terms.notices.length && { notices: terms.notices }) };
+}
+
+/** Several licences as one (a model running several workflows, a chain): the strictest class names it. */
+export function mergeLicences(infos: LicenceInfo[]): LicenceInfo {
+ if (infos.length <= 1) return infos[0] ?? { name: "Not recorded", class: "unknown", note: UNKNOWN_LICENCE };
+ const lead = infos.reduce((a, b) => (STRICTNESS[b.class] > STRICTNESS[a.class] ? b : a));
+ const notes = [...new Set(infos.map((i) => i.note))];
+ const notices = [...new Set(infos.flatMap((i) => i.notices ?? []))];
+ return { ...lead, note: notes.join(" · "), ...(notices.length && { notices }) };
+}
+
+/** Where a provider shows a hosted model (its page states the model's licence and the provider's terms). */
+export function providerPage(provider: string, endpoint: string): string | undefined {
+ if (provider === "fal") return `https://fal.ai/models/${endpoint}`;
+ if (provider === "replicate") return `https://replicate.com/${endpoint.split(":")[0]}`;
+ if (provider === "llm") return "https://www.anthropic.com/legal/commercial-terms";
+ return undefined;
+}
+
+export const PROVIDER_NAME: Record<string, string> = {
+ fal: "fal.ai",
+ replicate: "Replicate",
+ higgsfield: "Higgsfield",
+ comfyui: "ComfyUI (your GPU)",
+ llm: "Claude or Ollama",
+ local: "Your browser",
+ openai: "OpenAI",
+ google: "Google",
+};
+
+/** A model on a paid API: the provider's and the vendor's terms (a closed model, or open weights the provider hosts). */
+export function paidApiLicence(vendor: string, routes: { provider: string; endpoint: string }[]): LicenceInfo {
+ const providers = [...new Set(routes.map((r) => r.provider))];
+ const names = providers.map((p) => PROVIDER_NAME[p] ?? p);
+ const first = routes[0];
+ const url = first && providerPage(first.provider, first.endpoint);
+ return {
+ name: `Paid API · ${names.join(", ")}`,
+ class: "paid-api",
+ note: `${vendor}'s model through ${names.join(" or ")} on your key: you pay per run, under the provider's terms and the model's own (the provider's page states both)`,
+ ...(url && { url }),
+ };
+}
+
+/** Text steps: Claude through the Anthropic key, else the Ollama model; on the open engine, Ollama only. */
+export function llmLicence(endpoint: string, ollamaModel = "qwen3:8b"): LicenceInfo {
+ if (endpoint !== "ollama") {
+ return {
+ name: "Paid API · Anthropic (or Ollama)",
+ class: "paid-api",
+ url: "https://www.anthropic.com/legal/commercial-terms",
+ note: "Claude through your Anthropic key, under Anthropic's commercial terms; with no key, the Ollama model on your machine",
+ };
+ }
+ const known: [RegExp, string, LicenceClass, string?][] = [
+ [/^qwen/i, "Apache-2.0", "commercial", SPDX("Apache-2.0")],
+ [/^(mistral|mixtral)/i, "Apache-2.0", "commercial", SPDX("Apache-2.0")],
+ [/^(phi|deepseek)/i, "MIT", "commercial", SPDX("MIT")],
+ [/^gemma/i, "Gemma Terms of Use", "conditions", "https://ai.google.dev/gemma/terms"],
+ [/^llama/i, "Llama Community License", "conditions", "https://www.llama.com/"],
+ ];
+ const hit = known.find(([re]) => re.test(ollamaModel));
+ const note = `The Ollama model this install uses (${ollamaModel}); another model carries its own licence: ollama show <model> --license`;
+ return hit ? { name: hit[1], class: hit[2], note, ...(hit[3] && { url: hit[3] }) } : { name: "Not recorded", class: "unknown", note };
+}
+
+/** Tools that run in the browser (colour grade, ad compositing): Fuobe's own code. */
+export const BROWSER_LICENCE: LicenceInfo = { name: "Fuobe (open source)", class: "commercial", note: "Runs in your browser with Fuobe's own code: no model weights, nothing sent anywhere" };
+
+// ---------------------------------------------------------------------------
+// ComfyUI node packs: the code a workflow loads beside ComfyUI (scripts/comfy/install-comfyui.sh and
+// install-isolated-worker.sh), from the research (docs/research/comfyui-oss*.json) and the manifest's licence
+// notes. A pack whose repository has no LICENSE file is recorded as unknown.
+
+export interface NodePack {
+ name: string;
+ repo: string;
+ licence: LicenceInfo;
+ /** Installed on the isolated worker (install-isolated-worker.sh), not the main ComfyUI. */
+ worker?: "isolated";
+}
+
+const pack = (name: string, repo: string, licence: Omit<LicenceInfo, "url"> & { url?: string }, worker?: "isolated"): NodePack => ({
+ name,
+ repo,
+ licence: { url: repo, ...licence },
+ ...(worker && { worker }),
+});
+const GPL: Omit<LicenceInfo, "note"> = { name: "GPL-3.0", class: "commercial", url: SPDX("GPL-3.0-only") };
+const NO_FILE = (extra = "") => ({ name: "Not recorded", class: "unknown" as const, note: `The repository has no LICENSE file${extra}` });
+
+export const NODE_PACKS: NodePack[] = [
+ pack("ComfyUI-WanVideoWrapper", "https://github.com/kijai/ComfyUI-WanVideoWrapper", { name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0"), note: "Code Apache-2.0; the Wan weights it loads are Apache-2.0" }),
+ pack("ComfyUI-VideoHelperSuite", "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite", { ...GPL, note: "Video loading and saving; GPL-3.0 code, like ComfyUI" }),
+ pack("ComfyUI-KJNodes", "https://github.com/kijai/ComfyUI-KJNodes", { ...GPL, note: "Utility nodes (GrowMaskWithBlur, resizing); GPL-3.0 code, like ComfyUI" }),
+ pack("ComfyUI-SeedVR2_VideoUpscaler", "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler", { name: "Apache-2.0", class: "commercial", url: SPDX("Apache-2.0"), note: "SeedVR2 upscaling; code and weights Apache-2.0" }),
+ pack("ComfyUI-Frame-Interpolation", "https://github.com/Fannovel16/ComfyUI-Frame-Interpolation", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "RIFE and FILM frame interpolation; MIT code" }),
+ pack("ComfyUI-RMBG", "https://github.com/1038lab/ComfyUI-RMBG", { ...GPL, note: "Background removal; GPL-3.0 code. Fuobe uses BEN2 (MIT); RMBG-2.0 in the same pack is CC BY-NC 4.0" }),
+ pack("ComfyUI-ReActor", "https://github.com/Gourieff/ComfyUI-ReActor", { name: "MIT (per the research)", class: "commercial", note: "Face swap node; the inswapper_128 weights it loads are for non-commercial research only" }),
+ pack("ComfyUI-MMAudio", "https://github.com/kijai/ComfyUI-MMAudio", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the MMAudio weights it loads are CC BY-NC 4.0 (non-commercial)" }),
+ pack("ComfyUI_Fill-ChatterBox", "https://github.com/filliptm/ComfyUI_Fill-ChatterBox", NO_FILE("; the Chatterbox weights are MIT")),
+ pack("ComfyUI-IndexTTS2", "https://github.com/snicolast/ComfyUI-IndexTTS2", NO_FILE("; the IndexTTS-2 weights have their own Model Use License")),
+ pack("ComfyUI-Video-Depth-Anything", "https://github.com/yuvraj108c/ComfyUI-Video-Depth-Anything", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; Fuobe loads the Apache-2.0 Small model (Base and Large are CC BY-NC 4.0)" }),
+ pack("ComfyUI-MelBandRoFormer", "https://github.com/kijai/ComfyUI-MelBandRoFormer", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the MelBand RoFormer weights are MIT" }),
+ pack("ComfyUI-QwenASR", "https://github.com/1038lab/ComfyUI-QwenASR", { ...GPL, note: "Qwen3-ASR transcription; GPL-3.0 code, Apache-2.0 weights" }),
+ pack("ComfyUI-HunyuanVideo-Foley", "https://github.com/phazei/ComfyUI-HunyuanVideo-Foley", { name: "Not recorded", class: "unknown", note: "Code licence not recorded; the HunyuanVideo-Foley weights leave out the EU, UK and South Korea" }),
+ pack("ComfyUI-ToSVG", "https://github.com/Yanick112/ComfyUI-ToSVG", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "VTracer vectorising; MIT. The pack also imports PyMuPDF (AGPL-3.0) for a node Fuobe doesn't use" }),
+ pack("ComfyUI-Whisper", "https://github.com/yuvraj108c/ComfyUI-Whisper", { name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0"), note: "Word-timed captions in one job; non-commercial code (the author asks to be contacted for commercial use). The Whisper weights are MIT" }),
+ pack("ComfyUI-LatentSyncWrapper", "https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper", NO_FILE("; the LatentSync 1.6 weights are CreativeML OpenRAIL++-M"), "isolated"),
+ pack("ComfyUI-ThinkSound_Wrapper", "https://github.com/ShmuelRonen/ComfyUI-ThinkSound_Wrapper", NO_FILE("; the ThinkSound weights are Apache-2.0"), "isolated"),
+];
+
+export const nodePack = (name: string): NodePack | undefined => NODE_PACKS.find((p) => p.name === name);
+
+/** The parts of a LoRA's licence snapshot the class needs (src/lib/catalog/types.ts LoraLicence). */
+interface LoraLicenceLike {
+ commercial: boolean;
+ hostedOk: boolean;
+ snapshotDate?: string;
+ name?: string;
+}
+
+/**
+ * A LoRA's licence as information: commercial and hostable, commercial on your GPU only (civitai lists no
+ * "Rent": a condition), non-commercial, or not recorded. `page` is its model card.
+ */
+export function loraLicenceInfo(l: LoraLicenceLike | undefined, page?: string, extra?: string): LicenceInfo {
+ if (!l) return { name: "Your own", class: "commercial", note: "A LoRA you trained or added yourself", ...(page && { url: page }) };
+ const recorded = l.name?.trim();
+ const unknown = !recorded || /unspecified|no licen[cs]e|check (?:the )?card/i.test(recorded);
+ const cls: LicenceClass = unknown && !l.commercial ? "unknown" : !l.commercial ? "non-commercial" : !l.hostedOk ? "conditions" : "commercial";
+ const what = !l.commercial ? "Outputs may not be sold" : l.hostedOk ? "Commercial use, on your GPU and in the cloud" : "Commercial use on your GPU; the licence doesn't allow running it on another hosted service";
+ const note = [what, recorded && `licence as read: ${recorded}`, l.snapshotDate && `read ${l.snapshotDate}`, extra].filter(Boolean).join(" · ");
+ return { name: unknown ? "Not recorded" : (KNOWN.find((k) => k.re.test(recorded!))?.name ?? recorded!), class: cls, note, ...(page && { url: page }) };
+}
diff --git a/src/lib/model-access.ts b/src/lib/model-access.ts
new file mode 100644
index 00000000..3e559084
--- /dev/null
+++ b/src/lib/model-access.ts
@@ -0,0 +1,208 @@
+/**
+ * Settings → Models & licences: which models, licence classes, providers, node packs and LoRAs this install
+ * offers. Licences are information (src/lib/licences.ts); these switches are the admin's decision, and
+ * everything is on until someone turns it off. Pure logic, no I/O and no catalog import: the server reads
+ * the switches (src/server/model-access.ts) and the browser filters its pickers with the summary
+ * /api/status sends.
+ *
+ * A route is off when its model, its provider, one of its node packs or its licence class is switched off.
+ * A model is off when none of its routes is on; a Fuobe Original with one engine's routes off runs on the
+ * other one only.
+ */
+import { CLASS_LABEL, LICENCE_CLASSES, PROVIDER_NAME, type LicenceClass } from "./licences";
+import { enginesOf, providerEngine } from "./catalog/engines";
+import type { Engine, ModelDef, ModelRoute } from "./catalog/types";
+
+/** What is switched off; anything not listed is on. */
+export interface ModelAccess {
+ /** Model ids. */
+ models: string[];
+ classes: LicenceClass[];
+ /** Provider ids (fal, replicate, higgsfield, comfyui, llm, local). */
+ providers: string[];
+ /** ComfyUI node packs by name (src/lib/licences.ts NODE_PACKS). */
+ packs: string[];
+ /** LoRA files. */
+ loras: string[];
+ /**
+ * LoRAs whose licence allows your GPU only (civitai without "Rent") stay off fal and Replicate. Off by
+ * default: they are sent like any other LoRA, and the run's notes say what the licence says.
+ */
+ keepGpuOnlyLoras: boolean;
+}
+
+export const ALL_ON: ModelAccess = { models: [], classes: [], providers: [], packs: [], loras: [], keepGpuOnlyLoras: false };
+
+/** Where the switches live, as every message names it. */
+export const ACCESS_PLACE = "Settings → Models & licences";
+export const ACCESS_HREF = "/settings/models";
+
+const strings = (v: unknown): string[] => (Array.isArray(v) ? [...new Set(v.filter((x): x is string => typeof x === "string" && x.trim() !== "").map((x) => x.trim()))] : []);
+
+/** The stored switches, tolerant of a missing or hand-edited value (anything unreadable is on). */
+export function parseAccess(raw: string | null | undefined): ModelAccess {
+ if (!raw) return ALL_ON;
+ let v: Partial<Record<keyof ModelAccess, unknown>>;
+ try {
+ v = JSON.parse(raw) as typeof v;
+ } catch {
+ return ALL_ON;
+ }
+ if (!v || typeof v !== "object") return ALL_ON;
+ return {
+ models: strings(v.models),
+ classes: strings(v.classes).filter((c): c is LicenceClass => (LICENCE_CLASSES as string[]).includes(c)),
+ providers: strings(v.providers),
+ packs: strings(v.packs),
+ loras: strings(v.loras),
+ keepGpuOnlyLoras: v.keepGpuOnlyLoras === true,
+ };
+}
+
+export const allOn = (a: ModelAccess): boolean =>
+ !a.models.length && !a.classes.length && !a.providers.length && !a.packs.length && !a.loras.length && !a.keepGpuOnlyLoras;
+
+/** One switch flipped (the settings API's change). */
+export type AccessChange =
+ | { kind: "model" | "class" | "provider" | "pack" | "lora"; id: string; on: boolean }
+ | { kind: "keepGpuOnlyLoras"; on: boolean }
+ | { kind: "reset" };
+
+const LIST: Record<"model" | "class" | "provider" | "pack" | "lora", "models" | "classes" | "providers" | "packs" | "loras"> = {
+ model: "models",
+ class: "classes",
+ provider: "providers",
+ pack: "packs",
+ lora: "loras",
+};
+
+export function applyChange(a: ModelAccess, c: AccessChange): ModelAccess {
+ if (c.kind === "reset") return ALL_ON;
+ if (c.kind === "keepGpuOnlyLoras") return { ...a, keepGpuOnlyLoras: c.on };
+ if (c.kind === "class" && !(LICENCE_CLASSES as string[]).includes(c.id)) throw new Error(`Unknown licence class ${c.id}`);
+ const key = LIST[c.kind];
+ const list = (a[key] as string[]).filter((x) => x !== c.id);
+ return { ...a, [key]: c.on ? list : [...list, c.id] };
+}
+
+/** What a route needs for the class and pack switches: its licence class and the node packs its workflow loads. */
+export interface RouteFacts {
+ class: LicenceClass;
+ packs: string[];
+}
+
+export type FactsOf = (route: ModelRoute, model: ModelDef) => RouteFacts;
+
+export type AccessSwitch =
+ | { kind: "model"; id: string }
+ | { kind: "provider"; id: string }
+ | { kind: "pack"; id: string }
+ | { kind: "class"; id: LicenceClass }
+ | { kind: "lora"; id: string };
+
+/** The switch that turns this route off (the most specific one), or undefined when it is on. */
+export function routeOff(model: ModelDef, route: ModelRoute, access: ModelAccess, facts: FactsOf): AccessSwitch | undefined {
+ if (access.models.includes(model.id)) return { kind: "model", id: model.id };
+ if (access.providers.includes(route.provider)) return { kind: "provider", id: route.provider };
+ if (!access.packs.length && !access.classes.length) return undefined;
+ const f = facts(route, model);
+ const pack = f.packs.find((p) => access.packs.includes(p));
+ if (pack) return { kind: "pack", id: pack };
+ if (access.classes.includes(f.class)) return { kind: "class", id: f.class };
+ return undefined;
+}
+
+/** A switch in words, as the messages and the settings page say it. */
+export function switchLabel(s: AccessSwitch): string {
+ switch (s.kind) {
+ case "model":
+ return "the model is switched off";
+ case "provider":
+ return `${PROVIDER_NAME[s.id] ?? s.id} is switched off`;
+ case "pack":
+ return `the ${s.id} node pack is switched off`;
+ case "class":
+ return `${CLASS_LABEL[s.id]} is switched off`;
+ case "lora":
+ return "the LoRA is switched off";
+ }
+}
+
+const sameSwitch = (a: AccessSwitch, b: AccessSwitch) => a.kind === b.kind && a.id === b.id;
+
+/** The switches behind a model being off (one per reason, in route order). */
+export function offSwitches(model: ModelDef, access: ModelAccess, facts: FactsOf, routes = model.routes): AccessSwitch[] {
+ const out: AccessSwitch[] = [];
+ for (const r of routes) {
+ const s = routeOff(model, r, access, facts);
+ if (s && !out.some((x) => sameSwitch(x, s))) out.push(s);
+ }
+ return out;
+}
+
+const and = (xs: string[]) => (xs.length < 2 ? xs.join("") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)}`);
+
+/** The refusal a studio, the API, Assist and the CLI give for a model that is off, naming the switch. */
+export function offMessage(name: string, switches: AccessSwitch[]): string {
+ const why = switches.length ? ` (${and(switches.map(switchLabel))})` : "";
+ return `${name} is turned off in ${ACCESS_PLACE}${why}. Turn it back on there, or pick another model`;
+}
+
+const views = new WeakMap<ModelAccess, WeakMap<ModelDef, ModelDef | null>>();
+
+/**
+ * The model as this install offers it: only the routes that are on (an Original keeps the engines that still
+ * have one), the same object every time for the same switches; undefined when no route is on.
+ */
+export function gateModel(model: ModelDef, access: ModelAccess, facts: FactsOf): ModelDef | undefined {
+ if (allOn(access)) return model;
+ let cached = views.get(access);
+ if (!cached) views.set(access, (cached = new WeakMap()));
+ const hit = cached.get(model);
+ if (hit !== undefined) return hit ?? undefined;
+ const routes = model.routes.filter((r) => !routeOff(model, r, access, facts));
+ let view: ModelDef | null = null;
+ if (routes.length === model.routes.length) view = model;
+ else if (routes.length) {
+ const engines = enginesOf(model).filter((e) => routes.some((r) => providerEngine(r.provider) === e));
+ const engine = engines.includes(model.engine) ? model.engine : engines[0];
+ view = { ...model, routes, engine, ...(model.engines && { engines }) };
+ }
+ cached.set(model, view);
+ return view ?? undefined;
+}
+
+/**
+ * What the browser needs to filter its pickers (sent with /api/status only when something is off): the
+ * models with no route on, and the Originals with one engine off (the engines still on).
+ */
+export interface AccessSummary {
+ off: string[];
+ engines?: Record<string, Engine[]>;
+}
+
+export function accessSummary(models: ModelDef[], access: ModelAccess, facts: FactsOf): AccessSummary | undefined {
+ if (allOn(access)) return undefined;
+ const off: string[] = [];
+ const engines: Record<string, Engine[]> = {};
+ for (const m of models) {
+ const view = gateModel(m, access, facts);
+ if (!view) off.push(m.id);
+ else if (view !== m && enginesOf(view).length < enginesOf(m).length) engines[m.id] = enginesOf(view);
+ }
+ return { off, ...(Object.keys(engines).length && { engines }) };
+}
+
+/** Whether the model (on this engine, when given) is offered: everything is, without a summary. */
+export function offered(summary: AccessSummary | undefined, id: string | undefined, engine?: Engine): boolean {
+ if (!id) return false;
+ if (!summary) return true;
+ if (summary.off.includes(id)) return false;
+ const on = summary.engines?.[id];
+ return !engine || !on || on.includes(engine);
+}
+
+/** The first of these that is offered: a default that is off falls back to the next one in line. */
+export function firstOffered(summary: AccessSummary | undefined, ids: (string | undefined)[], engine?: Engine): string | undefined {
+ return ids.find((id) => offered(summary, id, engine));
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 593fcef3..0959cca7 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -10,7 +10,7 @@ import { cueText, type Cue } from "@/lib/cues";
import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";
import { upscaleTier } from "@/lib/av/upscale";
import { chainedWaitMessage, keyframeChain } from "@/lib/catalog/keyframes";
-import { estimateCost, inferOperation, planGeneration, presetRoute, routeLoras, routesFor } from "@/lib/catalog/plan";
+import { estimateCost, inferOperation, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
import { framedLength, keepMatte } from "@/lib/catalog/payload";
import { fitLoras, lorasFit } from "@/lib/catalog/loras";
import { dualEngine, onEngine, pickEngine } from "@/lib/catalog/engines";
@@ -44,6 +44,7 @@ import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider } from "./providers";
import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
import { ensureLorasOnComfy, prepareCloudLoras, withoutUnreachableCivitai } from "./loras";
+import { offeredLoras, offeredModel, offeredRoutes, requireOffered } from "./model-access";
import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
import { mediaFacts } from "./media-facts";
@@ -456,8 +457,11 @@ function prepare(original: GenerationRequest) {
// A style signature's sentences (palette, look) join the prompt here; the stored request keeps the user's words.
const worded = withSignatureWords(original);
const mode = engineMode();
+ // Settings → Models & licences: a model (or the engine of an Original asked for) that is switched off is refused,
+ // naming the switch; an Original otherwise runs on an engine that is still on, with the routes that are on.
const found = getModel(worded.modelId);
- const model = found && dualEngine(found) ? onEngine(found, engineFor(found, worded.engine)) : found;
+ const allowed = found && requireOffered(found, worded.engine);
+ const model = allowed && dualEngine(allowed) ? onEngine(allowed, engineFor(allowed, worded.engine)) : allowed;
const lookup = (id: string) => (model && id === model.id ? model : getModel(id));
const req = model ? stripMotionPaths(applySketch(applyMentions(worded, model, listElements()).request, model).request, model) : worded;
let plan = planGeneration(req, lookup, getPreset);
@@ -473,7 +477,13 @@ function prepare(original: GenerationRequest) {
if (plan.op === "translate" && !plan.params.targetLanguage) throw new Error("Pick a language to translate into");
// The length asked of a clip that is made (not one that follows its input video's length).
const seconds = MADE_LENGTH_OPS.has(plan.op) ? plan.params.duration : undefined;
- const { route, demo } = chooseRoute(routesFor(plan.model, plan.op), req.inputs?.images?.length ?? 0, plan.loras, seconds);
+ // LoRAs switched off (by file or licence class) are left out, their trigger words with them; with "keep GPU-only
+ // LoRAs on your GPU" on, the rest are marked so a cloud route leaves those out (fitLoras).
+ const access = offeredLoras(plan.loras);
+ if (access.dropped.length) plan = { ...plan, loras: access.loras, prompt: withoutTriggers(plan.prompt, plan.loras.filter((l) => !access.loras.some((k) => k.file === l.file)), access.loras) };
+ else if (access.loras.some((l, i) => l !== plan.loras[i])) plan = { ...plan, loras: access.loras };
+ // A preset can route to another model than the one asked for: its routes that are on (or the switch that's off).
+ const { route, demo } = chooseRoute(offeredRoutes(plan.model, routesFor(plan.model, plan.op)), req.inputs?.images?.length ?? 0, plan.loras, seconds);
// What the cloud run can carry: a LoRA whose licence doesn't allow hosting stays on the GPU, and an API
// takes at most so many (the plan's notes say which were left out). Open runs carry them all. Without a
// civitai key a Soul look's civitai LoRA the run can't get is left out (and said), rather than failing at the
@@ -485,7 +495,7 @@ function prepare(original: GenerationRequest) {
// A Soul look's triggers lead the prompt: a LoRA left out takes its trigger with it.
const prompt = plan.soul ? promptWithLoras(plan.prompt, plan.soul.triggers, fitted.loras) : plan.prompt;
plan = { ...plan, prompt, loras: fitted.loras };
- const notes = [...(plan.notes ?? []), ...reachable.notes, ...fitted.notes];
+ const notes = [...(plan.notes ?? []), ...access.notes, ...reachable.notes, ...fitted.notes];
// A frame-count API that can't make the length asked (Replicate's Wan 2.2 fast: 81–121 frames) says what it makes.
const made = demo ? undefined : framedLength(route.map?.numFrames, seconds, plan.params.fps);
if (made !== undefined && route.map?.numFrames) {
@@ -507,7 +517,7 @@ function prepare(original: GenerationRequest) {
const unreachable = asked.filter((l) => !reachable.loras.includes(l));
// Priced for the clip the route makes: Replicate's Wan 2.2 fast makes 5 s when 3 s was asked.
const priced = made !== undefined && plan.params.duration !== undefined ? { ...plan.params, duration: Math.round(made * 2) / 2 } : plan.params;
- return { req, plan, route, demo, providerId, notes, asked, unreachable, cost: free ? 0 : estimateCost(plan.model, priced, 1, plan.op, withLoras) };
+ return { req, plan, route, demo, providerId, notes, asked, unreachable, switchedOff: access.dropped, cost: free ? 0 : estimateCost(plan.model, priced, 1, plan.op, withLoras) };
}
/** Operations whose clip length is the duration picked (made, or added by extend), not an input video's. */
@@ -516,9 +526,12 @@ const MADE_LENGTH_OPS = new Set<Operation>(["t2v", "i2v", "flf2v", "ref2v", "ext
/** What a request would run as — model, operation, job count and cost — without starting it. */
export function previewGeneration(req: GenerationRequest) {
- const { plan, route, demo, providerId, cost, notes, asked, unreachable } = prepare(req);
+ const { plan, route, demo, providerId, cost, notes, asked, unreachable, switchedOff } = prepare(req);
const fitted = routeLoras(route, asked.filter((l) => !unreachable.includes(l)));
- const loras = { ...fitted, dropped: [...unreachable.map((l) => ({ file: l.file, reason: "it downloads from civitai, which needs your civitai key (Settings → LoRAs)" })), ...fitted.dropped] };
+ const loras = {
+ ...fitted,
+ dropped: [...switchedOff, ...unreachable.map((l) => ({ file: l.file, reason: "it downloads from civitai, which needs your civitai key (Settings → LoRAs)" })), ...fitted.dropped],
+ };
return {
model: plan.model,
op: plan.op,
@@ -563,7 +576,9 @@ const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (J
export function createGenerations(original: GenerationRequest, opts: CreateOptions = {}): Generation[] {
// Open models make multi-shot films shot by shot, then join the clips. A Fuobe Original is taken on the engine it runs
// on (Fuobe DoP's Frames mode is a GPU chain).
- const found = getModel(original.modelId);
+ // An Original runs on an engine still on in Settings → Models & licences (prepare refuses a model that is off).
+ const catalogModel = getModel(original.modelId);
+ const found = catalogModel && (offeredModel(catalogModel) ?? catalogModel);
const shotModel = found && dualEngine(found) ? onEngine(found, engineFor(found, original.engine)) : found;
if (!opts.dependsOn && shotModel?.options.multiShot?.mode === "concat" && (original.params?.shots?.filter((x) => x.prompt.trim()).length ?? 0) > 1) {
return createShotFilm(original, shotModel);
diff --git a/src/server/model-access.ts b/src/server/model-access.ts
new file mode 100644
index 00000000..ac6727ae
--- /dev/null
+++ b/src/server/model-access.ts
@@ -0,0 +1,196 @@
+import "server-only";
+import { MODELS } from "@/lib/catalog";
+import { onEngine } from "@/lib/catalog/engines";
+import { libraryEntry, loraName } from "@/lib/catalog/loras";
+import type { Engine, LoraRef, ModelDef, ModelRoute } from "@/lib/catalog/types";
+import type { ManifestWorkflow } from "@/lib/comfy";
+import {
+ BROWSER_LICENCE,
+ llmLicence,
+ licenceInfo,
+ loraLicenceInfo,
+ mergeLicences,
+ paidApiLicence,
+ workflowLicence,
+ type LicenceInfo,
+} from "@/lib/licences";
+import {
+ accessSummary as summarize,
+ ACCESS_PLACE,
+ applyChange,
+ gateModel,
+ offMessage,
+ offSwitches,
+ parseAccess,
+ routeOff,
+ type AccessChange,
+ type AccessSummary,
+ type FactsOf,
+ type ModelAccess,
+} from "@/lib/model-access";
+import { db } from "./db";
+import { loadManifest } from "./providers/comfyui";
+import { getSetting } from "./settings";
+
+/**
+ * Settings → Models & licences on the server: the switches (one settings row, JSON), each route's licence and
+ * node packs (the ComfyUI manifest for open routes, the provider's terms for paid ones), and the checks every
+ * run, listing and automatic pick goes through. Licences are information; only the admin's switches turn
+ * anything off, and everything is on by default.
+ */
+
+const KEY = "models.access";
+
+let cached: { raw: string | null; access: ModelAccess } | null = null;
+
+/** The switches in effect (the same object while they don't change, so gated model views stay cached). */
+export function readAccess(): ModelAccess {
+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(KEY) as { value: string } | undefined;
+ const raw = row?.value ?? null;
+ if (!cached || cached.raw !== raw) cached = { raw, access: parseAccess(raw) };
+ return cached.access;
+}
+
+export function saveAccess(next: ModelAccess): ModelAccess {
+ const raw = JSON.stringify(next);
+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(KEY, raw);
+ return readAccess();
+}
+
+/** Flip switches in one write (read, change, write inside one transaction). */
+export function changeAccess(changes: AccessChange[]): ModelAccess {
+ return db().transaction(() => saveAccess(changes.reduce(applyChange, readAccess())))();
+}
+
+// ---------------------------------------------------------------------------
+// Licences and node packs per route
+
+/** Workflow ids a ComfyUI endpoint names: one id, or a family (`video-concat-{n}`). */
+function workflowsOf(endpoint: string, all: ManifestWorkflow[]): ManifestWorkflow[] {
+ if (!endpoint.includes("{")) return all.filter((w) => w.id === endpoint);
+ const re = new RegExp(`^${endpoint.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{[^}]+\}/g, "\\d+")}$`);
+ return all.filter((w) => re.test(w.id));
+}
+
+let factsCache: { manifest: object; byEndpoint: Map<string, { licence: LicenceInfo; packs: string[]; workflows: string[] }> } | null = null;
+
+/** An open route's licence (its workflows' weights, the strictest one naming it), node packs and workflow ids. */
+function comfyFacts(endpoint: string): { licence: LicenceInfo; packs: string[]; workflows: string[] } {
+ const manifest = loadManifest();
+ if (factsCache?.manifest !== manifest) factsCache = { manifest, byEndpoint: new Map() };
+ const hit = factsCache.byEndpoint.get(endpoint);
+ if (hit) return hit;
+ const wfs = workflowsOf(endpoint, manifest.workflows);
+ const largestFirst = (w: ManifestWorkflow) => [...w.models].sort((a, b) => (b.sizeGb ?? 0) - (a.sizeGb ?? 0)).flatMap((m) => (m.url ? [m.url] : []));
+ const facts = {
+ licence: wfs.length ? mergeLicences(wfs.map((w) => licenceInfo(workflowLicence(w), largestFirst(w)))) : licenceInfo(workflowLicence({ id: endpoint })),
+ packs: [...new Set(wfs.flatMap((w) => w.customNodes.map((n) => n.name)))],
+ workflows: wfs.map((w) => w.id),
+ };
+ factsCache.byEndpoint.set(endpoint, facts);
+ return facts;
+}
+
+/** A route's licence: the weights' for ComfyUI, the provider's terms for a paid API, Fuobe's own code in the browser. */
+export function routeLicence(route: ModelRoute, model: Pick<ModelDef, "vendor">): LicenceInfo {
+ if (route.provider === "comfyui") return comfyFacts(route.endpoint).licence;
+ if (route.provider === "local") return BROWSER_LICENCE;
+ if (route.provider === "llm") return llmLicence(route.endpoint, getSetting("ollamaModel"));
+ return paidApiLicence(model.vendor, [route]);
+}
+
+export const factsOf: FactsOf = (route, model) => ({
+ class: routeLicence(route, model).class,
+ packs: route.provider === "comfyui" ? comfyFacts(route.endpoint).packs : [],
+});
+
+// ---------------------------------------------------------------------------
+// The checks
+
+/** The model as this install offers it (only its routes that are on), or undefined when it is off. */
+export function offeredModel(m: ModelDef): ModelDef | undefined {
+ return gateModel(m, readAccess(), factsOf);
+}
+
+/** Listings (the API, Assist, MCP, the CLI): only what is on, each model with the routes that are on. */
+export function offeredModels(list: ModelDef[]): ModelDef[] {
+ return list.flatMap((m) => offeredModel(m) ?? []);
+}
+
+/** Why a model is off, as the refusal names it ("…turned off in Settings → Models & licences (fal.ai is switched off)"). */
+export function offReason(m: ModelDef, routes?: ModelRoute[]): string {
+ return offMessage(m.name, offSwitches(m, readAccess(), factsOf, routes));
+}
+
+/**
+ * The model a run may use, refusing one that is off with a message naming the switch. `engine` (an Original's
+ * engine asked for) refuses that engine when only its routes are off.
+ */
+export function requireOffered(m: ModelDef, engine?: Engine): ModelDef {
+ const view = offeredModel(m);
+ if (!view) throw new Error(offReason(m));
+ if (engine && m.engines?.includes(engine) && !view.engines?.includes(engine) && view.engine !== engine) {
+ throw new Error(offReason(m, onEngine(m, engine).routes).replace(m.name, `${m.name} ${engine === "open" ? "on your GPU" : "in the cloud"}`));
+ }
+ return view;
+}
+
+/** The routes of these that are on (a run's candidates); throws naming the switches when none is. */
+export function offeredRoutes(m: ModelDef, routes: ModelRoute[]): ModelRoute[] {
+ const access = readAccess();
+ const on = routes.filter((r) => !routeOff(m, r, access, factsOf));
+ if (routes.length && !on.length) throw new Error(offReason(m, routes));
+ return on;
+}
+
+/** Whether a model id is offered (an unknown id is not). */
+export function isOffered(id: string | undefined, engine?: Engine): boolean {
+ const m = id ? MODELS.find((x) => x.id === id) : undefined;
+ const view = m && offeredModel(m);
+ return !!view && (!engine || !m!.engines || (view.engines ?? [view.engine]).includes(engine));
+}
+
+/**
+ * An automatic pick: the first of these that is on. When none is, the error says what to turn on (the first
+ * one's switch), so a studio never silently runs something else.
+ */
+export function pickOffered(ids: (string | undefined)[], engine?: Engine): string {
+ const id = ids.find((x) => isOffered(x, engine));
+ if (id) return id;
+ const first = ids.map((x) => (x ? MODELS.find((m) => m.id === x) : undefined)).find(Boolean);
+ throw new Error(first ? offReason(first) : `No model for this is turned on in ${ACCESS_PLACE}`);
+}
+
+/** The summary the browser filters its pickers with (undefined while everything is on). */
+export function offeredSummary(): AccessSummary | undefined {
+ return summarize(MODELS, readAccess(), factsOf);
+}
+
+// ---------------------------------------------------------------------------
+// LoRAs
+
+/** A LoRA's licence: the ref's snapshot, else the library's; a LoRA with neither is the user's own. */
+export function loraLicence(l: Pick<LoraRef, "file" | "url" | "licence">): LicenceInfo {
+ const e = libraryEntry(l);
+ return loraLicenceInfo(l.licence ?? e?.licence, e?.page);
+}
+
+/**
+ * The LoRAs a run may load: one switched off, or whose licence class is, is left out (the plan's notes say
+ * which switch). With "keep GPU-only LoRAs on your GPU" on, each LoRA is marked so a cloud route leaves the ones
+ * licensed for the user's GPU only out (src/lib/catalog/loras.ts localOnly).
+ */
+export function offeredLoras(loras: LoraRef[]): { loras: LoraRef[]; notes: string[]; dropped: { file: string; reason: string }[] } {
+ const access = readAccess();
+ const dropped: { file: string; reason: string }[] = [];
+ const kept: LoraRef[] = [];
+ for (const l of loras) {
+ // The user's own LoRAs (a trained @character, no licence recorded) aren't anyone's licensed work: only their own switch counts.
+ const own = !l.licence && !libraryEntry(l);
+ const reason = access.loras.includes(l.file) ? "it is switched off" : !own && access.classes.includes(loraLicence(l).class) ? "its licence class is switched off" : undefined;
+ if (reason) dropped.push({ file: l.file, reason: `${reason} in ${ACCESS_PLACE}` });
+ else kept.push(access.keepGpuOnlyLoras ? { ...l, keepOnGpu: true } : l);
+ }
+ const notes = dropped.length ? [`${dropped.map((d) => loraName({ file: d.file })).join(", ")} ${dropped.length > 1 ? "are" : "is"} left out: turned off in ${ACCESS_PLACE}`] : [];
+ return { loras: kept, notes, dropped };
+}
diff --git a/tests/model-access.test.ts b/tests/model-access.test.ts
new file mode 100644
index 00000000..fe515f73
--- /dev/null
+++ b/tests/model-access.test.ts
@@ -0,0 +1,239 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeEach, describe, expect, it } from "vitest";
+import { getModel, MODELS } from "@/lib/catalog";
+import { LORA_LIBRARY } from "@/lib/catalog/lora-library.generated";
+import { loraRef, loraEntry } from "@/lib/catalog/loras";
+import type { ModelDef } from "@/lib/catalog/types";
+import type { Manifest } from "@/lib/comfy";
+import { licenceInfo, loraLicenceInfo, mergeLicences, NODE_PACKS, paidApiLicence, UNKNOWN_LICENCE, workflowLicence } from "@/lib/licences";
+import { accessSummary, ALL_ON, applyChange, firstOffered, gateModel, offered, offMessage, parseAccess, routeOff, type FactsOf } from "@/lib/model-access";
+
+// The switches live in the settings table: a throwaway database.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-model-access-"));
+process.env.FUOBE_DATA_DIR = dir;
+const { changeAccess, factsOf, isOffered, offeredLoras, offeredModels, offeredSummary, pickOffered, readAccess, routeLicence } = await import("@/server/model-access");
+const { previewGeneration } = await import("@/server/generations");
+const { setSetting } = await import("@/server/settings");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const MANIFEST = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/manifest.json"), "utf8")) as Manifest;
+const model = (id: string) => getModel(id)!;
+const reset = () => changeAccess([{ kind: "reset" }]);
+
+describe("licences as information", () => {
+ it("sorts a recorded licence into its class, with a name and a link", () => {
+ expect(licenceInfo("Apache-2.0 (Wan 2.2, umT5, lightx2v)")).toMatchObject({ class: "commercial", name: "Apache-2.0", url: "https://spdx.org/licenses/Apache-2.0.html" });
+ expect(licenceInfo(workflowLicence({ id: "flux1-dev-t2i" }))).toMatchObject({ class: "non-commercial", name: "FLUX.1 [dev] Non-Commercial License" });
+ expect(licenceInfo("Tencent Hunyuan Community License (territory EXCLUDES the EU, UK and South Korea)")).toMatchObject({ class: "regions", excludes: "the EU, UK and South Korea" });
+ expect(licenceInfo("LTX-2 Community License (LTX-2.3 22B: free under US$10M annual revenue)", ["https://huggingface.co/Lightricks/LTX-2.3-fp8/resolve/main/x.safetensors"])).toMatchObject({
+ class: "conditions",
+ name: "LTX-2 Community License",
+ url: "https://huggingface.co/Lightricks/LTX-2.3-fp8",
+ });
+ expect(licenceInfo(workflowLicence({ id: "face-swap-reactor" })).class).toBe("research");
+ expect(licenceInfo("n/a (no model; ComfyUI core)")).toMatchObject({ class: "commercial", name: "No model weights" });
+ expect(licenceInfo(UNKNOWN_LICENCE).class).toBe("unknown");
+ // A variant Fuobe doesn't use, named in lower case, isn't the model's licence.
+ expect(licenceInfo("Apache-2.0 (Video-Depth-Anything-Small); Base/Large and metric variants are CC-BY-NC-4.0 (non-commercial) - keep the vits model").class).toBe("commercial");
+ // The strictest part names a chain.
+ expect(mergeLicences([licenceInfo("MIT (BiRefNet)"), licenceInfo("CC-BY-NC-4.0 (MMAudio weights: NON-COMMERCIAL)")]).class).toBe("non-commercial");
+ expect(licenceInfo("MIT (TRELLIS.2); the dino_v3_L_naf image encoder is under the DINOv3 License (the app must show a \"Built with DINOv3\" notice)").notices).toEqual(["Built with DINOv3"]);
+ });
+
+ it("gives every model a licence: its weights' on ComfyUI, the provider's terms on a paid API", () => {
+ for (const m of MODELS) for (const r of m.routes) expect(routeLicence(r, m).name, `${m.id} ${r.endpoint}`).toBeTruthy();
+ expect(routeLicence(model("nano-banana-pro").routes[0], model("nano-banana-pro"))).toMatchObject({ class: "paid-api", url: "https://fal.ai/models/fal-ai/nano-banana-pro" });
+ expect(paidApiLicence("Google", [{ provider: "replicate", endpoint: "google/nano-banana-pro:abc" }]).url).toBe("https://replicate.com/google/nano-banana-pro");
+ expect(routeLicence(model("oss-flux1-dev").routes[0], model("oss-flux1-dev")).class).toBe("non-commercial");
+ // A family endpoint (video-concat-{n}) takes its workflows' licence.
+ const join = model("oss-join-clips");
+ expect(routeLicence(join.routes[0], join)).toMatchObject({ class: "commercial", name: "No model weights" });
+ // Every workflow's licence is recorded (none falls back to unknown).
+ for (const w of MANIFEST.workflows) expect(workflowLicence(w), w.id).not.toBe(UNKNOWN_LICENCE);
+ });
+
+ it("knows the licence of every node pack a workflow loads", () => {
+ const used = new Set(MANIFEST.workflows.flatMap((w) => w.customNodes.map((n) => n.name)));
+ for (const name of used) expect(NODE_PACKS.find((p) => p.name === name), name).toBeDefined();
+ expect(NODE_PACKS.find((p) => p.name === "ComfyUI-Whisper")!.licence.class).toBe("non-commercial");
+ // A pack whose repository states no licence is unknown, honestly.
+ expect(NODE_PACKS.find((p) => p.name === "ComfyUI_Fill-ChatterBox")!.licence.class).toBe("unknown");
+ expect(factsOf(model("oss-captions-whisper").routes[0], model("oss-captions-whisper")).packs).toContain("ComfyUI-Whisper");
+ });
+
+ it("reads every LoRA's licence: commercial, your GPU only, non-commercial, or not recorded", () => {
+ for (const e of LORA_LIBRARY) expect(loraLicenceInfo(e.licence, e.page).class, e.key).toMatch(/^(commercial|conditions|non-commercial|unknown)$/);
+ expect(loraLicenceInfo(loraEntry("civitai-2490836-wiggle-redmond")!.licence).class).toBe("conditions");
+ expect(loraLicenceInfo(loraEntry("btsmovieset-ltx25-v1")!.licence).class).toBe("non-commercial");
+ expect(loraLicenceInfo({ commercial: false, hostedOk: true, name: "unspecified (check card)" }).class).toBe("unknown");
+ expect(loraLicenceInfo(undefined)).toMatchObject({ name: "Your own", class: "commercial" });
+ });
+});
+
+describe("the switches (pure)", () => {
+ const facts: FactsOf = (r) => ({ class: r.provider === "comfyui" ? "non-commercial" : "paid-api", packs: r.endpoint === "w" ? ["ComfyUI-Whisper"] : [] });
+ const m: ModelDef = {
+ id: "m",
+ name: "Model M",
+ vendor: "V",
+ family: "f",
+ engine: "open",
+ engines: ["open", "cloud"],
+ kind: "image",
+ tagline: "",
+ options: {},
+ routes: [
+ { op: "t2i", provider: "comfyui", endpoint: "w" },
+ { op: "t2i", provider: "fal", endpoint: "fal-ai/m" },
+ { op: "t2i", provider: "replicate", endpoint: "v/m" },
+ ],
+ };
+
+ it("parses what is stored, and anything unreadable is on", () => {
+ expect(parseAccess(null)).toEqual(ALL_ON);
+ expect(parseAccess("not json")).toEqual(ALL_ON);
+ expect(parseAccess(JSON.stringify({ models: ["a", "a", 3], classes: ["research", "nope"], keepGpuOnlyLoras: true }))).toEqual({ ...ALL_ON, models: ["a"], classes: ["research"], keepGpuOnlyLoras: true });
+ });
+
+ it("flips one switch at a time, and resets", () => {
+ let a = applyChange(ALL_ON, { kind: "model", id: "m", on: false });
+ a = applyChange(a, { kind: "provider", id: "fal", on: false });
+ expect(a).toMatchObject({ models: ["m"], providers: ["fal"] });
+ a = applyChange(a, { kind: "model", id: "m", on: true });
+ expect(a.models).toEqual([]);
+ expect(() => applyChange(a, { kind: "class", id: "free", on: false })).toThrow(/Unknown licence class/);
+ expect(applyChange(a, { kind: "reset" })).toEqual(ALL_ON);
+ });
+
+ it("turns routes off by model, provider, node pack and licence class, naming the most specific switch", () => {
+ const a = { ...ALL_ON, packs: ["ComfyUI-Whisper"], providers: ["fal"] };
+ expect(routeOff(m, m.routes[0], a, facts)).toEqual({ kind: "pack", id: "ComfyUI-Whisper" });
+ expect(routeOff(m, m.routes[1], a, facts)).toEqual({ kind: "provider", id: "fal" });
+ expect(routeOff(m, m.routes[2], a, facts)).toBeUndefined();
+ expect(routeOff(m, m.routes[2], { ...a, models: ["m"] }, facts)).toEqual({ kind: "model", id: "m" });
+ expect(routeOff(m, m.routes[2], { ...ALL_ON, classes: ["paid-api"] }, facts)).toEqual({ kind: "class", id: "paid-api" });
+ });
+
+ it("offers a model with the routes that are on: an Original loses an engine, a model loses a provider", () => {
+ const a = { ...ALL_ON, classes: ["non-commercial" as const] };
+ const view = gateModel(m, a, facts)!;
+ expect(view.routes.map((r) => r.provider)).toEqual(["fal", "replicate"]);
+ expect(view).toMatchObject({ engine: "cloud", engines: ["cloud"] });
+ // The same object while the switches don't change.
+ expect(gateModel(m, a, facts)).toBe(view);
+ expect(gateModel(m, ALL_ON, facts)).toBe(m);
+ expect(gateModel(m, { ...a, classes: ["non-commercial", "paid-api"] }, facts)).toBeUndefined();
+ expect(accessSummary([m], a, facts)).toEqual({ off: [], engines: { m: ["cloud"] } });
+ expect(accessSummary([m], ALL_ON, facts)).toBeUndefined();
+ });
+
+ it("tells the browser what is offered, and falls back to the next model that is on", () => {
+ const summary = { off: ["a"], engines: { b: ["cloud" as const] } };
+ expect(offered(undefined, "a")).toBe(true);
+ expect(offered(summary, "a")).toBe(false);
+ expect(offered(summary, "b")).toBe(true);
+ expect(offered(summary, "b", "open")).toBe(false);
+ expect(firstOffered(summary, ["a", undefined, "b", "c"], "open")).toBe("c");
+ });
+
+ it("says where to turn a model back on", () => {
+ expect(offMessage("FLUX.1 [dev]", [{ kind: "class", id: "non-commercial" }])).toBe(
+ "FLUX.1 [dev] is turned off in Settings → Models & licences (Non-commercial is switched off). Turn it back on there, or pick another model",
+ );
+ expect(offMessage("X", [{ kind: "provider", id: "fal" }, { kind: "pack", id: "ComfyUI-KJNodes" }])).toMatch(/\(fal\.ai is switched off and the ComfyUI-KJNodes node pack is switched off\)/);
+ });
+});
+
+describe("the switches on the server", () => {
+ beforeEach(() => {
+ reset();
+ setSetting("demoMode", "on");
+ setSetting("engineMode", "both");
+ });
+
+ it("stores the switches as one settings row and reads them back", () => {
+ expect(readAccess()).toEqual(ALL_ON);
+ changeAccess([
+ { kind: "class", id: "research", on: false },
+ { kind: "pack", id: "ComfyUI-Whisper", on: false },
+ ]);
+ const a = readAccess();
+ expect(a).toMatchObject({ classes: ["research"], packs: ["ComfyUI-Whisper"] });
+ expect(readAccess()).toBe(a);
+ changeAccess([{ kind: "class", id: "research", on: true }]);
+ expect(readAccess()).toMatchObject({ classes: [], packs: ["ComfyUI-Whisper"] });
+ reset();
+ expect(readAccess()).toEqual(ALL_ON);
+ });
+
+ it("refuses a model that is off, naming the switch, in every run and preview", () => {
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: false }]);
+ expect(() => previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "a cat" })).toThrow(
+ "Nano Banana Pro is turned off in Settings → Models & licences (the model is switched off). Turn it back on there, or pick another model",
+ );
+ changeAccess([{ kind: "class", id: "non-commercial", on: false }]);
+ expect(() => previewGeneration({ feature: "image", modelId: "oss-flux1-dev", prompt: "a cat" })).toThrow(/\(Non-commercial is switched off\)/);
+ changeAccess([{ kind: "pack", id: "ComfyUI-Whisper", on: false }]);
+ expect(() => previewGeneration({ feature: "captions", modelId: "oss-captions-whisper", op: "captions", inputs: { video: "/api/files/a.mp4" } })).toThrow(/the ComfyUI-Whisper node pack is switched off/);
+ });
+
+ it("runs a model on a provider that is still on, and refuses when none is", () => {
+ setSetting("demoMode", "auto");
+ setSetting("falKey", "id:secret");
+ setSetting("replicateToken", "r8_test");
+ try {
+ expect(previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "a cat" }).route.provider).toBe("fal");
+ changeAccess([{ kind: "provider", id: "fal", on: false }]);
+ expect(previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "a cat" }).route.provider).toBe("replicate");
+ changeAccess([{ kind: "provider", id: "replicate", on: false }]);
+ expect(() => previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "a cat" })).toThrow(/fal\.ai is switched off and Replicate is switched off/);
+ } finally {
+ setSetting("falKey", "");
+ setSetting("replicateToken", "");
+ }
+ });
+
+ it("runs an Original on the engine still on, and refuses the engine that is off when asked for", () => {
+ changeAccess([{ kind: "class", id: "paid-api", on: false }]);
+ expect(previewGeneration({ feature: "image", modelId: "fuobe-soul", prompt: "a cat" }).engine).toBe("open");
+ expect(() => previewGeneration({ feature: "image", modelId: "fuobe-soul", prompt: "a cat", engine: "cloud" })).toThrow(/^Fuobe Soul in the cloud is turned off in Settings → Models & licences \(Proprietary paid API is switched off\)/);
+ expect(isOffered("fuobe-soul")).toBe(true);
+ expect(isOffered("fuobe-soul", "cloud")).toBe(false);
+ expect(offeredSummary()?.engines?.["fuobe-soul"]).toEqual(["open"]);
+ expect(offeredSummary()?.off).toContain("nano-banana-pro");
+ });
+
+ it("leaves listings without what is off, and keeps engine mode working", () => {
+ changeAccess([{ kind: "provider", id: "comfyui", on: false }]);
+ const listed = offeredModels(MODELS);
+ expect(listed.some((m) => m.id === "oss-flux1-dev")).toBe(false);
+ expect(listed.find((m) => m.id === "fuobe-soul")?.engines).toEqual(["cloud"]);
+ // Engine mode still decides first: open source only with ComfyUI switched off refuses an open model by its own message.
+ setSetting("engineMode", "open");
+ expect(() => previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "a cat" })).toThrow(/open source only/);
+ });
+
+ it("picks the next model that is on, or says what to turn on", () => {
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: false }]);
+ expect(pickOffered(["nano-banana-pro", "seedream-5-pro"])).toBe("seedream-5-pro");
+ expect(() => pickOffered(["nano-banana-pro"])).toThrow(/^Nano Banana Pro is turned off in Settings → Models & licences/);
+ });
+
+ it("leaves out LoRAs switched off by file or licence class, and marks GPU-only ones when the admin keeps them home", () => {
+ const bts = loraRef(loraEntry("btsmovieset-ltx25-v1")!);
+ const aw = loraRef(loraEntry("awportrait")!);
+ const own = { file: "my-character.safetensors" };
+ expect(offeredLoras([bts, aw, own])).toEqual({ loras: [bts, aw, own], notes: [], dropped: [] });
+ changeAccess([{ kind: "class", id: "non-commercial", on: false }, { kind: "lora", id: aw.file, on: false }, { kind: "class", id: "commercial", on: false }]);
+ const out = offeredLoras([bts, aw, own]);
+ // The user's own LoRA isn't a licensed work: only its own switch counts.
+ expect(out.loras).toEqual([own]);
+ expect(out.dropped.map((d) => d.file)).toEqual([bts.file, aw.file]);
+ expect(out.notes[0]).toMatch(/left out: turned off in Settings → Models & licences/);
+ reset();
+ changeAccess([{ kind: "keepGpuOnlyLoras", on: true }]);
+ expect(offeredLoras([aw]).loras[0]).toMatchObject({ file: aw.file, keepOnGpu: true });
+ });
+});