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
feat([issue-1539]): add quant picker for bare-name Ollama registry models
[._.]/ Adam Eivybd17c04efef2
diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 1de778d874..27b88e11ab 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -2,6 +2,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'+import { fetchOllamaRegistryVariants } from './ollamaRegistryCatalog.js'const HF_API_BASE = 'https://huggingface.co/api/models'const HF_TIMEOUT_MS = 12_000@@ -883,9 +884,8 @@ export async function searchHuggingFaceModels({ backend, query = '', category =// 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.+// (`llama3.2`, `qwen2.5`) pull from Ollama's own registry — those are enriched+// from the Ollama registry tags/manifests instead (see applyOllamaRegistryVariants).function catalogRepoForBackend(backend, id) {const raw = String(id || '')if (backend === 'lmstudio') return raw.includes('/') ? raw.split('@')[0] : null@@ -907,18 +907,67 @@ function quantFromInstallId(backend, id) {return colon > slash ? raw.slice(colon + 1) : null}+// Enrich a bare Ollama registry entry (no HF repo) in place with a per-quant+// picker built from the Ollama registry's tags + manifests — the registry-backed+// analog of applyGgufVariants. The curated id stays stable (rewriteInstallId is+// implicitly false here); the RAM-aware default is conveyed via the recommended+// variant, whose installId is the precise `<name>:<tag>` pull. Returns true when+// variants were applied, false when the model isn't on the registry / has no+// quant-tagged builds (the curated entry then keeps its single hard-coded build).+async function applyOllamaRegistryVariants(entry, { usableBytes, installedIds }) {+ const candidates = await fetchOllamaRegistryVariants(entry.id, { paramsHint: entry.params })+ if (candidates.length === 0) return false+ const variants = candidates+ .map((c) => {+ const sizeBytes = Number.isFinite(c.sizeBytes) ? c.sizeBytes : null+ return {+ quant: c.quant,+ format: 'gguf',+ installId: c.installId,+ sizeBytes,+ size: formatBytes(sizeBytes) || c.quant,+ fit: classifyFit(sizeBytes, usableBytes),+ // Ollama tracks each `<name>:<tag>` build separately — per-quant installed+ // state so the card gates Install on the selected variant.+ installed: installIdInstalled('ollama', c.installId, entry.repository, installedIds)+ }+ })+ .sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0))+ // Seed the quant from the curator's id (`gpt-oss:20b` has no quant tag, so this+ // is usually null) so the no-RAM-budget fallback can anchor on it.+ if (entry.quant == null) entry.quant = quantFromInstallId('ollama', entry.id)+ const chosen = (usableBytes != null ? pickVariantForBudget(variants, usableBytes) : null)+ || variants.find((v) => v.quant && v.quant === entry.quant)+ || preferredQuantVariant(variants)+ for (const v of variants) v.recommended = v === chosen+ // Keep the curated entry's stable id (rewriteInstallId: false) — the playground+ // matches installed models on it; the UI installs the recommended variant.+ applyVariant(entry, chosen, false)+ entry.variants = variants+ entry.format = 'gguf'+ return true+}+// 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.+// the same per-quant variant picker + RAM-aware default the live HF search uses.+// HF-repo-backed entries (see catalogRepoForBackend) read their GGUF siblings;+// bare Ollama registry names are enriched from the Ollama registry instead. An+// MLX-only repo (no GGUF quants) or a model absent from the registry is 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 = [], timeoutMs = CATALOG_ENRICH_TIMEOUT_MS } = {}) {if (!isBackend(backend) || !Array.isArray(catalog)) return catalogconst usableBytes = usableMemoryBytes(systemMemoryBytes)const work = Promise.allSettled(catalog.map(async (entry) => {const repo = catalogRepoForBackend(backend, entry.id)- if (!repo) return+ if (!repo) {+ // Bare Ollama registry name (no HF repo) — discover quants from the Ollama+ // registry. LM Studio bare ids never reach here (catalogRepoForBackend+ // returns the repo for any `publisher/Repo`); a null repo there means a+ // malformed id, which has nothing to enrich.+ if (backend === 'ollama') await applyOllamaRegistryVariants(entry, { usableBytes, installedIds })+ return+ }const model = await fetchRepoModel(repo)if (!model) returnentry.repository = repodiff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.jsindex 4238b7ea1a..25601e2029 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { searchHuggingFaceModels, enrichCatalogWithVariants } from './huggingFaceCatalog.js'+import { __resetOllamaRegistryCache } from './ollamaRegistryCatalog.js'const response = (body, ok = true) => ({ok,@@ -662,15 +663,73 @@ describe('huggingFaceCatalog', () => {expect(catalog[0].size).toBe('2.0 GB')})- 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' }]+ // Route the Ollama registry's two endpoints (tags/list + per-tag manifests)+ // to a mock. `tags` is the tag list; `sizes` maps a tag → model-layer bytes.+ const ollamaRegistry = (tags, sizes = {}) => (url) => {+ if (/\/tags\/list$/.test(url)) return Promise.resolve(response({ tags }))+ const m = url.match(/\/manifests\/([^/]+)$/)+ if (m) {+ const tag = decodeURIComponent(m[1])+ const size = sizes[tag]+ return Promise.resolve(response({+ layers: Number.isFinite(size)+ ? [{ mediaType: 'application/vnd.ollama.image.model', size }]+ : []+ }))+ }+ return Promise.resolve(response({}))+ }++ it('adds a RAM-aware quant picker to a bare Ollama registry name', async () => {+ __resetOllamaRegistryCache()+ fetch.mockImplementation(ollamaRegistry(+ ['latest', '3b', '3b-instruct-q4_K_M', '3b-instruct-q8_0', '3b-instruct-fp16', '1b-instruct-q4_K_M'],+ { '3b-instruct-q4_K_M': 2_000_000_000, '3b-instruct-q8_0': 3_500_000_000, '3b-instruct-fp16': 6_500_000_000 }+ ))+ const catalog = [{ id: 'pickerllama', key: 'pickerllama', name: 'Picker Llama 3B', category: 'chat', params: '3B', size: '2.0 GB' }]+ await enrichCatalogWithVariants(catalog, { backend: 'ollama', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [] })++ expect(catalog[0].format).toBe('gguf')+ // Only the 3B (target-size) quant-tagged builds become variants — the 1B+ // build is a different size and the bare `3b`/`latest` carry no quant.+ expect(catalog[0].variants.map((v) => v.installId)).toEqual([+ 'pickerllama:3b-instruct-fp16', 'pickerllama:3b-instruct-q8_0', 'pickerllama:3b-instruct-q4_K_M'+ ])+ // Stable curated id; the RAM-aware default (128 GB → highest fidelity that fits) is recommended.+ expect(catalog[0].id).toBe('pickerllama')+ expect(catalog[0].variants.find((v) => v.recommended).installId).toBe('pickerllama:3b-instruct-fp16')+ expect(catalog[0].sizeBytes).toBe(6_500_000_000)+ })++ it('honors an explicit size tag and marks the per-quant installed build', async () => {+ __resetOllamaRegistryCache()+ fetch.mockImplementation(ollamaRegistry(+ ['20b', '20b-q4_K_M', '20b-q8_0', '120b-q4_K_M'],+ { '20b-q4_K_M': 12_000_000_000, '20b-q8_0': 22_000_000_000 }+ ))+ const catalog = [{ id: 'gpt-pick:20b', key: 'gpt-pick', name: 'GPT Pick 20B', category: 'reasoning', params: '20B', size: '12 GB' }]+ await enrichCatalogWithVariants(catalog, {+ backend: 'ollama', systemMemoryBytes: 16 * 1024 ** 3, installedIds: ['gpt-pick:20b-q4_K_M']+ })++ // Only the 20B builds (the card's size) — the 120B quant is excluded.+ expect(catalog[0].variants.map((v) => v.installId)).toEqual(['gpt-pick:20b-q8_0', 'gpt-pick:20b-q4_K_M'])+ // 16 GB box: the Q8 (22 GB) is too large, so the Q4 (12 GB) is recommended.+ expect(catalog[0].variants.find((v) => v.recommended).installId).toBe('gpt-pick:20b-q4_K_M')+ expect(catalog[0].variants.find((v) => v.installId === 'gpt-pick:20b-q4_K_M').installed).toBe(true)+ expect(catalog[0].variants.find((v) => v.installId === 'gpt-pick:20b-q8_0').installed).toBe(false)+ })++ it('leaves a bare Ollama name untouched when the model is not on the registry', async () => {+ __resetOllamaRegistryCache()+ // tags/list 404s (unknown model) → no tags → no variants.+ fetch.mockResolvedValue(response({}, false))+ const catalog = [{ id: 'nonexistent-model', key: 'nope', name: 'Nope', category: 'chat', params: '3B', 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()+ expect(catalog[0].id).toBe('nonexistent-model')+ expect(catalog[0].size).toBe('2.0 GB')})it('degrades gracefully (keeps the curated entry) when the HF probe fails', async () => {diff --git a/server/services/ollamaRegistryCatalog.js b/server/services/ollamaRegistryCatalog.jsnew file mode 100644index 0000000000..cc5fc1df9f--- /dev/null+++ b/server/services/ollamaRegistryCatalog.js@@ -0,0 +1,190 @@+// Ollama-registry quant discovery for bare curated catalog names.+//+// The curated catalog (server/lib/localLlmCatalog.js) ships two kinds of Ollama+// install ids:+// - `hf.co/<repo>[:quant]` — Hugging Face-backed; enriched by the HF path in+// huggingFaceCatalog.js (it reads the repo's GGUF siblings).+// - bare registry names (`llama3.2`, `qwen2.5`, `gpt-oss:20b`, `llama3.3:70b`)+// — these pull from Ollama's OWN registry, not Hugging Face, so the HF path+// has nothing to enumerate.+//+// This module gives the bare-name cards the same per-quant variant data by+// discovering each model's tags from the Ollama registry and reading per-quant+// weight sizes from the registry manifests. It returns raw variant candidates+// (`{ tag, installId, quant, sizeBytes }`); the fit/recommended/installed+// assembly stays in huggingFaceCatalog.js so the GGUF and Ollama-registry cards+// behave identically.+//+// Network is bounded by the same discipline as fetchRepoModel: per-process+// caches with a `null` sentinel (fetched-but-unavailable, cached) distinct from+// a transient failure (returns null, NOT cached, so a recovered registry+// re-enriches on the next request).++import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'+import { readResponseJson } from '../lib/readResponseJson.js'++const REGISTRY_BASE = 'https://registry.ollama.ai/v2'+const REGISTRY_TIMEOUT_MS = 12_000+// Ollama publishes OCI image manifests; the model weights live in a layer with+// this media type (template/params/license layers carry the other media types).+const MANIFEST_ACCEPT = 'application/vnd.docker.distribution.manifest.v2+json'+const MODEL_LAYER_MEDIA_TYPE = 'application/vnd.ollama.image.model'+// Upper bound on distinct quant variants probed per card. After dedup-by-quant+// at the target size this is rarely hit (a model ships ~4–8 quants), but it caps+// the manifest fan-out for a pathologically tag-heavy model.+const MAX_VARIANTS = 12++const tagsCache = new Map()+const manifestCache = new Map()+const CACHE_MAX = 500+// A transient fetch failure (network down / timeout / malformed body) — distinct+// from a genuine HTTP non-OK (404 / gated). The former must NOT be cached (it+// would permanently disable enrichment until the registry recovers); the latter+// is a real "no data" answer worth caching.+const TRANSIENT_FETCH = Symbol('ollama-registry-transient')++function cacheSet(cache, key, value) {+ // Evict oldest entry when the cap is reached (insertion-order iteration).+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value)+ cache.set(key, value)+}++// Split a curated Ollama install id into its registry path + optional tag.+// `gpt-oss:20b` → { name: 'gpt-oss', repoPath: 'library/gpt-oss', tag: '20b' }+// `llama3.2` → { name: 'llama3.2', repoPath: 'library/llama3.2', tag: null }+// `namespace/model:tag` → { name: 'namespace/model', repoPath: 'namespace/model', tag: 'tag' }+// Bare names live in the registry's implicit `library` namespace. hf.co-prefixed+// ids are NOT registry names (the HF path owns them) — returns null.+export function parseOllamaRegistryId(id) {+ const raw = String(id || '').trim()+ if (!raw || /^hf\.co\//i.test(raw)) return null+ const slash = raw.indexOf('/')+ const colon = raw.lastIndexOf(':')+ // A colon only marks a tag when it follows the namespace slash (or there's no+ // slash); a `:` inside a namespace segment would never occur for these ids.+ const hasTag = colon > slash+ const name = hasTag ? raw.slice(0, colon) : raw+ const tag = hasTag ? raw.slice(colon + 1) : null+ if (!name) return null+ const repoPath = name.includes('/') ? name : `library/${name}`+ return { name, repoPath, tag }+}++// Ollama quant suffix from a tag. Tags mix size + quant+// (`3b`, `q4_K_M`, `3b-instruct-q4_K_M`, `q8_0`, `fp16`); the quant is the+// trailing component. Returns a canonical UPPERCASE quant (`Q4_K_M`, `Q8_0`,+// `FP16`, `BF16`) so it ranks against the shared QUANT_PRIORITY (matched+// case-insensitively), or null when the tag carries no quant.+const OLLAMA_QUANT_RE = /(?:^|-)(iq\d(?:_[a-z0-9]+)*|q\d(?:_[a-z0-9]+)*|bf16|fp16|f16|fp32|f32)$/i+export function quantFromOllamaTag(tag) {+ const m = String(tag || '').match(OLLAMA_QUANT_RE)+ return m ? m[1].toUpperCase() : null+}++// Leading parameter-size token of a tag or params hint: `3b`, `70b`, `1.5b`,+// `35b` (from `35b-a3b` or `35B / 3B active`). Lowercased; null when absent+// (`q4_K_M`, `latest`, an embedding model's `137m`).+export function sizeTokenOf(text) {+ const m = String(text || '').match(/(\d+(?:\.\d+)?)\s*b\b/i)+ return m ? `${m[1]}b`.toLowerCase() : null+}++// Sum the model-weight layer(s) of an Ollama OCI manifest. Returns null when the+// manifest has no model layer (or no positive total) so the caller keeps the+// curated size estimate rather than showing 0.+export function sumModelLayerBytes(manifest) {+ const layers = Array.isArray(manifest?.layers) ? manifest.layers : []+ const total = layers+ .filter((l) => l?.mediaType === MODEL_LAYER_MEDIA_TYPE)+ .reduce((sum, l) => sum + (Number.isFinite(l?.size) ? l.size : 0), 0)+ return total > 0 ? total : null+}++// Prefer an instruct/chat build over a base/text build when two tags map to the+// same quant at the same size, then the shorter (plainer) tag.+function tagRank(tag) {+ if (/(instruct|chat|(?:^|-)it(?:$|-))/i.test(tag)) return 0+ if (/(?:^|-)(text|base)(?:$|-)/i.test(tag)) return 2+ return 1+}+function preferTag(candidate, current) {+ const cr = tagRank(candidate)+ const curr = tagRank(current)+ if (cr !== curr) return cr < curr+ return candidate.length < current.length+}++async function fetchTags(repoPath, timeoutMs) {+ if (tagsCache.has(repoPath)) return tagsCache.get(repoPath)+ // repoPath is derived from a curated id, but encode each segment defensively so+ // a stray character can't reshape the request path.+ const safePath = repoPath.split('/').map(encodeURIComponent).join('/')+ const result = await fetchWithTimeout(`${REGISTRY_BASE}/${safePath}/tags/list`, { headers: { Accept: 'application/json' } }, timeoutMs)+ .then((res) => (res.ok ? readResponseJson(res, { fallback: null, emptyValue: null }) : null))+ .catch(() => TRANSIENT_FETCH)+ if (result === TRANSIENT_FETCH) return null // transient — return null but don't cache+ const tags = Array.isArray(result?.tags) ? result.tags : null+ cacheSet(tagsCache, repoPath, tags)+ return tags+}++async function fetchManifestModelBytes(repoPath, tag, timeoutMs) {+ const key = `${repoPath}:${tag}`+ if (manifestCache.has(key)) return manifestCache.get(key)+ const safePath = repoPath.split('/').map(encodeURIComponent).join('/')+ const safeTag = encodeURIComponent(tag)+ const result = await fetchWithTimeout(`${REGISTRY_BASE}/${safePath}/manifests/${safeTag}`, { headers: { Accept: MANIFEST_ACCEPT } }, timeoutMs)+ .then((res) => (res.ok ? readResponseJson(res, { fallback: null, emptyValue: null }) : null))+ .catch(() => TRANSIENT_FETCH)+ if (result === TRANSIENT_FETCH) return null // transient — return null but don't cache+ const bytes = sumModelLayerBytes(result)+ cacheSet(manifestCache, key, bytes)+ return bytes+}++// Resolve the per-quant install variants for a bare Ollama registry model.+// Returns `[{ tag, installId, quant, sizeBytes }]` (sizeBytes null when the+// manifest is unavailable), or `[]` when the model isn't on the registry or has+// no quant-tagged builds at the target size. `paramsHint` (the curated card's+// params, e.g. '3B') supplies the target size when the id carries no size tag.+export async function fetchOllamaRegistryVariants(id, { paramsHint = null, timeoutMs = REGISTRY_TIMEOUT_MS } = {}) {+ const parsed = parseOllamaRegistryId(id)+ if (!parsed) return []+ const tags = await fetchTags(parsed.repoPath, timeoutMs)+ if (!Array.isArray(tags) || tags.length === 0) return []++ // Constrain variants to the card's parameter size so one card never mixes a+ // 1B and a 70B build in its picker.+ const targetSize = sizeTokenOf(parsed.tag) || sizeTokenOf(paramsHint)++ // Classify tags → quant-bearing ones at the target size, deduped by quant.+ const byQuant = new Map()+ for (const tag of tags) {+ const quant = quantFromOllamaTag(tag)+ if (!quant) continue+ const size = sizeTokenOf(tag)+ if (targetSize) {+ // With a known target size, require an explicit size match — a size-less+ // bare-quant tag (`q4_K_M`) belongs to the model's default size, which may+ // not be this card's build, so skip it.+ if (size !== targetSize) continue+ }+ const existing = byQuant.get(quant)+ if (!existing || preferTag(tag, existing)) byQuant.set(quant, tag)+ }+ const chosen = [...byQuant.entries()].slice(0, MAX_VARIANTS)+ if (chosen.length === 0) return []++ // Manifest size fan-out is bounded by the dedup + cap above; fetch concurrently.+ return Promise.all(chosen.map(async ([quant, tag]) => {+ const sizeBytes = await fetchManifestModelBytes(parsed.repoPath, tag, timeoutMs)+ return { tag, installId: `${parsed.name}:${tag}`, quant, sizeBytes }+ }))+}++// Test hook — clear the per-process caches so a suite's mocked fetch isn't+// shadowed by a prior test's cached result.+export function __resetOllamaRegistryCache() {+ tagsCache.clear()+ manifestCache.clear()+}diff --git a/server/services/ollamaRegistryCatalog.test.js b/server/services/ollamaRegistryCatalog.test.jsnew file mode 100644index 0000000000..6e2eb1d12f--- /dev/null+++ b/server/services/ollamaRegistryCatalog.test.js@@ -0,0 +1,157 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import {+ parseOllamaRegistryId,+ quantFromOllamaTag,+ sizeTokenOf,+ sumModelLayerBytes,+ fetchOllamaRegistryVariants,+ __resetOllamaRegistryCache+} from './ollamaRegistryCatalog.js'++const response = (body, ok = true) => ({+ ok,+ status: ok ? 200 : 404,+ json: vi.fn(async () => body),+ text: vi.fn(async () => JSON.stringify(body))+})++// Route the registry's two endpoints to a mock: tags/list → `tags`, per-tag+// manifests → model-layer bytes from `sizes` (omit a tag for an unsized build).+const registry = (tags, sizes = {}) => (url) => {+ if (/\/tags\/list$/.test(url)) return Promise.resolve(response({ tags }))+ const m = url.match(/\/manifests\/([^/]+)$/)+ if (m) {+ const size = sizes[decodeURIComponent(m[1])]+ return Promise.resolve(response({+ layers: Number.isFinite(size)+ ? [+ { mediaType: 'application/vnd.ollama.image.model', size },+ { mediaType: 'application/vnd.ollama.image.template', size: 1234 }+ ]+ : [{ mediaType: 'application/vnd.ollama.image.template', size: 1234 }]+ }))+ }+ return Promise.resolve(response({}))+}++describe('ollamaRegistryCatalog pure helpers', () => {+ it('parseOllamaRegistryId splits name/tag and defaults to the library namespace', () => {+ expect(parseOllamaRegistryId('llama3.2')).toEqual({ name: 'llama3.2', repoPath: 'library/llama3.2', tag: null })+ expect(parseOllamaRegistryId('gpt-oss:20b')).toEqual({ name: 'gpt-oss', repoPath: 'library/gpt-oss', tag: '20b' })+ expect(parseOllamaRegistryId('acme/model:q4_K_M')).toEqual({ name: 'acme/model', repoPath: 'acme/model', tag: 'q4_K_M' })+ expect(parseOllamaRegistryId('acme/model')).toEqual({ name: 'acme/model', repoPath: 'acme/model', tag: null })+ })++ it('parseOllamaRegistryId rejects hf.co repos and empty ids', () => {+ expect(parseOllamaRegistryId('hf.co/unsloth/Foo-GGUF:Q4_K_M')).toBeNull()+ expect(parseOllamaRegistryId('')).toBeNull()+ expect(parseOllamaRegistryId(null)).toBeNull()+ })++ it('quantFromOllamaTag parses the trailing quant component, canonicalized uppercase', () => {+ expect(quantFromOllamaTag('3b-instruct-q4_K_M')).toBe('Q4_K_M')+ expect(quantFromOllamaTag('q8_0')).toBe('Q8_0')+ expect(quantFromOllamaTag('8b-instruct-fp16')).toBe('FP16')+ expect(quantFromOllamaTag('70b-instruct-bf16')).toBe('BF16')+ expect(quantFromOllamaTag('iq2_xxs')).toBe('IQ2_XXS')+ // Size-only and alias tags carry no quant.+ expect(quantFromOllamaTag('3b')).toBeNull()+ expect(quantFromOllamaTag('latest')).toBeNull()+ })++ it('sizeTokenOf extracts the leading parameter size, or null', () => {+ expect(sizeTokenOf('3b-instruct-q4_K_M')).toBe('3b')+ expect(sizeTokenOf('70b')).toBe('70b')+ expect(sizeTokenOf('1.5b')).toBe('1.5b')+ expect(sizeTokenOf('35b-a3b-q4_K_M')).toBe('35b')+ expect(sizeTokenOf('35B / 3B active')).toBe('35b')+ expect(sizeTokenOf('q4_K_M')).toBeNull()+ expect(sizeTokenOf('137m')).toBeNull()+ })++ it('sumModelLayerBytes sums only the model-weight layers', () => {+ expect(sumModelLayerBytes({+ layers: [+ { mediaType: 'application/vnd.ollama.image.model', size: 2_000_000_000 },+ { mediaType: 'application/vnd.ollama.image.template', size: 999 }+ ]+ })).toBe(2_000_000_000)+ expect(sumModelLayerBytes({ layers: [{ mediaType: 'application/vnd.ollama.image.template', size: 999 }] })).toBeNull()+ expect(sumModelLayerBytes(null)).toBeNull()+ })+})++describe('fetchOllamaRegistryVariants', () => {+ beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn())+ __resetOllamaRegistryCache()+ })+ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it('returns one variant per quant at the target size, with manifest sizes', async () => {+ fetch.mockImplementation(registry(+ ['latest', '3b', '3b-instruct-q4_K_M', '3b-instruct-q8_0', '1b-instruct-q4_K_M'],+ { '3b-instruct-q4_K_M': 2_000_000_000, '3b-instruct-q8_0': 3_500_000_000 }+ ))++ const variants = await fetchOllamaRegistryVariants('llama3.2', { paramsHint: '3B' })++ expect(variants).toEqual(expect.arrayContaining([+ { tag: '3b-instruct-q4_K_M', installId: 'llama3.2:3b-instruct-q4_K_M', quant: 'Q4_K_M', sizeBytes: 2_000_000_000 },+ { tag: '3b-instruct-q8_0', installId: 'llama3.2:3b-instruct-q8_0', quant: 'Q8_0', sizeBytes: 3_500_000_000 }+ ]))+ // The 1B build is a different size and must be excluded.+ expect(variants.some((v) => v.tag.startsWith('1b'))).toBe(false)+ // Bare `3b` / `latest` carry no quant → not variants.+ expect(variants).toHaveLength(2)+ })++ it('derives the target size from an explicit tag over the params hint', async () => {+ fetch.mockImplementation(registry(+ ['20b-q4_K_M', '120b-q4_K_M'],+ { '20b-q4_K_M': 12_000_000_000, '120b-q4_K_M': 65_000_000_000 }+ ))++ const variants = await fetchOllamaRegistryVariants('gpt-oss:20b', { paramsHint: '20B' })+ expect(variants.map((v) => v.installId)).toEqual(['gpt-oss:20b-q4_K_M'])+ })++ it('prefers an instruct tag over a base/text tag for the same quant', async () => {+ fetch.mockImplementation(registry(+ ['7b-text-q4_K_M', '7b-instruct-q4_K_M'],+ { '7b-text-q4_K_M': 4_000_000_000, '7b-instruct-q4_K_M': 4_000_000_000 }+ ))++ const variants = await fetchOllamaRegistryVariants('mistral', { paramsHint: '7B' })+ expect(variants.map((v) => v.installId)).toEqual(['mistral:7b-instruct-q4_K_M'])+ })++ it('returns [] for an hf.co id (owned by the HF path)', async () => {+ const variants = await fetchOllamaRegistryVariants('hf.co/unsloth/Foo-GGUF:Q4_K_M', { paramsHint: '7B' })+ expect(variants).toEqual([])+ expect(fetch).not.toHaveBeenCalled()+ })++ it('returns [] when the model is absent from the registry (tags 404)', async () => {+ fetch.mockResolvedValue(response({}, false))+ expect(await fetchOllamaRegistryVariants('ghost-model', { paramsHint: '3B' })).toEqual([])+ })++ it('keeps a null size when the manifest is unavailable', async () => {+ fetch.mockImplementation(registry(['7b-instruct-q4_K_M'], {})) // no size for the tag+ const variants = await fetchOllamaRegistryVariants('mistral', { paramsHint: '7B' })+ expect(variants).toEqual([{ tag: '7b-instruct-q4_K_M', installId: 'mistral:7b-instruct-q4_K_M', quant: 'Q4_K_M', sizeBytes: null }])+ })++ it('caches a 404 tags result but not a transient failure', async () => {+ // First call: transient throw → null, NOT cached.+ fetch.mockRejectedValueOnce(new Error('network down'))+ expect(await fetchOllamaRegistryVariants('flaky', { paramsHint: '3B' })).toEqual([])+ // Recovered registry re-enriches (cache wasn't poisoned by the transient miss).+ fetch.mockImplementation(registry(['3b-instruct-q4_K_M'], { '3b-instruct-q4_K_M': 2_000_000_000 }))+ const variants = await fetchOllamaRegistryVariants('flaky', { paramsHint: '3B' })+ expect(variants.map((v) => v.installId)).toEqual(['flaky:3b-instruct-q4_K_M'])+ })+})