Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(discover): resolve real HF files + download sharded/multi-part GGUF

purple1d92d5dc51cf
diff --git a/src/api/__tests__/hf-gguf-resolve.test.ts b/src/api/__tests__/hf-gguf-resolve.test.ts
new file mode 100644
index 00000000..78b731e6
--- /dev/null
+++ b/src/api/__tests__/hf-gguf-resolve.test.ts
@@ -0,0 +1,111 @@
+/**
+ * Unit tests for `selectGgufFromTree` — the pure resolver that turns a
+ * HuggingFace repo file tree into the exact GGUF file(s) to download.
+ *
+ * Why it exists: the old path guessed ONE single-file name from the repo name
+ * and downloaded that URL blindly. Three real layouts broke it (all confirmed
+ * against the live HF API for bartowski/Llama-3.3-70B-Instruct-abliterated-GGUF):
+ * 1. quant in a subfolder, not at root (Q5_K_M/<file>.gguf)
+ * 2. quant split into multiple parts (-00001-of-00002.gguf)
+ * 3. guessed single-file name is a 404
+ * David: "mach dann alle hf models bestätigt korrekt downloaden."
+ *
+ * The tree fixtures below mirror the real shapes returned by
+ * https://huggingface.co/api/models/<repo>/tree/main?recursive=true
+ */
+import { describe, it, expect } from 'vitest'
+import { selectGgufFromTree, type HfTreeEntry } from '../discover'
+
+const REPO = 'bartowski/Llama-3.3-70B-Instruct-abliterated-GGUF'
+
+// Real-shape tree: single-file quants at root + larger quants split into a
+// quant-named subfolder (exactly what the live API returns for this repo).
+const tree70b: HfTreeEntry[] = [
+ { type: 'directory', path: 'Llama-3.3-70B-Instruct-abliterated-Q5_K_M' },
+ { type: 'file', path: 'README.md', size: 1234 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q4_K_M.gguf', size: 42_520_398_912 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q2_K.gguf', size: 26_375_113_792 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q2_K_L.gguf', size: 27_401_161_792 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q6_K/Llama-3.3-70B-Instruct-abliterated-Q6_K-00001-of-00002.gguf', size: 39_953_848_160 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q6_K/Llama-3.3-70B-Instruct-abliterated-Q6_K-00002-of-00002.gguf', size: 17_934_300_608 },
+ // intentionally out of order to prove sorting
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q5_K_M/Llama-3.3-70B-Instruct-abliterated-Q5_K_M-00002-of-00002.gguf', size: 9_962_267_232 },
+ { type: 'file', path: 'Llama-3.3-70B-Instruct-abliterated-Q5_K_M/Llama-3.3-70B-Instruct-abliterated-Q5_K_M-00001-of-00002.gguf', size: 39_987_555_008 },
+]
+
+describe('selectGgufFromTree', () => {
+ it('returns null when the tree has no GGUF files', () => {
+ expect(selectGgufFromTree([{ type: 'file', path: 'README.md', size: 1 }], REPO)).toBeNull()
+ expect(selectGgufFromTree([], REPO)).toBeNull()
+ })
+
+ it('resolves a single-file root quant (no sharding)', () => {
+ const r = selectGgufFromTree(tree70b, REPO, 'Q4_K_M')
+ expect(r).not.toBeNull()
+ expect(r!.sharded).toBe(false)
+ expect(r!.files).toHaveLength(1)
+ expect(r!.files[0].filename).toBe('Llama-3.3-70B-Instruct-abliterated-Q4_K_M.gguf')
+ expect(r!.files[0].url).toBe(`https://huggingface.co/${REPO}/resolve/main/Llama-3.3-70B-Instruct-abliterated-Q4_K_M.gguf`)
+ expect(r!.quant).toBe('Q4_K_M')
+ expect(r!.totalBytes).toBe(42_520_398_912)
+ })
+
+ it('resolves ALL parts of a sharded subfolder quant, sorted by part index', () => {
+ const r = selectGgufFromTree(tree70b, REPO, 'Q5_K_M')
+ expect(r).not.toBeNull()
+ expect(r!.sharded).toBe(true)
+ expect(r!.files).toHaveLength(2)
+ // sorted 00001 before 00002 despite the reversed input order
+ expect(r!.files[0].filename).toBe('Llama-3.3-70B-Instruct-abliterated-Q5_K_M-00001-of-00002.gguf')
+ expect(r!.files[1].filename).toBe('Llama-3.3-70B-Instruct-abliterated-Q5_K_M-00002-of-00002.gguf')
+ // each part keeps its full subfolder path in the URL
+ expect(r!.files[0].url).toContain('/Llama-3.3-70B-Instruct-abliterated-Q5_K_M/Llama-3.3-70B-Instruct-abliterated-Q5_K_M-00001-of-00002.gguf')
+ expect(r!.totalBytes).toBe(39_987_555_008 + 9_962_267_232)
+ expect(r!.quant).toBe('Q5_K_M')
+ })
+
+ it('handles a quant with no third segment (Q6_K) — groups + sorts both parts', () => {
+ const r = selectGgufFromTree(tree70b, REPO, 'Q6_K')
+ expect(r).not.toBeNull()
+ expect(r!.sharded).toBe(true)
+ expect(r!.files).toHaveLength(2)
+ expect(r!.files[0].filename).toContain('-00001-of-00002.gguf')
+ expect(r!.files[1].filename).toContain('-00002-of-00002.gguf')
+ })
+
+ it('does not confuse Q2_K with Q2_K_L-style neighbours', () => {
+ const r = selectGgufFromTree(tree70b, REPO, 'Q2_K')
+ expect(r!.sharded).toBe(false)
+ expect(r!.files[0].filename).toBe('Llama-3.3-70B-Instruct-abliterated-Q2_K.gguf')
+ })
+
+ it('falls back to Q4_K_M when the requested quant is absent', () => {
+ const r = selectGgufFromTree(tree70b, REPO, 'Q3_K_S')
+ expect(r).not.toBeNull()
+ // Q3_K_S not in the tree → default to Q4_K_M
+ expect(r!.quant).toBe('Q4_K_M')
+ expect(r!.files[0].filename).toBe('Llama-3.3-70B-Instruct-abliterated-Q4_K_M.gguf')
+ })
+
+ it('resolves a single file living in a subfolder (not sharded)', () => {
+ const tree: HfTreeEntry[] = [
+ { type: 'file', path: 'Qwen3.6-35B-Heretic-Q4_K_M/Qwen3.6-35B-Heretic-Q4_K_M.gguf', size: 21_000_000_000 },
+ ]
+ const r = selectGgufFromTree(tree, 'Youssofal/Qwen3.6-35B-A3B-Abliterated-Heretic-GGUF', 'Q4_K_M')
+ expect(r!.sharded).toBe(false)
+ expect(r!.files).toHaveLength(1)
+ expect(r!.files[0].filename).toBe('Qwen3.6-35B-Heretic-Q4_K_M.gguf')
+ expect(r!.files[0].url).toContain('/Qwen3.6-35B-Heretic-Q4_K_M/Qwen3.6-35B-Heretic-Q4_K_M.gguf')
+ })
+
+ it('IQ quants are recognised and grouped', () => {
+ const tree: HfTreeEntry[] = [
+ { type: 'file', path: 'Foo-IQ2_XXS.gguf', size: 100 },
+ { type: 'file', path: 'Foo-IQ4_XS.gguf', size: 200 },
+ ]
+ const r = selectGgufFromTree(tree, 'x/Foo-GGUF', 'IQ4_XS')
+ expect(r!.sharded).toBe(false)
+ expect(r!.quant).toBe('IQ4_XS')
+ expect(r!.files[0].filename).toBe('Foo-IQ4_XS.gguf')
+ })
+})
diff --git a/src/api/discover.ts b/src/api/discover.ts
index 97e431e8..ed172367 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -642,6 +642,120 @@ export async function searchHuggingFaceModels(query: string): Promise<DiscoverMo
}
}
+// ─── HuggingFace file-tree resolution (sharded / multi-part GGUF) ───
+//
+// The naive "guess one Q4 filename from the repo name" path (search results +
+// some curated entries) breaks for three real-world layouts the HF API reveals:
+// 1. The quant lives in a subfolder (bartowski ships big quants as
+// `<base>-<Quant>/<file>.gguf`), not at the repo root.
+// 2. The quant is split into multiple parts (`-00001-of-0000N.gguf`). Every
+// part must land in ONE folder for llama.cpp / LM Studio to load it as a
+// single model. `ollama pull` cannot consume split GGUF at all
+// (ollama/ollama#5245) — direct multi-part download is the only sound path.
+// 3. The guessed single-file name simply doesn't exist (404).
+// Resolving against the real tree fixes all three.
+
+export interface HfTreeEntry { type: string; path: string; size?: number }
+
+export interface HfGgufFile { url: string; filename: string; sizeBytes: number }
+
+export interface HfGgufResolution {
+ sharded: boolean
+ files: HfGgufFile[]
+ totalBytes: number
+ quant?: string
+}
+
+// 5-digit llama.cpp split convention: `<name>-00001-of-00002.gguf`. A few
+// uploaders pad to 4, so accept 4-5.
+const GGUF_SHARD_RE = /-(\d{4,5})-of-(\d{4,5})\.gguf$/i
+// Broad quant token matcher (covers Q2_K, Q3_K_S/M/L, Q4_0/1, Q4_K_S/M/L,
+// Q5_K_*, Q6_K(_L), Q8_0, IQ1..IQ4 variants, F16/BF16/F32). Used only to LABEL
+// and PICK a group — grouping itself never depends on it.
+const GGUF_QUANT_TOKEN = /(IQ\d_[A-Z0-9]+|Q\d_K(?:_[A-Z]+)?|Q\d_[01]|BF16|F16|F32)/i
+
+/**
+ * Pure: given a HuggingFace repo file tree, pick the GGUF file-set to download.
+ * Returns every part of a sharded set (sorted) or the single matching file.
+ * Exported for unit testing without a network round-trip.
+ */
+export function selectGgufFromTree(
+ entries: HfTreeEntry[],
+ repoId: string,
+ preferredQuant?: string,
+): HfGgufResolution | null {
+ const ggufs = entries.filter(e => e.type === 'file' && /\.gguf$/i.test(e.path))
+ if (ggufs.length === 0) return null
+
+ // Group by the path with the shard suffix stripped. Single files keep their
+ // full path (their own group of one); all parts of a split set collapse to
+ // the same key regardless of whether the quant sits in the folder or the leaf.
+ interface Group { key: string; quant?: string; parts: HfTreeEntry[] }
+ const groups = new Map<string, Group>()
+ for (const f of ggufs) {
+ const key = f.path.replace(GGUF_SHARD_RE, '')
+ const leaf = (f.path.split('/').pop() || '').replace(GGUF_SHARD_RE, '.gguf')
+ const quant = (GGUF_QUANT_TOKEN.exec(leaf)?.[1] || GGUF_QUANT_TOKEN.exec(f.path)?.[1])?.toUpperCase()
+ let g = groups.get(key)
+ if (!g) { g = { key, quant, parts: [] }; groups.set(key, g) }
+ g.parts.push(f)
+ }
+
+ const all = [...groups.values()]
+ const wanted = preferredQuant?.toUpperCase()
+ const picked =
+ (wanted ? all.find(g => g.quant === wanted) : undefined) ||
+ (wanted ? all.find(g => g.key.toUpperCase().includes(wanted)) : undefined) ||
+ all.find(g => g.quant === 'Q4_K_M') ||
+ all[0]
+ if (!picked) return null
+
+ const sorted = [...picked.parts].sort((a, b) => {
+ const ai = parseInt(a.path.match(GGUF_SHARD_RE)?.[1] || '0', 10)
+ const bi = parseInt(b.path.match(GGUF_SHARD_RE)?.[1] || '0', 10)
+ return ai - bi
+ })
+ const files: HfGgufFile[] = sorted.map(p => ({
+ url: `https://huggingface.co/${repoId}/resolve/main/${p.path}`,
+ filename: p.path.split('/').pop() as string,
+ sizeBytes: p.size || 0,
+ }))
+ return {
+ sharded: files.length > 1,
+ files,
+ totalBytes: files.reduce((s, f) => s + f.sizeBytes, 0),
+ quant: picked.quant,
+ }
+}
+
+/**
+ * Resolve the real downloadable GGUF file(s) for a HuggingFace repo by querying
+ * its file tree. Returns null if the tree can't be fetched — callers then fall
+ * back to their guessed single-file URL (no regression, just no improvement).
+ */
+export async function resolveHfGgufFiles(
+ repoId: string,
+ preferredQuant?: string,
+): Promise<HfGgufResolution | null> {
+ try {
+ const url = `https://huggingface.co/api/models/${repoId}/tree/main?recursive=true`
+ let json: string
+ const { isTauri, fetchExternal } = await import('./backend')
+ if (isTauri()) {
+ json = await fetchExternal(url)
+ } else {
+ const res = await fetch(url)
+ json = await res.text()
+ }
+ const entries = JSON.parse(json)
+ if (!Array.isArray(entries)) return null
+ return selectGgufFromTree(entries as HfTreeEntry[], repoId, preferredQuant)
+ } catch (err) {
+ log.warn('[discover] HF tree resolve failed', { repoId, err })
+ return null
+ }
+}
+
/** Detect the model directory for the active local provider */
export async function detectProviderModelPath(providerName: string): Promise<string | null> {
try {
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index 178f3ec7..a289f662 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -8,8 +8,8 @@ import {
getUncensoredTextModels, getMainstreamTextModels,
detectProviderModelPath, startModelDownloadToPath,
startModelDownload, searchCivitaiModels,
- installBundleComplete, checkBundlesInstalled,
- type DiscoverModel, type DownloadProgress, type ModelBundle, type CivitAIModelResult,
+ installBundleComplete, checkBundlesInstalled, resolveHfGgufFiles,
+ type DiscoverModel, type DownloadProgress, type ModelBundle, type CivitAIModelResult, type HfGgufFile,
} from '../../api/discover'
import { getSystemVRAM } from '../../api/comfyui'
import { openExternal } from '../../api/backend'
@@ -21,7 +21,7 @@ import { useModelStore } from '../../stores/modelStore'
import { useWorkflowStore } from '../../stores/workflowStore'
import { getProviderIdFromModel } from '../../api/providers'
import { matchesLmStudioInstalled, type InstalledModelLike } from '../../lib/lmstudio-match'
-import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'
+import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir, parseHfUrl, extractGgufQuant } from '../../lib/hf-to-provider'
import { GlassCard } from '../ui/GlassCard'
import { GlowButton } from '../ui/GlowButton'
import { ProgressBar } from '../ui/ProgressBar'
@@ -529,18 +529,79 @@ export function DiscoverModels({ category }: Props) {
}
if (!model.downloadUrl || !model.filename) return
- // HF GGUF: route by active chat model. If neither side has an active
- // model yet (first-launch with downloads enabled), fall back to the
- // old enabled-wins logic so we don't deadlock empty-state users.
+ // Resolve the REAL file(s) on HuggingFace before downloading. The curated /
+ // search-derived (url, filename) is only a *guess* — the repo may host the
+ // quant in a subfolder, split it into multiple parts, or not have that
+ // exact filename. Querying the tree turns the guess into the truth.
+ const parsed = parseHfUrl(model.downloadUrl)
+ const preferredQuant = extractGgufQuant(model.filename)
+ const resolution = parsed
+ ? await resolveHfGgufFiles(`${parsed.user}/${parsed.repo}`, preferredQuant)
+ : null
+
const lmStudioEnabled = !!providers.openai?.enabled && (providers.openai?.name || '').toLowerCase().includes('lm studio')
- const ollamaEnabled = !!providers.ollama?.enabled
+ const ollamaEnabledNow = !!providers.ollama?.enabled
+
+ // Resolve the LM Studio-style destination dir for any direct download.
+ // LM Studio scans <models>/<user>/<repo>/<file>.gguf and llama.cpp
+ // auto-merges every `-NNNNN-of-NNNNN` part it finds in one folder.
+ const ensureDirectDir = async (): Promise<string | null> => {
+ const base = hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))
+ if (!base) return null
+ setHfModelPath(base)
+ const subdir = hfUrlToLmStudioSubdir(model.downloadUrl!)
+ return subdir ? `${base}/${subdir}` : base
+ }
+
+ const downloadDirect = async (files: HfGgufFile[], targetDir: string) => {
+ const names = files.map(f => f.filename)
+ // Group multi-part sets so the header badge aggregates their progress.
+ if (names.length > 1) dlStore.getState().setBundleGroup(model.name, names)
+ for (const f of files) {
+ dlStore.getState().setMeta(f.filename, f.url, 'gguf', targetDir)
+ await startModelDownloadToPath(f.url, targetDir, f.filename, f.sizeBytes || undefined)
+ }
+ dlStore.getState().startPolling()
+ }
+
+ // ── Sharded / multi-part: `ollama pull` cannot load split GGUF
+ // (ollama/ollama#5245), so the only sound path is a direct multi-part
+ // download into the LM Studio dir where llama.cpp merges the parts. ──
+ if (resolution?.sharded) {
+ const targetDir = await ensureDirectDir()
+ if (!targetDir) {
+ setInstallError('Could not determine model directory. Please check app permissions.')
+ return
+ }
+ if (isActiveOllama || (!isActiveLmStudio && !lmStudioEnabled && ollamaEnabledNow)) {
+ setInstallError(`${model.name} is a split, ${resolution.files.length}-part GGUF. Ollama can't load split GGUF (ollama/ollama#5245) — all ${resolution.files.length} parts are downloading to your LM Studio models folder. Load it from LM Studio, or pick a single-file quant for Ollama.`)
+ }
+ try {
+ await downloadDirect(resolution.files, targetDir)
+ } catch (e) {
+ log.error('Sharded GGUF download failed', { err: e })
+ setInstallError(`Download failed: ${e instanceof Error ? e.message : String(e)}`)
+ }
+ return
+ }
+
+ // ── Single file. Use the resolved file when available (it corrects a wrong
+ // guessed name / subfolder); else fall back to the guess so a transient HF
+ // API outage doesn't block the download. ──
+ const single = resolution?.files[0]
+ const realUrl = single?.url || model.downloadUrl
+ const realName = single?.filename || model.filename
+ const realBytes = single?.sizeBytes || (model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined)
+
+ // Route by the active chat model. If neither side has an active model yet
+ // (first launch), fall back to the old enabled-wins logic.
let useOllamaPath: boolean
if (isActiveOllama) useOllamaPath = true
else if (isActiveLmStudio) useOllamaPath = false
- else useOllamaPath = !lmStudioEnabled && ollamaEnabled // legacy fallback
+ else useOllamaPath = !lmStudioEnabled && ollamaEnabledNow // legacy fallback
if (useOllamaPath) {
- const ref = hfUrlToOllamaRef(model.downloadUrl, model.filename)
+ const ref = hfUrlToOllamaRef(realUrl, realName)
if (!ref) {
setInstallError(`Cannot map ${model.name} to an Ollama HF reference — try LM Studio.`)
return
@@ -554,19 +615,14 @@ export function DiscoverModels({ category }: Props) {
return
}
- const destDir = hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))
- if (!destDir) {
+ const targetDir = await ensureDirectDir()
+ if (!targetDir) {
setInstallError('Could not determine model directory. Please check app permissions.')
return
}
- setHfModelPath(destDir)
-
- const subdir = hfUrlToLmStudioSubdir(model.downloadUrl)
- const targetDir = subdir ? `${destDir}/${subdir}` : destDir
try {
- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', targetDir)
- const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined
- await startModelDownloadToPath(model.downloadUrl, targetDir, model.filename, expectedBytes)
+ dlStore.getState().setMeta(realName, realUrl, 'gguf', targetDir)
+ await startModelDownloadToPath(realUrl, targetDir, realName, realBytes)
dlStore.getState().startPolling()
} catch (e) {
log.error('GGUF download failed', { err: e })