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

feat: add HuggingFace search to video LoRA suggestions (#6500)

[._.]/ Adam Eivyebd73d46c035
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 78555f9771..6583ff5dc5 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -7,9 +7,9 @@
* deep-link that preselects the LoRA on the generation page.
*/
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { Link } from 'react-router';
-import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search, Activity } from 'lucide-react';
+import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search, Activity, PlayCircle } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
@@ -35,6 +35,7 @@ import {
clearCivitaiAuth,
getCivitaiSuggestions,
searchCivitaiLoras,
+ searchVideoLoras,
probeLoraEffect,
} from '../services/api';
@@ -674,10 +675,18 @@ function SuggestionsPanel({ suggestions, loading, mediaFilter = 'all', installed
);
}
-// Curated HuggingFace video LoRAs (LTX-Video). No keyword search / pagination
-// like the Civitai sections — it's a small hand-picked list installed via the
-// HF path. Installed-state matches the exact repo+file pair because a repo may
-// publish multiple independently installable LoRA versions.
+// Family filter for the live HuggingFace search below the curated list.
+const VIDEO_FAMILY_FILTERS = [
+ { id: 'all', label: 'All video' },
+ { id: VIDEO_LORA_FAMILIES.LTX_VIDEO, label: 'LTX-Video' },
+ { id: VIDEO_LORA_FAMILIES.MINIMAX_H3, label: 'MiniMax H3' },
+];
+
+// Curated HuggingFace video LoRAs (small hand-picked list, installed via the
+// HF path) PLUS a live keyword/author/repository search across all of
+// HuggingFace (#6500). Installed-state matches the exact repo+file pair
+// because a repo may publish multiple independently installable LoRA
+// versions, and a search result may offer more than one installable file.
function VideoSuggestionsSection({ cards, installedHfKeys, installingVideoKey, installingVideoProgress, videoInstallBusy, onInstall }) {
const list = cards || [];
return (
@@ -694,34 +703,274 @@ function VideoSuggestionsSection({ cards, installedHfKeys, installingVideoKey, i
<p className="text-xs text-gray-600 italic">No video LoRA suggestions yet.</p>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
- {list.map((card) => {
- const key = hfCardKey(card);
- return (
- <VideoSuggestionCard
- key={key}
- card={card}
- installed={installedHfKeys?.has(key)}
- installing={installingVideoKey === key}
- progress={installingVideoKey === key ? installingVideoProgress : null}
- // Disable every quick-install button while ANY HF install is in
- // flight (this card's, another card's, or the form's) — one at a time.
- busy={!!installingVideoKey || videoInstallBusy}
- onInstall={onInstall}
- />
- );
- })}
+ {list.map((card) => (
+ <VideoSuggestionCard
+ key={hfCardKey(card)}
+ card={card}
+ installedHfKeys={installedHfKeys}
+ installingVideoKey={installingVideoKey}
+ installingVideoProgress={installingVideoProgress}
+ // Disable every quick-install button while ANY HF install is in
+ // flight (this card's, another card's, or the form's) — one at a time.
+ busy={!!installingVideoKey || videoInstallBusy}
+ onInstall={onInstall}
+ />
+ ))}
</div>
)}
+ <VideoSearchSection
+ installedHfKeys={installedHfKeys}
+ installingVideoKey={installingVideoKey}
+ installingVideoProgress={installingVideoProgress}
+ videoInstallBusy={videoInstallBusy}
+ onInstall={onInstall}
+ />
</div>
);
}
-function VideoSuggestionCard({ card, installed, installing, progress, busy, onInstall }) {
- const pct = pctOf(progress);
+// Live search across all of HuggingFace for LTX-Video / MiniMax H3 LoRAs —
+// the video counterpart to SuggestionsSection's per-runner Civitai search
+// below. Kept as its own always-mounted subsection (not gated by the curated
+// list) so a curated fetch failure never hides the search box.
+function VideoSearchSection({ installedHfKeys, installingVideoKey, installingVideoProgress, videoInstallBusy, onInstall }) {
+ const [family, setFamily] = useState('all');
+ const [query, setQuery] = useState('');
+ const [author, setAuthor] = useState('');
+ const [activeQuery, setActiveQuery] = useState('');
+ const [activeAuthor, setActiveAuthor] = useState('');
+ // null = no search run yet (box not shown as "searched"); [] = a real empty result.
+ const [items, setItems] = useState(null);
+ const [cursor, setCursor] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ // Bumped on every fetch; a response is applied only if it's still the LATEST
+ // request — so switching family/query mid-flight can't have a slower older
+ // response clobber a faster newer one.
+ const requestIdRef = useRef(0);
+
+ const fetchPage = useCallback((q, a, fam, { append, useCursor }) => {
+ const requestId = requestIdRef.current + 1;
+ requestIdRef.current = requestId;
+ setLoading(true);
+ setError(null);
+ searchVideoLoras({ family: fam, query: q, author: a, cursor: useCursor, limit: 12 })
+ .then((res) => {
+ if (requestIdRef.current !== requestId) return; // superseded by a later request
+ const results = res?.items || [];
+ setCursor(res?.nextCursor || null);
+ setActiveQuery(q);
+ setActiveAuthor(a);
+ setItems((prev) => {
+ if (!append || prev === null) return results;
+ const seen = new Set(prev.map(hfCardKey));
+ return [...prev, ...results.filter((c) => !seen.has(hfCardKey(c)))];
+ });
+ })
+ .catch((err) => {
+ if (requestIdRef.current !== requestId) return;
+ setError(err?.message || 'HuggingFace search failed');
+ })
+ .finally(() => {
+ if (requestIdRef.current === requestId) setLoading(false);
+ });
+ }, []);
+
+ const handleSearch = (e) => {
+ e?.preventDefault?.();
+ if (loading) return;
+ fetchPage(query.trim(), author.trim(), family, { append: false, useCursor: null });
+ };
+
+ // Switching family re-runs whatever search is active (or the box's current
+ // values pre-submit) under the new filter — otherwise the header/family
+ // pills would show results from the family the user just left.
+ const handleFamilyChange = (nextFamily) => {
+ setFamily(nextFamily);
+ if (items !== null) fetchPage(activeQuery, activeAuthor, nextFamily, { append: false, useCursor: null });
+ };
+
+ const clearSearch = () => {
+ requestIdRef.current += 1; // invalidate any in-flight request
+ setQuery(''); setAuthor(''); setActiveQuery(''); setActiveAuthor('');
+ setItems(null); setCursor(null); setError(null); setLoading(false);
+ };
+
+ const loadMore = () => {
+ if (loading) return;
+ fetchPage(activeQuery, activeAuthor, family, { append: true, useCursor: cursor });
+ };
+
+ const retry = () => fetchPage(activeQuery, activeAuthor, family, { append: false, useCursor: null });
+
+ const list = items || [];
+ const hasSearched = items !== null;
+ const canLoadMore = hasSearched && !error && cursor !== null;
+
+ return (
+ <div className="mt-4 pt-4 border-t border-port-border/60">
+ <div className="flex items-baseline gap-3 mb-2">
+ <h3 className="text-sm font-medium text-gray-300">Search HuggingFace</h3>
+ {hasSearched && <span className="text-xs text-gray-600">{list.length}</span>}
+ </div>
+ <p className="text-xs text-gray-500 mb-2">
+ Search all of HuggingFace for LTX-Video / MiniMax H3 LoRAs by name, author, or repository.
+ </p>
+ <form onSubmit={handleSearch} className="flex flex-wrap gap-2 mb-3">
+ <div className="inline-flex rounded-lg border border-port-border overflow-hidden">
+ {VIDEO_FAMILY_FILTERS.map((f) => (
+ <button
+ key={f.id}
+ type="button"
+ onClick={() => handleFamilyChange(f.id)}
+ aria-pressed={family === f.id}
+ className={`px-2.5 py-1.5 text-xs font-medium transition-colors ${
+ family === f.id ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-gray-200'
+ }`}
+ >
+ {f.label}
+ </button>
+ ))}
+ </div>
+ <div className="relative flex-1 min-w-[160px] max-w-md">
+ <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-600 pointer-events-none" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search name or repository…"
+ aria-label="Search HuggingFace video LoRAs by name or repository"
+ className="w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"
+ />
+ </div>
+ <input
+ type="text"
+ value={author}
+ onChange={(e) => setAuthor(e.target.value)}
+ placeholder="Author (optional)"
+ aria-label="Filter HuggingFace video LoRAs by author"
+ className="w-32 bg-port-bg border border-port-border rounded px-3 py-1.5 text-xs text-gray-200 placeholder:text-gray-600"
+ />
+ <button
+ type="submit"
+ disabled={loading}
+ className="bg-port-accent/90 text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent disabled:opacity-50"
+ >
+ {loading ? 'Searching…' : 'Search'}
+ </button>
+ {hasSearched && (
+ <button
+ type="button"
+ onClick={clearSearch}
+ className="px-2 py-1.5 rounded text-xs text-gray-400 hover:text-gray-200 border border-port-border"
+ >
+ Clear
+ </button>
+ )}
+ </form>
+ {error && (
+ <Banner
+ tone="error"
+ size="sm"
+ align="center"
+ className="mb-3"
+ actions={(
+ <button type="button" onClick={retry} disabled={loading} className="underline hover:no-underline disabled:opacity-50">
+ {loading ? 'Retrying…' : 'Retry'}
+ </button>
+ )}
+ >
+ {error}
+ </Banner>
+ )}
+ {hasSearched && !error && list.length === 0 && !loading && (
+ <p className="text-xs text-gray-600 italic">No matching video LoRAs found on HuggingFace.</p>
+ )}
+ {list.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
+ {list.map((card) => (
+ <VideoSuggestionCard
+ key={hfCardKey(card)}
+ card={card}
+ installedHfKeys={installedHfKeys}
+ installingVideoKey={installingVideoKey}
+ installingVideoProgress={installingVideoProgress}
+ busy={!!installingVideoKey || videoInstallBusy}
+ onInstall={onInstall}
+ />
+ ))}
+ </div>
+ )}
+ {canLoadMore && (
+ <div className="mt-3 flex justify-center">
+ <button
+ type="button"
+ onClick={loadMore}
+ disabled={loading}
+ className="text-xs text-gray-300 hover:text-white px-4 py-1.5 rounded border border-port-border hover:border-port-accent/40 disabled:opacity-50 flex items-center gap-1.5"
+ >
+ {loading ? <BrailleSpinner text="Loading…" /> : <><Download size={12} /> Load more</>}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// Shared by the curated list and the live search. Owns its own install-key
+// (repo+file) so a search card offering several `.safetensors` files can let
+// the user pick one — `installingVideoKey`/`installedHfKeys` are matched
+// against the CURRENTLY SELECTED file, not just the card's recommended
+// default. Curated cards never carry more than one file, so this collapses
+// to the original behavior for them.
+function VideoSuggestionCard({ card, installedHfKeys, installingVideoKey, installingVideoProgress, busy, onInstall }) {
+ const fileOptions = Array.isArray(card.files) && card.files.length > 1 ? card.files : null;
+ const [selectedFile, setSelectedFile] = useState(card.file);
+ const [showPreview, setShowPreview] = useState(false);
+ const effectiveCard = fileOptions && selectedFile !== card.file ? { ...card, file: selectedFile } : card;
+ const key = hfCardKey(effectiveCard);
+ const installed = installedHfKeys?.has(key);
+ const installing = installingVideoKey === key;
+ const pct = pctOf(installing ? installingVideoProgress : null);
+ const inputId = `hf-video-file-${key}`;
return (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
- {card.previewImageUrl ? (
- <img src={card.previewImageUrl} alt="" className="w-full h-64 object-cover bg-port-bg" loading="lazy" referrerPolicy="no-referrer" />
+ {showPreview && card.previewVideoUrl ? (
+ // Mounted only after a click — the browser makes no network request
+ // for the clip until the user asks for it, and `controls` (no
+ // `autoPlay`) keeps playback itself opt-in too.
+ <video
+ src={card.previewVideoUrl}
+ controls
+ preload="none"
+ referrerPolicy="no-referrer"
+ className="w-full h-64 object-cover bg-black"
+ />
+ ) : card.previewImageUrl ? (
+ <div className="relative">
+ <img src={card.previewImageUrl} alt="" className="w-full h-64 object-cover bg-port-bg" loading="lazy" referrerPolicy="no-referrer" />
+ {card.previewVideoUrl && (
+ <button
+ type="button"
+ onClick={() => setShowPreview(true)}
+ className="absolute inset-0 flex items-center justify-center bg-black/20 hover:bg-black/40 text-white/90 hover:text-white transition-colors"
+ aria-label="Play example clip"
+ title="Play example clip"
+ >
+ <PlayCircle size={40} />
+ </button>
+ )}
+ </div>
+ ) : card.previewVideoUrl ? (
+ <button
+ type="button"
+ onClick={() => setShowPreview(true)}
+ className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-600 hover:text-gray-400"
+ aria-label="Play example clip"
+ title="Play example clip"
+ >
+ <PlayCircle size={32} />
+ </button>
) : (
<div className="w-full h-64 bg-port-bg flex items-center justify-center text-gray-700">
<Sparkles size={32} />
@@ -735,12 +984,31 @@ function VideoSuggestionCard({ card, installed, installing, progress, busy, onIn
</span>
</div>
{card.note && <p className="text-[11px] text-gray-400 italic break-words">{card.note}</p>}
+ {typeof card.downloads === 'number' && (
+ <div className="text-[10px] text-gray-600">↓ {card.downloads.toLocaleString()}</div>
+ )}
{card.description && (
<details className="text-[11px] text-gray-500">
<summary className="cursor-pointer hover:text-gray-300">Details</summary>
<p className="mt-1 text-[10px] leading-snug bg-port-bg p-1.5 rounded border border-port-border line-clamp-4">{card.description}</p>
</details>
)}
+ {fileOptions && (
+ <div>
+ <label htmlFor={inputId} className="block text-[10px] uppercase tracking-wide text-gray-500 mb-0.5">File</label>
+ <select
+ id={inputId}
+ value={selectedFile}
+ onChange={(e) => setSelectedFile(e.target.value)}
+ disabled={installed || installing}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"
+ >
+ {fileOptions.map((f) => (
+ <option key={f.file} value={f.file}>{f.file}{f.recommended ? ' (recommended)' : ''}</option>
+ ))}
+ </select>
+ </div>
+ )}
<div className="flex items-center gap-2 mt-auto">
{installed ? (
<button disabled className="flex-1 bg-port-success/20 text-port-success border border-port-success/30 px-3 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1">
@@ -749,7 +1017,7 @@ function VideoSuggestionCard({ card, installed, installing, progress, busy, onIn
) : (
<button
type="button"
- onClick={() => onInstall(card)}
+ onClick={() => onInstall(effectiveCard)}
disabled={installing || busy}
className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
>
diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsx
index 51af0f7986..551a0b6668 100644
--- a/client/src/pages/Loras.test.jsx
+++ b/client/src/pages/Loras.test.jsx
@@ -4,13 +4,13 @@
* confirm pair — one stray tap can never reach deleteLoraFull.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { clickStartDownload } from '../test/downloadPreflightConfirm.js';
import Loras from './Loras';
import {
listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeLoraEffect,
- previewLoraInstall, getCivitaiSuggestions, installLoraFromCivitai,
+ previewLoraInstall, getCivitaiSuggestions, installLoraFromCivitai, searchVideoLoras,
} from '../services/api';
vi.mock('../services/api', () => ({
@@ -26,6 +26,7 @@ vi.mock('../services/api', () => ({
clearCivitaiAuth: vi.fn(),
getCivitaiSuggestions: vi.fn(async () => ({ runners: {}, video: [], fetchedAt: null })),
searchCivitaiLoras: vi.fn(),
+ searchVideoLoras: vi.fn(),
probeLoraEffect: vi.fn(),
}));
@@ -255,6 +256,89 @@ describe('Loras video suggestion quick-install preflight', () => {
});
});
+// #6500 — searching HuggingFace directly (rather than the curated list) and
+// installing a hit. Also the "several installable files" case: the search
+// result offers two `.safetensors` siblings, so picking the non-default one
+// must be what actually installs.
+describe('Loras video LoRA search-to-install', () => {
+ const SEARCH_CARD = {
+ source: 'huggingface',
+ repo: 'someorg/some-ltx-lora',
+ revision: 'main',
+ file: 'pytorch_lora_weights.safetensors',
+ files: [
+ { file: 'variant-a.safetensors', recommended: false },
+ { file: 'pytorch_lora_weights.safetensors', recommended: true },
+ ],
+ name: 'some-ltx-lora',
+ description: 'A searchable LTX LoRA.',
+ runnerFamily: 'ltx-video',
+ downloads: 12,
+ previewImageUrl: null,
+ previewVideoUrl: null,
+ previewType: null,
+ hfUrl: 'https://huggingface.co/someorg/some-ltx-lora',
+ installUrl: 'https://huggingface.co/someorg/some-ltx-lora',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listLorasFull.mockResolvedValue([]);
+ getCivitaiSuggestions.mockResolvedValue({ runners: {}, video: [], fetchedAt: null });
+ searchVideoLoras.mockResolvedValue({ family: 'all', query: 'vhs', author: '', items: [SEARCH_CARD], nextCursor: null });
+ previewLoraInstall.mockResolvedValue({
+ kind: 'huggingface', destPath: 'lora-someorg-ltx-hf.safetensors', expectedBytes: 2048,
+ freeBytes: 1e12, requiredBytes: 2048, headroomBytes: 0, verdict: 'ok',
+ });
+ installLoraFromHuggingfaceStream.mockResolvedValue({ name: 'lora-someorg-ltx-hf.safetensors' });
+ });
+
+ it('searches HuggingFace, lets the user pick a non-default file, and installs that exact file', async () => {
+ renderPage();
+
+ const searchInput = await screen.findByLabelText('Search HuggingFace video LoRAs by name or repository');
+ const searchForm = searchInput.closest('form');
+ fireEvent.change(searchInput, { target: { value: 'vhs' } });
+ fireEvent.click(within(searchForm).getByRole('button', { name: 'Search' }));
+
+ expect(await screen.findByText('some-ltx-lora')).toBeInTheDocument();
+ expect(searchVideoLoras).toHaveBeenCalledWith(expect.objectContaining({ family: 'all', query: 'vhs', author: '' }));
+
+ // Pick the non-recommended file before installing.
+ fireEvent.change(screen.getByLabelText('File'), { target: { value: 'variant-a.safetensors' } });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Quick install' }));
+ expect(await screen.findByRole('button', { name: 'Start download' })).toBeInTheDocument();
+ expect(previewLoraInstall).toHaveBeenCalledWith(expect.objectContaining({
+ url: SEARCH_CARD.installUrl,
+ source: 'huggingface',
+ family: 'ltx-video',
+ file: 'variant-a.safetensors',
+ }));
+
+ await clickStartDownload();
+ await waitFor(() => expect(installLoraFromHuggingfaceStream).toHaveBeenCalledWith(
+ expect.objectContaining({ url: SEARCH_CARD.installUrl, family: 'ltx-video', file: 'variant-a.safetensors' }),
+ ));
+ });
+
+ it('shows a retryable error banner when the search request fails', async () => {
+ searchVideoLoras.mockRejectedValueOnce(new Error('HuggingFace search failed: 503'));
+ renderPage();
+
+ const searchInput = await screen.findByLabelText('Search HuggingFace video LoRAs by name or repository');
+ const searchForm = searchInput.closest('form');
+ fireEvent.change(searchInput, { target: { value: 'vhs' } });
+ fireEvent.click(within(searchForm).getByRole('button', { name: 'Search' }));
+
+ expect(await screen.findByText('HuggingFace search failed: 503')).toBeInTheDocument();
+
+ searchVideoLoras.mockResolvedValueOnce({ family: 'all', query: 'vhs', author: '', items: [SEARCH_CARD], nextCursor: null });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByText('some-ltx-lora')).toBeInTheDocument();
+ });
+});
+
// Adapter-effect diagnostic (#4872). The card seeds from the server's CACHED
// report and re-measures on demand; only a measured all-zero adapter is the
// alarming one, and the badge must never echo itself when there is no summary.
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 6690b48d45..3e9c309962 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -539,6 +539,21 @@ export const searchCivitaiLoras = ({ runner, query = '', cursor = null, limit, s
return request(`/loras/search?${params.toString()}`, { silent });
};
+// Live keyword/author/repository search across all of HuggingFace for video
+// LoRAs (LTX-Video / MiniMax H3) — the video-panel counterpart to
+// searchCivitaiLoras above. `family` omitted/'all' searches both families;
+// `cursor` is the previous page's `nextCursor`, passed back opaquely to page
+// forward. `silent` defaults true — the search box owns its own error state.
+export const searchVideoLoras = ({ family = 'all', query = '', author = '', cursor = null, limit, silent = true } = {}) => {
+ const params = new URLSearchParams();
+ if (family && family !== 'all') params.set('family', family);
+ if (query) params.set('query', query);
+ if (author) params.set('author', author);
+ if (cursor) params.set('cursor', cursor);
+ if (limit) params.set('limit', String(limit));
+ return request(`/loras/search/video?${params.toString()}`, { silent });
+};
+
// Civitai auth — read/save/clear the API key. The key never round-trips back
// to the client; the GET only returns `{ hasKey, source }`.
export const getCivitaiAuth = () => request('/loras/auth/civitai');
diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.js
index 4955b13e89..b63beaf31d 100644
--- a/server/lib/huggingfaceLora.js
+++ b/server/lib/huggingfaceLora.js
@@ -160,6 +160,58 @@ export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl =
return readResponseJson(res);
};
+// Host allowlist for a `cursor` continuation URL — see searchHuggingfaceLoraModels.
+const HF_SEARCH_HOST = 'huggingface.co';
+
+/**
+ * Public HF `/api/models` list-search endpoint — lightweight per-entry shape
+ * (id, tags, downloads, likes; no siblings/cardData). Backs the video-LoRA
+ * search catalog: candidates found here still need a full
+ * `fetchHuggingfaceModel()` per repo before they can be classified/installed.
+ *
+ * `cursor`, when passed, is used AS THE ENTIRE REQUEST URL rather than folded
+ * into new params — it's the opaque continuation link HF returned in the
+ * previous page's `Link: rel="next"` response header, which already encodes
+ * its own search/offset state. Only a `huggingface.co` URL is accepted (the
+ * caller's own prior response is the only legitimate source of this value,
+ * but it still crossed a third-party HTTP response once, so re-validate
+ * rather than trust it blindly).
+ *
+ * Returns `{ items, nextCursor }` — `nextCursor` is the next page's Link URL
+ * (string) or null when exhausted. fetchImpl is injectable for tests.
+ */
+export const searchHuggingfaceLoraModels = async ({ query, author, tag = 'lora', limit = 12, cursor = null, token, fetchImpl = fetch, signal } = {}) => {
+ let url;
+ if (cursor) {
+ if (!URL.canParse(cursor) || new URL(cursor).hostname.toLowerCase() !== HF_SEARCH_HOST) {
+ throw new ServerError('Invalid HuggingFace search cursor', { status: 400, code: 'HF_BAD_CURSOR' });
+ }
+ url = cursor;
+ } else {
+ const params = new URLSearchParams();
+ const trimmedQuery = typeof query === 'string' ? query.trim() : '';
+ const trimmedAuthor = typeof author === 'string' ? author.trim() : '';
+ if (trimmedQuery) params.set('search', trimmedQuery);
+ if (trimmedAuthor) params.set('author', trimmedAuthor);
+ if (tag) params.set('filter', tag);
+ params.set('limit', String(Math.max(1, Math.min(50, limit))));
+ params.set('sort', 'downloads');
+ params.set('direction', '-1');
+ url = `${HF_API}?${params.toString()}`;
+ }
+ const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) }, signal });
+ if (!res.ok) {
+ throw new ServerError(`HuggingFace search failed: ${res.status}`, { status: 502, code: 'HF_SEARCH_FAILED' });
+ }
+ const items = await readResponseJson(res, { fallback: [] });
+ const linkHeader = typeof res.headers?.get === 'function' ? res.headers.get('link') : null;
+ const nextMatch = typeof linkHeader === 'string' ? linkHeader.match(/<([^>]+)>;\s*rel="next"/) : null;
+ return {
+ items: Array.isArray(items) ? items : [],
+ nextCursor: nextMatch ? nextMatch[1] : null,
+ };
+};
+
// All sibling rfilenames of an HF model response (any extension). Shared by the
// LoRA picker and the base-model classifier (huggingfaceModel.js).
export const modelSiblingFilenames = (model) => {
diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.js
index 97f84ff39a..57420b26bb 100644
--- a/server/lib/huggingfaceLora.test.js
+++ b/server/lib/huggingfaceLora.test.js
@@ -10,6 +10,7 @@ import {
flux2VariantFromBlob,
buildHfLoraSidecar,
fetchHuggingfaceModel,
+ searchHuggingfaceLoraModels,
} from './huggingfaceLora.js';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from './runners.js';
@@ -297,3 +298,55 @@ describe('fetchHuggingfaceModel', () => {
expect(fetchImpl).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: controller.signal }));
});
});
+
+describe('searchHuggingfaceLoraModels', () => {
+ const listResponse = (items, { link = null } = {}) => ({
+ ok: true,
+ text: async () => JSON.stringify(items),
+ headers: { get: (name) => (name.toLowerCase() === 'link' ? link : null) },
+ });
+
+ it('builds a search+author+filter query and reads the Link "next" header', async () => {
+ let calledUrl;
+ const fetchImpl = vi.fn(async (url) => {
+ calledUrl = url;
+ return listResponse(
+ [{ id: 'someorg/some-ltx-lora', tags: ['ltx-video'] }],
+ { link: '<https://huggingface.co/api/models?search=vhs&cursor=ABC>; rel="next"' },
+ );
+ });
+ const out = await searchHuggingfaceLoraModels({ query: 'vhs', author: 'someorg', limit: 5, fetchImpl });
+ const parsed = new URL(calledUrl);
+ expect(parsed.searchParams.get('search')).toBe('vhs');
+ expect(parsed.searchParams.get('author')).toBe('someorg');
+ expect(parsed.searchParams.get('filter')).toBe('lora');
+ expect(parsed.searchParams.get('limit')).toBe('5');
+ expect(out.items).toHaveLength(1);
+ expect(out.nextCursor).toBe('https://huggingface.co/api/models?search=vhs&cursor=ABC');
+ });
+
+ it('returns a null nextCursor when the response carries no Link header', async () => {
+ const fetchImpl = async () => listResponse([]);
+ const out = await searchHuggingfaceLoraModels({ query: 'x', fetchImpl });
+ expect(out.nextCursor).toBeNull();
+ });
+
+ it('fetches the cursor URL directly instead of rebuilding params', async () => {
+ let calledUrl;
+ const fetchImpl = vi.fn(async (url) => { calledUrl = url; return listResponse([]); });
+ await searchHuggingfaceLoraModels({ query: 'ignored', cursor: 'https://huggingface.co/api/models?search=vhs&cursor=ABC', fetchImpl });
+ expect(calledUrl).toBe('https://huggingface.co/api/models?search=vhs&cursor=ABC');
+ });
+
+ it('rejects a cursor pointing at a non-HuggingFace host', async () => {
+ const fetchImpl = vi.fn();
+ await expect(searchHuggingfaceLoraModels({ cursor: 'https://evil.example/api/models', fetchImpl }))
+ .rejects.toMatchObject({ code: 'HF_BAD_CURSOR' });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a non-OK response as HF_SEARCH_FAILED', async () => {
+ const fetchImpl = async () => ({ ok: false, status: 503 });
+ await expect(searchHuggingfaceLoraModels({ query: 'x', fetchImpl })).rejects.toMatchObject({ code: 'HF_SEARCH_FAILED' });
+ });
+});
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 94e61ceeb5..06ffb3890b 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -24,10 +24,10 @@ import {
} from '../services/loras.js';
import { probeLoraEffect } from '../services/loraEffectProbe.js';
import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggestions.js';
-import { getVideoSuggestions } from '../services/videoLoraSuggestions.js';
+import { getVideoSuggestions, searchVideoLoras } from '../services/videoLoraSuggestions.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';
import { HF_LORA_FAMILIES } from '../lib/huggingfaceLora.js';
import { openSseStream } from '../lib/sseDownload.js';
@@ -85,6 +85,33 @@ router.get('/search', asyncHandler(async (req, res) => {
}));
}));
+// Live keyword/author/repository search across all of HuggingFace for video
+// LoRAs (LTX-Video / MiniMax H3) — backs the video search box + family filter
+// + "Load more" pagination on /models/loras (#6500). Short-cached server-side
+// per (family, query, author, cursor) since each page fans out one metadata
+// fetch per candidate repo. `family` omitted/'all' searches both families.
+// `cursor` is opaque — always the previous page's `nextCursor`, never built
+// by the client.
+const videoSearchQuerySchema = z.object({
+ family: z.enum([...Object.values(VIDEO_LORA_FAMILIES), 'all']).optional(),
+ query: z.preprocess(emptyToUndefined, z.string().max(120).optional()),
+ author: z.preprocess(emptyToUndefined, z.string().max(120).optional()),
+ // HF's opaque Link-header cursor is a base64-ish query blob — longer than a
+ // Civitai cursor, so it gets its own generous-but-bounded cap.
+ cursor: z.preprocess(emptyToUndefined, z.string().max(2048).optional()),
+ limit: z.coerce.number().int().min(1).max(24).optional(),
+});
+router.get('/search/video', asyncHandler(async (req, res) => {
+ const { family, query, author, cursor, limit } = validateRequest(videoSearchQuerySchema, req.query);
+ res.json(await searchVideoLoras({
+ family: family && family !== 'all' ? family : null,
+ query: query || '',
+ author: author || '',
+ cursor: cursor || null,
+ limit: limit || 12,
+ }));
+}));
+
// Civitai auth status — returns just whether a key is configured (the key
// itself never leaves the server). The 2-segment path keeps it from
// colliding with the `/:filename` LoRA endpoints below. `source` lets the
diff --git a/server/routes/loras.test.js b/server/routes/loras.test.js
index 342eb5ce2c..377b9cdcee 100644
--- a/server/routes/loras.test.js
+++ b/server/routes/loras.test.js
@@ -43,6 +43,14 @@ vi.mock('../services/videoLoraSuggestions.js', () => ({
getVideoSuggestions: vi.fn(async () => ([
{ source: 'huggingface', repo: 'fal/ltx2.3-audio-reactive-lora', name: 'LTX', runnerFamily: 'ltx-video' },
])),
+ searchVideoLoras: vi.fn(async ({ family, query, author, cursor, limit }) => ({
+ family: family || 'all',
+ query: query || '',
+ author: author || '',
+ items: [{ source: 'huggingface', repo: 'someorg/some-ltx-lora', file: 'lora.safetensors', runnerFamily: 'ltx-video' }],
+ nextCursor: 'NEXT',
+ _echo: { cursor, limit },
+ })),
}));
vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(async () => ({})),
@@ -51,6 +59,7 @@ vi.mock('../services/settings.js', () => ({
const { default: lorasRoutes } = await import('./loras.js');
const { searchLorasInFamily } = await import('../services/civitaiSuggestions.js');
+const { searchVideoLoras } = await import('../services/videoLoraSuggestions.js');
const { installFromHuggingface, listLoras } = await import('../services/loras.js');
const { probeLoraEffect } = await import('../services/loraEffectProbe.js');
@@ -201,6 +210,57 @@ describe('GET /api/loras/search', () => {
});
});
+describe('GET /api/loras/search/video', () => {
+ it('dispatches a family + keyword + author + cursor to the service', async () => {
+ const res = await request(makeApp())
+ .get('/api/loras/search/video?family=ltx-video&query=vhs&author=someorg&cursor=CUR&limit=20');
+ expect(res.status).toBe(200);
+ expect(res.body.items.length).toBe(1);
+ expect(res.body.nextCursor).toBe('NEXT');
+ expect(searchVideoLoras).toHaveBeenCalledWith({
+ family: 'ltx-video',
+ query: 'vhs',
+ author: 'someorg',
+ cursor: 'CUR',
+ limit: 20,
+ });
+ });
+
+ it('treats an omitted family as "all" (search both video families)', async () => {
+ const res = await request(makeApp()).get('/api/loras/search/video?query=vhs');
+ expect(res.status).toBe(200);
+ expect(searchVideoLoras).toHaveBeenCalledWith({
+ family: null,
+ query: 'vhs',
+ author: '',
+ cursor: null,
+ limit: 12,
+ });
+ });
+
+ it('treats an explicit family=all the same as omitting it', async () => {
+ await request(makeApp()).get('/api/loras/search/video?family=all');
+ expect(searchVideoLoras).toHaveBeenCalledWith(expect.objectContaining({ family: null }));
+ });
+
+ it('rejects an unknown family with 400', async () => {
+ const res = await request(makeApp()).get('/api/loras/search/video?family=sdxl');
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('rejects an over-long keyword with 400', async () => {
+ const res = await request(makeApp())
+ .get(`/api/loras/search/video?query=${'x'.repeat(121)}`);
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an out-of-range limit (> 24) with 400', async () => {
+ const res = await request(makeApp()).get('/api/loras/search/video?limit=999');
+ expect(res.status).toBe(400);
+ });
+});
+
describe('GET /api/loras/suggestions', () => {
it('merges the curated video LoRAs into the Civitai suggestion payload', async () => {
const res = await request(makeApp()).get('/api/loras/suggestions');
diff --git a/server/services/videoLoraSuggestions.js b/server/services/videoLoraSuggestions.js
index 1887e70586..84a2087f5f 100644
--- a/server/services/videoLoraSuggestions.js
+++ b/server/services/videoLoraSuggestions.js
@@ -16,7 +16,18 @@
*/
import { VIDEO_LORA_FAMILIES } from '../lib/runners.js';
-import { extractHfCardDescription, fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';
+import {
+ buildHfResolveUrl,
+ detectVideoLoraFamily,
+ extractHfCardDescription,
+ fetchHuggingfaceModel,
+ looksLikeLtxVideo,
+ looksLikeMiniMaxH3,
+ modelClassificationBlob,
+ modelSiblingFilenames,
+ pickHfLoraFile,
+ searchHuggingfaceLoraModels,
+} from '../lib/huggingfaceLora.js';
import { getHfToken } from './hfToken.js';
const TTL_MS = 60 * 60 * 1000; // 1 hour — matches the Civitai suggestion cache.
@@ -99,5 +110,183 @@ export const getVideoSuggestions = async ({ fetchImpl, force = false } = {}) =>
return items;
};
-// Test seam — clear the cache between tests.
-export const _resetVideoSuggestionsCache = () => { cache = null; };
+// ---------------------------------------------------------------------------
+// Searchable video-LoRA catalog (#6500) — live keyword/author search across
+// ALL of HuggingFace, not just the curated two-entry list above. Two-phase:
+//
+// 1. `searchHuggingfaceLoraModels()` hits HF's lightweight list-search endpoint
+// (id + tags, no siblings/cardData) — cheap, and already narrowed with
+// `filter=lora`. A quick classification pass over THAT payload (repo id
+// + tags only) drops anything that plainly isn't LTX/H3 before spending
+// a real request on it.
+// 2. Only the survivors get a full `fetchHuggingfaceModel()` fetch (bounded
+// to the page size — never more than `limit` repos per search), which
+// carries `cardData.base_model` and `siblings` — the two fields the
+// quick pass can't see. Re-classify from that full payload (the tags-only
+// guess is provisional) and reject anything with zero `.safetensors`
+// siblings (a base checkpoint or a non-adapter repo, not an installable
+// LoRA) instead of guessing from the largest file.
+//
+// Cached per (family, query, author, cursor) for a short TTL — long enough to
+// absorb repeat page loads and a user re-opening the same search, short
+// enough that a fresh HF upload shows up soon. Entries are evicted oldest-
+// first past SEARCH_CACHE_MAX_ENTRIES so an unbounded stream of distinct
+// queries can't grow the process's memory without limit.
+const SEARCH_TTL_MS = 10 * 60 * 1000; // 10 minutes
+const SEARCH_CACHE_MAX_ENTRIES = 40;
+const SEARCH_PAGE_LIMIT_DEFAULT = 12;
+const SEARCH_PAGE_LIMIT_MAX = 24;
+const SEARCH_LIST_TIMEOUT_MS = 10000; // the one list-search request
+const SEARCH_METADATA_TIMEOUT_MS = 8000; // PER repo metadata fetch — one slow repo must not stall the page
+
+const VIDEO_PREVIEW_RE = /\.(mp4|webm|mov)$/i;
+
+// searchCache: "<family>::<query>::<author>::<cursor>" -> { fetchedAt, result }
+const searchCache = new Map();
+
+const searchCacheKey = ({ family, query, author, cursor }) =>
+ `${family || 'all'}::${query || ''}::${author || ''}::${cursor || ''}`;
+
+const rememberSearch = (key, result) => {
+ searchCache.set(key, { fetchedAt: now(), result });
+ if (searchCache.size > SEARCH_CACHE_MAX_ENTRIES) {
+ // Map preserves insertion order — the first key is the oldest entry.
+ searchCache.delete(searchCache.keys().next().value);
+ }
+};
+
+// `family` is either a specific VIDEO_LORA_FAMILIES value or falsy/'all' for
+// "any recognized video family". `candidateFamily` is null when the repo
+// doesn't classify as a video LoRA at all — never a match regardless of filter.
+const matchesRequestedFamily = (family, candidateFamily) => {
+ if (!candidateFamily) return false;
+ if (!family || family === 'all') return true;
+ return candidateFamily === family;
+};
+
+// Cheap family guess from the list-search payload alone (repo id + tags —
+// no cardData.base_model, no siblings). Used only to decide which candidates
+// are worth a full metadata fetch; the real verdict comes from
+// detectVideoLoraFamily() against that full response.
+const guessFamilyFromListEntry = (item) => {
+ const blob = modelClassificationBlob({ repo: item?.id, model: { tags: item?.tags } });
+ if (looksLikeMiniMaxH3(blob)) return VIDEO_LORA_FAMILIES.MINIMAX_H3;
+ if (looksLikeLtxVideo(blob)) return VIDEO_LORA_FAMILIES.LTX_VIDEO;
+ return null;
+};
+
+// A sibling that looks like a rendered example clip — best-effort, absent on
+// most repos. Returned as a `resolve` URL exactly like the download link, so
+// the client can play it on user interaction only (no autoplay).
+const pickHfPreviewVideo = (repo, model) => {
+ const match = modelSiblingFilenames(model).find((f) => VIDEO_PREVIEW_RE.test(f));
+ return match ? buildHfResolveUrl(repo, 'main', match) : null;
+};
+
+// Build one search-result card. Unlike the curated cards above, `file` is a
+// best-effort RECOMMENDATION (pickHfLoraFile's heuristic) — `files` carries
+// every eligible `.safetensors` sibling so the UI can let the user pick a
+// different one instead of PortOS silently guessing on a multi-adapter repo.
+const buildSearchCard = ({ repo, item, model, family, files }) => {
+ const recommendedFile = pickHfLoraFile(model, null, null);
+ const previewVideoUrl = pickHfPreviewVideo(repo, model);
+ const previewImageUrl = pickHfPreview(model);
+ return {
+ source: 'huggingface',
+ repo,
+ revision: 'main',
+ file: recommendedFile,
+ files: files.map((file) => ({ file, recommended: file === recommendedFile })),
+ name: repo.split('/')[1] || repo,
+ description: extractHfCardDescription(model, DESCRIPTION_MAX_CHARS),
+ runnerFamily: family,
+ downloads: typeof item?.downloads === 'number' ? item.downloads : null,
+ likes: typeof item?.likes === 'number' ? item.likes : null,
+ previewImageUrl,
+ previewVideoUrl,
+ previewType: previewVideoUrl ? 'video' : (previewImageUrl ? 'image' : null),
+ hfUrl: `https://huggingface.co/${repo}`,
+ // Bare repo URL — the client sends `file` alongside it, exactly like the
+ // curated cards' install call, rather than encoding the file into the URL.
+ installUrl: `https://huggingface.co/${repo}`,
+ };
+};
+
+// Fetch + classify one search candidate. Returns null (never throws) on any
+// per-repo failure — a single bad/unreachable repo must not fail the whole
+// page of results.
+const buildSearchResult = async (item, { family, token, fetchImpl }) => {
+ const repo = item?.id;
+ if (!repo) return null;
+ const model = await fetchHuggingfaceModel(repo, { token, fetchImpl, signal: AbortSignal.timeout(SEARCH_METADATA_TIMEOUT_MS) })
+ .catch((err) => {
+ console.log(`⚠️ Video LoRA search metadata fetch failed for ${repo}: ${err?.message || err}`);
+ return null;
+ });
+ if (!model) return null;
+ // Re-classify from the FULL card — the list-level guess is provisional; a
+ // repo whose tags looked like a match can still turn out unrelated (or vice
+ // versa) once cardData.base_model is in hand.
+ const confirmedFamily = detectVideoLoraFamily({ repo, model });
+ if (!matchesRequestedFamily(family, confirmedFamily)) return null;
+ const files = modelSiblingFilenames(model).filter((f) => /\.safetensors$/i.test(f));
+ // No .safetensors sibling → a base checkpoint or a non-adapter repo, not an
+ // installable LoRA. Reject rather than guessing from the file list.
+ if (!files.length) return null;
+ return buildSearchCard({ repo, item, model, family: confirmedFamily, files });
+};
+
+/**
+ * Live (short-cached) search across all of HuggingFace for LTX-Video /
+ * MiniMax H3 LoRAs. Backs the /models/loras video search box + family filter
+ * + "Load more" pagination.
+ *
+ * `family`: a VIDEO_LORA_FAMILIES value, or null/'all' for both.
+ * `query`: keyword — HF matches it against the repo id/name, so pasting an
+ * exact `org/name` repository also works as an exact-repo search.
+ * `author`: HF username/org, filtered server-side by HF itself.
+ * `cursor`: the previous page's `nextCursor` (opaque) to page forward.
+ *
+ * Returns `{ family, query, author, items, nextCursor }`. Throws (uncached)
+ * on a failed list-search request — the UI surfaces that as a retryable
+ * error, matching searchLorasInFamily's Civitai-search contract. A per-repo
+ * metadata failure is swallowed and just drops that one candidate.
+ */
+export const searchVideoLoras = async ({ family = null, query = '', author = '', cursor = null, limit = SEARCH_PAGE_LIMIT_DEFAULT, fetchImpl, force = false } = {}) => {
+ const trimmedQuery = typeof query === 'string' ? query.trim() : '';
+ const trimmedAuthor = typeof author === 'string' ? author.trim() : '';
+ const boundedLimit = Math.max(1, Math.min(SEARCH_PAGE_LIMIT_MAX, limit || SEARCH_PAGE_LIMIT_DEFAULT));
+ const cacheKey = searchCacheKey({ family, query: trimmedQuery, author: trimmedAuthor, cursor });
+ const cached = searchCache.get(cacheKey);
+ if (!force && cached && now() - cached.fetchedAt < SEARCH_TTL_MS) return cached.result;
+
+ const token = (await getHfToken().catch(() => null)) || '';
+ const { items, nextCursor } = await searchHuggingfaceLoraModels({
+ query: trimmedQuery,
+ author: trimmedAuthor,
+ limit: boundedLimit,
+ cursor,
+ token,
+ fetchImpl,
+ signal: AbortSignal.timeout(SEARCH_LIST_TIMEOUT_MS),
+ });
+
+ // Cheap pre-filter on the list payload bounds the metadata fan-out to at
+ // most one fetch per candidate that's actually worth checking — never more
+ // than the page size itself.
+ const candidates = items.filter((item) => matchesRequestedFamily(family, guessFamilyFromListEntry(item)));
+ const built = await Promise.all(candidates.map((item) => buildSearchResult(item, { family, token, fetchImpl })));
+
+ const result = {
+ family: family || 'all',
+ query: trimmedQuery,
+ author: trimmedAuthor,
+ items: built.filter(Boolean),
+ nextCursor: nextCursor || null,
+ };
+ rememberSearch(cacheKey, result);
+ return result;
+};
+
+// Test seam — clear both caches between tests.
+export const _resetVideoSuggestionsCache = () => { cache = null; searchCache.clear(); };
diff --git a/server/services/videoLoraSuggestions.test.js b/server/services/videoLoraSuggestions.test.js
index 6e1729435a..a6015ac420 100644
--- a/server/services/videoLoraSuggestions.test.js
+++ b/server/services/videoLoraSuggestions.test.js
@@ -70,3 +70,173 @@ describe('getVideoSuggestions', () => {
expect(calls).toBeGreaterThan(after);
});
});
+
+describe('searchVideoLoras', () => {
+ // The list-search endpoint (HF_API with no path segment after it) and the
+ // per-repo metadata endpoint (HF_API/<repo>) share a base URL — route the
+ // fetchImpl on that distinction, exactly like the real HF API shapes them.
+ const listResponse = (items, { link = null } = {}) => ({
+ ok: true,
+ text: async () => JSON.stringify(items),
+ headers: { get: (name) => (name.toLowerCase() === 'link' ? link : null) },
+ });
+ const routedFetch = ({ list, models }) => async (url) => {
+ if (String(url).startsWith('https://huggingface.co/api/models?')) return listResponse(list);
+ const repo = String(url).replace('https://huggingface.co/api/models/', '');
+ const model = models[repo];
+ if (!model) return { ok: false, status: 404 };
+ return mockJsonResponse(model);
+ };
+
+ it('classifies from the full model card, includes the recommended file, and builds a usable card', async () => {
+ const fetchImpl = routedFetch({
+ list: [{ id: 'someorg/some-ltx-lora', tags: ['ltx-video'], downloads: 42, likes: 7 }],
+ models: {
+ 'someorg/some-ltx-lora': {
+ id: 'someorg/some-ltx-lora',
+ tags: ['ltx-video'],
+ cardData: { base_model: 'Lightricks/LTX-2.3', description: 'A test LTX LoRA.', thumbnail: 'https://hf/preview.png' },
+ siblings: [{ rfilename: 'lora.safetensors' }],
+ },
+ },
+ });
+ const result = await svc.searchVideoLoras({ family: 'ltx-video', query: 'lora', fetchImpl });
+ expect(result.items).toHaveLength(1);
+ const card = result.items[0];
+ expect(card.source).toBe('huggingface');
+ expect(card.repo).toBe('someorg/some-ltx-lora');
+ expect(card.revision).toBe('main');
+ expect(card.file).toBe('lora.safetensors');
+ expect(card.files).toEqual([{ file: 'lora.safetensors', recommended: true }]);
+ expect(card.runnerFamily).toBe('ltx-video');
+ expect(card.downloads).toBe(42);
+ expect(card.description).toBe('A test LTX LoRA.');
+ expect(card.previewImageUrl).toBe('https://hf/preview.png');
+ expect(card.installUrl).toBe('https://huggingface.co/someorg/some-ltx-lora');
+ });
+
+ it('rejects a candidate with no .safetensors sibling (base checkpoint, not an installable adapter)', async () => {
+ const fetchImpl = routedFetch({
+ list: [{ id: 'someorg/base-checkpoint', tags: ['ltx-video'] }],
+ models: {
+ 'someorg/base-checkpoint': {
+ id: 'someorg/base-checkpoint',
+ tags: ['ltx-video'],
+ siblings: [{ rfilename: 'model.bin' }],
+ },
+ },
+ });
+ const result = await svc.searchVideoLoras({ query: 'checkpoint', fetchImpl });
+ expect(result.items).toEqual([]);
+ });
+
+ it('lets the user pick when a repo publishes several LoRA files, instead of guessing', async () => {
+ const fetchImpl = routedFetch({
+ list: [{ id: 'someorg/multi-lora', tags: ['minimax-h3'] }],
+ models: {
+ 'someorg/multi-lora': {
+ id: 'someorg/multi-lora',
+ tags: ['minimax', 'h3'],
+ siblings: [
+ { rfilename: 'variant-a.safetensors' },
+ { rfilename: 'pytorch_lora_weights.safetensors' },
+ ],
+ },
+ },
+ });
+ const result = await svc.searchVideoLoras({ family: 'minimax-h3', query: 'multi', fetchImpl });
+ expect(result.items).toHaveLength(1);
+ const card = result.items[0];
+ // pickHfLoraFile prefers the canonical `pytorch_lora_weights.safetensors`
+ // name — but BOTH files stay listed so the UI can offer the other one.
+ expect(card.file).toBe('pytorch_lora_weights.safetensors');
+ expect(card.files).toEqual([
+ { file: 'variant-a.safetensors', recommended: false },
+ { file: 'pytorch_lora_weights.safetensors', recommended: true },
+ ]);
+ });
+
+ it('drops a repo that does not confirm as the requested family once the full card is in hand', async () => {
+ const fetchImpl = routedFetch({
+ // Tags look LTX-ish at the list level, but the full card's base_model
+ // says otherwise — the FULL classification is the real verdict.
+ list: [{ id: 'someorg/not-actually-video', tags: ['lora'] }],
+ models: {
+ 'someorg/not-actually-video': {
+ id: 'someorg/not-actually-video',
+ tags: ['lora'],
+ cardData: { base_model: 'black-forest-labs/FLUX.2-dev' },
+ siblings: [{ rfilename: 'lora.safetensors' }],
+ },
+ },
+ });
+ const result = await svc.searchVideoLoras({ query: 'x', fetchImpl });
+ expect(result.items).toEqual([]);
+ });
+
+ it('paginates: forwards the cursor and returns the next page token', async () => {
+ let capturedUrl = null;
+ const fetchImpl = async (url) => {
+ capturedUrl = url;
+ return listResponse([], { link: '<https://huggingface.co/api/models?cursor=PAGE3>; rel="next"' });
+ };
+ const result = await svc.searchVideoLoras({ query: 'x', cursor: 'https://huggingface.co/api/models?cursor=PAGE2', fetchImpl });
+ expect(capturedUrl).toBe('https://huggingface.co/api/models?cursor=PAGE2');
+ expect(result.nextCursor).toBe('https://huggingface.co/api/models?cursor=PAGE3');
+ });
+
+ it('tolerates one candidate failing its metadata fetch without dropping the rest of the page', async () => {
+ const fetchImpl = routedFetch({
+ list: [
+ { id: 'someorg/unreachable', tags: ['ltx-video'] },
+ { id: 'someorg/reachable', tags: ['ltx-video'] },
+ ],
+ models: {
+ // 'someorg/unreachable' intentionally absent → routedFetch 404s it.
+ 'someorg/reachable': {
+ id: 'someorg/reachable',
+ tags: ['ltx-video'],
+ siblings: [{ rfilename: 'lora.safetensors' }],
+ },
+ },
+ });
+ const result = await svc.searchVideoLoras({ family: 'ltx-video', query: 'x', fetchImpl });
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].repo).toBe('someorg/reachable');
+ });
+
+ it('caches identical (family, query, author, cursor) searches within the TTL', async () => {
+ let calls = 0;
+ const fetchImpl = async (url) => {
+ calls += 1;
+ if (String(url).startsWith('https://huggingface.co/api/models?')) return listResponse([]);
+ return { ok: false, status: 404 };
+ };
+ await svc.searchVideoLoras({ query: 'repeat', fetchImpl });
+ const after = calls;
+ await svc.searchVideoLoras({ query: 'repeat', fetchImpl });
+ expect(calls).toBe(after);
+ });
+
+ it('force=true busts the search cache', async () => {
+ let calls = 0;
+ const fetchImpl = async (url) => {
+ calls += 1;
+ if (String(url).startsWith('https://huggingface.co/api/models?')) return listResponse([]);
+ return { ok: false, status: 404 };
+ };
+ await svc.searchVideoLoras({ query: 'repeat', fetchImpl });
+ const after = calls;
+ await svc.searchVideoLoras({ query: 'repeat', fetchImpl, force: true });
+ expect(calls).toBeGreaterThan(after);
+ });
+
+ it('bubbles a failed list-search request (uncached) so the UI can offer a retry', async () => {
+ const fetchImpl = async () => ({ ok: false, status: 503 });
+ await expect(svc.searchVideoLoras({ query: 'x', fetchImpl })).rejects.toMatchObject({ code: 'HF_SEARCH_FAILED' });
+ // A failed top-level request must not poison the cache — retrying with a
+ // working fetchImpl should succeed rather than replaying the failure.
+ const retryFetch = routedFetch({ list: [], models: {} });
+ await expect(svc.searchVideoLoras({ query: 'x', fetchImpl: retryFetch })).resolves.toMatchObject({ items: [] });
+ });
+});