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

address review (codex): unify video LoRAs on the loraFilenames/loraScales contract

[._.]/ Adam Eivy28a4e4e09955
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 4c48a5ee3a..482ab96a11 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -14,7 +14,7 @@ import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
import Banner from '../components/ui/Banner';
import { formatBytes } from '../utils/formatters';
-import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from '../lib/runnerFamilies';
import {
listLorasFull,
installLoraFromCivitai,
@@ -739,9 +739,12 @@ function LoraCard({ lora, onDelete, deleting }) {
const badgeClass = family ? (RUNNER_BADGE_CLASS[family] || 'bg-gray-600/20 text-gray-300 border-gray-500/30') : 'bg-port-warning/20 text-port-warning border-port-warning/30';
const triggerWords = lora.triggerWords || [];
const civitai = lora.civitai;
- // Image Gen page reads ?lora=<filename> as a preselect hint via query string;
- // keeps the manager → gen handoff URL-driven (deep-linkable).
- const testHref = `/media/image?lora=${encodeURIComponent(lora.filename)}`;
+ // The gen pages read ?lora=<filename> as a preselect hint via query string;
+ // keeps the manager → gen handoff URL-driven (deep-linkable). Video-family
+ // LoRAs (ltx-video) deep-link to Video Gen — routing them to Image Gen would
+ // preselect an LTX adapter into an incompatible image render.
+ const isVideoLora = family === VIDEO_LORA_FAMILIES.LTX_VIDEO;
+ const testHref = `${isVideoLora ? '/media/video' : '/media/image'}?lora=${encodeURIComponent(lora.filename)}`;
return (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index f657c56a2a..b6fdbdfc77 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -311,6 +311,27 @@ export default function VideoGen() {
// 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(() => {}); }, []);
+ // ?lora=<filename> preselects a video LoRA when the user clicks "Test" on a
+ // video LoRA card in /media/loras. Mirrors the ImageGen ?lora= handoff:
+ // defer until the library has loaded (for name/scale/triggers), append the
+ // LoRA's trigger words, then strip the param so a refresh doesn't re-add it.
+ useEffect(() => {
+ const fromUrl = searchParams.get('lora');
+ if (!fromUrl || !availableLoras.length) return;
+ const match = availableLoras.find((l) => l.filename === fromUrl);
+ if (match) {
+ setSelectedLoras((prev) => prev.find((s) => s.filename === fromUrl) ? prev : [...prev, {
+ filename: match.filename,
+ name: match.name,
+ scale: typeof match.recommendedScale === 'number' ? match.recommendedScale : 1.0,
+ }]);
+ if (match.triggerWords?.length) {
+ setPrompt((p) => { const add = match.triggerWords.join(', '); return p && p.trim() ? `${p}, ${add}` : add; });
+ }
+ }
+ setSearchParams((prev) => { const next = new URLSearchParams(prev); next.delete('lora'); return next; }, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [availableLoras]);
const { visibleHistory, hiddenHistory } = useMemo(() => ({
visibleHistory: history.filter((v) => !v.hidden),
@@ -997,14 +1018,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 })))
- : '',
+ // Video LoRAs (ltx2 only) ride as the universal parallel-array contract
+ // (loraFilenames + loraScales) — the SAME shape ImageGen submits and a
+ // history requeue emits — so buildFormData appends them as repeated
+ // multipart keys and the route needs no bespoke shape. Only sent when the
+ // model's runtime supports LoRAs (else the route 400s LORAS_REQUIRE_LTX2);
+ // undefined fields are dropped by buildFormData.
+ loraFilenames: (loraFamily && selectedLoras.length) ? selectedLoras.map((l) => l.filename) : undefined,
+ loraScales: (loraFamily && selectedLoras.length) ? selectedLoras.map((l) => l.scale) : undefined,
sourceImageFile: (mode === 'image' || legacyFflf
|| (mode === 'extend' && currentModel?.runtime !== 'ltx2'))
? (sourceImageFile || '') : '',
diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.js
index b8944585a4..35de1b93f4 100644
--- a/server/lib/huggingfaceLora.js
+++ b/server/lib/huggingfaceLora.js
@@ -66,10 +66,19 @@ export const parseHuggingfaceLoraRef = (raw) => {
);
}
const repo = `${segments[0]}/${segments[1]}`;
- // Recover a revision from `/tree/<rev>` or `/blob/<rev>` URLs.
+ // Recover a revision from `/tree/<rev>` or `/blob/<rev>` URLs. A revision can
+ // itself contain slashes (a branch like `feature/foo` or a ref like
+ // `refs/pr/123`), so join ALL segments after the marker — and, for /blob/
+ // URLs, drop the trailing filepath component so `…/blob/main/lora.safetensors`
+ // yields revision `main`, not `main/lora.safetensors`. (/tree/ URLs have no
+ // trailing file, so nothing is dropped there.)
let revision = null;
const treeIdx = segments.findIndex((s) => s === 'tree' || s === 'blob');
- if (treeIdx >= 0 && segments[treeIdx + 1]) revision = segments[treeIdx + 1];
+ if (treeIdx >= 0 && segments[treeIdx + 1]) {
+ const rest = segments.slice(treeIdx + 1);
+ if (segments[treeIdx] === 'blob' && rest.length > 1) rest.pop(); // drop the file path
+ revision = rest.join('/') || null;
+ }
return { repo, revision };
};
diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.js
index 6ff5152bd0..cbf22ff601 100644
--- a/server/lib/huggingfaceLora.test.js
+++ b/server/lib/huggingfaceLora.test.js
@@ -21,6 +21,15 @@ describe('parseHuggingfaceLoraRef', () => {
expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/blob/main/lora.safetensors'))
.toEqual({ repo: 'fal/x', revision: 'main' });
});
+ it('preserves slash-containing revisions and drops the trailing file on /blob/', () => {
+ expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/tree/feature/foo'))
+ .toEqual({ repo: 'fal/x', revision: 'feature/foo' });
+ expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/tree/refs/pr/123'))
+ .toEqual({ repo: 'fal/x', revision: 'refs/pr/123' });
+ expect(parseHuggingfaceLoraRef('https://huggingface.co/fal/x/blob/feature/foo/lora.safetensors'))
+ .toEqual({ repo: 'fal/x', revision: 'feature/foo' });
+ });
+
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' });
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index e397288741..0825ea83a3 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -151,23 +151,26 @@ 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(
+ // Video LoRAs to fuse for this render (ltx2 runtime only). Sent as the SAME
+ // universal contract image renders use — parallel `loraFilenames` +
+ // `loraScales` arrays — NOT a bespoke shape. This is what lets a history
+ // requeue via getRenderConfigForItem() (which emits exactly these fields)
+ // round-trip with no per-page translation. Multipart sends each array as
+ // repeated keys; a SINGLE entry arrives as a bare string and scales arrive as
+ // strings, so wrap+coerce in preprocess (mirrors server/routes/imageGen.js).
+ // `filename` rejects path separators here; the service re-validates with
+ // assertSafeLoraFilename before touching disk.
+ loraFilenames: z.preprocess(
+ (v) => (v == null || v === '') ? undefined : (Array.isArray(v) ? v : [v]),
+ z.array(z.string().min(1).max(255).regex(/^[^/\\]+\.safetensors$/i, 'filename must be a bare .safetensors basename')).max(8).optional(),
+ ),
+ loraScales: z.preprocess(
(v) => {
if (v == null || v === '') return undefined;
- if (typeof v === 'string') {
- try { return JSON.parse(v); } catch { return v; }
- }
- return v;
+ const raw = Array.isArray(v) ? v : [v];
+ return raw.map((x) => (typeof x === 'string' && x !== '' ? Number(x) : x));
},
- 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(),
+ z.array(z.number().min(0).max(2)).max(8).optional(),
),
});
@@ -700,12 +703,22 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
extendFromVideoPath = candidate;
}
+ // Collapse the parallel loraFilenames/loraScales arrays into the internal
+ // `[{ filename, scale }]` shape the service (resolveVideoLoras) and the
+ // resume param echo consume. A defaulted scale keeps the worker contract
+ // simple. Empty (picker cleared) → undefined.
+ const loras = Array.isArray(body.loraFilenames) && body.loraFilenames.length
+ ? body.loraFilenames.map((filename, i) => ({
+ filename,
+ scale: typeof body.loraScales?.[i] === 'number' ? body.loraScales[i] : 1.0,
+ }))
+ : undefined;
+
// 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') {
+ // fails in the worker.
+ if (loras && effectiveModel && effectiveModel.runtime !== 'ltx2') {
await cleanupAllStaged();
throw new ServerError(
`LoRAs require an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,
@@ -743,11 +756,7 @@ 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,
+ loras,
},
});
// Match the legacy response shape (jobId, generationId, filename, model,
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index b0fdf6c6d8..5ff04f7177 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -262,6 +262,50 @@ describe('videoGen routes', () => {
}));
});
+ it('translates the universal loraFilenames/loraScales contract into internal { filename, scale } params', async () => {
+ // This is the contract a history requeue (getRenderConfigForItem) emits,
+ // so it must round-trip without a bespoke shape.
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'styled clip',
+ loraFilenames: ['a.safetensors', 'b.safetensors'],
+ loraScales: [0.7, 1.0],
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ params: expect.objectContaining({
+ loras: [
+ { filename: 'a.safetensors', scale: 0.7 },
+ { filename: 'b.safetensors', scale: 1.0 },
+ ],
+ }),
+ }));
+ });
+
+ it('defaults a missing scale to 1.0 when fewer loraScales than loraFilenames', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'clip',
+ loraFilenames: ['a.safetensors'],
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({ loras: [{ filename: 'a.safetensors', scale: 1.0 }] }),
+ }));
+ });
+
+ it('rejects LoRAs on a non-ltx2 runtime with LORAS_REQUIRE_LTX2', async () => {
+ videoGenService.listVideoModels.mockReturnValueOnce([
+ { id: 'ltx_legacy', name: 'LTX legacy', runtime: 'mlx_video' },
+ ]);
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'clip',
+ modelId: 'ltx_legacy',
+ loraFilenames: ['a.safetensors'],
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('LORAS_REQUIRE_LTX2');
+ });
+
it('strips path-traversal segments from sourceImageFile via basename + prefix-check', async () => {
const r = await request(app).post('/api/video-gen/').send({
prompt: 'a cat',