Skip to content

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

inline HF model download badge on image + video gen forms

[._.]/ Adam Eivy8280ee6c6529
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 37cf37b1d4..2cd2be7a9d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,7 @@ TBD
- **Brain → Links: edit a link's URL**: the per-link edit form now exposes the URL alongside the title (each with a visible label so they're unambiguous even when the title defaults to the URL). Changing the URL re-derives the GitHub repo metadata, guards against duplicate URLs (409), and resets stale clone state so a cloned repo's local path can't point at the wrong target.
- **Base style image (style probe)** on a universe: generate a canonical image from the universe's embrace/avoid influences as the positive/negative prompt, with no character or subject — to preview the world's base visual emphasis. `styleNotes` is intentionally NOT mixed into the probe prompt because it never reaches the image model on any downstream prompt (canon refs, variations, sheets, comic pages) — including it would misrepresent what those renders will look like. Triggerable from both the Universe Builder (under the style/influences editor) and the Story Builder's Universe Aesthetic step; the result persists on the universe (`styleImageRefs`) so both surfaces share it. Includes a "Regenerate" affordance to re-roll the probe once an image already exists (new filenames append to `styleImageRefs[]` so prior renders survive as walk-back fallbacks).
- **Reader Map** on a series arc (`series.arc.readerMap`): a distinct audience-experience roadmap — hooks, payoffs, emotional beats, and cliffhangers across the arc — built on top of the Vonnegut story shape, separate from the protagonist arc. Generated and refined via the new Story Builder reader-map step (also preserved by arc regeneration).
+- **Image + Video Gen: inline model download status**. The model picker on both pages now shows whether the selected model's weights are already in the local HuggingFace cache. Available models get a green "Available · 7.8 GB" badge; missing ones get a "Download (~est)" button that pre-fetches the repo over SSE with a live progress bar (so users learn about a multi-GB pull before hitting Render instead of being surprised by a silent lazy download mid-generation). Hitting Render without pre-downloading still works — the existing lazy-download path is the fallback. The video form also surfaces the active text encoder (a separate ~7–25 GB Gemma pull) with its own button. New endpoints: `GET /api/image-gen/models/status`, `GET /api/image-gen/models/:id/download` (SSE), `GET /api/video-gen/models/status`, `GET /api/video-gen/models/:id/download` (SSE), `GET /api/video-gen/text-encoder/download` (SSE). Cache detection lives in `server/lib/hfCache.js` (`inspectModelCache`); download orchestration in `server/lib/hfDownload.js` and the new `scripts/hf_download_repo.py` helper (runs in the FLUX.2 venv, falls back to the mflux pythonPath). Mflux legacy `dev` / `schnell` map to their canonical `black-forest-labs/FLUX.1-*` repos so they get the same badge as every other entry.
- Local LLMs: when an Ollama model pull fails with `412: requires a newer version of Ollama`, PortOS now auto-upgrades Ollama in place and retries the install — no confirm click. On macOS with `/Applications/Ollama.app` present, this downloads the latest `Ollama-darwin.zip` directly from GitHub releases, force-kills the running Ollama, replaces the `.app` bundle, strips quarantine, relaunches, and polls `/api/version` until the new binary is serving. (The old brew-only path silently left the old binary running, because `/usr/local/bin/ollama` symlinks into the `.app` bundle — even a successful `brew upgrade` doesn't change which binary is on disk inside the `.app`.) On Linux it still re-runs the official Ollama install script; for headless macOS installs (brew formula only, no `.app`), it still runs `brew upgrade ollama`. The UI now shows a prominent yellow warning banner with live step-by-step progress for the whole upgrade flow, instead of a quiet inline confirm row. Failed `brew` runs now also surface the actual stderr (e.g. `Error: ollama not installed`) instead of just an exit code.
## Changed
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index 086fe79b42..b301fc6e45 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -13,6 +13,7 @@ import { filterResolutions, resolveResolutionLabel } from '../../lib/imageGenRes
import { randomSeed } from '../../lib/genUtils';
import { RUNNER_FAMILIES } from '../../lib/runnerFamilies';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
+import ModelDownloadBadge, { deriveSizeEstimate } from '../media/ModelDownloadBadge';
const QUANTIZE_OPTIONS = [
{ value: '3', label: '3-bit' },
@@ -39,6 +40,14 @@ export default function ImageGenControls({
// Optional column override — defaults to 2/3 like the Image Gen page.
// Pass e.g. "grid-cols-2 sm:grid-cols-4" to fit a denser layout.
className = 'grid grid-cols-2 sm:grid-cols-3 gap-3',
+ // Pre-download badge integration. `modelStatus` is the per-model entry from
+ // useModelDownloadStatus().getStatus(modelId); `onModelDownload` /
+ // `onModelDownloadCancel` are optional triggers. Omitting the props hides
+ // the badge — callers that don't care (Universe Builder batch render) opt
+ // out by simply not passing them.
+ modelStatus = null,
+ onModelDownload,
+ onModelDownloadCancel,
}) {
const isLocal = mode === IMAGE_GEN_MODE.LOCAL;
const isCodex = mode === IMAGE_GEN_MODE.CODEX;
@@ -71,6 +80,14 @@ export default function ImageGenControls({
>
{models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
+ {onModelDownload && modelStatus && (
+ <ModelDownloadBadge
+ status={modelStatus}
+ onDownload={() => onModelDownload(modelId)}
+ onCancel={onModelDownloadCancel}
+ estimateLabel={deriveSizeEstimate(currentModel?.name)}
+ />
+ )}
</div>
)}
diff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsx
new file mode 100644
index 0000000000..c3e49d3aa9
--- /dev/null
+++ b/client/src/components/media/ModelDownloadBadge.jsx
@@ -0,0 +1,107 @@
+// Inline "Available · 7.8 GB" / "Download (~8 GB)" badge for the image and
+// video gen model pickers. Drops below the model <select> so the user can
+// see — before hitting Render — whether their pick still needs a multi-GB
+// HF pull. Rendering Render is NOT blocked: lazy download remains the
+// fallback, so a user who just wants to fire and wait can keep doing that.
+//
+// Three render states:
+// 1. cached → green CheckCircle, "Available · <size>"
+// 2. unknown → grey, no CTA (model has no `repo` in the registry)
+// 3. needsDl → "↓ Download (~est)" button; while downloading, a stage
+// label + percentage replace the button.
+
+import { CheckCircle, Download, Loader2 } from 'lucide-react';
+import { formatBytes } from '../../utils/formatters.js';
+
+const STAGE_LABELS = {
+ starting: 'Starting…',
+ list: 'Fetching file list…',
+ download: 'Downloading…',
+};
+
+export default function ModelDownloadBadge({
+ status, // { id, repo, cached, sizeBytes, downloading?, progress? }
+ onDownload, // () => void
+ onCancel, // () => void
+ estimateLabel, // e.g. "~8 GB" — caller derives from model entry name
+}) {
+ if (!status) {
+ return <p className="text-[10px] text-gray-500 mt-1">Checking model cache…</p>;
+ }
+
+ // Unknown repo (custom mflux entry without `repo`) — just skip the badge
+ // rather than mislead the user with "not downloaded".
+ if (status.cached === null) {
+ return null;
+ }
+
+ if (status.downloading) {
+ const frame = status.progress || {};
+ const pct = typeof frame.progress === 'number' ? Math.round(frame.progress * 100) : null;
+ const stage = STAGE_LABELS[frame.stage] || (frame.type === 'log' ? 'Downloading…' : (STAGE_LABELS[frame.type] || 'Downloading…'));
+ const fileLine = frame.file ? `${frame.step}/${frame.total} · ${frame.file}` : '';
+ return (
+ <div className="mt-1 flex items-center gap-2 text-[11px]">
+ <Loader2 className="w-3.5 h-3.5 animate-spin text-port-accent" />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between gap-2 text-port-accent">
+ <span className="truncate">
+ {stage}
+ {pct != null ? ` ${pct}%` : ''}
+ </span>
+ {onCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ className="text-gray-400 hover:text-white shrink-0"
+ >
+ Cancel
+ </button>
+ )}
+ </div>
+ {fileLine && (
+ <div className="text-[10px] text-gray-500 truncate" title={fileLine}>{fileLine}</div>
+ )}
+ {pct != null && (
+ <div className="mt-0.5 h-1 bg-port-border rounded overflow-hidden">
+ <div className="h-full bg-port-accent" style={{ width: `${pct}%` }} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ if (status.cached) {
+ const sizeLabel = status.sizeBytes ? ` · ${formatBytes(status.sizeBytes)}` : '';
+ return (
+ <p className="mt-1 flex items-center gap-1.5 text-[11px] text-port-success">
+ <CheckCircle className="w-3.5 h-3.5" />
+ <span>Available{sizeLabel}</span>
+ </p>
+ );
+ }
+
+ // Not cached, not in flight — offer the inline trigger.
+ return (
+ <button
+ type="button"
+ onClick={onDownload}
+ className="mt-1 inline-flex items-center gap-1.5 text-[11px] text-port-accent hover:text-white border border-port-border hover:border-port-accent rounded px-2 py-1"
+ title={status.repo ? `Pre-download ${status.repo} into ~/.cache/huggingface/hub/` : 'Pre-download model weights'}
+ >
+ <Download className="w-3.5 h-3.5" />
+ <span>Download{estimateLabel ? ` (${estimateLabel})` : ''}</span>
+ </button>
+ );
+}
+
+// Pull a size estimate out of the model's display name when the registry
+// embedded one (e.g. "Flux 2 Klein 4B (SDNQ 4-bit, ~8 GB @ 512px)"). The
+// registry isn't required to carry a structured size field, so we just
+// pluck whatever "~N GB" parenthetical the human-readable label included.
+export function deriveSizeEstimate(modelName) {
+ if (!modelName) return null;
+ const m = String(modelName).match(/~\s*(\d+(?:\.\d+)?)\s*GB/i);
+ return m ? `~${m[1]} GB` : null;
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 62416dd272..4a8d29f7ae 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -30,6 +30,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
+| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |
| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 2a3c765a05..7e5cf091d6 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -47,6 +47,7 @@ export * from './usePipelineEditorialProgress.js';
export * from './usePipelineVolumeBeatsProgress.js';
export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
+export * from './useModelDownloadStatus.js';
// === Media (annotations, completion, attachments) ===
export * from './useMediaAnnotations.js';
diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.js
new file mode 100644
index 0000000000..477fe5cd01
--- /dev/null
+++ b/client/src/hooks/useModelDownloadStatus.js
@@ -0,0 +1,113 @@
+import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
+import { useSseProgress } from './useSseProgress.js';
+import { getImageModelStatuses, getVideoModelStatuses } from '../services/apiImageVideo.js';
+
+// Sentinel `modelId` used to drive a text-encoder download instead of a model
+// download. The video form passes this to `start()`; the URL builder below
+// rewrites to the dedicated /text-encoder/download endpoint. Exported so
+// callers and the hook agree on the magic string.
+export const TEXT_ENCODER_DOWNLOAD_ID = '__text_encoder__';
+
+const buildDownloadUrl = (kind, modelId) => {
+ if (!modelId) return null;
+ if (kind === 'video' && modelId === TEXT_ENCODER_DOWNLOAD_ID) {
+ return '/api/video-gen/text-encoder/download';
+ }
+ return `/api/${kind}-gen/models/${encodeURIComponent(modelId)}/download`;
+};
+
+// Model download-status hook. Drives the inline "Available · 7.8 GB" /
+// "Download (~8 GB)" badge next to the image/video gen model picker.
+//
+// `kind` selects the endpoint family ('image' | 'video'). `start(modelId)`
+// opens an EventSource against the download endpoint. When the stream
+// emits a terminal frame we automatically refetch /models/status so the
+// badge flips to "Available" without the caller wiring that up.
+export function useModelDownloadStatus({ kind = 'image' } = {}) {
+ const [statuses, setStatuses] = useState(null);
+ const [extra, setExtra] = useState({}); // video: { textEncoder: {...} }
+ const [loading, setLoading] = useState(false);
+ const [activeModelId, setActiveModelId] = useState(null);
+
+ const fetchStatuses = useCallback(async () => {
+ setLoading(true);
+ // Best-effort: a failure leaves the badge in its loading state. The form
+ // still works because lazy download is the existing fallback.
+ const body = await (kind === 'video' ? getVideoModelStatuses() : getImageModelStatuses())
+ .catch(() => null);
+ if (body == null) {
+ setStatuses([]);
+ setExtra({});
+ } else if (kind === 'video') {
+ setStatuses(Array.isArray(body?.models) ? body.models : []);
+ setExtra({ textEncoder: body?.textEncoder || null });
+ } else {
+ setStatuses(Array.isArray(body) ? body : []);
+ setExtra({});
+ }
+ setLoading(false);
+ }, [kind]);
+
+ useEffect(() => { fetchStatuses(); }, [fetchStatuses]);
+
+ // EventSource for the active download. `null` URL = idle (useSseProgress's
+ // `enabled: false` cleanup tears the connection down on cancel).
+ const downloadUrl = buildDownloadUrl(kind, activeModelId);
+ const sse = useSseProgress(downloadUrl, { enabled: !!downloadUrl });
+
+ // Refetch on natural stream close. useSseProgress flips `closed:true` once
+ // per subscription and resets to false when the URL changes; that single
+ // transition is the safe signal — no extra `wasClosed` ref needed.
+ useEffect(() => {
+ if (sse.closed) {
+ fetchStatuses();
+ setActiveModelId(null);
+ }
+ }, [sse.closed, fetchStatuses]);
+
+ const start = useCallback((modelId) => {
+ setActiveModelId(modelId);
+ }, []);
+
+ // Manual cancel: refetch directly because `sse.close()` followed by
+ // setActiveModelId(null) clears the URL, which causes useSseProgress to
+ // reset `closed → false` before the close-effect can observe `true`.
+ // Without this direct refetch the badge would stay stuck on its pre-cancel
+ // state until the next page mount.
+ const cancel = useCallback(() => {
+ sse.close();
+ setActiveModelId(null);
+ fetchStatuses();
+ }, [sse, fetchStatuses]);
+
+ // Memoize the active model's enriched status so a new SSE frame doesn't
+ // hand a fresh object to every non-active model's badge (only the active
+ // one re-renders). For inactive models we return the raw entry, which is
+ // referentially stable across frames.
+ const activeStatus = useMemo(() => {
+ if (!activeModelId) return null;
+ const list = Array.isArray(statuses) ? statuses : [];
+ const entry = list.find((s) => s.id === activeModelId);
+ if (!entry) return null;
+ return { ...entry, downloading: true, progress: sse.latest };
+ }, [activeModelId, statuses, sse.latest]);
+
+ const getStatus = useCallback((modelId) => {
+ if (modelId === activeModelId) return activeStatus;
+ const list = Array.isArray(statuses) ? statuses : [];
+ return list.find((s) => s.id === modelId) || null;
+ }, [statuses, activeModelId, activeStatus]);
+
+ return {
+ statuses,
+ extra,
+ loading,
+ refresh: fetchStatuses,
+ start,
+ cancel,
+ getStatus,
+ activeModelId,
+ progress: sse.latest,
+ downloading: !!activeModelId,
+ };
+}
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 28bd1c502a..75441aed71 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -39,6 +39,7 @@ import { resolveCleanersFromConfig } from '../lib/imageCleaners';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import { useImageGenProgress } from '../hooks/useImageGenProgress';
+import { useModelDownloadStatus } from '../hooks/useModelDownloadStatus';
import {
getImageGenStatus, generateImage, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
@@ -193,6 +194,12 @@ export default function ImageGen() {
// via imageGenEvents so the same UI bits light up).
const { progress: externalProgress, begin: beginGenerate, end: endGenerate, resume: resumeGenerate } = useImageGenProgress();
+ // Per-model cache status drives the inline "Available / Download" badge
+ // under the model picker. Only meaningful for the local backend (external
+ // SD-API and Codex don't use HF cache), so we conditionally pass the
+ // status through to ImageGenControls below.
+ const modelDownload = useModelDownloadStatus({ kind: 'image' });
+
// selectedMode is null until settings load — fall back to status.mode
// so the form doesn't flicker between defaults.
const effectiveMode = selectedMode || status?.mode || IMAGE_GEN_MODE.EXTERNAL;
@@ -993,6 +1000,9 @@ export default function ImageGen() {
seed={seed} onSeedChange={setSeed}
showSeed
disabled={statusLoading}
+ modelStatus={isLocalMode ? modelDownload.getStatus(modelId) : null}
+ onModelDownload={isLocalMode ? modelDownload.start : undefined}
+ onModelDownloadCancel={modelDownload.cancel}
/>
{isLocalMode && (
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index d322658a7f..500a7549d9 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -44,6 +44,8 @@ import BatchQueuePanel from '../components/media/BatchQueuePanel';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import ModelSelect from '../components/ModelSelect';
+import ModelDownloadBadge, { deriveSizeEstimate } from '../components/media/ModelDownloadBadge';
+import { useModelDownloadStatus, TEXT_ENCODER_DOWNLOAD_ID } from '../hooks/useModelDownloadStatus';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import usePreviewRoute from '../hooks/usePreviewRoute';
@@ -469,6 +471,20 @@ export default function VideoGen() {
}, [modelId, models, status?.defaultModel]);
const currentModel = models.find((m) => m.id === modelId);
+
+ // Inline cache-status badge for the picked video model + the active text
+ // encoder (a separate ~7-25 GB HF pull). Drives the "Available" / "Download"
+ // affordance under the Model select, so users learn about the multi-GB
+ // pull before hitting Render.
+ const modelDownload = useModelDownloadStatus({ kind: 'video' });
+ const modelStatus = modelId ? modelDownload.getStatus(modelId) : null;
+ const textEncoderInfo = modelDownload.extra.textEncoder || null;
+ const textEncoderStatus = textEncoderInfo
+ ? (modelDownload.activeModelId === TEXT_ENCODER_DOWNLOAD_ID
+ ? { ...textEncoderInfo, downloading: true, progress: modelDownload.progress }
+ : textEncoderInfo)
+ : null;
+
const { matched: matchedResolution, label: resolutionLabel } = resolveResolutionLabel(VIDEO_RESOLUTIONS, width, height);
const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;
@@ -1204,6 +1220,24 @@ export default function VideoGen() {
value={modelId}
onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidanceScale(''); }}
/>
+ {modelStatus && (
+ <ModelDownloadBadge
+ status={modelStatus}
+ onDownload={() => modelDownload.start(modelId)}
+ onCancel={modelDownload.cancel}
+ estimateLabel={deriveSizeEstimate(currentModel?.name)}
+ />
+ )}
+ {textEncoderStatus && textEncoderStatus.cached === false && (
+ <div className="mt-1">
+ <p className="text-[10px] text-gray-500">Text encoder ({textEncoderStatus.repo}) is also required:</p>
+ <ModelDownloadBadge
+ status={textEncoderStatus}
+ onDownload={() => modelDownload.start(TEXT_ENCODER_DOWNLOAD_ID)}
+ onCancel={modelDownload.cancel}
+ />
+ </div>
+ )}
</div>
)}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 25c564ab66..806597e783 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -4,6 +4,9 @@ import { request } from './apiCore.js';
// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for
// backward compatibility with existing call sites.
export const listImageModels = () => request('/image-gen/models');
+// Per-model download status: `[{ id, repo, cached, sizeBytes }]`. Drives the
+// inline Available/Download badge on the image gen form.
+export const getImageModelStatuses = () => request('/image-gen/models/status', { silent: true });
export const listLoras = () => request('/image-gen/loras');
export const listImageGallery = () => request('/image-gen/gallery');
export const getActiveImageJob = () => request('/image-gen/active');
@@ -36,6 +39,10 @@ export const clearHfToken = () => request('/image-gen/setup/hf-token', { method:
// Video gen
export const getVideoGenStatus = () => request('/video-gen/status');
export const listVideoModels = () => request('/video-gen/models');
+// `{ models: [...], textEncoder: { repo, cached, sizeBytes } }`. Same shape
+// contract as the image variant + a text-encoder block since the active
+// encoder is a separate multi-GB pull.
+export const getVideoModelStatuses = () => request('/video-gen/models/status', { silent: true });
export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });
export const listVideoHistory = () => request('/video-gen/history');
export const deleteVideoHistoryItem = (id) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE' });
diff --git a/scripts/hf_download_repo.py b/scripts/hf_download_repo.py
new file mode 100755
index 0000000000..4ce63ced98
--- /dev/null
+++ b/scripts/hf_download_repo.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""
+PortOS HuggingFace snapshot pre-fetch.
+
+Downloads a full HF repo into the standard `~/.cache/huggingface/hub/` cache
+so the image / video gen forms can show a model as "Available" instead of
+forcing the user to discover a multi-GB pull mid-render. Spawned over SSE
+from `server/routes/imageGen.js#/models/:repoId/download` and the matching
+video route.
+
+Wire protocol (matches the STAGE:/DOWNLOAD: convention the rest of the
+image-gen runners use, so the existing SSE bridge picks it up unchanged):
+
+ STAGE:list — fetching file list
+ STAGE:download:<n>/<total>:<filename> — starting file <n> of <total>
+ DOWNLOAD:<n>/<total>:<filename> — same; redundant for the regex
+ STAGE:complete:<bytes> — done, with total resident bytes
+ USER_ERROR:<kind>:<repo> — typed error (gated_repo, …)
+ ❌ <prose message> — paired with USER_ERROR
+
+Exit codes: 0 ok, 2 user-error, 1 unexpected.
+"""
+
+import argparse
+import os
+import sys
+from pathlib import Path
+
+# `huggingface_hub` is installed in the FLUX.2 venv (and any mflux venv) —
+# the caller picks the python binary that has it. Import errors surface as
+# a USER_ERROR with a clear "venv missing huggingface_hub" message so the
+# UI can route the user to the FLUX.2 install banner.
+try:
+ from huggingface_hub import HfApi, hf_hub_download
+ from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
+except Exception as err: # noqa: BLE001
+ print(f"USER_ERROR:venv_missing_hf_hub:{err}", file=sys.stderr, flush=True)
+ print("❌ Python venv is missing huggingface_hub. Run the FLUX.2 install from Image Gen settings.", file=sys.stderr, flush=True)
+ sys.exit(2)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Pre-fetch a HuggingFace repo snapshot.")
+ parser.add_argument("--repo", required=True, help="HF repo id, e.g. 'org/name'.")
+ parser.add_argument("--revision", default=None, help="Optional revision (branch / tag / sha).")
+ parser.add_argument("--token-env", default=None, help="Env var name to read the HF token from (e.g. HF_TOKEN).")
+ args = parser.parse_args()
+
+ token = None
+ if args.token_env:
+ token = os.environ.get(args.token_env) or None
+ # huggingface_hub also reads HF_TOKEN itself, but being explicit lets
+ # the caller scope which env var the child trusts.
+
+ api = HfApi()
+ print("STAGE:list", file=sys.stderr, flush=True)
+ try:
+ files = api.list_repo_files(args.repo, revision=args.revision, token=token)
+ except GatedRepoError:
+ print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ Access to {args.repo} is gated. Accept the license at https://huggingface.co/{args.repo} and paste your HuggingFace token into Image Gen settings, then retry.", file=sys.stderr, flush=True)
+ return 2
+ except RepositoryNotFoundError:
+ print(f"USER_ERROR:repo_not_found:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ Repository {args.repo} not found on HuggingFace.", file=sys.stderr, flush=True)
+ return 2
+ except Exception as err: # noqa: BLE001
+ # Anything that smells like 401 from list_repo_files — surface it
+ # as token-rejected so the UI can prompt for a new HF_TOKEN.
+ if "401" in str(err) or "Unauthorized" in str(err):
+ print(f"USER_ERROR:hf_unauthorized:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ HuggingFace rejected the token. Update HF_TOKEN in Image Gen settings.", file=sys.stderr, flush=True)
+ return 2
+ print(f"USER_ERROR:list_failed:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ Failed to list {args.repo}: {err}", file=sys.stderr, flush=True)
+ return 2
+
+ # Skip the few HF housekeeping files that are not actually downloadable
+ # as part of a snapshot (`.gitattributes` is, but `LICENSE` and similar
+ # are — we keep them; the only true skip is the `.huggingface` folder).
+ files = [f for f in files if not f.startswith(".huggingface/")]
+ total = len(files)
+ if total == 0:
+ print(f"USER_ERROR:repo_empty:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ Repository {args.repo} reports zero downloadable files.", file=sys.stderr, flush=True)
+ return 2
+
+ total_bytes = 0
+ for i, filename in enumerate(files, start=1):
+ # Stage marker (UI-friendly) + DOWNLOAD: marker (matches the existing
+ # mlx_video DOWNLOAD: regex in videoGen/local.js so the same line
+ # drives progress in either pipeline).
+ print(f"STAGE:download:{i}/{total}:{filename}", file=sys.stderr, flush=True)
+ print(f"DOWNLOAD:{i}/{total}:{filename}", file=sys.stderr, flush=True)
+ try:
+ resolved = hf_hub_download(
+ repo_id=args.repo,
+ filename=filename,
+ revision=args.revision,
+ token=token,
+ )
+ except GatedRepoError:
+ print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)
+ print(f"❌ {args.repo} is gated. Accept the license + paste your HF token.", file=sys.stderr, flush=True)
+ return 2
+ except Exception as err: # noqa: BLE001
+ print(f"USER_ERROR:download_failed:{filename}", file=sys.stderr, flush=True)
+ print(f"❌ Failed to download {filename}: {err}", file=sys.stderr, flush=True)
+ return 2
+ # Sum sizes for the completion event so the UI can show the resident
+ # bytes total — matches what the cache inspector returns server-side.
+ try:
+ total_bytes += Path(resolved).stat().st_size
+ except OSError:
+ pass
+
+ print(f"STAGE:complete:{total_bytes}", file=sys.stderr, flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/server/lib/README.md b/server/lib/README.md
index ec3caa9f04..761958a301 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -79,6 +79,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
+| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. |
+| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
+| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})` — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
## File & I/O
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
new file mode 100644
index 0000000000..d9437f40b9
--- /dev/null
+++ b/server/lib/hfCache.js
@@ -0,0 +1,126 @@
+// HuggingFace Hub cache inspection — detect whether a model repo has been
+// downloaded into `~/.cache/huggingface/hub/` (or wherever HF_HOME points)
+// so the image/video gen forms can show "Available" vs "Download" inline
+// without waiting until first render to discover a multi-GB download.
+//
+// Cache layout (huggingface_hub >=0.14):
+// <root>/models--<owner>--<name>/
+// refs/main -> commit sha
+// snapshots/<sha>/ -> symlinks to ../../blobs/<hash>
+// blobs/<hash> -> actual file bytes
+//
+// "Cached" here means: at least one snapshot directory exists AND every
+// non-metadata file (safetensors, ckpt, bin, pt, msgpack) in that snapshot
+// resolves to an existing blob with non-zero size. A partial download
+// (interrupted mid-snapshot) leaves dangling symlinks — we treat that as
+// not cached so the user gets the Download button instead of a confusing
+// "Available" badge followed by a runtime failure.
+//
+// All filesystem work is async (`fs.promises`) so the `/models/status`
+// route — which inspects every registered model — doesn't block the Node
+// event loop while walking large snapshot directories.
+
+import { promises as fs } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+// HF cache root resolution mirrors huggingface_hub's own precedence:
+// HF_HUB_CACHE > HF_HOME/hub > ~/.cache/huggingface/hub. We never set
+// HF_HOME ourselves (see imageGen/local.js header), so the third branch
+// is the common path for PortOS installs.
+export const getHfCacheRoot = () => {
+ if (process.env.HF_HUB_CACHE) return process.env.HF_HUB_CACHE;
+ if (process.env.HF_HOME) return join(process.env.HF_HOME, 'hub');
+ return join(homedir(), '.cache', 'huggingface', 'hub');
+};
+
+// HF's on-disk naming: `org/name` -> `models--org--name`. Forward slashes
+// inside the name (rare) are also `--` separated. Strip trailing slash so
+// a registry-edit user pasting `org/name/` doesn't miss a real cache hit.
+const repoToDirName = (repoId) => `models--${repoId.replace(/\/$/, '').replace(/\//g, '--')}`;
+
+const WEIGHT_EXTENSIONS = ['.safetensors', '.ckpt', '.bin', '.pt', '.msgpack', '.gguf'];
+const isWeightFile = (name) => WEIGHT_EXTENSIONS.some((ext) => name.endsWith(ext));
+
+// Walk a snapshot directory recursively. HF stores nested layouts (e.g.
+// `text_encoder/model.safetensors`) so a flat readdir would miss real
+// weight files and falsely report a model as not cached.
+async function collectWeightFiles(dir, out) {
+ let entries;
+ try {
+ entries = await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ await collectWeightFiles(path, out);
+ } else if (isWeightFile(entry.name)) {
+ out.push({ name: entry.name, path });
+ }
+ }
+}
+
+// Returns the path of the most recently modified snapshot under a repo, or
+// null if no snapshots exist. HF writes snapshots/<sha>/ on every revision
+// pull; the latest mtime is the most recently downloaded.
+async function latestSnapshotDir(repoDir) {
+ const snapshotsRoot = join(repoDir, 'snapshots');
+ let entries;
+ try {
+ entries = await fs.readdir(snapshotsRoot, { withFileTypes: true });
+ } catch {
+ return null;
+ }
+ let latest = null;
+ let latestMs = -1;
+ await Promise.all(entries.map(async (entry) => {
+ if (!entry.isDirectory()) return;
+ const p = join(snapshotsRoot, entry.name);
+ const s = await fs.stat(p).catch(() => null);
+ if (!s) return;
+ if (s.mtimeMs > latestMs) {
+ latestMs = s.mtimeMs;
+ latest = p;
+ }
+ }));
+ return latest;
+}
+
+// Returns `{ cached, sizeBytes, snapshotPath }`. `cached` is true only when
+// the snapshot directory contains at least one weight file AND every weight
+// file in the snapshot resolves to a non-zero blob. `sizeBytes` is the sum
+// of resolved weight-blob sizes (config/tokenizer files are tiny and ignored
+// so the displayed footprint reflects the user-meaningful download).
+export async function inspectModelCache(repoId) {
+ if (!repoId || typeof repoId !== 'string') {
+ return { cached: false, sizeBytes: 0, snapshotPath: null };
+ }
+ const root = getHfCacheRoot();
+ const repoDir = join(root, repoToDirName(repoId));
+ const snapshotPath = await latestSnapshotDir(repoDir);
+ if (!snapshotPath) {
+ return { cached: false, sizeBytes: 0, snapshotPath: null };
+ }
+ const weights = [];
+ await collectWeightFiles(snapshotPath, weights);
+ if (weights.length === 0) {
+ return { cached: false, sizeBytes: 0, snapshotPath };
+ }
+ // Each snapshot file is a symlink into ../../blobs/<hash>; a stat that
+ // follows the link surfaces dangling-symlink failures (interrupted
+ // download) as a throw. One stat per file covers both broken-link
+ // detection and size accounting.
+ let sizeBytes = 0;
+ for (const file of weights) {
+ const s = await fs.stat(file.path).catch(() => null);
+ if (!s || s.size === 0) {
+ return { cached: false, sizeBytes: 0, snapshotPath };
+ }
+ sizeBytes += s.size;
+ }
+ return { cached: true, sizeBytes, snapshotPath };
+}
+
+export const isModelCached = async (repoId) => (await inspectModelCache(repoId)).cached;
diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.js
new file mode 100644
index 0000000000..8e0710f4cd
--- /dev/null
+++ b/server/lib/hfCache.test.js
@@ -0,0 +1,134 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { inspectModelCache, getHfCacheRoot, isModelCached } from './hfCache.js';
+
+// Build a fake HF cache layout under tmp so we can assert the inspector
+// without touching the user's real ~/.cache/huggingface/hub. Snapshot files
+// are symlinked into ../../blobs/ exactly as huggingface_hub writes them.
+function buildFakeCache({ repoId, snapshots, partial = false }) {
+ const root = mkdtempSync(join(tmpdir(), 'hfcache-test-'));
+ const repoDir = join(root, `models--${repoId.replace(/\//g, '--')}`);
+ const blobsDir = join(repoDir, 'blobs');
+ mkdirSync(blobsDir, { recursive: true });
+ for (const [sha, files] of Object.entries(snapshots)) {
+ const snapDir = join(repoDir, 'snapshots', sha);
+ mkdirSync(snapDir, { recursive: true });
+ for (const [filename, bytes] of Object.entries(files)) {
+ const blobName = `${sha}-${filename}.blob`;
+ const blobPath = join(blobsDir, blobName);
+ if (!(partial && filename.endsWith('.safetensors'))) {
+ writeFileSync(blobPath, Buffer.alloc(bytes));
+ }
+ symlinkSync(blobPath, join(snapDir, filename));
+ }
+ }
+ return { root, repoDir };
+}
+
+describe('hfCache', () => {
+ let originalEnv;
+
+ beforeEach(() => {
+ originalEnv = { HF_HUB_CACHE: process.env.HF_HUB_CACHE, HF_HOME: process.env.HF_HOME };
+ });
+
+ afterEach(() => {
+ process.env.HF_HUB_CACHE = originalEnv.HF_HUB_CACHE;
+ process.env.HF_HOME = originalEnv.HF_HOME;
+ if (originalEnv.HF_HUB_CACHE === undefined) delete process.env.HF_HUB_CACHE;
+ if (originalEnv.HF_HOME === undefined) delete process.env.HF_HOME;
+ });
+
+ it('resolves cache root with precedence HF_HUB_CACHE > HF_HOME/hub > ~/.cache', () => {
+ process.env.HF_HUB_CACHE = '/explicit/hub';
+ expect(getHfCacheRoot()).toBe('/explicit/hub');
+
+ delete process.env.HF_HUB_CACHE;
+ process.env.HF_HOME = '/custom/hf';
+ expect(getHfCacheRoot()).toBe('/custom/hf/hub');
+
+ delete process.env.HF_HOME;
+ expect(getHfCacheRoot()).toMatch(/\.cache\/huggingface\/hub$/);
+ });
+
+ it('reports cached=false for missing repo dir', async () => {
+ process.env.HF_HUB_CACHE = mkdtempSync(join(tmpdir(), 'hfcache-empty-'));
+ const result = await inspectModelCache('foo/bar');
+ expect(result.cached).toBe(false);
+ expect(result.sizeBytes).toBe(0);
+ rmSync(process.env.HF_HUB_CACHE, { recursive: true, force: true });
+ });
+
+ it('reports cached=true and sums weight-file sizes when snapshot is complete', async () => {
+ const { root } = buildFakeCache({
+ repoId: 'org/model',
+ snapshots: {
+ 'abc123': {
+ 'config.json': 1024,
+ 'model.safetensors': 4096,
+ 'tokenizer.json': 512,
+ },
+ },
+ });
+ process.env.HF_HUB_CACHE = root;
+ const result = await inspectModelCache('org/model');
+ expect(result.cached).toBe(true);
+ expect(result.sizeBytes).toBe(4096); // weight files only, config/tokenizer excluded
+ expect(result.snapshotPath).toContain('snapshots/abc123');
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('reports cached=false when snapshot has no weight files (config-only stub)', async () => {
+ const { root } = buildFakeCache({
+ repoId: 'org/configonly',
+ snapshots: { 'sha1': { 'config.json': 200 } },
+ });
+ process.env.HF_HUB_CACHE = root;
+ expect((await inspectModelCache('org/configonly')).cached).toBe(false);
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('reports cached=false for partial download (dangling weight symlink)', async () => {
+ const { root } = buildFakeCache({
+ repoId: 'org/partial',
+ snapshots: {
+ 'sha2': { 'config.json': 200, 'model.safetensors': 4096 },
+ },
+ partial: true,
+ });
+ process.env.HF_HUB_CACHE = root;
+ expect((await inspectModelCache('org/partial')).cached).toBe(false);
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('walks nested snapshot subdirectories (e.g. text_encoder/model.safetensors)', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'hfcache-nested-'));
+ const repoDir = join(root, 'models--org--nested');
+ const blobs = join(repoDir, 'blobs');
+ const snap = join(repoDir, 'snapshots', 'shaN');
+ mkdirSync(blobs, { recursive: true });
+ mkdirSync(join(snap, 'text_encoder'), { recursive: true });
+ const blobPath = join(blobs, 'encoder.blob');
+ writeFileSync(blobPath, Buffer.alloc(8192));
+ symlinkSync(blobPath, join(snap, 'text_encoder', 'model.safetensors'));
+ process.env.HF_HUB_CACHE = root;
+ const result = await inspectModelCache('org/nested');
+ expect(result.cached).toBe(true);
+ expect(result.sizeBytes).toBe(8192);
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('isModelCached is a boolean wrapper', async () => {
+ process.env.HF_HUB_CACHE = mkdtempSync(join(tmpdir(), 'hfcache-bool-'));
+ expect(await isModelCached('does/notexist')).toBe(false);
+ rmSync(process.env.HF_HUB_CACHE, { recursive: true, force: true });
+ });
+
+ it('returns cached=false for empty/invalid repoId without throwing', async () => {
+ expect((await inspectModelCache('')).cached).toBe(false);
+ expect((await inspectModelCache(null)).cached).toBe(false);
+ expect((await inspectModelCache(undefined)).cached).toBe(false);
+ });
+});
diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.js
new file mode 100644
index 0000000000..eb18f77579
--- /dev/null
+++ b/server/lib/hfDownload.js
@@ -0,0 +1,161 @@
+// Pre-download a HuggingFace repo snapshot into the local HF cache, with
+// SSE-friendly progress events. Used by the inline "Download" badge on
+// the image + video gen forms so users don't discover a multi-GB pull
+// the first time they hit Render.
+//
+// Picks a Python venv that has `huggingface_hub` installed. The FLUX.2 venv
+// is the preferred choice (always installed when image gen is set up); the
+// mflux/legacy pythonPath is the fallback for installs that use only mflux.
+//
+// Wire protocol parses the stdout/stderr lines from scripts/hf_download_repo.py:
+// STAGE:list -> { type: 'stage', stage: 'list' }
+// STAGE:download:<n>/<total>:<file> -> stage + progress n/total
+// STAGE:complete:<bytes> -> { type: 'complete', sizeBytes }
+// USER_ERROR:<kind>:<repo> -> typed-error capture
+// ❌ <prose> -> errorMessage
+// Unknown lines fall through as raw `{ type: 'log', message }`.
+
+import { spawn } from 'node:child_process';
+import { join } from 'node:path';
+import { resolveFlux2Python, isFlux2VenvHealthy } from './pythonSetup.js';
+import { PATHS } from './fileUtils.js';
+import { getHfTokenInfo } from './hfToken.js';
+import { getSettings } from '../services/settings.js';
+
+const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');
+
+// Resolve a Python interpreter with huggingface_hub installed. Order: FLUX.2
+// venv (the modern path; always has hf_hub via diffusers), then the
+// settings.imageGen.local.pythonPath (mflux installs). Returns null if
+// neither is available — the caller surfaces a user-facing error rather
+// than silently failing the download.
+//
+// Health-gate the FLUX.2 venv: an interrupted install leaves the binary in
+// place but no packages, and resolveFlux2Python() alone would still return
+// that broken interpreter. Every download would then fail on the broken
+// venv before reaching the working mflux pythonPath.
+export async function resolveHfDownloadPython() {
+ if (resolveFlux2Python() && await isFlux2VenvHealthy()) return resolveFlux2Python();
+ const settings = await getSettings();
+ return settings?.imageGen?.local?.pythonPath || null;
+}
+
+// Returns `{ promise, kill }`. The promise resolves with `{ ok, sizeBytes,
+// errorKind, errorMessage }`. `kill()` SIGTERMs the python child so the
+// SSE handler can stop the download when the EventSource client closes.
+export function downloadHfRepo({ repo, revision = null, onEvent }) {
+ let proc = null;
+ let killed = false;
+ let errorKind = null;
+ let errorMessage = null;
+ let sizeBytes = 0;
+
+ const promise = (async () => {
+ const pythonPath = await resolveHfDownloadPython();
+ if (!pythonPath) {
+ const msg = 'No Python venv with huggingface_hub found. Install the FLUX.2 venv from Image Gen settings first.';
+ onEvent({ type: 'error', message: msg, kind: 'venv_missing' });
+ return { ok: false, errorKind: 'venv_missing', errorMessage: msg };
+ }
+ const { token } = await getHfTokenInfo();
+ const env = { ...process.env };
+ // The Python helper looks up the token by env-var name so we don't have
+ // to pass secrets on argv. Strip any stale value when the user has
+ // explicitly cleared their stored token.
+ if (token) env.HF_TOKEN = token;
+ else delete env.HF_TOKEN;
+
+ const args = [HELPER_SCRIPT, '--repo', repo, '--token-env', 'HF_TOKEN'];
+ if (revision) args.push('--revision', revision);
+
+ onEvent({ type: 'stage', stage: 'starting', message: `Downloading ${repo}…` });
+
+ return new Promise((resolve) => {
+ proc = spawn(pythonPath, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
+
+ const handleLine = (raw) => {
+ const line = raw.trim();
+ if (!line) return;
+ if (line.startsWith('STAGE:')) {
+ // STAGE:<name>[:rest]. Special-case the file-progress + complete
+ // shapes so the UI can render a real progress bar; everything
+ // else falls through as a generic stage event.
+ const body = line.slice('STAGE:'.length);
+ const colon = body.indexOf(':');
+ const stage = colon === -1 ? body : body.slice(0, colon);
+ const detail = colon === -1 ? '' : body.slice(colon + 1);
+ if (stage === 'download') {
+ // detail looks like `3/47:model-00003-of-00047.safetensors`
+ const m = detail.match(/^(\d+)\/(\d+):(.+)$/);
+ if (m) {
+ const step = parseInt(m[1], 10);
+ const total = parseInt(m[2], 10);
+ onEvent({
+ type: 'progress',
+ progress: total > 0 ? step / total : 0,
+ step,
+ total,
+ file: m[3],
+ });
+ return;
+ }
+ }
+ if (stage === 'complete') {
+ const bytes = parseInt(detail, 10);
+ if (Number.isFinite(bytes)) sizeBytes = bytes;
+ // Don't emit a `complete` event here — wait for the close
+ // handler so a successful exit code is required.
+ return;
+ }
+ onEvent({ type: 'stage', stage, detail });
+ return;
+ }
+ if (line.startsWith('USER_ERROR:')) {
+ const body = line.slice('USER_ERROR:'.length);
+ const colon = body.indexOf(':');
+ errorKind = colon === -1 ? body : body.slice(0, colon);
+ return;
+ }
+ if (line.startsWith('❌')) {
+ errorMessage = line.replace(/^❌\s*/, '');
+ return;
+ }
+ if (line.startsWith('DOWNLOAD:')) return; // mirrored by STAGE:download
+ onEvent({ type: 'log', message: line });
+ };
+
+ proc.stderr.on('data', (chunk) => {
+ for (const l of chunk.toString().split(/[\r\n]+/)) handleLine(l);
+ });
+ proc.stdout.on('data', (chunk) => {
+ for (const l of chunk.toString().split(/[\r\n]+/)) handleLine(l);
+ });
+ proc.on('error', (err) => {
+ const msg = `Failed to spawn python: ${err.message}`;
+ onEvent({ type: 'error', message: msg, kind: 'spawn_failed' });
+ resolve({ ok: false, errorKind: 'spawn_failed', errorMessage: msg });
+ });
+ proc.on('close', (code, signal) => {
+ if (killed) {
+ onEvent({ type: 'error', message: 'Cancelled', kind: 'cancelled' });
+ return resolve({ ok: false, errorKind: 'cancelled', errorMessage: 'Cancelled' });
+ }
+ if (code === 0) {
+ onEvent({ type: 'complete', sizeBytes, repo });
+ return resolve({ ok: true, sizeBytes });
+ }
+ const msg = errorMessage || (signal ? `Killed by ${signal}` : `Exit code ${code}`);
+ onEvent({ type: 'error', message: msg, kind: errorKind, repo });
+ return resolve({ ok: false, errorKind, errorMessage: msg });
+ });
+ });
+ })();
+
+ return {
+ promise,
+ kill: () => {
+ killed = true;
+ if (proc && !proc.killed) proc.kill('SIGTERM');
+ },
+ };
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index adc55601a4..87fd7a2749 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -58,6 +58,9 @@ export * from './cliProviderRun.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './hfToken.js';
+export * from './hfCache.js';
+export * from './hfDownload.js';
+export * from './sseDownload.js';
export * from './mediaModels.js';
export * from './promptPartials.js';
export * from './promptRunner.js';
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 21b93af0cf..717cd28ebf 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -551,6 +551,38 @@ export const getImageModels = () => {
return (reg.image || []).filter((m) => !platformBroken(m.broken));
};
+// Map a registry entry to the HuggingFace repo id whose weights need to be
+// resident on disk before generation can run. Used by the download-status
+// badge on the image/video gen forms.
+//
+// Most entries already carry `repo` directly. mflux's legacy `dev` / `schnell`
+// ids predate the field and resolve to the canonical Black Forest Labs repos
+// at runtime via the `mflux-generate` CLI — hardcode those two so the badge
+// can probe their HF cache the same way as every other model.
+const MFLUX_LEGACY_REPOS = {
+ dev: 'black-forest-labs/FLUX.1-dev',
+ schnell: 'black-forest-labs/FLUX.1-schnell',
+};
+
+export const repoForModel = (model) => {
+ if (!model || typeof model !== 'object') return null;
+ if (isNonEmptyString(model.repo)) return model.repo;
+ if (MFLUX_LEGACY_REPOS[model.id]) return MFLUX_LEGACY_REPOS[model.id];
+ return null;
+};
+
+// `getTextEncoderRepo()` can return either an HF repo id (`org/name`) or a
+// resolved local filesystem path when the registry entry has a `localPath`
+// override. Anything that starts with `/` or `~` is a local path; only
+// `org/name` is a valid input to HF-cache inspection / download endpoints.
+export const isHfRepoId = (value) => (
+ typeof value === 'string'
+ && value.length > 0
+ && !value.startsWith('/')
+ && !value.startsWith('~')
+ && value.includes('/')
+);
+
// Resolve the active text encoder to a path mlx_video can pass via
// --text-encoder-repo. Prefers `localPath` (e.g. an existing LM Studio
// install) when it exists; otherwise returns the HF repo id which mlx_video
diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.js
new file mode 100644
index 0000000000..284079b37b
--- /dev/null
+++ b/server/lib/sseDownload.js
@@ -0,0 +1,44 @@
+// 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.
+
+import { inspectModelCache } from './hfCache.js';
+import { downloadHfRepo } from './hfDownload.js';
+
+const inFlight = new Map(); // repo -> { promise, kill }
+
+const SSE_HEADERS = {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+};
+
+export async function startHfDownloadStream({ req, res, repo, alreadyDownloadedMessage }) {
+ res.writeHead(200, SSE_HEADERS);
+ const send = (event) => {
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
+ };
+ const safeEnd = () => { if (!res.writableEnded) res.end(); };
+
+ const existing = await inspectModelCache(repo);
+ if (existing.cached) {
+ send({ type: 'complete', message: alreadyDownloadedMessage || `${repo} already downloaded.`, repo, sizeBytes: existing.sizeBytes });
+ return safeEnd();
+ }
+ if (inFlight.has(repo)) {
+ send({ type: 'error', message: `Another download for ${repo} is already running.`, kind: 'already_running' });
+ return safeEnd();
+ }
+
+ const handle = downloadHfRepo({ repo, onEvent: send });
+ inFlight.set(repo, handle);
+ handle.promise.finally(() => {
+ inFlight.delete(repo);
+ safeEnd();
+ });
+ req.on('close', () => { handle.kill(); safeEnd(); });
+}
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index d647793022..6e88a4eb05 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -23,7 +23,9 @@ import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveImageCleaners } from '..
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { getSettings, saveSettings } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
-import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
+import { getImageModels, isFlux2, isZImage, isErnie, repoForModel } from '../lib/mediaModels.js';
+import { inspectModelCache } from '../lib/hfCache.js';
+import { startHfDownloadStream } from '../lib/sseDownload.js';
import {
REQUIRED_PACKAGES, detectPython, installPackages,
createVenv, isAllowedPython, pipNameFor,
@@ -379,6 +381,42 @@ router.get('/models', (_req, res) => {
res.json(local.listImageModels());
});
+// Per-model download status. Returns `[{ id, repo, cached, sizeBytes }]` so
+// the form can show an inline "Available" or "Download" badge next to the
+// model picker — without waiting until a render to discover a multi-GB HF
+// download. Models without a known HF repo (typically third-party custom
+// entries with `runner: 'mflux'` and a non-default name) report
+// `cached: null` so the UI can render "unknown" rather than a misleading
+// "not downloaded" state. Lazy generation still works regardless of badge.
+router.get('/models/status', asyncHandler(async (_req, res) => {
+ const statuses = await Promise.all(getImageModels().map(async (m) => {
+ const repo = repoForModel(m);
+ if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0 };
+ const { cached, sizeBytes } = await inspectModelCache(repo);
+ return { id: m.id, repo, cached, sizeBytes };
+ }));
+ res.json(statuses);
+}));
+
+// SSE-driven model download. Cancels the python child if the client
+// disconnects mid-download; cross-route in-flight dedupe lives in
+// startHfDownloadStream so a FLUX repo shared with video gen can't spawn
+// two concurrent children.
+router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
+ const model = getImageModels().find((m) => m.id === req.params.modelId);
+ if (!model) {
+ return res.status(404).json({ error: `Unknown model id: ${req.params.modelId}` });
+ }
+ const repo = repoForModel(model);
+ if (!repo) {
+ return res.status(400).json({
+ error: `Model "${model.id}" has no HuggingFace repo on file — cannot pre-download.`,
+ code: 'NO_REPO_FOR_MODEL',
+ });
+ }
+ await startHfDownloadStream({ req, res, repo });
+}));
+
router.get('/loras', asyncHandler(async (_req, res) => {
res.json(await local.listLoraFilenames());
}));
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index c04150becb..4b2e644e09 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -30,6 +30,9 @@ import {
DEFAULT_NUM_FRAMES,
} from '../services/videoGen/local.js';
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
+import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
+import { inspectModelCache } from '../lib/hfCache.js';
+import { startHfDownloadStream } from '../lib/sseDownload.js';
const router = Router();
@@ -178,6 +181,51 @@ router.get('/models', (_req, res) => {
res.json(listVideoModels());
});
+// Per-model download status — see /api/image-gen/models/status for the
+// shape contract. We also surface the active text-encoder repo so the
+// video form can warn when the Gemma encoder isn't downloaded yet (a
+// surprise multi-GB pull on top of the model itself).
+router.get('/models/status', asyncHandler(async (_req, res) => {
+ // Text encoder is shared across all video renders. A registry entry with
+ // `localPath` (e.g. an LM Studio install) trumps the HF cache check, so
+ // surface both the repo-cache status and the resolved local path so the UI
+ // can distinguish "not downloaded" from "served from LM Studio".
+ const encoderRepo = getTextEncoderRepo();
+ const [models, encoderInspection] = await Promise.all([
+ Promise.all(listVideoModels().map(async (m) => {
+ const repo = repoForModel(m);
+ if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0 };
+ const { cached, sizeBytes } = await inspectModelCache(repo);
+ return { id: m.id, repo, cached, sizeBytes };
+ })),
+ isHfRepoId(encoderRepo) ? inspectModelCache(encoderRepo) : Promise.resolve(null),
+ ]);
+ const textEncoder = encoderInspection
+ ? { repo: encoderRepo, ...encoderInspection }
+ : { repo: encoderRepo, cached: true, sizeBytes: 0 };
+ res.json({ models, textEncoder });
+}));
+
+router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
+ const model = listVideoModels().find((m) => m.id === req.params.modelId);
+ if (!model) return res.status(404).json({ error: `Unknown video model: ${req.params.modelId}` });
+ const repo = repoForModel(model);
+ if (!repo) return res.status(400).json({ error: `Model "${model.id}" has no HuggingFace repo on file.`, code: 'NO_REPO_FOR_MODEL' });
+ await startHfDownloadStream({ req, res, repo });
+}));
+
+// Text encoder pre-fetch. The Gemma encoder is a separate ~7-25 GB pull from
+// the video model itself, so it gets its own button on the video form.
+router.get('/text-encoder/download', asyncHandler(async (req, res) => {
+ const repo = getTextEncoderRepo();
+ // Local-path encoders (LM Studio) are not downloadable — they're served
+ // off disk and the status endpoint already reports cached: true for them.
+ if (!isHfRepoId(repo)) {
+ return res.status(400).json({ error: 'Active text encoder is a local-path entry, not an HF repo.', code: 'NOT_DOWNLOADABLE' });
+ }
+ await startHfDownloadStream({ req, res, repo });
+}));
+
router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// Pre-enqueue cleanup hook: every throw path below MUST drop ALL multipart
// temp uploads (the parser wrote them before this handler ran). Without
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index af0b2a8864..c93d138e5e 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -64,7 +64,7 @@ vi.mock('../lib/multipart.js', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
- PATHS: { images: '/mock/images', videos: '/mock/videos', uploads: '/mock/uploads' },
+ PATHS: { root: '/mock', data: '/mock/data', images: '/mock/images', videos: '/mock/videos', uploads: '/mock/uploads' },
// Route awaits ensureDir before staging the upload; no-op for tests since
// we mock copyFile too.
ensureDir: vi.fn(async () => {}),