Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: detect Flux.2 Klein HuggingFace LoRAs instead of offering only LTX-Video

[._.]/ Adam Eivy937771bf2e3d
diff --git a/.changelog/next/fixed-agent-414807a0.md b/.changelog/next/fixed-agent-414807a0.md
new file mode 100644
index 0000000000..2fea815ed7
--- /dev/null
+++ b/.changelog/next/fixed-agent-414807a0.md
@@ -0,0 +1 @@
+- HuggingFace LoRA install now detects Flux.2 Klein (and other image families) instead of only offering LTX-Video.
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 99e8035fce..82ed7add03 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -1,10 +1,10 @@
/**
- * LoRA Manager — install / browse / delete Civitai LoRAs.
+ * LoRA Manager — install / browse / delete Civitai and HuggingFace LoRAs.
*
- * Paste a Civitai URL to download and install. Each LoRA card shows the
- * Civitai preview, base model (Flux.1 / Flux.2 / Z-Image / Other), trigger
- * words, recommended scale, and a "Test in Image Gen" deep-link that
- * preselects the LoRA on the generation page.
+ * Paste a Civitai or HuggingFace URL to download and install. Each LoRA card
+ * shows the preview, base model (Flux.1 / Flux.2 / Z-Image / LTX / Other),
+ * trigger words, recommended scale, and a "Test in Image Gen" / Video Gen
+ * deep-link that preselects the LoRA on the generation page.
*/
import { useState, useEffect, useCallback } from 'react';
@@ -70,6 +70,20 @@ const cardKey = (card) => suggestionKey(card.modelId, card.versionId);
const hfCardKey = (card) => `${card.repo}:${card.file || ''}`;
const installedHfKey = (lora) => `${lora.huggingface?.repo || ''}:${lora.huggingface?.file || ''}`;
+// Manual family choices when HF autodetection returns HF_UNKNOWN_FAMILY.
+// Image families first — the previous LTX-only confirm silently mis-tagged
+// Flux.2 Klein adapters (Alissonerdx/CharacterSheet) as video LoRAs.
+const HF_FAMILY_OVERRIDES = [
+ { family: RUNNER_FAMILIES.FLUX2, label: 'Flux 2' },
+ { family: RUNNER_FAMILIES.MFLUX, label: 'Flux 1' },
+ { family: RUNNER_FAMILIES.Z_IMAGE, label: 'Z-Image' },
+ { family: RUNNER_FAMILIES.QWEN, label: 'Qwen' },
+ { family: RUNNER_FAMILIES.ERNIE, label: 'ERNIE' },
+ { family: RUNNER_FAMILIES.HIDREAM, label: 'HiDream' },
+ { family: VIDEO_LORA_FAMILIES.LTX_VIDEO, label: 'LTX-Video' },
+ { family: VIDEO_LORA_FAMILIES.MINIMAX_H3, label: 'MiniMax H3' },
+];
+
// Integer download percent (0..100) from an SSE progress frame, or null when
// the frame carries no numeric ratio (server sent no Content-Length → the UI
// shows an indeterminate bar). Shared by the HF install form button, the
@@ -82,8 +96,8 @@ export default function Loras() {
const [error, setError] = useState(null);
const [installUrl, setInstallUrl] = useState('');
const [installing, setInstalling] = useState(false);
- // HuggingFace video-LoRA import (fal / Lightricks LTX LoRAs) — separate from
- // the Civitai installer above because video LoRAs live on HF.
+ // HuggingFace LoRA import (Flux.2 Klein image adapters, fal / Lightricks
+ // LTX video LoRAs) — separate from the Civitai installer above.
const [hfUrl, setHfUrl] = useState('');
const [hfInstalling, setHfInstalling] = useState(false);
// Byte-level download progress for the in-flight HF install (form OR curated
@@ -91,9 +105,9 @@ export default function Loras() {
// where progress is 0..1, or null when the server had no Content-Length.
const [hfProgress, setHfProgress] = useState(null);
// When autodetection can't classify the repo (HF_UNKNOWN_FAMILY), hold the
- // URL here to render an inline "install as LTX-Video?" confirm row — the API
- // supports an explicit family override, so a valid LTX LoRA with an
- // unrecognizable id shouldn't dead-end at an error toast.
+ // URL here to render an inline family picker — the API supports an explicit
+ // family override, so a valid LoRA with an unrecognizable id shouldn't
+ // dead-end at an error toast (or get force-tagged as LTX-Video).
const [hfFamilyPrompt, setHfFamilyPrompt] = useState(null);
const [deleting, setDeleting] = useState(null);
// Arms one installed card's delete at a time — a LoRA is a multi-gigabyte
@@ -174,9 +188,10 @@ export default function Loras() {
return performInstall(installUrl.trim());
};
- // Install a video LoRA from a HuggingFace repo. The family is auto-detected
- // server-side from the repo id/tags (LTX-Video → ltx-video); HF_UNKNOWN_FAMILY
- // surfaces as a toast asking the user to confirm it's an LTX LoRA.
+ // Install a LoRA from a HuggingFace repo. The family is auto-detected
+ // server-side from the repo id/tags/filenames (Flux.2 Klein → flux2,
+ // LTX-Video → ltx-video); HF_UNKNOWN_FAMILY surfaces as an inline picker
+ // of image and video families rather than a dead-end toast.
// Shared install runner: `family` is undefined for the first attempt
// (server autodetects) and set to the override on the inline-confirm retry.
const runHfInstall = useCallback(async (url, family) => {
@@ -195,8 +210,8 @@ export default function Loras() {
})
.catch((err) => {
// Autodetection failed but the install is otherwise valid — offer an
- // inline confirm to retry with the LTX-Video family rather than toast a
- // dead-end. (Skip when we already tried with an explicit override.)
+ // inline family picker rather than toast a dead-end or force LTX.
+ // (Skip when we already tried with an explicit override.)
if (err?.code === 'HF_UNKNOWN_FAMILY' && !family) {
setHfFamilyPrompt(url);
} else {
@@ -265,7 +280,7 @@ export default function Loras() {
<div>
<h1 className="text-2xl font-bold text-white mb-1">LoRA Manager</h1>
<p className="text-sm text-gray-400">
- Install LoRA fine-tunes from Civitai (image) or HuggingFace (video) and apply them to your Image Gen and Video Gen renders.
+ Install LoRA fine-tunes from Civitai or HuggingFace and apply them to your Image Gen and Video Gen renders.
</p>
</div>
@@ -312,15 +327,15 @@ export default function Loras() {
>
<div className="flex items-center gap-2 text-sm font-medium text-gray-300">
<Download size={16} />
- <span>Install video LoRA from HuggingFace</span>
+ <span>Install LoRA from HuggingFace</span>
</div>
<div className="flex gap-2">
<input
type="text"
value={hfUrl}
onChange={(e) => setHfUrl(e.target.value)}
- aria-label="HuggingFace video LoRA URL"
- placeholder="https://huggingface.co/fal/ltx2.3-audio-reactive-lora"
+ aria-label="HuggingFace LoRA URL"
+ placeholder="https://huggingface.co/Alissonerdx/CharacterSheet"
className="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600"
disabled={hfInstalling}
/>
@@ -335,24 +350,30 @@ export default function Loras() {
{hfInstalling && <HfDownloadProgress progress={hfProgress} />}
<p className="text-xs text-gray-500">
Paste a <code className="bg-port-bg px-1 rounded">huggingface.co</code> repo URL — or an{' '}
- <code className="bg-port-bg px-1 rounded">org/name</code> id — for an LTX-Video LoRA
- (e.g. <code className="bg-port-bg px-1 rounded">fal/ltx2.3-audio-reactive-lora</code>).
- These apply to <Link to="/media/video" className="text-port-accent hover:underline">Video Gen</Link> renders on an LTX-2 (ltx2) model. Gated repos use your HuggingFace token from Image Gen settings.
+ <code className="bg-port-bg px-1 rounded">org/name</code> id — for an image or video LoRA
+ (e.g. <code className="bg-port-bg px-1 rounded">Alissonerdx/CharacterSheet</code> or{' '}
+ <code className="bg-port-bg px-1 rounded">fal/ltx2.3-audio-reactive-lora</code>).
+ Flux.2 Klein adapters apply in <Link to="/media/image" className="text-port-accent hover:underline">Image Gen</Link>;
+ LTX-Video LoRAs apply in <Link to="/media/video" className="text-port-accent hover:underline">Video Gen</Link>.
+ Gated repos use your HuggingFace token from Image Gen settings.
</p>
{hfFamilyPrompt && (
- <div className="flex items-center justify-between gap-3 rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2">
+ <div className="rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2 space-y-2">
<span className="text-xs text-gray-300">
- Couldn&apos;t detect the model family for <code className="bg-port-bg px-1 rounded">{hfFamilyPrompt}</code>. Install it as an LTX-Video LoRA?
+ Couldn&apos;t detect the model family for <code className="bg-port-bg px-1 rounded">{hfFamilyPrompt}</code>. Choose the runner this LoRA targets:
</span>
- <div className="flex items-center gap-2 shrink-0">
- <button
- type="button"
- onClick={() => runHfInstall(hfFamilyPrompt, VIDEO_LORA_FAMILIES.LTX_VIDEO)}
- disabled={hfInstalling}
- className="bg-port-accent text-white px-3 py-1 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
- >
- {hfInstalling ? (hfPct != null ? `Installing ${hfPct}%` : 'Installing…') : 'Install as LTX-Video'}
- </button>
+ <div className="flex flex-wrap items-center gap-2">
+ {HF_FAMILY_OVERRIDES.map(({ family, label }) => (
+ <button
+ key={family}
+ type="button"
+ onClick={() => runHfInstall(hfFamilyPrompt, family)}
+ disabled={hfInstalling}
+ className="bg-port-accent text-white px-3 py-1 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
+ >
+ {hfInstalling ? (hfPct != null ? `Installing ${hfPct}%` : 'Installing…') : `Install as ${label}`}
+ </button>
+ ))}
<button
type="button"
onClick={() => setHfFamilyPrompt(null)}
diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsx
index 6e8f028602..2824977904 100644
--- a/client/src/pages/Loras.test.jsx
+++ b/client/src/pages/Loras.test.jsx
@@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import Loras from './Loras';
-import { listLorasFull, deleteLoraFull } from '../services/api';
+import { listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream } from '../services/api';
vi.mock('../services/api', () => ({
listLorasFull: vi.fn(),
@@ -112,3 +112,24 @@ describe('Loras installed-card delete confirmation', () => {
expect(screen.getByText('Example LoRA')).toBeInTheDocument();
});
});
+
+describe('Loras HuggingFace family picker', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listLorasFull.mockResolvedValue([]);
+ installLoraFromHuggingfaceStream.mockRejectedValue(
+ Object.assign(new Error('could not classify'), { code: 'HF_UNKNOWN_FAMILY' }),
+ );
+ });
+
+ it('offers image and video families when autodetection fails, not just LTX-Video', async () => {
+ renderPage();
+ const input = await screen.findByLabelText('HuggingFace LoRA URL');
+ fireEvent.change(input, { target: { value: 'https://huggingface.co/Alissonerdx/CharacterSheet' } });
+ fireEvent.submit(input.closest('form'));
+ expect(await screen.findByRole('button', { name: 'Install as Flux 2' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Install as Flux 1' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Install as LTX-Video' })).toBeInTheDocument();
+ expect(screen.queryByText(/Install it as an LTX-Video LoRA/)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 9648d26b41..b2181c64f9 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -433,10 +433,11 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(
silent,
});
-// Install a video LoRA from a HuggingFace repo (fal / Lightricks LTX LoRAs).
-// `family` is an optional override (e.g. 'ltx-video') when autodetection from
-// the repo id/tags can't classify it. `silent` lets the page route HF_AUTH /
-// HF_UNKNOWN_FAMILY errors into its own inline UI.
+// Install an image or video LoRA from a HuggingFace repo (Flux.2 Klein, fal /
+// Lightricks LTX, MiniMax H3). `family` is an optional override (e.g. 'flux2'
+// or 'ltx-video') when autodetection from the repo id/tags/filenames can't
+// classify it. `silent` lets the page route HF_AUTH / HF_UNKNOWN_FAMILY errors
+// into its own inline UI.
export const installLoraFromHuggingface = ({ url, family, file, silent = false } = {}) => request('/loras/install/huggingface', {
method: 'POST',
body: JSON.stringify({ url, ...(family ? { family } : {}), ...(file ? { file } : {}) }),
diff --git a/server/lib/README.md b/server/lib/README.md
index 0b14d76c29..7f0dd98b28 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -274,7 +274,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, pitch math (`pitchToMidi`/`midiToFreq`), and `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
| `civitai.js` | Civitai URL parsing + API client. |
-| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision}`, fetch `/api/models` metadata, select an exact or preferred `.safetensors`, detect the video-LoRA family (`ltx-video`), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js` for video LoRAs. Pure. |
+| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision,file}`, fetch `/api/models` metadata, select an exact or family-matching `.safetensors`, detect the image or video LoRA family (`flux2` / `ltx-video` / …), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js`. Pure. |
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.js
index bc4bff7d3f..e139514b0a 100644
--- a/server/lib/huggingfaceLora.js
+++ b/server/lib/huggingfaceLora.js
@@ -1,13 +1,14 @@
/**
* HuggingFace LoRA import — pure helpers for parsing HF refs, fetching repo
* metadata, picking the .safetensors to download, and building the PortOS
- * sidecar for a video LoRA.
+ * sidecar for an image or video LoRA.
*
- * Video LoRAs (e.g. fal/ltx2.3-audio-reactive-lora) live on HuggingFace, not
- * Civitai, so the Civitai installer in services/loras.js can't reach them.
- * This module is the HF analogue of server/lib/civitai.js: it parses the ref,
- * hits the public `/api/models/{repo}` endpoint for the file list + card data,
- * picks the LoRA weights file, and shapes a sidecar that listLoras() can read.
+ * Image LoRAs (Flux.2 Klein, Z-Image, …) and video LoRAs (fal/LTX, MiniMax H3)
+ * both live on HuggingFace. Civitai's installer can't reach them. This module
+ * is the HF analogue of server/lib/civitai.js: it parses the ref, hits the
+ * public `/api/models/{repo}` endpoint for the file list + card data, picks
+ * the LoRA weights file, classifies the runner family, and shapes a sidecar
+ * that listLoras() can read.
*
* The download itself reuses services/loras.js#downloadToFile against the HF
* `resolve` URL (with the user's HF token as a bearer header) — no Python
@@ -18,18 +19,27 @@
*/
import { ServerError } from './errorHandler.js';
-import { VIDEO_LORA_FAMILIES } from './runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from './runners.js';
import { readResponseJson } from './readResponseJson.js';
+// Families the HF installer may stamp. Image runners plus video families —
+// the route schema and the family-override validator share this list.
+export const HF_LORA_FAMILIES = Object.freeze([
+ ...Object.values(RUNNER_FAMILIES),
+ ...Object.values(VIDEO_LORA_FAMILIES),
+]);
+
export const HF_API = 'https://huggingface.co/api/models';
const HF_HOSTS = new Set(['huggingface.co', 'www.huggingface.co']);
-// Parse any HuggingFace ref shape into `{ repo, revision }`:
+// Parse any HuggingFace ref shape into `{ repo, revision, file }`:
// https://huggingface.co/fal/ltx2.3-audio-reactive-lora
// https://huggingface.co/fal/ltx2.3-audio-reactive-lora/tree/main
+// https://huggingface.co/org/name/blob/main/weights.safetensors
// fal/ltx2.3-audio-reactive-lora
// fal/[email protected] (or `:v1.0`)
-// `repo` is the `org/name` id; `revision` is a branch/tag/sha or null.
+// `repo` is the `org/name` id; `revision` is a branch/tag/sha or null;
+// `file` is a `.safetensors` path recovered from /blob/ or /resolve/ URLs.
// Throws ServerError on garbage.
export const parseHuggingfaceLoraRef = (raw) => {
if (typeof raw !== 'string' || !raw.trim()) {
@@ -46,7 +56,7 @@ export const parseHuggingfaceLoraRef = (raw) => {
{ status: 400, code: 'HF_BAD_URL' },
);
}
- return { repo: m[1], revision: m[2] || null };
+ return { repo: m[1], revision: m[2] || null, file: null };
}
let parsed;
@@ -66,18 +76,30 @@ export const parseHuggingfaceLoraRef = (raw) => {
);
}
const repo = `${segments[0]}/${segments[1]}`;
- // Recover a revision from `/tree/<rev>/…` or `/blob/<rev>/…` URLs. The URL
- // shape is `…/<tree|blob>/<rev>/<optional subpath>`, and the subpath itself
- // can contain slashes (`/blob/main/weights/lora.safetensors`), so only the
- // FIRST segment after the marker is the revision — joining the rest would
- // mis-read a subdirectory as part of the ref and 404 the metadata fetch. This
- // means a slash-containing branch/ref pasted as a /tree/ URL isn't recovered
+ // Recover a revision from `/tree/<rev>/…`, `/blob/<rev>/…`, or
+ // `/resolve/<rev>/…` URLs. The URL shape is `…/<marker>/<rev>/<optional
+ // subpath>`, and the subpath itself can contain slashes
+ // (`/blob/main/weights/lora.safetensors`), so only the FIRST segment after
+ // the marker is the revision — joining the rest would mis-read a
+ // subdirectory as part of the ref and 404 the metadata fetch. This means a
+ // slash-containing branch/ref pasted as a /tree/ URL isn't recovered
// (genuinely ambiguous from the URL alone) — use the `org/name@refs/pr/123`
// form for those (the bare-ref parser above keeps the full ref).
+ //
+ // When the leftover subpath ends in `.safetensors`, surface it as `file` so
+ // pasting a specific weight URL (CharacterSheet/blob/main/TripleView_*.safetensors)
+ // installs that artifact instead of the repo's auto-picked sibling.
let revision = null;
- const treeIdx = segments.findIndex((s) => s === 'tree' || s === 'blob');
- if (treeIdx >= 0 && segments[treeIdx + 1]) revision = segments[treeIdx + 1];
- return { repo, revision };
+ let file = null;
+ const treeIdx = segments.findIndex((s) => s === 'tree' || s === 'blob' || s === 'resolve');
+ if (treeIdx >= 0 && segments[treeIdx + 1]) {
+ revision = segments[treeIdx + 1];
+ const rest = segments.slice(treeIdx + 2);
+ if (rest.length && /\.safetensors$/i.test(rest[rest.length - 1])) {
+ file = rest.join('/');
+ }
+ }
+ return { repo, revision, file };
};
// Build the bearer header for an optional HF token. Public LoRAs need no auth;
@@ -134,11 +156,37 @@ export const modelSiblingFilenames = (model) => {
const safetensorsSiblings = (model) =>
modelSiblingFilenames(model).filter((f) => /\.safetensors$/i.test(f));
+// A weight file trained for Krea 2 (not a PortOS runner). Repos like
+// Alissonerdx/CharacterSheet ship Klein-9B *and* Krea siblings; the Krea
+// artifact must not be auto-picked (or inherit the repo's flux.2 tags).
+const KREA_FILE_RE = /(?:^|[-_/\s.])krea(?:[\s._-]?2)?(?:[-_/\s.]|$)/i;
+const FLUX2_LORA_RE = /flux[\s._-]?2|flux\.2|klein[\s._-]?[49]b/i;
+
+// '4b' | '9b' | null from a classification blob or filename. `klein9b` /
+// `klein-9b` / `flux.2-klein-9b` all resolve; a bare "4bit" does not.
+export const flux2VariantFromBlob = (blob) => {
+ if (typeof blob !== 'string' || !blob) return null;
+ const m = blob.match(/(?:^|[-_/\s.])(?:klein[\s._-]?)?([49])b(?:[-_/\s.]|$)/i);
+ return m ? `${m[1].toLowerCase()}b` : null;
+};
+
+const fileLooksLikeKrea = (filename) =>
+ KREA_FILE_RE.test(filename) && !FLUX2_LORA_RE.test(filename);
+
+const fileMatchesFlux2Variant = (filename, variant) => {
+ if (fileLooksLikeKrea(filename)) return false;
+ if (variant === '9b') return /klein[\s._-]?9b|(?:^|[-_/])9b(?:[-_./]|$)/i.test(filename);
+ if (variant === '4b') return /klein[\s._-]?4b|(?:^|[-_/])4b(?:[-_./]|$)/i.test(filename);
+ return FLUX2_LORA_RE.test(filename);
+};
+
// Pick the LoRA weights file to download. An explicit file must exactly match a
// .safetensors sibling — this lets curated cards select a versioned artifact
// from repos that publish several LoRAs without accepting an arbitrary path.
-// Without an explicit file, preserve the legacy canonical-name preference.
-export const pickHfLoraFile = (model, preferredFile = null) => {
+// Without an explicit file, prefer a sibling matching `familyHint` (so a
+// Flux.2 Klein 9B card isn't installed as its Krea sibling), then the legacy
+// canonical-name preference.
+export const pickHfLoraFile = (model, preferredFile = null, familyHint = null) => {
const files = safetensorsSiblings(model);
if (!files.length) {
throw new ServerError(
@@ -157,6 +205,10 @@ export const pickHfLoraFile = (model, preferredFile = null) => {
return exact;
}
if (files.length === 1) return files[0];
+ if (familyHint?.family === RUNNER_FAMILIES.FLUX2) {
+ const match = files.find((f) => fileMatchesFlux2Variant(f, familyHint.fluxVariant || null));
+ if (match) return match;
+ }
const canonical = files.find((f) => /(^|\/)pytorch_lora_weights\.safetensors$/i.test(f))
|| files.find((f) => /(^|\/)lora\.safetensors$/i.test(f))
|| files.find((f) => /lora/i.test(f) && !/\//.test(f)) // top-level "*lora*"
@@ -206,6 +258,42 @@ export const detectVideoLoraFamily = ({ repo, model } = {}) => {
return null;
};
+// Image-runner detection for an HF LoRA. Looks at the repo id, tags,
+// cardData.base_model, sibling filenames, and an optional picked file.
+// A picked Krea-2 file does not inherit sibling/repo flux.2 tags — those
+// describe a different artifact in the same collection.
+export const detectImageLoraFamily = ({ repo, model, file } = {}) => {
+ const fileName = typeof file === 'string' ? file : '';
+ if (fileName && fileLooksLikeKrea(fileName)) return null;
+ const siblings = modelSiblingFilenames(model).join(' ');
+ const blob = `${modelClassificationBlob({ repo, model })} ${siblings} ${fileName}`.toLowerCase();
+ // FLUX.2 before FLUX.1 — "flux.2" contains "flux". klein9b is a Flux.2
+ // Klein size marker even when the card omits the word "flux".
+ if (FLUX2_LORA_RE.test(blob)) {
+ return { family: RUNNER_FAMILIES.FLUX2, fluxVariant: flux2VariantFromBlob(blob) };
+ }
+ if (/z[\s._-]?image/.test(blob)) return { family: RUNNER_FAMILIES.Z_IMAGE, fluxVariant: null };
+ if (/ernie/.test(blob)) return { family: RUNNER_FAMILIES.ERNIE, fluxVariant: null };
+ if (/hidream/.test(blob)) return { family: RUNNER_FAMILIES.HIDREAM, fluxVariant: null };
+ if (/qwen[\s._-]?image/.test(blob)) return { family: RUNNER_FAMILIES.QWEN, fluxVariant: null };
+ if (/flux[\s._-]?1|flux\.1|\bflux\b/.test(blob)) {
+ return { family: RUNNER_FAMILIES.MFLUX, fluxVariant: null };
+ }
+ return null;
+};
+
+// Combined image+video classifier. Image wins when both signals exist: cards
+// like Alissonerdx/CharacterSheet tag flux.2-klein-9b and mention LTX only as
+// a downstream identity-reference use case. Returns `{ family, fluxVariant }`
+// or null (unrecognized → the installer surfaces HF_UNKNOWN_FAMILY).
+export const detectHfLoraFamily = ({ repo, model, file } = {}) => {
+ const image = detectImageLoraFamily({ repo, model, file });
+ if (image) return image;
+ const video = detectVideoLoraFamily({ repo, model });
+ if (video) return { family: video, fluxVariant: null };
+ return null;
+};
+
const DESCRIPTION_MAX_CHARS = 2000;
// Read the HF model-card description, clamped to `maxChars`. Shared by the
@@ -222,7 +310,7 @@ export const extractHfCardDescription = (model, maxChars) => {
// block instead of `civitai`, sets `source: 'huggingface'`, and stamps
// `runnerFamily` directly (HF has no Civitai baseModel string for listLoras()
// to re-derive from, so the stored family is authoritative).
-export const buildHfLoraSidecar = ({ repo, revision, file, model, family, filename }) => {
+export const buildHfLoraSidecar = ({ repo, revision, file, model, family, filename, fluxVariant = null }) => {
const tags = Array.isArray(model?.tags) ? model.tags : [];
const baseModelRaw = model?.cardData?.base_model;
const baseModel = typeof baseModelRaw === 'string'
@@ -235,9 +323,20 @@ export const buildHfLoraSidecar = ({ repo, revision, file, model, family, filena
: '';
const description = extractHfCardDescription(model, DESCRIPTION_MAX_CHARS);
const isV2 = /(?:^|[-_.])v2(?:[-_.]|$)/i.test(file);
+ // Multi-file collections (CharacterSheet ships TripleView + QuadView + Krea)
+ // need the file stem in the display name so two installs from the same repo
+ // don't show up as identical cards. Canonical single-file names
+ // (pytorch_lora_weights / lora) stay as the repo name.
+ const repoName = repo.split('/')[1] || repo;
+ const fileStem = typeof file === 'string'
+ ? file.replace(/\.safetensors$/i, '').split('/').pop()
+ : '';
+ const useFileStem = fileStem && !/^(pytorch_lora_weights|lora)$/i.test(fileStem);
+ const baseName = useFileStem ? `${repoName} · ${fileStem}` : repoName;
+ const alreadyV2 = /(?:^|[-_.])v2(?:[-_.]|$)/i.test(baseName);
return {
filename,
- name: `${repo.split('/')[1] || repo}${isV2 ? ' V2' : ''}`,
+ name: `${baseName}${isV2 && !alreadyV2 ? ' V2' : ''}`,
description,
huggingface: {
repo,
@@ -248,7 +347,7 @@ export const buildHfLoraSidecar = ({ repo, revision, file, model, family, filena
tags,
},
runnerFamily: family,
- fluxVariant: null,
+ fluxVariant: family === RUNNER_FAMILIES.FLUX2 ? (fluxVariant || null) : null,
triggerWords: instancePrompt ? [instancePrompt] : [],
recommendedScale: isV2 ? 1.2 : 1.0,
file: {
diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.js
index 6ad6c746d0..cc85d790ae 100644
--- a/server/lib/huggingfaceLora.test.js
+++ b/server/lib/huggingfaceLora.test.js
@@ -5,40 +5,53 @@ import {
buildHfAuthHeaders,
pickHfLoraFile,
detectVideoLoraFamily,
+ detectImageLoraFamily,
+ detectHfLoraFamily,
+ flux2VariantFromBlob,
buildHfLoraSidecar,
fetchHuggingfaceModel,
} from './huggingfaceLora.js';
-import { VIDEO_LORA_FAMILIES } from './runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from './runners.js';
describe('parseHuggingfaceLoraRef', () => {
it('parses a full HF URL', () => {
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/ltx2.3-audio-reactive-lora'))
- .toEqual({ repo: 'fal/ltx2.3-audio-reactive-lora', revision: null });
+ .toEqual({ repo: 'fal/ltx2.3-audio-reactive-lora', revision: null, file: null });
});
it('recovers a revision from /tree/<rev> and /blob/<rev> URLs', () => {
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/tree/v1.0'))
- .toEqual({ repo: 'fal/x', revision: 'v1.0' });
+ .toEqual({ repo: 'fal/x', revision: 'v1.0', file: null });
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/blob/main/lora.safetensors'))
- .toEqual({ repo: 'fal/x', revision: 'main' });
+ .toEqual({ repo: 'fal/x', revision: 'main', file: 'lora.safetensors' });
});
it('takes only the first segment after tree/blob as the revision (subpaths are not part of the ref)', () => {
// The common copy-paste case: a single-segment revision followed by a
// (possibly nested) subpath. Only `main` is the ref; the rest is the path.
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/blob/main/weights/lora.safetensors'))
- .toEqual({ repo: 'fal/x', revision: 'main' });
+ .toEqual({ repo: 'fal/x', revision: 'main', file: 'weights/lora.safetensors' });
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/tree/main/subdir'))
- .toEqual({ repo: 'fal/x', revision: 'main' });
+ .toEqual({ repo: 'fal/x', revision: 'main', file: null });
+ });
+
+ it('recovers a .safetensors path from a /resolve/<rev>/… URL', () => {
+ expect(parseHuggingfaceLoraRef(
+ 'https://huggingface.co/Alissonerdx/CharacterSheet/resolve/main/TripleView_klein9b_v1.safetensors',
+ )).toEqual({
+ repo: 'Alissonerdx/CharacterSheet',
+ revision: 'main',
+ file: 'TripleView_klein9b_v1.safetensors',
+ });
});
it('recovers a slash-containing ref from the org/name@rev form (URL form is ambiguous)', () => {
expect(parseHuggingfaceLoraRef('fal/x@refs/pr/123'))
- .toEqual({ repo: 'fal/x', revision: 'refs/pr/123' });
+ .toEqual({ repo: 'fal/x', revision: 'refs/pr/123', file: null });
});
it('parses a bare org/name id (optionally @rev or :rev)', () => {
- expect(parseHuggingfaceLoraRef('fal/ltx-lora')).toEqual({ repo: 'fal/ltx-lora', revision: null });
- expect(parseHuggingfaceLoraRef('fal/ltx-lora@v2')).toEqual({ repo: 'fal/ltx-lora', revision: 'v2' });
- expect(parseHuggingfaceLoraRef('fal/ltx-lora:abc123')).toEqual({ repo: 'fal/ltx-lora', revision: 'abc123' });
+ expect(parseHuggingfaceLoraRef('fal/ltx-lora')).toEqual({ repo: 'fal/ltx-lora', revision: null, file: null });
+ expect(parseHuggingfaceLoraRef('fal/ltx-lora@v2')).toEqual({ repo: 'fal/ltx-lora', revision: 'v2', file: null });
+ expect(parseHuggingfaceLoraRef('fal/ltx-lora:abc123')).toEqual({ repo: 'fal/ltx-lora', revision: 'abc123', file: null });
});
it('rejects garbage and non-HF hosts', () => {
expect(() => parseHuggingfaceLoraRef('')).toThrow(/Empty/);
@@ -90,6 +103,16 @@ describe('pickHfLoraFile', () => {
it('throws when there is no .safetensors', () => {
expect(() => pickHfLoraFile(m('config.json', 'README.md'))).toThrow(/no .safetensors/);
});
+ it('prefers a Flux.2 Klein 9B sibling over a Krea sibling when hinted', () => {
+ const model = m(
+ 'DynamicCharacterSheet_krea2_v1.safetensors',
+ 'QuadView_klein9b_v1.safetensors',
+ 'QuadView_krea2_v1.safetensors',
+ 'TripleView_klein9b_v1.safetensors',
+ );
+ expect(pickHfLoraFile(model, null, { family: RUNNER_FAMILIES.FLUX2, fluxVariant: '9b' }))
+ .toBe('QuadView_klein9b_v1.safetensors');
+ });
});
describe('detectVideoLoraFamily', () => {
@@ -125,6 +148,70 @@ describe('detectVideoLoraFamily', () => {
});
});
+describe('flux2VariantFromBlob', () => {
+ it('reads klein9b / klein-9b / flux.2-klein-9b', () => {
+ expect(flux2VariantFromBlob('flux.2-klein-9b')).toBe('9b');
+ expect(flux2VariantFromBlob('TripleView_klein9b_v1.safetensors')).toBe('9b');
+ expect(flux2VariantFromBlob('flux2-klein-4b-int8')).toBe('4b');
+ });
+ it('does not treat 4bit as a size variant', () => {
+ expect(flux2VariantFromBlob('model-4bit')).toBe(null);
+ });
+});
+
+describe('detectImageLoraFamily', () => {
+ const characterSheet = {
+ tags: ['lora', 'flux.2', 'flux.2-klein-9b', 'krea-2'],
+ siblings: [
+ { rfilename: 'DynamicCharacterSheet_krea2_v1.safetensors' },
+ { rfilename: 'QuadView_klein9b_v1.safetensors' },
+ { rfilename: 'QuadView_krea2_v1.safetensors' },
+ { rfilename: 'TripleView_klein9b_v1.safetensors' },
+ ],
+ };
+
+ it('classifies Alissonerdx/CharacterSheet as flux2-9b from tags + filenames', () => {
+ expect(detectImageLoraFamily({ repo: 'Alissonerdx/CharacterSheet', model: characterSheet }))
+ .toEqual({ family: RUNNER_FAMILIES.FLUX2, fluxVariant: '9b' });
+ });
+
+ it('does not inherit repo flux.2 tags onto a picked Krea sibling', () => {
+ expect(detectImageLoraFamily({
+ repo: 'Alissonerdx/CharacterSheet',
+ model: characterSheet,
+ file: 'QuadView_krea2_v1.safetensors',
+ })).toBe(null);
+ });
+
+ it('classifies a klein9b filename even without flux tags', () => {
+ expect(detectImageLoraFamily({
+ repo: 'someone/opaque-sheet',
+ model: { tags: ['lora'], siblings: [{ rfilename: 'TripleView_klein9b_v1.safetensors' }] },
+ })).toEqual({ family: RUNNER_FAMILIES.FLUX2, fluxVariant: '9b' });
+ });
+});
+
+describe('detectHfLoraFamily', () => {
+ it('prefers Flux.2 over LTX when a card name-drops LTX as a use case', () => {
+ expect(detectHfLoraFamily({
+ repo: 'Alissonerdx/CharacterSheet',
+ model: {
+ tags: ['lora', 'flux.2-klein-9b'],
+ siblings: [{ rfilename: 'TripleView_klein9b_v1.safetensors' }],
+ },
+ })).toEqual({ family: RUNNER_FAMILIES.FLUX2, fluxVariant: '9b' });
+ });
+
+ it('still classifies a pure LTX video repo as ltx-video', () => {
+ expect(detectHfLoraFamily({ repo: 'fal/ltx2.3-audio-reactive-lora' }))
+ .toEqual({ family: VIDEO_LORA_FAMILIES.LTX_VIDEO, fluxVariant: null });
+ });
+
+ it('returns null for an unsupported image family (SDXL)', () => {
+ expect(detectHfLoraFamily({ repo: 'someone/sdxl-anime-lora', model: { tags: ['sdxl'] } })).toBe(null);
+ });
+});
+
describe('buildHfLoraSidecar', () => {
it('shapes a video-LoRA sidecar with a huggingface block and stamped family', () => {
const sidecar = buildHfLoraSidecar({
@@ -155,9 +242,24 @@ describe('buildHfLoraSidecar', () => {
filename: 'lora-fal-ltx2.3-audio-reactive-lora-v2-hf.safetensors',
model: {},
});
- expect(sidecar.name).toBe('ltx2.3-audio-reactive-lora V2');
+ expect(sidecar.name).toBe('ltx2.3-audio-reactive-lora · ltx2.3_audio_reactive_lora_v2');
expect(sidecar.recommendedScale).toBe(1.2);
});
+
+ it('stamps fluxVariant and a file-stem name for a Flux.2 Klein collection', () => {
+ const sidecar = buildHfLoraSidecar({
+ repo: 'Alissonerdx/CharacterSheet',
+ revision: null,
+ file: 'QuadView_klein9b_v1.safetensors',
+ family: RUNNER_FAMILIES.FLUX2,
+ fluxVariant: '9b',
+ filename: 'lora-alissonerdx-charactersheet-quadview-klein9b-v1-hf.safetensors',
+ model: { tags: ['flux.2-klein-9b'] },
+ });
+ expect(sidecar.runnerFamily).toBe('flux2');
+ expect(sidecar.fluxVariant).toBe('9b');
+ expect(sidecar.name).toBe('CharacterSheet · QuadView_klein9b_v1');
+ });
});
describe('fetchHuggingfaceModel', () => {
diff --git a/server/lib/huggingfaceModel.js b/server/lib/huggingfaceModel.js
index 0e6c35681b..7ada630a4c 100644
--- a/server/lib/huggingfaceModel.js
+++ b/server/lib/huggingfaceModel.js
@@ -153,7 +153,7 @@ export const inspectModelFiles = (model) => {
// A repo is a LoRA ADAPTER (not a base model) when its id/tags carry a LoRA
// marker or it's a PEFT/adapter package. The base-model installer must refuse
-// these — a LoRA has the video LoRA installer (/api/loras/install/huggingface)
+// these — a LoRA has the LoRA installer (/api/loras/install/huggingface)
// and would otherwise register as a bogus base entry the render path can't load.
//
// Deliberately does NOT key on `cardData.base_model` alone: full fine-tunes and
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 9eeb545dde..9449c6157b 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -24,7 +24,8 @@ import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggesti
import { getVideoSuggestions } from '../services/videoLoraSuggestions.js';
import { findLorasByCharacter } from '../services/characterLoraResolver.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
-import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from '../lib/runners.js';
+import { RUNNER_FAMILIES } from '../lib/runners.js';
+import { HF_LORA_FAMILIES } from '../lib/huggingfaceLora.js';
import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -134,11 +135,12 @@ router.post('/install', asyncHandler(async (req, res) => {
res.status(201).json(sidecar);
}));
-// Install a video LoRA from a HuggingFace repo (fal / Lightricks LTX LoRAs).
-// `family` is an optional override; absence auto-detects from the repo.
+// Install an image or video LoRA from a HuggingFace repo (Flux.2 Klein,
+// fal / Lightricks LTX, MiniMax H3). `family` is an optional override;
+// absence auto-detects from the repo id / tags / filenames.
const hfInstallSchema = z.object({
url: z.string().min(1).max(1024),
- family: z.enum(Object.values(VIDEO_LORA_FAMILIES)).optional(),
+ family: z.enum(HF_LORA_FAMILIES).optional(),
file: z.string().min(1).max(512).regex(/\.safetensors$/i).optional(),
// One-shot token override; absence falls back to the stored/env/CLI HF token.
token: z.string().min(1).max(256).optional(),
@@ -163,7 +165,7 @@ router.post('/install/huggingface', asyncHandler(async (req, res) => {
// retry, exactly as the plain POST path's thrown error does.
const hfInstallStreamSchema = z.object({
url: z.string().min(1).max(1024),
- family: z.enum(Object.values(VIDEO_LORA_FAMILIES)).optional(),
+ family: z.enum(HF_LORA_FAMILIES).optional(),
file: z.string().min(1).max(512).regex(/\.safetensors$/i).optional(),
});
router.post('/install/huggingface/stream', asyncHandler(async (req, res) => {
diff --git a/server/routes/loras.test.js b/server/routes/loras.test.js
index 799569590a..d7ef4f9fe2 100644
--- a/server/routes/loras.test.js
+++ b/server/routes/loras.test.js
@@ -123,6 +123,17 @@ describe('POST /api/loras/install/huggingface/stream', () => {
expect(res.status).toBe(400);
});
+ it('accepts an image-family override (flux2) on the stream path', async () => {
+ const res = await request(makeApp())
+ .post('/api/loras/install/huggingface/stream')
+ .send({ url: 'Alissonerdx/CharacterSheet', family: 'flux2' });
+ expect(res.status).toBe(200);
+ expect(installFromHuggingface).toHaveBeenCalledWith(
+ expect.objectContaining({ url: 'Alissonerdx/CharacterSheet', family: 'flux2' }),
+ expect.objectContaining({ onProgress: expect.any(Function) }),
+ );
+ });
+
it('rejects a requested file that is not safetensors before opening the stream', async () => {
const res = await request(makeApp())
.post('/api/loras/install/huggingface/stream')
diff --git a/server/services/loras.js b/server/services/loras.js
index 4f77c503d2..e6cd3d1aff 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -46,12 +46,13 @@ import {
buildHfAuthHeaders,
buildHfLoraSidecar,
buildHfResolveUrl,
- detectVideoLoraFamily,
+ detectHfLoraFamily,
fetchHuggingfaceModel,
+ HF_LORA_FAMILIES,
parseHuggingfaceLoraRef,
pickHfLoraFile,
} from '../lib/huggingfaceLora.js';
-import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, composeCompatKey } from '../lib/runners.js';
+import { RUNNER_FAMILIES, composeCompatKey } from '../lib/runners.js';
import {
classifyLoraKeyLayout,
classifyLoraKeyLayoutFromHeader,
@@ -537,23 +538,24 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
return sidecar;
};
-// Set of recognized video-LoRA families an HF import may target. Used to
-// validate a user-supplied `family` override before trusting it.
-const VIDEO_LORA_FAMILY_VALUES = new Set(Object.values(VIDEO_LORA_FAMILIES));
+// Set of recognized LoRA families an HF import may target (image runners +
+// video families). Used to validate a user-supplied `family` override.
+const HF_LORA_FAMILY_VALUES = new Set(HF_LORA_FAMILIES);
-// Install a video LoRA from a HuggingFace repo (e.g.
-// fal/ltx2.3-audio-reactive-lora). Mirrors installFromCivitai: parse the ref →
-// fetch repo metadata → pick the .safetensors → stream-download → write the
-// sidecar. The family is auto-detected from the repo id / tags / base_model,
-// or taken from an explicit `input.family` override (validated against the
-// known video families). Returns the new sidecar JSON.
+// Install a LoRA from a HuggingFace repo (Flux.2 Klein image adapters, fal /
+// Lightricks LTX video LoRAs, MiniMax H3). Mirrors installFromCivitai: parse
+// the ref → fetch repo metadata → pick the .safetensors → stream-download →
+// write the sidecar. The family is auto-detected from the repo id / tags /
+// base_model / filenames, or taken from an explicit `input.family` override
+// (validated against the known image + video families). Returns the new sidecar.
export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgress = null, signal = null } = {}) => {
- const { repo, revision } = parseHuggingfaceLoraRef(input?.url);
+ const { repo, revision, file: parsedFile } = parseHuggingfaceLoraRef(input?.url);
// Stored/env/CLI HF token — only needed for gated repos, but harmless to
// send on public ones (HF ignores a bearer it doesn't require).
const token = (typeof input?.token === 'string' && input.token.trim()) || (await getHfToken()) || '';
const model = await fetchHuggingfaceModel(repo, { token, revision, fetchImpl });
- const file = pickHfLoraFile(model, input?.file || null);
+ const preferredFile = input?.file || parsedFile || null;
+ const detected = detectHfLoraFamily({ repo, model, file: preferredFile });
// Family: explicit override (validated) wins over autodetection so a user
// can correct a mis-detected repo from the UI. An unrecognized repo with no
@@ -561,35 +563,47 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
// would surface under a model it can't actually load against.
let family = null;
if (input?.family) {
- if (!VIDEO_LORA_FAMILY_VALUES.has(input.family)) {
+ if (!HF_LORA_FAMILY_VALUES.has(input.family)) {
throw new ServerError(
- `Unknown video LoRA family "${input.family}" — expected one of ${[...VIDEO_LORA_FAMILY_VALUES].join(', ')}`,
+ `Unknown LoRA family "${input.family}" — expected one of ${[...HF_LORA_FAMILY_VALUES].join(', ')}`,
{ status: 400, code: 'HF_BAD_FAMILY' },
);
}
family = input.family;
} else {
- family = detectVideoLoraFamily({ repo, model });
+ family = detected?.family || null;
}
if (!family) {
throw new ServerError(
- `Couldn't determine a supported video model for HuggingFace repo "${repo}". Only LTX-Video LoRAs are supported today — pass an explicit family if you know this LoRA targets LTX-2.`,
+ `Couldn't determine a supported model for HuggingFace repo "${repo}". PortOS can install Flux 2, Flux 1, Z-Image, ERNIE, HiDream, Qwen, LTX-Video, and MiniMax H3 LoRAs — pass an explicit family if you know which one this targets.`,
{ status: 422, code: 'HF_UNKNOWN_FAMILY' },
);
}
+ const file = pickHfLoraFile(
+ model,
+ preferredFile,
+ { family, fluxVariant: family === RUNNER_FAMILIES.FLUX2 ? (detected?.fluxVariant || null) : null },
+ );
+ const refined = preferredFile ? detected : detectHfLoraFamily({ repo, model, file });
+ const fluxVariant = family === RUNNER_FAMILIES.FLUX2
+ ? (refined?.fluxVariant || detected?.fluxVariant || null)
+ : null;
+
// Stable filename: `lora-<org>-<name>[-<file-variant>]-hf.safetensors`.
- // No explicit file preserves the original filename contract. A versioned
- // file from the same repo (for example `_v2`) gets a distinct suffix so both
- // artifacts can coexist and projects can pin either one.
+ // Canonical single-file names (pytorch_lora_weights / lora) keep the original
+ // repo-only contract. Any other stem (CharacterSheet's QuadView_klein9b_v1,
+ // a `_v2` artifact) gets a distinct suffix so siblings can coexist.
const slug = slugifyForFilename(repo.replace('/', '-'));
const repoNameSlug = slugifyForFilename((repo.split('/')[1] || repo).replace(/_/g, '-'));
- const fileStemSlug = slugifyForFilename(file.replace(/\.safetensors$/i, '').split('/').pop().replace(/_/g, '-'));
- const explicitVariant = input?.file
- ? (fileStemSlug.startsWith(`${repoNameSlug}-`)
+ const pickedStem = file.replace(/\.safetensors$/i, '').split('/').pop();
+ const fileStemSlug = slugifyForFilename(pickedStem.replace(/_/g, '-'));
+ const isCanonicalStem = /^(pytorch_lora_weights|lora)$/i.test(pickedStem);
+ const explicitVariant = isCanonicalStem
+ ? ''
+ : (fileStemSlug.startsWith(`${repoNameSlug}-`)
? fileStemSlug.slice(repoNameSlug.length + 1)
- : (fileStemSlug === repoNameSlug ? '' : fileStemSlug))
- : '';
+ : (fileStemSlug === repoNameSlug ? '' : fileStemSlug));
const filename = `lora-${slug}${explicitVariant ? `-${explicitVariant}` : ''}-hf.safetensors`;
const destPath = join(PATHS.loras, filename);
if (existsSync(destPath)) {
@@ -615,7 +629,7 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
await verifyDownloadedLora(destPath, { source: 'huggingface' });
const sidecar = await withKeyLayout(
- buildHfLoraSidecar({ repo, revision, file, model, family, filename }),
+ buildHfLoraSidecar({ repo, revision, file, model, family, filename, fluxVariant }),
destPath,
);
await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 2a5ec05c6b..11e5227096 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -531,11 +531,11 @@ describe('installFromHuggingface', () => {
);
expect(sidecar.filename).toBe('lora-fal-ltx2.3-audio-reactive-lora-v2-hf.safetensors');
expect(sidecar.huggingface.file).toBe('ltx2.3_audio_reactive_lora_v2.safetensors');
- expect(sidecar.name).toMatch(/V2$/);
+ expect(sidecar.name).toBe('ltx2.3-audio-reactive-lora · ltx2.3_audio_reactive_lora_v2');
expect(sidecar.recommendedScale).toBe(1.2);
});
- it('refuses a repo it cannot classify as a supported video family', async () => {
+ it('refuses a repo it cannot classify as a supported family', async () => {
const fetchImpl = async (url) => {
if (url.startsWith('https://huggingface.co/api/models/')) {
return mockJsonResponse({ id: 'someone/sdxl-lora', tags: ['sdxl'], siblings: [{ rfilename: 'lora.safetensors' }] });
@@ -622,6 +622,74 @@ describe('installFromHuggingface', () => {
expect(sawSignal).toBe(controller.signal);
});
+ it('installs a Flux.2 Klein 9B collection as flux2 and picks the klein9b file', async () => {
+ const characterSheet = {
+ id: 'Alissonerdx/CharacterSheet',
+ tags: ['lora', 'flux.2', 'flux.2-klein-9b', 'krea-2'],
+ siblings: [
+ { rfilename: 'DynamicCharacterSheet_krea2_v1.safetensors' },
+ { rfilename: 'QuadView_klein9b_v1.safetensors' },
+ { rfilename: 'QuadView_krea2_v1.safetensors' },
+ { rfilename: 'TripleView_klein9b_v1.safetensors' },
+ ],
+ };
+ const calls = [];
+ const fetchImpl = async (url) => {
+ calls.push(url);
+ if (url.startsWith('https://huggingface.co/api/models/Alissonerdx/CharacterSheet')) {
+ return mockJsonResponse(characterSheet);
+ }
+ if (url.includes('/resolve/main/QuadView_klein9b_v1.safetensors')) {
+ const stream = new ReadableStream({
+ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); },
+ });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const sidecar = await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/Alissonerdx/CharacterSheet' },
+ { fetchImpl },
+ );
+ expect(sidecar.runnerFamily).toBe('flux2');
+ expect(sidecar.fluxVariant).toBe('9b');
+ expect(sidecar.huggingface.file).toBe('QuadView_klein9b_v1.safetensors');
+ expect(sidecar.filename).toBe('lora-alissonerdx-charactersheet-quadview-klein9b-v1-hf.safetensors');
+ expect(sidecar.name).toContain('QuadView_klein9b_v1');
+ expect(calls.some((u) => u.includes('QuadView_klein9b_v1.safetensors'))).toBe(true);
+ expect(calls.some((u) => u.includes('krea2'))).toBe(false);
+ });
+
+ it('installs a specific Klein 9B file when the pasted URL points at it', async () => {
+ const characterSheet = {
+ id: 'Alissonerdx/CharacterSheet',
+ tags: ['lora', 'flux.2-klein-9b'],
+ siblings: [
+ { rfilename: 'QuadView_klein9b_v1.safetensors' },
+ { rfilename: 'TripleView_klein9b_v1.safetensors' },
+ ],
+ };
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://huggingface.co/api/models/Alissonerdx/CharacterSheet')) {
+ return mockJsonResponse(characterSheet);
+ }
+ if (url.includes('/resolve/main/TripleView_klein9b_v1.safetensors')) {
+ const stream = new ReadableStream({
+ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); },
+ });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const sidecar = await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/Alissonerdx/CharacterSheet/blob/main/TripleView_klein9b_v1.safetensors' },
+ { fetchImpl },
+ );
+ expect(sidecar.huggingface.file).toBe('TripleView_klein9b_v1.safetensors');
+ expect(sidecar.runnerFamily).toBe('flux2');
+ expect(sidecar.fluxVariant).toBe('9b');
+ });
+
it('accepts an explicit family override', async () => {
const fetchImpl = async (url) => {
if (url.startsWith('https://huggingface.co/api/models/')) {