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 O1: the LoRA fetcher and mirror (pinned downloads, licence snapshot per file, civitai key)
Claudee9c9f3c8e6b5
diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.tsindex ad44082d..989b31cf 100644--- a/src/app/api/providers/test/route.ts+++ b/src/app/api/providers/test/route.ts@@ -1,4 +1,5 @@import { candidateValues, isTestProvider, PROVIDER_SETTINGS, settingProblem } from "@/lib/connections";+import { testCivitaiKey } from "@/server/loras";import { PROVIDERS } from "@/server/providers";import { validateSetting, withCandidates, type SettingName } from "@/server/settings";@@ -12,7 +13,8 @@ import { validateSetting, withCandidates, type SettingName } from "@/server/settexport async function POST(request: Request) {const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown; field?: unknown };const provider = body.provider;- const adapter = isTestProvider(provider) ? PROVIDERS[provider] : undefined;+ // The civitai key isn't a model provider's: it downloads LoRAs.+ const adapter = provider === "civitai" ? { test: testCivitaiKey } : isTestProvider(provider) ? PROVIDERS[provider as Exclude<typeof provider, "civitai">] : undefined;if (!isTestProvider(provider) || !adapter?.test) return Response.json({ ok: false, detail: "Unknown provider" }, { status: 400 });const values = candidateValues(provider, body.values, body.value) as Partial<Record<SettingName, string>>;try {diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex edaaf34b..61a537c4 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -153,6 +153,11 @@ export function applyBindings(const MODEL_LOADERS = new Set(["UNETLoader", "CheckpointLoaderSimple", "UnetLoaderGGUF", "ImageOnlyCheckpointLoader"]);+/** Whether a graph has a diffusion model loader LoRAs can be attached after (wrapper graphs load models their own way). */+export function canTakeLoras(wf: ComfyWorkflow): boolean {+ return Object.values(wf).some((n) => MODEL_LOADERS.has(n.class_type));+}+/*** Insert LoraLoaderModelOnly nodes after every diffusion model loader (or only the* high/low-noise expert for Wan 2.2 MoE when a LoRA targets one of them) and rewirediff --git a/src/lib/connections.ts b/src/lib/connections.tsindex faba648f..8b104c70 100644--- a/src/lib/connections.ts+++ b/src/lib/connections.ts@@ -4,7 +4,7 @@* address looks like, when to offer the first-run guide, and each connection's one-line status.*/-export type TestProvider = "fal" | "replicate" | "higgsfield" | "comfyui" | "llm";+export type TestProvider = "fal" | "replicate" | "higgsfield" | "comfyui" | "llm" | "civitai";/** The settings each provider's connection test reads; an unsaved value for one of them can be tested before it's saved. */export const PROVIDER_SETTINGS = {@@ -13,6 +13,8 @@ export const PROVIDER_SETTINGS = {higgsfield: ["higgsfieldKey"],comfyui: ["comfyUrl", "comfyToken", "comfyIsolatedUrl"],llm: ["anthropicKey", "ollamaUrl", "ollamaModel", "enhanceProvider"],+ // Not a model provider: the key that downloads a recipe's civitai LoRAs (Settings → LoRAs).+ civitai: ["civitaiKey"],} as const satisfies Record<TestProvider, readonly string[]>;export type ConnectionSetting = (typeof PROVIDER_SETTINGS)[TestProvider][number];@@ -33,6 +35,8 @@ export function candidateValues(provider: TestProvider, values?: unknown, value?return out;}+/** Where to get a civitai API key (Settings → LoRAs links to it). */+export const CIVITAI_KEYS_URL = "https://civitai.com/user/account";/** Where to get a fal.ai key (the guide and Settings link to it). */export const FAL_KEYS_URL = "https://fal.ai/dashboard/keys";/** The ComfyUI address a local install listens on. */diff --git a/src/server/db.ts b/src/server/db.tsindex 12a5931f..a9a16876 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -445,6 +445,20 @@ const MIGRATIONS: string[] = [ALTER TABLE generations ADD COLUMN pinned_at INTEGER;ALTER TABLE generations ADD COLUMN review TEXT;CREATE INDEX IF NOT EXISTS generations_pinned ON generations(pinned_at) WHERE pinned_at IS NOT NULL;`,+ // originals (o/lora-plumbing): every LoRA copy Fuobe made — a download into ComfyUI's loras folder or a mirror on+ // fal / Replicate storage — with its pinned source, hash, size and the licence / civitai permissions it was made under.+ `CREATE TABLE IF NOT EXISTS lora_mirrors (+ file TEXT NOT NULL,+ target TEXT NOT NULL,+ source_url TEXT NOT NULL,+ version TEXT,+ hosted_url TEXT,+ sha256 TEXT,+ size_bytes INTEGER,+ licence_json TEXT,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (file, target)+ );`,];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex 3ad07319..58bf668f 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -33,7 +33,8 @@ import { createExtendChain, createKeyframeFilm, createShotFilm } from "./chains"import { enhancePrompt } from "./enhance";import { setResolver, watchGenerations, type LiveEvent } from "./live";import { provider } from "./providers";-import { probeComfy } from "./providers/comfyui";+import { comfyLoraFiles, probeComfy } from "./providers/comfyui";+import { ensureLorasOnComfy, prepareCloudLoras } from "./loras";import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";import type { PollContext, PollResult, RemoteOutput } from "./providers/types";import { mediaFacts } from "./media-facts";@@ -300,6 +301,9 @@ export const ASSET_FREE: Record<string, string> = {"assist_thread_state.skills_json": "skill names","skills.meta_json": "SKILL.md front matter","skills.files_json": "a skill's own text files, stored inline",+ "lora_mirrors.source_url": "where a LoRA file downloads from (civitai, Hugging Face), without the key",+ "lora_mirrors.hosted_url": "the provider's copy of a LoRA file (fal or Replicate storage), never ours",+ "lora_mirrors.licence_json": "the licence and civitai permissions a LoRA copy was made under",};/** The query that finds the rows of one ASSET_REFS table naming a file (@id), except the purged generation's own (@g). */@@ -802,6 +806,13 @@ async function submit(if (providerId !== "mock" && plan.model.engine !== "open") update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, resolution: tier.resolution }, 1, plan.op) });}}+ // LoRA files: ComfyUI gets the ones it lacks downloaded into its loras folder; a cloud run gets a civitai+ // file mirrored once to the provider's storage (the civitai key never leaves this server).+ if (input.loras?.length && (providerId === "fal" || providerId === "replicate")) {+ input.loras = await prepareCloudLoras(input.loras, providerId, (data, name) => adapter.prepareFile(data, "application/octet-stream", name, route), (message) => update(id, { message }));+ } else if (input.loras?.length && providerId === "comfyui") {+ await ensureLorasOnComfy(input.loras, await comfyLoraFiles(route), (message) => update(id, { message }));+ }const res = await adapter.submit({ generationId: id, model: plan.model, route, input });const now = Date.now();const status = statusOf(id);diff --git a/src/server/loras.ts b/src/server/loras.tsnew file mode 100644index 00000000..3c514eec--- /dev/null+++ b/src/server/loras.ts@@ -0,0 +1,408 @@+import "server-only";+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { cloudPath, civitaiVersion, loraByFile, loraName, needsToken, type LoraEntry } from "@/lib/catalog/loras";+import type { LoraRef } from "@/lib/catalog/types";+import { DATA_DIR, db } from "./db";+import { getSetting } from "./settings";++/**+ * LoRA files for both engines. Nothing here is committed to the repo: files are fetched when a run needs them.+ * - Open engine: before a ComfyUI run, a LoRA its server lacks is downloaded into ComfyUI's loras folder+ * (Settings → LoRA folder): Hugging Face files directly, civitai files by their pinned version with the+ * user's civitai key, checked against the SHA256 (or size) the source states, saved under the unique `file`.+ * - Cloud engine: a civitai LoRA can't go to fal or Replicate as a URL (civitai answers 401 without the key,+ * and the key never leaves this server), so it is mirrored once to the provider's storage, when the+ * model's civitai permissions still include "Rent".+ * Every copy is recorded in `lora_mirrors` with the licence / permission snapshot it was made under.+ */++export class LoraError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "LoraError";+ }+}++const CIVITAI_API = "https://civitai.com/api/v1";+/** fal and Replicate don't document how long an upload lives (unverified): mirrors are made again after this. */+const MIRROR_TTL_MS: Record<string, number> = { fal: 7 * 86_400_000, replicate: 86_400_000 };+/** Where Fuobe keeps a LoRA it downloaded only to mirror it (ComfyUI's folder is used when it has the file). */+export const LORA_CACHE_DIR = path.join(DATA_DIR, "loras");++export type MirrorTarget = "comfyui" | "fal" | "replicate";++export interface LoraCopy {+ file: string;+ target: MirrorTarget;+ sourceUrl: string;+ version: string | null;+ hostedUrl: string | null;+ sha256: string | null;+ sizeBytes: number | null;+ /** The licence the copy was made under: the research's snapshot and, for civitai, the permissions read that day. */+ licence: Record<string, unknown> | null;+ createdAt: number;+}++interface Row {+ file: string;+ target: MirrorTarget;+ source_url: string;+ version: string | null;+ hosted_url: string | null;+ sha256: string | null;+ size_bytes: number | null;+ licence_json: string | null;+ created_at: number;+}++const toCopy = (r: Row): LoraCopy => ({+ file: r.file,+ target: r.target,+ sourceUrl: r.source_url,+ version: r.version,+ hostedUrl: r.hosted_url,+ sha256: r.sha256,+ sizeBytes: r.size_bytes,+ licence: r.licence_json ? (JSON.parse(r.licence_json) as Record<string, unknown>) : null,+ createdAt: r.created_at,+});++export function listLoraCopies(): LoraCopy[] {+ return (db().prepare("SELECT * FROM lora_mirrors ORDER BY created_at DESC").all() as Row[]).map(toCopy);+}++function getCopy(file: string, target: MirrorTarget): LoraCopy | null {+ const r = db().prepare("SELECT * FROM lora_mirrors WHERE file = ? AND target = ?").get(file, target) as Row | undefined;+ return r ? toCopy(r) : null;+}++function recordCopy(c: Omit<LoraCopy, "createdAt">): void {+ db()+ .prepare(+ `INSERT INTO lora_mirrors (file, target, source_url, version, hosted_url, sha256, size_bytes, licence_json, created_at)+ VALUES (@file, @target, @source_url, @version, @hosted_url, @sha256, @size_bytes, @licence_json, @created_at)+ ON CONFLICT(file, target) DO UPDATE SET source_url = excluded.source_url, version = excluded.version, hosted_url = excluded.hosted_url,+ sha256 = excluded.sha256, size_bytes = excluded.size_bytes, licence_json = excluded.licence_json, created_at = excluded.created_at`,+ )+ .run({+ file: c.file,+ target: c.target,+ source_url: c.sourceUrl,+ version: c.version,+ hosted_url: c.hostedUrl,+ sha256: c.sha256,+ size_bytes: c.sizeBytes,+ licence_json: c.licence ? JSON.stringify(c.licence) : null,+ created_at: Date.now(),+ });+}++// ---------------------------------------------------------------------------+// Sources++/** The civitai key, as set in Settings or CIVITAI_API_KEY. */+const civitaiKey = () => getSetting("civitaiKey");++/** A URL as it may be shown or stored: never with a token in it. */+export function redact(text: string, token = civitaiKey()): string {+ let out = text.replace(/([?&]token=)[^&\s"']+/gi, "$1•••");+ if (token) out = out.split(token).join("•••");+ return out;+}++const withToken = (url: string, token: string) => `${url}${url.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}`;++/** What civitai says about a pinned version: the file's size and SHA256, and the model it belongs to. */+async function civitaiVersionFacts(version: string): Promise<{ sha256?: string; sizeBytes?: number; modelId?: string }> {+ const token = civitaiKey();+ const res = await fetch(`${CIVITAI_API}/model-versions/${encodeURIComponent(version)}`, {+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ signal: AbortSignal.timeout(30_000),+ }).catch(() => null);+ if (!res?.ok) return {};+ const body = (await res.json().catch(() => ({}))) as { modelId?: number; files?: { name?: string; primary?: boolean; type?: string; sizeKB?: number; hashes?: { SHA256?: string } }[] };+ const files = body.files ?? [];+ const f = files.find((x) => x.primary) ?? files.find((x) => x.name?.endsWith(".safetensors")) ?? files[0];+ return {+ ...(f?.hashes?.SHA256 && { sha256: f.hashes.SHA256.toLowerCase() }),+ ...(f?.sizeKB && { sizeBytes: Math.round(f.sizeKB * 1024) }),+ ...(body.modelId && { modelId: String(body.modelId) }),+ };+}++/** The permissions a civitai model shows today (allowCommercialUse: Image, RentCivit, Rent, Sell…). */+export async function civitaiPermissions(modelId: string): Promise<string[] | null> {+ const res = await fetch(`${CIVITAI_API}/models/${encodeURIComponent(modelId)}`, { signal: AbortSignal.timeout(30_000) }).catch(() => null);+ if (!res?.ok) return null;+ const body = (await res.json().catch(() => ({}))) as { allowCommercialUse?: string[] | string };+ const v = body.allowCommercialUse;+ return Array.isArray(v) ? v : typeof v === "string" ? v.split(/[,\s]+/).filter(Boolean) : [];+}++/** What Hugging Face says about a file before the download: its SHA256 (x-linked-etag), size and the commit it's at. */+async function hfFacts(url: string): Promise<{ sha256?: string; sizeBytes?: number; revision?: string }> {+ const res = await fetch(url, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(30_000) }).catch(() => null);+ if (!res) return {};+ const etag = res.headers.get("x-linked-etag")?.replace(/"/g, "");+ const size = Number(res.headers.get("x-linked-size"));+ const revision = res.headers.get("x-repo-commit") ?? undefined;+ return { ...(etag && /^[0-9a-f]{64}$/i.test(etag) && { sha256: etag.toLowerCase() }), ...(size > 0 && { sizeBytes: size }), ...(revision && { revision }) };+}++/** Where `file` goes inside `dir`: a plain relative path that stays inside it (trained LoRAs live in fuobe/). */+export function lorasPath(dir: string, file: string): string {+ const root = path.resolve(dir);+ const dest = path.resolve(root, file);+ if (!file || path.isAbsolute(file) || file.split(/[\\/]/).includes("..") || !dest.startsWith(root + path.sep) || !/\.safetensors$/i.test(file)) {+ throw new LoraError(`"${file}" isn't a LoRA file name Fuobe can save`);+ }+ return dest;+}++const mb = (n: number) => `${Math.max(1, Math.round(n / 1_048_576))} MB`;++export interface Downloaded {+ path: string;+ sha256: string;+ sizeBytes: number;+ sourceUrl: string;+ version: string | null;+}++/**+ * Download one LoRA into `dir` under its unique file name: a pinned civitai version with the user's key+ * (?token=, never logged or stored), or a public Hugging Face file. The bytes are checked against the+ * SHA256 the source states (civitai's version API, Hugging Face's x-linked-etag), else its size, and land+ * under the final name only when they match.+ */+export async function downloadLora(ref: LoraRef, dir: string, onProgress?: (message: string) => void): Promise<Downloaded> {+ const entry = loraByFile(ref.file);+ const name = loraName(ref);+ const url = entry?.url ?? ref.url;+ if (!url) throw new LoraError(`${name} has no download address — put ${ref.file} in ComfyUI/models/loras`);+ if (entry?.download === "hf-gated") {+ throw new LoraError(`${name} is in a gated Hugging Face repo: accept its licence on ${entry.page}, then put ${ref.file} in ComfyUI/models/loras`);+ }+ const dest = lorasPath(dir, ref.file);+ let expect: { sha256?: string; sizeBytes?: number } = {};+ let version: string | null = null;+ let fetchUrl = url;+ if (needsToken(url)) {+ version = ref.version ?? entry?.version ?? civitaiVersion(url) ?? null;+ if (!version || civitaiVersion(url) !== version) throw new LoraError(`${name} isn't pinned to a civitai version, so Fuobe won't download it`);+ const token = civitaiKey();+ if (!token) throw new LoraError(`${name} downloads from civitai, which needs your free API key: add it in Settings → LoRAs (civitai.com/user/account)`);+ const facts = await civitaiVersionFacts(version);+ if (facts.modelId && entry?.civitaiModel && facts.modelId !== entry.civitaiModel) throw new LoraError(`civitai version ${version} belongs to another model than ${name}`);+ expect = facts;+ fetchUrl = withToken(url, token);+ } else {+ const facts = await hfFacts(url);+ expect = facts;+ version = facts.revision ?? null;+ }+ onProgress?.(`Downloading ${name}${expect.sizeBytes ? ` (${mb(expect.sizeBytes)})` : ""}`);+ let res: Response;+ try {+ res = await fetch(fetchUrl, { redirect: "follow", signal: AbortSignal.timeout(60 * 60_000) });+ } catch (e) {+ throw new LoraError(`Couldn't reach ${new URL(url).host} to download ${name} (${redact((e as Error).message)})`);+ }+ if (res.status === 401 || res.status === 403) {+ throw new LoraError(+ needsToken(url) ? `civitai refused the download of ${name} (${res.status}): check your civitai key in Settings → LoRAs` : `${new URL(url).host} refused the download of ${name} (${res.status})`,+ );+ }+ if (!res.ok || !res.body) throw new LoraError(`Downloading ${name} failed: ${new URL(url).host} answered ${res.status}`);+ const total = Number(res.headers.get("content-length")) || expect.sizeBytes || 0;+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ const part = `${dest}.part`;+ const hash = crypto.createHash("sha256");+ let bytes = 0;+ let shown = 0;+ const out = fs.createWriteStream(part);+ try {+ for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {+ hash.update(chunk);+ bytes += chunk.length;+ if (!out.write(chunk)) await new Promise<void>((r) => out.once("drain", () => r()));+ const pct = total ? Math.floor((bytes / total) * 10) : 0;+ if (pct > shown) {+ shown = pct;+ onProgress?.(`Downloading ${name} · ${pct * 10}%`);+ }+ }+ await new Promise<void>((resolve, reject) => out.end((e?: Error | null) => (e ? reject(e) : resolve())));+ } catch (e) {+ out.destroy();+ fs.rmSync(part, { force: true });+ throw new LoraError(`Downloading ${name} was cut off (${redact((e as Error).message)})`);+ }+ const sha256 = hash.digest("hex");+ const bad = expect.sha256 ? sha256 !== expect.sha256 : expect.sizeBytes ? Math.abs(bytes - expect.sizeBytes) > 1024 : false;+ if (bad || (total && Number(res.headers.get("content-length")) && bytes !== Number(res.headers.get("content-length")))) {+ fs.rmSync(part, { force: true });+ throw new LoraError(`The downloaded ${name} doesn't match what ${new URL(url).host} says it is, so it wasn't kept — try again`);+ }+ fs.renameSync(part, dest);+ return { path: dest, sha256, sizeBytes: bytes, sourceUrl: url, version };+}++/** One download per file at a time (two jobs needing the same LoRA wait for the same download). */+const inFlight = new Map<string, Promise<Downloaded>>();++function downloadOnce(ref: LoraRef, dir: string, onProgress?: (m: string) => void): Promise<Downloaded> {+ const key = `${path.resolve(dir)}::${ref.file}`;+ const cur = inFlight.get(key);+ if (cur) return cur;+ const p = downloadLora(ref, dir, onProgress).finally(() => inFlight.delete(key));+ inFlight.set(key, p);+ return p;+}++/** The licence a copy is made under: the research's snapshot (and the permissions civitai shows today, when read). */+const licenceSnapshot = (ref: LoraRef, entry: LoraEntry | undefined, permissionsNow?: string[] | null) => {+ const l = ref.licence ?? entry?.licence;+ return l || permissionsNow ? { ...l, ...(permissionsNow && { permissionsNow, readOn: new Date().toISOString().slice(0, 10) }) } : null;+};++// ---------------------------------------------------------------------------+// Open engine++/**+ * Before a ComfyUI run: every LoRA it names must be in ComfyUI's loras folder. A missing one is downloaded+ * into Settings → LoRA folder (when that is ComfyUI's folder on this machine); otherwise the run stops+ * with what to do. `listed` is ComfyUI's own list (GET /models/loras), null when it can't be read.+ */+export async function ensureLorasOnComfy(loras: LoraRef[] | undefined, listed: string[] | null, onProgress?: (m: string) => void): Promise<void> {+ if (!loras?.length) return;+ const dir = getSetting("comfyLorasDir");+ // A list ComfyUI couldn't give says nothing: without a folder to check, ComfyUI's own check has the last word.+ if (!listed && !dir) return;+ const have = new Set((listed ?? []).map((f) => f.replace(/\\/g, "/")));+ const onDisk = (file: string) => {+ try {+ return !!dir && fs.existsSync(lorasPath(dir, file));+ } catch {+ return false;+ }+ };+ const missing = loras.filter((l) => l.file && !have.has(l.file) && !onDisk(l.file));+ for (const l of missing) {+ const entry = loraByFile(l.file);+ const name = loraName(l);+ if (!l.url && !entry) throw new LoraError(`ComfyUI doesn't have ${l.file}: put it in ComfyUI/models/loras`);+ if (!dir) {+ const where = entry?.page ?? (l.url ? redact(l.url) : "");+ throw new LoraError(`ComfyUI doesn't have ${name} yet. Set the LoRA folder in Settings → LoRAs so Fuobe can download it, or put ${l.file} in ComfyUI/models/loras${where ? ` (from ${where})` : ""}`);+ }+ const got = await downloadOnce(l, dir, onProgress);+ recordCopy({ file: l.file, target: "comfyui", sourceUrl: got.sourceUrl, version: got.version, hostedUrl: null, sha256: got.sha256, sizeBytes: got.sizeBytes, licence: licenceSnapshot(l, entry) });+ }+}++// ---------------------------------------------------------------------------+// Cloud engine++/**+ * Before a fal or Replicate run: every LoRA gets a URL the provider can fetch. Public files go as they are;+ * a civitai file is mirrored once to the provider's storage (`upload`), when the model's civitai permissions+ * still include "Rent" (running it on a third-party service), and the mirror is reused while it lives.+ */+export async function prepareCloudLoras(+ loras: LoraRef[] | undefined,+ target: "fal" | "replicate",+ upload: (data: Buffer, name: string) => Promise<string>,+ onProgress?: (m: string) => void,+): Promise<LoraRef[] | undefined> {+ if (!loras?.length) return loras;+ const out: LoraRef[] = [];+ for (const l of loras) {+ if (cloudPath(l)) {+ out.push(l);+ continue;+ }+ const entry = loraByFile(l.file);+ const name = loraName(l);+ if (!l.url || !needsToken(l.url)) throw new LoraError(`${name} can't be sent to ${target === "fal" ? "fal.ai" : "Replicate"}: it has no public download`);+ if (l.licence?.hostedOk === false) throw new LoraError(`${name} runs only on your GPU (its licence doesn't allow hosting it)`);+ const cached = getCopy(l.file, target);+ if (cached?.hostedUrl && Date.now() - cached.createdAt < MIRROR_TTL_MS[target]) {+ out.push({ ...l, hostedUrl: cached.hostedUrl });+ continue;+ }+ // The hosting right is read again before a copy is made: civitai permissions can change.+ const now = entry?.civitaiModel ? await civitaiPermissions(entry.civitaiModel) : null;+ if (now && !now.includes("Rent")) {+ throw new LoraError(`${name}'s civitai licence no longer allows running it on a hosted service, so it can only run on your GPU`);+ }+ const local = [getSetting("comfyLorasDir"), LORA_CACHE_DIR].filter(Boolean).map((d) => path.join(d, l.file)).find((p) => fs.existsSync(p));+ let file = local;+ let facts: Pick<Downloaded, "sha256" | "sizeBytes" | "version"> | null = null;+ if (!file) {+ const got = await downloadOnce(l, LORA_CACHE_DIR, onProgress);+ file = got.path;+ facts = got;+ }+ onProgress?.(`Copying ${name} to ${target === "fal" ? "fal.ai" : "Replicate"} (once)`);+ const data = fs.readFileSync(file);+ const hostedUrl = await upload(data, path.basename(l.file));+ recordCopy({+ file: l.file,+ target,+ sourceUrl: l.url,+ version: facts?.version ?? l.version ?? entry?.version ?? null,+ hostedUrl,+ sha256: facts?.sha256 ?? crypto.createHash("sha256").update(data).digest("hex"),+ sizeBytes: data.length,+ licence: licenceSnapshot(l, entry, now),+ });+ out.push({ ...l, hostedUrl });+ }+ return out;+}++/**+ * Download a library LoRA into the LoRA folder ahead of a run (Settings → LoRAs). Returns the copy recorded.+ */+export async function downloadToComfy(file: string): Promise<LoraCopy> {+ const entry = loraByFile(file);+ if (!entry) throw new LoraError("That LoRA isn't in Fuobe's library");+ const dir = getSetting("comfyLorasDir");+ if (!dir) throw new LoraError("Set the LoRA folder first (ComfyUI's models/loras on this machine)");+ const got = await downloadOnce(entry, dir);+ recordCopy({ file, target: "comfyui", sourceUrl: got.sourceUrl, version: got.version, hostedUrl: null, sha256: got.sha256, sizeBytes: got.sizeBytes, licence: licenceSnapshot(entry, entry) });+ return getCopy(file, "comfyui")!;+}++/** Which library files are in the LoRA folder now (a file someone put there by hand counts too). */+export function filesInLoraFolder(): Set<string> {+ const dir = getSetting("comfyLorasDir");+ const out = new Set<string>();+ if (!dir || !fs.existsSync(dir)) return out;+ for (const e of fs.readdirSync(dir, { recursive: true, withFileTypes: true })) {+ if (!e.isFile() || !e.name.endsWith(".safetensors")) continue;+ const rel = path.relative(dir, path.join(e.parentPath ?? dir, e.name)).split(path.sep).join("/");+ out.add(rel);+ }+ return out;+}++/** Test the civitai key (Settings → Save & test): civitai's /me answers 200 for a good key. */+export async function testCivitaiKey(): Promise<{ ok: boolean; detail: string }> {+ const token = civitaiKey();+ if (!token) return { ok: false, detail: "No key set" };+ let res: Response;+ try {+ res = await fetch(`${CIVITAI_API}/me`, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15_000) });+ } catch (e) {+ return { ok: false, detail: `Can't reach civitai (${redact((e as Error).message, token)})` };+ }+ if (res.status === 401 || res.status === 403) return { ok: false, detail: `Key rejected (${res.status})` };+ if (!res.ok) return { ok: false, detail: `Couldn't check the key: civitai answered ${res.status}. Try again in a moment` };+ const me = (await res.json().catch(() => ({}))) as { username?: string };+ return { ok: true, detail: me.username ? `Signed in as ${me.username}` : "Key accepted" };+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex b807e535..3ca2bb1a 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -15,6 +15,7 @@ import {dropVhsAudio,expandCaptionWorkflow,explainComfyError,+ canTakeLoras,injectLoras,languageName,paletteSentence,@@ -37,6 +38,7 @@ import { expandAudioJoinWorkflow, expandVideoJoinWorkflow } from "@/lib/av/joinsimport { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipProblem, wholeClipTool } from "@/lib/av/video-finish";import { guessKind } from "@/lib/catalog/payload";+import { loraByFile, needsToken } from "@/lib/catalog/loras";import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, swapTarget } from "@/lib/catalog/genjutsu";import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, targetPhrase } from "@/lib/catalog/remove-object";import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";@@ -930,7 +932,11 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,} catch (e) {throw new ProviderError((e as Error).message);}- if (input.loras?.length) wf = injectLoras(wf, input.loras);+ if (input.loras?.length) {+ // A LoRA a graph can't attach would be dropped without a word: say so instead.+ if (!canTakeLoras(wf)) throw new ProviderError(`${manifest.title} can't take LoRAs (it has no model loader to attach them to)`);+ wf = injectLoras(wf, input.loras);+ }// The output not asked for isn't saved (nor encoded: ComfyUI runs only what an output node needs).if (keepRole && manifest.outputs.some((o) => o.role === keepRole)) for (const o of manifest.outputs) if (o.role && o.role !== keepRole) delete wf[o.node];if (ctx.op === "remove-object" && !handOff) for (const o of manifest.outputs) if (o.role === "mask") delete wf[o.node];@@ -1075,7 +1081,10 @@ export const comfyProvider: ProviderAdapter = {const where = worker === "isolated" ? "the isolated ComfyUI worker" : "your ComfyUI";const missingPack =body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)` : undefined;- const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : (missingPack ?? body.error?.message);+ // A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.+ const loraModels = (input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));+ let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? body.error?.message);+ if (detail && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;if (!detail && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);throw new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status);}@@ -1190,6 +1199,16 @@ export const comfyProvider: ProviderAdapter = {},};+/** The LoRA files the ComfyUI server that runs `route` has (GET /models/loras), or null when it can't say. */+export async function comfyLoraFiles(route?: ModelRoute): Promise<string[] | null> {+ try {+ const res = await comfyFetch("/models/loras", {}, workerFor(route?.endpoint));+ return res.ok ? ((await res.json()) as string[]) : null;+ } catch {+ return null;+ }+}+/** Which manifest models are present on the connected ComfyUI server. */export async function modelInventory(): Promise<Record<string, string[]> | null> {try {diff --git a/src/server/settings.ts b/src/server/settings.tsindex 8af8186e..e1027b92 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -32,8 +32,13 @@ export const SETTINGS = {comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },/** A second ComfyUI for workflows whose node packs can't share the main install (LatentSync 1.6, ThinkSound; scripts/comfy/README.md). */comfyIsolatedUrl: { key: "comfyui.isolatedUrl", env: "COMFYUI_ISOLATED_URL" },- /** ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there. */+ /**+ * ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there, and a recipe's+ * LoRAs (looks, motions) are downloaded there before a run needs them (src/server/loras.ts).+ */comfyLorasDir: { key: "comfyui.lorasDir", env: "COMFYUI_LORAS_DIR" },+ /** civitai API key: downloads the civitai LoRAs of a recipe (civitai answers 401 without one). Never sent to fal or Replicate. */+ civitaiKey: { key: "civitai.key", env: "CIVITAI_API_KEY", secret: true },/** AI-Toolkit UI (ostris/ai-toolkit, port 8675) for open-source character LoRA training. */aiToolkitUrl: { key: "aitk.url", env: "AI_TOOLKIT_URL" },aiToolkitToken: { key: "aitk.token", env: "AI_TOOLKIT_AUTH", secret: true },diff --git a/tests/comfy-lora.test.ts b/tests/comfy-lora.test.tsnew file mode 100644index 00000000..55cb7878--- /dev/null+++ b/tests/comfy-lora.test.ts@@ -0,0 +1,78 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import { loraEntry, loraRef } from "@/lib/catalog/loras";+import type { GenInput, Operation } from "@/lib/catalog/types";+import { canTakeLoras, type ComfyWorkflow } from "@/lib/comfy";++// LoRAs on the open engine through the provider: a recipe's LoRA stack on the library graphs (injectLoras after+// each diffusion model loader, Wan 2.2's high / low-noise experts apart), and graphs that can't take one.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-lora-"));+process.env.FUOBE_DATA_DIR = tmp;+process.env.COMFYUI_URL = "http://comfy.test:8188";+const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");+const { getModel, PRESETS, MOTIONS, EFFECTS } = await import("@/lib/catalog");+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));++async function prepare(id: string, input: GenInput, op: Operation) {+ return prepareWorkflow(id, { seed: 7, ...input }, { generationId: "g", op, upload: async (_d, _t, name) => `up_${name}`, media: () => undefined, serverRam: async () => undefined });+}++/** The LoRA chain after a loader: each LoraLoaderModelOnly from the loader on, in order. */+function chainAfter(wf: ComfyWorkflow, loader: string): { file: string; strength: number }[] {+ const out: { file: string; strength: number }[] = [];+ let up = loader;+ for (;;) {+ const next = Object.entries(wf).find(([, n]) => n.class_type === "LoraLoaderModelOnly" && Array.isArray(n.inputs.model) && n.inputs.model[0] === up);+ if (!next) return out;+ out.push({ file: String(next[1].inputs.lora_name), strength: Number(next[1].inputs.strength_model) });+ up = next[0];+ }+}++const loaderOf = (wf: ComfyWorkflow, match: RegExp) => Object.entries(wf).find(([, n]) => n.class_type === "UNETLoader" && match.test(String(n.inputs.unet_name)))![0];++describe("LoRA stacks on ComfyUI graphs", () => {+ it("puts each Wan 2.2 LoRA on its expert: the pair apart, a Wan 2.1 LoRA on both", async () => {+ const pair = ["civitai-2126493-camera-tilt-up-overhead", "civitai-2126538-camera-tilt-up-overhead"].map((k) => loraRef(loraEntry(k)!, 0.8));+ const squish = { file: "squish_18.safetensors", strength: 0.6, target: "both" as const };+ const { workflow: wf } = await prepare("wan22-i2v-14b", { prompt: "rise", images: ["a.png"], duration: 5, loras: [...pair, squish] }, "i2v");+ expect(chainAfter(wf, loaderOf(wf, /high_noise/))).toEqual([+ { file: pair[0].file, strength: 0.8 },+ { file: "squish_18.safetensors", strength: 0.6 },+ ]);+ expect(chainAfter(wf, loaderOf(wf, /low_noise/))).toEqual([+ { file: pair[1].file, strength: 0.8 },+ { file: "squish_18.safetensors", strength: 0.6 },+ ]);+ // Everything that read a loader now reads the end of its LoRA chain.+ const loaders = new Set([loaderOf(wf, /high_noise/), loaderOf(wf, /low_noise/)]);+ const readers = Object.values(wf).filter((n) => n.class_type !== "LoraLoaderModelOnly" && Object.values(n.inputs).some((v) => Array.isArray(v) && loaders.has(String(v[0]))));+ expect(readers).toEqual([]);+ });++ it("stacks a Soul look's three LoRAs after Z-Image Turbo's loader, in order", async () => {+ const looks = ["awportrait", "y2k", "hardflash"].map((k) => loraRef(loraEntry(k)!));+ const { workflow: wf } = await prepare("z-image-turbo-t2i", { prompt: "a woman leaving a club", aspectRatio: "3:4", loras: looks }, "t2i");+ expect(chainAfter(wf, loaderOf(wf, /z_image_turbo/))).toEqual(looks.map((l) => ({ file: l.file, strength: l.strength })));+ });++ it("refuses LoRAs on a graph with no model loader instead of dropping them", async () => {+ const graph = "video-trim";+ expect(canTakeLoras(getWorkflow(graph).workflow)).toBe(false);+ await expect(prepare(graph, { video: "a.mp4", startTime: 0, endTime: 1, loras: [loraRef(loraEntry("awportrait")!)] }, "trim")).rejects.toThrow(/can't take LoRAs/);+ });++ it("sends every preset's open LoRAs to a graph that can take them", () => {+ const bad: string[] = [];+ for (const p of [...PRESETS, ...MOTIONS, ...EFFECTS]) {+ if (!p.open?.loras?.length) continue;+ const m = getModel(p.open.modelId);+ for (const r of m?.routes.filter((x) => x.provider === "comfyui" && x.op === p.open!.op) ?? []) {+ if (!canTakeLoras(getWorkflow(r.endpoint.replace("{n}", "2")).workflow)) bad.push(`${p.id} → ${r.endpoint}`);+ }+ }+ expect(bad).toEqual([]);+ });+});diff --git a/tests/lora-fetch.test.ts b/tests/lora-fetch.test.tsnew file mode 100644index 00000000..92e2fda6--- /dev/null+++ b/tests/lora-fetch.test.ts@@ -0,0 +1,200 @@+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";+import { loraEntry, loraRef } from "@/lib/catalog/loras";+import type { LoraRef } from "@/lib/catalog/types";++// The downloader reads the civitai key and the LoRA folder from the settings table: a throwaway data folder.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-lora-fetch-"));+process.env.FUOBE_DATA_DIR = dir;+const { downloadLora, ensureLorasOnComfy, prepareCloudLoras, listLoraCopies, lorasPath, redact, LORA_CACHE_DIR } = await import("@/server/loras");+const { setSetting } = await import("@/server/settings");+const { db } = await import("@/server/db");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const KEY = "civitai-secret-0123456789abcdef";+const bytes = (s: string) => Buffer.from(s.repeat(64));+const sha = (b: Buffer) => crypto.createHash("sha256").update(b).digest("hex");++interface Call {+ url: string;+ method: string;+ headers: Record<string, string>;+}++/** A fake network: answers by URL prefix, records every call (with headers), never touches the internet. */+function network(routes: Record<string, (c: Call) => Response>) {+ const calls: Call[] = [];+ const real = globalThis.fetch;+ globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {+ const call = { url: String(input), method: init?.method ?? "GET", headers: Object.fromEntries(new Headers(init?.headers).entries()) };+ calls.push(call);+ const hit = Object.keys(routes)+ .sort((a, b) => b.length - a.length)+ .find((k) => call.url.startsWith(k));+ if (!hit) return new Response("not here", { status: 404 });+ return routes[hit](call);+ }) as typeof fetch;+ return { calls, restore: () => (globalThis.fetch = real) };+}++let net: ReturnType<typeof network> | undefined;+let folder: string;+beforeEach(() => {+ folder = fs.mkdtempSync(path.join(dir, "loras-"));+ setSetting("civitaiKey", "");+ setSetting("comfyLorasDir", "");+ db().prepare("DELETE FROM lora_mirrors").run();+ fs.rmSync(LORA_CACHE_DIR, { recursive: true, force: true });+});+afterEach(() => net?.restore());++const aw = loraRef(loraEntry("awportrait")!);+const y2k = loraRef(loraEntry("y2k")!);+const AW_BODY = bytes("awportrait");+const Y2K_BODY = bytes("y2k-style");++/** Hugging Face: a HEAD answered with a redirect carrying the file's SHA256 and size, then the file. */+const hfRoutes = (body: Buffer, etag = sha(body)) => ({+ [aw.url!]: (c: Call) =>+ c.method === "HEAD"+ ? new Response(null, { status: 302, headers: { "x-linked-etag": `"${etag}"`, "x-linked-size": String(body.length), "x-repo-commit": "abc123" } })+ : new Response(new Uint8Array(body), { status: 200, headers: { "content-length": String(body.length) } }),+});++/** civitai: the version API (hash, size, model) and the download, which needs ?token=. */+const civitaiRoutes = (body: Buffer, opts: { modelId?: number; permissions?: string[]; hash?: string } = {}) => ({+ "https://civitai.com/api/v1/model-versions/3422541": () =>+ Response.json({ id: 3422541, modelId: opts.modelId ?? 2979601, files: [{ name: "V1.safetensors", primary: true, sizeKB: body.length / 1024, hashes: { SHA256: (opts.hash ?? sha(body)).toUpperCase() } }] }),+ "https://civitai.com/api/v1/models/2979601": () => Response.json({ id: 2979601, allowCommercialUse: opts.permissions ?? ["Image", "RentCivit", "Rent", "Sell"] }),+ "https://civitai.com/api/download/models/3422541": (c: Call) =>+ new URL(c.url).searchParams.get("token") === KEY ? new Response(new Uint8Array(body), { status: 200, headers: { "content-length": String(body.length) } }) : Response.json({ error: "Unauthorized" }, { status: 401 }),+});++describe("LoRA downloads (pinned, checked, never leaking the civitai key)", () => {+ it("downloads a Hugging Face file directly under its unique name and checks its SHA256", async () => {+ net = network(hfRoutes(AW_BODY));+ const got = await downloadLora(aw, folder);+ expect(got.path).toBe(path.join(folder, "AWPortrait-Z.safetensors"));+ expect(fs.readFileSync(got.path).equals(AW_BODY)).toBe(true);+ expect(got).toMatchObject({ sha256: sha(AW_BODY), sizeBytes: AW_BODY.length, version: "abc123", sourceUrl: aw.url });+ expect(fs.readdirSync(folder)).toEqual(["AWPortrait-Z.safetensors"]);+ });++ it("keeps nothing when the bytes don't match the stated hash", async () => {+ net = network(hfRoutes(AW_BODY, "0".repeat(64)));+ await expect(downloadLora(aw, folder)).rejects.toThrow(/doesn't match/);+ expect(fs.readdirSync(folder)).toEqual([]);+ });++ it("asks for a civitai key before touching a civitai download", async () => {+ net = network(civitaiRoutes(Y2K_BODY));+ await expect(downloadLora(y2k, folder)).rejects.toThrow(/needs your free API key: add it in Settings → LoRAs/);+ expect(net.calls.filter((c) => c.url.includes("/api/download/"))).toEqual([]);+ });++ it("downloads the pinned civitai version with ?token= and stores neither the key nor a tokenised URL", async () => {+ setSetting("civitaiKey", KEY);+ setSetting("comfyLorasDir", folder);+ net = network(civitaiRoutes(Y2K_BODY));+ await ensureLorasOnComfy([y2k], [], () => {});+ const saved = path.join(folder, "civitai-3422541-y2k.safetensors");+ expect(fs.readFileSync(saved).equals(Y2K_BODY)).toBe(true);+ // The version it asked civitai about is the pinned one, never "latest".+ expect(net.calls.map((c) => c.url.split("?")[0])).toEqual(["https://civitai.com/api/v1/model-versions/3422541", "https://civitai.com/api/download/models/3422541"]);+ const [copy] = listLoraCopies();+ expect(copy).toMatchObject({ file: "civitai-3422541-y2k.safetensors", target: "comfyui", version: "3422541", sha256: sha(Y2K_BODY), sourceUrl: y2k.url });+ // The licence snapshot it was made under.+ expect(copy.licence).toMatchObject({ commercial: true, hostedOk: true, snapshotDate: "2026-10-23", permissions: ["Image", "RentCivit", "Rent", "Sell", "SellMerge"] });+ const stored = JSON.stringify(db().prepare("SELECT * FROM lora_mirrors").all());+ expect(stored).not.toContain(KEY);+ expect(stored).not.toContain("token=");+ });++ it("says to check the key on a 401, without the key in the message", async () => {+ setSetting("civitaiKey", "wrong-key-987654321");+ net = network(civitaiRoutes(Y2K_BODY));+ const err = (await downloadLora(y2k, folder).catch((e: Error) => e)) as Error;+ expect(err.message).toMatch(/civitai refused the download of V67 Y2K Style \(401\): check your civitai key in Settings → LoRAs/);+ expect(err.message).not.toContain("wrong-key");+ expect(redact(`https://civitai.com/api/download/models/1?token=${KEY}`, KEY)).toBe("https://civitai.com/api/download/models/1?token=•••");+ });++ it("refuses an unpinned civitai URL and a version that belongs to another model", async () => {+ setSetting("civitaiKey", KEY);+ net = network(civitaiRoutes(Y2K_BODY, { modelId: 1 }));+ await expect(downloadLora({ ...y2k, file: "x.safetensors", url: "https://civitai.com/api/download/models/latest", version: undefined }, folder)).rejects.toThrow(/isn't pinned/);+ await expect(downloadLora(y2k, folder)).rejects.toThrow(/belongs to another model/);+ expect(fs.readdirSync(folder)).toEqual([]);+ });++ it("keeps every file inside the LoRA folder", () => {+ expect(lorasPath(folder, "fuobe/maya.safetensors")).toBe(path.join(folder, "fuobe", "maya.safetensors"));+ for (const bad of ["../evil.safetensors", "/etc/x.safetensors", "a/../../b.safetensors", "notes.txt", ""]) expect(() => lorasPath(folder, bad), bad).toThrow(/isn't a LoRA file name/);+ });+});++describe("Before a ComfyUI run", () => {+ it("does nothing when ComfyUI already lists the LoRA", async () => {+ net = network({});+ await ensureLorasOnComfy([aw], ["AWPortrait-Z.safetensors"]);+ expect(net.calls).toEqual([]);+ });++ it("says what to do when the LoRA is missing and no LoRA folder is set", async () => {+ net = network({});+ await expect(ensureLorasOnComfy([aw], ["other.safetensors"])).rejects.toThrow(+ /ComfyUI doesn't have Shakker-Labs AWPortrait-Z yet\. Set the LoRA folder in Settings → LoRAs .* put AWPortrait-Z\.safetensors in ComfyUI\/models\/loras \(from https:\/\/huggingface\.co\/Shakker-Labs\/AWPortrait-Z\)/,+ );+ // ComfyUI couldn't list its LoRAs and there's no folder to check: its own validation has the last word.+ await expect(ensureLorasOnComfy([aw], null)).resolves.toBeUndefined();+ });++ it("downloads a missing LoRA into the folder once, even when two runs ask at the same time", async () => {+ setSetting("comfyLorasDir", folder);+ net = network(hfRoutes(AW_BODY));+ const progress: string[] = [];+ await Promise.all([ensureLorasOnComfy([aw], [], (m) => progress.push(m)), ensureLorasOnComfy([aw], [])]);+ expect(net.calls.filter((c) => c.method === "GET")).toHaveLength(1);+ expect(progress[0]).toMatch(/^Downloading Shakker-Labs AWPortrait-Z/);+ expect(fs.existsSync(path.join(folder, "AWPortrait-Z.safetensors"))).toBe(true);+ // Already on disk (ComfyUI's list not refreshed yet): no second download.+ await ensureLorasOnComfy([aw], []);+ expect(net.calls.filter((c) => c.method === "GET")).toHaveLength(1);+ });+});++describe("Before a cloud run", () => {+ const upload = () => {+ const sent: { name: string; size: number }[] = [];+ return { sent, fn: async (data: Buffer, name: string) => (sent.push({ name, size: data.length }), `https://v3.fal.media/files/${name}`) };+ };++ it("sends public files as they are and mirrors a civitai file once (Rent allowed), then reuses the mirror", async () => {+ setSetting("civitaiKey", KEY);+ net = network(civitaiRoutes(Y2K_BODY));+ const up = upload();+ const first = (await prepareCloudLoras([aw, y2k], "fal", up.fn)) as LoraRef[];+ expect(first[0]).toBe(aw);+ expect(first[1].hostedUrl).toBe("https://v3.fal.media/files/civitai-3422541-y2k.safetensors");+ expect(up.sent).toEqual([{ name: "civitai-3422541-y2k.safetensors", size: Y2K_BODY.length }]);+ const mirror = listLoraCopies().find((c) => c.target === "fal")!;+ expect(mirror).toMatchObject({ hostedUrl: first[1].hostedUrl, version: "3422541", sha256: sha(Y2K_BODY) });+ expect(mirror.licence).toMatchObject({ permissionsNow: ["Image", "RentCivit", "Rent", "Sell"] });+ const again = (await prepareCloudLoras([y2k], "fal", up.fn)) as LoraRef[];+ expect(again[0].hostedUrl).toBe(first[1].hostedUrl);+ expect(up.sent).toHaveLength(1);+ });++ it("won't mirror when civitai no longer allows hosting, or a local-only LoRA", async () => {+ setSetting("civitaiKey", KEY);+ net = network(civitaiRoutes(Y2K_BODY, { permissions: ["Image", "RentCivit"] }));+ const up = upload();+ await expect(prepareCloudLoras([y2k], "fal", up.fn)).rejects.toThrow(/no longer allows running it on a hosted service/);+ const wiggle = loraRef(loraEntry("civitai-2490836-wiggle-redmond")!);+ await expect(prepareCloudLoras([wiggle], "replicate", up.fn)).rejects.toThrow(/runs only on your GPU/);+ expect(up.sent).toEqual([]);+ });+});