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
cache HF repo metadata to disk and bound the catalog burst that triggered GOAWAY
[._.]/ Adam Eivy21b1c2c032ec
diff --git a/.changelog/next/fixed-hf-search-goaway-and-burst.md b/.changelog/next/fixed-hf-search-goaway-and-burst.mdnew file mode 100644index 0000000000..356829207f--- /dev/null+++ b/.changelog/next/fixed-hf-search-goaway-and-burst.md@@ -0,0 +1,2 @@+- Hugging Face model search no longer fails with a bare "fetch failed". The Hub's HTTP/2 GOAWAY on a retired pooled connection is retried once (opt-in `retries` on the shared `fetchWithTimeout`), and a repeated failure now names the condition instead of surfacing undici's opaque message.+- Opening Settings → Local LLM no longer bursts the Hugging Face and Ollama registry APIs. Per-repo metadata is cached to disk (`data/cache/`, 7-day TTL) so a known catalog costs zero requests after the first load — even across restarts — and what remains flows through a bounded gate instead of ~36 simultaneous probes. Cold catalog load 1.3s, warm 0.04s.diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 7dd72fc03f..f0c45e0011 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -345,7 +345,12 @@ export function LocalLlmTab() {});}, []);- const loadCatalog = useCallback((backend, q, source = catalogSource, category = activeCategory) => {+ // `source` and `category` are required rather than defaulted from state: a+ // state default would put them in the dep list, so `loadCatalog`'s identity+ // would change on every category click and re-trigger the debounce effect —+ // the exact refetch the effect below is written to avoid. Every call site+ // passes both.+ const loadCatalog = useCallback((backend, q, source, category) => {const requestId = ++catalogRequestId.current;setCatalogLoading(true);setCatalogError('');@@ -368,14 +373,26 @@ export function LocalLlmTab() {.finally(() => {if (requestId === catalogRequestId.current) setCatalogLoading(false);});- }, [activeCategory, catalogSource]);+ }, []);useEffect(() => { loadStatus(); }, [loadStatus]);// Debounce so typing in the search box doesn't fire a request per keystroke.+ //+ // `activeCategory` is a trigger for the Hugging Face source ONLY — the live+ // search asks the Hub for that category's models, so switching tabs is a new+ // query. The curated catalog sends just backend+q and filters by category on+ // the client (see visibleCatalogGroups), so refetching on a tab click would+ // re-request a byte-identical list AND re-run the server's ~36-repo variant+ // enrichment. `catalogCategoryKey` is the category when it matters and a+ // constant when it doesn't, which keeps the whole effect one code path.+ const catalogCategoryKey = catalogSource === 'huggingface' ? activeCategory : 'client-filtered';useEffect(() => {const t = setTimeout(() => loadCatalog(selected, query, catalogSource, activeCategory), catalogSource === 'huggingface' ? 450 : 250);return () => clearTimeout(t);- }, [selected, query, catalogSource, activeCategory, loadCatalog]);+ // activeCategory is intentionally absent — catalogCategoryKey carries it for+ // the one source that needs it. loadCatalog reads the freshest value anyway.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selected, query, catalogSource, catalogCategoryKey, loadCatalog]);useEffect(() => {const handleProgress = (data) => {diff --git a/server/lib/README.md b/server/lib/README.mdindex d0fe456ac3..df6e077e9e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -340,10 +340,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `arrayUtils.js` | `shuffle(arr)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). || `asyncMutex.js` | Promise-based async mutex. || `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. |+| `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceCatalog.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. || `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. |+| `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. || `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), `isoWeeksInYear(year)` (52, or 53 in a leap-week year), and `isConsecutiveWeek(a, b)` — which bridges a year rollover only when `a` is genuinely its year's last week. Shared by `services/productivity.js` (streaks) and `services/weeklyDigest.js` (digest filenames). || `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |diff --git a/server/lib/concurrencyGate.js b/server/lib/concurrencyGate.jsnew file mode 100644index 0000000000..893ba38f2b--- /dev/null+++ b/server/lib/concurrencyGate.js@@ -0,0 +1,43 @@+/**+ * Process-wide bounded-concurrency gate for un-batched async work.+ *+ * `createConcurrencyGate(limit)` → `run(fn)`, which resolves/rejects with+ * `fn()`'s result once a slot frees. Waiters are released FIFO. `fn` runs at+ * most `limit`-at-a-time; a rejecting `fn` still releases its slot.+ *+ * Sibling to two narrower primitives, and the reason to reach for this one+ * instead:+ * - `mapWithConcurrency.js` caps in-flight work *within one array map*. That is+ * not enough when several independent call sites fan out at the same remote+ * at once — each map stays under its own cap while the host sees the sum. A+ * gate is shared state, so one budget holds across call sites and requests.+ * - `asyncMutex.js` (`createMutex`) is this with `limit` fixed at 1. Prefer it+ * when the intent is mutual exclusion rather than a throughput cap.+ *+ * @param {number} limit - max simultaneous `fn()` executions (floored at 1)+ * @returns {{ run: <T>(fn: () => Promise<T>) => Promise<T>, active: () => number }}+ */+export function createConcurrencyGate(limit) {+ const max = Number.isFinite(Number(limit)) ? Math.max(1, Math.floor(Number(limit))) : 1;+ const waiting = []; // FIFO of `resolve` callbacks holding a slot request+ let active = 0;++ function release() {+ // Hand the slot straight to the oldest waiter, or give it back if none.+ const next = waiting.shift();+ if (next) next();+ else active -= 1;+ }++ async function run(fn) {+ if (active < max) active += 1;+ else await new Promise((resolve) => waiting.push(resolve));+ try {+ return await fn();+ } finally {+ release();+ }+ }++ return { run, active: () => active };+}diff --git a/server/lib/concurrencyGate.test.js b/server/lib/concurrencyGate.test.jsnew file mode 100644index 0000000000..5debf713b8--- /dev/null+++ b/server/lib/concurrencyGate.test.js@@ -0,0 +1,87 @@+import { describe, it, expect } from 'vitest';+import { createConcurrencyGate } from './concurrencyGate.js';++// A deferred promise plus the observable "did it start yet" flag, so a test can+// assert on what the gate ADMITTED rather than on timing.+function deferredTask() {+ let resolve;+ let reject;+ const settled = new Promise((res, rej) => { resolve = res; reject = rej; });+ const task = { started: false, resolve, reject };+ task.fn = () => {+ task.started = true;+ return settled;+ };+ return task;+}++// Yield a macrotask so any `run()` that could start has started.+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++describe('createConcurrencyGate', () => {+ it('admits only `limit` tasks at once and releases the rest FIFO', async () => {+ const gate = createConcurrencyGate(2);+ const tasks = [deferredTask(), deferredTask(), deferredTask(), deferredTask()];+ const runs = tasks.map((t) => gate.run(t.fn));+ await tick();++ expect(tasks.map((t) => t.started)).toEqual([true, true, false, false]);+ // Releasing the FIRST slot must admit the OLDEST waiter, not the newest.+ tasks[0].resolve('a');+ await tick();+ expect(tasks.map((t) => t.started)).toEqual([true, true, true, false]);++ tasks[1].resolve('b');+ tasks[2].resolve('c');+ await tick();+ expect(tasks[3].started).toBe(true);++ tasks[3].resolve('d');+ await expect(Promise.all(runs)).resolves.toEqual(['a', 'b', 'c', 'd']);+ expect(gate.active()).toBe(0);+ });++ it('releases the slot when a task rejects, so a failure cannot wedge the gate', async () => {+ const gate = createConcurrencyGate(1);+ const first = deferredTask();+ const second = deferredTask();+ const firstRun = gate.run(first.fn);+ const secondRun = gate.run(second.fn);+ await tick();+ expect(second.started).toBe(false);++ first.reject(new Error('boom'));+ await expect(firstRun).rejects.toThrow('boom');+ await tick();+ expect(second.started).toBe(true);++ second.resolve('ok');+ await expect(secondRun).resolves.toBe('ok');+ expect(gate.active()).toBe(0);+ });++ it('never exceeds the cap under a burst larger than the queue drain rate', async () => {+ const gate = createConcurrencyGate(3);+ let inFlight = 0;+ let peak = 0;+ await Promise.all(Array.from({ length: 25 }, () => gate.run(async () => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await tick();+ inFlight -= 1;+ })));+ expect(peak).toBe(3);+ expect(gate.active()).toBe(0);+ });++ it('floors a non-positive or non-numeric limit at 1 rather than admitting everything', async () => {+ for (const limit of [0, undefined]) {+ const gate = createConcurrencyGate(limit);+ const tasks = [deferredTask(), deferredTask()];+ tasks.forEach((t) => { gate.run(t.fn); });+ await tick();+ expect(tasks.map((t) => t.started)).toEqual([true, false]);+ tasks.forEach((t) => t.resolve(null));+ }+ });+});diff --git a/server/lib/fetchErrorChain.js b/server/lib/fetchErrorChain.jsnew file mode 100644index 0000000000..d33c39cb85--- /dev/null+++ b/server/lib/fetchErrorChain.js@@ -0,0 +1,63 @@+/**+ * Flatten a fetch rejection's whole `cause` chain into one searchable string.+ *+ * Node/undici reports every network-level failure as the same opaque+ * `TypeError: fetch failed`, with the real reason (ECONNRESET, ETIMEDOUT, an+ * HTTP/2 GOAWAY, ...) tucked into `err.cause` — and sometimes nested deeper+ * still. A classifier that reads only `err.message` therefore sees "fetch+ * failed" for everything and misclassifies retryable failures as fatal, which+ * is the precise bug this exists to prevent. Collects each level's `.code` as+ * well as its `.message`, so code-only signals (`UND_ERR_SOCKET`) match too.+ *+ * Callers layer their OWN predicate on top of this string rather than sharing+ * one: what counts as retryable is caller-specific. The Ollama pull loop treats+ * a timeout as transient (it is streaming a multi-GB download over a flaky+ * link); the Hugging Face probes deliberately do NOT (a slow Hub would then get+ * double the traffic). Keep that policy at the call site; keep the extraction+ * here.+ *+ * @param {unknown} err+ * @returns {string} `code: message: code: message…` across the chain, or+ * `String(err)` when nothing was extractable.+ */+export function describeFetchError(err) {+ const parts = [];+ let node = err;+ const seen = new Set();+ // Bound the walk in case of a self-referential cause chain.+ for (let depth = 0; node && typeof node === 'object' && depth < 5; depth++) {+ if (seen.has(node)) break;+ seen.add(node);+ if (node.code) parts.push(String(node.code));+ if (node.message) parts.push(String(node.message));+ node = node.cause;+ }+ // A chain can bottom out in a bare string cause — keep it.+ if (typeof node === 'string') parts.push(node);+ return parts.join(': ') || String(err);+}++/**+ * Is this a connection-level failure with no HTTP response — an HTTP/2 GOAWAY+ * (the remote retiring an idle pooled connection, which undici surfaces as a+ * request error) or the usual reset/hang-up family?+ *+ * These are artifacts of connection REUSE rather than of the request, so the+ * same request generally succeeds immediately on a fresh socket, which is what+ * makes them worth one replay via `fetchWithTimeout`'s `shouldRetry`.+ *+ * Deliberately narrow. It excludes timeouts (`AbortError`, `\btimeout\b`) that+ * broader classifiers like `ollamaManager`'s `isTransientPullError` include:+ * that one is retrying a multi-GB streamed download over a flaky link, where a+ * timeout really is worth another go, while a request-per-item probe loop that+ * retried timeouts would hand a merely-slow host double the traffic. Callers+ * needing the wider net should keep their own predicate over+ * `describeFetchError`.+ *+ * @param {unknown} err+ * @returns {boolean}+ */+export function isReplayableConnectionError(err) {+ return /GOAWAY|ECONNRESET|EPIPE|ETIMEDOUT|ECONNREFUSED|socket hang up|other side closed|UND_ERR_SOCKET/i+ .test(describeFetchError(err));+}diff --git a/server/lib/fetchWithTimeout.js b/server/lib/fetchWithTimeout.jsindex 42c332d819..5f2421efa5 100644--- a/server/lib/fetchWithTimeout.js+++ b/server/lib/fetchWithTimeout.js@@ -1,12 +1,50 @@/**- * Fetch wrapper with AbortController timeout.+ * Fetch wrapper with AbortController timeout, and an opt-in retry for+ * connection-level failures.+ *+ * The retry exists because undici reports a retired pooled connection (notably+ * an HTTP/2 GOAWAY) as a request-level rejection, so a perfectly good request+ * dies as a bare `TypeError: fetch failed`. The same request succeeds on a fresh+ * socket, which makes one replay the correct response — but only for the caller+ * that says so.+ *+ * It is OFF by default and per-call for two reasons. A blanket retry doubles+ * traffic against a genuinely-down host, and replaying a non-idempotent POST+ * (an OAuth token exchange burning a single-use refresh code, a peer sync push)+ * can do real damage. `shouldRetry` stays caller-supplied for a subtler reason:+ * only GOAWAY is *definitively* safe to replay — HTTP/2 §6.8 guarantees streams+ * above `lastStreamID` were never processed — whereas an ECONNRESET after the+ * request was fully sent may mean the server processed it and only the response+ * was lost. The caller knows which of those its endpoint can tolerate.** @param {string} url* @param {RequestInit} [options]* @param {number} [timeoutMs=15000] - Timeout in milliseconds+ * @param {object} [retry] - Opt-in retry policy; omit for the historical no-retry behavior+ * @param {number} [retry.retries=0] - Extra attempts after the first+ * @param {number} [retry.retryDelayMs=250] - Pause between attempts, so the replay+ * opens a new connection rather than racing the pool's teardown of the old one+ * @param {(err: unknown) => boolean} [retry.shouldRetry] - Required for a retry to+ * fire; decides whether THIS failure is safely replayable+ * @returns {Promise<Response>}+ */+export function fetchWithTimeout(url, options = {}, timeoutMs = 15000, retry = {}) {+ const { retries = 0, retryDelayMs = 250, shouldRetry } = retry;+ // Each attempt re-enters fetchOnce, so a replay builds a FRESH+ // AbortController and gets a full timeout budget rather than inheriting the+ // exhausted one.+ return fetchOnce(url, options, timeoutMs).catch((err) => {+ if (retries < 1 || typeof shouldRetry !== 'function' || !shouldRetry(err)) throw err;+ return new Promise((resolve) => setTimeout(resolve, retryDelayMs))+ .then(() => fetchWithTimeout(url, options, timeoutMs, { ...retry, retries: retries - 1 }));+ });+}++/**+ * One attempt: fetch with an AbortController timeout, honoring a caller signal.* @returns {Promise<Response>}*/-export async function fetchWithTimeout(url, options = {}, timeoutMs = 15000) {+async function fetchOnce(url, options = {}, timeoutMs = 15000) {const controller = new AbortController();const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;const timeoutId = hasTimeout ? setTimeout(() => controller.abort(), timeoutMs) : null;diff --git a/server/lib/index.js b/server/lib/index.jsindex 55d012229b..44e05b9128 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -316,10 +316,12 @@ export * from './apiRegistry.js';export * from './arrayUtils.js';export * from './asyncMutex.js';export * from './authGate.js';+export * from './concurrencyGate.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './errorHandler.js';export * from './extensionErrors.js';+export * from './fetchErrorChain.js';export * from './isoWeek.js';export * from './lwwTimestamp.js';export * from './mapWithConcurrency.js';diff --git a/server/services/backup.js b/server/services/backup.jsindex 0e6cd3aab9..0105f15f80 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -62,6 +62,7 @@ export const DEFAULT_EXCLUDES = [{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },+ { path: '/cache/', reason: 'Remote-API metadata caches (e.g. Hugging Face repo records) — regenerable on demand, and stale on restore anyway', overridable: false },// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per// run, byte-for-byte regenerable from the archived source video by the// deterministic postprocess (walkPostprocess.js). The source video, packageddiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 1d5ca71217..aebbfb0070 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -54,6 +54,7 @@ export const CATEGORIES = {// but installs that predate that move still carry the dir, and backup still excludes it.'browser-downloads': { label: 'Browser Downloads', description: 'Files the agent browser downloaded — re-downloadable, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'browser-profile': { label: 'Browser Profile', description: 'Chrome/Chromium browser data', archivable: false, deletable: true, purgeScope: 'category' },+ cache: { label: 'Remote API Cache', description: 'Cached metadata from remote APIs (Hugging Face repo records) — refetched on demand, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'calendar': { label: 'Calendar', description: 'Calendar sync data', archivable: true, deletable: false },'certs': { label: 'TLS Certificates', description: 'HTTPS certificate and private key — purging drops the install back to HTTP', archivable: false, deletable: false },'commission-feedback': { label: 'Commission Feedback', description: 'Reactions on creative commissions (file mirror of the Postgres store)', archivable: true, deletable: false },diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex ce759fbb72..75d7594560 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -1,12 +1,18 @@import { formatBytes as formatBytesRaw } from '../lib/fileUtils.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'+import { createConcurrencyGate } from '../lib/concurrencyGate.js'+import { createSingleFlight } from '../lib/singleFlight.js'+import { describeFetchError, isReplayableConnectionError } from '../lib/fetchErrorChain.js'+import { readCachedRepoModel, writeCachedRepoModel } from './huggingFaceRepoCache.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+// Pause before the single connection-blip retry (see hfFetch).+const HF_RETRY_DELAY_MS = 250// Upper bound on how long the curated-catalog endpoint waits for HF variant// enrichment. The curated catalog must stay usable offline (it was a pure local// list before enrichment), so when HF is slow/down we return the catalog as-is@@ -669,6 +675,34 @@ function hfHeaders() {return headers}+// 4 at a time, shared by BOTH entry points: a cold catalog load fires ~36+// `?blobs=true` probes and a keystroke fires up to 18 more, concurrently — a+// 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)+// 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()++// 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.+function hfFetch(url) {+ return hfGate.run(() => fetchWithTimeout(+ url,+ { headers: hfHeaders() },+ HF_TIMEOUT_MS,+ { retries: 1, retryDelayMs: HF_RETRY_DELAY_MS, shouldRetry: isReplayableConnectionError }+ // undici reports a connection-level failure as 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)}]`)+ }))+}+// `filter` is a Hugging Face library tag — 'gguf' for the GGUF query, 'mlx' for// the Apple-MLX query, or null/'' to relax the format filter (audio category and// the GGUF-signal fallback). Only one filter at a time; MLX runs as a separate@@ -683,7 +717,7 @@ async function fetchModels(search, limit, filter) {})if (filter) params.set('filter', filter)- const response = await fetchWithTimeout(`${HF_API_BASE}?${params.toString()}`, { headers: hfHeaders() }, HF_TIMEOUT_MS)+ 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)}` : ''}`)@@ -701,27 +735,47 @@ const REPO_MODEL_CACHE_MAX = 500const TRANSIENT_FETCH = Symbol('transient-fetch')// Fetch (and cache) the per-model record WITH per-file sizes. The search-// endpoint returns siblings without sizes; only `?blobs=true` carries them, and-// the box is debounced per keystroke, so cache by repo to avoid re-fetching.-// `null` = fetched-but-unavailable (gated / private / 404), cached (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 HF-// re-enriches on the next request instead of staying blank until restart.+// endpoint returns siblings without sizes; only `?blobs=true` carries them.+//+// Three tiers, cheapest first: an in-process Map, then the disk cache+// (huggingFaceRepoCache.js), then the Hub. The disk tier is what stops the+// curated catalog — a KNOWN, fixed list of ~36 repos — from re-asking the Hub+// 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.async function fetchRepoModel(repoId) {if (repoModelCache.has(repoId)) return repoModelCache.get(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 fetchWithTimeout(`${HF_API_BASE}/${safeRepoPath}?blobs=true`, { headers: hfHeaders() }, HF_TIMEOUT_MS)- .then((res) => (res.ok ? res.json() : null))- .catch(() => TRANSIENT_FETCH)- if (model === TRANSIENT_FETCH) return null // transient — return null but don't cache+ return repoModelFlight.run(repoId, async () => {+ const cached = await readCachedRepoModel(repoId)+ // `hit` is separate from the value because a cached `model` of null is a+ // real answer (gated/absent), not a miss.+ if (cached.hit) {+ rememberRepoModel(repoId, cached.model)+ return cached.model+ }+ // 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))+ .catch(() => TRANSIENT_FETCH)+ if (model === TRANSIENT_FETCH) return null // transient — return null but don't cache+ rememberRepoModel(repoId, model)+ await writeCachedRepoModel(repoId, model)+ return model+ })+}++function rememberRepoModel(repoId, model) {// Evict oldest entry when the cap is reached (insertion-order iteration).if (repoModelCache.size >= REPO_MODEL_CACHE_MAX) {repoModelCache.delete(repoModelCache.keys().next().value)}repoModelCache.set(repoId, model)- return model}// Total resident size of an audio repo's weight files — audio generators shipdiff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.jsindex 9c18efb4cc..11635852f5 100644--- a/server/services/huggingFaceCatalog.test.js+++ b/server/services/huggingFaceCatalog.test.js@@ -926,4 +926,112 @@ describe('huggingFaceCatalog', () => {expect(small.installed).toBe(true)})})++ // The Hub retires idle pooled HTTP/2 connections; undici surfaces the retirement+ // as a request-level `fetch failed` with a GOAWAY cause, which used to blank the+ // whole result set. It is a connection artifact, not a request failure.+ describe('hub politeness — transient retry and burst bounding', () => {+ const goaway = () => {+ const err = new TypeError('fetch failed')+ err.cause = new Error('HTTP/2: "GOAWAY" frame received with code 0')+ return err+ }++ it('retries a GOAWAY once and returns the results the retry fetched', async () => {+ const repo = 'goaway-pub/Retry-GGUF'+ let searchCalls = 0+ fetch.mockImplementation(async (url) => {+ const u = String(url)+ if (u.includes('blobs=true')) return response({ id: repo, siblings: [{ rfilename: 'R-Q4_K_M.gguf', size: 4_000_000_000 }] })+ searchCalls += 1+ if (searchCalls === 1) throw goaway()+ return response([{ modelId: repo, downloads: 10, tags: ['gguf'], siblings: [{ rfilename: 'R-Q4_K_M.gguf', size: 4_000_000_000 }] }])+ })++ const results = await searchHuggingFaceModels({ backend: 'lmstudio', query: 'retry' })++ expect(searchCalls).toBe(2)+ expect(results.some((r) => r.repository === repo)).toBe(true)+ })++ it('reports a repeated GOAWAY as a named condition, not a bare "fetch failed"', async () => {+ let calls = 0+ fetch.mockImplementation(async () => { calls += 1; throw goaway() })++ await expect(searchHuggingFaceModels({ backend: 'lmstudio', query: 'always-goaway' }))+ .rejects.toThrow(/Hugging Face is not responding/)+ expect(calls).toBe(2) // one retry, not an unbounded loop+ })++ it('does not retry a timeout — a slow hub must not get double the traffic', async () => {+ let calls = 0+ fetch.mockImplementation(async () => {+ calls += 1+ const err = new Error('The operation was aborted')+ err.name = 'AbortError'+ throw err+ })++ await expect(searchHuggingFaceModels({ backend: 'lmstudio', query: 'timeout-not-retried' }))+ .rejects.toThrow(/aborted/i)+ expect(calls).toBe(1)+ })++ it('caps simultaneous hub requests while enriching a full catalog', async () => {+ let inFlight = 0+ let peak = 0+ fetch.mockImplementation(async (url) => {+ inFlight += 1+ peak = Math.max(peak, inFlight)+ await new Promise((resolve) => setTimeout(resolve, 5))+ inFlight -= 1+ const repo = String(url).split('/api/models/')[1]?.split('?')[0] || 'x/y'+ return response({ id: repo, siblings: [{ rfilename: 'C-Q4_K_M.gguf', size: 4_000_000_000 }] })+ })++ // 30 distinct repos so none is served from the per-process repo cache — this+ // is the cold-page-load shape the gate exists for.+ const catalog = Array.from({ length: 30 }, (_, i) => ({+ id: `burst-pub/Burst-${i}-GGUF`, key: `burst-${i}`, name: `Burst ${i}`, category: 'chat', size: '2.0 GB'+ }))+ await enrichCatalogWithVariants(catalog, {+ backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [], timeoutMs: 0+ })++ // Two properties, both required. The upper bound is the cap itself; the+ // lower bound catches a gate that degraded to serial, which the cap+ // assertion alone would happily pass. Not `toBe(4)`: each probe now+ // awaits the disk cache before reaching the gate, so arrivals stagger and+ // the observed peak legitimately lands a slot or two below the cap. The+ // exact-cap guarantee is pinned in concurrencyGate.test.js instead.+ expect(peak).toBeLessThanOrEqual(4)+ expect(peak).toBeGreaterThan(1)+ // The cap must not cost coverage — every entry still enriched.+ 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 = 0+ fetch.mockImplementation(async (url) => {+ const u = String(url)+ if (u.includes('blobs=true')) {+ blobCalls += 1+ await new Promise((resolve) => setTimeout(resolve, 5))+ return response({ id: repo, siblings: [{ rfilename: 'S-Q4_K_M.gguf', size: 4_000_000_000 }] })+ }+ return response([])+ })++ const catalogs = Array.from({ length: 3 }, () => ([+ { id: repo, key: 'shared', name: 'Shared', category: 'chat', size: '2.0 GB' }+ ]))+ await Promise.all(catalogs.map((c) => enrichCatalogWithVariants(c, {+ backend: 'lmstudio', systemMemoryBytes: 128 * 1024 ** 3, installedIds: [], timeoutMs: 0+ })))++ expect(blobCalls).toBe(1)+ expect(catalogs.every((c) => c[0].format === 'gguf')).toBe(true)+ })+ })})diff --git a/server/services/huggingFaceRepoCache.js b/server/services/huggingFaceRepoCache.jsnew file mode 100644index 0000000000..0f9cafa7d3--- /dev/null+++ b/server/services/huggingFaceRepoCache.js@@ -0,0 +1,137 @@+// Disk-backed cache of Hugging Face per-repo metadata (`/api/models/<repo>?blobs=true`).+//+// The curated local-LLM catalog is a KNOWN, fixed list of ~36 repos. Enriching it+// needs each repo's per-file sizes and native context length — data the search+// listing omits — so before this cache every cold page load re-asked the Hub for+// all 36, and a server restart made every load cold again. That is both the burst+// that provokes the Hub's HTTP/2 GOAWAY and a standing cost paid for metadata that+// barely changes: a published GGUF repo's file sizes are immutable, and new quants+// appear on the order of weeks, not minutes.+//+// So the cache is deliberately long-lived (CACHE_TTL_MS) and survives restarts. It+// is `ephemeral-file` under docs/STORAGE.md — pure regenerable cache, losing it+// costs one refetch — so it lives in `data/cache/` and is excluded from backup.+//+// Records are stored WHOLE rather than projected down to the fields enrichment+// currently reads. A projection would be ~10x smaller (≈440B vs ≈5KB per repo),+// but it silently breaks the day someone reads a field the projection dropped —+// they'd get `undefined` from a cache hit and a correct value from a miss, which+// is the worst kind of bug to chase. At the 500-entry cap the whole file is ≈2.5MB.++import { join } from 'node:path'+import { PATHS, readJSONFileStrict, atomicWrite, ensureDir } from '../lib/fileUtils.js'++const CACHE_FILE = join(PATHS.data, 'cache', 'huggingface-repos.json')+// Bump when the envelope shape changes — a mismatch drops the file and refetches+// rather than trying to read an older layout.+const CACHE_SCHEMA_VERSION = 1+// 7 days. Long because the payload is near-immutable (published file sizes never+// change); bounded because a repo CAN gain a new quant, and a stale card would+// hide it indefinitely.+const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000+// Matches the in-memory cap so the two tiers can't disagree about what fits.+const CACHE_MAX_ENTRIES = 500+// Coalesce the write burst: enriching a catalog resolves ~36 probes within a+// second or two, and each one would otherwise rewrite the whole file.+const SAVE_DEBOUNCE_MS = 2_000++// repoId -> { fetchedAt, model }. `model: null` is a REAL cached answer (gated /+// private / 404), distinct from an absent key — same absent-vs-empty sentinel+// discipline the in-memory tier uses.+let entries = null // null = not loaded yet (distinct from loaded-and-empty)+let loading = null // in-flight load promise, so a burst of readers shares one file read+let saveTimer = null+let dirty = false++function isFresh(entry, now) {+ return Boolean(entry) && Number.isFinite(entry.fetchedAt) && (now - entry.fetchedAt) < CACHE_TTL_MS+}++// Load the cache file once per process. A missing file is an empty cache; an+// unreadable or wrong-version one is ALSO an empty cache — this is regenerable+// data, so refetching is always a safe recovery and never costs the user+// anything durable.+// Memoized on the PROMISE, not the result: enrichment fires ~36 probes at once+// and they all reach this before the first read resolves, so keying on the+// settled Map would let every one of them re-read the file.+async function load() {+ if (!loading) loading = readEntries()+ return loading+}++async function readEntries() {+ const { ok, value } = await readJSONFileStrict(CACHE_FILE, null)+ entries = new Map()+ if (!ok || value?.schemaVersion !== CACHE_SCHEMA_VERSION || !value?.entries) return entries+ const now = Date.now()+ for (const [repoId, entry] of Object.entries(value.entries)) {+ if (isFresh(entry, now)) entries.set(repoId, entry)+ }+ return entries+}++async function flush() {+ saveTimer = null+ if (!dirty || !entries) return+ dirty = false+ const now = Date.now()+ // Drop stale entries on the way out, so the file self-prunes instead of+ // growing forever with repos the user searched once a year ago.+ const fresh = [...entries.entries()].filter(([, entry]) => isFresh(entry, now))+ // Newest-first, then cap — an overflowing cache should evict the entries least+ // 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)+ await ensureDir(join(PATHS.data, 'cache'))+ await atomicWrite(CACHE_FILE, {+ schemaVersion: CACHE_SCHEMA_VERSION,+ entries: Object.fromEntries(capped)+ })+}++function scheduleSave() {+ dirty = true+ if (saveTimer) return+ // Outside the request lifecycle — a throw here would be unhandled, so the+ // failure is logged and swallowed (per the root CLAUDE.md timer-callback rule).+ // A cache that fails to persist still works in memory; the next load refetches.+ saveTimer = setTimeout(() => {+ flush().catch((err) => console.error(`❌ Failed to persist Hugging Face repo cache: ${err.message}`))+ }, SAVE_DEBOUNCE_MS)+ saveTimer.unref?.()+}++/**+ * Read a cached repo record.+ * @returns {Promise<{ hit: boolean, model: object|null }>} `hit: false` on a miss+ * or an expired entry. On a hit, `model` may legitimately be `null` (the repo is+ * gated/private/absent) — which is why the hit flag is separate from the value.+ */+export async function readCachedRepoModel(repoId) {+ const store = await load()+ const entry = store.get(repoId)+ if (!isFresh(entry, Date.now())) return { hit: false, model: null }+ return { hit: true, model: entry.model }+}++/** Record a fetched repo record (`null` = fetched-but-unavailable). */+export async function writeCachedRepoModel(repoId, model) {+ const store = await load()+ store.set(repoId, { fetchedAt: Date.now(), model })+ scheduleSave()+}++/** Test hook — drop in-memory state so a suite starts from a known cache. */+export function __resetRepoCache() {+ entries = null+ loading = null+ dirty = false+ if (saveTimer) clearTimeout(saveTimer)+ saveTimer = null+}++/** Test hook — force the pending debounced write to complete now. */+export async function __flushRepoCache() {+ if (saveTimer) clearTimeout(saveTimer)+ await flush()+}diff --git a/server/services/huggingFaceRepoCache.test.js b/server/services/huggingFaceRepoCache.test.jsnew file mode 100644index 0000000000..01c9b2e10b--- /dev/null+++ b/server/services/huggingFaceRepoCache.test.js@@ -0,0 +1,98 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, rm, readFile, mkdir, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// The cache resolves its file from PATHS.data at import time of each call, so+// point PATHS at a temp dir before importing the module under test.+let tempRoot;++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ get PATHS() {+ return { ...actual.PATHS, data: tempRoot };+ }+ };+});++const cacheFile = () => join(tempRoot, 'cache', 'huggingface-repos.json');++let cache;++describe('huggingFaceRepoCache', () => {+ beforeEach(async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'portos-hf-cache-'));+ vi.resetModules();+ cache = await import('./huggingFaceRepoCache.js');+ cache.__resetRepoCache();+ });++ afterEach(async () => {+ cache.__resetRepoCache();+ await rm(tempRoot, { recursive: true, force: true });+ });++ it('reports a miss for an unknown repo', async () => {+ expect(await cache.readCachedRepoModel('nobody/Nothing')).toEqual({ hit: false, model: null });+ });++ it('round-trips a record through disk so a restart does not refetch', async () => {+ const model = { id: 'pub/Repo-GGUF', siblings: [{ rfilename: 'a-Q4_K_M.gguf', size: 42 }] };+ await cache.writeCachedRepoModel('pub/Repo-GGUF', model);+ await cache.__flushRepoCache();++ // Fresh module instance = a fresh process, reading only what is on disk.+ vi.resetModules();+ const reloaded = await import('./huggingFaceRepoCache.js');+ expect(await reloaded.readCachedRepoModel('pub/Repo-GGUF')).toEqual({ hit: true, model });+ });++ // The whole point of the `hit` flag: a gated/404 repo caches as `null`, and a+ // caller must not confuse that real answer with "never looked".+ it('distinguishes a cached null (gated/absent repo) from a miss', async () => {+ await cache.writeCachedRepoModel('gated/Repo', null);+ await cache.__flushRepoCache();+ expect(await cache.readCachedRepoModel('gated/Repo')).toEqual({ hit: true, model: null });+ expect(await cache.readCachedRepoModel('other/Repo')).toEqual({ hit: false, model: null });+ });++ it('treats an entry past the TTL as a miss and prunes it on the next save', async () => {+ const stale = Date.now() - (8 * 24 * 60 * 60 * 1000); // 8 days — TTL is 7+ await mkdir(join(tempRoot, 'cache'), { recursive: true });+ await writeFile(cacheFile(), JSON.stringify({+ schemaVersion: 1,+ entries: {+ 'old/Repo': { fetchedAt: stale, model: { id: 'old/Repo' } },+ 'new/Repo': { fetchedAt: Date.now(), model: { id: 'new/Repo' } }+ }+ }));++ expect((await cache.readCachedRepoModel('old/Repo')).hit).toBe(false);+ expect((await cache.readCachedRepoModel('new/Repo')).hit).toBe(true);++ await cache.writeCachedRepoModel('third/Repo', { id: 'third/Repo' });+ await cache.__flushRepoCache();+ const onDisk = JSON.parse(await readFile(cacheFile(), 'utf8'));+ expect(Object.keys(onDisk.entries).sort()).toEqual(['new/Repo', 'third/Repo']);+ });++ it('ignores a cache file written by a different schema version', async () => {+ await mkdir(join(tempRoot, 'cache'), { recursive: true });+ await writeFile(cacheFile(), JSON.stringify({+ schemaVersion: 999,+ entries: { 'pub/Repo': { fetchedAt: Date.now(), model: { id: 'pub/Repo' } } }+ }));+ expect((await cache.readCachedRepoModel('pub/Repo')).hit).toBe(false);+ });++ // Regenerable data: a corrupt file must degrade to an empty cache and a+ // refetch, never throw and take the catalog endpoint down with it.+ it('treats a corrupt cache file as empty rather than throwing', async () => {+ await mkdir(join(tempRoot, 'cache'), { recursive: true });+ await writeFile(cacheFile(), '{ this is not json');+ expect((await cache.readCachedRepoModel('pub/Repo')).hit).toBe(false);+ await expect(cache.writeCachedRepoModel('pub/Repo', { id: 'pub/Repo' })).resolves.not.toThrow();+ });+});diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 37fcd5f34e..fd3bd41878 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -21,6 +21,7 @@ import { createHash } from 'crypto'import { execFile, spawn } from '../lib/childProcess.js';import { promisify } from 'util'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'+import { describeFetchError } from '../lib/fetchErrorChain.js'import { readJSONFile, sha256File, safeJSONParse, ensureDir, atomicWrite, sleep } from '../lib/fileUtils.js'import {parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile,@@ -809,32 +810,6 @@ async function attemptOllamaPull(modelId, onProgress) {return lastError ? { success: false, error: lastError } : { success: true }}-/**- * Flatten a thrown fetch error into a single descriptive string, walking the- * `cause` chain. Node/undici reports network failures as `TypeError: fetch- * failed` with the real reason (ECONNRESET, ETIMEDOUT, ...) tucked into- * `err.cause` (and sometimes nested deeper). Without this, the transient- * classifier only sees "fetch failed" and misclassifies retryable failures as- * fatal. Includes each level's `.code` so `isTransientPullError()` can match.- * @param {unknown} err- * @returns {string}- */-function describeFetchError(err) {- const parts = []- let node = err- const seen = new Set()- // Bound the walk in case of a self-referential cause chain.- for (let depth = 0; node && typeof node === 'object' && depth < 5; depth++) {- if (seen.has(node)) break- seen.add(node)- if (node.code) parts.push(String(node.code))- if (node.message) parts.push(String(node.message))- node = node.cause- }- if (typeof node === 'string') parts.push(node)- return parts.join(': ') || String(err)-}-/*** Classify a pull/stream error string as a transient network failure worth* retrying (Ollama↔registry EOF, connection reset, undici "terminated", etc.).diff --git a/server/services/ollamaRegistryCatalog.js b/server/services/ollamaRegistryCatalog.jsindex db3b38a662..e692af294a 100644--- a/server/services/ollamaRegistryCatalog.js+++ b/server/services/ollamaRegistryCatalog.js@@ -22,9 +22,32 @@import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'+import { createConcurrencyGate } from '../lib/concurrencyGate.js'+import { createSingleFlight } from '../lib/singleFlight.js'+import { isReplayableConnectionError } from '../lib/fetchErrorChain.js'const REGISTRY_BASE = 'https://registry.ollama.ai/v2'const REGISTRY_TIMEOUT_MS = 12_000+// Per-process cap on simultaneous registry requests, so a cold catalog load+// (~31 bare Ollama entries, each a tags call plus a manifest call per quant)+// arrives as a trickle rather than a thundering herd. See concurrencyGate for+// why a shared gate rather than a per-entry cap.+//+// 16, not the 4 the Hugging Face path uses: this fan-out is an order of+// magnitude larger (~31 × (1 + quants) vs ~36 flat), and the whole enrich must+// still land inside huggingFaceCatalog's 5s CATALOG_ENRICH_TIMEOUT_MS or the+// cards render without their quant pickers. The payloads are also far smaller+// (OCI manifest JSON, not full model records).+const registryGate = createConcurrencyGate(16)+// Coalesce concurrent identical lookups. Both caches below are written only when+// the response resolves, so without this every caller that arrives during a+// cold fetch misses and queues its own duplicate behind the gate — and with a+// gate in front, duplicates cost queue depth rather than just a spare socket.+const registryFlight = createSingleFlight()+// Replay a dropped pooled connection once. Both calls below are GETs, so a+// replay is safe; without this a GOAWAY (or reset) collapses to TRANSIENT_FETCH+// and the card silently renders with no quant picker and no size.+const REGISTRY_RETRY = { retries: 1, retryDelayMs: 250, shouldRetry: isReplayableConnectionError }// 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'@@ -151,31 +174,37 @@ function preferTag(candidate, current) {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(resolveRegistryBody)- .catch(() => TRANSIENT_FETCH)- if (result === TRANSIENT_FETCH) return null // transient (throw / 5xx / 429 / unparseable 200) — don't cache- const tags = Array.isArray(result?.tags) ? result.tags : null- cacheSet(tagsCache, repoPath, tags)- return tags+ return registryFlight.run(`tags:${repoPath}`, async () => {+ // 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 registryGate+ .run(() => fetchWithTimeout(`${REGISTRY_BASE}/${safePath}/tags/list`, { headers: { Accept: 'application/json' } }, timeoutMs, REGISTRY_RETRY))+ .then(resolveRegistryBody)+ .catch(() => TRANSIENT_FETCH)+ if (result === TRANSIENT_FETCH) return null // transient (throw / 5xx / 429 / unparseable 200) — 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)- // Same transient-vs-cacheable distinction as fetchTags (see resolveRegistryBody).- const result = await fetchWithTimeout(`${REGISTRY_BASE}/${safePath}/manifests/${safeTag}`, { headers: { Accept: MANIFEST_ACCEPT } }, timeoutMs)- .then(resolveRegistryBody)- .catch(() => TRANSIENT_FETCH)- if (result === TRANSIENT_FETCH) return null // transient (throw / 5xx / 429 / unparseable 200) — don't cache- const bytes = sumModelLayerBytes(result) // result is null (permanent non-OK) or the manifest object- cacheSet(manifestCache, key, bytes)- return bytes+ return registryFlight.run(`manifest:${key}`, async () => {+ const safePath = repoPath.split('/').map(encodeURIComponent).join('/')+ const safeTag = encodeURIComponent(tag)+ // Same transient-vs-cacheable distinction as fetchTags (see resolveRegistryBody).+ const result = await registryGate+ .run(() => fetchWithTimeout(`${REGISTRY_BASE}/${safePath}/manifests/${safeTag}`, { headers: { Accept: MANIFEST_ACCEPT } }, timeoutMs, REGISTRY_RETRY))+ .then(resolveRegistryBody)+ .catch(() => TRANSIENT_FETCH)+ if (result === TRANSIENT_FETCH) return null // transient (throw / 5xx / 429 / unparseable 200) — don't cache+ const bytes = sumModelLayerBytes(result) // result is null (permanent non-OK) or the manifest object+ cacheSet(manifestCache, key, bytes)+ return bytes+ })}// Resolve the per-quant install variants for a bare Ollama registry model.