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

add video LoRA support: HuggingFace import + fuse LoRAs into the ltx2 runtime

[._.]/ Adam Eivyf1f6cd22b048
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index be33e131ff..073de089e6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **Character LoRA training — train consistent character adapters from your universe canon** — Create → Media Gen gains a **Training** tab (`/media/training`) that closes the loop from "character exists in a universe" to "every render of that character looks the same." Per character, a **dataset workbench** builds reference material three ways: batch-generate single-subject training renders from the character's canon descriptors (deterministic view/pose/expression/outfit variation matrix, queued through the normal image lane), upload your own images (normalized to PNG via sharp), or slice the character's existing reference-sheet turnaround into grid crops. A **vision-LLM captioner** (same provider pathway as the voice agent's visual describe) auto-captions every image prefixed with the character's trigger word, with per-image caption editing and re-captioning. Once ≥10 captioned images are ready, **train a FLUX.2 Klein LoRA locally** through one of two engines, picked automatically: mflux's MLX-native trainer (`mflux-train`, mflux ≥0.17 — wrapped by `scripts/train_mflux_lora.py`, preferred on Apple Silicon; the dataset stages in mflux's `NNNN.png`+`NNNN.txt` auto-discovery layout, and quantize/low-ram knobs derive from total RAM so a 48 GB machine trains QLoRA-style instead of OOMing) or a vendored torch/diffusers+peft trainer (`scripts/train_flux2_lora.py` — bf16 bases only, precompute-then-free text/VAE encoding, gradient checkpointing) as the fallback. Either engine exports diffusers-format adapters. Training runs ride the media-job GPU lane (serialized with renders, SSE progress with per-step loss, mid-training sample previews, 30-min idle watchdog, cancel saves a checkpoint). The finished adapter lands in `data/loras/` with a sidecar carrying the character link + trigger word + size-variant compat key (`flux2-4b`/`flux2-9b`), so it appears in the existing LoRA library and picker with the right base-model gating immediately. **Auto-apply:** pipeline comic-page and storyboard renders that match a character with a trained LoRA automatically attach the adapter and weave its trigger word into the prompt (local mode; per-stage opt-out in Generation settings). Character cards in the universe editor and catalog detail pages show a trained-LoRA chip + dataset entry point; trained LoRAs in the library link back to their dataset. Datasets are machine-local (like the LoRA files themselves — never federated) and fully backed up; training checkpoints/caches are excluded as regenerable. Run records live in PostgreSQL (`lora_training_runs`). (`server/services/loraTraining/`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraDatasetCaption.js`, `server/services/characterLoraResolver.js`, `client/src/pages/LoraTraining.jsx`, `client/src/pages/LoraDatasetDetail.jsx`)
+- **Video LoRAs — install LTX-2 LoRAs from HuggingFace and fuse them into Video Gen renders** — LoRA support now extends past image models to the **dgrauet `ltx2` video runtime**. A new **"Install video LoRA from HuggingFace"** box on the LoRA Manager (`/media/loras`) takes any HF repo URL or `org/name` id (e.g. `fal/ltx2.3-audio-reactive-lora`), fetches the repo metadata, picks the `.safetensors`, auto-detects the video family from the repo id / tags / `base_model` (LTX-Video → `ltx-video`), and writes a sidecar — the HuggingFace analogue of the existing Civitai installer (gated repos use your HuggingFace token from Image Gen settings). Video Gen (`/media/video`) gains a **LoRA picker** that appears only on an LTX-2 (`ltx2`) model, filtered to the `ltx-video` family, with per-LoRA strength and a trigger-word append button — the same component the Image Gen page uses. Selected LoRAs fuse into the transformer via the pipeline's `_pending_loras` hook (the exact mechanism upstream's `ltx-2-mlx generate --lora` CLI uses), so they apply across **every** mode — text, image, FFLF, extend, and audio-to-video — including multi-chunk chains. Applied LoRAs are stamped into the video-history entry and round-trip through the resume/Remix flow. Only the `ltx2` runtime can fuse LoRAs today; the route and service reject LoRAs on the legacy `mlx_video` / `wan22` / `hunyuan` runtimes with a clear error. (`server/lib/huggingfaceLora.js`, `server/services/loras.js`, `server/routes/loras.js`, `server/services/videoGen/local.js`, `server/routes/videoGen.js`, `scripts/generate_ltx2.py`, `server/lib/runners.js`, `client/src/lib/runnerFamilies.js`, `client/src/pages/VideoGen.jsx`, `client/src/pages/Loras.jsx`)
+
## Changed
- **CoS system jobs can now pin their own AI provider + model** — Each autonomous "System Task" (Chief of Staff → Jobs) gains an optional **AI Provider & Model** picker in its create and edit forms, so a heavy refactor job can run on Opus while a lightweight triage job runs on a cheaper/local model — independently, per job, instead of every job inheriting the single active provider. The override is forwarded into the generated task's metadata on both the scheduled and manual-trigger paths, where the agent runner already honors `metadata.provider`/`metadata.model`. Leaving the picker on its defaults preserves the prior behavior (active provider, per-task model selection). Only AI-agent jobs show the picker; shell/script jobs never reach the AI runner. A pinned provider is now resolved *before* the active-provider availability gate, so a job pinned to a healthy provider runs even when the globally active provider is down or unset. (`client/src/components/cos/tabs/JobsTab.jsx`, `server/services/autonomousJobs/crud.js`, `server/services/autonomousJobs/skillTemplates.js`, `server/services/agentProviderResolution.js`, `server/routes/cosJobRoutes.js`, `server/lib/validation.js`)
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
index fd4bbb7396..e80e47b1cc 100644
--- a/client/src/lib/runnerFamilies.js
+++ b/client/src/lib/runnerFamilies.js
@@ -12,6 +12,20 @@ export const RUNNER_FAMILIES = Object.freeze({
QWEN: 'qwen',
});
+// Video-LoRA families — kept separate from the image RUNNER_FAMILIES so the
+// Civitai iteration (which only knows image baseModels) never sees them. Video
+// LoRAs are imported from HuggingFace. Mirror of server/lib/runners.js.
+export const VIDEO_LORA_FAMILIES = Object.freeze({
+ LTX_VIDEO: 'ltx-video',
+});
+
+// Map a video model (carries `runtime`, not `runner`) to its LoRA family. Only
+// the dgrauet `ltx2` runtime fuses arbitrary user LoRAs today; everything else
+// returns null so the VideoGen picker hides itself. Mirror of
+// server/lib/runners.js#videoLoraFamily.
+export const videoLoraFamily = (model) =>
+ model?.runtime === 'ltx2' ? VIDEO_LORA_FAMILIES.LTX_VIDEO : null;
+
// FLUX.2 Klein ships in two sizes with different transformer hidden dims (4B =
// 3072, 9B = 4096), so a LoRA trained for one can't load on the other. The
// size is encoded in the model id/repo. Returns '4b' | '9b' | null. Mirror of
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 9bce9cb78c..4c48a5ee3a 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -18,6 +18,7 @@ import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
import {
listLorasFull,
installLoraFromCivitai,
+ installLoraFromHuggingface,
deleteLoraFull,
getCivitaiAuth,
setCivitaiAuth,
@@ -56,6 +57,10 @@ 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.
+ const [hfUrl, setHfUrl] = useState('');
+ const [hfInstalling, setHfInstalling] = useState(false);
const [deleting, setDeleting] = useState(null);
// Civitai auth — `auth` is `{ hasKey, source }`; `authPrompt` is set to a
// pending install URL when a 401/403 redirects the user to the inline key
@@ -124,6 +129,24 @@ 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.
+ const handleHfInstall = useCallback(async (e) => {
+ e?.preventDefault?.();
+ const url = hfUrl.trim();
+ if (!url || hfInstalling) return;
+ setHfInstalling(true);
+ await installLoraFromHuggingface({ url, silent: true })
+ .then((sidecar) => {
+ toast.success(`Installed ${sidecar.name}`);
+ setHfUrl('');
+ refresh();
+ })
+ .catch((err) => toast.error(err?.message || 'HuggingFace install failed'))
+ .finally(() => setHfInstalling(false));
+ }, [hfUrl, hfInstalling, refresh]);
+
const handleDelete = async (filename) => {
setDeleting(filename);
await deleteLoraFull(filename)
@@ -140,7 +163,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 and apply them to your Image Gen renders.
+ Install LoRA fine-tunes from Civitai (image) or HuggingFace (video) and apply them to your Image Gen and Video Gen renders.
</p>
</div>
@@ -180,6 +203,39 @@ export default function Loras() {
</p>
</form>
+ <form
+ onSubmit={handleHfInstall}
+ className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"
+ >
+ <div className="flex items-center gap-2 text-sm font-medium text-gray-300">
+ <Download size={16} />
+ <span>Install video LoRA from HuggingFace</span>
+ </div>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={hfUrl}
+ onChange={(e) => setHfUrl(e.target.value)}
+ placeholder="https://huggingface.co/fal/ltx2.3-audio-reactive-lora"
+ 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}
+ />
+ <button
+ type="submit"
+ disabled={hfInstalling || !hfUrl.trim()}
+ className="bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
+ >
+ {hfInstalling ? 'Downloading…' : 'Install'}
+ </button>
+ </div>
+ <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.
+ </p>
+ </form>
+
{authPrompt && (
<CivitaiAuthModal
pendingUrl={authPrompt.url}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 020082697e..9e3d2f1c3e 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -62,7 +62,10 @@ import {
listImageGallery,
getSettings, patchSettingsSlice,
getActiveVideoJob,
+ listLorasFull,
} from '../services/api';
+import LoraPicker from '../components/imageGen/LoraPicker';
+import { videoLoraFamily } from '../lib/runnerFamilies';
import { randomSeed } from '../lib/genUtils';
import { VIDEO_RESOLUTIONS } from '../lib/videoGenResolutions';
import { VIDEO_TILING_OPTIONS, VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';
@@ -159,6 +162,11 @@ export default function VideoGen() {
const [seed, setSeed] = useState('');
const [tiling, setTiling] = useState('auto');
const [disableAudio, setDisableAudio] = useState(false);
+ // Video LoRAs (ltx2 runtime only) — `{ filename, name, scale }` entries the
+ // LoraPicker owns; `availableLoras` is the full installed library filtered
+ // by the picker to the model's video family. See videoLoraFamily().
+ const [availableLoras, setAvailableLoras] = useState([]);
+ const [selectedLoras, setSelectedLoras] = useState([]);
// "No music" appends a soundscape constraint at submit time. LTX-2
// conditions audio on prompt text — adding "no music, no soundtrack"
// pushes the model toward ambient/diegetic sound (footsteps, room tone)
@@ -300,6 +308,9 @@ export default function VideoGen() {
useMediaCompletionRefresh({ onVideoCompleted: refreshHistory });
useEffect(() => { refreshHistory(); }, [refreshHistory]);
useEffect(() => { listImageGallery().then(setImageGallery).catch(() => {}); }, []);
+ // Installed LoRA library — the picker filters this to the current model's
+ // video family (ltx-video). Silent: a failure just hides the picker.
+ useEffect(() => { listLorasFull().then((l) => setAvailableLoras(Array.isArray(l) ? l : [])).catch(() => {}); }, []);
const { visibleHistory, hiddenHistory } = useMemo(() => ({
visibleHistory: history.filter((v) => !v.hidden),
@@ -562,6 +573,16 @@ export default function VideoGen() {
setKeyframes(p.keyframes.map((kf) => ({ file: kf.file, index: kf.index })));
setKeyframesMode(true);
}
+ // Restore the LoRA picker — params carry { filename, scale } basenames;
+ // resolve the display name from the loaded library (falls back to the
+ // filename if the library hasn't loaded yet or the LoRA was deleted).
+ if (Array.isArray(p.loras) && p.loras.length) {
+ setSelectedLoras(p.loras.map((l) => ({
+ filename: l.filename,
+ name: availableLoras.find((a) => a.filename === l.filename)?.name || l.filename,
+ scale: typeof l.scale === 'number' ? l.scale : 1.0,
+ })));
+ }
setGenerating(true);
// Skip a forced setProgress(0) here — attachJobEvents will replay the
// server's last SSE payload synchronously after EventSource open, and
@@ -652,6 +673,12 @@ export default function VideoGen() {
const currentModel = models.find((m) => m.id === modelId);
+ // Video-LoRA family for the selected model — 'ltx-video' on ltx2, else null.
+ // When null the picker is hidden and no LoRAs ride along on submit (the
+ // route would 400 with LORAS_REQUIRE_LTX2). Derived, not state, so it tracks
+ // the model dropdown without an effect.
+ const loraFamily = videoLoraFamily(currentModel);
+
// Multi-keyframe availability + validation. Keyframes are an ltx2-runtime
// primitive (the route 400s with KEYFRAMES_REQUIRE_LTX2 otherwise), so the
// picker only offers itself when the selected model runs on ltx2. Mirror
@@ -943,6 +970,14 @@ export default function VideoGen() {
// arrays element-by-element); the route's zod preprocess JSON-parses it
// and strips any unknown keys, so sending the entries verbatim is safe.
keyframes: keyframesActive ? JSON.stringify(keyframes) : '',
+ // Video LoRAs (ltx2 only) ride as a JSON string of { filename, scale } —
+ // same single-string-field trick as keyframes (buildFormData would
+ // otherwise stringify each entry to "[object Object]"). Only included
+ // when the model's runtime actually supports LoRAs; otherwise the route
+ // would 400 with LORAS_REQUIRE_LTX2.
+ loras: (loraFamily && selectedLoras.length)
+ ? JSON.stringify(selectedLoras.map((l) => ({ filename: l.filename, scale: l.scale })))
+ : '',
sourceImageFile: (mode === 'image' || legacyFflf
|| (mode === 'extend' && currentModel?.runtime !== 'ltx2'))
? (sourceImageFile || '') : '',
@@ -1413,6 +1448,26 @@ export default function VideoGen() {
</div>
)}
+ {/* Video LoRAs — only on ltx2-runtime models (loraFamily non-null).
+ The picker filters availableLoras to the model's video family
+ and hides itself when none are compatible. */}
+ {loraFamily && (
+ <div className="col-span-2 sm:col-span-3">
+ <LoraPicker
+ availableLoras={availableLoras}
+ selected={selectedLoras}
+ onChange={setSelectedLoras}
+ currentRunnerFamily={loraFamily}
+ currentCompatKey={loraFamily}
+ onAppendTrigger={(triggers) => setPrompt((p) => {
+ const add = triggers.join(', ');
+ return p && p.trim() ? `${p}, ${add}` : add;
+ })}
+ disabled={generating}
+ />
+ </div>
+ )}
+
<div>
<label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label>
<select
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index a698c5cc0d..87dc109bd3 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -202,6 +202,16 @@ 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.
+export const installLoraFromHuggingface = ({ url, family, silent = false } = {}) => request('/loras/install/huggingface', {
+ method: 'POST',
+ body: JSON.stringify(family ? { url, family } : { url }),
+ silent,
+});
+
// Civitai LoRA suggestions per runner family. Cached server-side for 1h.
// Pass `force: true` to bust the cache and re-fetch from Civitai.
export const getCivitaiSuggestions = ({ force = false } = {}) =>
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 9b61850ba2..f198d25e83 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -331,6 +331,13 @@ def parse_args() -> argparse.Namespace:
"ltx-2.3-22b-distilled-lora-384.safetensors.")
p.add_argument("--lora-strength", type=float, default=1.0,
help="Distilled-LoRA fusion strength (default 1.0, matches dgrauet's CLI).")
+ p.add_argument("--user-loras", default=None,
+ help="JSON list of {path, strength} dicts — user LoRAs (e.g. a "
+ "fal LTX-2.3 LoRA) fused into the transformer via the pipeline's "
+ "_pending_loras hook, the same mechanism upstream's "
+ "`ltx-2-mlx generate --lora <path> <strength>` uses. Works across "
+ "all modes (text/image/fflf/extend/a2v) because every pipeline "
+ "loads its DiT through _load_transformer_with_optional_streaming.")
p.add_argument("--image", default=None, help="Source/start frame (image, fflf modes)")
p.add_argument("--last-image", default=None, help="End frame (fflf mode)")
p.add_argument("--keyframes-json", default=None,
@@ -358,6 +365,58 @@ def parse_args() -> argparse.Namespace:
return p.parse_args()
+def _parse_user_loras(raw: str | None) -> list[tuple[str, float]]:
+ """Parse --user-loras JSON into a list of (path, strength) tuples.
+
+ Validation is strict so a Node-side bug surfaces here before any GPU work.
+ Each entry must be {path: str (existing file), strength: number}. Returns
+ [] when --user-loras is unset.
+ """
+ if not raw:
+ return []
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError as e:
+ raise SystemExit(f"--user-loras is not valid JSON: {e}")
+ if not isinstance(data, list):
+ raise SystemExit("--user-loras must be a JSON list of {path, strength}")
+ specs: list[tuple[str, float]] = []
+ for i, item in enumerate(data):
+ if not isinstance(item, dict) or "path" not in item:
+ raise SystemExit(f"user-loras[{i}] must be an object with 'path'")
+ path = item["path"]
+ if not isinstance(path, str) or not path:
+ raise SystemExit(f"user-loras[{i}].path must be a non-empty string")
+ if not Path(path).exists():
+ raise SystemExit(f"user-loras[{i}].path does not exist: {path}")
+ strength = item.get("strength", 1.0)
+ try:
+ strength = float(strength)
+ except (TypeError, ValueError):
+ raise SystemExit(f"user-loras[{i}].strength must be a number")
+ specs.append((path, strength))
+ return specs
+
+
+def _apply_user_loras(pipe, specs: list[tuple[str, float]]) -> None:
+ """Set the pipeline's _pending_loras hook so user-LoRA deltas fuse into the
+ transformer at load time.
+
+ The DiT loads lazily inside generate_and_save (via
+ _load_transformer_with_optional_streaming, which reads _pending_loras and
+ fuses the deltas before quantization), so setting it on the constructed
+ pipe — before the generate call — is sufficient. This is the exact
+ mechanism the upstream `ltx-2-mlx generate --lora` CLI uses, and it works
+ across every mode because all pipelines route DiT construction through that
+ one method. No-op when no user LoRAs were requested.
+ """
+ if not specs:
+ return
+ pipe._pending_loras = list(specs)
+ names = ", ".join(f"{Path(p).name}@{s:g}" for p, s in specs)
+ emit_status(f"Fusing {len(specs)} user LoRA(s): {names}")
+
+
def bind_output_fps(pipe, fps: float) -> None:
"""Make pipeline _decode_and_save_video() calls decode at the requested rate.
@@ -486,6 +545,7 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:
distilled_lora=args.distilled_lora or "ltx-2.3-22b-distilled-lora-384.safetensors",
distilled_lora_strength=args.lora_strength,
)
+ _apply_user_loras(pipe, args.user_lora_specs)
bind_output_fps(pipe, args.fps)
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating with CFG…")
@@ -511,6 +571,7 @@ def run_text(args: argparse.Namespace) -> str:
emit_status(f"Loading T2V pipeline ({args.model})…")
emit_stage(1, 0, 1, "Loading model")
pipe = OneStagePipeline(model_dir=args.model, gemma_model_id=args.gemma)
+ _apply_user_loras(pipe, args.user_lora_specs)
bind_output_fps(pipe, args.fps)
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating T2V…")
@@ -532,6 +593,7 @@ def run_image(args: argparse.Namespace) -> str:
emit_status(f"Loading I2V pipeline ({args.model})…")
emit_stage(1, 0, 1, "Loading model")
pipe = OneStagePipeline(model_dir=args.model, gemma_model_id=args.gemma)
+ _apply_user_loras(pipe, args.user_lora_specs)
bind_output_fps(pipe, args.fps)
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating I2V…")
@@ -619,6 +681,7 @@ def run_fflf(args: argparse.Namespace) -> str:
distilled_lora=distilled_lora,
distilled_lora_strength=args.lora_strength,
)
+ _apply_user_loras(pipe, args.user_lora_specs)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Interpolating between {len(keyframe_images)} keyframes at indices {keyframe_indices}…")
return pipe.generate_and_save(
@@ -656,6 +719,7 @@ def run_extend(args: argparse.Namespace) -> str:
emit_status(f"Loading Extend pipeline ({args.model})…")
emit_stage(1, 0, 1, "Loading model")
pipe = ExtendPipeline(model_dir=args.model, gemma_model_id=args.gemma)
+ _apply_user_loras(pipe, args.user_lora_specs)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Extending video {args.extend_direction} by {args.extend_frames} latent frames…")
num_steps = args.steps if args.steps is not None else 30
@@ -709,6 +773,7 @@ def run_a2v(args: argparse.Namespace) -> str:
emit_status(f"Loading A2V pipeline ({args.model})…")
emit_stage(1, 0, 1, "Loading model")
pipe = AudioToVideoPipeline(model_dir=args.model, gemma_model_id=args.gemma)
+ _apply_user_loras(pipe, args.user_lora_specs)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Generating A2V from {Path(args.audio).name}…")
stage1_steps = args.steps if args.steps is not None else 30
@@ -771,6 +836,9 @@ def maybe_strip_audio(output_path: str) -> None:
def main() -> NoReturn:
args = parse_args()
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
+ # Parse user LoRAs once up-front (strict validation surfaces bad input
+ # before any model load). Each run_* sets pipe._pending_loras from this.
+ args.user_lora_specs = _parse_user_loras(args.user_loras)
configure_negative_prompt(args.negative_prompt)
runners = {
diff --git a/server/lib/README.md b/server/lib/README.md
index 66bc91c62b..5c81d10281 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -177,6 +177,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. |
| `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. |
| `civitai.js` | Civitai URL parsing + API client. |
+| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision}`, fetch `/api/models` metadata, pick the `.safetensors`, detect the video-LoRA family (`ltx-video`), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js` for video LoRAs. 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). |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.js
new file mode 100644
index 0000000000..b8944585a4
--- /dev/null
+++ b/server/lib/huggingfaceLora.js
@@ -0,0 +1,211 @@
+/**
+ * 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.
+ *
+ * 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.
+ *
+ * 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
+ * subprocess, mirroring the Civitai path.
+ *
+ * No try/catch — errors bubble to centralized middleware; domain errors throw
+ * ServerError.
+ */
+
+import { ServerError } from './errorHandler.js';
+import { VIDEO_LORA_FAMILIES } from './runners.js';
+import { readResponseJson } from './readResponseJson.js';
+
+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 }`:
+// https://huggingface.co/fal/ltx2.3-audio-reactive-lora
+// https://huggingface.co/fal/ltx2.3-audio-reactive-lora/tree/main
+// 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.
+// Throws ServerError on garbage.
+export const parseHuggingfaceLoraRef = (raw) => {
+ if (typeof raw !== 'string' || !raw.trim()) {
+ throw new ServerError('Empty HuggingFace URL', { status: 400, code: 'HF_BAD_URL' });
+ }
+ const trimmed = raw.trim();
+
+ // Bare `org/name` (optionally `@rev` / `:rev`) — no scheme.
+ if (!/^https?:\/\//i.test(trimmed)) {
+ const m = trimmed.match(/^([^/\s]+\/[^/\s@:]+)(?:[@:]([\w.\-/]+))?$/);
+ if (!m) {
+ throw new ServerError(
+ `HuggingFace ref must be a URL or "org/name" — got "${trimmed.slice(0, 60)}"`,
+ { status: 400, code: 'HF_BAD_URL' },
+ );
+ }
+ return { repo: m[1], revision: m[2] || null };
+ }
+
+ let parsed;
+ try {
+ parsed = new URL(trimmed);
+ } catch {
+ throw new ServerError(`Malformed URL: "${trimmed.slice(0, 60)}"`, { status: 400, code: 'HF_BAD_URL' });
+ }
+ if (!HF_HOSTS.has(parsed.hostname.toLowerCase())) {
+ throw new ServerError(`Not a HuggingFace URL: ${parsed.hostname}`, { status: 400, code: 'HF_BAD_URL' });
+ }
+ const segments = parsed.pathname.split('/').filter(Boolean);
+ if (segments.length < 2) {
+ throw new ServerError(
+ `HuggingFace URL must point at /<org>/<name> — got "${parsed.pathname}"`,
+ { status: 400, code: 'HF_BAD_URL' },
+ );
+ }
+ const repo = `${segments[0]}/${segments[1]}`;
+ // Recover a revision from `/tree/<rev>` or `/blob/<rev>` URLs.
+ 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 };
+};
+
+// Build the bearer header for an optional HF token. Public LoRAs need no auth;
+// gated repos (rare for LoRAs) require the user's token.
+export const buildHfAuthHeaders = (token) => {
+ if (typeof token !== 'string' || !token.trim()) return {};
+ return { Authorization: `Bearer ${token.trim()}` };
+};
+
+// HF `resolve` URL for a single file — survives the CDN redirect with the
+// bearer header (HF, unlike Civitai, keeps the Authorization header across the
+// 302 to its LFS CDN, so no `?token=` query param dance is needed).
+export const buildHfResolveUrl = (repo, revision, file) =>
+ `https://huggingface.co/${repo}/resolve/${encodeURIComponent(revision || 'main')}/${file.split('/').map(encodeURIComponent).join('/')}`;
+
+// Fetch model metadata from the public HF API. Returns the parsed JSON with
+// `siblings` (file list), `tags`, and `cardData` (carries `base_model`).
+// fetchImpl is injectable for tests.
+export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch } = {}) => {
+ if (!/^[^/\s]+\/[^/\s]+$/.test(String(repo))) {
+ throw new ServerError(`Invalid HuggingFace repo id: ${repo}`, { status: 400, code: 'HF_BAD_URL' });
+ }
+ // The `blobs=true` expand isn't needed — siblings carry rfilename, and we
+ // size-rank via the resolve HEAD only if multiple LoRA files tie.
+ const url = revision
+ ? `${HF_API}/${repo}/revision/${encodeURIComponent(revision)}`
+ : `${HF_API}/${repo}`;
+ const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) } });
+ if (!res.ok) {
+ if (res.status === 404) {
+ throw new ServerError(`HuggingFace repo ${repo} not found`, { status: 404, code: 'HF_NOT_FOUND' });
+ }
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `HuggingFace rejected the request (${res.status}) — this repo may be gated. Accept its license at https://huggingface.co/${repo} and add your HF token in Image Gen settings.`,
+ { status: res.status, code: 'HF_AUTH' },
+ );
+ }
+ throw new ServerError(`HuggingFace metadata fetch failed: ${res.status}`, { status: 502, code: 'HF_FETCH_FAILED' });
+ }
+ return readResponseJson(res);
+};
+
+// List the `.safetensors` siblings of an HF model response.
+const safetensorsSiblings = (model) => {
+ const siblings = Array.isArray(model?.siblings) ? model.siblings : [];
+ return siblings
+ .map((s) => (typeof s?.rfilename === 'string' ? s.rfilename : null))
+ .filter((f) => f && /\.safetensors$/i.test(f));
+};
+
+// Pick the LoRA weights file to download. Most LoRA repos ship a single
+// .safetensors; when several are present we prefer the canonical diffusers
+// filename, then anything with "lora" in the name, then the first. Throws when
+// the repo has none (it's not a LoRA weights repo, or weights are split into a
+// subdir we don't recognize).
+export const pickHfLoraFile = (model) => {
+ const files = safetensorsSiblings(model);
+ if (!files.length) {
+ throw new ServerError(
+ `HuggingFace repo ${model?.id || model?.modelId || ''} has no .safetensors file`,
+ { status: 422, code: 'HF_NO_SAFETENSORS' },
+ );
+ }
+ if (files.length === 1) return files[0];
+ 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*"
+ || files.find((f) => /lora/i.test(f));
+ return canonical || files[0];
+};
+
+// Detect the PortOS video-LoRA family for an HF repo. LTX-2 / LTX-Video LoRAs
+// (fal, Lightricks) map to the `ltx-video` family — the only video family with
+// a working runtime today. Looks at the repo id, HF tags, and the card's
+// `base_model`. Returns a VIDEO_LORA_FAMILIES value or null (unrecognized →
+// the installer surfaces a clear error rather than mis-tagging it).
+export const detectVideoLoraFamily = ({ repo, model } = {}) => {
+ const haystacks = [String(repo || '').toLowerCase()];
+ const tags = Array.isArray(model?.tags) ? model.tags : [];
+ for (const t of tags) haystacks.push(String(t).toLowerCase());
+ const baseModel = model?.cardData?.base_model;
+ if (typeof baseModel === 'string') haystacks.push(baseModel.toLowerCase());
+ else if (Array.isArray(baseModel)) for (const b of baseModel) haystacks.push(String(b).toLowerCase());
+ const blob = haystacks.join(' ');
+ // `ltxv` / `ltx-video` / `ltx2` / `ltx-2` / `ltx 2.3` all collapse to ltx.
+ if (/\bltx[\s._-]?v?(?:ideo)?\b|\bltx[\s._-]?2/.test(blob) || /ltxvideo/.test(blob)) {
+ return VIDEO_LORA_FAMILIES.LTX_VIDEO;
+ }
+ return null;
+};
+
+const DESCRIPTION_MAX_CHARS = 2000;
+
+// Build the canonical sidecar for an HF-installed video LoRA. Shape mirrors the
+// Civitai sidecar (services builds the same fields) but carries a `huggingface`
+// 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 }) => {
+ const tags = Array.isArray(model?.tags) ? model.tags : [];
+ const baseModelRaw = model?.cardData?.base_model;
+ const baseModel = typeof baseModelRaw === 'string'
+ ? baseModelRaw
+ : (Array.isArray(baseModelRaw) ? baseModelRaw[0] || null : null);
+ // HF widget/card sometimes carries trigger words under cardData.instance_prompt
+ // or a `widgetData` prompt; keep it best-effort and tolerant of absence.
+ const instancePrompt = typeof model?.cardData?.instance_prompt === 'string'
+ ? model.cardData.instance_prompt.trim()
+ : '';
+ const rawDesc = typeof model?.cardData?.description === 'string' ? model.cardData.description : '';
+ const description = rawDesc.length > DESCRIPTION_MAX_CHARS ? rawDesc.slice(0, DESCRIPTION_MAX_CHARS) : rawDesc;
+ return {
+ filename,
+ name: repo.split('/')[1] || repo,
+ description,
+ huggingface: {
+ repo,
+ revision: revision || 'main',
+ file,
+ url: `https://huggingface.co/${repo}`,
+ baseModel,
+ tags,
+ },
+ runnerFamily: family,
+ fluxVariant: null,
+ triggerWords: instancePrompt ? [instancePrompt] : [],
+ recommendedScale: 1.0,
+ file: {
+ sizeKB: null,
+ hashes: {},
+ downloadUrl: buildHfResolveUrl(repo, revision, file),
+ },
+ previewImageUrl: null,
+ source: 'huggingface',
+ installedAt: new Date().toISOString(),
+ };
+};
diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.js
new file mode 100644
index 0000000000..6ff5152bd0
--- /dev/null
+++ b/server/lib/huggingfaceLora.test.js
@@ -0,0 +1,123 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseHuggingfaceLoraRef,
+ buildHfResolveUrl,
+ buildHfAuthHeaders,
+ pickHfLoraFile,
+ detectVideoLoraFamily,
+ buildHfLoraSidecar,
+ fetchHuggingfaceModel,
+} from './huggingfaceLora.js';
+import { 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 });
+ });
+ 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' });
+ expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/blob/main/lora.safetensors'))
+ .toEqual({ repo: 'fal/x', revision: 'main' });
+ });
+ 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' });
+ });
+ it('rejects garbage and non-HF hosts', () => {
+ expect(() => parseHuggingfaceLoraRef('')).toThrow(/Empty/);
+ expect(() => parseHuggingfaceLoraRef('https://example.com/fal/x')).toThrow(/Not a HuggingFace/);
+ expect(() => parseHuggingfaceLoraRef('justaword')).toThrow(/org\/name/);
+ });
+});
+
+describe('buildHfResolveUrl', () => {
+ it('builds a resolve URL defaulting revision to main and encoding path segments', () => {
+ expect(buildHfResolveUrl('fal/x', null, 'lora.safetensors'))
+ .toBe('https://huggingface.co/fal/x/resolve/main/lora.safetensors');
+ expect(buildHfResolveUrl('fal/x', 'v1', 'sub dir/lora.safetensors'))
+ .toBe('https://huggingface.co/fal/x/resolve/v1/sub%20dir/lora.safetensors');
+ });
+});
+
+describe('buildHfAuthHeaders', () => {
+ it('returns a bearer header only when a token is present', () => {
+ expect(buildHfAuthHeaders('hf_abc')).toEqual({ Authorization: 'Bearer hf_abc' });
+ expect(buildHfAuthHeaders('')).toEqual({});
+ expect(buildHfAuthHeaders(undefined)).toEqual({});
+ });
+});
+
+describe('pickHfLoraFile', () => {
+ const m = (...names) => ({ siblings: names.map((rfilename) => ({ rfilename })) });
+ it('returns the lone .safetensors', () => {
+ expect(pickHfLoraFile(m('lora.safetensors', 'README.md'))).toBe('lora.safetensors');
+ });
+ it('prefers the canonical diffusers filename', () => {
+ expect(pickHfLoraFile(m('extra.safetensors', 'pytorch_lora_weights.safetensors')))
+ .toBe('pytorch_lora_weights.safetensors');
+ });
+ it('prefers a name containing "lora" when no canonical match', () => {
+ expect(pickHfLoraFile(m('model.safetensors', 'my_style_lora.safetensors')))
+ .toBe('my_style_lora.safetensors');
+ });
+ it('throws when there is no .safetensors', () => {
+ expect(() => pickHfLoraFile(m('config.json', 'README.md'))).toThrow(/no .safetensors/);
+ });
+});
+
+describe('detectVideoLoraFamily', () => {
+ it('classifies LTX repos as ltx-video from the repo id', () => {
+ expect(detectVideoLoraFamily({ repo: 'fal/ltx2.3-audio-reactive-lora' })).toBe(VIDEO_LORA_FAMILIES.LTX_VIDEO);
+ expect(detectVideoLoraFamily({ repo: 'Lightricks/LTX-Video-LoRA' })).toBe(VIDEO_LORA_FAMILIES.LTX_VIDEO);
+ });
+ it('classifies via tags / base_model when the id is opaque', () => {
+ expect(detectVideoLoraFamily({ repo: 'someone/cool-lora', model: { tags: ['ltxv', 'lora'] } }))
+ .toBe(VIDEO_LORA_FAMILIES.LTX_VIDEO);
+ expect(detectVideoLoraFamily({ repo: 'someone/cool-lora', model: { cardData: { base_model: 'Lightricks/LTX-Video' } } }))
+ .toBe(VIDEO_LORA_FAMILIES.LTX_VIDEO);
+ });
+ it('returns null for unrelated repos (e.g. an image SDXL LoRA)', () => {
+ expect(detectVideoLoraFamily({ 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({
+ repo: 'fal/ltx2.3-audio-reactive-lora',
+ revision: null,
+ file: 'lora.safetensors',
+ family: VIDEO_LORA_FAMILIES.LTX_VIDEO,
+ filename: 'lora-fal-ltx2-3-audio-reactive-lora-hf.safetensors',
+ model: { tags: ['ltxv'], cardData: { base_model: 'Lightricks/LTX-2.3', instance_prompt: 'audio reactive' } },
+ });
+ expect(sidecar.runnerFamily).toBe('ltx-video');
+ expect(sidecar.source).toBe('huggingface');
+ expect(sidecar.huggingface.repo).toBe('fal/ltx2.3-audio-reactive-lora');
+ expect(sidecar.huggingface.revision).toBe('main');
+ expect(sidecar.huggingface.baseModel).toBe('Lightricks/LTX-2.3');
+ expect(sidecar.triggerWords).toEqual(['audio reactive']);
+ expect(sidecar.recommendedScale).toBe(1.0);
+ expect(sidecar.civitai).toBeUndefined();
+ expect(sidecar.file.downloadUrl).toContain('/resolve/main/lora.safetensors');
+ });
+});
+
+describe('fetchHuggingfaceModel', () => {
+ it('rejects malformed repo ids before any fetch', async () => {
+ await expect(fetchHuggingfaceModel('notarepo')).rejects.toThrow(/Invalid HuggingFace repo id/);
+ });
+ it('surfaces a gated/auth error on 401/403', async () => {
+ const fetchImpl = async () => ({ ok: false, status: 403 });
+ await expect(fetchHuggingfaceModel('fal/x', { fetchImpl })).rejects.toMatchObject({ code: 'HF_AUTH' });
+ });
+ it('returns the parsed body on success', async () => {
+ const body = { id: 'fal/x', siblings: [{ rfilename: 'lora.safetensors' }], tags: ['ltxv'] };
+ // readResponseJson reads res.text() then parses tolerantly.
+ const fetchImpl = async () => ({ ok: true, text: async () => JSON.stringify(body) });
+ await expect(fetchHuggingfaceModel('fal/x', { fetchImpl })).resolves.toEqual(body);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index e9ff22803c..69b1a09c98 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -150,6 +150,7 @@ export * from './songCraftRef.js';
export * from './appResolver.js';
export * from './capabilityMap.js';
export * from './civitai.js';
+export * from './huggingfaceLora.js';
export * from './localLlmCatalog.js';
export * from './localLlmDisk.js';
export * from './localModelHeuristics.js';
diff --git a/server/lib/runners.js b/server/lib/runners.js
index 09ea767569..d9c48fd640 100644
--- a/server/lib/runners.js
+++ b/server/lib/runners.js
@@ -25,6 +25,28 @@ export const RUNNER_FAMILIES = Object.freeze({
QWEN: 'qwen',
});
+// Video-LoRA families are tracked SEPARATELY from the image RUNNER_FAMILIES
+// above. The Civitai suggestion/search code iterates Object.values(
+// RUNNER_FAMILIES) and would 400 on any family Civitai has no baseModel
+// mapping for — and video LoRAs (e.g. fal/ltx2.3-audio-reactive-lora) are
+// imported from HuggingFace, not Civitai (see installFromHuggingface), so they
+// must never enter that iteration. The compat-key machinery
+// (composeCompatKey / the picker's familyOf) is family-string-agnostic, so a
+// LoRA tagged `runnerFamily: 'ltx-video'` filters correctly against an
+// `ltx-video` video model without any change there.
+export const VIDEO_LORA_FAMILIES = Object.freeze({
+ LTX_VIDEO: 'ltx-video',
+});
+
+// Map a video-model registry entry (which carries `runtime`, not `runner`) to
+// the LoRA family the picker filters on. Only dgrauet's `ltx2` runtime can
+// fuse arbitrary user LoRAs today — its `ltx_pipelines_mlx` pipelines honor a
+// `_pending_loras` hook (see scripts/generate_ltx2.py). The legacy mlx_video /
+// wan22 / hunyuan runtimes have no general LoRA path, so they return null
+// ("no LoRA support") and the VideoGen picker hides itself.
+export const videoLoraFamily = (model) =>
+ model?.runtime === 'ltx2' ? VIDEO_LORA_FAMILIES.LTX_VIDEO : null;
+
// Convenience predicate helpers — match the semantics of the existing
// `isFlux2()` / `isZImage()` / `isErnie()` exports in `mediaModels.js`
// (which still exist for back-compat with their many call sites). New code
diff --git a/server/lib/runners.test.js b/server/lib/runners.test.js
index 8a672e6ff8..e6698f8ae3 100644
--- a/server/lib/runners.test.js
+++ b/server/lib/runners.test.js
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, videoLoraFamily, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
const __dirname_self = dirname(fileURLToPath(import.meta.url));
const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');
@@ -49,6 +49,33 @@ describe('RUNNER_FAMILIES', () => {
});
});
+describe('VIDEO_LORA_FAMILIES / videoLoraFamily', () => {
+ it('exports the canonical ltx-video family id, frozen', () => {
+ expect(VIDEO_LORA_FAMILIES.LTX_VIDEO).toBe('ltx-video');
+ expect(Object.isFrozen(VIDEO_LORA_FAMILIES)).toBe(true);
+ });
+
+ it('maps only the ltx2 runtime to a LoRA family', () => {
+ expect(videoLoraFamily({ runtime: 'ltx2' })).toBe('ltx-video');
+ expect(videoLoraFamily({ runtime: 'mlx_video' })).toBe(null);
+ expect(videoLoraFamily({ runtime: 'wan22' })).toBe(null);
+ expect(videoLoraFamily({ runtime: 'hunyuan' })).toBe(null);
+ expect(videoLoraFamily({})).toBe(null);
+ expect(videoLoraFamily(null)).toBe(null);
+ });
+
+ it('composeCompatKey leaves the ltx-video family bare (no variant)', () => {
+ expect(composeCompatKey('ltx-video', null)).toBe('ltx-video');
+ expect(composeCompatKey('ltx-video', '9b')).toBe('ltx-video');
+ });
+
+ it('client mirror carries the video family + helper', () => {
+ const text = readFileSync(CLIENT_MIRROR_PATH, 'utf-8');
+ expect(text).toMatch(/LTX_VIDEO:\s*'ltx-video'/);
+ expect(text).toMatch(/export const videoLoraFamily/);
+ });
+});
+
describe('flux2VariantFromModel', () => {
it('reads the size from the model id across all four flux2 ids', () => {
expect(flux2VariantFromModel({ id: 'flux2-klein-4b' })).toBe('4b');
diff --git a/server/routes/loras.js b/server/routes/loras.js
index e3f1553479..5c9a72f2b5 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -16,13 +16,14 @@ import {
deleteLora,
getLora,
installFromCivitai,
+ installFromHuggingface,
listLoras,
patchLoraSidecar,
} from '../services/loras.js';
import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggestions.js';
import { findLorasByCharacter } from '../services/characterLoraResolver.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
-import { RUNNER_FAMILIES } from '../lib/runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from '../lib/runners.js';
const router = Router();
@@ -119,6 +120,20 @@ 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.
+const hfInstallSchema = z.object({
+ url: z.string().min(1).max(1024),
+ family: z.enum(Object.values(VIDEO_LORA_FAMILIES)).optional(),
+ // One-shot token override; absence falls back to the stored/env/CLI HF token.
+ token: z.string().min(1).max(256).optional(),
+});
+router.post('/install/huggingface', asyncHandler(async (req, res) => {
+ const data = validateRequest(hfInstallSchema, req.body);
+ const sidecar = await installFromHuggingface(data);
+ res.status(201).json(sidecar);
+}));
+
// Trained LoRAs linked to a universe character — used by the character card
// chip in the universe editor + catalog detail page. 2-segment path keeps it
// off the `/:filename` wildcard below.
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 44c84ce0d4..e397288741 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -151,6 +151,24 @@ const generateBodySchema = z.object({
index: z.number().int().min(0).max(1023),
})).min(2).max(8).optional(),
),
+ // Video LoRAs to fuse for this render (ltx2 runtime only). Each entry is a
+ // basename under data/loras/ + a fusion strength. Multipart bodies send this
+ // as a JSON string (same shape the unified picker writes), so preprocess
+ // parses it before zod. `filename` rejects path separators here — the
+ // service re-validates with assertSafeLoraFilename before touching disk.
+ loras: z.preprocess(
+ (v) => {
+ if (v == null || v === '') return undefined;
+ if (typeof v === 'string') {
+ try { return JSON.parse(v); } catch { return v; }
+ }
+ return v;
+ },
+ z.array(z.object({
+ filename: z.string().min(1).max(255).regex(/^[^/\\]+\.safetensors$/i, 'filename must be a bare .safetensors basename'),
+ scale: z.number().min(0).max(2).optional(),
+ })).max(8).optional(),
+ ),
});
// Probes required-package imports on each call so a half-installed Python
@@ -682,6 +700,19 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
extendFromVideoPath = candidate;
}
+ // Video LoRAs are an ltx2-runtime primitive — the dgrauet pipeline fuses
+ // them via _pending_loras (see scripts/generate_ltx2.py). Reject up-front on
+ // any other runtime so a bad modelId can't enqueue a doomed job that only
+ // fails in the worker. `loras: []` (picker cleared) is treated as absent.
+ if (Array.isArray(body.loras) && body.loras.length > 0
+ && effectiveModel && effectiveModel.runtime !== 'ltx2') {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `LoRAs require an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,
+ { status: 400, code: 'LORAS_REQUIRE_LTX2' },
+ );
+ }
+
const effectiveChunks = body.mode === 'a2v' ? 1 : (body.chunks ?? 1);
// Enqueue rather than spawn synchronously — the mediaJobQueue worker will
@@ -712,6 +743,11 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
mode: body.mode,
imageStrength: body.imageStrength,
chunks: effectiveChunks,
+ // Normalize picker entries to { filename, scale } with a defaulted scale
+ // so the service/worker always sees a number. `[]` (cleared) → undefined.
+ loras: Array.isArray(body.loras) && body.loras.length
+ ? body.loras.map((l) => ({ filename: l.filename, scale: typeof l.scale === 'number' ? l.scale : 1.0 }))
+ : undefined,
},
});
// Match the legacy response shape (jobId, generationId, filename, model,
@@ -739,6 +775,9 @@ const ACTIVE_JOB_PARAM_FIELDS = [
'width', 'height', 'numFrames', 'fps',
'steps', 'guidanceScale', 'seed',
'tiling', 'disableAudio', 'mode', 'chunks', 'imageStrength',
+ // loras are { filename, scale } basenames (no server filesystem paths), so
+ // they're safe to echo back for the resuming picker to repopulate.
+ 'loras',
];
const pickJobParams = (params) => {
if (!params || typeof params !== 'object') return {};
diff --git a/server/services/loras.js b/server/services/loras.js
index 2c1a5f1626..bccecc96b9 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -40,8 +40,18 @@ import {
pickVersion,
slugifyForFilename,
} from '../lib/civitai.js';
-import { RUNNER_FAMILIES, composeCompatKey } from '../lib/runners.js';
+import {
+ buildHfAuthHeaders,
+ buildHfLoraSidecar,
+ buildHfResolveUrl,
+ detectVideoLoraFamily,
+ fetchHuggingfaceModel,
+ parseHuggingfaceLoraRef,
+ pickHfLoraFile,
+} from '../lib/huggingfaceLora.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, composeCompatKey } from '../lib/runners.js';
import { detectFlux2Variant } from '../lib/safetensors.js';
+import { getHfToken } from '../lib/hfToken.js';
import { getSettings } from './settings.js';
const SIDECAR_SUFFIX = '.metadata.json';
@@ -243,11 +253,19 @@ export const resolveCivitaiKey = async () => {
// `.partial` from a previous crashed install (and prevents two concurrent
// installs of the same target from racing on the same temp path).
// fetchImpl is injectable for tests.
-const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} , hasApiKey = false } = {}) => {
+const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} , hasApiKey = false, source = 'civitai' } = {}) => {
const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;
const res = await fetchImpl(url, { headers, redirect: 'follow' });
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
+ // HuggingFace LoRAs: a 401/403 means the repo is gated and the token is
+ // missing/insufficient — point the user at the license + HF token UI.
+ if (source === 'huggingface') {
+ const message = hasApiKey
+ ? `HuggingFace rejected the download (${res.status}) even with your saved token — accept the model's license on its HF page, or the token may be expired/scoped.`
+ : `HuggingFace download rejected (${res.status}) — this LoRA's repo is gated. Accept its license on HuggingFace and add your HF token in Image Gen settings, then retry.`;
+ throw new ServerError(message, { status: res.status, code: 'HF_AUTH' });
+ }
// When a key was supplied and Civitai still rejects, the cause is
// almost always early-access content or a deactivated/scoped key —
// not a missing key. Don't tell the user to set a key they've
@@ -257,7 +275,9 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,
: `Civitai download rejected (${res.status}) — this LoRA may require an API key. Configure a Civitai API key in PortOS Settings (or set the CIVITAI_API_KEY env var) and retry.`;
throw new ServerError(message, { status: res.status, code: 'CIVITAI_AUTH' });
}
- throw new ServerError(`Civitai download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
+ const label = source === 'huggingface' ? 'HuggingFace' : 'Civitai';
+ const code = source === 'huggingface' ? 'HF_DOWNLOAD_FAILED' : 'CIVITAI_DOWNLOAD_FAILED';
+ throw new ServerError(`${label} download failed: ${res.status} ${res.statusText}`, { status: 502, code });
}
if (!res.body) {
throw new ServerError('Civitai download returned no body', { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
@@ -383,3 +403,72 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
console.log(`✅ Installed Civitai LoRA: ${filename}`);
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));
+
+// 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.
+export const installFromHuggingface = async (input, { fetchImpl = fetch } = {}) => {
+ const { repo, revision } = 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);
+
+ // Family: explicit override (validated) wins over autodetection so a user
+ // can correct a mis-detected repo from the UI. An unrecognized repo with no
+ // override is refused rather than silently tagged — a wrongly-tagged LoRA
+ // 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)) {
+ throw new ServerError(
+ `Unknown video LoRA family "${input.family}" — expected one of ${[...VIDEO_LORA_FAMILY_VALUES].join(', ')}`,
+ { status: 400, code: 'HF_BAD_FAMILY' },
+ );
+ }
+ family = input.family;
+ } else {
+ family = detectVideoLoraFamily({ repo, model });
+ }
+ 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.`,
+ { status: 422, code: 'HF_UNKNOWN_FAMILY' },
+ );
+ }
+
+ // Stable filename: `lora-<org>-<name>-hf.safetensors`. The org+name slug
+ // disambiguates same-named LoRAs from different authors; the `-hf` suffix
+ // keeps it distinct from a Civitai install of the same model.
+ const slug = slugifyForFilename(repo.replace('/', '-'));
+ const filename = `lora-${slug}-hf.safetensors`;
+ const destPath = join(PATHS.loras, filename);
+ if (existsSync(destPath)) {
+ throw new ServerError(
+ `Already installed: ${filename}. Delete it first to reinstall.`,
+ { status: 409, code: 'HF_ALREADY_INSTALLED' },
+ );
+ }
+
+ await ensureDir(PATHS.loras);
+ console.log(`📥 Installing HuggingFace LoRA: ${repo} (${file}) → ${filename} [family=${family}]`);
+ await downloadToFile(buildHfResolveUrl(repo, revision, file), destPath, {
+ fetchImpl,
+ headers: { 'User-Agent': 'PortOS/hf-lora-installer', ...buildHfAuthHeaders(token) },
+ hasApiKey: !!token,
+ source: 'huggingface',
+ });
+
+ const sidecar = buildHfLoraSidecar({ repo, revision, file, model, family, filename });
+ await writeFile(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ console.log(`✅ Installed HuggingFace LoRA: ${filename}`);
+ return sidecar;
+};
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 6f776d6bd7..b74a0e66df 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -403,3 +403,73 @@ describe('installFromCivitai', () => {
expect(tmpFiles.some((f) => f.endsWith('.partial'))).toBe(false);
});
});
+
+describe('installFromHuggingface', () => {
+ const HF_MODEL = {
+ id: 'fal/ltx2.3-audio-reactive-lora',
+ tags: ['ltxv', 'lora'],
+ cardData: { base_model: 'Lightricks/LTX-2.3', instance_prompt: 'audio reactive' },
+ siblings: [
+ { rfilename: 'README.md' },
+ { rfilename: 'pytorch_lora_weights.safetensors' },
+ ],
+ };
+
+ it('fetches metadata, downloads the .safetensors, writes a video-LoRA sidecar', async () => {
+ const calls = [];
+ const fetchImpl = async (url) => {
+ calls.push(url);
+ if (url.startsWith('https://huggingface.co/api/models/fal/ltx2.3-audio-reactive-lora')) {
+ return mockJsonResponse(HF_MODEL);
+ }
+ if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
+ const stream = new ReadableStream({
+ start(c) { c.enqueue(new Uint8Array(Buffer.from('weights'))); c.close(); },
+ });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const sidecar = await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/fal/ltx2.3-audio-reactive-lora', token: 'hf_test' },
+ { fetchImpl },
+ );
+ expect(sidecar.filename).toBe('lora-fal-ltx2.3-audio-reactive-lora-hf.safetensors');
+ expect(sidecar.runnerFamily).toBe('ltx-video');
+ expect(sidecar.source).toBe('huggingface');
+ expect(sidecar.huggingface.repo).toBe('fal/ltx2.3-audio-reactive-lora');
+ expect(sidecar.triggerWords).toEqual(['audio reactive']);
+ // The picked file is the canonical diffusers weights, not the README.
+ expect(calls.some((u) => u.includes('/resolve/main/pytorch_lora_weights.safetensors'))).toBe(true);
+ });
+
+ it('refuses a repo it cannot classify as a supported video 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' }] });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ await expect(
+ lorasService.installFromHuggingface({ url: 'someone/sdxl-lora', token: 'hf_test' }, { fetchImpl }),
+ ).rejects.toMatchObject({ code: 'HF_UNKNOWN_FAMILY' });
+ });
+
+ it('accepts an explicit family override', async () => {
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://huggingface.co/api/models/')) {
+ return mockJsonResponse({ id: 'someone/mystery-lora', siblings: [{ rfilename: 'lora.safetensors' }] });
+ }
+ if (url.includes('/resolve/main/lora.safetensors')) {
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const sidecar = await lorasService.installFromHuggingface(
+ { url: 'someone/mystery-lora', family: 'ltx-video', token: 'hf_test' },
+ { fetchImpl },
+ );
+ expect(sidecar.runnerFamily).toBe('ltx-video');
+ });
+});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 5a64dab223..bbea1bcfe4 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -26,6 +26,7 @@ import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscale
import { hfTokenEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess } from './generateVideoHelpers.js';
+import { assertSafeLoraFilename } from '../loras.js';
// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1
// scripts/setup-image-video.sh`. Used when a model entry has
@@ -329,11 +330,32 @@ export const resolveT2vTwoStageOverride = ({
return { guidance: 1.0, steps: 8, stage2Steps: 3 };
};
+// Resolve picker `{ filename, scale }` LoRA entries into absolute
+// `{ path, strength }` pairs the ltx2 helper fuses via the pipeline's
+// `_pending_loras` hook (see scripts/generate_ltx2.py). Validates each
+// basename can't escape PATHS.loras (assertSafeLoraFilename) and that the file
+// exists — a typo or a deleted LoRA would otherwise surface as an opaque
+// Python FileNotFoundError deep inside the render. Returns [] for no LoRAs.
+// Only the ltx2 runtime consumes the result; buildArgs rejects LoRAs on the
+// other runtimes before this is even reached for a doomed job.
+export const resolveVideoLoras = (loras) => {
+ if (!Array.isArray(loras) || loras.length === 0) return [];
+ return loras.map((l) => {
+ assertSafeLoraFilename(l?.filename);
+ const path = join(PATHS.loras, l.filename);
+ if (!existsSync(path)) {
+ throw new ServerError(`LoRA not found: ${l.filename}`, { status: 400, code: 'LORA_NOT_FOUND' });
+ }
+ const strength = Number.isFinite(l?.scale) ? l.scale : 1.0;
+ return { path, strength, filename: l.filename };
+ });
+};
+
// Build the spawn args for dgrauet's ltx-2-mlx runtime via our Python helper.
// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`
// resolves) but the script file lives in the PortOS repo so updates ship
// with PortOS releases instead of the user's HF cache.
-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {
+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras }) => {
assertByovRuntimeInstalled('ltx2');
// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2
// routes to ExtendPipeline.extend_from_video — conditions on the entire
@@ -443,6 +465,13 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
'--steps', String(steps),
'--cfg-scale', String(guidance),
];
+ // User LoRAs — fused into the transformer via the pipeline's _pending_loras
+ // hook. Emitted as a JSON list of { path, strength }; generate_ltx2.py sets
+ // pipe._pending_loras before generation so the deltas fuse at load time
+ // (the same mechanism the upstream `ltx-2-mlx generate --lora` CLI uses).
+ if (Array.isArray(loras) && loras.length > 0) {
+ args.push('--user-loras', JSON.stringify(loras.map((l) => ({ path: l.path, strength: l.strength }))));
+ }
// Two-stage T2V experiment passes an explicit stage-2 step count; omitted
// otherwise so the pipeline keeps its own default.
if (stage2Steps != null) args.push('--stage2-steps', String(stage2Steps));
@@ -554,12 +583,22 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {
+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath, loras }) => {
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
if (model.runtime === 'ltx2') {
- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo });
+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras });
+ }
+ // Defense-in-depth: only the ltx2 runtime can fuse user LoRAs. The route
+ // already rejects this combination, but a non-route caller (test, queue
+ // replay) could reach here — fail clearly rather than silently dropping the
+ // LoRAs and producing a base render the user thinks is LoRA-styled.
+ if (Array.isArray(loras) && loras.length > 0) {
+ throw new ServerError(
+ `LoRAs are only supported on the ltx2 runtime. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,
+ { status: 400, code: 'LORAS_REQUIRE_LTX2' },
+ );
}
if (model.runtime === 'wan22') {
return buildWan22Args({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath });
@@ -637,7 +676,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
// use (avoiding drift between two hardcoded constants).
export const DEFAULT_NUM_FRAMES = 121;
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, loras = null, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -662,6 +701,12 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
throw new ServerError(`Video model "${modelId}" is missing the required \`repo\` field in data/media-models.json`, { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' });
}
+ // Resolve LoRA basenames → absolute { path, strength } pairs up-front so a
+ // missing/typo'd LoRA fails with a clean 400 before any GPU work. buildArgs
+ // rejects LoRAs on non-ltx2 runtimes (the route also guards), so this is a
+ // no-op there.
+ const resolvedLoras = resolveVideoLoras(loras);
+
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
@@ -810,6 +855,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// render apart from a user who happened to pick 8 steps — comparing it
// against the default Standard render is the whole point of the knob.
...(t2vTwoStage ? { twoStageT2v: true, stage2Steps: actualStage2Steps } : {}),
+ // Stamp the applied LoRAs (basename + strength) so the history entry and
+ // the Remix flow can show/round-trip which LoRAs styled this render.
+ ...(resolvedLoras.length ? { loras: resolvedLoras.map((l) => ({ filename: l.filename, scale: l.strength })) } : {}),
...(hidden ? { hidden: true } : {}),
};
const job = { ...meta, clients: [], status: 'running' };
@@ -823,7 +871,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath, loras: resolvedLoras }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 4169216734..51c47423cc 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -19,6 +19,7 @@ const MOCK_PATHS = {
images: '/mock/data/images',
videoThumbnails: '/mock/data/video-thumbnails',
uploads: '/mock/data/uploads',
+ loras: '/mock/data/loras',
};
vi.mock('../../lib/fileUtils.js', () => ({
@@ -27,6 +28,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: MOCK_PATHS,
readJSONFile: vi.fn(async () => []),
atomicWrite: vi.fn(async () => {}),
+ // resolveVideoLoras → assertSafeLoraFilename → assertSafeFilename; the
+ // filename safety check is unit-tested in loras.test.js, so a no-op here
+ // lets the LoRA-arg test focus on the spawn-args plumbing.
+ assertSafeFilename: vi.fn(),
UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
}));
@@ -852,3 +857,74 @@ describe('generateVideo — panel-side completion watchdog', () => {
expect(hang.proc.kill).not.toHaveBeenCalled();
});
});
+
+describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
+ it('emits --user-loras JSON with resolved path + strength for ltx2 renders', async () => {
+ const { spawn } = await import('child_process');
+ const spawnMock = vi.mocked(spawn);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'lora-arg-test',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'audio reactive clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ loras: [{ filename: 'lora-fal-ltx2-3-audio-reactive-lora-hf.safetensors', scale: 0.8 }],
+ });
+
+ const call = spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin).includes('.portos/ltx-2-mlx/.venv/bin/python3')
+ && Array.isArray(args) && args.includes('--user-loras'),
+ );
+ expect(call).toBeTruthy();
+ const args = call[1];
+ const payload = JSON.parse(args[args.indexOf('--user-loras') + 1]);
+ expect(payload).toEqual([
+ { path: join(MOCK_PATHS.loras, 'lora-fal-ltx2-3-audio-reactive-lora-hf.safetensors'), strength: 0.8 },
+ ]);
+ });
+
+ it('defaults missing scale to 1.0', async () => {
+ const { spawn } = await import('child_process');
+ const spawnMock = vi.mocked(spawn);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'lora-default-scale',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ loras: [{ filename: 'style.safetensors' }],
+ });
+
+ const call = spawnMock.mock.calls.find(
+ ([, args]) => Array.isArray(args) && args.includes('--user-loras'),
+ );
+ const payload = JSON.parse(call[1][call[1].indexOf('--user-loras') + 1]);
+ expect(payload[0].strength).toBe(1.0);
+ });
+
+ it('omits --user-loras when no LoRAs are passed', async () => {
+ const { spawn } = await import('child_process');
+ const spawnMock = vi.mocked(spawn);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'no-lora',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+
+ const call = spawnMock.mock.calls.find(
+ ([bin]) => String(bin).includes('.portos/ltx-2-mlx/.venv/bin/python3'),
+ );
+ expect(call[1]).not.toContain('--user-loras');
+ });
+});