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
surface MLX models in HF search + RAM-aware quant picker for curated cards
[._.]/ Adam Eivy3258dafa7c7e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3054800bda..6cfd34e486 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,9 @@## Local LLMs- **The Hugging Face model search now lets you pick a quantization, and defaults to the highest-fidelity build that fits your machine's memory.** Previously every GGUF repo installed a single auto-chosen Q4-ish quant, hiding larger variants (like a `…-BF16.gguf`) that a big-memory box can comfortably run. Each Hugging Face result now carries a **Quant** menu listing every GGUF variant in the repo (multi-part shards summed into one entry), with a per-quant fit hint — *fits comfortably* / *tight fit* / *exceeds RAM* — measured against your usable memory. The default selection is RAM-aware: PortOS reserves headroom for the OS and KV cache, then picks the largest variant that still fits (so a 128 GB unified-memory Mac defaults to BF16/Q8 where a 16 GB laptop stays on Q4), and you can override it per model. This is purely a file-picker improvement — these are all still GGUF files the existing Ollama/LM Studio runtimes already support; nothing about the GGUF-only requirement changed (raw safetensors/full-precision HF models need a different runtime and remain out of scope). Ollama installs via `hf.co/<repo>:<quant>`; LM Studio via `<repo>@<quant>`.+- **[issue-1537] The Hugging Face search now surfaces Apple MLX models on Apple Silicon, not just GGUF.** On an Apple-Silicon Mac with LM Studio, search results now include MLX builds (Apple's native format — often the fastest path on unified-memory Macs) alongside GGUF, each tagged with an **MLX**/**GGUF** badge so you know what you're installing. MLX cards carry the same size + RAM-fit hint as GGUF cards and install through LM Studio (`lms get <repo>`). MLX is shown only where it actually runs: it's hidden on non-Apple hosts, and for the Ollama backend (Ollama's MLX acceleration applies to its own registry's GGUF models automatically and can't pull arbitrary Hugging Face safetensors repos).+- **The built-in "Recommended" model cards now have the same RAM-aware quant picker as the Hugging Face search.** Recommended models used to hard-code one quant each; cards backed by a Hugging Face repo now show the **Quant** menu and default to the highest-fidelity build that fits this machine's memory, so the recommendation adapts to your hardware instead of being fixed. (Models that pull from Ollama's own registry by bare name keep their single curated build — per-quant selection for those is tracked as a follow-up.)+- **Hugging Face search results now rank by downloads and recency more strongly.** A model's download count and how recently it was updated now dominate the result ordering (recency is graduated — a model updated this week outranks an equivalent one from months or years ago, and stale models are demoted), so popular, actively-maintained models surface first instead of being outweighed by publisher/format bonuses.## Comic pagesdiff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 41c3eb52fb..793073bafd 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -55,6 +55,14 @@ const FIT_META = {'too-large': { label: 'exceeds RAM', cls: 'text-port-error' },};+// Model format badge — GGUF (llama.cpp, cross-backend) vs. MLX (Apple's native+// format, LM Studio on Apple Silicon only). Shown so the user knows what they're+// installing when both formats appear in the same result list.+const FORMAT_META = {+ gguf: { label: 'GGUF', title: 'GGUF — llama.cpp format, runs on Ollama and LM Studio', cls: 'border-port-border text-gray-400' },+ mlx: { label: 'MLX', title: "MLX — Apple's native format, installs via LM Studio on Apple Silicon", cls: 'border-port-accent/40 text-port-accent' },+};+// Summarize a migrate result for the success toast (per-model statuses → counts).function summarizeMigrate(r) {@@ -712,7 +720,7 @@ export function LocalLlmTab() {{catalogError && (<p className="text-xs text-port-warning">{catalogError}</p>)}- {catalogSource === 'huggingface' && Number.isFinite(systemMemoryGb) && (+ {Number.isFinite(systemMemoryGb) && catalog.some((m) => Array.isArray(m.variants) && m.variants.length > 1) && (<p className="text-[11px] text-gray-500">This machine has {systemMemoryGb} GB of memory — the default quant is the highest-fidelity build that fits. Use the Quant menu on a result to choose a smaller or larger one.</p>@@ -756,7 +764,17 @@ export function LocalLlmTab() {return (<div key={m.key || m.id} className="flex items-start gap-3 bg-port-bg border border-port-border rounded-lg p-3"><div className="flex-1 min-w-0">- <div className="text-sm text-white truncate">{m.name} <span className="text-xs text-gray-500">· {m.params}</span></div>+ <div className="text-sm text-white truncate">+ {m.name} <span className="text-xs text-gray-500">· {m.params}</span>+ {FORMAT_META[m.format] && (+ <span+ title={FORMAT_META[m.format].title}+ className={`ml-1.5 align-middle text-[10px] px-1 py-0.5 rounded border ${FORMAT_META[m.format].cls}`}+ >+ {FORMAT_META[m.format].label}+ </span>+ )}+ </div><div className="text-xs text-gray-500 truncate">{chosenId}</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>}diff --git a/server/lib/README.md b/server/lib/README.mdindex bc8a007c54..8f201630c9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. || `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. || `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |-| `platform.js` | Platform/OS detection helpers. |+| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). || `timezone.js` | Timezone utilities for scheduling. || `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. || `buildId.js` | Build-ID derived from the built client bundle. |diff --git a/server/lib/platform.js b/server/lib/platform.jsindex 73687e9d47..3a1cd52deb 100644--- a/server/lib/platform.js+++ b/server/lib/platform.js@@ -5,6 +5,17 @@ const execAsync = promisify(exec);const platform = process.platform;+/**+ * Is this an Apple-Silicon Mac (arm64 darwin)? Gates MLX model features: MLX is+ * Apple's native ML framework, so MLX formats only run on Apple Silicon. (Node+ * under Rosetta reports `process.arch === 'x64'`, which correctly reads false.)+ * Detect at the route boundary and pass into pure services, like `os.totalmem()`.+ * @returns {boolean}+ */+export function isAppleSilicon() {+ return process.platform === 'darwin' && process.arch === 'arm64';+}+/*** Get list of listening TCP ports* @returns {Promise<number[]>} Array of port numbersdiff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 4066693858..f4a341eea6 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -25,7 +25,8 @@ import {localLlmCompareSchema} from '../lib/validation.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'-import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'+import { isAppleSilicon } from '../lib/platform.js'+import { searchHuggingFaceModels, enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js'import {getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer} from '../services/localLlm.js'@@ -55,13 +56,25 @@ router.get('/vision-models', asyncHandler(async (_req, res) => {res.json({ models: await listVisionModels() })}))-// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install picker+// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install picker.+// HF-repo-backed entries are enriched with the same per-quant variant picker ++// RAM-aware default as the live Hugging Face search, so the recommended quant+// fits this machine instead of being hard-coded per model.router.get('/catalog', asyncHandler(async (req, res) => {const { backend, q } = req.queryif (!isBackend(backend)) throw new ServerError('backend must be "ollama" or "lmstudio"', { status: 400 })- const installed = (await listModels(backend)).map((m) => m.id)+ // Per-quant installed detection needs LM Studio's quantization on the id+ // (`<id>@<quant>`) — mirror the HF-search route so a single installed quant+ // doesn't flag every quant of a repo as installed.+ const installed = (await listModels(backend)).map((m) => (+ backend === 'lmstudio' && m.quantization ? `${m.id}@${m.quantization}` : m.id+ ))const models = q ? searchCatalog(backend, q, installed) : getCatalog(backend, installed)- res.json({ backend, models })+ // Total system memory drives the RAM-aware recommended quant (unified memory on+ // Apple Silicon also backs the GPU, so a big box can default to higher fidelity).+ const systemMemoryBytes = os.totalmem()+ await enrichCatalogWithVariants(models, { backend, systemMemoryBytes, installedIds: installed })+ res.json({ backend, models, systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3) })}))// GET /api/local-llm/huggingface-search?backend=ollama&q=qwen&category=coding@@ -88,8 +101,12 @@ router.get('/huggingface-search', asyncHandler(async (req, res) => {// fit verdicts. On unified-memory Macs this pool also backs the GPU, so a big// box can default to a higher-fidelity build than the old Q4-always pick.const systemMemoryBytes = os.totalmem()- const models = await searchHuggingFaceModels({ backend, query: q, category, limit, installedIds: installed, installedAudioRepos, systemMemoryBytes })- res.json({ backend, source: 'huggingface', models, systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3) })+ // MLX models surface only on Apple Silicon (and only for LM Studio) — gate the+ // extra MLX query on the host so non-Apple installs don't see un-installable+ // results. Detected here at the route boundary; the service stays deterministic.+ const appleSilicon = isAppleSilicon()+ const models = await searchHuggingFaceModels({ backend, query: q, category, limit, installedIds: installed, installedAudioRepos, systemMemoryBytes, appleSilicon })+ res.json({ backend, source: 'huggingface', models, systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3), appleSilicon })}))// POST /api/local-llm/install-backend — install the backend app/binary itselfdiff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex ffd44474f3..57da57dc89 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -282,13 +282,26 @@ function scoreModel(model, category, file) {const categoryText = `${repoId} ${tags.join(' ')} ${model?.pipeline_tag || ''}`.toLowerCase()let score = 0- score += Math.log10(downloads + 1) * 12+ // Downloads and recency are the two factors the user cares about most, so they+ // dominate the blend. Downloads: a heavier log weight (a 1M-download model beats+ // a trusted-publisher 1K-download one). Recency: graduated, not a single 180-day+ // step — a model updated this week clearly outranks one from months/years ago,+ // and a stale model is actively demoted. (The Hub query already sorts by+ // downloads; this re-asserts both factors after the trust/format bonuses.)+ score += Math.log10(downloads + 1) * 18score += Math.log10(likes + 1) * 8+ if (daysOld != null) {+ if (daysOld <= 14) score += 26+ else if (daysOld <= 45) score += 20+ else if (daysOld <= 120) score += 12+ else if (daysOld <= 270) score += 5+ else if (daysOld <= 540) score -= 4+ else score -= 14+ }if (TRUSTED_PUBLISHERS.has(publisher)) score += 22if (file) score += 18if (/gguf/i.test(repoId) || tags.includes('gguf')) score += 10if (category !== 'chat' && CATEGORY_SEARCH[category]?.split(/\s+/).some((term) => categoryText.includes(term))) score += 12- if (daysOld != null && daysOld <= 180) score += 8if (licenseOf(model)) score += 4if (/(uncensored|abliterated|nsfw)/i.test(repoId)) score -= 12return Math.round(score)@@ -349,6 +362,7 @@ function buildVariants(model, backend, usableBytes) {const sizeBytes = largestUnit > 0 ? largestUnit : nullreturn {quant,+ format: 'gguf',installId: variantInstallId(backend, repoId, quant),sizeBytes,size: formatBytes(sizeBytes) || quant,@@ -412,6 +426,85 @@ function isInstalled(backend, result, installedIds) {return installIdInstalled(backend, result.id, result.repository, installedIds)}+// ---- MLX (Apple Silicon) ----------------------------------------------------+// MLX is Apple's native ML format. It ships sharded `.safetensors` + a config+// (no single GGUF), and is installable ONLY via LM Studio (`lms get <repo>`) on+// Apple Silicon — Ollama's MLX path accelerates GGUF from its own registry and+// can't pull arbitrary HF safetensors repos, so MLX is never surfaced for the+// Ollama backend (the search gates the whole MLX query on lmstudio+Apple Silicon).+const MLX_PUBLISHER = 'mlx-community'+const SAFETENSORS_RE = /\.safetensors$/i++function safetensorsFilesOf(model) {+ return siblingsOf(model)+ .map((s) => ({ name: normalizeText(s.rfilename || s.name), size: Number.isFinite(s.size) ? s.size : null }))+ .filter((file) => SAFETENSORS_RE.test(file.name))+}++// Sum the safetensors shards — an MLX repo's resident footprint ≈ the weight+// total (same overhead heuristic as GGUF; MEMORY_OVERHEAD covers the KV cache).+function sumSafetensorsBytes(model) {+ const total = safetensorsFilesOf(model).reduce((sum, f) => sum + (f.size || 0), 0)+ return total > 0 ? total : null+}++// MLX quant from the repo-name suffix. mlx-community encodes the quant in the+// REPO name (one quant per repo), not per-file: `Qwen2.5-7B-Instruct-4bit`,+// `-8bit`, `-6bit`, `-3bit`, `-bf16`, `-fp16`, sometimes a trailing method tag+// (`-4bit-DWQ`). Null when unparseable (the bare repo still installs — LM Studio+// resolves it — but no quant label is shown).+function mlxQuantFromRepo(repoId) {+ const name = String(repoId).split('/').pop() || ''+ const m = name.match(/(?:^|[-_])(\d{1,2}bit|bf16|fp16|fp32|f16|f32)(?:[-_](?:dwq|hi|lo|mixed[a-z0-9_]*))?$/i)+ return m ? m[1].toLowerCase() : null+}++function hasMlxSignal(model) {+ const repoId = repoIdOf(model)+ const hasSafetensors = siblingsOf(model).some((s) => SAFETENSORS_RE.test(normalizeText(s.rfilename || s.name)))+ return (tagsOf(model).includes('mlx') || repoId.toLowerCase().includes('mlx') || publisherOf(repoId) === MLX_PUBLISHER)+ && hasSafetensors+}++// Build an MLX search result. Same shape as a GGUF result with `format: 'mlx'`,+// a single variant (the repo's quant), and the LM Studio bare-repo install id.+// Sizes/variant fit are backfilled in enrichWithSizes from `?blobs=true`.+function toMlxResult(model, requestedCategory, installedIds) {+ const repoId = repoIdOf(model)+ if (!repoId || !repoId.includes('/')) return null+ const category = classifyModel(model, requestedCategory)+ const quant = mlxQuantFromRepo(repoId)+ const result = {+ id: repoId, // `lms get <repo>` — the repo IS the quant for mlx-community+ key: repoId,+ name: displayName(repoId),+ category,+ params: extractParams(repoId) || 'MLX',+ size: quant ? quant.toUpperCase() : 'MLX',+ family: repoId.split('/').pop().split(/[-_]/)[0]?.toLowerCase() || 'huggingface',+ description: model?.cardData?.summary || model?.cardData?.description+ || 'Apple MLX model — installs via LM Studio on Apple Silicon.',+ capabilities: capabilitiesFor(model, category),+ installed: false,+ source: 'huggingface',+ format: 'mlx',+ repository: repoId,+ publisher: publisherOf(repoId),+ downloads: Number(model?.downloads || 0),+ likes: Number(model?.likes || 0),+ sizeBytes: null,+ contextLength: null,+ createdAt: model?.createdAt || model?.created_at || null,+ updatedAt: model?.lastModified || model?.last_modified || model?.updatedAt || null,+ license: licenseOf(model),+ quant,+ score: scoreModel(model, category, null),+ installable: true+ }+ result.installed = installIdInstalled('lmstudio', repoId, repoId, installedIds)+ return result+}+function toResult(model, backend, requestedCategory, installedIds, installedAudioRepos = new Set()) {const repoId = repoIdOf(model)if (!repoId || !repoId.includes('/')) return null@@ -442,6 +535,9 @@ function toResult(model, backend, requestedCategory, installedIds, installedAudicapabilities: capabilitiesFor(model, category),installed: false,source: 'huggingface',+ // Format discriminator for the UI badge: GGUF chat models vs. (separately+ // queried) MLX. Audio repos are neither, so they stay null.+ format: isAudio ? null : 'gguf',repository: repoId,publisher: publisherOf(repoId),downloads: Number(model?.downloads || 0),@@ -477,7 +573,11 @@ function hfHeaders() {return headers}-async function fetchModels(search, limit, useGgufFilter) {+// `filter` is a Hugging Face library tag — 'gguf' for the GGUF query, 'mlx' for+// the Apple-MLX query, or null/'' to relax the format filter (audio category and+// the GGUF-signal fallback). Only one filter at a time; MLX runs as a separate+// query so its results don't pollute the GGUF list.+async function fetchModels(search, limit, filter) {const params = new URLSearchParams({search,sort: 'downloads',@@ -485,7 +585,7 @@ async function fetchModels(search, limit, useGgufFilter) {limit: String(limit),full: 'true'})- if (useGgufFilter) params.set('filter', 'gguf')+ if (filter) params.set('filter', filter)const response = await fetchWithTimeout(`${HF_API_BASE}?${params.toString()}`, { headers: hfHeaders() }, HF_TIMEOUT_MS)if (!response.ok) {@@ -539,6 +639,33 @@ function contextLengthOf(model) {return Number.isFinite(n) && n > 0 ? n : null}+// Build the per-quant GGUF variant list onto `result` from a fetched repo record+// and anchor the result on the RAM-aware (or QUANT_PRIORITY) default. Shared by+// the live HF search and the curated-catalog enrichment so both cards behave the+// same. Returns true when variants were applied, false when the repo has no+// parseable GGUF quant (e.g. an MLX-only repo) so the caller can leave it as-is.+function applyGgufVariants(result, model, { backend, usableBytes, installedIds }) {+ const variants = buildVariants(model, backend, usableBytes)+ if (variants.length === 0) return false+ // Per-quant installed state — Ollama tracks each quant separately, so the card+ // must gate Install on the *selected* variant, not one repo-wide flag.+ for (const v of variants) v.installed = installIdInstalled(backend, v.installId, result.repository, installedIds)+ // Always anchor the result on one of its own variants so the install id and the+ // client's controlled <select> agree. Prefer the RAM-aware pick; otherwise the+ // QUANT_PRIORITY default (matched by quant); fall back to the largest variant.+ // `usableBytes != null` (not truthiness): 0 is a real budget on a tiny machine —+ // pick the smallest (all flagged too-large) rather than falling through as if+ // memory were unknown.+ const chosen = (usableBytes != null ? pickVariantForBudget(variants, usableBytes) : null)+ || variants.find((v) => v.quant && v.quant === result.quant)+ || variants[0]+ applyVariant(result, chosen)+ for (const v of variants) v.recommended = v.installId === result.id+ result.installed = chosen.installed+ result.variants = variants+ return true+}+// Backfill real file sizes AND native context windows from the per-model// `?blobs=true` record (the search listing carries neither). Both are fetched// from the same cached repo record, so a result missing either triggers one@@ -546,42 +673,40 @@ function contextLengthOf(model) {async function enrichWithSizes(results, { backend, usableBytes, installedIds = [] } = {}) {await Promise.allSettled(results.map(async (result) => {const isAudio = result.category === 'audio'+ const isMlx = result.format === 'mlx'const needsSize = !Number.isFinite(result.sizeBytes)- const needsContext = !isAudio && result.contextLength == null+ // MLX repos carry no GGUF metadata block, so they have no native-context field.+ const needsContext = !isAudio && !isMlx && result.contextLength == null// Variants come only from the per-repo `?blobs=true` record (the listing// omits per-file sizes), so build them here for every non-audio result.const needsVariants = !isAudio && !result.variantsif (!needsSize && !needsContext && !needsVariants) returnconst model = await fetchRepoModel(result.repository)if (!model) return- if (!isAudio) {- const variants = buildVariants(model, backend, usableBytes)- if (variants.length > 0) {- // Per-quant installed state — Ollama tracks each quant separately, so the- // card must gate Install on the *selected* variant, not one repo-wide flag.- for (const v of variants) v.installed = installIdInstalled(backend, v.installId, result.repository, installedIds)- // Always anchor the result on one of its own variants so the install id- // and the client's controlled <select> agree. Prefer the RAM-aware pick;- // otherwise the QUANT_PRIORITY default toResult chose (matched by quant);- // fall back to the largest variant. Without this, LM Studio's bare-repo- // default id — and any repo where the blobs endpoint omits sizes, so the- // budget pick can't fire — would match no variant, flagging zero- // recommended and making Install pull a different quant than the one shown.- // `usableBytes != null` (not truthiness): 0 is a real budget on a tiny- // machine — pick the smallest (all flagged too-large) rather than falling- // through to QUANT_PRIORITY as if memory were unknown.- const chosen = (usableBytes != null ? pickVariantForBudget(variants, usableBytes) : null)- || variants.find((v) => v.quant && v.quant === result.quant)- || variants[0]- applyVariant(result, chosen)- // Flag whichever variant the result now points at as recommended so the- // UI can mark it (covers both the RAM-aware and QUANT_PRIORITY default).- for (const v of variants) v.recommended = v.installId === result.id- // Realign the result-level installed flag with the (possibly RAM-switched)- // default variant — toResult computed it against the pre-switch id.- result.installed = chosen.installed- result.variants = variants+ if (isMlx) {+ // MLX size = summed safetensors shards. The picker shows a single variant+ // (the repo's quant) so the card UI matches the multi-quant GGUF cards.+ const bytes = sumSafetensorsBytes(model)+ if (Number.isFinite(bytes)) {+ result.sizeBytes = bytes+ result.size = formatBytes(bytes) || result.size}+ const variant = {+ quant: result.quant || 'mlx',+ format: 'mlx',+ installId: result.id, // bare repo — mlx-community encodes the quant in the name+ sizeBytes: Number.isFinite(result.sizeBytes) ? result.sizeBytes : null,+ size: formatBytes(result.sizeBytes) || (result.quant ? result.quant.toUpperCase() : 'MLX'),+ fit: classifyFit(result.sizeBytes, usableBytes),+ installed: installIdInstalled(backend, result.id, result.repository, installedIds),+ recommended: true+ }+ result.variants = [variant]+ result.installed = variant.installed+ return+ }+ if (!isAudio) {+ applyGgufVariants(result, model, { backend, usableBytes, installedIds })}if (needsSize && !Number.isFinite(result.sizeBytes)) {const bytes = isAudio@@ -618,7 +743,7 @@ function curatedAudioResult(entry, installedAudioRepos) {}}-export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [], installedAudioRepos = [], systemMemoryBytes = null }) {+export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [], installedAudioRepos = [], systemMemoryBytes = null, appleSilicon = false }) {if (!isBackend(backend)) return []const requestedCategory = CATEGORY_IDS.has(category) ? category : 'all'// Usable RAM drives the per-quant fit verdicts and the RAM-aware default pick;@@ -631,8 +756,17 @@ export async function searchHuggingFaceModels({ backend, query = '', category =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, ggufOnly)- if (models.length === 0 && ggufOnly) models = await fetchModels(search, fetchLimit, false)+ // MLX is only installable via LM Studio on Apple Silicon (see toMlxResult), so+ // run the extra MLX query only there — never for Ollama, non-Apple hosts, or+ // the audio category. `appleSilicon` is injected by the route (default false),+ // keeping the service deterministic for tests regardless of the test host.+ const wantMlx = appleSilicon && backend === 'lmstudio' && requestedCategory !== 'audio'+ const [ggufModelsRaw, mlxModelsRaw] = await Promise.all([+ fetchModels(search, fetchLimit, ggufOnly ? 'gguf' : null),+ wantMlx ? fetchModels(search, fetchLimit, 'mlx') : Promise.resolve([])+ ])+ let models = ggufModelsRaw+ if (models.length === 0 && ggufOnly) models = await fetchModels(search, fetchLimit, null)const seen = new Set()// Curated audio suggestions lead the Audio & Music list (filtered by query@@ -663,9 +797,84 @@ export async function searchHuggingFaceModels({ backend, query = '', category =return true})- const results = [...curated, ...live]+ // MLX results (LM Studio + Apple Silicon only) merge into the same list — each+ // is its own card (`format: 'mlx'`), deduped against the GGUF repos already seen.+ const mlxLive = mlxModelsRaw+ .filter((model) => hasMlxSignal(model))+ .map((model) => toMlxResult(model, requestedCategory, installedIds))+ .filter(Boolean)+ .filter((model) => {+ if (seen.has(model.repository)) return false+ seen.add(model.repository)+ return true+ })++ const results = [...curated, ...live, ...mlxLive].sort((a, b) => b.score - a.score || b.downloads - a.downloads).slice(0, limit)return enrichWithSizes(results, { backend, usableBytes, installedIds })}++// The Hugging Face repo backing a curated install id, or null for a bare Ollama+// registry name. LM Studio curated ids ARE HF repos (`publisher/Repo-GGUF`);+// Ollama ids are HF-backed only when prefixed `hf.co/`. Bare Ollama names+// (`llama3.2`, `qwen2.5`) pull from Ollama's own registry — per-quant variants+// for those need the Ollama registry tag API (tracked as follow-up #1539), so+// they get no picker here.+function catalogRepoForBackend(backend, id) {+ const raw = String(id || '')+ if (backend === 'lmstudio') return raw.includes('/') ? raw.split('@')[0] : null+ const m = raw.match(/^hf\.co\/(.+)$/i)+ return m ? m[1].split(':')[0] : null+}++// Quant tag baked into a curated install id (`<repo>@Q4_K_M` / `hf.co/<repo>:Q4`),+// so the no-RAM-budget fallback can anchor on the curator's chosen quant. Null+// for ids with no quant tag (bare LM Studio repos / bare Ollama names).+function quantFromInstallId(backend, id) {+ const raw = String(id || '')+ if (backend === 'lmstudio') {+ const at = raw.indexOf('@')+ return at >= 0 ? raw.slice(at + 1) : null+ }+ const slash = raw.indexOf('/')+ const colon = raw.lastIndexOf(':')+ return colon > slash ? raw.slice(colon + 1) : null+}++// Enrich curated-catalog entries (from localLlmCatalog.getCatalog) in place with+// the same per-quant variant picker + RAM-aware default the live HF search uses,+// for every entry that is HF-repo-backed (see catalogRepoForBackend). Entries+// with no HF repo (bare Ollama registry names) or an MLX-only repo (no GGUF+// quants) are left untouched — the card then shows the curator's single id with+// no picker. `usableBytes` makes the recommended quant fit this machine.+export async function enrichCatalogWithVariants(catalog, { backend, systemMemoryBytes = null, installedIds = [] } = {}) {+ if (!isBackend(backend) || !Array.isArray(catalog)) return catalog+ const usableBytes = usableMemoryBytes(systemMemoryBytes)+ await Promise.allSettled(catalog.map(async (entry) => {+ const repo = catalogRepoForBackend(backend, entry.id)+ if (!repo) return+ const model = await fetchRepoModel(repo)+ if (!model) return+ entry.repository = repo+ // Seed the quant from the curator's id so the no-budget fallback anchors on it.+ if (entry.quant == null) entry.quant = quantFromInstallId(backend, entry.id)+ const applied = applyGgufVariants(entry, model, { backend, usableBytes, installedIds })+ if (!applied) return // MLX-only / no parseable GGUF quant — leave the curated entry as-is+ entry.format = 'gguf'+ // Backfill the real size + native context window the curated list hard-codes.+ if (!Number.isFinite(entry.sizeBytes)) {+ const picked = pickGgufFile(model)+ if (Number.isFinite(picked?.size)) {+ entry.sizeBytes = picked.size+ entry.size = formatBytes(picked.size) || entry.size+ }+ }+ if (entry.contextLength == null) {+ const ctx = contextLengthOf(model)+ if (ctx != null) entry.contextLength = ctx+ }+ }))+ return catalog+}diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.jsindex fce661b704..4adb51daf1 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'-import { searchHuggingFaceModels } from './huggingFaceCatalog.js'+import { searchHuggingFaceModels, enrichCatalogWithVariants } from './huggingFaceCatalog.js'const response = (body, ok = true) => ({ok,@@ -413,6 +413,163 @@ describe('huggingFaceCatalog', () => {})})+ describe('sort order', () => {+ it('ranks by downloads, with recency breaking near-ties between equally-popular models', async () => {+ const now = Date.now()+ const day = 86_400_000+ const models = [+ { modelId: 'org/Old-Popular-GGUF', downloads: 5000, lastModified: new Date(now - 800 * day).toISOString(), tags: ['gguf'], siblings: [{ rfilename: 'm-Q4_K_M.gguf', size: 4_000_000_000 }] },+ { modelId: 'org/New-Popular-GGUF', downloads: 5000, lastModified: new Date(now - 3 * day).toISOString(), tags: ['gguf'], siblings: [{ rfilename: 'm-Q4_K_M.gguf', size: 4_000_000_000 }] },+ { modelId: 'org/Huge-GGUF', downloads: 5_000_000, lastModified: new Date(now - 200 * day).toISOString(), tags: ['gguf'], siblings: [{ rfilename: 'm-Q4_K_M.gguf', size: 4_000_000_000 }] },+ ]+ fetch.mockImplementation(async (url) => (+ String(url).includes('blobs=true')+ ? response({ id: 'x', siblings: [{ rfilename: 'm-Q4_K_M.gguf', size: 4_000_000_000 }] })+ : response(models)+ ))++ const results = await searchHuggingFaceModels({ backend: 'ollama', query: 'm' })+ const order = results.map((r) => r.repository)++ // Far-and-away most-downloaded model leads overall.+ expect(order[0]).toBe('org/Huge-GGUF')+ // Between two models with identical downloads, the fresher one ranks higher.+ expect(order.indexOf('org/New-Popular-GGUF')).toBeLessThan(order.indexOf('org/Old-Popular-GGUF'))+ })+ })++ describe('MLX models (Apple Silicon)', () => {+ // URL-aware mock: order matters (most-specific first). MLX adds a parallel+ // `filter=mlx` query + per-repo blobs fetch, so a sequential mock is fragile;+ // route by URL instead.+ const urlRouter = (routes) => vi.fn(async (url) => {+ const u = String(url)+ for (const [match, body] of routes) {+ const hit = typeof match === 'function' ? match(u) : u.includes(match)+ if (hit) return response(body)+ }+ return response([])+ })+ const mlxListing = (modelId, files) => (+ { modelId, downloads: 5000, likes: 200, tags: ['mlx', 'safetensors'], siblings: files.map((rfilename) => ({ rfilename })) }+ )+ const mlxBlobs = (id, sized) => ({ id, siblings: Object.entries(sized).map(([rfilename, size]) => ({ rfilename, size })) })++ it('surfaces an MLX result for LM Studio on Apple Silicon with a summed safetensors variant', async () => {+ const repo = 'mlx-community/Qwythos-9B-MLX-4bit'+ fetch.mockImplementation(urlRouter([+ ['filter=mlx', [mlxListing(repo, ['model-00001-of-00002.safetensors', 'model-00002-of-00002.safetensors'])]],+ ['filter=gguf', []],+ [(u) => u.includes('blobs=true'), mlxBlobs(repo, {+ 'model-00001-of-00002.safetensors': 9_000_000_000,+ 'model-00002-of-00002.safetensors': 9_000_000_000,+ })],+ ]))++ const results = await searchHuggingFaceModels({+ backend: 'lmstudio', query: 'qwythos', systemMemoryBytes: 128 * 1024 ** 3, appleSilicon: true+ })+ const mlx = results.find((r) => r.repository === repo)++ expect(mlx).toBeTruthy()+ expect(mlx).toMatchObject({ format: 'mlx', id: repo, quant: '4bit', installable: true, sizeBytes: 18_000_000_000 })+ expect(mlx.variants).toHaveLength(1)+ expect(mlx.variants[0]).toMatchObject({ format: 'mlx', quant: '4bit', installId: repo, sizeBytes: 18_000_000_000, fit: 'comfortable', recommended: true })+ })++ it('never surfaces MLX for the Ollama backend (Ollama MLX uses its own registry, not HF safetensors)', async () => {+ const ggufRepo = 'org/Plain-GGUF'+ const mlxRepo = 'mlx-community/Should-Not-Appear-4bit'+ fetch.mockImplementation(urlRouter([+ ['filter=mlx', [mlxListing(mlxRepo, ['model.safetensors'])]],+ ['filter=gguf', [{ modelId: ggufRepo, downloads: 10, tags: ['gguf'], siblings: [{ rfilename: 'Plain-Q4_K_M.gguf', size: 4_000_000_000 }] }]],+ [(u) => u.includes('blobs=true'), { id: ggufRepo, siblings: [{ rfilename: 'Plain-Q4_K_M.gguf', size: 4_000_000_000 }] }],+ ]))++ const results = await searchHuggingFaceModels({ backend: 'ollama', query: 'plain', appleSilicon: true })++ expect(results.some((r) => r.format === 'mlx')).toBe(false)+ expect(results.some((r) => r.repository === mlxRepo)).toBe(false)+ })++ it('does not surface MLX on a non-Apple host even for LM Studio', async () => {+ const mlxRepo = 'mlx-community/Hidden-On-Intel-4bit'+ fetch.mockImplementation(urlRouter([+ ['filter=mlx', [mlxListing(mlxRepo, ['model.safetensors'])]],+ ['filter=gguf', []],+ ]))++ const results = await searchHuggingFaceModels({ backend: 'lmstudio', query: 'hidden', appleSilicon: false })++ expect(results.some((r) => r.repository === mlxRepo)).toBe(false)+ })++ it('parses a bf16 repo-name quant and marks an installed MLX repo', async () => {+ const repo = 'mlx-community/Qwythos-9B-MLX-bf16'+ fetch.mockImplementation(urlRouter([+ ['filter=mlx', [mlxListing(repo, ['model.safetensors'])]],+ ['filter=gguf', []],+ [(u) => u.includes('blobs=true'), mlxBlobs(repo, { 'model.safetensors': 18_000_000_000 })],+ ]))++ const results = await searchHuggingFaceModels({+ backend: 'lmstudio', query: 'qwythos', systemMemoryBytes: 128 * 1024 ** 3, appleSilicon: true, installedIds: [repo]+ })+ const mlx = results.find((r) => r.repository === repo)++ expect(mlx.quant).toBe('bf16')+ expect(mlx.installed).toBe(true)+ expect(mlx.variants[0].installed).toBe(true)+ })+ })++ describe('curated catalog quant enrichment', () => {+ const blobs = (id, sized) => response({ id, siblings: Object.entries(sized).map(([rfilename, size]) => ({ rfilename, size })) })++ it('adds the RAM-aware variant picker to an LM Studio curated (HF-repo) entry', async () => {+ const repo = 'lmstudio-community/Curated-Llama-GGUF'+ fetch.mockResolvedValueOnce(blobs(repo, {+ 'Curated-Llama-Q4_K_M.gguf': 4_000_000_000,+ 'Curated-Llama-Q8_0.gguf': 8_000_000_000,+ }))++ const catalog = [{ id: repo, key: 'curated-llama', name: 'Curated Llama', category: 'chat', size: '2.0 GB' }]+ await enrichCatalogWithVariants(catalog, { backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [] })++ expect(catalog[0].format).toBe('gguf')+ expect(catalog[0].variants.map((v) => v.installId)).toEqual([`${repo}@Q8_0`, `${repo}@Q4_K_M`])+ // 128 GB → highest-fidelity that fits becomes the recommended default.+ expect(catalog[0].id).toBe(`${repo}@Q8_0`)+ expect(catalog[0].variants.find((v) => v.recommended).installId).toBe(`${repo}@Q8_0`)+ expect(catalog[0].sizeBytes).toBe(8_000_000_000)+ })++ it('enriches an Ollama hf.co curated id and keeps the hf.co install ids', async () => {+ const repo = 'unsloth/Curated-Devstral-GGUF'+ fetch.mockResolvedValueOnce(blobs(repo, {+ 'Devstral-UD-Q4_K_XL.gguf': 14_000_000_000,+ 'Devstral-Q8_0.gguf': 24_000_000_000,+ }))++ const catalog = [{ id: `hf.co/${repo}:UD-Q4_K_XL`, key: 'devstral', name: 'Devstral', category: 'coding', size: '14 GB' }]+ await enrichCatalogWithVariants(catalog, { backend: 'ollama', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [] })++ expect(catalog[0].variants.map((v) => v.installId)).toEqual([`hf.co/${repo}:Q8_0`, `hf.co/${repo}:UD-Q4_K_XL`])+ expect(catalog[0].id).toBe(`hf.co/${repo}:Q8_0`)+ })++ it('leaves a bare Ollama registry name untouched (no HF repo → no picker)', async () => {+ fetch.mockResolvedValue(response([]))+ const catalog = [{ id: 'llama3.2', key: 'llama3.2', name: 'Llama 3.2 3B', category: 'chat', size: '2.0 GB' }]+ await enrichCatalogWithVariants(catalog, { backend: 'ollama', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [] })++ expect(catalog[0].variants).toBeUndefined()+ expect(catalog[0].id).toBe('llama3.2')+ // No HF repo means no network probe at all.+ expect(fetch).not.toHaveBeenCalled()+ })+ })+describe('audio installed registry', () => {it('marks an audio model installed when it is in the shared registry', async () => {fetch.mockResolvedValue(response([