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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(downloads): provider-aware GGUF download — Ollama pulls, LM Studio nests
purple5b7b1d1bf139
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex 6e145ef1..a6f07276 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -528,10 +528,35 @@ pub fn detect_model_path(provider: String) -> Result<serde_json::Value, String>}}- // Fallback: create LU models directory- let fallback = home.join("locally-uncensored").join("models");- fs::create_dir_all(&fallback).map_err(|e| format!("Create fallback dir: {}", e))?;- Ok(serde_json::json!(fallback.to_string_lossy()))+ // No managed dir exists yet for this provider. For the two providers LU+ // actively writes downloads into (Ollama, LM Studio), pre-create the+ // conventional path so the first download just works on a fresh box —+ // this is the Plug & Play path. Frontend gating ensures we only ever+ // direct-write into the LM Studio dir; Ollama's path is here purely so+ // legacy callers don't get an Err — see download_model_to_path callers.+ //+ // The previous `~/locally-uncensored/models` fallback was unreachable+ // by any backend and produced the "downloaded but invisible" bug+ // (Discord drdeath9669, kmmorr23, GH disc #35). We remove it: if a+ // user picked a backend with no conventional dir, return an explicit+ // error so the UI can show a real message instead of silently writing+ // into a junk folder.+ match provider_lower.as_str() {+ "ollama" => {+ let p = home.join(".ollama").join("models");+ fs::create_dir_all(&p).map_err(|e| format!("Create Ollama models dir: {}", e))?;+ Ok(serde_json::json!(p.to_string_lossy()))+ }+ "lm studio" | "lmstudio" => {+ let p = home.join(".lmstudio").join("models");+ fs::create_dir_all(&p).map_err(|e| format!("Create LM Studio models dir: {}", e))?;+ Ok(serde_json::json!(p.to_string_lossy()))+ }+ _ => Err(format!(+ "No conventional model directory for provider '{}'. Configure a custom path in Settings → Models, or pick a backend (Ollama / LM Studio) with a known model location.",+ provider+ )),+ }}#[allow(non_snake_case)]diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex b6c8a33a..be86da0e 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -18,6 +18,7 @@ import { useDownloadStore } from '../../stores/downloadStore'import { useProviderStore } from '../../stores/providerStore'import { useSettingsStore } from '../../stores/settingsStore'import { useWorkflowStore } from '../../stores/workflowStore'+import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'import { GlassCard } from '../ui/GlassCard'import { GlowButton } from '../ui/GlowButton'import { ProgressBar } from '../ui/ProgressBar'@@ -401,7 +402,7 @@ export function DiscoverModels({ category }: Props) {}const handleTextDownload = async (model: DiscoverModel) => {- // Ollama-native models: use ollama pull instead of GGUF download+ // Ollama-native models: use ollama pull (registry path).if (model.ollamaModel) {try {await pullModel(model.ollamaModel)@@ -412,16 +413,47 @@ export function DiscoverModels({ category }: Props) {return}if (!model.downloadUrl || !model.filename) return++ // HF GGUF: which backend will actually consume this file?+ // - LM Studio explicitly enabled (openai provider with LM Studio name)+ // → nest under <user>/<repo>/ so its scanner picks it up.+ // - Otherwise default to Ollama (always-on by default), pull via+ // /api/pull as `hf.co/<user>/<repo>:<quant>`.+ // Why: a raw .gguf in `~/.ollama/models` or in `~/.lmstudio/models/`+ // (top-level) is silently ignored by both runtimes. That mismatch is+ // the bug behind the "downloaded model never appears" reports.+ const lmStudioOn = !!providers.openai?.enabled && (providers.openai?.name || '').toLowerCase().includes('lm studio')+ const ollamaOn = !!providers.ollama?.enabled+ const useOllamaPath = !lmStudioOn && ollamaOn++ if (useOllamaPath) {+ const ref = hfUrlToOllamaRef(model.downloadUrl, model.filename)+ if (!ref) {+ setInstallError(`Cannot map ${model.name} to an Ollama HF reference — try LM Studio.`)+ return+ }+ try {+ await pullModel(ref)+ } catch (e) {+ console.error('Ollama HF pull failed:', e)+ setInstallError(`Ollama pull failed: ${e instanceof Error ? e.message : String(e)}. Is Ollama running?`)+ }+ return+ }+const destDir = hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))if (!destDir) {setInstallError('Could not determine model directory. Please check app permissions.')return}setHfModelPath(destDir)++ const subdir = hfUrlToLmStudioSubdir(model.downloadUrl)+ const targetDir = subdir ? `${destDir}/${subdir}` : destDirtry {- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', destDir)+ 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, destDir, model.filename, expectedBytes)+ await startModelDownloadToPath(model.downloadUrl, targetDir, model.filename, expectedBytes)dlStore.getState().startPolling()} catch (e) {console.error('GGUF download failed:', e)@@ -442,13 +474,29 @@ export function DiscoverModels({ category }: Props) {<p className="text-sm text-gray-500">{subtitle}</p>+ {/* Always-visible "your own model" call-out for text. Discord users+ repeatedly asked for a way to install their own GGUFs / HF models,+ unaware the search bar already does it (booster.netv2, #general).+ Spelling out what the search bar accepts moves it from "feature+ you have to discover" to "feature you can't miss." */}+ {isText && (+ <div className={`flex items-start gap-2.5 p-2.5 rounded-lg border ${+ 'bg-blue-50 dark:bg-blue-500/[0.08] border-blue-200 dark:border-blue-500/20 text-blue-900 dark:text-blue-200'+ }`}>+ <Search size={14} className="mt-0.5 shrink-0" />+ <div className="text-[0.65rem] leading-relaxed">+ <strong>Looking for your own model?</strong> Search any HuggingFace GGUF below — paste a repo name like <code className="font-mono px-1 rounded bg-white/30 dark:bg-white/10">bartowski/Llama-3.1-8B-Instruct-GGUF</code> or a keyword like "qwen 14b". Hit Enter and pick a quant.+ </div>+ </div>+ )}+<div className="relative"><Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" /><inputvalue={search}onChange={(e) => setSearch(e.target.value)}onKeyDown={(e) => { if (e.key === 'Enter' && isText) handleSearch() }}- placeholder={isText ? 'Search HuggingFace GGUF models... (Enter to search)' : 'Filter models...'}+ placeholder={isText ? 'Search HuggingFace GGUF (e.g. "qwen 14b" or "bartowski/Llama-3.1") — Enter to search' : 'Filter models...'}className="w-full pl-9 pr-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-sm text-gray-900 dark:text-white placeholder-gray-500 focus:outline-none focus:border-gray-400 dark:focus:border-white/30"/></div>diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsxindex bcdb8f4e..faaa4073 100644--- a/src/components/onboarding/Onboarding.tsx+++ b/src/components/onboarding/Onboarding.tsx@@ -13,6 +13,8 @@ import { openExternal } from '../../api/backend'import { formatBytes } from '../../lib/formatters'import { backendCall } from '../../api/backend'import { getSystemVRAM } from '../../api/comfyui'+import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'+import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'type Step = 'welcome' | 'theme' | 'backends' | 'comfyui' | 'models' | 'done'const STEP_ORDER: Step[] = ['welcome', 'theme', 'backends', 'comfyui', 'models', 'done']@@ -85,6 +87,19 @@ export function Onboarding() {const [ollamaStartTime, setOllamaStartTime] = useState<number | null>(null)const [ollamaElapsed, setOllamaElapsed] = useState(0)+ // LM Studio install state — same shape as Ollama; both can show their+ // own progress card if the user picks both. In practice they pick one.+ const [lmstudioInstalling, setLmstudioInstalling] = useState(false)+ const [lmstudioStatus, setLmstudioStatus] = useState('')+ const [lmstudioProgress, setLmstudioProgress] = useState(0)+ const [lmstudioTotal, setLmstudioTotal] = useState(0)+ const [lmstudioSpeed, setLmstudioSpeed] = useState(0)+ const [lmstudioLogs, setLmstudioLogs] = useState<string[]>([])+ const [lmstudioError, setLmstudioError] = useState('')+ const [lmstudioReady, setLmstudioReady] = useState(false)+ const [lmstudioStartTime, setLmstudioStartTime] = useState<number | null>(null)+ const [lmstudioElapsed, setLmstudioElapsed] = useState(0)+const isDark = settings.theme === 'dark'const bgClass = isDark ? 'bg-[#0a0a0a] text-white' : 'bg-white text-gray-900'const cardClass = isDark ? 'bg-[#141414] border-white/[0.08]' : 'bg-gray-50 border-gray-200'@@ -98,12 +113,46 @@ export function Onboarding() {const handleDownloadSelected = async () => {setDownloadError(null)const providers = useProviderStore.getState().providers- const destDir = hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))- if (!destDir) {- setDownloadError('Could not determine model directory. Please check app permissions.')- return++ // Decide which backend the download has to feed. selectedBackend (set in+ // the backends step) is the strongest signal; ollamaReady covers the+ // "we just installed Ollama in-app" path; final fallback is the first+ // detected backend, defaulting to ollama. The earlier code wrote a raw+ // .gguf into `~/.ollama/models` regardless — Ollama ignores files placed+ // there directly, which is the root cause of the "downloaded model+ // never appears" bug reported on Discord and GH discussion #35.+ const targetBackend = selectedBackend || (ollamaReady ? 'ollama' : detectedBackends[0]?.id) || 'ollama'+ const useOllamaPath = targetBackend === 'ollama'++ // Sanity-check / auto-start Ollama before pulling. The pull command will+ // otherwise spin in "connecting" with no actionable error if the daemon+ // isn't reachable.+ if (useOllamaPath && isTauri) {+ let ok = await checkOllama()+ if (!ok) {+ try { await backendCall('start_ollama') } catch { /* fall through to retry loop */ }+ for (let i = 0; i < 20 && !ok; i++) {+ await new Promise(r => setTimeout(r, 250))+ ok = await checkOllama()+ }+ }+ if (!ok) {+ setDownloadError('Cannot reach Ollama (localhost:11434). Open the Ollama app or run `ollama serve`, then retry.')+ return+ }+ }++ // Direct-write providers (LM Studio etc.) still need a base dir.+ let destDir: string | null = null+ if (!useOllamaPath) {+ const settingsOverride = useSettingsStore.getState().settings.hfDownloadPathOverride?.trim() || ''+ destDir = settingsOverride || hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))+ if (!destDir) {+ setDownloadError('Could not determine model directory. Please check app permissions, or set a custom path in Settings → Models.')+ return+ }+ setHfModelPath(destDir)}- setHfModelPath(destDir)for (const name of selectedModels) {if (pulledModels.includes(name)) continue@@ -112,16 +161,73 @@ export function Onboarding() {setPullingModel(name)try {- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', destDir)- const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined- await startModelDownloadToPath(model.downloadUrl, destDir, model.filename, expectedBytes)- dlStore.getState().startPolling()+ if (useOllamaPath) {+ // Ollama: HF URL → `hf.co/<user>/<repo>:<quant>` → /api/pull. Ollama+ // materialises the GGUF into its own blob+manifest store; the file+ // appears in `ollama list` (and therefore in our model manager) the+ // moment the pull finishes — no separate scanner involved.+ const ollamaRef = hfUrlToOllamaRef(model.downloadUrl, model.filename)+ if (!ollamaRef) {+ setDownloadError(`Cannot derive an Ollama reference for ${model.label}. Try LM Studio instead.`)+ continue+ }++ // Seed an entry in the download store so the existing onboarding+ // progress UI keeps working. Translation from PullProgress (Ollama)+ // → DownloadProgress (LU) below.+ dlStore.getState().setMeta(model.filename, model.downloadUrl, 'ollama')+ useDownloadStore.setState(s => ({+ downloads: {+ ...s.downloads,+ [model.filename!]: {+ progress: 0, total: 0, speed: 0,+ filename: model.filename!,+ status: 'connecting',+ },+ },+ }))++ const { promise } = pullModelTauri(ollamaRef, (p) => {+ const total = p.total || 0+ const completed = p.completed || 0+ const status = (p.status || '').toLowerCase()+ const isComplete = status.includes('success') || status === 'complete'+ useDownloadStore.setState(s => ({+ downloads: {+ ...s.downloads,+ [model.filename!]: {+ progress: completed, total,+ speed: 0,+ filename: model.filename!,+ status: isComplete ? 'complete' : 'downloading',+ },+ },+ }))+ })+ await promise+ // Mark complete in case the final progress event didn't include+ // a "success" status string (Ollama varies between versions).+ useDownloadStore.getState().markComplete(model.filename)+ } else {+ // LM Studio etc.: nest under <user>/<repo>/ so the scanner finds+ // it. A bare .gguf in the model root is silently ignored by LM+ // Studio's library — the second half of the same Discord bug.+ const subdir = hfUrlToLmStudioSubdir(model.downloadUrl)+ const targetDir = subdir ? `${destDir}/${subdir}` : destDir!+ 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().startPolling()+ }setPulledModels(prev => [...prev, name])} catch (e) {- setDownloadError(`Download failed: ${e instanceof Error ? e.message : String(e)}`)+ setDownloadError(`Download failed for ${model.label}: ${e instanceof Error ? e.message : String(e)}`)}}setPullingModel(null)+ // Tell the rest of the app the model list changed — Model Manager,+ // Chat picker, etc. listen for this and re-fetch.+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))setStep('done')}@@ -146,6 +252,26 @@ export function Onboarding() {// Detect system VRAM for model filteringuseEffect(() => { getSystemVRAM().then(v => setSystemVRAM(v)).catch(() => {}) }, [])+ // Count models the user already has installed across all backends. Used to+ // suppress the "Recommended" starter pick when the user is clearly an+ // experienced reinstaller — the previous version slapped "Recommended" on+ // half a dozen 5–16 GB models for everyone, which was both noisy and a bad+ // suggestion if you already had your own preferences. Failing the call+ // returns 0 (no Ollama running yet → genuinely fresh install → recommend+ // away).+ const [existingModelCount, setExistingModelCount] = useState<number>(0)+ useEffect(() => {+ if (step !== 'models') return+ let cancelled = false+ import('../../api/ollama').then(({ listModels }) =>+ listModels()+ .then(models => { if (!cancelled) setExistingModelCount(models.length) })+ .catch(() => { if (!cancelled) setExistingModelCount(0) })+ )+ return () => { cancelled = true }+ }, [step])+ const showRecommendedBadge = existingModelCount === 0+// Elapsed timer for ComfyUI installationuseEffect(() => {if (!installStartTime) return@@ -160,6 +286,13 @@ export function Onboarding() {return () => clearInterval(timer)}, [ollamaStartTime])+ // Elapsed timer for LM Studio installation+ useEffect(() => {+ if (!lmstudioStartTime) return+ const timer = setInterval(() => setLmstudioElapsed(Math.floor((Date.now() - lmstudioStartTime) / 1000)), 1000)+ return () => clearInterval(timer)+ }, [lmstudioStartTime])+// Auto-detect ComfyUI when entering the comfyui stepuseEffect(() => {if (step === 'comfyui' && !comfyFound && !comfyDetecting) {@@ -398,6 +531,11 @@ export function Onboarding() {setOllamaInstalling(false)setOllamaReady(true)setOllamaStartTime(null)+ // Lock the model-download flow onto Ollama so+ // GGUFs go through `ollama pull` (which produces+ // a usable model) instead of a raw .gguf write+ // (which Ollama then can't see).+ setSelectedBackend('ollama')} else if (s.status === 'error') {clearInterval(poll)setOllamaInstalling(false)@@ -466,6 +604,126 @@ export function Onboarding() {<p className="text-[0.65rem] text-red-400">{ollamaError}</p>)}+ {/* LM Studio ready */}+ {lmstudioReady && (+ <div className={`p-3 rounded-lg border ${isDark ? 'bg-green-500/10 border-green-500/20' : 'bg-green-50 border-green-200'}`}>+ <div className="flex items-center gap-2 justify-center">+ <Check size={14} className="text-green-400" />+ <span className="text-[0.7rem] font-medium">LM Studio is ready (server on :1234)</span>+ </div>+ </div>+ )}++ {/* LM Studio install — alt path. Hidden once any installer is+ running so two heavy downloads don't kick off at once. */}+ {!lmstudioInstalling && !lmstudioReady && !ollamaInstalling && !ollamaReady && (+ <button+ onClick={async () => {+ setLmstudioInstalling(true)+ setLmstudioError('')+ setLmstudioStartTime(Date.now())+ setLmstudioElapsed(0)+ try {+ await backendCall('install_lmstudio')+ const poll = setInterval(async () => {+ try {+ const s: any = await backendCall('install_lmstudio_status')+ setLmstudioStatus(s.status || '')+ setLmstudioLogs(s.logs || [])+ setLmstudioProgress(s.download_progress || 0)+ setLmstudioTotal(s.download_total || 0)+ setLmstudioSpeed(s.download_speed || 0)+ if (s.status === 'complete') {+ clearInterval(poll)+ setLmstudioInstalling(false)+ setLmstudioReady(true)+ setLmstudioStartTime(null)+ // Wire the OpenAI-compat provider to LM Studio so+ // /v1/chat/completions calls hit the right port,+ // and route GGUF downloads through the LM-Studio+ // <user>/<repo>/<file>.gguf nesting.+ setSelectedBackend('lmstudio')+ setProviderConfig('openai', {+ enabled: true,+ name: 'LM Studio',+ baseUrl: 'http://localhost:1234/v1',+ isLocal: true,+ })+ } else if (s.status === 'error') {+ clearInterval(poll)+ setLmstudioInstalling(false)+ setLmstudioStartTime(null)+ const lastLog = s.logs?.[s.logs.length - 1] || 'Installation failed'+ setLmstudioError(lastLog)+ }+ } catch { /* keep polling */ }+ }, 1000)+ } catch (err) {+ setLmstudioInstalling(false)+ setLmstudioStartTime(null)+ setLmstudioError(err instanceof Error ? err.message : 'Installation failed')+ }+ }}+ className={`w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] font-medium transition-all ${+ isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'+ }`}+ >+ <Download size={14} /> Or install LM Studio (GUI app, ~570 MB)+ </button>+ )}++ {/* LM Studio install progress */}+ {lmstudioInstalling && (+ <div className={`p-3 rounded-lg border ${cardClass} text-left`}>+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Loader2 size={14} className="animate-spin text-purple-400" />+ <span className="text-[0.7rem] font-medium">+ {lmstudioStatus === 'downloading' ? 'Downloading LM Studio...' :+ lmstudioStatus === 'installing' ? 'Installing LM Studio...' :+ lmstudioStatus === 'starting' ? 'Starting LM Studio server...' :+ 'Setting up LM Studio...'}+ </span>+ </div>+ <span className={`text-[0.55rem] font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ {Math.floor(lmstudioElapsed / 60)}:{String(lmstudioElapsed % 60).padStart(2, '0')}+ </span>+ </div>+ {lmstudioStatus === 'downloading' && lmstudioTotal > 0 && (+ <div className="space-y-1">+ <ProgressBar progress={(lmstudioProgress / lmstudioTotal) * 100} />+ <div className="flex justify-between">+ <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ {formatBytes(lmstudioProgress)} / {formatBytes(lmstudioTotal)}+ </span>+ <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ {lmstudioSpeed > 0 ? `${formatBytes(lmstudioSpeed)}/s` : ''}+ </span>+ </div>+ </div>+ )}+ <div className={`text-[0.55rem] font-mono mt-1 max-h-16 overflow-y-auto space-y-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ {lmstudioLogs.slice(-4).map((log, i) => (+ <p key={i}>{log}</p>+ ))}+ </div>+ </div>+ )}++ {lmstudioError && (+ <p className="text-[0.65rem] text-red-400">+ {lmstudioError}+ {lmstudioError.toLowerCase().includes('didn\'t come up') && (+ <button+ onClick={() => { backendCall('start_lmstudio_server').catch(() => {}); setLmstudioError('') }}+ className={`block mt-1 ${secondaryBtn}`}+ >+ Start LM Studio server+ </button>+ )}+ </p>+ )}+{/* Other alternatives collapsed */}{!ollamaInstalling && !ollamaReady && (<details className={`text-left ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>@@ -473,7 +731,7 @@ export function Onboarding() {Other backends</summary><div className="space-y-1 mt-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">- {LOCAL_BACKENDS.filter(b => b.id !== 'ollama').map(b => (+ {LOCAL_BACKENDS.filter(b => b.id !== 'ollama' && b.id !== 'lmstudio').map(b => (<buttonkey={b.id}onClick={() => openExternal(b.url)}@@ -498,14 +756,17 @@ export function Onboarding() {)}<div className="flex items-center justify-center gap-2 pt-1">- {!ollamaInstalling && !ollamaReady && (+ {!ollamaInstalling && !lmstudioInstalling && !ollamaReady && !lmstudioReady && (<button onClick={runDetection} className={secondaryBtn}><RefreshCw size={12} /> Re-Scan</button>)}- {(ollamaReady || !ollamaInstalling) && (- <button onClick={() => setStep('comfyui')} className={ollamaReady ? primaryBtn : `${secondaryBtn} opacity-60`}>- {ollamaReady ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}+ {(ollamaReady || lmstudioReady || (!ollamaInstalling && !lmstudioInstalling)) && (+ <button+ onClick={() => setStep('comfyui')}+ className={(ollamaReady || lmstudioReady) ? primaryBtn : `${secondaryBtn} opacity-60`}+ >+ {(ollamaReady || lmstudioReady) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}</button>)}</div>@@ -805,7 +1066,7 @@ export function Onboarding() {<div><div className="flex items-center gap-1.5"><span className="font-medium text-[0.7rem]">{model.label}</span>- {model.recommended && (+ {model.recommended && showRecommendedBadge && (<span className={`text-[0.5rem] px-1 py-0.5 rounded ${isDark ? 'bg-white/10 text-gray-300' : 'bg-gray-200 text-gray-600'}`}>Recommended</span>diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 13015228..eec101c6 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -1,4 +1,4 @@-import { useCallback } from 'react'+import { useCallback, useEffect } from 'react'import { listModels, pullModel as pullModelApi, pullModelTauri, deleteModel as deleteModelApi } from '../api/ollama'import { isTauri } from '../api/backend'import { getCheckpoints as getComfyCheckpoints, getDiffusionModels as getComfyDiffusionModels, checkComfyConnection, filterPartialFiles } from '../api/comfyui'@@ -32,6 +32,19 @@ export function useModels() {const isPulling = Object.keys(activePulls).length > 0+ // Refresh trigger: any code path that just installed a model (onboarding,+ // DiscoverModels, the Ollama in-app installer) dispatches this event so+ // every mounted consumer of useModels re-fetches without needing a manual+ // RefreshCw click.+ useEffect(() => {+ const handler = () => { fetchModels().catch(() => {}) }+ window.addEventListener('lu-models-refresh', handler)+ return () => window.removeEventListener('lu-models-refresh', handler)+ // fetchModels is reassigned below on every render but always wraps the+ // same setModels — depending on it would just churn listeners.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])+const fetchModels = useCallback(async () => {try {const allModels: AIModel[] = []diff --git a/src/lib/hf-to-provider.ts b/src/lib/hf-to-provider.tsnew file mode 100644index 00000000..94f12450--- /dev/null+++ b/src/lib/hf-to-provider.ts@@ -0,0 +1,100 @@+/**+ * HuggingFace GGUF URL → provider-specific reference / target path.+ *+ * Why this exists:+ *+ * Ollama and LM Studio both consume GGUFs but expect very different layouts.+ * Ollama owns its model directory (blob store + manifests) and ignores any+ * raw .gguf you drop into ~/.ollama/models. The only sound way to get a HF+ * GGUF into Ollama is to call /api/pull with `hf.co/<user>/<repo>:<quant>`,+ * which Ollama then materialises into its own store.+ *+ * LM Studio scans the model dir for `<user>/<repo>/<file>.gguf` — flat .gguf+ * files at the top level of the model dir are ignored.+ *+ * The previous behaviour was: download the raw .gguf into the provider dir+ * and hope. For both providers above, that "hope" never resolves and the+ * model never appears in the model list — the bug from Discord/GitHub.+ */++const HF_HOST_RE = /^https?:\/\/(?:huggingface\.co|hf\.co)\/([^\/]+)\/([^\/]+)\/(?:resolve|raw|blob)\/[^\/]+\/(.+)$/i++export interface HfRef {+ user: string+ repo: string+ filename: string+}++export function parseHfUrl(url: string): HfRef | null {+ const m = url.match(HF_HOST_RE)+ if (!m) return null+ return { user: m[1], repo: m[2], filename: m[3] }+}++/**+ * Extract the quantisation tag from a GGUF filename.+ *+ * Recognises the formats bartowski / mradermacher / unsloth / QuantFactory+ * actually ship: Q\d_K_[MSL], IQ\d_[A-Z0-9_]+, Q\d_0, Q\d_1, F16, BF16, F32.+ *+ * Returns undefined if no recognised quant is found — callers should fall+ * back to letting Ollama auto-pick (it defaults to Q4_K_M when no tag is+ * given on `hf.co/<repo>` references).+ */+export function extractGgufQuant(filename: string): string | undefined {+ const m = filename.match(+ /[-._](Q\d_K_[MSL]|Q\d_[01]|IQ\d_[A-Z0-9_]+|F16|BF16|F32)\.gguf$/i+ )+ return m?.[1].toUpperCase()+}++/**+ * Build the Ollama HF reference for a HuggingFace GGUF download URL.+ *+ * Returns e.g. "hf.co/bartowski/Meta-Llama-3.1-8B-Instruct-abliterated-GGUF:Q5_K_M".+ * Falls back to no quant tag (Ollama then auto-selects) when the filename+ * doesn't match a known quant pattern.+ *+ * Returns null for non-HF URLs — callers should treat that as "this URL+ * cannot go through ollama pull, use direct download".+ */+export function hfUrlToOllamaRef(url: string, filename?: string): string | null {+ const parsed = parseHfUrl(url)+ if (!parsed) return null+ const quant = extractGgufQuant(filename || parsed.filename)+ const base = `hf.co/${parsed.user}/${parsed.repo}`+ return quant ? `${base}:${quant}` : base+}++/**+ * Build the publisher/repo subfolder LM Studio expects for a HF GGUF.+ *+ * Returns e.g. "bartowski/Meta-Llama-3.1-8B-Instruct-abliterated-GGUF".+ * The full destination becomes `<lmstudio_models_dir>/<this>/<filename>.gguf`,+ * which is the layout LM Studio's scanner uses (mirrors the HF repo path).+ */+export function hfUrlToLmStudioSubdir(url: string): string | null {+ const parsed = parseHfUrl(url)+ if (!parsed) return null+ return `${parsed.user}/${parsed.repo}`+}++/**+ * The list of provider IDs whose downloads must go through ollama pull+ * rather than a direct file write.+ */+export function isOllamaProvider(providerName: string | undefined | null): boolean {+ if (!providerName) return false+ const lower = providerName.toLowerCase()+ return lower === 'ollama'+}++/**+ * The list of provider IDs whose downloads expect the LM-Studio-style+ * <user>/<repo>/<file>.gguf nesting.+ */+export function isLmStudioProvider(providerName: string | undefined | null): boolean {+ if (!providerName) return false+ const lower = providerName.toLowerCase()+ return lower === 'lm studio' || lower === 'lmstudio'+}