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

HF model search: pick a GGUF quant + default to the largest that fits RAM

[._.]/ Adam Eivy2cb03810d694
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3c792da689..3054800bda 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## 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>`.
+
## Comic pages
- **[issue-1534] Refine a rendered comic page with a small fix instead of re-rendering it from scratch.** Each rendered page now has a **Refine** box: type a free-text adjustment ("warm the lighting", "remove the extra signage text", "make the two background figures match across panels") and the page re-renders image-to-image from its *existing* image, applying only that change while preserving everything that was already right. The AI tweaks the page's current render prompt to reflect your instruction (it does not regenerate the prompt from the comic script), then runs a low-denoise re-render off the page's own image — so the panel layout, composition, and lettering survive. It refines the page's final render when one exists, otherwise its proof, and shows a short "what changed" summary after each refine. Works with both the local and Codex image backends.
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 13dd987402..8e2e5deebf 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -47,6 +47,14 @@ const CAPABILITY_META = {
audio: { Icon: Music, label: 'Audio generation', cls: 'text-pink-400 border-pink-400/50' },
};
+// Server-computed per-quant fit verdict → badge styling + short label. Drives
+// the RAM-fit hint on the quant picker so a too-large build reads as a warning.
+const FIT_META = {
+ comfortable: { label: 'fits comfortably', cls: 'text-port-success' },
+ tight: { label: 'tight fit', cls: 'text-port-warning' },
+ 'too-large': { label: 'exceeds RAM', cls: 'text-port-error' },
+};
+
// Summarize a migrate result for the success toast (per-model statuses → counts).
function summarizeMigrate(r) {
@@ -212,6 +220,12 @@ export function LocalLlmTab() {
const [catalog, setCatalog] = useState([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [catalogError, setCatalogError] = useState('');
+ // Total unified/system memory (GB) reported by the HF search, used to caption
+ // the RAM-aware quant defaults. null until the first Hugging Face search.
+ const [systemMemoryGb, setSystemMemoryGb] = useState(null);
+ // Per-result quant override: { [repoKey]: installId }. Empty → use each
+ // result's RAM-aware default (`m.id`). Cleared whenever the catalog reloads.
+ const [selectedVariants, setSelectedVariants] = useState({});
const [activeCategory, setActiveCategory] = useState('all');
const [query, setQuery] = useState('');
const [manualId, setManualId] = useState('');
@@ -259,6 +273,9 @@ export function LocalLlmTab() {
.then((r) => {
if (requestId !== catalogRequestId.current) return;
setCatalog(r.models || []);
+ if (Number.isFinite(r.systemMemoryGb)) setSystemMemoryGb(r.systemMemoryGb);
+ // A fresh result set invalidates any per-card quant overrides.
+ setSelectedVariants({});
})
.catch((err) => {
if (requestId !== catalogRequestId.current) return;
@@ -695,6 +712,11 @@ export function LocalLlmTab() {
{catalogError && (
<p className="text-xs text-port-warning">{catalogError}</p>
)}
+ {catalogSource === 'huggingface' && Number.isFinite(systemMemoryGb) && (
+ <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>
+ )}
{/* Catalog cards */}
<div className="space-y-4">
@@ -705,22 +727,59 @@ export function LocalLlmTab() {
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{group.models.map((m) => {
- const ram = recommendedRamGb(m?.sizeBytes, m?.size);
- const ctxLabel = formatContextLength(m.contextLength);
const isHf = m.source === 'huggingface';
const isAudio = m.category === 'audio';
+ // Multi-quant repos let the user trade their RAM for fidelity.
+ // `chosenId` is the selected variant's install id (defaulting to
+ // the server's RAM-aware pick `m.id`); the card's size/RAM/fit
+ // reflect that choice.
+ const variants = (!isAudio && Array.isArray(m.variants)) ? m.variants : [];
+ const hasVariantPicker = variants.length > 1;
+ // Default to the server's RAM-aware pick (`m.id`). If it doesn't
+ // line up with a listed variant, fall back to the recommended
+ // one so the controlled <select> always has a matching option.
+ const idMatchesVariant = variants.some((v) => v.installId === m.id);
+ const recommendedId = variants.find((v) => v.recommended)?.installId;
+ const chosenId = selectedVariants[m.key] || (idMatchesVariant ? m.id : recommendedId) || m.id;
+ const chosenVariant = variants.find((v) => v.installId === chosenId) || null;
+ const size = chosenVariant?.size || m.size;
+ const sizeBytes = chosenVariant?.sizeBytes ?? m.sizeBytes;
+ const fit = chosenVariant?.fit;
+ const fitMeta = fit ? FIT_META[fit] : null;
+ const ram = recommendedRamGb(sizeBytes, size);
+ const ctxLabel = formatContextLength(m.contextLength);
const createdMs = new Date(m.createdAt).getTime();
const updatedMs = new Date(m.updatedAt).getTime();
return (
- <div key={m.id} className="flex items-start gap-3 bg-port-bg border border-port-border rounded-lg p-3">
+ <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-xs text-gray-500 truncate">{m.id}</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>}
+ {hasVariantPicker && (
+ <div className="flex items-center gap-1.5 flex-wrap mt-1">
+ <label htmlFor={`quant-${m.key}`} className="text-[11px] text-gray-500">Quant</label>
+ <select
+ id={`quant-${m.key}`}
+ value={chosenId}
+ onChange={(e) => setSelectedVariants((prev) => ({ ...prev, [m.key]: e.target.value }))}
+ disabled={busy}
+ className="text-[11px] bg-port-card border border-port-border rounded px-1.5 py-0.5 text-gray-300 max-w-[16rem]"
+ title="Pick a quantization — higher quants are larger but higher fidelity"
+ >
+ {variants.map((v) => (
+ <option key={v.installId} value={v.installId}>
+ {v.quant}{v.size ? ` · ${v.size}` : ''}{v.recommended ? ' · recommended' : ''}{v.fit === 'too-large' ? ' · exceeds RAM' : ''}
+ </option>
+ ))}
+ </select>
+ {fitMeta && <span className={`text-[11px] ${fitMeta.cls}`} title="Fit on this machine — model weights + ~20% overhead vs. usable memory">{fitMeta.label}</span>}
+ </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>
+ <span>{size}</span>
{ctxLabel && (
<span title="Native context window (max tokens)">{ctxLabel}</span>
)}
@@ -766,11 +825,11 @@ export function LocalLlmTab() {
null
) : (
<button
- onClick={() => (isAudio ? installAudio(m) : install(m.id))}
+ onClick={() => (isAudio ? installAudio(m) : install(chosenId))}
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"
>
- {actionInProgress === `install-${m.id}` ? <BrailleSpinner /> : <Download size={12} />}
+ {actionInProgress === `install-${chosenId}` ? <BrailleSpinner /> : <Download size={12} />}
Install
</button>
)}
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index dfa3b2ca3d..a240425736 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -8,6 +8,7 @@
* contract the Database tab uses).
*/
+import os from 'os'
import { Router } from 'express'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
import {
@@ -78,8 +79,12 @@ router.get('/huggingface-search', asyncHandler(async (req, res) => {
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 })
+ // Total system memory drives the RAM-aware default quant pick and the per-quant
+ // 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) })
}))
// POST /api/local-llm/install-backend — install the backend app/binary itself
diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.js
index 9bf3b031a7..5d8f5dee59 100644
--- a/server/services/huggingFaceCatalog.js
+++ b/server/services/huggingFaceCatalog.js
@@ -101,12 +101,44 @@ const QUANT_PRIORITY = [
'F16'
]
+// Weights → resident RAM multiplier (KV cache + runtime overhead). Mirrors the
+// client's `recommendedRamGb` (~20% overhead) so the server's "does it fit"
+// verdict and the UI's per-model RAM estimate agree.
+const MEMORY_OVERHEAD = 1.2
+
+// Usable RAM for a model after reserving headroom for the OS, the GGUF KV cache
+// growth, and other resident apps. On unified-memory Macs this same pool also
+// backs the GPU, so we reserve generously: max(8 GB, 20% of total). Returns null
+// when the caller didn't supply a system-memory figure — that disables the
+// RAM-aware default pick and leaves the QUANT_PRIORITY default untouched.
+function usableMemoryBytes(systemMemoryBytes) {
+ if (!Number.isFinite(systemMemoryBytes) || systemMemoryBytes <= 0) return null
+ const reserve = Math.max(8 * 1024 ** 3, systemMemoryBytes * 0.2)
+ return Math.max(0, systemMemoryBytes - reserve)
+}
+
+function estimatedResidentBytes(sizeBytes) {
+ return Number.isFinite(sizeBytes) && sizeBytes > 0 ? sizeBytes * MEMORY_OVERHEAD : null
+}
+
+// How comfortably a quant's estimated resident footprint fits the usable budget.
+// 'unknown' when either the file size or the machine's memory is unavailable.
+function classifyFit(sizeBytes, usableBytes) {
+ const resident = estimatedResidentBytes(sizeBytes)
+ if (resident == null || !Number.isFinite(usableBytes) || usableBytes <= 0) return 'unknown'
+ if (resident > usableBytes) return 'too-large'
+ if (resident > usableBytes * 0.6) return 'tight'
+ return 'comfortable'
+}
+
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, '')
+ // Drop a trailing `@quant` (added when a specific variant is selected) so the
+ // bare-repo installed list still matches a quant-tagged result id.
+ return raw.split('/').pop().replace(/@[^/]*$/, '').replace(/[-.]gguf$/i, '')
}
function repoIdOf(model) {
@@ -138,7 +170,12 @@ function hasGgufSignal(model) {
}
function quantFromFilename(filename) {
- const stem = normalizeText(filename).split('/').pop().replace(/\.gguf$/i, '')
+ const stem = normalizeText(filename).split('/').pop()
+ .replace(/\.gguf$/i, '')
+ // Multi-part GGUF shards (`…-00001-of-00002`) carry the quant before the
+ // shard suffix — strip it so BF16/F16 splits resolve to their real quant
+ // instead of failing the match and being dropped from the variant list.
+ .replace(/-\d{5}-of-\d{5}$/i, '')
const match = stem.match(/(?:UD-)?(?:IQ\d(?:_[A-Z0-9]+)*|Q\d(?:_[A-Z0-9]+)*|BF16|F16)$/i)
return match?.[0] || null
}
@@ -251,10 +288,69 @@ function displayName(repoId) {
return repoId.split('/').pop().replace(/[-_]?gguf$/i, '').replace(/[-_]+/g, ' ').trim() || repoId
}
+// Backend-specific pull/download id for a chosen quant.
+// ollama → `hf.co/<repo>:<quant>` (Ollama resolves the GGUF, incl. shards)
+// lmstudio → `<repo>@<quant>` (the `lms get <repo>@<quant>` syntax)
+// A null quant falls back to the bare repo so the backend picks its own default.
+function variantInstallId(backend, repoId, quant) {
+ if (backend === 'lmstudio') return quant ? `${repoId}@${quant}` : repoId
+ return `hf.co/${repoId}${quant ? `:${quant}` : ''}`
+}
+
function installIdForBackend(backend, repoId, file) {
+ // The default result keeps LM Studio's bare-repo id (LM Studio resolves a
+ // recommended quant itself); the quant only enters the id when a specific
+ // variant is selected or the RAM-aware default re-pick applies one.
if (backend === 'lmstudio') return repoId
- const quant = file?.quant
- return `hf.co/${repoId}${quant ? `:${quant}` : ''}`
+ return variantInstallId('ollama', repoId, file?.quant)
+}
+
+// Every installable GGUF quant in a repo, deduped by quant (multi-part shards
+// summed), sorted by size DESC (≈ fidelity DESC) so the picker lists the
+// highest-quality build first. Files whose quant can't be parsed are skipped —
+// they have no `:quant`/`@quant` tag a backend can pull. `usableBytes` annotates
+// each variant with a fit verdict for the UI (null → 'unknown').
+function buildVariants(model, backend, usableBytes) {
+ const repoId = repoIdOf(model)
+ const groups = new Map()
+ for (const file of ggufFilesOf(model)) {
+ const quant = quantFromFilename(file.name)
+ if (!quant) continue
+ const group = groups.get(quant) || { quant, sizeBytes: 0 }
+ group.sizeBytes += Number.isFinite(file.size) ? file.size : 0
+ groups.set(quant, group)
+ }
+ return [...groups.values()]
+ .map((group) => {
+ const sizeBytes = group.sizeBytes > 0 ? group.sizeBytes : null
+ return {
+ quant: group.quant,
+ installId: variantInstallId(backend, repoId, group.quant),
+ sizeBytes,
+ size: formatBytes(sizeBytes) || group.quant,
+ fit: classifyFit(sizeBytes, usableBytes)
+ }
+ })
+ .sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0))
+}
+
+// RAM-aware default: the highest-fidelity variant whose estimated resident
+// footprint fits the usable budget (variants are size-desc, so the first that
+// fits is the best). If none fit, fall back to the smallest. Returns null when
+// no variant carries a known size (caller keeps the QUANT_PRIORITY default).
+function pickVariantForBudget(variants, usableBytes) {
+ const sized = variants.filter((v) => Number.isFinite(v.sizeBytes) && v.sizeBytes > 0)
+ if (sized.length === 0) return null
+ return sized.find((v) => estimatedResidentBytes(v.sizeBytes) <= usableBytes) || sized[sized.length - 1]
+}
+
+// Promote a chosen variant onto the result's primary install fields so the
+// default card reflects it (id/quant/size) without the client having to re-pick.
+function applyVariant(result, variant) {
+ result.id = variant.installId
+ result.quant = variant.quant
+ result.sizeBytes = variant.sizeBytes
+ result.size = variant.size
}
function isInstalled(backend, result, installedIds) {
@@ -397,15 +493,32 @@ function contextLengthOf(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
// (deduped) per-repo fetch.
-async function enrichWithSizes(results) {
+async function enrichWithSizes(results, { backend, usableBytes } = {}) {
await Promise.allSettled(results.map(async (result) => {
+ const isAudio = result.category === 'audio'
const needsSize = !Number.isFinite(result.sizeBytes)
- const needsContext = result.category !== 'audio' && result.contextLength == null
- if (!needsSize && !needsContext) return
+ const needsContext = !isAudio && 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.variants
+ if (!needsSize && !needsContext && !needsVariants) return
const model = await fetchRepoModel(result.repository)
if (!model) return
- if (needsSize) {
- const bytes = result.category === 'audio'
+ if (!isAudio) {
+ const variants = buildVariants(model, backend, usableBytes)
+ if (variants.length > 0) {
+ // RAM-aware default: only re-pick when we have a memory budget; without
+ // one, keep the QUANT_PRIORITY default chosen in toResult.
+ const chosen = usableBytes ? pickVariantForBudget(variants, usableBytes) : null
+ if (chosen) 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
+ result.variants = variants
+ }
+ }
+ if (needsSize && !Number.isFinite(result.sizeBytes)) {
+ const bytes = isAudio
? sumWeightBytes(model)
: (() => { const picked = pickGgufFile(model); return Number.isFinite(picked?.size) ? picked.size : null })()
if (Number.isFinite(bytes)) {
@@ -439,9 +552,12 @@ function curatedAudioResult(entry, installedAudioRepos) {
}
}
-export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [], installedAudioRepos = [] }) {
+export async function searchHuggingFaceModels({ backend, query = '', category = 'all', limit = 12, installedIds = [], installedAudioRepos = [], systemMemoryBytes = null }) {
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;
+ // null (no system-memory figure) keeps the QUANT_PRIORITY default behaviour.
+ const usableBytes = usableMemoryBytes(systemMemoryBytes)
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
@@ -485,5 +601,5 @@ export async function searchHuggingFaceModels({ backend, query = '', category =
.sort((a, b) => b.score - a.score || b.downloads - a.downloads)
.slice(0, limit)
- return enrichWithSizes(results)
+ return enrichWithSizes(results, { backend, usableBytes })
}
diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.js
index f9a30cb4c2..d1097327ae 100644
--- a/server/services/huggingFaceCatalog.test.js
+++ b/server/services/huggingFaceCatalog.test.js
@@ -198,6 +198,111 @@ describe('huggingFaceCatalog', () => {
expect(results.find((r) => r.repository === 'meta-llama/Llama-3.1-8B-Instruct')).toBeUndefined()
})
+ })
+
+ describe('quant variants + RAM-aware default', () => {
+ // Each test uses a UNIQUE repo id: `fetchRepoModel` caches per repo at module
+ // scope, so reusing an id would replay a prior test's blobs response.
+ const listing = (modelId, files) => response([
+ { modelId, downloads: 100, likes: 10, tags: ['gguf'], siblings: files.map((rfilename) => ({ rfilename })) }
+ ])
+ const blobs = (id, sized) => response({ id, siblings: Object.entries(sized).map(([rfilename, size]) => ({ rfilename, size })) })
+
+ it('exposes every quant as a size-desc variant and defaults to the largest that fits a big machine', async () => {
+ const repo = 'empero-ai/Qwythos-9B-Claude-GGUF'
+ fetch
+ .mockResolvedValueOnce(listing(repo, ['Qwythos-9B-Q4_K_M.gguf', 'Qwythos-9B-Q8_0.gguf', 'Qwythos-9B-BF16.gguf']))
+ .mockResolvedValueOnce(blobs(repo, {
+ 'Qwythos-9B-Q4_K_M.gguf': 5_500_000_000,
+ 'Qwythos-9B-Q8_0.gguf': 9_500_000_000,
+ 'Qwythos-9B-BF16.gguf': 18_000_000_000,
+ }))
+
+ const [result] = await searchHuggingFaceModels({ backend: 'ollama', query: 'qwythos', systemMemoryBytes: 128 * 1024 ** 3 })
+
+ expect(result.variants.map((v) => v.quant)).toEqual(['BF16', 'Q8_0', 'Q4_K_M'])
+ expect(result.variants[0].installId).toBe(`hf.co/${repo}:BF16`)
+ // 128 GB unified memory → default to the highest-fidelity build that fits.
+ expect(result).toMatchObject({ id: `hf.co/${repo}:BF16`, quant: 'BF16', sizeBytes: 18_000_000_000 })
+ expect(result.variants.find((v) => v.quant === 'BF16')).toMatchObject({ recommended: true, fit: 'comfortable' })
+ })
+
+ it('defaults to a small quant on a low-memory machine', async () => {
+ const repo = 'empero-ai/Qwythos-9B-Small-GGUF'
+ fetch
+ .mockResolvedValueOnce(listing(repo, ['Qwythos-9B-Q4_K_M.gguf', 'Qwythos-9B-Q8_0.gguf', 'Qwythos-9B-BF16.gguf']))
+ .mockResolvedValueOnce(blobs(repo, {
+ 'Qwythos-9B-Q4_K_M.gguf': 5_500_000_000,
+ 'Qwythos-9B-Q8_0.gguf': 9_500_000_000,
+ 'Qwythos-9B-BF16.gguf': 18_000_000_000,
+ }))
+
+ // 16 GB total → usable 8 GB → only Q4_K_M's ~6.6 GB resident estimate fits.
+ const [result] = await searchHuggingFaceModels({ backend: 'ollama', query: 'qwythos', systemMemoryBytes: 16 * 1024 ** 3 })
+
+ expect(result).toMatchObject({ id: `hf.co/${repo}:Q4_K_M`, quant: 'Q4_K_M' })
+ const byQuant = Object.fromEntries(result.variants.map((v) => [v.quant, v.fit]))
+ // Q4_K_M still fits (it's the chosen default) but its ~6.6 GB resident
+ // estimate is past the 60%-of-usable comfort line → 'tight'.
+ expect(byQuant).toEqual({ BF16: 'too-large', Q8_0: 'too-large', Q4_K_M: 'tight' })
+ })
+
+ it('keeps the QUANT_PRIORITY default and marks fit unknown when no memory budget is supplied', async () => {
+ const repo = 'empero-ai/Qwythos-9B-NoBudget-GGUF'
+ fetch
+ .mockResolvedValueOnce(listing(repo, ['Qwythos-9B-Q4_K_M.gguf', 'Qwythos-9B-Q8_0.gguf', 'Qwythos-9B-BF16.gguf']))
+ .mockResolvedValueOnce(blobs(repo, {
+ 'Qwythos-9B-Q4_K_M.gguf': 5_500_000_000,
+ 'Qwythos-9B-Q8_0.gguf': 9_500_000_000,
+ 'Qwythos-9B-BF16.gguf': 18_000_000_000,
+ }))
+
+ const [result] = await searchHuggingFaceModels({ backend: 'ollama', query: 'qwythos' })
+
+ // No systemMemoryBytes → the QUANT_PRIORITY pick (Q4_K_M) is preserved.
+ expect(result).toMatchObject({ id: `hf.co/${repo}:Q4_K_M`, quant: 'Q4_K_M' })
+ expect(result.variants.map((v) => v.quant)).toEqual(['BF16', 'Q8_0', 'Q4_K_M'])
+ expect(result.variants.find((v) => v.recommended).quant).toBe('Q4_K_M')
+ expect(result.variants.every((v) => v.fit === 'unknown')).toBe(true)
+ })
+
+ it('sums multi-part GGUF shards into a single variant and resolves the quant', async () => {
+ const repo = 'org/Big-Shard-GGUF'
+ fetch
+ .mockResolvedValueOnce(listing(repo, ['Big-BF16-00001-of-00002.gguf', 'Big-BF16-00002-of-00002.gguf']))
+ .mockResolvedValueOnce(blobs(repo, {
+ 'Big-BF16-00001-of-00002.gguf': 20_000_000_000,
+ 'Big-BF16-00002-of-00002.gguf': 20_000_000_000,
+ }))
+
+ const [result] = await searchHuggingFaceModels({ backend: 'ollama', query: 'big', systemMemoryBytes: 128 * 1024 ** 3 })
+
+ expect(result.variants).toHaveLength(1)
+ expect(result.variants[0]).toMatchObject({ quant: 'BF16', sizeBytes: 40_000_000_000 })
+ })
+
+ it('builds LM Studio variant ids with the @quant syntax and still detects installed repos', async () => {
+ const repo = 'bartowski/LmModel-GGUF'
+ fetch
+ .mockResolvedValueOnce(listing(repo, ['LmModel-Q4_K_M.gguf', 'LmModel-Q8_0.gguf']))
+ .mockResolvedValueOnce(blobs(repo, {
+ 'LmModel-Q4_K_M.gguf': 4_000_000_000,
+ 'LmModel-Q8_0.gguf': 8_000_000_000,
+ }))
+
+ const [result] = await searchHuggingFaceModels({
+ backend: 'lmstudio', query: 'lmmodel', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [repo]
+ })
+
+ expect(result.variants.map((v) => v.installId)).toEqual([`${repo}@Q8_0`, `${repo}@Q4_K_M`])
+ // RAM-aware default applies the quant to the LM Studio id too.
+ expect(result.id).toBe(`${repo}@Q8_0`)
+ // Bare-repo installed list still matches the quant-tagged result.
+ expect(result.installed).toBe(true)
+ })
+ })
+
+ describe('audio installed registry', () => {
it('marks an audio model installed when it is in the shared registry', async () => {
fetch.mockResolvedValue(response([
{