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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add Audio & Music category to Local LLM HF installer (DRY audio-model registry)
Adam Eivyc74c7c7e093c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ddae4ed300..1fef94c7ae 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@- **On-device music generation in the Track editor.** Generate a track's audio locally from its prompt (+ lyrics) — no API key, no network at inference. Three OSS engines behind one picker: **MusicGen** (MLX) and **AudioLDM2** (diffusers) for instrumental/ambient beds, and **ACE-Step** (`INSTALL_ACESTEP=1 bash scripts/setup-image-video.sh`) for full songs *with vocals*, which uses the track's lyrics as conditioning. Engines whose opt-in venv isn't installed show their install hint and gate the Generate button (same posture as the FLUX.2 image venv). The generated WAV lands in the shared music library and attaches to the track with its engine/model/duration metadata.- **Install additional audio models from HuggingFace.** The Track editor's generator panel can pull extra checkpoints (e.g. a larger MusicGen, an AudioLDM2 variant) straight from HuggingFace into the local cache — same streamed-download path as the image/video model installer — and they become selectable for generation immediately. User-installed models persist in `data/audio-models.json` and can be removed from the same panel.+- **"Audio & Music" category in the Local LLM model installer (Settings → Local LLM).** The Hugging Face model search gained an audio/music output category that surfaces generation models (MusicGen, AudioLDM2, ACE-Step, Stable Audio, Magenta…) — the GGUF filter is relaxed for this category since audio models aren't GGUF. Installing an audio model downloads it into the HF cache and registers it in the **same** shared audio-model registry the Music studio reads (`data/audio-models.json`), so there's one DRY place to manage audio models: install it once from the installer and it's immediately selectable in the Music studio. Models no on-device engine can run yet — and ACE-Step, which uses a fixed checkpoint — are discovery-only with a "Visit" link. Curated suggestions lead the list: **ACE-Step v1.5**, **`google/magenta-realtime-2`**, and **`stabilityai/stable-audio-3-medium`** (the last gated behind a Hugging Face data-sharing agreement).- **Autopilot convergence rounds are now configurable.** The series autopilot re-verifies the arc (and re-reviews the manuscript) in bounded auto-resolve loops, and previously hard-stopped after 3 arc rounds / 2 editorial rounds with "did not converge after 3 rounds" — leaving no way to give a stubborn arc more attempts. You can now set **Arc verify rounds** and **Editorial rounds** (0–20, where 0 skips that gate) in Autonomous mode → **Options**; the values persist as a per-install default and are reused on **Resume**. A per-run override still wins over the saved default, which wins over the built-in floor (3 / 2). When a gate still can't auto-resolve within the limit, the pause message now says how many blocking findings remain and points you to edit the arc/manuscript or raise the limit and resume.- Editorial Checks page now has an AI provider + model selector that configures the editorial pass. Leave it on "Default provider" to use the active/stage provider, or pick a specific provider/model to override the LLM-backed checks for that run.diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 64e21cb403..2cb723b273 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router-dom';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';@@ -8,7 +8,8 @@ import { formatBytes, formatContextLength, timeAgo, recommendedRamGb } from '../import { localLlmTargetKey } from '../../lib/localLlmTargetKey';import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,- deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService+ deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,+ installAudioModel} from '../../services/api';import socket from '../../services/socket';import MemoryManagement from './MemoryManagement.jsx';@@ -26,11 +27,12 @@ const CATEGORY_LABELS = {reasoning: 'Reasoning',coding: 'Coding',vision: 'Image Analysis',+ audio: 'Audio & Music',embedding: 'Text Embeddings',lightweight: 'Small & Fast',multilingual: 'Multilingual'};-const CATEGORY_ORDER = ['reasoning', 'coding', 'vision', 'embedding', 'chat', 'lightweight', 'multilingual'];+const CATEGORY_ORDER = ['reasoning', 'coding', 'vision', 'audio', 'embedding', 'chat', 'lightweight', 'multilingual'];const categoryLabel = (id) => CATEGORY_LABELS[id] || id;// Render model capabilities as colored icons (LM Studio style) instead of text.@@ -42,6 +44,7 @@ const CAPABILITY_META = {vision: { Icon: Eye, label: 'Vision', cls: 'text-amber-400 border-amber-400/50' },embeddings: { Icon: Boxes, label: 'Embeddings', cls: 'text-violet-400 border-violet-400/50' },tools: { Icon: Wrench, label: 'Tool use', cls: 'text-blue-400 border-blue-400/50' },+ audio: { Icon: Music, label: 'Audio generation', cls: 'text-pink-400 border-pink-400/50' },};@@ -334,10 +337,16 @@ export function LocalLlmTab() {const catalogCategories = useMemo(() => {const counts = new Map();for (const model of catalog) counts.set(model.category || 'chat', (counts.get(model.category || 'chat') || 0) + 1);- return CATEGORY_ORDER- .filter((id) => counts.has(id))- .map((id) => ({ id, label: categoryLabel(id), count: counts.get(id) }));- }, [catalog]);+ // Hugging Face is searched per-category server-side, so a default GGUF query+ // never surfaces audio results — expose the full category set as filter+ // buttons (count shown only when known) so the user can navigate to+ // categories like Audio & Music. The curated local catalog stays+ // counts-driven (its categories are fixed and fully present).+ const ids = catalogSource === 'huggingface'+ ? CATEGORY_ORDER+ : CATEGORY_ORDER.filter((id) => counts.has(id));+ return ids.map((id) => ({ id, label: categoryLabel(id), count: counts.has(id) ? counts.get(id) : null }));+ }, [catalog, catalogSource]);const visibleCatalogGroups = useMemo(() => {const filterCategory = catalogSource === 'huggingface' ? 'all' : activeCategory;const categoryIds = filterCategory === 'all'@@ -380,6 +389,32 @@ export function LocalLlmTab() {clearConfirm: false});+ // Audio/music models don't run on Ollama/LM Studio — they install into the+ // shared audio-model registry (server/services/audioModels.js) via the Music+ // studio's streaming HF-download endpoint, so the Music studio picks them up.+ // The download streams SSE frames; surface progress in the same banner as the+ // socket-driven install progress, and treat an `error` frame as failure.+ const installAudio = (model) => {+ let failed = false;+ return runAction(+ `install-${model.id}`,+ async () => {+ await installAudioModel(+ { engine: model.engine, repo: model.repository, name: model.name },+ (ev) => {+ if (ev?.type === 'stage') setProgressMsg(ev.stage || '');+ else if (ev?.type === 'progress') setProgressMsg(`${ev.file || 'downloading'} — ${Math.round((ev.progress || 0) * 100)}%`);+ else if (ev?.type === 'error') { failed = true; toast.error(ev.message || 'Download failed'); }+ },+ );+ // installAudioModel resolves even after an error frame (it only throws on+ // a non-OK response) — re-throw so runAction skips the success toast.+ if (failed) throw Object.assign(new Error('audio install failed'), { handled: true });+ },+ `${model.name} installed — available in the Music studio`,+ { onError: (err) => { if (!err?.handled) toast.error(err?.message || 'Install failed'); }, clearConfirm: false },+ ).finally(() => setProgressMsg(''));+ };const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`).then((result) => {// Drop the just-deleted model from any pending comparison (runAction@@ -608,7 +643,7 @@ export function LocalLlmTab() {id="llm-catalog-search"value={query}onChange={(e) => setQuery(e.target.value)}- placeholder={catalogSource === 'huggingface' ? 'Search Hugging Face GGUF models…' : `Search the ${labelFor(selected)} catalog…`}+ placeholder={catalogSource === 'huggingface' ? (activeCategory === 'audio' ? 'Search Hugging Face audio models…' : '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>@@ -645,7 +680,7 @@ export function LocalLlmTab() {onClick={() => setActiveCategory(category.id)}className={`px-2.5 py-1 text-xs rounded transition-colors ${activeCategory === category.id ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}>- {category.label} ({category.count})+ {category.label}{category.count != null ? ` (${category.count})` : ''}</button>))}</div>@@ -672,6 +707,7 @@ export function LocalLlmTab() {{group.models.map((m) => {const ram = recommendedRamGb(m?.sizeBytes, m?.size);const isHf = m.source === 'huggingface';+ const isAudio = m.category === 'audio';const createdMs = new Date(m.createdAt).getTime();const updatedMs = new Date(m.updatedAt).getTime();return (@@ -680,6 +716,7 @@ export function LocalLlmTab() {<div className="text-sm text-white truncate">{m.name} <span className="text-xs text-gray-500">· {m.params}</span></div><div className="text-xs text-gray-500 truncate">{m.id}</div><div className="text-xs text-gray-500 mt-0.5">{m.description}</div>+ {m.note && <div className="text-[11px] text-port-warning/90 mt-0.5">{m.note}</div>}<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>@@ -719,9 +756,13 @@ export function LocalLlmTab() {<div className="flex flex-col items-end gap-1 shrink-0">{m.installed ? (<span className="text-xs px-2 py-1 text-port-success">Installed</span>+ ) : m.installable === false ? (+ // Audio models with no PortOS runtime (or a fixed-checkpoint+ // engine like ACE-Step) are discovery-only — "Visit" below.+ null) : (<button- onClick={() => install(m.id)}+ onClick={() => (isAudio ? installAudio(m) : install(m.id))}disabled={busy}className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1">diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsxindex 53776b3800..549b325b4b 100644--- a/client/src/pages/LocalLlmPlayground.jsx+++ b/client/src/pages/LocalLlmPlayground.jsx@@ -16,6 +16,7 @@ const CATEGORY_LABELS = {reasoning: 'Reasoning',coding: 'Coding',vision: 'Image Analysis',+ audio: 'Audio & Music',embedding: 'Text Embeddings',lightweight: 'Small & Fast',multilingual: 'Multilingual',diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex 4ff1efa1d6..878669a304 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -23,6 +23,14 @@ export const LOCAL_LLM_CATEGORIES = [{ id: 'reasoning', label: 'Reasoning' },{ id: 'coding', label: 'Coding' },{ id: 'vision', label: 'Image Analysis' },+ // Audio/music GENERATION models (ACE-Step, MusicGen, AudioLDM2, Stable Audio,+ // Magenta…). These are NOT GGUF chat models and don't run on Ollama/LM Studio+ // — the Hugging Face search relaxes its GGUF filter for this category and the+ // installer routes audio installs into the shared audio-model registry+ // (server/services/audioModels.js) so the Music studio picks them up. The+ // curated `LOCAL_LLM_CATALOG` below never tags entries 'audio'; this category+ // is populated live from the Hub.+ { id: 'audio', label: 'Audio & Music' },{ id: 'embedding', label: 'Text Embeddings' },{ id: 'lightweight', label: 'Small & Fast' },{ id: 'multilingual', label: 'Multilingual' }diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 3b6eceb97c..dfa3b2ca3d 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -29,6 +29,8 @@ import {getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer} from '../services/localLlm.js'import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'+import { listUserModels } from '../services/audioModels.js'+import { ENGINES } from '../services/pipeline/musicGen.js'import { abortSignalFromResponse } from '../lib/requestAbort.js'import { awaitWritableDrain } from '../lib/streamBackpressure.js'import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'@@ -62,11 +64,21 @@ router.get('/catalog', asyncHandler(async (req, res) => {}))// GET /api/local-llm/huggingface-search?backend=ollama&q=qwen&category=coding-// Live Hub discovery for GGUF-compatible community models.+// Live Hub discovery — GGUF-compatible community models, plus (for the `audio`+// category) audio/music generators that install into the shared audio-model+// registry and surface in the Music studio.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 })+ // Cross-reference the shared audio-model registry so a model already installed+ // via the Music studio (or this tab) shows "Installed". Only the user-added+ // repos count — shipped engine defaults download lazily on first generation.+ let installedAudioRepos = []+ if (category === 'audio') {+ const perEngine = await Promise.all(Object.keys(ENGINES).map((id) => listUserModels(id)))+ installedAudioRepos = perEngine.flat().map((m) => m.repo)+ }+ const models = await searchHuggingFaceModels({ backend, query: q, category, limit, installedIds: installed, installedAudioRepos })res.json({ backend, source: 'huggingface', models })}))diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 73ac893269..5f2999fd0e 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -1,6 +1,7 @@import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'import { LOCAL_LLM_CATEGORIES, isBackend } from '../lib/localLlmCatalog.js'+import { ENGINES } from './pipeline/musicGen.js'const HF_API_BASE = 'https://huggingface.co/api/models'const HF_TIMEOUT_MS = 12_000@@ -11,11 +12,61 @@ const CATEGORY_SEARCH = {reasoning: 'reasoning thinking gguf',coding: 'coding coder agentic code gguf',vision: 'vision image text gguf',+ // Audio is NOT a GGUF category — the search relaxes the GGUF filter for it+ // (see `searchHuggingFaceModels`) and these terms surface generation models.+ audio: 'music audio text-to-music text-to-audio song generation',embedding: 'embedding sentence-transformers gguf',lightweight: 'small 4b 3b 2b gguf',multilingual: 'multilingual qwen llama gguf'}+// Map a Hugging Face audio repo onto the PortOS music engine that can actually+// run it (server/services/pipeline/musicGen.js). Returns null when no shipped+// engine matches — the model is still DISCOVERABLE (search + "Visit") but not+// installable, because no sidecar can render it. Kept as a local heuristic+// rather than importing engine internals: the engine *runtime* knowledge lives+// in musicGen.js; this is just a repo-name → engine-id classifier.+function inferAudioEngine(haystack) {+ if (/ace-?step/.test(haystack)) return 'acestep'+ if (/musicgen/.test(haystack)) return 'musicgen'+ if (/audioldm/.test(haystack)) return 'audioldm2'+ return null+}++// An engine can host an arbitrary user-installed HF checkpoint only when its+// sidecar threads `--model <repo>` into from_pretrained (musicgen/audioldm2).+// ACE-Step resolves a fixed foundation checkpoint and ignores --model, so it is+// `customModels: false` and its repos are Visit-only here. The single source of+// truth for that flag is the ENGINES registry.+const engineHostsCustomRepo = (engineId) => ENGINES[engineId]?.customModels === true++// Curated audio/music suggestions surfaced at the top of the Audio & Music+// category so the headline generators are always one click from discovery even+// when the live Hub ranking buries them. `engine: null` means "no PortOS+// runtime yet" (Visit-only, experimental); `gated` flags repos that require+// accepting a license / data-sharing agreement on Hugging Face before download.+const CURATED_AUDIO_MODELS = [+ {+ repo: 'ACE-Step/acestep-v15-xl-base',+ name: 'ACE-Step v1.5 XL Base',+ description: 'Full-song generation with vocals — the ACE-Step v1.5 foundation checkpoint.',+ note: 'ACE-Step uses a fixed foundation checkpoint — install/select it from the Music studio.',+ },+ {+ repo: 'google/magenta-realtime-2',+ name: 'Magenta RealTime 2',+ description: "Google's real-time music generation model.",+ note: 'Experimental — no on-device PortOS runtime yet; open on Hugging Face to explore.',+ },+ {+ repo: 'stabilityai/stable-audio-3-medium',+ name: 'Stable Audio 3 Medium',+ description: "Stability AI's text-to-audio generation model.",+ note: 'Gated — requires accepting a data-sharing agreement on Hugging Face before download.',+ gated: true,+ },+]+const TRUSTED_PUBLISHERS = new Set(['unsloth','bartowski',@@ -28,7 +79,12 @@ const TRUSTED_PUBLISHERS = new Set(['google','microsoft','nomic-ai',- 'ibm-granite'+ 'ibm-granite',+ // audio/music generator publishers+ 'facebook',+ 'cvssp',+ 'stabilityai',+ 'ace-step'])const QUANT_PRIORITY = [@@ -117,9 +173,16 @@ function extractParams(repoId) {return match[2] ? `${match[1]}B / ${match[2]}B active` : `${match[1]}B`}+// Detect an audio/music GENERATION model from its pipeline tag / tags / repo.+// Anchored on Hugging Face pipeline-tag tokens (hyphenated) and known generator+// families so a chat model that merely mentions "audio" isn't miscategorised in+// the auto-classify ('all') path.+const AUDIO_RE = /(text-to-audio|text-to-music|text-to-speech|audio-to-audio|automatic-speech-recognition|musicgen|audioldm|stable-audio|ace-?step|magenta|\bbark\b|\bxtts\b)/+function classifyModel(model, requestedCategory) {if (CATEGORY_IDS.has(requestedCategory) && requestedCategory !== 'all') return requestedCategoryconst haystack = `${repoIdOf(model)} ${(tagsOf(model) || []).join(' ')} ${model?.pipeline_tag || ''}`.toLowerCase()+ if (AUDIO_RE.test(haystack)) return 'audio'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'@@ -132,6 +195,9 @@ function classifyModel(model, requestedCategory) {function capabilitiesFor(model, category) {const tags = tagsOf(model)const caps = new Set()+ // Audio generators don't "chat" — they render audio, so they get only the+ // `audio` capability badge (no chat/tools).+ if (category === 'audio') return ['audio']if (category !== 'embedding') caps.add('chat')if (category === 'coding') caps.add('code')if (category === 'reasoning') caps.add('reasoning')@@ -190,22 +256,33 @@ function isInstalled(backend, result, installedIds) {return false}-function toResult(model, backend, requestedCategory, installedIds) {+function toResult(model, backend, requestedCategory, installedIds, installedAudioRepos = new Set()) {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 isAudio = category === 'audio'+ // Audio generators are not GGUF — skip the GGUF file picker entirely so a+ // non-GGUF repo doesn't surface a bogus "GGUF" size or an `hf.co/...:quant`+ // Ollama install id it can never honour.+ const file = isAudio ? null : pickGgufFile(model)const score = scoreModel(model, category, file)+ // For audio the `id` is just the repo id (the React key + the value the audio+ // installer routes to the music registry); for GGUF chat models it's the+ // backend-specific pull/download id.+ const id = isAudio ? repoId : installIdForBackend(backend, repoId, file)+ const audioEngine = isAudio+ ? inferAudioEngine(`${repoId} ${tagsOf(model).join(' ')} ${model?.pipeline_tag || ''}`.toLowerCase())+ : nullconst result = {id,key: repoId,name: displayName(repoId),category,- params: extractParams(repoId) || 'HF',- size: formatBytes(file?.size) || (file?.quant || 'GGUF'),+ params: extractParams(repoId) || (isAudio ? 'Audio' : 'HF'),+ size: formatBytes(file?.size) || (isAudio ? 'HF model' : (file?.quant || 'GGUF')),family: repoId.split('/').pop().split(/[-_]/)[0]?.toLowerCase() || 'huggingface',- description: model?.cardData?.summary || model?.cardData?.description || 'Community Hugging Face GGUF model.',+ description: model?.cardData?.summary || model?.cardData?.description+ || (isAudio ? 'Community Hugging Face audio model.' : 'Community Hugging Face GGUF model.'),capabilities: capabilitiesFor(model, category),installed: false,source: 'huggingface',@@ -220,7 +297,16 @@ function toResult(model, backend, requestedCategory, installedIds) {quant: file?.quant || null,score}- result.installed = isInstalled(backend, result, installedIds)+ if (isAudio) {+ // Engine the model maps to (or null) + whether the installer can host it.+ // A null engine or a fixed-checkpoint engine (ACE-Step) is Visit-only.+ result.engine = audioEngine+ result.installable = Boolean(audioEngine) && engineHostsCustomRepo(audioEngine)+ result.installed = installedAudioRepos.has(repoId.toLowerCase())+ } else {+ result.installable = true+ result.installed = isInstalled(backend, result, installedIds)+ }return result}@@ -250,38 +336,50 @@ async function fetchModels(search, limit, useGgufFilter) {return Array.isArray(data) ? data : []}-// The search endpoint returns siblings WITHOUT per-file sizes; only the-// per-model endpoint (?blobs=true) carries them. Cache by repo so repeated-// searches (the box is debounced per keystroke) don't re-fetch. `undefined` =-// not fetched, `null` = fetched-but-no-size (sentinel, per the absent-vs-empty-// rule) so a sizeless repo isn't probed on every search.-const repoSizeCache = new Map()-const REPO_SIZE_CACHE_MAX = 500+const repoModelCache = new Map()+const REPO_MODEL_CACHE_MAX = 500-async function fetchRepoSizeBytes(repoId) {- if (repoSizeCache.has(repoId)) return repoSizeCache.get(repoId)+// Fetch (and cache) the per-model record WITH per-file sizes. The search+// endpoint returns siblings without sizes; only `?blobs=true` carries them, and+// the box is debounced per keystroke, so cache by repo to avoid re-fetching.+// `null` = fetched-but-unavailable (gated / private / 404), cached (per the+// absent-vs-empty sentinel rule) so a sizeless repo isn't re-probed every search.+async function fetchRepoModel(repoId) {+ if (repoModelCache.has(repoId)) return repoModelCache.get(repoId)// repoId comes from the HF search response (untrusted upstream) — encode each// path segment so a `?`/`#`/`..` in the id can't reshape the request path/query.const safeRepoPath = String(repoId).split('/').map(encodeURIComponent).join('/')const model = await fetchWithTimeout(`${HF_API_BASE}/${safeRepoPath}?blobs=true`, { headers: hfHeaders() }, HF_TIMEOUT_MS).then((res) => (res.ok ? res.json() : null)).catch(() => null)- // Re-run the same quant picker against the now-sized siblings.- const picked = pickGgufFile(model)- const bytes = Number.isFinite(picked?.size) ? picked.size : null// Evict oldest entry when the cap is reached (insertion-order iteration).- if (repoSizeCache.size >= REPO_SIZE_CACHE_MAX) {- repoSizeCache.delete(repoSizeCache.keys().next().value)+ if (repoModelCache.size >= REPO_MODEL_CACHE_MAX) {+ repoModelCache.delete(repoModelCache.keys().next().value)}- repoSizeCache.set(repoId, bytes)- return bytes+ repoModelCache.set(repoId, model)+ return model+}++// Total resident size of an audio repo's weight files — audio generators ship+// `.safetensors`/`.ckpt`/`.bin` weights rather than a single GGUF, so the quant+// picker doesn't apply; sum the weight siblings instead.+const WEIGHT_FILE_RE = /\.(safetensors|ckpt|bin|pt|pth|onnx|gguf)$/i+function sumWeightBytes(model) {+ const total = siblingsOf(model)+ .filter((s) => WEIGHT_FILE_RE.test(normalizeText(s.rfilename || s.name)))+ .reduce((sum, s) => sum + (Number.isFinite(s.size) ? s.size : 0), 0)+ return total > 0 ? total : null}// Backfill real file sizes for results the search endpoint left sizeless.async function enrichWithSizes(results) {await Promise.allSettled(results.map(async (result) => {if (Number.isFinite(result.sizeBytes)) return- const bytes = await fetchRepoSizeBytes(result.repository)+ const model = await fetchRepoModel(result.repository)+ if (!model) return+ const bytes = result.category === 'audio'+ ? sumWeightBytes(model)+ : (() => { const picked = pickGgufFile(model); return Number.isFinite(picked?.size) ? picked.size : null })()if (Number.isFinite(bytes)) {result.sizeBytes = bytesresult.size = formatBytes(bytes) || result.size@@ -290,24 +388,64 @@ async function enrichWithSizes(results) {return results}-export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [] }) {+// Build a result object for a curated audio suggestion. These don't come from+// the live Hub search, so synthesize a minimal model record and run it through+// the same `toResult` path (engine inference, install id, capabilities, etc.) so+// the result shape stays defined in exactly one place. `enrichWithSizes` fills+// the size from `?blobs=true`; the curated-only fields drive the UI badges and+// the score pins these above live results in the merge below.+function curatedAudioResult(entry, installedAudioRepos) {+ const synthetic = { modelId: entry.repo, downloads: 0, likes: 0, tags: [], cardData: { summary: entry.description } }+ return {+ ...toResult(synthetic, 'lmstudio', 'audio', [], installedAudioRepos),+ name: entry.name,+ suggested: true,+ note: entry.note || null,+ gated: entry.gated === true,+ score: Number.MAX_SAFE_INTEGER,+ }+}++export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [], installedAudioRepos = [] }) {if (!isBackend(backend)) return []const requestedCategory = CATEGORY_IDS.has(category) ? category : 'all'+ const installedAudio = new Set(installedAudioRepos.map((r) => String(r).toLowerCase()))+ // Audio models aren't GGUF — don't constrain the Hub query (or post-filter)+ // to GGUF repos for the audio category, or ACE-Step / Stable Audio / MusicGen+ // would all be filtered out.+ const ggufOnly = requestedCategory !== 'audio'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)+ let models = await fetchModels(search, fetchLimit, ggufOnly)+ if (models.length === 0 && ggufOnly) models = await fetchModels(search, fetchLimit, false)const seen = new Set()- const results = models- .filter(hasGgufSignal)- .map((model) => toResult(model, backend, requestedCategory, installedIds))+ // Curated audio suggestions lead the Audio & Music list (filtered by query+ // when the user is typing) so the headline generators are always visible.+ const curated = requestedCategory === 'audio'+ ? CURATED_AUDIO_MODELS+ .filter((entry) => {+ const q = normalizeText(query).toLowerCase()+ if (!q) return true+ return entry.repo.toLowerCase().includes(q) || entry.name.toLowerCase().includes(q)+ })+ .map((entry) => {+ seen.add(entry.repo)+ return curatedAudioResult(entry, installedAudio)+ })+ : []++ const live = models+ .filter((model) => (ggufOnly ? hasGgufSignal(model) : true))+ .map((model) => toResult(model, backend, requestedCategory, installedIds, installedAudio)).filter(Boolean).filter((model) => {if (seen.has(model.repository)) return falseseen.add(model.repository)return true})++ const results = [...curated, ...live].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.jsindex 79b332a932..e98898724e 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -48,6 +48,7 @@ describe('huggingFaceCatalog', () => {license: 'apache-2.0'})expect(results[0].capabilities).toEqual(expect.arrayContaining(['chat', 'code']))+ expect(results[0].installable).toBe(true)})it('returns LM Studio repo ids and marks installed repos', async () => {@@ -102,4 +103,67 @@ describe('huggingFaceCatalog', () => {expect(results.map((r) => r.repository)).toEqual(['org/Useful-GGUF'])})++ describe('audio category', () => {+ it('surfaces non-GGUF audio models (relaxes the GGUF filter) and infers the engine', async () => {+ fetch.mockResolvedValue(response([+ {+ modelId: 'facebook/musicgen-large',+ downloads: 500000,+ likes: 2000,+ tags: ['text-to-audio', 'musicgen', 'safetensors'],+ pipeline_tag: 'text-to-audio',+ siblings: [{ rfilename: 'model.safetensors', size: 13_000_000_000 }]+ }+ ]))++ const results = await searchHuggingFaceModels({ backend: 'ollama', query: 'musicgen', category: 'audio' })+ const musicgen = results.find((r) => r.repository === 'facebook/musicgen-large')++ expect(musicgen).toBeTruthy()+ expect(musicgen.category).toBe('audio')+ expect(musicgen.capabilities).toEqual(['audio'])+ expect(musicgen.engine).toBe('musicgen')+ // MusicGen threads --model into from_pretrained → custom checkpoints work.+ expect(musicgen.installable).toBe(true)+ // The Ollama install id is never used for audio — it's the bare repo id.+ expect(musicgen.id).toBe('facebook/musicgen-large')+ })++ it('always leads with curated suggestions (ACE-Step / Magenta / Stable Audio)', async () => {+ fetch.mockResolvedValue(response([]))++ const results = await searchHuggingFaceModels({ backend: 'ollama', category: 'audio' })+ const byRepo = Object.fromEntries(results.map((r) => [r.repository, r]))++ // ACE-Step uses a fixed checkpoint (customModels: false) → Visit-only.+ expect(byRepo['ACE-Step/acestep-v15-xl-base']).toMatchObject({ category: 'audio', engine: 'acestep', installable: false, suggested: true })+ // No PortOS runtime yet → not installable.+ expect(byRepo['google/magenta-realtime-2']).toMatchObject({ engine: null, installable: false, suggested: true })+ // Gated behind a data-sharing agreement.+ expect(byRepo['stabilityai/stable-audio-3-medium']).toMatchObject({ gated: true, installable: false })+ expect(byRepo['stabilityai/stable-audio-3-medium'].note).toMatch(/data-sharing agreement/i)+ })++ it('marks an audio model installed when it is in the shared registry', async () => {+ fetch.mockResolvedValue(response([+ {+ modelId: 'facebook/musicgen-small',+ downloads: 100,+ tags: ['text-to-audio'],+ pipeline_tag: 'text-to-audio',+ siblings: [{ rfilename: 'model.safetensors', size: 2_000_000_000 }]+ }+ ]))++ const results = await searchHuggingFaceModels({+ backend: 'ollama',+ query: 'musicgen-small',+ category: 'audio',+ installedAudioRepos: ['facebook/musicgen-small']+ })+ const small = results.find((r) => r.repository === 'facebook/musicgen-small')+ expect(small.installed).toBe(true)+ })+ })})