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(models): a failed HuggingFace search says so instead of No models found
purple4c073364f1c4
diff --git a/src/api/__tests__/a-failed-hf-search-is-not-an-empty-one.test.ts b/src/api/__tests__/a-failed-hf-search-is-not-an-empty-one.test.tsnew file mode 100644index 00000000..d57f5279--- /dev/null+++ b/src/api/__tests__/a-failed-hf-search-is-not-an-empty-one.test.ts@@ -0,0 +1,53 @@+/**+ * Bug hunt C3 (Oktober 2026): Models, Discover (Chat). Offline (fetch_external+ * throws "dns error") or rate limited (HF answers {"error": "Rate limit+ * reached..."}), the HuggingFace search said "No models found", as if no such+ * model existed. searchHuggingFaceModels swallowed every error into [].+ * It now throws an HfSearchError that says which of the two it was, and an+ * answer with no hits stays an empty list.+ *+ * Run: npx vitest run src/api/__tests__/a-failed-hf-search-is-not-an-empty-one.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const fetchExternal = vi.fn<(url: string) => Promise<string>>()++vi.mock('../backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../backend')>()),+ isTauri: () => true,+ fetchExternal: (url: string) => fetchExternal(url),+}))++import { searchHuggingFaceModels, HfSearchError, hfSearchFailureText } from '../discover'++beforeEach(() => { fetchExternal.mockReset() })++describe('the HuggingFace search when HuggingFace does not answer', () => {+ it('offline: the search fails as offline instead of returning no hits', async () => {+ fetchExternal.mockRejectedValue('error sending request for url (https://huggingface.co/api/models?...): dns error')+ const err = await searchHuggingFaceModels('offline').catch((e: unknown) => e)+ expect(err).toBeInstanceOf(HfSearchError)+ expect((err as HfSearchError).kind).toBe('offline')+ expect(hfSearchFailureText(err)).toBe('Hugging Face could not be reached. Check the connection and search again.')+ })++ it('rate limited: the error JSON is named as the limit, not read as an empty list', async () => {+ fetchExternal.mockResolvedValue(JSON.stringify({ error: 'Rate limit reached. You reached free usage limit' }))+ const err = await searchHuggingFaceModels('ratelimit').catch((e: unknown) => e)+ expect(err).toBeInstanceOf(HfSearchError)+ expect((err as HfSearchError).kind).toBe('rate-limit')+ expect(hfSearchFailureText(err)).toMatch(/limiting searches/)+ })++ it('an answer with no hits is still an empty list', async () => {+ fetchExternal.mockResolvedValue('[]')+ await expect(searchHuggingFaceModels('nothing-matches')).resolves.toEqual([])+ })++ it('an answer with hits is still mapped to models', async () => {+ fetchExternal.mockResolvedValue(JSON.stringify([{ id: 'org/Foo-GGUF', downloads: 2500 }]))+ const hits = await searchHuggingFaceModels('foo')+ expect(hits.map((h) => h.name)).toEqual(['Foo'])+ expect(hits[0].filename).toBe('Foo-Q4_K_M.gguf')+ })+})diff --git a/src/api/discover.ts b/src/api/discover.tsindex ef1e47a4..3a1f6b10 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -1538,7 +1538,32 @@ export function deriveQ4FilenameFromRepo(repoName: string): string {return QUANT_SUFFIX.test(baseName) ? `${baseName}.gguf` : `${baseName}-Q4_K_M.gguf`}+/**+ * The HuggingFace search could not answer: no connection, the free rate limit,+ * or a reply that is not a list of repos. Thrown instead of an empty list so+ * the page can tell "nothing matches" from "nobody answered".+ */+export class HfSearchError extends Error {+ readonly kind: 'offline' | 'rate-limit'+ constructor(kind: 'offline' | 'rate-limit', detail: string) {+ super(detail)+ this.name = 'HfSearchError'+ this.kind = kind+ }+}++/** The sentence the user reads when the HuggingFace search failed. */+export function hfSearchFailureText(err: unknown): string {+ if (err instanceof HfSearchError && err.kind === 'rate-limit') {+ return 'Hugging Face is limiting searches right now. Wait a minute and search again.'+ }+ return 'Hugging Face could not be reached. Check the connection and search again.'+}++const RATE_LIMIT = /rate.?limit|too many requests|\b429\b/i+export async function searchHuggingFaceModels(query: string): Promise<DiscoverModel[]> {+ let repos: Array<{ id: string; downloads?: number; modelId?: string }>try {// Case-insensitive · HF repos almost always end in `-GGUF` (uppercase),// and the previous case-sensitive `includes('gguf')` missed those, so a@@ -1554,43 +1579,52 @@ export async function searchHuggingFaceModels(query: string): Promise<DiscoverMo} else {const res = await fetch(url)json = await res.text()+ if (res.status === 429) throw new HfSearchError('rate-limit', `HTTP 429: ${json.slice(0, 200)}`)}- const repos: Array<{ id: string; downloads?: number; modelId?: string }> = JSON.parse(json)-- const models: DiscoverModel[] = []- for (const repo of repos) {- const repoName = repo.id.split('/').pop() || ''- const q4File = deriveQ4FilenameFromRepo(repoName)- const downloadUrl = `https://huggingface.co/${repo.id}/resolve/main/${q4File}`-- // Display name = repo basename without the GGUF suffix. The previous- // version referenced an undefined `baseName` here, throwing a- // ReferenceError that the catch silently turned into an empty array- // · the user-facing P11 search was returning "No models found" for- // every query, even ones that match plenty of HF results.- const displayName = repoName.replace(/-GGUF$/i, '').replace(/-gguf$/i, '')-- const downloads = repo.downloads || 0- const pullsStr = downloads > 1000000 ? `${(downloads / 1000000).toFixed(1)}M` :- downloads > 1000 ? `${Math.round(downloads / 1000)}K` : `${downloads}`-- models.push({- name: displayName,- description: repo.id,- pulls: pullsStr,- tags: ['Q4_K_M', 'GGUF'],- updated: '',- downloadUrl,- filename: q4File,- url: `https://huggingface.co/${repo.id}`,- })+ const parsed: unknown = JSON.parse(json)+ if (!Array.isArray(parsed)) {+ // HF answers a limit or an outage with {"error": "..."} instead of a list.+ const said = isRecord(parsed) && typeof parsed.error === 'string' ? parsed.error : json.slice(0, 200)+ throw new HfSearchError(RATE_LIMIT.test(said) ? 'rate-limit' : 'offline', said)}- return models+ repos = parsed} catch (err) {log.warn('[discover] HF search failed', { err })- return []+ if (err instanceof HfSearchError) throw err+ throw new HfSearchError(RATE_LIMIT.test(String(err)) ? 'rate-limit' : 'offline', String(err))+ }++ const models: DiscoverModel[] = []+ for (const repo of repos) {+ if (typeof repo?.id !== 'string') continue+ const repoName = repo.id.split('/').pop() || ''+ const q4File = deriveQ4FilenameFromRepo(repoName)+ const downloadUrl = `https://huggingface.co/${repo.id}/resolve/main/${q4File}`++ // Display name = repo basename without the GGUF suffix. The previous+ // version referenced an undefined `baseName` here, throwing a+ // ReferenceError that the catch silently turned into an empty array+ // · the user-facing P11 search was returning "No models found" for+ // every query, even ones that match plenty of HF results.+ const displayName = repoName.replace(/-GGUF$/i, '').replace(/-gguf$/i, '')++ const downloads = repo.downloads || 0+ const pullsStr = downloads > 1000000 ? `${(downloads / 1000000).toFixed(1)}M` :+ downloads > 1000 ? `${Math.round(downloads / 1000)}K` : `${downloads}`++ models.push({+ name: displayName,+ description: repo.id,+ pulls: pullsStr,+ tags: ['Q4_K_M', 'GGUF'],+ updated: '',+ downloadUrl,+ filename: q4File,+ url: `https://huggingface.co/${repo.id}`,+ })}+ return models}// ─── HuggingFace file-tree resolution (sharded / multi-part GGUF) ───diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex 4d68d657..4e2d7a92 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -6,6 +6,7 @@ import { Search, XCircle, Sparkles, Unlock, ShieldCheck, ExternalLink, Info } frimport { X } from 'lucide-react'import {searchHuggingFaceModels,+ hfSearchFailureText,getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles,getUncensoredTextModels, getMainstreamTextModels,detectProviderModelPath, luEngineDownloadDir,@@ -613,6 +614,9 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:// end the spinner: a slow answer to an older query arriving late used to// overwrite the hits of the query now in the box.const hfSearchSeq = useRef(0)+ // Offline or rate limited is not "No models found": the user would go on+ // trying other words instead of checking the connection.+ const [hfSearchError, setHfSearchError] = useState<string | null>(null)const handleSearch = async () => {if (!search.trim() || !isText) return@@ -620,8 +624,16 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:setLoading(true)try {const results = await searchHuggingFaceModels(search.trim())- if (mine === hfSearchSeq.current) setHfSearchResults(results)- } catch { /* keep existing */ }+ if (mine === hfSearchSeq.current) {+ setHfSearchResults(results)+ setHfSearchError(null)+ }+ } catch (err) {+ if (mine === hfSearchSeq.current) {+ setHfSearchResults([])+ setHfSearchError(hfSearchFailureText(err))+ }+ }if (mine === hfSearchSeq.current) setLoading(false)}@@ -1223,6 +1235,10 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:)}</div>+ {hfSearchError && (+ <p role="alert" className={skin.cls.searchEmpty} data-testid="hf-search-failed">{hfSearchError}</p>+ )}+{/* HuggingFace Search Results */}{hfSearchResults.length > 0 && (<div className={`${skin.cls.group} mt-6`}>@@ -1252,7 +1268,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:</>) : null}- {!loading && filteredBundles.length === 0 && filteredUncensored.length === 0 && filteredMainstream.length === 0 && (+ {!loading && !(isText && hfSearchError) && filteredBundles.length === 0 && filteredUncensored.length === 0 && filteredMainstream.length === 0 && (<p className={skin.cls.searchEmpty}>No models found</p>)}diff --git a/src/components/models/__tests__/a-failed-hf-search-says-so.test.tsx b/src/components/models/__tests__/a-failed-hf-search-says-so.test.tsxnew file mode 100644index 00000000..3cca9140--- /dev/null+++ b/src/components/models/__tests__/a-failed-hf-search-says-so.test.tsx@@ -0,0 +1,84 @@+/**+ * @vitest-environment jsdom+ *+ * Bug hunt C3 (Oktober 2026): Models, Discover (Chat), HuggingFace search with+ * no connection or over the rate limit. The page said "No models found", as if+ * the model did not exist, and the user went on trying other words instead of+ * checking the connection. A failed search now says so; a search that really+ * finds nothing still says "No models found".+ *+ * Run: npx vitest run src/components/models/__tests__/a-failed-hf-search-says-so.test.tsx+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, cleanup, waitFor } from '@testing-library/react'+import type { DiscoverModel } from '../../../api/model-bundles'++const search = vi.fn<(q: string) => Promise<DiscoverModel[]>>()++vi.mock('../../../api/discover', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/discover')>()),+ searchHuggingFaceModels: (q: string) => search(q),+}))+vi.mock('../../../api/backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/backend')>()),+ backendCall: vi.fn(async () => []),+ openExternal: vi.fn(),+ isTauri: () => false,+ isMacOS: () => false,+}))+vi.mock('../../../api/comfyui', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/comfyui')>()),+ getSystemVRAM: vi.fn(async () => 16),+ readComfyFolderLists: vi.fn(async () => ({})),+ refreshComfyModels: vi.fn(async () => {}),+}))+vi.mock('../../../lib/hardware', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../lib/hardware')>()),+ getMaxVramGb: vi.fn(async () => 16),+ getTotalRamGb: vi.fn(async () => 64),+}))+vi.mock('../../../api/kimi-k3-catalog', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/kimi-k3-catalog')>()),+ kimiK31CatalogEntries: vi.fn(async () => []),+}))+vi.mock('../CivitaiSearchPanel', () => ({ CivitaiSearchPanel: () => null }))+vi.mock('../../chat/LuEngineSwitchBar', () => ({ LuEngineSwitchBar: () => null }))++import { DiscoverModels } from '../DiscoverModels'+import { HfSearchError } from '../../../api/discover'++const text = () => document.body.textContent ?? ''+// Matches nothing in the curated lists, so only the HF search decides.+const QUERY = 'zzqxnomodel'++beforeEach(() => {+ cleanup()+ search.mockReset()+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })+})+afterEach(() => { cleanup(); vi.unstubAllGlobals() })++describe('a failed HuggingFace search in Discover (Chat)', () => {+ it('THE REPORT: offline says Hugging Face could not be reached, not "No models found"', async () => {+ search.mockRejectedValue(new HfSearchError('offline', 'dns error'))+ render(<DiscoverModels category="text" search={QUERY} searchSubmitToken={1} />)+ await waitFor(() => expect(text()).toContain('Hugging Face could not be reached. Check the connection and search again.'))+ expect(document.querySelector('[data-testid="hf-search-failed"]')?.getAttribute('role')).toBe('alert')+ expect(text()).not.toContain('No models found')+ })++ it('rate limited says the limit', async () => {+ search.mockRejectedValue(new HfSearchError('rate-limit', 'Rate limit reached'))+ render(<DiscoverModels category="text" search={QUERY} searchSubmitToken={1} />)+ await waitFor(() => expect(text()).toContain('Hugging Face is limiting searches right now.'))+ expect(text()).not.toContain('No models found')+ })++ it('a search that finds nothing still says "No models found"', async () => {+ search.mockResolvedValue([])+ render(<DiscoverModels category="text" search={QUERY} searchSubmitToken={1} />)+ await waitFor(() => expect(search).toHaveBeenCalled())+ await waitFor(() => expect(text()).toContain('No models found'))+ expect(document.querySelector('[data-testid="hf-search-failed"]')).toBeNull()+ })+})diff --git a/src/mobile/screens/models/ModelsPage.tsx b/src/mobile/screens/models/ModelsPage.tsxindex d4869d46..ccfdf36a 100644--- a/src/mobile/screens/models/ModelsPage.tsx+++ b/src/mobile/screens/models/ModelsPage.tsx@@ -60,6 +60,10 @@ function useSearch(query: string, online: boolean): SearchState {if (!alive) returnsetResult({ query, hits })loadVariantsOf(hits.map(repoOfHit))+ }, () => {+ // The search now throws when HuggingFace does not answer. This screen+ // keeps its earlier behaviour: an empty list instead of a spinner forever.+ if (alive) setResult({ query, hits: [] })})return () => {alive = false