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
address review (claude): stop caching transient Hub failures, and isolate the test suite from the live cache
[._.]/ Adam Eivyc9de6b214e2a
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 5f0aa44e79..33d3235d2b 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -97,6 +97,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.+- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).---diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex c138a220e1..46fbbd64f1 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -680,27 +680,65 @@ function hfHeaders() {// burst the Hub answers with an HTTP/2 GOAWAY. See concurrencyGate for why a// shared gate rather than a per-map cap.const hfGate = createConcurrencyGate(4)+// The interactive search's own LIST query gets a separate, tiny budget so it is+// never stuck behind the catalog's fan-out. `enrichCatalogWithVariants` bounds+// how long the *response* waits, not the probes themselves — abandoned probes+// keep draining through hfGate — so a user who lands on the curated tab and then+// switches to Hugging Face would otherwise queue behind up to ~32 waiters. On a+// degraded Hub each of those costs two timeouts, which is minutes of a search box+// that has not even issued its request yet. This query is 1–2 requests, not a+// fan-out, so a budget of 2 keeps the total offered to the Hub bounded (4 + 2)+// while making the path the user is actually waiting on independent.+const hfSearchGate = createConcurrencyGate(2)// Coalesce concurrent probes of the SAME repo — a repo can appear in both the// curated catalog and the live search, and neither caches until it resolves.const repoModelFlight = createSingleFlight()+// Statuses that are a real, durable "this repo has no data for you" answer and+// so are safe to cache. Everything else non-OK (429 rate limit, 5xx, 408) is the+// Hub having a bad moment — mirrors `resolveRegistryBody` in+// ollamaRegistryCatalog.js, which has always drawn this line.+const HF_PERMANENT_NOT_FOUND = new Set([401, 403, 404, 410])+// Single door to the Hub: bounded concurrency + the shared one-shot retry.-// Resolves with the Response (including non-2xx — status handling stays with the-// caller); throws only when the request itself failed twice. The retry runs-// INSIDE the gate slot so a replay doesn't re-queue behind every other probe.+//+// Returns a discriminated outcome rather than a Response, because the body must+// be consumed INSIDE the gate slot. Releasing at response headers would bound+// only the header waits while every body streamed concurrently — i.e. exactly+// the many-simultaneous-streams-on-one-pooled-connection condition that earns+// the GOAWAY this gate exists to prevent.+//+// { outcome: 'ok', data } — 2xx with a parseable body+// { outcome: 'permanent', status, errorText } — a durable no-data answer; cacheable+// { outcome: 'transient', status, errorText } — a bad moment; MUST NOT be cached+//+// Throws only when both attempts failed at the connection level.function hfFetch(url) {- return hfGate.run(() => fetchWithTimeout(- url,- { headers: hfHeaders() },- HF_TIMEOUT_MS,- { retries: 1, retryDelayMs: HF_RETRY_DELAY_MS, shouldRetry: isReplayableConnectionError }- // Both attempts lost the connection. undici's own message is a bare `fetch- // failed`, which reaches the search box verbatim and reads like a bug in- // PortOS — name the actual condition so the user knows to just try again.- ).catch((err) => {- if (!isReplayableConnectionError(err)) throw err- throw new Error(`Hugging Face is not responding (connection dropped twice) — try again in a moment. [${describeFetchError(err)}]`)- }))+ return hfGate.run(async () => {+ const res = await fetchWithTimeout(+ url,+ { headers: hfHeaders() },+ HF_TIMEOUT_MS,+ { retries: 1, retryDelayMs: HF_RETRY_DELAY_MS, shouldRetry: isReplayableConnectionError }+ // Both attempts lost the connection. undici's own message is a bare `fetch+ // failed`, which reaches the search box verbatim and reads like a bug in+ // PortOS — name the actual condition so the user knows to just try again.+ ).catch((err) => {+ if (!isReplayableConnectionError(err)) throw err+ throw new Error(`Hugging Face is not responding (connection dropped twice) — try again in a moment. [${describeFetchError(err)}]`)+ })+ if (!res.ok) {+ const errorText = await res.text().catch(() => '')+ const outcome = HF_PERMANENT_NOT_FOUND.has(res.status) ? 'permanent' : 'transient'+ return { outcome, status: res.status, errorText }+ }+ // A 200 whose body won't parse is a proxy/captive-portal error page, not an+ // answer about the repo — transient, so it is never cached as "no data".+ const data = await readResponseJson(res, { fallback: null })+ return data == null+ ? { outcome: 'transient', status: res.status, errorText: 'unparseable response body' }+ : { outcome: 'ok', data }+ })}// `filter` is a Hugging Face library tag — 'gguf' for the GGUF query, 'mlx' for@@ -717,21 +755,21 @@ async function fetchModels(search, limit, filter) {})if (filter) params.set('filter', filter)- const response = await hfFetch(`${HF_API_BASE}?${params.toString()}`)- if (!response.ok) {- const text = await response.text().catch(() => '')- throw new Error(`Hugging Face search failed: ${response.status}${text ? ` — ${text.slice(0, 160)}` : ''}`)+ const result = await hfSearchGate.run(() => hfFetch(`${HF_API_BASE}?${params.toString()}`))+ if (result.outcome !== 'ok') {+ const detail = result.errorText ? ` — ${result.errorText.slice(0, 160)}` : ''+ throw new Error(`Hugging Face search failed: ${result.status}${detail}`)}- const data = await readResponseJson(response, { fallback: [] })- return Array.isArray(data) ? data : []+ return Array.isArray(result.data) ? result.data : []}const repoModelCache = new Map()const REPO_MODEL_CACHE_MAX = 500-// A transient fetch failure (network down / timeout / malformed body) — distinct-// from a genuine HTTP non-OK (404 / gated / private). The former must NOT be-// cached (it would permanently disable enrichment for the process until HF-// recovers); the latter is a real "no data" answer worth caching.+// A connection-level failure (network down / both retry attempts dropped) —+// distinct both from a durable no-data answer (401/403/404/410, cacheable) and+// from a transient HTTP status (429/5xx), which `hfFetch` reports as+// `outcome: 'transient'`. Neither transient form may be cached: doing so would+// disable enrichment for the repo until the TTL expires, a week later.const TRANSIENT_FETCH = Symbol('transient-fetch')// Fetch (and cache) the per-model record WITH per-file sizes. The search@@ -743,10 +781,12 @@ const TRANSIENT_FETCH = Symbol('transient-fetch')// for all of them after every restart, self-update, or dev reload. Steady state// on that path is zero network.//-// `null` = fetched-but-unavailable (gated / private / 404), cached at both tiers-// (per the absent-vs-empty sentinel rule) so a sizeless repo isn't re-probed-// every search. A transient failure returns null too but is NOT cached, so a-// recovered Hub re-enriches on the next request instead of staying blank.+// `null` = fetched-but-unavailable, and it is cached at both tiers (per the+// absent-vs-empty sentinel rule) so a sizeless repo isn't re-probed every search+// — but ONLY when the Hub gave a durable answer (401/403/404/410). A rate limit,+// a 5xx, or a dropped connection also returns null and is NOT cached, so a+// recovered Hub re-enriches on the next request instead of staying blank for the+// week the disk TTL would otherwise hold it.async function fetchRepoModel(repoId) {if (repoModelCache.has(repoId)) return repoModelCache.get(repoId)return repoModelFlight.run(repoId, async () => {@@ -760,10 +800,15 @@ async function fetchRepoModel(repoId) {// repoId comes from the HF search response (untrusted upstream) — encode each// path segment so a `?`/`#`/`..` in the id can't reshape the request path/query.const safeRepoPath = String(repoId).split('/').map(encodeURIComponent).join('/')- const model = await hfFetch(`${HF_API_BASE}/${safeRepoPath}?blobs=true`)- .then((res) => (res.ok ? res.json() : null))+ const result = await hfFetch(`${HF_API_BASE}/${safeRepoPath}?blobs=true`).catch(() => TRANSIENT_FETCH)- if (model === TRANSIENT_FETCH) return null // transient — return null but don't cache+ // Transient — a rate limit, a 5xx, or a dropped connection. Return null so+ // this load degrades gracefully, but do NOT cache it: persisting a transient+ // as "no data" would bake a bad moment into the disk tier for the full TTL,+ // and a restart would no longer clear it the way the old memory-only cache did.+ if (result === TRANSIENT_FETCH || result.outcome === 'transient') return null+ // 'permanent' (gated / private / gone) IS a real answer — cache the null.+ const model = result.outcome === 'ok' ? result.data : nullrememberRepoModel(repoId, model)await writeCachedRepoModel(repoId, model)return modeldiff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.jsindex 11635852f5..25eb2194cf 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -2,6 +2,22 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { searchHuggingFaceModels, enrichCatalogWithVariants } from './huggingFaceCatalog.js'import { __resetOllamaRegistryCache } from './ollamaRegistryCatalog.js'+// The disk cache resolves its file from the REAL PATHS.data, and fetchRepoModel+// consults it before the network — so without this mock these tests read the+// developer's live `data/cache/huggingface-repos.json`. The fixtures below use+// real repo ids (bartowski/…, facebook/musicgen-small, nomic-ai/…) that this very+// feature caches the moment anyone opens Settings → Local LLM, so a cached record+// would bypass the `fetch` mock entirely and fail assertions locally while CI —+// with no cache file — stayed green. Mocking also keeps the debounced writer from+// ever persisting these fabricated records (a 13 GB `Qwen3.6-35B`, `burst-pub/…`)+// into the real cache, which the running server would then serve as genuine sizes.+// Spies, not plain stubs, so the what-gets-persisted tests below can observe the+// writes — which is the whole point of the transient-vs-durable distinction.+vi.mock('./huggingFaceRepoCache.js', () => ({+ readCachedRepoModel: vi.fn(async () => ({ hit: false, model: null })),+ writeCachedRepoModel: vi.fn(async () => {})+}))+const response = (body, ok = true) => ({ok,status: ok ? 200 : 500,@@ -10,8 +26,11 @@ const response = (body, ok = true) => ({})describe('huggingFaceCatalog', () => {- beforeEach(() => {+ beforeEach(async () => {vi.stubGlobal('fetch', vi.fn())+ const cache = await import('./huggingFaceRepoCache.js')+ cache.readCachedRepoModel.mockClear()+ cache.writeCachedRepoModel.mockClear()})afterEach(() => {@@ -1010,6 +1029,89 @@ describe('huggingFaceCatalog', () => {expect(catalog.every((e) => e.format === 'gguf')).toBe(true)})+ // The disk cache holds entries for a WEEK, so what gets written matters far+ // more than it did when a restart cleared everything. A rate limit is exactly+ // what a burst provokes — caching it as "this repo has no sizes" would bake+ // the degradation in for seven days, across restarts.+ it.each([+ ['a 429 rate limit', 429],+ ['a 503 outage', 503],+ ['a 408 timeout', 408]+ ])('does not cache %s as a durable "no data" answer', async (_label, status) => {+ const repo = `transient-${status}/Repo-GGUF`+ const { writeCachedRepoModel } = await import('./huggingFaceRepoCache.js')++ fetch.mockImplementation(async (url) => (+ String(url).includes('blobs=true')+ ? { ok: false, status, json: vi.fn(), text: vi.fn(async () => 'slow down') }+ : response([{ modelId: repo, downloads: 1, tags: ['gguf'], siblings: [{ rfilename: 'T-Q4_K_M.gguf', size: 100 }] }])+ ))++ const catalog = [{ id: repo, key: 't', name: 'T', category: 'chat', size: '2.0 GB' }]+ await enrichCatalogWithVariants(catalog, {+ backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [], timeoutMs: 0+ })++ expect(writeCachedRepoModel.mock.calls).toEqual([])+ })++ // A durable answer IS worth caching — the counterpart to the test above, so a+ // fix for one can't quietly disable the other.+ it.each([+ ['a 404 (repo gone)', 404],+ ['a 403 (gated)', 403]+ ])('caches %s as a durable "no data" answer', async (_label, status) => {+ const repo = `permanent-${status}/Repo-GGUF`+ const { writeCachedRepoModel } = await import('./huggingFaceRepoCache.js')++ fetch.mockImplementation(async (url) => (+ String(url).includes('blobs=true')+ ? { ok: false, status, json: vi.fn(), text: vi.fn(async () => 'nope') }+ : response([])+ ))++ const catalog = [{ id: repo, key: 'p', name: 'P', category: 'chat', size: '2.0 GB' }]+ await enrichCatalogWithVariants(catalog, {+ backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [], timeoutMs: 0+ })++ expect(writeCachedRepoModel.mock.calls).toEqual([[repo, null]])+ })++ // The gate must bound open CONNECTIONS, not just header waits — releasing the+ // slot before the body is read would let all N stream at once, which is the+ // condition that earns the GOAWAY in the first place.+ it('holds the gate slot until the response body is consumed', async () => {+ let bodiesInFlight = 0+ let peakBodies = 0+ fetch.mockImplementation(async (url) => {+ const repo = String(url).split('/api/models/')[1]?.split('?')[0] || 'x/y'+ // Instrument text(), which is what readResponseJson actually consumes.+ return {+ ok: true,+ status: 200,+ json: vi.fn(),+ text: async () => {+ bodiesInFlight += 1+ peakBodies = Math.max(peakBodies, bodiesInFlight)+ await new Promise((resolve) => setTimeout(resolve, 5))+ bodiesInFlight -= 1+ return JSON.stringify({ id: repo, siblings: [{ rfilename: 'B-Q4_K_M.gguf', size: 4_000_000_000 }] })+ }+ }+ })++ const catalog = Array.from({ length: 20 }, (_, i) => ({+ id: `body-pub/Body-${i}-GGUF`, key: `body-${i}`, name: `Body ${i}`, category: 'chat', size: '2.0 GB'+ }))+ await enrichCatalogWithVariants(catalog, {+ backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [], timeoutMs: 0+ })++ expect(peakBodies).toBeLessThanOrEqual(4)+ expect(catalog.every((e) => e.format === 'gguf')).toBe(true)+ })+it('coalesces concurrent probes of the same repo into one request', async () => {const repo = 'dedupe-pub/Shared-GGUF'let blobCalls = 0diff --git a/server/services/huggingFaceRepoCache.js b/server/services/huggingFaceRepoCache.jsindex 0f9cafa7d3..49c6a9a278 100644--- a/server/services/huggingFaceRepoCache.js+++ b/server/services/huggingFaceRepoCache.js@@ -82,6 +82,12 @@ async function flush() {// likely to be wanted again, not whichever the Map happened to hold first.fresh.sort((a, b) => b[1].fetchedAt - a[1].fetchedAt)const capped = fresh.slice(0, CACHE_MAX_ENTRIES)+ // Apply the prune+cap to the IN-MEMORY map too, not just the disk projection.+ // Nothing else evicts from it, and each HF search enriches up to 18 repos at+ // ~5 KB apiece — so on a long-lived server heavy search use would grow the+ // process by tens of MB that never came back, while every flush re-sorted the+ // whole set to write only the top 500.+ entries = new Map(capped)await ensureDir(join(PATHS.data, 'cache'))await atomicWrite(CACHE_FILE, {schemaVersion: CACHE_SCHEMA_VERSION,@@ -98,9 +104,25 @@ function scheduleSave() {saveTimer = setTimeout(() => {flush().catch((err) => console.error(`❌ Failed to persist Hugging Face repo cache: ${err.message}`))}, SAVE_DEBOUNCE_MS)+ // unref'd so a pending cache write never holds the process open — but that+ // means a restart landing inside the debounce window drops the batch and the+ // next boot re-pays the whole burst, which is the one cost this module exists+ // to remove. The shutdown flush below closes that window without giving up the+ // unref.saveTimer.unref?.()}+// Persist a pending batch on shutdown. Fire-and-forget by necessity — the signal+// handler can't await — but atomicWrite's temp+rename means a half-written file+// is never observable, and a dropped write only costs a refetch. `once` per+// signal so repeated SIGTERMs don't stack handlers.+for (const signal of ['SIGTERM', 'SIGINT']) {+ process.once(signal, () => {+ if (!dirty) return+ flush().catch((err) => console.error(`❌ Failed to flush Hugging Face repo cache on ${signal}: ${err.message}`))+ })+}+/*** Read a cached repo record.* @returns {Promise<{ hit: boolean, model: object|null }>} `hit: false` on a miss