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
promote the HuggingFace download stack out of lib
[._.]/ Adam Eivyadaee119123c
diff --git a/client/src/components/imageGen/HfTokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsxindex 9401c7576d..d4e35e00e2 100644--- a/client/src/components/imageGen/HfTokenBanner.jsx+++ b/client/src/components/imageGen/HfTokenBanner.jsx@@ -17,7 +17,7 @@ import apiCore from '../../services/apiCore';/*** Where a resolved token came from, phrased for the user — keyed by the `source`- * `server/lib/hfToken.js` reports. Shared so every gated surface names the same+ * `server/services/hfToken.js` reports. Shared so every gated surface names the same* command: three separate copies had drifted, and one still told users to run the* deprecated `huggingface-cli login` while its neighbor said `hf auth login`.*/diff --git a/client/src/hooks/useHfTokenStatus.js b/client/src/hooks/useHfTokenStatus.jsindex c4a1114410..527e1c8b1d 100644--- a/client/src/hooks/useHfTokenStatus.js+++ b/client/src/hooks/useHfTokenStatus.js@@ -1,6 +1,6 @@/*** Read the CENTRAL HuggingFace token status (`GET /image-gen/setup/hf-token-status`,- * backed by `server/lib/hfToken.js`: stored token → env vars → `hf auth login` file).+ * backed by `server/services/hfToken.js`: stored token → env vars → `hf auth login` file).** Every gated-model surface needs the same three-state answer — token present / not* present / not yet known — and each one had grown its own copy with its own failurediff --git a/server/lib/README.md b/server/lib/README.mdindex 20060bfaae..84f6248c9e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -174,10 +174,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. || `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. || `ansiStrip.js` | Streaming ANSI / control-byte stripper. |-| `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. || `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. || `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it, and `findCachedRepoFiles(repoId,filenames,{revision?})` is its all-or-nothing plural form (paths in request order, or `null` if ANY is missing — a caller needing several pinned files, e.g. the shards of one checkpoint, can do nothing useful with a partial set); `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |-| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. `parseHfDownloadLine(line)` is the wire decoder (`STAGE:download` / `STAGE:bytes` / `STAGE:verify` / `STAGE:complete` / `USER_ERROR`) so a single-file multi-GB pull reports byte progress instead of sitting at 100% for the whole transfer. || `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. || `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. || `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)`, `onClientDisconnect(req,res,cb)` — shared SSE driver for model downloads. **Use `onClientDisconnect`, never `req.on('close')`**: on a POST whose body `express.json()` already consumed, `req` is complete at handler entry and emits `close` immediately, which reads as an instant disconnect and cancels work that never started. Required targets may name an immutable `revision` and exact `only` files, fallback chains are first-success, and the cross-route in-flight Map deduplicates pulls. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 77e54fd6d4..c08d91f83f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -122,11 +122,9 @@ export * from './contextBudget.js';export * from './cursor.js';export * from './grok.js';export * from './grokVideoClip.js';-export * from './hfToken.js';export * from './heavyJobClaim.js';export * from './hfErrors.js';export * from './hfCache.js';-export * from './hfDownload.js';export * from './icLoraWeights.js';export * from './sseDownload.js';export * from './sseHeaders.js';diff --git a/server/lib/layering.test.js b/server/lib/layering.test.jsindex 3ece89d9ef..24a99928a9 100644--- a/server/lib/layering.test.js+++ b/server/lib/layering.test.js@@ -28,8 +28,6 @@ const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set(['assetMounts.js','createSettingsGatedSyncScheduler.js','creativeDirectorPrompts.js',- 'hfDownload.js',- 'hfToken.js','promptRunner.js','spriteValidation.js','stageRunner.js',diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex 4d40f50e1d..908df02cb1 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -1,17 +1,13 @@-// Shared SSE driver for HF-repo pre-download endpoints. Image gen and video-// gen both expose `GET /…/models/:id/download` (and video also a separate-// `/text-encoder/download`); without this helper each route open-codes the-// same `writeHead → send → cache-check → in-flight check → spawn → cleanup`-// flow. A single in-flight Map keyed by repo also dedupes across routes:-// FLUX-family repos referenced by both image and video gen would otherwise-// spawn two concurrent children.+// Pure SSE response plumbing, shared by every streaming route: open a stream+// with write-safe helpers, and notice when the client hangs up.+//+// The HF-repo download driver that used to live here moved to+// `services/hfDownloadStream.js` — it spawns a child process and reads+// settings, so it belongs above this layer (issue #4901). These two helpers do+// not, and 11 routes use them with no HF involvement at all.-import { findCachedRepoFile, inspectModelCache } from './hfCache.js';-import { downloadHfRepo } from './hfDownload.js';import { SSE_HEADERS } from './sseHeaders.js';-const inFlight = new Map(); // repo -> { promise, kill }-/*** Open an SSE response and return write-safe helpers. Canonical replacement* for the per-route `writeHead → send → safeEnd` boilerplate: `send` JSON-@@ -56,245 +52,3 @@ export function onClientDisconnect(_req, res, onDisconnect) {onDisconnect();});}--export async function startHfDownloadStream({ req, res, repo, revision = null, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {- // Three input shapes, two semantics:- // - `repo` (single string) / `repos` (ordered array) — ALL must succeed. Used- // when a model has auxiliary repos that must be present alongside the main- // weights (e.g. HiDream's separate Llama-3.1 text encoder). Sequential;- // short-circuits on any single-repo error.- // - `fallbacks` (ordered array of `{ repo, only? }`) — FIRST SUCCESS wins, and- // a failure advances to the next entry. Used when the same file lives in- // several repos with different access (Ingredients: gated first-party repo,- // then an un-gated mirror), so a user with no HF token still succeeds.- //- // `only` (array of exact repo-relative filenames, per entry) forwards to the- // helper's single-file mode — MANDATORY for aggregate repos where a snapshot is- // catastrophic (the ~708 GB DeepBeepMeep/LTX-2 mirror).- //- // `ignore` (array of fnmatch globs, per entry) is the inverse: still snapshot- // the repo, but drop paths the runtime never loads — extra checkpoint formats- // or a bundled sibling model. Ignored when `only` is set for the same entry.- //- // `cachedFile` is the "is it already here?" predicate for a single-file pull:- // `inspectModelCache` reports the whole repo cached as soon as ANY weight is- // resident, which for an aggregate mirror is true after the first unrelated- // file — so the generic already-cached short-circuit would skip a weight the- // user doesn't have. Callers pass an async `() => boolean` that checks the one- // file instead.- const normalizeOnly = (v) => (Array.isArray(v) ? v.filter((f) => typeof f === 'string' && f.length > 0) : []);- const normalizeRevision = (v) => (typeof v === 'string' && v.length > 0 ? v : null);- const normalizeTarget = (target) => {- if (typeof target === 'string' && target.length > 0) return { repo: target, only: [], ignore: [], revision: null };- if (!target || typeof target.repo !== 'string' || target.repo.length === 0) return null;- return {- repo: target.repo,- only: normalizeOnly(target.only),- ignore: normalizeOnly(target.ignore),- revision: normalizeRevision(target.revision),- };- };- const firstSuccessWins = Array.isArray(fallbacks);- const targetInputs = firstSuccessWins- ? fallbacks- : (Array.isArray(repos) ? repos : [revision ? { repo, revision } : repo]);- const targets = targetInputs- .map(normalizeTarget)- .filter(Boolean);- const { send, safeEnd } = openSseStream(res);-- if (targets.length === 0) {- send({ type: 'error', message: 'No repo specified for download.' });- return safeEnd();- }-- // Disconnect bookkeeping wired BEFORE the cache-inspection await. The- // inspection can take double-digit ms on a cold cache; without this the- // client closing mid-await would land after spawn with no kill path.- let currentHandle = null;- let aborted = false;- onClientDisconnect(req, res, () => {- aborted = true;- // Only a live handle means a download was mid-flight, so this keeps the- // cancel line out of the log when the client simply navigated away between- // repos.- if (currentHandle) {- console.log(`🛑 HuggingFace download cancelled (client disconnect)`);- currentHandle.kill();- }- safeEnd();- });-- let downloadedAny = false;- let totalSize = 0;- // Only meaningful in first-success-wins mode: which repo actually delivered,- // and the per-attempt failures to report if none did.- let succeededRepo = null;- const attemptErrors = [];- for (let i = 0; i < targets.length; i += 1) {- const { repo: r, only: onlyFiles, ignore: ignorePatterns, revision } = targets[i];- const isLastTarget = i === targets.length - 1;- if (aborted) return;- // For a single-file pull the repo-wide cache verdict is both the wrong- // question AND too expensive to ask: `inspectModelCache` recursively stats- // every weight in the snapshot, and an aggregate mirror reports `cached` off- // any unrelated resident file — so it would skip the file the user actually- // asked for after walking hundreds of GB to get there. Skip the walk entirely- // and defer to the caller's per-file predicate.- const singleFile = onlyFiles.length > 0;- const existing = singleFile- ? { cached: false, sizeBytes: 0 }- : await inspectModelCache(r, { revision });- if (aborted) return;- const alreadyHave = singleFile- ? (typeof cachedFile === 'function'- ? await cachedFile({ repo: r, only: onlyFiles, revision })- : (await Promise.all(onlyFiles.map((file) => findCachedRepoFile(r, file, { revision })))).every(Boolean))- : existing.cached;- if (aborted) return;- // `force` is set by a repair-initiated re-download: repairModelCache()- // deleted the corrupt file(s), but for a multi-shard repo the remaining- // shards still make inspectModelCache() report `cached` — so skipping here- // would leave the just-deleted shard missing and never re-fetched. Forcing- // re-runs the HF fetch, which is a cheap no-op for files already present- // (etag match) and pulls only what's gone.- if (alreadyHave && !force) {- // A single-file pull has no repo-wide total to report (we deliberately- // never computed one) — and claiming the aggregate mirror's resident bytes- // would be a wildly wrong number on the badge anyway. Report 0 and let the- // badge fall back to the registry's size estimate.- if (singleFile) {- console.log(`📦 HuggingFace weight already cached: ${onlyFiles.join(', ')} (${r})`);- send({ type: 'log', message: `${onlyFiles.join(', ')} already cached.`, repo: r, sizeBytes: 0 });- } else {- totalSize += existing.sizeBytes || 0;- console.log(`📦 HuggingFace repo already cached: ${r} (${existing.sizeBytes} bytes)`);- send({ type: 'log', message: `${r} already cached (${existing.sizeBytes} bytes).`, repo: r, sizeBytes: existing.sizeBytes });- }- // In first-success-wins mode the file being present is the whole goal —- // don't fall through and try the mirror for something we already have.- if (firstSuccessWins) { succeededRepo = r; break; }- continue;- }- // Dedupe key includes the filenames: an aggregate repo hosts many unrelated- // weights, so two single-file pulls of DIFFERENT files from the same repo are- // not duplicates and must not block each other.- const revisionKey = revision ? `@${revision}` : '';- const flightKey = singleFile ? `${r}${revisionKey}::${onlyFiles.join(',')}` : `${r}${revisionKey}`;- if (inFlight.has(flightKey)) {- console.log(`⏭️ HuggingFace download already running for ${flightKey} — refusing duplicate`);- send({ type: 'error', message: `Another download for ${r} is already running.`, kind: 'already_running', repo: r });- return safeEnd();- }- // Server-side visibility for a pull that used to surface only on the SSE- // stream (the browser) — a headless/PM2 log had no record the multi-GB- // fetch ever ran. Log the start, each file as it streams, and the outcome.- console.log(`⬇️ Downloading HuggingFace repo: ${r}${singleFile ? ` (${onlyFiles.length} file(s) only)` : ''}${force ? ' (forced re-fetch)' : ''}`);- const handle = downloadHfRepo({- repo: r,- revision,- only: singleFile ? onlyFiles : null,- ignore: ignorePatterns,- pythonPath,- onEvent: (ev) => {- // File-start frames only. Byte ticks arrive several times a second on- // a large single-file pull and would drown the PM2 log.- if (ev.type === 'progress' && ev.file && ev.downloaded == null && ev.stage !== 'verify') {- console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);- }- // A failure that we're about to retry against the next candidate isn't a- // user-facing error — downgrade it to a log so the UI doesn't flash a red- // "gated repo" banner for something the mirror then delivers fine.- if (firstSuccessWins && ev.type === 'error') {- send({- type: 'log',- message: `${r}: ${ev.message}${isLastTarget ? '' : ' — trying the next source.'}`,- repo: r,- });- return;- }- send({ ...ev, repo: r });- },- });- currentHandle = handle;- inFlight.set(flightKey, handle);- let result;- try {- result = await handle.promise;- if (result?.ok) {- console.log(`✅ HuggingFace download complete: ${r} (${result.sizeBytes || 0} bytes)`);- } else if (result?.errorKind !== 'cancelled') {- console.error(`❌ HuggingFace download failed: ${r} — ${result?.errorMessage || 'unknown error'}`);- }- } finally {- inFlight.delete(flightKey);- currentHandle = null;- }- if (!firstSuccessWins) {- // ALL must succeed here — unlike the fallback-chain branch below, there- // is no next candidate to fall through to. Silently treating a failed- // repo as done (the prior bug) let the loop reach `complete` even- // though one of the required repos never downloaded.- if (!result?.ok) {- if (result?.errorKind === 'cancelled') return safeEnd();- send({- type: 'error',- kind: result?.errorKind || 'download_failed',- message: `${r}: ${result?.errorMessage || 'unknown error'}`,- repo: r,- });- return safeEnd();- }- downloadedAny = true;- totalSize += result.sizeBytes || 0;- continue;- }- if (result?.ok) {- downloadedAny = true;- succeededRepo = r;- totalSize += result.sizeBytes || 0;- break;- }- // A user cancel must not silently roll onto the next candidate.- if (result?.errorKind === 'cancelled') return safeEnd();- attemptErrors.push(`${r}: ${result?.errorMessage || 'unknown error'}`);- }-- if (!aborted) {- if (firstSuccessWins) {- if (!succeededRepo) {- send({- type: 'error',- kind: 'all_sources_failed',- message: `Every source failed — ${attemptErrors.join('; ')}`,- });- return safeEnd();- }- send({- type: 'complete',- message: downloadedAny- ? `${succeededRepo} downloaded.`- : (alreadyDownloadedMessage || `${succeededRepo} already downloaded.`),- repos: [succeededRepo],- sizeBytes: totalSize,- });- return safeEnd();- }- const names = targets.map((t) => t.repo);- let message;- if (names.length === 1) {- // Preserve legacy single-repo `complete` message semantics: if it was- // already cached on entry, surface the caller's `alreadyDownloadedMessage`- // (or the default already-downloaded line).- message = !downloadedAny- ? (alreadyDownloadedMessage || `${names[0]} already downloaded.`)- : `${names[0]} downloaded.`;- } else {- message = downloadedAny- ? `Downloaded ${names.length} repos: ${names.join(', ')}`- : `All ${names.length} repos already cached: ${names.join(', ')}`;- }- send({ type: 'complete', message, repos: names, sizeBytes: totalSize });- }- safeEnd();-}diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 4b49020df6..370b809871 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -24,7 +24,7 @@ import setupRouter from './imageGenSetup.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getImageModels, requiredReposForModel } from '../lib/mediaModels.js';import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';-import { startHfDownloadStream } from '../lib/sseDownload.js';+import { startHfDownloadStream } from '../services/hfDownloadStream.js';import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';import { prepareGenerateParams, resolveLocalImageModel } from '../services/imageGen/prepareParams.js';import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.jsindex c7d8666822..03a27e7eb4 100644--- a/server/routes/imageGenSetup.js+++ b/server/routes/imageGenSetup.js@@ -16,7 +16,7 @@ import { join } from 'node:path';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { getSettings, updateSettingsWith } from '../services/settings.js';-import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';+import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../services/hfToken.js';import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import { createInstallLogger } from '../lib/installLogger.js';import {diff --git a/server/routes/imageTo3d.genericDispatch.test.js b/server/routes/imageTo3d.genericDispatch.test.jsindex fa87d94a64..3ba637e006 100644--- a/server/routes/imageTo3d.genericDispatch.test.js+++ b/server/routes/imageTo3d.genericDispatch.test.js@@ -45,7 +45,7 @@ vi.mock('../services/imageTo3d/adapters.js', () => ({} : null)),}));-vi.mock('../lib/hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));+vi.mock('../services/hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));vi.mock('../services/imageTo3d/models.js', () => ({listModels: vi.fn(),@@ -56,7 +56,7 @@ vi.mock('../services/imageTo3d/models.js', () => ({getModelAsset: vi.fn(),}));-import { hfChildEnv } from '../lib/hfToken.js';+import { hfChildEnv } from '../services/hfToken.js';import routes from './imageTo3d.js';const makeApp = () => {diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex 86c08d41c3..7c2b77fb32 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -66,7 +66,7 @@ vi.mock('../services/imageTo3d/trellis2.js', async (importOriginal) => ({// The install route resolves the central HF child env (#3032).// Mock it so the suite never reads the host's real settings.json or// ~/.cache/huggingface/token, and so the resolution-failure branch is drivable.-vi.mock('../lib/hfToken.js', () => ({+vi.mock('../services/hfToken.js', () => ({hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' })),}));@@ -83,7 +83,7 @@ vi.mock('../services/imageTo3d/models.js', () => ({import * as targets from '../services/imageTo3d/targets.js';import * as trellis2 from '../services/imageTo3d/trellis2.js';import * as models from '../services/imageTo3d/models.js';-import { hfChildEnv } from '../lib/hfToken.js';+import { hfChildEnv } from '../services/hfToken.js';import routes from './imageTo3d.js';const makeApp = () => {diff --git a/server/routes/music.js b/server/routes/music.jsindex a14689f586..cf07c638c3 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -36,7 +36,8 @@ import {import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';import { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';import { describeMusic, writeLyrics } from '../services/musicDesigner.js';-import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';+import { startHfDownloadStream } from '../services/hfDownloadStream.js';+import { openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import { inspectModelCache } from '../lib/hfCache.js';import { getCudaCapability } from '../lib/cudaCapability.js';diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex d8d5a766d8..1d827856cb 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -137,9 +137,11 @@ const sse = vi.hoisted(() => ({}),}));vi.mock('../lib/sseDownload.js', () => ({- startHfDownloadStream: (args) => sse.run(args),openSseStream: (res) => sse.open(res),}));+vi.mock('../services/hfDownloadStream.js', () => ({+ startHfDownloadStream: (args) => sse.run(args),+}));// Register-after-download gates on whether the repo landed in the cache.const cache = vi.hoisted(() => ({ cached: true, byRevision: null, calls: [] }));diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.jsindex 3a67859dd4..4b1edaed27 100644--- a/server/routes/videoGen.integrity.test.js+++ b/server/routes/videoGen.integrity.test.js@@ -34,7 +34,7 @@ vi.mock('../lib/hfCache.js', async (importOriginal) => ({}));const sseDownload = vi.hoisted(() => ({ start: vi.fn() }));-vi.mock('../lib/sseDownload.js', async (importOriginal) => ({+vi.mock('../services/hfDownloadStream.js', async (importOriginal) => ({...(await importOriginal()),startHfDownloadStream: sseDownload.start,}));diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 9dc49a2255..4eabf1281f 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -58,7 +58,8 @@ import {verifyCachedRepoFiles, repairCachedRepoFiles, summarizeVerify, aggregateVerifies,isSafeHfRepoRelativePath,} from '../lib/hfCache.js';-import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';+import { startHfDownloadStream } from '../services/hfDownloadStream.js';+import { openSseStream } from '../lib/sseDownload.js';import { saveUploadedGalleryVideo } from '../services/videoUpload.js';import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 4693079bc1..e41a61f39e 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -141,7 +141,6 @@ const sseDownload = vi.hoisted(() => ({}),}));vi.mock('../lib/sseDownload.js', () => ({- startHfDownloadStream: sseDownload.start,openSseStream: (res) => {res.writeHead(200, { 'Content-Type': 'text/event-stream' });return {@@ -150,6 +149,9 @@ vi.mock('../lib/sseDownload.js', () => ({};},}));+vi.mock('../services/hfDownloadStream.js', () => ({+ startHfDownloadStream: sseDownload.start,+}));// Render submissions go through the mediaJobQueue. Mock its surface so the// route tests stay synchronous and don't kick off the worker loop.diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.jsindex 2cdd33b27d..f37cc3e502 100644--- a/server/services/audioMidiTranscription.js+++ b/server/services/audioMidiTranscription.js@@ -31,7 +31,7 @@ import { tmpdir } from 'os';import { PATHS, shortId, importFileToDir } from '../lib/fileUtils.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { killWithEscalation } from '../lib/killWithEscalation.js';-import { hfChildEnv } from '../lib/hfToken.js';+import { hfChildEnv } from './hfToken.js';import { isGatedRepoError, extractGatedRepo } from '../lib/hfErrors.js';import { resolveMuscriptorPython, isMuscriptorRuntimeReady, MUSCRIPTOR_VENV_DEFAULT } from '../lib/pythonSetup.js';import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';diff --git a/server/lib/hfDownload.js b/server/services/hfDownload.jssimilarity index 97%rename from server/lib/hfDownload.jsrename to server/services/hfDownload.jsindex d13bee91d0..c68d90f924 100644--- a/server/lib/hfDownload.js+++ b/server/services/hfDownload.js@@ -23,16 +23,16 @@// parseHfDownloadLine is the single decoder — downloadHfRepo and the tests// share it so a wire-shape change cannot drift between them.-import { spawn } from './childProcess.js';+import { spawn } from '../lib/childProcess.js';import { join } from 'node:path';import {resolveFlux2Python, isFlux2VenvHealthy, HF_HUB_PYTHON_RESOLVERS,-} from './pythonSetup.js';-import { PATHS } from './fileUtils.js';+} from '../lib/pythonSetup.js';+import { PATHS } from '../lib/fileUtils.js';import { getHfTokenInfo } from './hfToken.js';-import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';-import { createLineReader } from './streamLines.js';-import { getSettings } from '../services/settings.js';+import { safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';+import { createLineReader } from '../lib/streamLines.js';+import { getSettings } from './settings.js';const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');diff --git a/server/lib/hfDownload.test.js b/server/services/hfDownload.test.jssimilarity index 100%rename from server/lib/hfDownload.test.jsrename to server/services/hfDownload.test.jsdiff --git a/server/services/hfDownloadStream.js b/server/services/hfDownloadStream.jsnew file mode 100644index 0000000000..f8e4a79dba--- /dev/null+++ b/server/services/hfDownloadStream.js@@ -0,0 +1,260 @@+// SSE driver for HuggingFace repo pre-download endpoints. Image gen and video+// gen both expose `GET /…/models/:id/download` (and video also a separate+// `/text-encoder/download`); without this helper each route open-codes the+// same `writeHead → send → cache-check → in-flight check → spawn → cleanup`+// flow. A single in-flight Map keyed by repo also dedupes across routes:+// FLUX-family repos referenced by both image and video gen would otherwise+// spawn two concurrent children.+//+// Lives in services rather than lib because it drives `downloadHfRepo` — a+// python child process that reads settings for its venv and HF token. The pure+// SSE plumbing it builds on (`openSseStream`, `onClientDisconnect`) stays in+// `lib/sseDownload.js` (issue #4901).++import { findCachedRepoFile, inspectModelCache } from '../lib/hfCache.js';+import { openSseStream, onClientDisconnect } from '../lib/sseDownload.js';+import { downloadHfRepo } from './hfDownload.js';++const inFlight = new Map(); // repo -> { promise, kill }++export async function startHfDownloadStream({ req, res, repo, revision = null, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {+ // Three input shapes, two semantics:+ // - `repo` (single string) / `repos` (ordered array) — ALL must succeed. Used+ // when a model has auxiliary repos that must be present alongside the main+ // weights (e.g. HiDream's separate Llama-3.1 text encoder). Sequential;+ // short-circuits on any single-repo error.+ // - `fallbacks` (ordered array of `{ repo, only? }`) — FIRST SUCCESS wins, and+ // a failure advances to the next entry. Used when the same file lives in+ // several repos with different access (Ingredients: gated first-party repo,+ // then an un-gated mirror), so a user with no HF token still succeeds.+ //+ // `only` (array of exact repo-relative filenames, per entry) forwards to the+ // helper's single-file mode — MANDATORY for aggregate repos where a snapshot is+ // catastrophic (the ~708 GB DeepBeepMeep/LTX-2 mirror).+ //+ // `ignore` (array of fnmatch globs, per entry) is the inverse: still snapshot+ // the repo, but drop paths the runtime never loads — extra checkpoint formats+ // or a bundled sibling model. Ignored when `only` is set for the same entry.+ //+ // `cachedFile` is the "is it already here?" predicate for a single-file pull:+ // `inspectModelCache` reports the whole repo cached as soon as ANY weight is+ // resident, which for an aggregate mirror is true after the first unrelated+ // file — so the generic already-cached short-circuit would skip a weight the+ // user doesn't have. Callers pass an async `() => boolean` that checks the one+ // file instead.+ const normalizeOnly = (v) => (Array.isArray(v) ? v.filter((f) => typeof f === 'string' && f.length > 0) : []);+ const normalizeRevision = (v) => (typeof v === 'string' && v.length > 0 ? v : null);+ const normalizeTarget = (target) => {+ if (typeof target === 'string' && target.length > 0) return { repo: target, only: [], ignore: [], revision: null };+ if (!target || typeof target.repo !== 'string' || target.repo.length === 0) return null;+ return {+ repo: target.repo,+ only: normalizeOnly(target.only),+ ignore: normalizeOnly(target.ignore),+ revision: normalizeRevision(target.revision),+ };+ };+ const firstSuccessWins = Array.isArray(fallbacks);+ const targetInputs = firstSuccessWins+ ? fallbacks+ : (Array.isArray(repos) ? repos : [revision ? { repo, revision } : repo]);+ const targets = targetInputs+ .map(normalizeTarget)+ .filter(Boolean);+ const { send, safeEnd } = openSseStream(res);++ if (targets.length === 0) {+ send({ type: 'error', message: 'No repo specified for download.' });+ return safeEnd();+ }++ // Disconnect bookkeeping wired BEFORE the cache-inspection await. The+ // inspection can take double-digit ms on a cold cache; without this the+ // client closing mid-await would land after spawn with no kill path.+ let currentHandle = null;+ let aborted = false;+ onClientDisconnect(req, res, () => {+ aborted = true;+ // Only a live handle means a download was mid-flight, so this keeps the+ // cancel line out of the log when the client simply navigated away between+ // repos.+ if (currentHandle) {+ console.log(`🛑 HuggingFace download cancelled (client disconnect)`);+ currentHandle.kill();+ }+ safeEnd();+ });++ let downloadedAny = false;+ let totalSize = 0;+ // Only meaningful in first-success-wins mode: which repo actually delivered,+ // and the per-attempt failures to report if none did.+ let succeededRepo = null;+ const attemptErrors = [];+ for (let i = 0; i < targets.length; i += 1) {+ const { repo: r, only: onlyFiles, ignore: ignorePatterns, revision } = targets[i];+ const isLastTarget = i === targets.length - 1;+ if (aborted) return;+ // For a single-file pull the repo-wide cache verdict is both the wrong+ // question AND too expensive to ask: `inspectModelCache` recursively stats+ // every weight in the snapshot, and an aggregate mirror reports `cached` off+ // any unrelated resident file — so it would skip the file the user actually+ // asked for after walking hundreds of GB to get there. Skip the walk entirely+ // and defer to the caller's per-file predicate.+ const singleFile = onlyFiles.length > 0;+ const existing = singleFile+ ? { cached: false, sizeBytes: 0 }+ : await inspectModelCache(r, { revision });+ if (aborted) return;+ const alreadyHave = singleFile+ ? (typeof cachedFile === 'function'+ ? await cachedFile({ repo: r, only: onlyFiles, revision })+ : (await Promise.all(onlyFiles.map((file) => findCachedRepoFile(r, file, { revision })))).every(Boolean))+ : existing.cached;+ if (aborted) return;+ // `force` is set by a repair-initiated re-download: repairModelCache()+ // deleted the corrupt file(s), but for a multi-shard repo the remaining+ // shards still make inspectModelCache() report `cached` — so skipping here+ // would leave the just-deleted shard missing and never re-fetched. Forcing+ // re-runs the HF fetch, which is a cheap no-op for files already present+ // (etag match) and pulls only what's gone.+ if (alreadyHave && !force) {+ // A single-file pull has no repo-wide total to report (we deliberately+ // never computed one) — and claiming the aggregate mirror's resident bytes+ // would be a wildly wrong number on the badge anyway. Report 0 and let the+ // badge fall back to the registry's size estimate.+ if (singleFile) {+ console.log(`📦 HuggingFace weight already cached: ${onlyFiles.join(', ')} (${r})`);+ send({ type: 'log', message: `${onlyFiles.join(', ')} already cached.`, repo: r, sizeBytes: 0 });+ } else {+ totalSize += existing.sizeBytes || 0;+ console.log(`📦 HuggingFace repo already cached: ${r} (${existing.sizeBytes} bytes)`);+ send({ type: 'log', message: `${r} already cached (${existing.sizeBytes} bytes).`, repo: r, sizeBytes: existing.sizeBytes });+ }+ // In first-success-wins mode the file being present is the whole goal —+ // don't fall through and try the mirror for something we already have.+ if (firstSuccessWins) { succeededRepo = r; break; }+ continue;+ }+ // Dedupe key includes the filenames: an aggregate repo hosts many unrelated+ // weights, so two single-file pulls of DIFFERENT files from the same repo are+ // not duplicates and must not block each other.+ const revisionKey = revision ? `@${revision}` : '';+ const flightKey = singleFile ? `${r}${revisionKey}::${onlyFiles.join(',')}` : `${r}${revisionKey}`;+ if (inFlight.has(flightKey)) {+ console.log(`⏭️ HuggingFace download already running for ${flightKey} — refusing duplicate`);+ send({ type: 'error', message: `Another download for ${r} is already running.`, kind: 'already_running', repo: r });+ return safeEnd();+ }+ // Server-side visibility for a pull that used to surface only on the SSE+ // stream (the browser) — a headless/PM2 log had no record the multi-GB+ // fetch ever ran. Log the start, each file as it streams, and the outcome.+ console.log(`⬇️ Downloading HuggingFace repo: ${r}${singleFile ? ` (${onlyFiles.length} file(s) only)` : ''}${force ? ' (forced re-fetch)' : ''}`);+ const handle = downloadHfRepo({+ repo: r,+ revision,+ only: singleFile ? onlyFiles : null,+ ignore: ignorePatterns,+ pythonPath,+ onEvent: (ev) => {+ // File-start frames only. Byte ticks arrive several times a second on+ // a large single-file pull and would drown the PM2 log.+ if (ev.type === 'progress' && ev.file && ev.downloaded == null && ev.stage !== 'verify') {+ console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);+ }+ // A failure that we're about to retry against the next candidate isn't a+ // user-facing error — downgrade it to a log so the UI doesn't flash a red+ // "gated repo" banner for something the mirror then delivers fine.+ if (firstSuccessWins && ev.type === 'error') {+ send({+ type: 'log',+ message: `${r}: ${ev.message}${isLastTarget ? '' : ' — trying the next source.'}`,+ repo: r,+ });+ return;+ }+ send({ ...ev, repo: r });+ },+ });+ currentHandle = handle;+ inFlight.set(flightKey, handle);+ let result;+ try {+ result = await handle.promise;+ if (result?.ok) {+ console.log(`✅ HuggingFace download complete: ${r} (${result.sizeBytes || 0} bytes)`);+ } else if (result?.errorKind !== 'cancelled') {+ console.error(`❌ HuggingFace download failed: ${r} — ${result?.errorMessage || 'unknown error'}`);+ }+ } finally {+ inFlight.delete(flightKey);+ currentHandle = null;+ }+ if (!firstSuccessWins) {+ // ALL must succeed here — unlike the fallback-chain branch below, there+ // is no next candidate to fall through to. Silently treating a failed+ // repo as done (the prior bug) let the loop reach `complete` even+ // though one of the required repos never downloaded.+ if (!result?.ok) {+ if (result?.errorKind === 'cancelled') return safeEnd();+ send({+ type: 'error',+ kind: result?.errorKind || 'download_failed',+ message: `${r}: ${result?.errorMessage || 'unknown error'}`,+ repo: r,+ });+ return safeEnd();+ }+ downloadedAny = true;+ totalSize += result.sizeBytes || 0;+ continue;+ }+ if (result?.ok) {+ downloadedAny = true;+ succeededRepo = r;+ totalSize += result.sizeBytes || 0;+ break;+ }+ // A user cancel must not silently roll onto the next candidate.+ if (result?.errorKind === 'cancelled') return safeEnd();+ attemptErrors.push(`${r}: ${result?.errorMessage || 'unknown error'}`);+ }++ if (!aborted) {+ if (firstSuccessWins) {+ if (!succeededRepo) {+ send({+ type: 'error',+ kind: 'all_sources_failed',+ message: `Every source failed — ${attemptErrors.join('; ')}`,+ });+ return safeEnd();+ }+ send({+ type: 'complete',+ message: downloadedAny+ ? `${succeededRepo} downloaded.`+ : (alreadyDownloadedMessage || `${succeededRepo} already downloaded.`),+ repos: [succeededRepo],+ sizeBytes: totalSize,+ });+ return safeEnd();+ }+ const names = targets.map((t) => t.repo);+ let message;+ if (names.length === 1) {+ // Preserve legacy single-repo `complete` message semantics: if it was+ // already cached on entry, surface the caller's `alreadyDownloadedMessage`+ // (or the default already-downloaded line).+ message = !downloadedAny+ ? (alreadyDownloadedMessage || `${names[0]} already downloaded.`)+ : `${names[0]} downloaded.`;+ } else {+ message = downloadedAny+ ? `Downloaded ${names.length} repos: ${names.join(', ')}`+ : `All ${names.length} repos already cached: ${names.join(', ')}`;+ }+ send({ type: 'complete', message, repos: names, sizeBytes: totalSize });+ }+ safeEnd();+}diff --git a/server/lib/sseDownload.test.js b/server/services/hfDownloadStream.test.jssimilarity index 99%rename from server/lib/sseDownload.test.jsrename to server/services/hfDownloadStream.test.jsindex a84b263a8a..d91710054e 100644--- a/server/lib/sseDownload.test.js+++ b/server/services/hfDownloadStream.test.js@@ -6,7 +6,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// never pull the deleted shard back. Mock the IO-bound cache inspect + HF fetch// so the pure stream-control logic is exercised in isolation.-vi.mock('./hfCache.js', () => ({+vi.mock('../lib/hfCache.js', () => ({inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),findCachedRepoFile: vi.fn(async () => null),}));@@ -17,8 +17,8 @@ vi.mock('./hfDownload.js', () => ({downloadHfRepo: vi.fn(() => ({ promise: Promise.resolve({ ok: true, sizeBytes: 100 }), kill: vi.fn() })),}));-import { startHfDownloadStream } from './sseDownload.js';-import { inspectModelCache } from './hfCache.js';+import { startHfDownloadStream } from './hfDownloadStream.js';+import { inspectModelCache } from '../lib/hfCache.js';import { downloadHfRepo } from './hfDownload.js';// Minimal req/res doubles. Disconnect detection lives on `res` (seediff --git a/server/lib/hfToken.js b/server/services/hfToken.jssimilarity index 94%rename from server/lib/hfToken.jsrename to server/services/hfToken.jsindex a717087d6c..4f7e8e7218 100644--- a/server/lib/hfToken.js+++ b/server/services/hfToken.js@@ -7,9 +7,9 @@import { homedir } from 'node:os';import { join } from 'node:path';-import { tryReadFile } from './fileUtils.js';-import { safeChildProcessEnv } from './processEnv.js';-import { getSettings } from '../services/settings.js';+import { tryReadFile } from '../lib/fileUtils.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { getSettings } from './settings.js';const HF_CLI_TOKEN_PATH = join(homedir(), '.cache', 'huggingface', 'token');diff --git a/server/lib/hfToken.test.js b/server/services/hfToken.test.jssimilarity index 100%rename from server/lib/hfToken.test.jsrename to server/services/hfToken.test.jsdiff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 9b5a6db27f..8742abaf0b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -26,7 +26,7 @@ import { rejectDegenerateFrame } from './frameGuard.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { createLineReader } from '../../lib/streamLines.js';diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.jsindex aec9359f96..5f52600a43 100644--- a/server/services/imageTo3d/adapters.js+++ b/server/services/imageTo3d/adapters.js@@ -61,7 +61,7 @@* server reads that field and PortOS installs update independently.*/-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import {isTrellis2Installed,installTrellis2,diff --git a/server/services/imageTo3d/models.genericDispatch.test.js b/server/services/imageTo3d/models.genericDispatch.test.jsindex 26db8c0a20..d9443fdcca 100644--- a/server/services/imageTo3d/models.genericDispatch.test.js+++ b/server/services/imageTo3d/models.genericDispatch.test.js@@ -27,7 +27,7 @@ vi.mock('./targets.js', () => ({renderOptionSupportFor: () => null,}));-vi.mock('../../lib/hfToken.js', () => ({+vi.mock('../hfToken.js', () => ({hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_test' })),}));@@ -58,7 +58,7 @@ vi.mock('./adapters.js', () => ({getTargetAdapter: vi.fn((id) => (id === 'second-target' ? { isInstalled: fakeIsInstalled, run: fakeRun } : null)),}));-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import * as store from './db.js';import { createModel } from './models.js';diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsindex bd8a53c54f..e2ceb1c609 100644--- a/server/services/imageTo3d/models.test.js+++ b/server/services/imageTo3d/models.test.js@@ -37,7 +37,7 @@ vi.mock('./trellis2.js', () => ({// The render spawns with the central HF child env (#3032). Mock the resolver// so the suite doesn't pull in the real settings store (which needs PATHS.data, and// this suite mocks fileUtils down to `imageTo3d` alone).-vi.mock('../../lib/hfToken.js', () => ({+vi.mock('../hfToken.js', () => ({hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' })),}));diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 5aef3eed46..c332aee151 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -21,7 +21,7 @@ import { platform } from 'os';import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { v4 as uuidv4 } from '../../lib/uuid.js';-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { getImageModels } from '../../lib/mediaModels.js';diff --git a/server/services/loras.js b/server/services/loras.jsindex 949db0c2dc..50dc47b790 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -63,7 +63,7 @@ import {isKnownLoraKeyLayout,readSafetensorsHeader,} from '../lib/safetensors.js';-import { getHfToken } from '../lib/hfToken.js';+import { getHfToken } from './hfToken.js';import { getSettings } from './settings.js';const SIDECAR_SUFFIX = '.metadata.json';diff --git a/server/services/mediaModelInstall.js b/server/services/mediaModelInstall.jsindex 978a38702f..2230abdcfa 100644--- a/server/services/mediaModelInstall.js+++ b/server/services/mediaModelInstall.js@@ -23,7 +23,7 @@ import {classifyHfMediaModel,} from '../lib/huggingfaceModel.js';import { addUserModelEntry } from '../lib/mediaModels.js';-import { getHfToken } from '../lib/hfToken.js';+import { getHfToken } from './hfToken.js';import { ServerError } from '../lib/errorHandler.js';// Add a media model from a HuggingFace repo. `input.url` is any HF ref shapediff --git a/server/services/mediaModelInstall.test.js b/server/services/mediaModelInstall.test.jsindex 9cd446889d..23c420a51d 100644--- a/server/services/mediaModelInstall.test.js+++ b/server/services/mediaModelInstall.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { pinPlatform } from '../lib/testHelper.js';-vi.mock('../lib/hfToken.js', () => ({ getHfToken: vi.fn(async () => '') }));+vi.mock('./hfToken.js', () => ({ getHfToken: vi.fn(async () => '') }));vi.mock('../lib/mediaModels.js', () => ({ addUserModelEntry: vi.fn((entry) => entry) }));const { addModelFromHuggingface } = await import('./mediaModelInstall.js');diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 0519a4f4bb..ce6f7d4165 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -1370,7 +1370,7 @@ async function importModelFromHfSafetensors(spec, onProgress) {code: 'OLLAMA_OUTDATED'}}- const { getHfToken } = await import('../lib/hfToken.js')+ const { getHfToken } = await import('./hfToken.js')const token = await getHfToken()if (!token) {return {@@ -1732,10 +1732,10 @@ async function finalizeHuggingFacePull(modelId) {const modelsDir = getModelsDir()const blobsDir = join(modelsDir, 'blobs')- // Imported lazily: lib/hfToken.js reaches services/settings.js, which resolves- // its file path from PATHS at module load — a static import would drag that- // (and everything settings pulls in) into every consumer of this module.- const { getHfToken } = await import('../lib/hfToken.js')+ // Imported lazily: hfToken.js reaches settings.js, which resolves its file+ // path from PATHS at module load — a static import would drag that (and+ // everything settings pulls in) into every consumer of this module.+ const { getHfToken } = await import('./hfToken.js')const headers = buildHfAuthHeaders(await getHfToken())const fetched = await fetchHuggingFaceDocument(`${base}/manifests/${ref.tag}`, headers)if (fetched.error) return { success: false, error: `manifest fetch failed: ${fetched.error}` }diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 0d2149386a..ced10ae293 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -18,7 +18,7 @@ vi.mock('../lib/childProcess.js', () => ({// The HF pull recovery attaches the user's HF token (so a gated repo Ollama could// pull is recoverable too). Stub the resolver rather than reading real settings.const hfTokenMock = { token: null }-vi.mock('../lib/hfToken.js', () => ({ getHfToken: async () => hfTokenMock.token }))+vi.mock('./hfToken.js', () => ({ getHfToken: async () => hfTokenMock.token }))// pullModel talks to Ollama over its native HTTP API via the global `fetch`// (through fetchWithTimeout). We stub `fetch` so each test scripts thediff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex ce53d39ed1..33401914c7 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -44,7 +44,7 @@ import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { randomUUID } from 'crypto';import { PATHS, ensureDir } from '../../lib/fileUtils.js';-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import { runSidecarProcess, parseSidecarResult } from '../../lib/sidecarProcess.js';import {resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT,diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsindex e16326fd20..f1611d0ece 100644--- a/server/services/pipeline/musicGen.test.js+++ b/server/services/pipeline/musicGen.test.js@@ -479,7 +479,7 @@ vi.mock('../../lib/fileUtils.js', async () => {};});-vi.mock('../../lib/hfToken.js', () => ({ hfChildEnv: async () => ({}) }));+vi.mock('../hfToken.js', () => ({ hfChildEnv: async () => ({}) }));// Venv resolvers — flip readiness per engine per test.vi.mock('../../lib/pythonSetup.js', async () => {diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.jsindex ec2fcbe125..b2441a82f3 100644--- a/server/services/specDecodeModels.js+++ b/server/services/specDecodeModels.js@@ -22,7 +22,7 @@ import { ensureDir, expandHome } from '../lib/fileUtils.js';import { isProjectorName, isShardedGguf } from '../lib/localLlmDisk.js';import { ServerError } from '../lib/errorHandler.js';import { buildHfAuthHeaders, buildHfResolveUrl, fetchHuggingfaceModel, modelSiblingFilenames } from '../lib/huggingfaceLora.js';-import { getHfToken } from '../lib/hfToken.js';+import { getHfToken } from './hfToken.js';import {SPEC_DECODE_PRESETS,SPEC_MODEL_ROLES,diff --git a/server/services/specDecodeModels.test.js b/server/services/specDecodeModels.test.jsindex 3729711110..3b6ff2d0ad 100644--- a/server/services/specDecodeModels.test.js+++ b/server/services/specDecodeModels.test.js@@ -12,7 +12,7 @@ import {_resetSpecDecodeDownloadsForTests,} from './specDecodeModels.js';import * as specDecodePresets from '../lib/specDecodePresets.js';-import * as hfToken from '../lib/hfToken.js';+import * as hfToken from './hfToken.js';import * as huggingfaceLora from '../lib/huggingfaceLora.js';const siblings = (...names) => ({ siblings: names.map((rfilename) => ({ rfilename })) });diff --git a/server/services/videoGen/deleteHistoryItem.test.js b/server/services/videoGen/deleteHistoryItem.test.jsindex 215ca9d652..a6189fe321 100644--- a/server/services/videoGen/deleteHistoryItem.test.js+++ b/server/services/videoGen/deleteHistoryItem.test.js@@ -55,7 +55,7 @@ vi.mock('../../lib/ffmpeg.js', () => ({extractEvaluationFrames: vi.fn(async () => []),}));-vi.mock('../../lib/hfToken.js', () => ({+vi.mock('../hfToken.js', () => ({hfChildEnv: vi.fn(async () => ({})),getHfToken: vi.fn(async () => null),}));diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 652a558e9a..90fdcdfaee 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -220,7 +220,7 @@ vi.mock('../../lib/ffmpeg.js', async () => ({// hfChildEnv() carries the resolved token over the inherited child env; mocking here// avoids touching the real settings layer (which would await an unmocked// `getSettings()` chain and hang the spawn-mock-driven tests).-vi.mock('../../lib/hfToken.js', () => ({+vi.mock('../hfToken.js', () => ({hfChildEnv: vi.fn(async () => ({})),getHfToken: vi.fn(async () => null),}));@@ -2974,7 +2974,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {it('uses the pinned cache-only helper, locked sampler and credential-free environment', async () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');- const { hfChildEnv } = await import('../../lib/hfToken.js');+ const { hfChildEnv } = await import('../hfToken.js');const spawnMock = vi.mocked(spawnDetached);spawnMock.mockClear();vi.mocked(hfChildEnv).mockClear();diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.jsindex 5a7136ac81..a98cfa4019 100644--- a/server/services/videoGen/spawnWatch.js+++ b/server/services/videoGen/spawnWatch.js@@ -14,7 +14,7 @@ import { videoGenEvents } from './events.js';import {broadcastSse, closeJobAfterDelay, PYTHON_NOISE_RE,} from '../../lib/sseUtils.js';-import { hfChildEnv } from '../../lib/hfToken.js';+import { hfChildEnv } from '../hfToken.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';import {makeVideoGenLineHandler,diff --git a/server/services/videoLoraSuggestions.js b/server/services/videoLoraSuggestions.jsindex a72873a733..a59e44cd72 100644--- a/server/services/videoLoraSuggestions.js+++ b/server/services/videoLoraSuggestions.js@@ -17,7 +17,7 @@import { VIDEO_LORA_FAMILIES } from '../lib/runners.js';import { extractHfCardDescription, fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';-import { getHfToken } from '../lib/hfToken.js';+import { getHfToken } from './hfToken.js';const TTL_MS = 60 * 60 * 1000; // 1 hour — matches the Civitai suggestion cache.const DESCRIPTION_MAX_CHARS = 240;diff --git a/server/services/videoLoraSuggestions.test.js b/server/services/videoLoraSuggestions.test.jsindex bc281118b0..f7a481783f 100644--- a/server/services/videoLoraSuggestions.test.js+++ b/server/services/videoLoraSuggestions.test.js@@ -6,7 +6,7 @@ let svc;beforeEach(async () => {vi.resetModules();// No HF token in tests — getHfToken reads settings/env, stub to null.- vi.doMock('../lib/hfToken.js', () => ({ getHfToken: async () => null }));+ vi.doMock('./hfToken.js', () => ({ getHfToken: async () => null }));svc = await import('./videoLoraSuggestions.js');svc._resetVideoSuggestionsCache();});