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 Hugging Face local model search

Adam Eivydbf6a500f443
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index e9fec080cb..0762bfe152 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -4,7 +4,7 @@ import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import { formatBytes } from '../../utils/formatters';
import {
- getLocalLlmStatus, getLocalLlmCatalog, installLocalLlmModel,
+ getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, controlOllamaService
} from '../../services/api';
import socket from '../../services/socket';
@@ -188,7 +188,10 @@ export function LocalLlmTab() {
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState('ollama');
+ const [catalogSource, setCatalogSource] = useState('recommended');
const [catalog, setCatalog] = useState([]);
+ const [catalogLoading, setCatalogLoading] = useState(false);
+ const [catalogError, setCatalogError] = useState('');
const [activeCategory, setActiveCategory] = useState('all');
const [query, setQuery] = useState('');
const [manualId, setManualId] = useState('');
@@ -197,6 +200,7 @@ export function LocalLlmTab() {
const [confirmAction, setConfirmAction] = useState(null);
const progressTimer = useRef(null);
const statusRequestId = useRef(0);
+ const catalogRequestId = useRef(0);
const selectedInitialized = useRef(false);
const loadStatus = useCallback(() => {
@@ -220,18 +224,34 @@ export function LocalLlmTab() {
});
}, []);
- const loadCatalog = useCallback((backend, q) => {
- getLocalLlmCatalog(backend, q)
- .then((r) => setCatalog(r.models || []))
- .catch(() => setCatalog([]));
- }, []);
+ const loadCatalog = useCallback((backend, q, source = catalogSource, category = activeCategory) => {
+ const requestId = ++catalogRequestId.current;
+ setCatalogLoading(true);
+ setCatalogError('');
+ const request = source === 'huggingface'
+ ? getLocalLlmHuggingFaceSearch(backend, q, category, 18)
+ : getLocalLlmCatalog(backend, q);
+ return request
+ .then((r) => {
+ if (requestId !== catalogRequestId.current) return;
+ setCatalog(r.models || []);
+ })
+ .catch((err) => {
+ if (requestId !== catalogRequestId.current) return;
+ setCatalog([]);
+ setCatalogError(source === 'huggingface' ? (err?.message || 'Hugging Face search failed') : '');
+ })
+ .finally(() => {
+ if (requestId === catalogRequestId.current) setCatalogLoading(false);
+ });
+ }, [activeCategory, catalogSource]);
useEffect(() => { loadStatus(); }, [loadStatus]);
// Debounce so typing in the search box doesn't fire a request per keystroke.
useEffect(() => {
- const t = setTimeout(() => loadCatalog(selected, query), 250);
+ const t = setTimeout(() => loadCatalog(selected, query, catalogSource, activeCategory), catalogSource === 'huggingface' ? 450 : 250);
return () => clearTimeout(t);
- }, [selected, query, loadCatalog]);
+ }, [selected, query, catalogSource, activeCategory, loadCatalog]);
useEffect(() => {
const handleProgress = (data) => {
@@ -240,7 +260,7 @@ export function LocalLlmTab() {
if (data.event === 'complete') {
progressTimer.current = setTimeout(() => setProgressMsg(''), 3000);
loadStatus();
- loadCatalog(selected, query);
+ loadCatalog(selected, query, catalogSource, activeCategory);
}
if (data.event === 'error') {
progressTimer.current = setTimeout(() => setProgressMsg(''), 5000);
@@ -251,7 +271,7 @@ export function LocalLlmTab() {
socket.off('localLlm:progress', handleProgress);
clearTimeout(progressTimer.current);
};
- }, [loadStatus, loadCatalog, selected, query]);
+ }, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);
const runAction = useCallback((key, fn, successMsg) => {
setConfirmAction(null);
@@ -270,11 +290,11 @@ export function LocalLlmTab() {
}) : prev);
}
loadStatus();
- loadCatalog(selected, query);
+ loadCatalog(selected, query, catalogSource, activeCategory);
})
.catch(() => { /* request() surfaces API errors as a toast */ })
.finally(() => setActionInProgress(null));
- }, [loadStatus, loadCatalog, selected, query]);
+ }, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);
const busy = actionInProgress != null;
const selectedData = status?.[selected];
@@ -289,9 +309,10 @@ export function LocalLlmTab() {
.map((id) => ({ id, label: categoryLabel(id), count: counts.get(id) }));
}, [catalog]);
const visibleCatalogGroups = useMemo(() => {
- const categoryIds = activeCategory === 'all'
+ const filterCategory = catalogSource === 'huggingface' ? 'all' : activeCategory;
+ const categoryIds = filterCategory === 'all'
? catalogCategories.map((c) => c.id)
- : [activeCategory];
+ : [filterCategory];
return categoryIds
.map((category) => ({
category,
@@ -299,7 +320,7 @@ export function LocalLlmTab() {
models: catalog.filter((model) => (model.category || 'chat') === category)
}))
.filter((group) => group.models.length > 0);
- }, [activeCategory, catalog, catalogCategories]);
+ }, [activeCategory, catalog, catalogCategories, catalogSource]);
// LM Studio's REST fallback returns { pending: true } — the download was only
// queued, not finished — so don't claim "installed" in that case.
@@ -381,16 +402,29 @@ export function LocalLlmTab() {
<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
<h2 className="text-sm font-medium text-gray-300">Models</h2>
- <div className="flex items-center gap-1.5">
- {BACKENDS.map((b) => (
- <button
- key={b.id}
- onClick={() => { setSelected(b.id); setActiveCategory('all'); }}
- className={`px-2.5 py-1 text-xs rounded transition-colors ${selected === b.id ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}
- >
- {b.label}
- </button>
- ))}
+ <div className="flex items-center gap-2 flex-wrap justify-end">
+ <div className="flex items-center gap-1.5">
+ {['recommended', 'huggingface'].map((source) => (
+ <button
+ key={source}
+ onClick={() => { setCatalogSource(source); setActiveCategory('all'); }}
+ className={`px-2.5 py-1 text-xs rounded transition-colors ${catalogSource === source ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ {source === 'recommended' ? 'Recommended' : 'Hugging Face'}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-1.5">
+ {BACKENDS.map((b) => (
+ <button
+ key={b.id}
+ onClick={() => { setSelected(b.id); setActiveCategory('all'); }}
+ className={`px-2.5 py-1 text-xs rounded transition-colors ${selected === b.id ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ {b.label}
+ </button>
+ ))}
+ </div>
</div>
</div>
@@ -432,7 +466,7 @@ export function LocalLlmTab() {
id="llm-catalog-search"
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder={`Search the ${labelFor(selected)} catalog…`}
+ placeholder={catalogSource === 'huggingface' ? 'Search Hugging Face GGUF models…' : `Search the ${labelFor(selected)} catalog…`}
className="flex-1 bg-transparent py-2 text-sm text-white placeholder-gray-600 focus:outline-none"
/>
</div>
@@ -475,6 +509,16 @@ export function LocalLlmTab() {
</div>
)}
+ {catalogLoading && (
+ <div className="flex items-center gap-2 text-xs text-gray-400">
+ <BrailleSpinner />
+ {catalogSource === 'huggingface' ? 'Searching Hugging Face' : 'Loading recommendations'}
+ </div>
+ )}
+ {catalogError && (
+ <p className="text-xs text-port-warning">{catalogError}</p>
+ )}
+
{/* Catalog cards */}
<div className="space-y-4">
{visibleCatalogGroups.map((group) => (
@@ -492,6 +536,8 @@ export function LocalLlmTab() {
<div className="flex items-center gap-1.5 flex-wrap text-[11px] text-gray-600 mt-1">
<span className="text-gray-500">{categoryLabel(m.category)}</span>
<span>{m.size}</span>
+ {m.source === 'huggingface' && <span>{m.downloads?.toLocaleString?.() || 0} downloads</span>}
+ {m.source === 'huggingface' && m.license && <span>{m.license}</span>}
{(m.capabilities || []).map((capability) => (
<span key={capability} className="px-1.5 py-0.5 bg-port-border/60 rounded">{capability}</span>
))}
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 376ca993e8..f0264f79f5 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -7,6 +7,9 @@ export const getLocalLlmStatus = () => request('/local-llm/status');
export const getLocalLlmCatalog = (backend, q = '') =>
request(`/local-llm/catalog?backend=${encodeURIComponent(backend)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);
+export const getLocalLlmHuggingFaceSearch = (backend, q = '', category = 'all', limit = 12) =>
+ request(`/local-llm/huggingface-search?backend=${encodeURIComponent(backend)}&category=${encodeURIComponent(category)}&limit=${encodeURIComponent(limit)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);
+
export const installLocalLlmModel = (backend, modelId) =>
request('/local-llm/install', { method: 'POST', body: JSON.stringify({ backend, modelId }) });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 914aca0704..739566bc17 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1063,6 +1063,12 @@ export const localLlmMigrateSchema = z.object({
});
export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });
export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop', 'enable', 'disable']) });
+export const localLlmHuggingFaceSearchSchema = z.object({
+ backend: localLlmBackendSchema,
+ q: z.string().max(160).optional().default(''),
+ category: z.string().max(40).optional().default('all'),
+ limit: z.coerce.number().int().min(1).max(30).optional().default(12),
+});
/**
* Validate data against a Zod schema, throwing on failure.
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index d8ba7c08c3..61eb236ba1 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -17,9 +17,11 @@ import {
localLlmSwitchSchema,
localLlmMigrateSchema,
localLlmInstallBackendSchema,
- localLlmOllamaServiceSchema
+ localLlmOllamaServiceSchema,
+ localLlmHuggingFaceSearchSchema
} from '../lib/validation.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
+import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'
import {
getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, controlOllamaServer
} from '../services/localLlm.js'
@@ -45,6 +47,15 @@ router.get('/catalog', asyncHandler(async (req, res) => {
res.json({ backend, models })
}))
+// GET /api/local-llm/huggingface-search?backend=ollama&q=qwen&category=coding
+// Live Hub discovery for GGUF-compatible community models.
+router.get('/huggingface-search', asyncHandler(async (req, res) => {
+ const { backend, q, category, limit } = validateRequest(localLlmHuggingFaceSearchSchema, req.query)
+ const installed = (await listModels(backend)).map((m) => m.id)
+ const models = await searchHuggingFaceModels({ backend, query: q, category, limit, installedIds: installed })
+ res.json({ backend, source: 'huggingface', models })
+}))
+
// POST /api/local-llm/install-backend — install the backend app/binary itself
// (Homebrew on macOS, official script for Ollama on Linux). Streams progress.
router.post('/install-backend', asyncHandler(async (req, res) => {
diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.js
new file mode 100644
index 0000000000..f715b03e7b
--- /dev/null
+++ b/server/services/huggingFaceCatalog.js
@@ -0,0 +1,267 @@
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
+import { LOCAL_LLM_CATEGORIES, isBackend } from '../lib/localLlmCatalog.js'
+
+const HF_API_BASE = 'https://huggingface.co/api/models'
+const HF_TIMEOUT_MS = 12_000
+
+const CATEGORY_IDS = new Set(LOCAL_LLM_CATEGORIES.map((c) => c.id))
+const CATEGORY_SEARCH = {
+ chat: 'instruct chat gguf',
+ reasoning: 'reasoning thinking gguf',
+ coding: 'coding coder agentic code gguf',
+ vision: 'vision image text gguf',
+ embedding: 'embedding sentence-transformers gguf',
+ lightweight: 'small 4b 3b 2b gguf',
+ multilingual: 'multilingual qwen llama gguf'
+}
+
+const TRUSTED_PUBLISHERS = new Set([
+ 'unsloth',
+ 'bartowski',
+ 'ggml-org',
+ 'lmstudio-community',
+ 'mradermacher',
+ 'qwen',
+ 'meta-llama',
+ 'mistralai',
+ 'google',
+ 'microsoft',
+ 'nomic-ai',
+ 'ibm-granite'
+])
+
+const QUANT_PRIORITY = [
+ 'UD-Q4_K_XL',
+ 'UD-Q4_K_M',
+ 'Q4_K_M',
+ 'Q4_K_S',
+ 'IQ4_XS',
+ 'UD-IQ4_XS',
+ 'Q5_K_M',
+ 'Q6_K',
+ 'Q8_0',
+ 'BF16',
+ 'F16'
+]
+
+const normalizeText = (value) => String(value || '').trim()
+
+function normalizeInstalledForBackend(backend, id) {
+ const raw = normalizeText(id).toLowerCase().replace(/:latest$/, '')
+ if (backend === 'ollama') return raw
+ return raw.split('/').pop().replace(/[-.]gguf$/i, '')
+}
+
+function repoIdOf(model) {
+ return normalizeText(model?.modelId || model?.id || model?.name)
+}
+
+function publisherOf(repoId) {
+ return repoId.split('/')[0]?.toLowerCase() || ''
+}
+
+function tagsOf(model) {
+ return Array.isArray(model?.tags) ? model.tags.map((tag) => String(tag).toLowerCase()) : []
+}
+
+function siblingsOf(model) {
+ return Array.isArray(model?.siblings) ? model.siblings : []
+}
+
+function ggufFilesOf(model) {
+ return siblingsOf(model)
+ .map((s) => ({ name: normalizeText(s.rfilename || s.name), size: Number.isFinite(s.size) ? s.size : null }))
+ .filter((file) => /\.gguf$/i.test(file.name))
+}
+
+function hasGgufSignal(model) {
+ const repoId = repoIdOf(model).toLowerCase()
+ const tags = tagsOf(model)
+ return repoId.includes('gguf') || tags.includes('gguf') || ggufFilesOf(model).length > 0
+}
+
+function quantFromFilename(filename) {
+ const stem = normalizeText(filename).split('/').pop().replace(/\.gguf$/i, '')
+ const match = stem.match(/(?:UD-)?(?:IQ\d(?:_[A-Z0-9]+)*|Q\d(?:_[A-Z0-9]+)*|BF16|F16)$/i)
+ return match?.[0] || null
+}
+
+function pickGgufFile(model) {
+ const files = ggufFilesOf(model)
+ if (files.length === 0) return null
+ return files
+ .map((file) => {
+ const quant = quantFromFilename(file.name)
+ const priority = quant ? QUANT_PRIORITY.findIndex((q) => q.toLowerCase() === quant.toLowerCase()) : -1
+ return { ...file, quant, priority: priority === -1 ? 999 : priority }
+ })
+ .sort((a, b) => a.priority - b.priority || (a.size || Number.MAX_SAFE_INTEGER) - (b.size || Number.MAX_SAFE_INTEGER))[0]
+}
+
+function formatBytes(bytes) {
+ if (!Number.isFinite(bytes) || bytes <= 0) return null
+ const units = ['B', 'KB', 'MB', 'GB', 'TB']
+ let value = bytes
+ let idx = 0
+ while (value >= 1024 && idx < units.length - 1) {
+ value /= 1024
+ idx++
+ }
+ return `${value >= 10 || idx === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[idx]}`
+}
+
+function extractParams(repoId) {
+ const match = repoId.match(/(\d+(?:\.\d+)?)\s*b(?:[-_ ]?a(\d+)b)?/i)
+ if (!match) return null
+ return match[2] ? `${match[1]}B / ${match[2]}B active` : `${match[1]}B`
+}
+
+function classifyModel(model, requestedCategory) {
+ if (CATEGORY_IDS.has(requestedCategory) && requestedCategory !== 'all') return requestedCategory
+ const haystack = `${repoIdOf(model)} ${(tagsOf(model) || []).join(' ')} ${model?.pipeline_tag || ''}`.toLowerCase()
+ if (/(embed|sentence-transformers|feature-extraction)/.test(haystack)) return 'embedding'
+ if (/(vision|vl|llava|image-text|multimodal|mmproj)/.test(haystack)) return 'vision'
+ if (/(code|coder|coding|devstral|starcoder|deepseek-coder|repo)/.test(haystack)) return 'coding'
+ if (/(reason|thinking|r1|qwq)/.test(haystack)) return 'reasoning'
+ if (/(1b|2b|3b|4b|small|mini|tiny|smol)/.test(haystack)) return 'lightweight'
+ if (/(multilingual|qwen|aya|bloom|command-r)/.test(haystack)) return 'multilingual'
+ return 'chat'
+}
+
+function capabilitiesFor(model, category) {
+ const tags = tagsOf(model)
+ const caps = new Set()
+ if (category !== 'embedding') caps.add('chat')
+ if (category === 'coding') caps.add('code')
+ if (category === 'reasoning') caps.add('reasoning')
+ if (category === 'vision') caps.add('vision')
+ if (category === 'embedding') caps.add('embeddings')
+ if (tags.includes('tools') || tags.includes('tool-calling') || /tool/i.test(repoIdOf(model))) caps.add('tools')
+ return [...caps]
+}
+
+function licenseOf(model) {
+ const cardLicense = normalizeText(model?.cardData?.license || model?.license)
+ if (cardLicense) return cardLicense
+ const tag = tagsOf(model).find((t) => t.startsWith('license:'))
+ return tag ? tag.replace(/^license:/, '') : null
+}
+
+function scoreModel(model, category, file) {
+ const repoId = repoIdOf(model)
+ const publisher = publisherOf(repoId)
+ const tags = tagsOf(model)
+ const downloads = Number(model?.downloads || 0)
+ const likes = Number(model?.likes || 0)
+ const updatedAt = Date.parse(model?.lastModified || model?.last_modified || model?.updatedAt || '')
+ const daysOld = Number.isFinite(updatedAt) ? (Date.now() - updatedAt) / 86_400_000 : null
+ const categoryText = `${repoId} ${tags.join(' ')} ${model?.pipeline_tag || ''}`.toLowerCase()
+
+ let score = 0
+ score += Math.log10(downloads + 1) * 12
+ score += Math.log10(likes + 1) * 8
+ if (TRUSTED_PUBLISHERS.has(publisher)) score += 22
+ if (file) score += 18
+ if (/gguf/i.test(repoId) || tags.includes('gguf')) score += 10
+ if (category !== 'chat' && CATEGORY_SEARCH[category]?.split(/\s+/).some((term) => categoryText.includes(term))) score += 12
+ if (daysOld != null && daysOld <= 180) score += 8
+ if (licenseOf(model)) score += 4
+ if (/(uncensored|abliterated|nsfw)/i.test(repoId)) score -= 12
+ return Math.round(score)
+}
+
+function displayName(repoId) {
+ return repoId.split('/').pop().replace(/[-_]?gguf$/i, '').replace(/[-_]+/g, ' ').trim() || repoId
+}
+
+function installIdForBackend(backend, repoId, file) {
+ if (backend === 'lmstudio') return repoId
+ const quant = file?.quant
+ return `hf.co/${repoId}${quant ? `:${quant}` : ''}`
+}
+
+function isInstalled(backend, result, installedIds) {
+ const installed = new Set(installedIds.map((id) => normalizeInstalledForBackend(backend, id)))
+ if (installed.has(normalizeInstalledForBackend(backend, result.id))) return true
+ if (backend === 'lmstudio') {
+ return installed.has(normalizeInstalledForBackend(backend, result.repository))
+ }
+ return false
+}
+
+function toResult(model, backend, requestedCategory, installedIds) {
+ const repoId = repoIdOf(model)
+ if (!repoId || !repoId.includes('/')) return null
+ const file = pickGgufFile(model)
+ const category = classifyModel(model, requestedCategory)
+ const id = installIdForBackend(backend, repoId, file)
+ const score = scoreModel(model, category, file)
+ const result = {
+ id,
+ key: repoId,
+ name: displayName(repoId),
+ category,
+ params: extractParams(repoId) || 'HF',
+ size: formatBytes(file?.size) || (file?.quant || 'GGUF'),
+ family: repoId.split('/').pop().split(/[-_]/)[0]?.toLowerCase() || 'huggingface',
+ description: model?.cardData?.summary || model?.cardData?.description || 'Community Hugging Face GGUF model.',
+ capabilities: capabilitiesFor(model, category),
+ installed: false,
+ source: 'huggingface',
+ repository: repoId,
+ publisher: publisherOf(repoId),
+ downloads: Number(model?.downloads || 0),
+ likes: Number(model?.likes || 0),
+ updatedAt: model?.lastModified || model?.last_modified || model?.updatedAt || null,
+ license: licenseOf(model),
+ quant: file?.quant || null,
+ score
+ }
+ result.installed = isInstalled(backend, result, installedIds)
+ return result
+}
+
+async function fetchModels(search, limit, useGgufFilter) {
+ const params = new URLSearchParams({
+ search,
+ sort: 'downloads',
+ direction: '-1',
+ limit: String(limit),
+ full: 'true'
+ })
+ if (useGgufFilter) params.set('filter', 'gguf')
+
+ const headers = { Accept: 'application/json' }
+ const token = process.env.HUGGINGFACE_TOKEN || process.env.HF_TOKEN
+ if (token) headers.Authorization = `Bearer ${token}`
+
+ const response = await fetchWithTimeout(`${HF_API_BASE}?${params.toString()}`, { headers }, HF_TIMEOUT_MS)
+ if (!response.ok) {
+ const text = await response.text().catch(() => '')
+ throw new Error(`Hugging Face search failed: ${response.status}${text ? ` — ${text.slice(0, 160)}` : ''}`)
+ }
+ const data = await response.json()
+ return Array.isArray(data) ? data : []
+}
+
+export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [] }) {
+ if (!isBackend(backend)) return []
+ const requestedCategory = CATEGORY_IDS.has(category) ? category : 'all'
+ const search = normalizeText(query) || CATEGORY_SEARCH[requestedCategory] || 'gguf'
+ const fetchLimit = Math.max(limit * 3, 30)
+ let models = await fetchModels(search, fetchLimit, true)
+ if (models.length === 0) models = await fetchModels(search, fetchLimit, false)
+
+ const seen = new Set()
+ return models
+ .filter(hasGgufSignal)
+ .map((model) => toResult(model, backend, requestedCategory, installedIds))
+ .filter(Boolean)
+ .filter((model) => {
+ if (seen.has(model.repository)) return false
+ seen.add(model.repository)
+ return true
+ })
+ .sort((a, b) => b.score - a.score || b.downloads - a.downloads)
+ .slice(0, limit)
+}
diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.js
new file mode 100644
index 0000000000..a2fe6bfed7
--- /dev/null
+++ b/server/services/huggingFaceCatalog.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { searchHuggingFaceModels } from './huggingFaceCatalog.js'
+
+const response = (body, ok = true) => ({
+ ok,
+ status: ok ? 200 : 500,
+ json: vi.fn(async () => body),
+ text: vi.fn(async () => JSON.stringify(body))
+})
+
+describe('huggingFaceCatalog', () => {
+ beforeEach(() => {
+ vi.stubGlobal('fetch', vi.fn())
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it('maps GGUF search results to Ollama hf.co install ids with preferred quants', async () => {
+ fetch.mockResolvedValue(response([
+ {
+ modelId: 'unsloth/Qwen3.6-35B-A3B-GGUF',
+ downloads: 100000,
+ likes: 1000,
+ tags: ['gguf', 'qwen', 'image-text-to-text', 'license:apache-2.0'],
+ lastModified: new Date().toISOString(),
+ siblings: [
+ { rfilename: 'Qwen3.6-35B-A3B-UD-IQ2_XXS.gguf', size: 13_000_000_000 },
+ { rfilename: 'Qwen3.6-35B-A3B-UD-Q4_K_M.gguf', size: 24_000_000_000 }
+ ]
+ }
+ ]))
+
+ const results = await searchHuggingFaceModels({
+ backend: 'ollama',
+ query: 'qwen3.6',
+ category: 'coding',
+ installedIds: []
+ })
+
+ expect(results[0]).toMatchObject({
+ id: 'hf.co/unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M',
+ repository: 'unsloth/Qwen3.6-35B-A3B-GGUF',
+ category: 'coding',
+ source: 'huggingface',
+ quant: 'UD-Q4_K_M',
+ license: 'apache-2.0'
+ })
+ expect(results[0].capabilities).toEqual(expect.arrayContaining(['chat', 'code']))
+ })
+
+ it('returns LM Studio repo ids and marks installed repos', async () => {
+ fetch.mockResolvedValue(response([
+ {
+ id: 'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF',
+ downloads: 10,
+ likes: 2,
+ tags: ['gguf'],
+ siblings: [{ rfilename: 'Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf', size: 4_700_000_000 }]
+ }
+ ]))
+
+ const results = await searchHuggingFaceModels({
+ backend: 'lmstudio',
+ query: 'llama',
+ installedIds: ['bartowski/Meta-Llama-3.1-8B-Instruct-GGUF']
+ })
+
+ expect(results[0].id).toBe('bartowski/Meta-Llama-3.1-8B-Instruct-GGUF')
+ expect(results[0].installed).toBe(true)
+ })
+
+ it('filters out non-GGUF results even if Hugging Face returns them', async () => {
+ fetch.mockResolvedValue(response([
+ { modelId: 'org/Plain-Safetensors', tags: ['safetensors'], siblings: [] },
+ { modelId: 'org/Useful-GGUF', tags: [], siblings: [{ rfilename: 'Useful-Q4_K_M.gguf' }] }
+ ]))
+
+ const results = await searchHuggingFaceModels({ backend: 'ollama', query: 'useful' })
+
+ expect(results.map((r) => r.repository)).toEqual(['org/Useful-GGUF'])
+ })
+})