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
add self-service install/manage of image+video base models from HuggingFace
[._.]/ Adam Eivye6d678689413
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9b3525df44..7bf1cfe16f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -71,6 +71,7 @@- **[issue-2196] Video Gen now takes an exact custom Width×Height.** The `/media/video` page only offered a 9-item resolution preset dropdown, so a size the presets didn't cover was only reachable via URL params, remix/continue, or aspect-snap on upload. Two numeric Width and Height inputs now sit beside the preset select — type any dimensions and the render uses them (the server still rounds each down to a multiple of 64 and enforces the per-tier pixel budget). Uploading a source image still auto-snaps the size to the image's aspect ratio by default, until you take the dimensions into your own hands.- **[issue-2197] First-run model downloads now show GB progress instead of raw text.** The video and image generation handlers now parse byte sizes from `DOWNLOAD:` markers and tqdm progress bars, displaying a formatted "Downloading model · first run · X.X GB / Y.Y GB" message instead of the raw protocol output. Progress frames include `downloadedBytes`/`totalBytes` numeric fields so the UI can build download progress bars. Phase tracking (`isDownloading`, `currentPhase`) ensures the formatting only applies during actual download phases.- **[issue-2198] A wedged local video render that produces no output is now killed automatically instead of pinning the GPU queue.** The existing completion watchdog only guards a render that finishes and then hangs in teardown — it never armed for a render that stalls *before emitting anything* (a known MLX/Metal failure mode where the job never exits and never prints), which held the serialized GPU lane until you manually canceled. A new idle-stall deadline arms at spawn and resets on every child output line (stdout or stderr); if a render produces no output for a generous window (default 10 minutes, tunable via `VIDEOGEN_IDLE_STALL_MS`) it's SIGKILLed and surfaced as a failed job, so the next queued render can start. The window is deliberately generous so a legitimately slow first-token render (weights load + Metal kernel compile) is never killed, and a manual cancel still works and always wins. (`server/services/videoGen/local.js`)+- **[issue-2124] Add and manage custom image/video base models from HuggingFace — no more hand-editing a JSON file and restarting.** Base models used to be addable only by editing `data/media-models.json` and restarting the server, while LoRAs had a first-class "install from HuggingFace" flow. The Media Models page (`/media/models`) now has that same self-service experience for base models: paste a HuggingFace repo (URL or `org/name`), and PortOS inspects its files + model card to detect whether it's an image or video model and which runtime loads it, then appends a registry entry and hot-reloads it live (no restart). The catalog lists every built-in model read-only alongside your added ones, which you can rename, retune (steps/guidance), or remove inline. Formats no runtime can load are **refused up front with a clear reason** — a GGUF-only repo (e.g. `unsloth/LTX-2.3-GGUF`), a Wan or HunyuanVideo repo (which need a dedicated BYO venv), or anything unclassifiable — so a bad add can never wedge the model picker. For a GGUF LTX build specifically, the refusal points you at the native MLX Q4 model PortOS already ships. The multi-GB weight download still happens through the existing per-model download badge on the gen form once the entry exists.## MeatSpace POSTdiff --git a/client/src/pages/MediaModels.jsx b/client/src/pages/MediaModels.jsxindex fb179acb66..b66b80b2d0 100644--- a/client/src/pages/MediaModels.jsx+++ b/client/src/pages/MediaModels.jsx@@ -1,27 +1,54 @@/**- * Media Models — view + clean up cached HuggingFace model weights and LoRA files.+ * Media Models — manage the model catalog + clean up cached weights.*- * HF models live at HF's standard location (`~/.cache/huggingface/hub` unless- * the user set HF_HOME). PortOS doesn't move or symlink them — it just reads- * sizes for display and offers Delete to free disk space. LoRAs sit in- * `data/loras/` and are tracked by DataManager.+ * Two concerns share this page:+ * 1. Model catalog (registry): the image/video base models that can be picked+ * in the gen forms. Built-in entries are read-only; user-added entries+ * (installed from HuggingFace) are editable/removable. Adding a model here+ * appends a `data/media-models.json` entry and hot-reloads the registry —+ * no server restart (issue #2124).+ * 2. Cached weights: HF models live at HF's standard location+ * (`~/.cache/huggingface/hub` unless HF_HOME is set). PortOS doesn't move or+ * symlink them — it reads sizes for display and offers Delete to free disk.+ * LoRAs sit in `data/loras/`.*/import { useState, useEffect, useCallback } from 'react';-import { AlertTriangle, Trash2, Image as ImageIcon, Film } from 'lucide-react';+import { AlertTriangle, Trash2, Image as ImageIcon, Film, Plus, Pencil, Lock, X, Check } from 'lucide-react';import toast from '../components/ui/Toast';-import { listCachedModels, deleteCachedModel, deleteLora } from '../services/api';+import {+ listCachedModels,+ deleteCachedModel,+ deleteLora,+ listMediaModelRegistry,+ addMediaModelFromHf,+ patchCustomMediaModel,+ removeCustomMediaModel,+} from '../services/api';export default function MediaModels() {const [data, setData] = useState({ models: [], loras: [], hubDir: '', diskUsage: {} });+ const [registry, setRegistry] = useState({ video: [], image: [] });const [busy, setBusy] = useState(null);const [error, setError] = useState(null);+ // Add-from-HF form state+ const [hfUrl, setHfUrl] = useState('');+ const [adding, setAdding] = useState(false);+ const [addError, setAddError] = useState(null);++ // Inline edit state for a user-added entry+ const [editId, setEditId] = useState(null);+ const [editFields, setEditFields] = useState({ name: '', steps: '', guidance: '' });+const refresh = useCallback(() => {setError(null);listCachedModels().then(setData).catch(err => setError(err?.message || 'Failed to load media models'));+ listMediaModelRegistry()+ .then(setRegistry)+ .catch(() => {}); // registry is secondary — cache view still renders on failure}, []);useEffect(() => { refresh(); }, [refresh]);@@ -48,6 +75,71 @@ export default function MediaModels() {.finally(() => setBusy(null));};+ const handleAddFromHf = async (e) => {+ e?.preventDefault?.();+ const url = hfUrl.trim();+ if (!url) return;+ setAdding(true);+ setAddError(null);+ await addMediaModelFromHf({ url, silent: true })+ .then((result) => {+ toast.success(`Added ${result?.entry?.name || 'model'} — download its weights from the gen form`);+ setHfUrl('');+ // The response carries the server-derived entry + kind, so update the+ // registry list locally instead of refetching (both round-trips).+ const kind = result?.kind === 'image' ? 'image' : 'video';+ const entry = { ...result.entry, kind, builtIn: false };+ setRegistry((r) => ({ ...r, [kind]: [...r[kind], entry] }));+ })+ .catch((err) => setAddError(err?.message || 'Failed to add model'))+ .finally(() => setAdding(false));+ };++ const startEdit = (m) => {+ setEditId(m.id);+ setEditFields({+ name: m.name ?? '',+ steps: m.steps ?? '',+ guidance: m.guidance ?? '',+ });+ };++ const cancelEdit = () => { setEditId(null); };++ const saveEdit = async (id) => {+ setBusy(id);+ const patch = {+ name: editFields.name.trim(),+ steps: Number(editFields.steps),+ guidance: Number(editFields.guidance),+ };+ await patchCustomMediaModel(id, patch)+ .then((updated) => {+ toast.success('Model updated');+ setEditId(null);+ // Merge the returned fields into the matching registry row locally+ // instead of refetching the whole catalog + cache.+ const merge = (list) => list.map((m) => (m.id === id ? { ...m, ...updated } : m));+ setRegistry((r) => ({ video: merge(r.video), image: merge(r.image) }));+ })+ .catch((err) => toast.error(err.message || 'Update failed'))+ .finally(() => setBusy(null));+ };++ const handleRemoveCustom = async (id) => {+ setBusy(id);+ await removeCustomMediaModel(id)+ .then(() => {+ toast.success('Custom model removed');+ setRegistry((r) => ({+ video: r.video.filter((m) => m.id !== id),+ image: r.image.filter((m) => m.id !== id),+ }));+ })+ .catch((err) => toast.error(err.message || 'Remove failed'))+ .finally(() => setBusy(null));+ };+if (error) {return (<div className="p-6 text-center">@@ -60,6 +152,89 @@ export default function MediaModels() {);}+ const renderRegistryRow = (m) => {+ const isEditing = editId === m.id;+ return (+ <div key={`${m.kind}-${m.id}`} className="bg-port-bg border border-port-border rounded-lg p-3">+ {isEditing ? (+ <div className="space-y-2">+ <div>+ <label htmlFor={`edit-name-${m.id}`} className="block text-xs text-gray-400 mb-1">Name</label>+ <input+ id={`edit-name-${m.id}`}+ type="text"+ value={editFields.name}+ onChange={(e) => setEditFields((f) => ({ ...f, name: e.target.value }))}+ className="w-full px-2 py-1 text-sm bg-port-card border border-port-border rounded text-white"+ />+ </div>+ <div className="flex gap-2">+ <div className="flex-1">+ <label htmlFor={`edit-steps-${m.id}`} className="block text-xs text-gray-400 mb-1">Steps</label>+ <input+ id={`edit-steps-${m.id}`}+ type="number"+ min="1"+ max="200"+ value={editFields.steps}+ onChange={(e) => setEditFields((f) => ({ ...f, steps: e.target.value }))}+ className="w-full px-2 py-1 text-sm bg-port-card border border-port-border rounded text-white"+ />+ </div>+ <div className="flex-1">+ <label htmlFor={`edit-guidance-${m.id}`} className="block text-xs text-gray-400 mb-1">Guidance</label>+ <input+ id={`edit-guidance-${m.id}`}+ type="number"+ min="0"+ max="30"+ step="0.5"+ value={editFields.guidance}+ onChange={(e) => setEditFields((f) => ({ ...f, guidance: e.target.value }))}+ className="w-full px-2 py-1 text-sm bg-port-card border border-port-border rounded text-white"+ />+ </div>+ </div>+ <div className="flex gap-2 justify-end">+ <button type="button" onClick={cancelEdit} disabled={busy === m.id} className="px-3 py-1.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:bg-port-bg flex items-center gap-1">+ <X className="w-3 h-3" /> Cancel+ </button>+ <button type="button" onClick={() => saveEdit(m.id)} disabled={busy === m.id} className="px-3 py-1.5 text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded disabled:opacity-50 flex items-center gap-1">+ <Check className="w-3 h-3" /> {busy === m.id ? 'Saving…' : 'Save'}+ </button>+ </div>+ </div>+ ) : (+ <div className="flex items-center gap-3">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate flex items-center gap-2">+ {m.name}+ {m.builtIn && <Lock className="w-3 h-3 text-gray-500 shrink-0" title="Built-in (read-only)" />}+ {m.deprecated && <span className="text-[10px] px-1 rounded bg-port-warning/20 text-port-warning">legacy</span>}+ </div>+ <div className="text-xs text-gray-500 truncate">+ {m.repo || m.id}+ {' · '}+ {m.runtime || m.runner || m.kind}+ {m.steps != null && ` · ${m.steps} steps`}+ </div>+ </div>+ {!m.builtIn && (+ <div className="flex gap-1 shrink-0">+ <button type="button" onClick={() => startEdit(m)} disabled={busy === m.id} className="px-2 py-1.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:bg-port-bg disabled:opacity-50 flex items-center gap-1">+ <Pencil className="w-3 h-3" /> Edit+ </button>+ <button type="button" onClick={() => handleRemoveCustom(m.id)} disabled={busy === m.id} className="px-2 py-1.5 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1">+ <Trash2 className="w-3 h-3" /> {busy === m.id ? '…' : 'Remove'}+ </button>+ </div>+ )}+ </div>+ )}+ </div>+ );+ };+return (<div className="space-y-6"><div className="grid grid-cols-2 md:grid-cols-4 gap-3">@@ -71,6 +246,56 @@ export default function MediaModels() {))}</div>+ {/* Model Catalog — add from HuggingFace + manage user-added entries */}+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">+ <h2 className="text-sm font-medium text-gray-300 flex items-center gap-2">+ <Plus className="w-4 h-4" /> Add a base model from HuggingFace+ </h2>+ <form onSubmit={handleAddFromHf} className="space-y-2">+ <label htmlFor="hf-model-url" className="block text-xs text-gray-400">+ HuggingFace repo (URL or <code>org/name</code>) — safetensors/MLX models only+ </label>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ id="hf-model-url"+ type="text"+ value={hfUrl}+ onChange={(e) => { setHfUrl(e.target.value); setAddError(null); }}+ placeholder="e.g. notapalindrome/ltx23-mlx-av-q4"+ className="flex-1 px-3 py-2 text-sm bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-600"+ />+ <button+ type="submit"+ disabled={adding || !hfUrl.trim()}+ className="px-4 py-2 text-sm bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded-lg disabled:opacity-50 flex items-center justify-center gap-1 shrink-0"+ >+ <Plus className="w-4 h-4" /> {adding ? 'Adding…' : 'Add Model'}+ </button>+ </div>+ {addError && (+ <p className="text-xs text-port-error flex items-start gap-1">+ <AlertTriangle className="w-3 h-3 mt-0.5 shrink-0" /> {addError}+ </p>+ )}+ <p className="text-[11px] text-gray-600">+ GGUF-only, Wan, and HunyuanVideo repos are refused — no PortOS runtime can load them. For a GGUF LTX build, use the native MLX Q4 model instead.+ </p>+ </form>++ {registry.video.length > 0 && (+ <div className="space-y-2">+ <h3 className="text-xs font-medium text-gray-400 flex items-center gap-2"><Film className="w-3 h-3" /> Video models ({registry.video.length})</h3>+ <div className="space-y-2">{registry.video.map(renderRegistryRow)}</div>+ </div>+ )}+ {registry.image.length > 0 && (+ <div className="space-y-2">+ <h3 className="text-xs font-medium text-gray-400 flex items-center gap-2"><ImageIcon className="w-3 h-3" /> Image models ({registry.image.length})</h3>+ <div className="space-y-2">{registry.image.map(renderRegistryRow)}</div>+ </div>+ )}+ </div>+{data.hubDir && (<p className="text-xs text-gray-500">HuggingFace cache: <code className="text-gray-400">{data.hubDir}</code>diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex c2af39d8fc..0d9e00cad6 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -258,6 +258,57 @@ export const listCachedModels = () => request('/image-video/models');export const deleteCachedModel = (dirName) => request(`/image-video/models/hf/${encodeURIComponent(dirName)}`, { method: 'DELETE' });export const deleteLora = (filename) => request(`/image-video/models/lora/${encodeURIComponent(filename)}`, { method: 'DELETE' });+// Media-model REGISTRY (the catalog of pickable image/video base models,+// distinct from listCachedModels which reports on-disk HF cache usage). Returns+// `{ video: [...], image: [...] }` with a `builtIn` flag per entry so the+// manager renders built-ins read-only and user-added entries editable.+export const listMediaModelRegistry = () => request('/image-video/models/registry');++// Search the HuggingFace Hub for candidate base-model repos. `pipeline` scopes+// to e.g. 'text-to-image'/'text-to-video'. `silent` (default true) because the+// caller owns its own error UI. Returns `{ items: [{ id, likes, downloads, pipeline_tag }] }`.+export const searchHfMediaModels = ({ query = '', pipeline, limit, silent = true } = {}) => {+ const params = new URLSearchParams();+ if (query) params.set('query', query);+ if (pipeline) params.set('pipeline', pipeline);+ if (limit) params.set('limit', String(limit));+ const qs = params.toString();+ return request(`/image-video/models/search${qs ? `?${qs}` : ''}`, { silent });+};++// Add a custom base model from a HuggingFace repo. The server strictly refuses+// GGUF-only / wan / hunyuan / unclassifiable repos, so a rejection carries a+// typed `.code` (HF_UNSUPPORTED_FORMAT, HF_UNKNOWN_KIND, HF_UNKNOWN_RUNNER, …)+// the page can surface inline. `kind`/`runtime`/`runner` are optional overrides+// for a mis-detected repo; `name`/`steps`/`guidance` override derived defaults.+// `silent` lets the page route the typed errors into its own inline UI.+export const addMediaModelFromHf = ({ url, kind, runtime, runner, name, steps, guidance, silent = false } = {}) => {+ const body = { url };+ if (kind) body.kind = kind;+ if (runtime) body.runtime = runtime;+ if (runner) body.runner = runner;+ if (name) body.name = name;+ if (steps != null) body.steps = steps;+ if (guidance != null) body.guidance = guidance;+ return request('/image-video/models/install/huggingface', {+ method: 'POST',+ body: JSON.stringify(body),+ silent,+ });+};++// Edit a user-added model's name/steps/guidance. Built-ins return 403.+export const patchCustomMediaModel = (id, patch) => request(`/image-video/models/custom/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+});++// Remove a user-added model entry (weights stay in the HF cache). Built-ins+// return 403; unknown ids 404.+export const removeCustomMediaModel = (id) => request(`/image-video/models/custom/${encodeURIComponent(id)}`, {+ method: 'DELETE',+});+// LoRA manager — Civitai-aware list/install/patch/delete. Reads sidecar// metadata so the manager UI can show trigger words, base model, recommended// scale, preview thumbnail. Used by /media/loras and the Image Gen LoRA picker.diff --git a/server/lib/README.md b/server/lib/README.mdindex a51513cf5d..73855606f4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -205,6 +205,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. || `civitai.js` | Civitai URL parsing + API client. || `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision}`, fetch `/api/models` metadata, pick the `.safetensors`, detect the video-LoRA family (`ltx-video`), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js` for video LoRAs. Pure. |+| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. || `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. || `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). || `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex 30cca299d4..9e5f53c47d 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -21,7 +21,7 @@ import { ServerError } from './errorHandler.js';import { VIDEO_LORA_FAMILIES } from './runners.js';import { readResponseJson } from './readResponseJson.js';-const HF_API = 'https://huggingface.co/api/models';+export const HF_API = 'https://huggingface.co/api/models';const HF_HOSTS = new Set(['huggingface.co', 'www.huggingface.co']);// Parse any HuggingFace ref shape into `{ repo, revision }`:@@ -121,14 +121,19 @@ export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl =return readResponseJson(res);};-// List the `.safetensors` siblings of an HF model response.-const safetensorsSiblings = (model) => {+// All sibling rfilenames of an HF model response (any extension). Shared by the+// LoRA picker and the base-model classifier (huggingfaceModel.js).+export const modelSiblingFilenames = (model) => {const siblings = Array.isArray(model?.siblings) ? model.siblings : [];return siblings.map((s) => (typeof s?.rfilename === 'string' ? s.rfilename : null))- .filter((f) => f && /\.safetensors$/i.test(f));+ .filter(Boolean);};+// List the `.safetensors` siblings of an HF model response.+const safetensorsSiblings = (model) =>+ modelSiblingFilenames(model).filter((f) => /\.safetensors$/i.test(f));+// Pick the LoRA weights file to download. Most LoRA repos ship a single// .safetensors; when several are present we prefer the canonical diffusers// filename, then anything with "lora" in the name, then the first. Throws when@@ -150,21 +155,32 @@ export const pickHfLoraFile = (model) => {return canonical || files[0];};+// Lowercased signal blob for classifying an HF repo: repo id + tags ++// cardData.base_model (string or array). Shared by the LoRA family detector and+// the base-model classifier (huggingfaceModel.js extends it with pipeline_tag /+// library_name). Kept in one place so the two classifiers read the same fields.+export const modelClassificationBlob = ({ repo, model } = {}) => {+ const parts = [String(repo || '').toLowerCase()];+ const tags = Array.isArray(model?.tags) ? model.tags : [];+ for (const t of tags) parts.push(String(t).toLowerCase());+ const baseModel = model?.cardData?.base_model;+ if (typeof baseModel === 'string') parts.push(baseModel.toLowerCase());+ else if (Array.isArray(baseModel)) for (const b of baseModel) parts.push(String(b).toLowerCase());+ return parts.join(' ');+};++// `ltxv` / `ltx-video` / `ltx2` / `ltx-2` / `ltx 2.3` all collapse to ltx.+// Exported so the base-model classifier reuses the exact same LTX detection.+export const LTX_VIDEO_RE = /\bltx[\s._-]?v?(?:ideo)?\b|\bltx[\s._-]?2/;+export const looksLikeLtxVideo = (blob) => LTX_VIDEO_RE.test(blob) || /ltxvideo/.test(blob);+// Detect the PortOS video-LoRA family for an HF repo. LTX-2 / LTX-Video LoRAs// (fal, Lightricks) map to the `ltx-video` family — the only video family with// a working runtime today. Looks at the repo id, HF tags, and the card's// `base_model`. Returns a VIDEO_LORA_FAMILIES value or null (unrecognized →// the installer surfaces a clear error rather than mis-tagging it).export const detectVideoLoraFamily = ({ repo, model } = {}) => {- const haystacks = [String(repo || '').toLowerCase()];- const tags = Array.isArray(model?.tags) ? model.tags : [];- for (const t of tags) haystacks.push(String(t).toLowerCase());- const baseModel = model?.cardData?.base_model;- if (typeof baseModel === 'string') haystacks.push(baseModel.toLowerCase());- else if (Array.isArray(baseModel)) for (const b of baseModel) haystacks.push(String(b).toLowerCase());- const blob = haystacks.join(' ');- // `ltxv` / `ltx-video` / `ltx2` / `ltx-2` / `ltx 2.3` all collapse to ltx.- if (/\bltx[\s._-]?v?(?:ideo)?\b|\bltx[\s._-]?2/.test(blob) || /ltxvideo/.test(blob)) {+ if (looksLikeLtxVideo(modelClassificationBlob({ repo, model }))) {return VIDEO_LORA_FAMILIES.LTX_VIDEO;}return null;diff --git a/server/lib/huggingfaceModel.js b/server/lib/huggingfaceModel.jsnew file mode 100644index 0000000000..d689ea47be--- /dev/null+++ b/server/lib/huggingfaceModel.js@@ -0,0 +1,280 @@+/**+ * HuggingFace base-model classifier — pure helpers for the "add a base model+ * from HuggingFace" flow (issue #2124). The LoRA installer's analogue+ * (huggingfaceLora.js) picks a single .safetensors and tags a video-LoRA+ * family; this module instead inspects a full repo's siblings + card and+ * decides which PortOS image/video *runtime* (if any) can load it, then shapes+ * a `data/media-models.json` registry entry.+ *+ * The overriding design goal is STRICT REFUSAL: a base model that no runtime+ * can load must never land in the registry, because a broken entry wedges the+ * model picker (a 400/"Unknown model" the first time the UI tries to use it).+ * So GGUF-only repos (llama.cpp/ggml — read nowhere in the image/video+ * pipeline), Wan/HunyuanVideo (BYO-venv runtimes provisioned only via+ * scripts/setup-image-video.sh, not self-service), and anything unclassifiable+ * are refused up front with a typed ServerError the UI can surface.+ *+ * No try/catch — errors bubble to centralized middleware; domain errors throw+ * ServerError.+ */++import { ServerError } from './errorHandler.js';+import { RUNNER_FAMILIES } from './runners.js';+import { readResponseJson } from './readResponseJson.js';+import {+ HF_API,+ looksLikeLtxVideo,+ modelClassificationBlob,+ modelSiblingFilenames,+} from './huggingfaceLora.js';++// Search the HF Hub for candidate base-model repos matching a free-text query.+// Backs the manager UI's "search HuggingFace" box (mirrors the LoRA installer's+// GET /search). Returns lightweight `{ id, likes, downloads, pipeline_tag }`+// rows — the caller adds one by pasting its id into the add flow, which does+// the full classify/refuse pass. `pipeline` scopes to `text-to-image` /+// `text-to-video` etc. when provided. fetchImpl is injectable for tests.+export const searchHuggingfaceModels = async (query, { pipeline, limit = 12, fetchImpl = fetch } = {}) => {+ const params = new URLSearchParams();+ const search = typeof query === 'string' ? query.trim() : '';+ if (search) params.set('search', search);+ if (pipeline) params.set('pipeline_tag', pipeline);+ params.set('limit', String(Math.max(1, Math.min(50, limit))));+ params.set('sort', 'downloads');+ const res = await fetchImpl(`${HF_API}?${params.toString()}`, {+ headers: { Accept: 'application/json' },+ });+ if (!res.ok) {+ throw new ServerError(`HuggingFace search failed: ${res.status}`, { status: 502, code: 'HF_SEARCH_FAILED' });+ }+ const rows = await readResponseJson(res, { fallback: [] });+ const list = Array.isArray(rows) ? rows : [];+ return list.map((r) => ({+ id: r?.id || r?.modelId || null,+ likes: Number.isFinite(r?.likes) ? r.likes : 0,+ downloads: Number.isFinite(r?.downloads) ? r.downloads : 0,+ pipeline_tag: typeof r?.pipeline_tag === 'string' ? r.pipeline_tag : null,+ })).filter((r) => r.id);+};++// Video runtimes a user MAY target when adding a model. Both load MLX /+// diffusers `.safetensors`:+// - mlx_video — notapalindrome's single-PyPI-package runtime (T2V/I2V).+// - ltx2 — dgrauet's BYO-venv KeyframeInterpolationPipeline.+// A repo whose detected runtime isn't in this allowlist is refused (see+// detectVideoRuntime + classifyHfMediaModel) — this is the single gate, not a+// default-mlx_video-plus-denylist. Kept in sync with BYOV_RUNTIME_INFO's keys+// in server/services/videoGen/runtimes.js (the classifier stays pure, so the+// self-service exclusions live here rather than importing that stateful module).+export const ADDABLE_VIDEO_RUNTIMES = Object.freeze(['mlx_video', 'ltx2']);++// Detect the underlying video runtime family from the classification blob, so+// the allowlist above can refuse the rest symmetrically with the image path.+// Wan / HunyuanVideo resolve to their (non-addable) runtime ids + the install+// hint the refusal surfaces; LTX resolves to mlx_video (the safetensors/MLX+// default). Returns `{ runtime, installHint? }` or null when no video marker+// matches. A NEW BYO-venv runtime added upstream automatically falls through to+// "not addable" instead of silently registering as a broken mlx_video entry.+const detectVideoRuntime = (blob) => {+ if (/\bwan[\s._-]?2|wan-ai\b/.test(blob) || /\bwan2\.\d/.test(blob)) {+ return { runtime: 'wan22', installHint: 'INSTALL_WAN22=1 bash scripts/setup-image-video.sh' };+ }+ if (/hunyuan/.test(blob)) {+ return { runtime: 'hunyuan', installHint: 'INSTALL_HUNYUAN=1 bash scripts/setup-image-video.sh' };+ }+ if (looksLikeLtxVideo(blob)) return { runtime: 'mlx_video' };+ return null;+};++// Image runners are all self-service (mflux + the shared diffusers runner+// families). Any RUNNER_FAMILIES value is fair game.+export const ADDABLE_IMAGE_RUNNERS = Object.freeze(Object.values(RUNNER_FAMILIES));++// Default steps/guidance per target so an added entry renders sanely without+// the user having to know each pipeline's sweet spot. Mirrors the shipped+// DEFAULT_REGISTRY entries.+const VIDEO_DEFAULTS = { mlx_video: { steps: 25, guidance: 3.0 }, ltx2: { steps: 8, guidance: 3.0 } };+const IMAGE_DEFAULTS = {+ [RUNNER_FAMILIES.MFLUX]: { steps: 20, guidance: 3.5 },+ [RUNNER_FAMILIES.FLUX2]: { steps: 8, guidance: 3.5 },+ [RUNNER_FAMILIES.Z_IMAGE]: { steps: 8, guidance: 1.0 },+ [RUNNER_FAMILIES.ERNIE]: { steps: 50, guidance: 4.0 },+ [RUNNER_FAMILIES.HIDREAM]: { steps: 50, guidance: 5.0 },+ [RUNNER_FAMILIES.QWEN]: { steps: 30, guidance: 4.0 },+};++// Inspect the repo's file list. `.gguf` present (llama.cpp/ggml) is the format+// we can never load in the image/video pipeline; `.safetensors` is required.+// Reuses the shared sibling lister from huggingfaceLora.js.+export const inspectModelFiles = (model) => {+ const names = modelSiblingFilenames(model);+ return {+ hasSafetensors: names.some((f) => /\.safetensors$/i.test(f)),+ hasGguf: names.some((f) => /\.gguf$/i.test(f)),+ fileCount: names.length,+ };+};++// Refuse formats no runtime can load. Throws a typed ServerError; the message+// is user-facing and points at the supported alternative.+const assertLoadableFormat = ({ repo, model }) => {+ const { hasSafetensors, hasGguf } = inspectModelFiles(model);+ if (hasGguf && !hasSafetensors) {+ throw new ServerError(+ `HuggingFace repo "${repo}" ships only GGUF weights, which no PortOS image/video runtime can load (GGUF is used only by the local text-LLM + Whisper paths). If a native MLX/safetensors build of this model exists, add that instead.`,+ { status: 422, code: 'HF_UNSUPPORTED_FORMAT' },+ );+ }+ if (!hasSafetensors) {+ throw new ServerError(+ `HuggingFace repo "${repo}" has no .safetensors weights — only diffusers/MLX safetensors models can be added.`,+ { status: 422, code: 'HF_NO_SAFETENSORS' },+ );+ }+};++// Extend the shared LoRA classification blob with the base-model-only signals+// (pipeline_tag / library_name), so both classifiers read the same core fields.+const classificationBlob = ({ repo, model }) => {+ const extra = [];+ if (typeof model?.pipeline_tag === 'string') extra.push(model.pipeline_tag.toLowerCase());+ if (typeof model?.library_name === 'string') extra.push(model.library_name.toLowerCase());+ return `${modelClassificationBlob({ repo, model })} ${extra.join(' ')}`;+};++// Best-effort image-runner detection from the classification blob. Order+// matters: FLUX.2 before FLUX.1, since "flux.2" contains "flux".+const detectImageRunner = (blob) => {+ if (/flux[\s._-]?2|flux\.2/.test(blob)) return RUNNER_FAMILIES.FLUX2;+ if (/z[\s._-]?image/.test(blob)) return RUNNER_FAMILIES.Z_IMAGE;+ if (/ernie/.test(blob)) return RUNNER_FAMILIES.ERNIE;+ if (/hidream/.test(blob)) return RUNNER_FAMILIES.HIDREAM;+ if (/qwen[\s._-]?image/.test(blob)) return RUNNER_FAMILIES.QWEN;+ if (/flux[\s._-]?1|flux\.1|\bflux\b/.test(blob)) return RUNNER_FAMILIES.MFLUX;+ return null;+};++const isVideoPipelineTag = (model) =>+ typeof model?.pipeline_tag === 'string' && /video/.test(model.pipeline_tag.toLowerCase());+const isImagePipelineTag = (model) =>+ typeof model?.pipeline_tag === 'string' && /text-to-image|image-to-image/.test(model.pipeline_tag.toLowerCase());++/**+ * Classify an HF repo into a proposed PortOS media-model entry.+ *+ * @param {object} args+ * @param {string} args.repo - `org/name` repo id+ * @param {object} args.model - parsed HF `/api/models/{repo}` response+ * @param {'image'|'video'} [args.kind] - explicit kind override+ * @param {string} [args.runtime] - explicit video runtime override+ * @param {string} [args.runner] - explicit image runner override+ * @returns {{ kind, runtime?, runner?, format:'safetensors' }}+ * Throws ServerError (HF_UNSUPPORTED_FORMAT / HF_NO_SAFETENSORS /+ * HF_UNSUPPORTED_RUNTIME / HF_UNKNOWN_KIND / HF_UNKNOWN_RUNNER /+ * HF_BAD_KIND / HF_BAD_RUNTIME / HF_BAD_RUNNER) on anything unloadable or+ * unclassifiable.+ */+export const classifyHfMediaModel = ({ repo, model, kind, runtime, runner } = {}) => {+ assertLoadableFormat({ repo, model });+ const blob = classificationBlob({ repo, model });+ // Detect once and reuse across kind-resolution + runtime/runner resolution.+ const detectedVideo = detectVideoRuntime(blob);+ const imageRunner = detectImageRunner(blob);++ // Validate explicit overrides against the addable enums before trusting them.+ if (kind !== undefined && kind !== 'image' && kind !== 'video') {+ throw new ServerError(`Unknown model kind "${kind}" — expected "image" or "video".`, { status: 400, code: 'HF_BAD_KIND' });+ }+ if (runtime !== undefined && !ADDABLE_VIDEO_RUNTIMES.includes(runtime)) {+ throw new ServerError(+ `Video runtime "${runtime}" can't be added self-service — expected one of ${ADDABLE_VIDEO_RUNTIMES.join(', ')}.`,+ { status: 400, code: 'HF_BAD_RUNTIME' },+ );+ }+ if (runner !== undefined && !ADDABLE_IMAGE_RUNNERS.includes(runner)) {+ throw new ServerError(+ `Unknown image runner "${runner}" — expected one of ${ADDABLE_IMAGE_RUNNERS.join(', ')}.`,+ { status: 400, code: 'HF_BAD_RUNNER' },+ );+ }++ // Resolve kind: explicit override wins, else detect.+ let resolvedKind = kind || null;+ if (!resolvedKind) {+ if (runtime) resolvedKind = 'video';+ else if (runner) resolvedKind = 'image';+ else if (detectedVideo || isVideoPipelineTag(model)) resolvedKind = 'video';+ else if (imageRunner || isImagePipelineTag(model)) resolvedKind = 'image';+ }+ if (!resolvedKind) {+ throw new ServerError(+ `Couldn't tell whether "${repo}" is an image or video model. Pass an explicit kind (and runtime/runner) if you know what it targets.`,+ { status: 422, code: 'HF_UNKNOWN_KIND' },+ );+ }++ if (resolvedKind === 'video') {+ // Explicit override wins (already allowlist-validated). Otherwise use the+ // detected runtime — and if that detected runtime isn't addable (wan22 /+ // hunyuan need a BYO venv), refuse with the install hint. A repo with no+ // video marker at all defaults to mlx_video (the safetensors/MLX default).+ if (runtime) return { kind: 'video', runtime, format: 'safetensors' };+ if (detectedVideo && !ADDABLE_VIDEO_RUNTIMES.includes(detectedVideo.runtime)) {+ throw new ServerError(+ `HuggingFace repo "${repo}" targets the "${detectedVideo.runtime}" runtime, which needs a dedicated venv (${detectedVideo.installHint}) and can't be added self-service — set it up via the script, then edit data/media-models.json.`,+ { status: 422, code: 'HF_UNSUPPORTED_RUNTIME' },+ );+ }+ return { kind: 'video', runtime: detectedVideo?.runtime || 'mlx_video', format: 'safetensors' };+ }++ const resolvedRunner = runner || imageRunner;+ if (!resolvedRunner) {+ throw new ServerError(+ `Couldn't determine which image runner loads "${repo}". Pass an explicit runner (one of ${ADDABLE_IMAGE_RUNNERS.join(', ')}).`,+ { status: 422, code: 'HF_UNKNOWN_RUNNER' },+ );+ }+ return { kind: 'image', runner: resolvedRunner, format: 'safetensors' };+};++// Derive a stable, collision-resistant registry id from the repo. `org/name`+// → `org-name` lowercased, with a `hf-` prefix so a user entry can't collide+// with a shipped built-in id (which are hand-picked short slugs like+// `ltx23_distilled_q4`). Non-id chars collapse to a single dash.+export const customModelIdFromRepo = (repo) => {+ const slug = String(repo || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/-+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 80);+ return `hf-${slug || 'model'}`;+};++// Build the `data/media-models.json` entry for a classified add. `source:+// 'user'` is the flag the registry mutators + UI gate on to distinguish+// user-added (editable/removable) from shipped built-in (read-only). Steps /+// guidance default per target but respect explicit values.+export const buildCustomModelEntry = ({ repo, model, classification, name, steps, guidance }) => {+ const id = customModelIdFromRepo(repo);+ const displayName = (typeof name === 'string' && name.trim())+ || (typeof model?.cardData?.model_name === 'string' && model.cardData.model_name.trim())+ || repo.split('/')[1]+ || repo;+ const defaults = classification.kind === 'video'+ ? (VIDEO_DEFAULTS[classification.runtime] || { steps: 25, guidance: 3.0 })+ : (IMAGE_DEFAULTS[classification.runner] || { steps: 20, guidance: 3.5 });+ const entry = {+ id,+ name: displayName,+ repo,+ steps: Number.isFinite(steps) ? steps : defaults.steps,+ guidance: Number.isFinite(guidance) ? guidance : defaults.guidance,+ source: 'user',+ installedAt: new Date().toISOString(),+ };+ if (classification.kind === 'video') entry.runtime = classification.runtime;+ else entry.runner = classification.runner;+ return entry;+};diff --git a/server/lib/huggingfaceModel.test.js b/server/lib/huggingfaceModel.test.jsnew file mode 100644index 0000000000..53f8787efe--- /dev/null+++ b/server/lib/huggingfaceModel.test.js@@ -0,0 +1,180 @@+import { describe, it, expect } from 'vitest';+import {+ classifyHfMediaModel,+ inspectModelFiles,+ customModelIdFromRepo,+ buildCustomModelEntry,+ searchHuggingfaceModels,+} from './huggingfaceModel.js';++// Build a minimal HF `/api/models/{repo}` response.+const hf = ({ files = [], tags = [], base = null, pipeline = null } = {}) => ({+ siblings: files.map((rfilename) => ({ rfilename })),+ tags,+ cardData: base ? { base_model: base } : {},+ pipeline_tag: pipeline,+});++describe('inspectModelFiles', () => {+ it('detects safetensors and gguf presence', () => {+ expect(inspectModelFiles(hf({ files: ['model.safetensors', 'config.json'] })))+ .toMatchObject({ hasSafetensors: true, hasGguf: false });+ expect(inspectModelFiles(hf({ files: ['model-Q4_K_M.gguf'] })))+ .toMatchObject({ hasSafetensors: false, hasGguf: true });+ });+});++describe('classifyHfMediaModel — strict refusal', () => {+ it('refuses a GGUF-only repo (no runtime can load it)', () => {+ expect(() => classifyHfMediaModel({+ repo: 'unsloth/LTX-2.3-GGUF',+ model: hf({ files: ['ltx-2.3-22b-distilled-Q4_K_M.gguf'], tags: ['ltx'] }),+ })).toThrow(/GGUF/);+ });++ it('refuses a repo with no safetensors', () => {+ expect(() => classifyHfMediaModel({+ repo: 'foo/bar',+ model: hf({ files: ['README.md'] }),+ })).toThrow(/no .safetensors/i);+ });++ it('refuses Wan repos (BYO-venv, not self-service)', () => {+ expect(() => classifyHfMediaModel({+ repo: 'Wan-AI/Wan2.2-T2V-A14B',+ model: hf({ files: ['model.safetensors'], tags: ['wan'] }),+ })).toThrow(/Wan/);+ });++ it('refuses HunyuanVideo repos', () => {+ expect(() => classifyHfMediaModel({+ repo: 'tencent/HunyuanVideo',+ model: hf({ files: ['model.safetensors'], tags: ['hunyuan'] }),+ })).toThrow(/Hunyuan/);+ });++ it('refuses an unclassifiable safetensors repo with no kind hint', () => {+ expect(() => classifyHfMediaModel({+ repo: 'someone/mystery-weights',+ model: hf({ files: ['model.safetensors'] }),+ })).toThrow(/image or video/);+ });+});++describe('classifyHfMediaModel — happy paths', () => {+ it('classifies an LTX safetensors repo as video/mlx_video', () => {+ expect(classifyHfMediaModel({+ repo: 'notapalindrome/ltx23-mlx-av-q4',+ model: hf({ files: ['model.safetensors'], tags: ['ltx-video'] }),+ })).toEqual({ kind: 'video', runtime: 'mlx_video', format: 'safetensors' });+ });++ it('honors an explicit ltx2 runtime override', () => {+ expect(classifyHfMediaModel({+ repo: 'dgrauet/ltx-2.3-mlx-q8',+ model: hf({ files: ['model.safetensors'], tags: ['ltx'] }),+ runtime: 'ltx2',+ })).toEqual({ kind: 'video', runtime: 'ltx2', format: 'safetensors' });+ });++ it('detects a FLUX.2 image repo as flux2', () => {+ expect(classifyHfMediaModel({+ repo: 'black-forest-labs/FLUX.2-klein-9B',+ model: hf({ files: ['model.safetensors'], pipeline: 'text-to-image' }),+ })).toEqual({ kind: 'image', runner: 'flux2', format: 'safetensors' });+ });++ it('detects a Qwen image repo', () => {+ expect(classifyHfMediaModel({+ repo: 'Qwen/Qwen-Image',+ model: hf({ files: ['model.safetensors'], pipeline: 'text-to-image' }),+ })).toEqual({ kind: 'image', runner: 'qwen', format: 'safetensors' });+ });++ it('rejects an invalid explicit runtime', () => {+ expect(() => classifyHfMediaModel({+ repo: 'x/y',+ model: hf({ files: ['model.safetensors'], tags: ['ltx'] }),+ runtime: 'gguf-runtime',+ })).toThrow(/can't be added self-service/);+ });++ it('falls back to a caller-supplied kind+runner for an ambiguous image repo', () => {+ expect(classifyHfMediaModel({+ repo: 'someone/custom-flux',+ model: hf({ files: ['model.safetensors'] }),+ kind: 'image',+ runner: 'mflux',+ })).toEqual({ kind: 'image', runner: 'mflux', format: 'safetensors' });+ });+});++describe('customModelIdFromRepo', () => {+ it('slugifies with an hf- prefix', () => {+ expect(customModelIdFromRepo('notapalindrome/ltx23-mlx-av-q4')).toBe('hf-notapalindrome-ltx23-mlx-av-q4');+ expect(customModelIdFromRepo('black-forest-labs/FLUX.2-klein-9B')).toBe('hf-black-forest-labs-flux-2-klein-9b');+ });+});++describe('buildCustomModelEntry', () => {+ it('builds a video entry with runtime + user source + defaults', () => {+ const entry = buildCustomModelEntry({+ repo: 'notapalindrome/ltx23-mlx-av-q4',+ model: hf({ tags: ['ltx'] }),+ classification: { kind: 'video', runtime: 'mlx_video', format: 'safetensors' },+ });+ expect(entry).toMatchObject({+ id: 'hf-notapalindrome-ltx23-mlx-av-q4',+ repo: 'notapalindrome/ltx23-mlx-av-q4',+ runtime: 'mlx_video',+ source: 'user',+ steps: 25,+ guidance: 3.0,+ });+ expect(entry.runner).toBeUndefined();+ expect(entry.installedAt).toBeTruthy();+ });++ it('builds an image entry with runner + honors overrides', () => {+ const entry = buildCustomModelEntry({+ repo: 'Qwen/Qwen-Image',+ model: hf({}),+ classification: { kind: 'image', runner: 'qwen', format: 'safetensors' },+ name: 'My Qwen',+ steps: 40,+ guidance: 5,+ });+ expect(entry).toMatchObject({ runner: 'qwen', name: 'My Qwen', steps: 40, guidance: 5, source: 'user' });+ expect(entry.runtime).toBeUndefined();+ });+});++describe('searchHuggingfaceModels', () => {+ it('builds the search URL and maps rows', async () => {+ let calledUrl = null;+ const fetchImpl = async (url) => {+ calledUrl = url;+ return {+ ok: true,+ text: async () => JSON.stringify([+ { id: 'org/a', likes: 5, downloads: 100, pipeline_tag: 'text-to-image' },+ { modelId: 'org/b', pipeline_tag: 'text-to-video' },+ { likes: 1 }, // no id → dropped+ ]),+ };+ };+ const rows = await searchHuggingfaceModels('ltx', { pipeline: 'text-to-video', limit: 5, fetchImpl });+ expect(calledUrl).toContain('search=ltx');+ expect(calledUrl).toContain('pipeline_tag=text-to-video');+ expect(calledUrl).toContain('limit=5');+ expect(rows).toEqual([+ { id: 'org/a', likes: 5, downloads: 100, pipeline_tag: 'text-to-image' },+ { id: 'org/b', likes: 0, downloads: 0, pipeline_tag: 'text-to-video' },+ ]);+ });++ it('throws on a non-ok response', async () => {+ const fetchImpl = async () => ({ ok: false, status: 503, text: async () => '' });+ await expect(searchHuggingfaceModels('x', { fetchImpl })).rejects.toThrow(/search failed/i);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 4a85db345e..012d8f4aab 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -181,6 +181,7 @@ export * from './appResolver.js';export * from './capabilityMap.js';export * from './civitai.js';export * from './huggingfaceLora.js';+export * from './huggingfaceModel.js';export * from './localLlmCatalog.js';export * from './localLlmDisk.js';export * from './localModelHeuristics.js';diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 48de02e3cb..385b70e18f 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -20,6 +20,7 @@ import { join, dirname } from 'path';import { PATHS, expandHome } from './fileUtils.js';import { isPlainObject } from './objects.js';import { RUNNER_FAMILIES } from './runners.js';+import { ServerError } from './errorHandler.js';// fileUtils.ensureDir is async/Promise-returning; this module needs a// synchronous version because `loadMediaModels()` is called at import-time// from videoGen/imageGen modules, which can't await before exporting.@@ -696,6 +697,126 @@ export const loadMediaModels = () => {return cached;};+// Bust the boot-only cache so the next loadMediaModels() re-reads the file.+// The registry is cached at module scope (videoGen/imageGen import it+// synchronously at boot), so a runtime add/edit/remove must invalidate the+// cache or the change 400s ("Unknown model") until a server restart — the+// exact gotcha called out in issue #2124. Returns the freshly-loaded registry.+export const reloadMediaModels = () => {+ cached = null;+ return loadMediaModels();+};++// Persist a registry object to disk and swap it in as the cache. The cache is+// only replaced AFTER a successful write, so a persist failure leaves the live+// cache untouched (the mutators build an immutable `next` rather than editing+// the shared cache in place). Single-user trust model → no file lock needed.+const persistRegistry = (reg) => {+ ensureDir(REGISTRY_FILE);+ writeFileSync(REGISTRY_FILE, JSON.stringify(reg, null, 2) + '\n');+ cached = reg;+ return reg;+};++// A user-added entry (from the "add from HuggingFace" flow) carries+// `source: 'user'`. Shipped built-ins have no `source` (or a non-'user' one+// like 'trained' won't appear here). Only user entries are editable/removable+// through the API — built-ins are read-only (the registry is their source of+// truth + they round-trip through the shipped-defaults upgrade machinery).+export const isUserModelEntry = (entry) => entry?.source === 'user';++// Locate a model entry by id across every list (video macos/windows + image),+// returning `{ entry, list, listKey, idx }` or null. `listKey` ('macos' |+// 'windows' | 'image') lets the mutators rebuild just the affected list+// immutably (no deep clone of the whole registry).+const findModelLocation = (reg, id) => {+ const lists = [+ ['macos', reg.video?.macos],+ ['windows', reg.video?.windows],+ ['image', reg.image],+ ];+ for (const [listKey, list] of lists) {+ if (!Array.isArray(list)) continue;+ const idx = list.findIndex((m) => m?.id === id);+ if (idx >= 0) return { entry: list[idx], list, listKey, idx };+ }+ return null;+};++// Rebuild the registry with one list replaced — shallow everywhere except the+// swapped array, so we neither deep-clone the whole registry nor mutate the+// live cache before the write succeeds.+const withList = (reg, listKey, nextList) =>+ listKey === 'image'+ ? { ...reg, image: nextList }+ : { ...reg, video: { ...reg.video, [listKey]: nextList } };++// Add a user model entry to the registry. `kind` selects the target list:+// 'video' → the current platform's video list; 'image' → the image list.+// Throws on a duplicate id (a repo already added). Persists + hot-reloads.+export const addUserModelEntry = (entry, { kind }) => {+ if (!entry || typeof entry.id !== 'string') {+ throw new ServerError('Model entry must carry a string id', { status: 400, code: 'BAD_MODEL_ENTRY' });+ }+ if (kind !== 'video' && kind !== 'image') {+ throw new ServerError(`Unknown model kind "${kind}" — expected "image" or "video".`, { status: 400, code: 'BAD_MODEL_KIND' });+ }+ const reg = loadMediaModels();+ if (findModelLocation(reg, entry.id)) {+ throw new ServerError(+ `A model with id "${entry.id}" is already in the registry (repo already added?). Remove it first to re-add.`,+ { status: 409, code: 'MODEL_ALREADY_EXISTS' },+ );+ }+ const listKey = kind === 'video' ? (IS_WIN ? 'windows' : 'macos') : 'image';+ const current = listKey === 'image' ? reg.image : reg.video[listKey];+ persistRegistry(withList(reg, listKey, [...(current || []), entry]));+ console.log(`📝 Added user media model: ${entry.id} (${kind}) → ${entry.repo || '?'}`);+ return entry;+};++// Guard shared by patch/remove: locate a USER entry by id or throw (404 for+// unknown, 403 for a built-in). Returns the `findModelLocation` result.+const requireUserEntry = (reg, id, verb) => {+ const loc = findModelLocation(reg, id);+ if (!loc) throw new ServerError(`Unknown model id: ${id}`, { status: 404, code: 'NOT_FOUND' });+ if (!isUserModelEntry(loc.entry)) {+ throw new ServerError(+ `Model "${id}" is a built-in — built-in models can't be ${verb} through this surface.`,+ { status: 403, code: 'MODEL_READONLY' },+ );+ }+ return loc;+};++// Patch a USER model entry's editable fields (name, steps, guidance). Refuses+// built-ins and unknown ids. Persists + hot-reloads. Returns the updated entry.+const USER_EDITABLE_FIELDS = new Set(['name', 'steps', 'guidance']);+export const patchUserModelEntry = (id, patch) => {+ const reg = loadMediaModels();+ const loc = requireUserEntry(reg, id, 'edited');+ const cleanPatch = {};+ for (const [k, v] of Object.entries(patch || {})) {+ if (USER_EDITABLE_FIELDS.has(k) && v !== undefined) cleanPatch[k] = v;+ }+ const updated = { ...loc.entry, ...cleanPatch, id, source: 'user' };+ const nextList = loc.list.map((m, i) => (i === loc.idx ? updated : m));+ persistRegistry(withList(reg, loc.listKey, nextList));+ console.log(`📝 Patched user media model: ${id}`);+ return updated;+};++// Remove a USER model entry. Refuses built-ins and unknown ids. Persists ++// hot-reloads. Returns `{ ok, id }`.+export const removeUserModelEntry = (id) => {+ const reg = loadMediaModels();+ const loc = requireUserEntry(reg, id, 'removed');+ const nextList = loc.list.filter((_, i) => i !== loc.idx);+ persistRegistry(withList(reg, loc.listKey, nextList));+ console.log(`🗑️ Removed user media model: ${id}`);+ return { ok: true, id };+};+const platformBroken = (broken) =>broken === true || (typeof broken === 'string' && broken === (IS_WIN ? 'windows' : 'macos'));diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex 4674fb06e7..6b8accecb1 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -748,3 +748,75 @@ describe('mediaModels registry', () => {logSpy.mockRestore();});});++describe('user model entry mutators (#2124)', () => {+ const videoEntry = {+ id: 'hf-test-video', name: 'Test Video', repo: 'test/video',+ runtime: 'mlx_video', steps: 25, guidance: 3.0, source: 'user',+ };+ const imageEntry = {+ id: 'hf-test-image', name: 'Test Image', repo: 'test/image',+ runner: 'flux2', steps: 8, guidance: 3.5, source: 'user',+ };++ it('isUserModelEntry distinguishes user from built-in', async () => {+ const { isUserModelEntry } = await import('./mediaModels.js');+ expect(isUserModelEntry({ source: 'user' })).toBe(true);+ expect(isUserModelEntry({})).toBe(false);+ expect(isUserModelEntry({ source: 'trained' })).toBe(false);+ });++ it('adds a user video entry, persists it, and hot-reloads the cache', async () => {+ const { addUserModelEntry, getVideoModels, loadMediaModels } = await import('./mediaModels.js');+ loadMediaModels(); // prime the cache+ addUserModelEntry(videoEntry, { kind: 'video' });+ // Reads back through the (busted + re-read) cache — no restart needed.+ expect(getVideoModels().some((m) => m.id === 'hf-test-video')).toBe(true);+ // And it's persisted to disk.+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));+ const inList = [...onDisk.video.macos, ...onDisk.video.windows].some((m) => m.id === 'hf-test-video');+ expect(inList).toBe(true);+ });++ it('adds a user image entry', async () => {+ const { addUserModelEntry, getImageModels } = await import('./mediaModels.js');+ addUserModelEntry(imageEntry, { kind: 'image' });+ expect(getImageModels().some((m) => m.id === 'hf-test-image')).toBe(true);+ });++ it('refuses a duplicate id', async () => {+ const { addUserModelEntry } = await import('./mediaModels.js');+ addUserModelEntry(videoEntry, { kind: 'video' });+ expect(() => addUserModelEntry(videoEntry, { kind: 'video' })).toThrow(/already/i);+ });++ it('patches a user entry but refuses built-ins', async () => {+ const { addUserModelEntry, patchUserModelEntry, getImageModels } = await import('./mediaModels.js');+ addUserModelEntry(imageEntry, { kind: 'image' });+ const updated = patchUserModelEntry('hf-test-image', { name: 'Renamed', steps: 12 });+ expect(updated.name).toBe('Renamed');+ expect(updated.steps).toBe(12);+ expect(getImageModels().find((m) => m.id === 'hf-test-image').name).toBe('Renamed');+ // 'dev' is a shipped built-in+ expect(() => patchUserModelEntry('dev', { name: 'Hack' })).toThrow(/built-in/i);+ expect(() => patchUserModelEntry('does-not-exist', { name: 'x' })).toThrow(/Unknown/i);+ });++ it('removes a user entry but refuses built-ins', async () => {+ const { addUserModelEntry, removeUserModelEntry, getVideoModels } = await import('./mediaModels.js');+ addUserModelEntry(videoEntry, { kind: 'video' });+ expect(removeUserModelEntry('hf-test-video')).toEqual({ ok: true, id: 'hf-test-video' });+ expect(getVideoModels().some((m) => m.id === 'hf-test-video')).toBe(false);+ expect(() => removeUserModelEntry('dev')).toThrow(/built-in/i);+ expect(() => removeUserModelEntry('nope')).toThrow(/Unknown/i);+ });++ it('reloadMediaModels busts the cache', async () => {+ const { loadMediaModels, reloadMediaModels } = await import('./mediaModels.js');+ const first = loadMediaModels();+ const second = loadMediaModels();+ expect(first).toBe(second); // cached identity+ const reloaded = reloadMediaModels();+ expect(reloaded).not.toBe(first); // fresh object after bust+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 52075e51b4..b3c3b56c84 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -23,7 +23,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.music-video', path: '/media/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },- { id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },+ { id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk', 'add model', 'install model', 'custom model'] },{ id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },{ id: 'nav.create.universe-builder', path: '/universes', label: 'Universes', section: 'Create', aliases: ['universes', 'universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries', 'list', 'manage'] },{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.jsindex 5d4d315390..65a7a7c963 100644--- a/server/routes/imageVideoModels.js+++ b/server/routes/imageVideoModels.js@@ -13,10 +13,19 @@ import { existsSync } from 'fs';import { readdir, stat, rm } from 'fs/promises';import { homedir } from 'os';import { join } from 'path';+import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { PATHS, formatBytes, dirSize } from '../lib/fileUtils.js';-import { loadMediaModels } from '../lib/mediaModels.js';+import {+ isUserModelEntry,+ loadMediaModels,+ patchUserModelEntry,+ removeUserModelEntry,+} from '../lib/mediaModels.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';+import { emptyToUndefined, validateRequest } from '../lib/validation.js';+import { ADDABLE_IMAGE_RUNNERS, ADDABLE_VIDEO_RUNTIMES, searchHuggingfaceModels } from '../lib/huggingfaceModel.js';+import { addModelFromHuggingface } from '../services/mediaModelInstall.js';const router = Router();const HF_DEFAULT_HUB = join(homedir(), '.cache', 'huggingface', 'hub');@@ -108,6 +117,98 @@ router.get('/', asyncHandler(async (_req, res) => {});}));+// GET /registry — the media-model registry as the manager UI needs it:+// every image + video entry flattened with a `builtIn` flag so the page can+// render built-ins read-only and user-added entries editable/removable. This+// is distinct from `GET /` (which reports on-disk HF *cache* usage) — this+// reports the model *catalog* (what can be picked), including entries whose+// weights aren't downloaded yet.+router.get('/registry', asyncHandler(async (_req, res) => {+ const reg = loadMediaModels();+ const flatten = (list, kind) =>+ (Array.isArray(list) ? list : []).map((m) => ({+ id: m.id,+ name: m.name,+ repo: m.repo || null,+ kind,+ runtime: m.runtime || null,+ runner: m.runner || null,+ steps: m.steps ?? null,+ guidance: m.guidance ?? null,+ deprecated: !!m.deprecated,+ broken: m.broken ?? false,+ builtIn: !isUserModelEntry(m),+ source: m.source || null,+ installedAt: m.installedAt || null,+ }));+ res.json({+ video: [+ ...flatten(reg.video?.macos, 'video'),+ ...flatten(reg.video?.windows, 'video'),+ ],+ image: flatten(reg.image, 'image'),+ });+}));++// GET /search — free-text HuggingFace Hub search for candidate base-model+// repos. Backs the manager UI's discovery box; the user adds one by feeding its+// id into POST /install/huggingface (which runs the full classify/refuse pass).+const modelSearchSchema = z.object({+ query: z.preprocess(emptyToUndefined, z.string().max(120).optional()),+ pipeline: z.preprocess(emptyToUndefined, z.string().max(60).optional()),+ limit: z.coerce.number().int().min(1).max(50).optional(),+});+router.get('/search', asyncHandler(async (req, res) => {+ const { query, pipeline, limit } = validateRequest(modelSearchSchema, req.query);+ const items = await searchHuggingfaceModels(query || '', { pipeline, limit: limit || 12 });+ res.json({ items });+}));++// POST /install/huggingface — add a custom base model from an HF repo. Strict:+// the classifier refuses GGUF-only, wan/hunyuan, or unclassifiable repos so a+// bad add can't wedge the picker. The (multi-GB) weight download is deferred to+// the existing per-model download SSE once the entry exists — this call is+// metadata-only and returns the new entry. `kind`/`runtime`/`runner` are+// optional overrides for a mis-detected repo; `name`/`steps`/`guidance`+// override the derived defaults. HF token comes from settings/env — never the+// request body.+// runtime/runner enums are built from the classifier's ADDABLE_* allowlists —+// single source of truth so the route can't drift from what the classifier+// (and RUNNER_FAMILIES) actually accept.+const hfAddModelSchema = z.object({+ url: z.string().min(1).max(1024),+ kind: z.enum(['image', 'video']).optional(),+ runtime: z.enum(ADDABLE_VIDEO_RUNTIMES).optional(),+ runner: z.enum(ADDABLE_IMAGE_RUNNERS).optional(),+ name: z.string().min(1).max(200).optional(),+ steps: z.coerce.number().int().min(1).max(200).optional(),+ guidance: z.coerce.number().min(0).max(30).optional(),+});+router.post('/install/huggingface', asyncHandler(async (req, res) => {+ const data = validateRequest(hfAddModelSchema, req.body);+ const result = await addModelFromHuggingface(data);+ res.status(201).json(result);+}));++// PATCH /custom/:id — edit a user-added model's name/steps/guidance. Built-ins+// return 403 MODEL_READONLY.+const patchModelSchema = z.object({+ name: z.string().min(1).max(200).optional(),+ steps: z.coerce.number().int().min(1).max(200).optional(),+ guidance: z.coerce.number().min(0).max(30).optional(),+});+router.patch('/custom/:id', asyncHandler(async (req, res) => {+ const patch = validateRequest(patchModelSchema, req.body);+ res.json(patchUserModelEntry(req.params.id, patch));+}));++// DELETE /custom/:id — remove a user-added model. Built-ins return 403+// MODEL_READONLY; unknown ids 404. This removes the registry ENTRY only; any+// downloaded weights stay in the HF cache (deletable via DELETE /hf/:dirName).+router.delete('/custom/:id', asyncHandler(async (req, res) => {+ res.json(removeUserModelEntry(req.params.id));+}));+router.delete('/hf/:dirName', asyncHandler(async (req, res) => {const dirName = req.params.dirName;if (!dirName.startsWith('models--') || dirName.includes('/') || dirName.includes('\\') || dirName.includes('..')) {diff --git a/server/routes/imageVideoModels.test.js b/server/routes/imageVideoModels.test.jsnew file mode 100644index 0000000000..345da348f5--- /dev/null+++ b/server/routes/imageVideoModels.test.js@@ -0,0 +1,134 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware, ServerError } from '../lib/errorHandler.js';++// Stub the registry + install service — this suite verifies routing ++// validation + status-code mapping for the #2124 add/manage endpoints, not the+// live HuggingFace fetch or on-disk registry write.+vi.mock('../lib/mediaModels.js', () => ({+ loadMediaModels: vi.fn(() => ({+ video: {+ macos: [+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Q4', repo: 'notapalindrome/ltx23-mlx-av-q4', runtime: 'mlx_video', steps: 25, guidance: 3 },+ { id: 'hf-mine', name: 'Mine', repo: 'me/mine', runtime: 'ltx2', steps: 8, guidance: 3, source: 'user' },+ ],+ windows: [],+ },+ image: [+ { id: 'dev', name: 'Flux 1 Dev', runner: 'mflux', steps: 20, guidance: 3.5 },+ ],+ })),+ isUserModelEntry: (e) => e?.source === 'user',+ patchUserModelEntry: vi.fn((id, patch) => ({ id, ...patch, source: 'user' })),+ removeUserModelEntry: vi.fn((id) => ({ ok: true, id })),+}));++vi.mock('../lib/huggingfaceModel.js', () => ({+ ADDABLE_VIDEO_RUNTIMES: ['mlx_video', 'ltx2'],+ ADDABLE_IMAGE_RUNNERS: ['mflux', 'flux2', 'z-image', 'ernie', 'hidream', 'qwen'],+ searchHuggingfaceModels: vi.fn(async (query) => [{ id: `org/${query}`, likes: 1, downloads: 2, pipeline_tag: 'text-to-image' }]),+}));++vi.mock('../services/mediaModelInstall.js', () => ({+ addModelFromHuggingface: vi.fn(async (input) => ({+ entry: { id: 'hf-new', name: 'New', repo: 'org/new', runtime: 'mlx_video', source: 'user' },+ kind: 'video',+ })),+}));++// Avoid touching the real HF cache dir in GET / (not under test here).+vi.mock('../lib/fileUtils.js', async (orig) => {+ const actual = await orig();+ return { ...actual };+});++const { default: routes } = await import('./imageVideoModels.js');+const { addModelFromHuggingface } = await import('../services/mediaModelInstall.js');+const { patchUserModelEntry, removeUserModelEntry } = await import('../lib/mediaModels.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/image-video/models', routes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => { vi.clearAllMocks(); });++describe('GET /registry', () => {+ it('flattens video + image entries with a builtIn flag', async () => {+ const res = await request(makeApp()).get('/api/image-video/models/registry');+ expect(res.status).toBe(200);+ expect(res.body.video).toHaveLength(2);+ expect(res.body.image).toHaveLength(1);+ const builtIn = res.body.video.find((m) => m.id === 'ltx23_distilled_q4');+ const user = res.body.video.find((m) => m.id === 'hf-mine');+ expect(builtIn.builtIn).toBe(true);+ expect(user.builtIn).toBe(false);+ });+});++describe('GET /search', () => {+ it('returns mapped HF search rows', async () => {+ const res = await request(makeApp()).get('/api/image-video/models/search?query=ltx&pipeline=text-to-video');+ expect(res.status).toBe(200);+ expect(res.body.items[0].id).toBe('org/ltx');+ });+});++describe('POST /install/huggingface', () => {+ it('adds a model and returns 201 with the entry', async () => {+ const res = await request(makeApp())+ .post('/api/image-video/models/install/huggingface')+ .send({ url: 'org/new' });+ expect(res.status).toBe(201);+ expect(res.body.entry.id).toBe('hf-new');+ expect(addModelFromHuggingface).toHaveBeenCalledWith(expect.objectContaining({ url: 'org/new' }));+ });++ it('rejects a missing url with 400', async () => {+ const res = await request(makeApp())+ .post('/api/image-video/models/install/huggingface')+ .send({});+ expect(res.status).toBe(400);+ });++ it('rejects an out-of-enum runner override', async () => {+ const res = await request(makeApp())+ .post('/api/image-video/models/install/huggingface')+ .send({ url: 'org/x', runner: 'not-a-runner' });+ expect(res.status).toBe(400);+ });++ it('surfaces a typed classifier refusal (e.g. GGUF-only) with its status', async () => {+ addModelFromHuggingface.mockRejectedValueOnce(+ new ServerError('ships only GGUF', { status: 422, code: 'HF_UNSUPPORTED_FORMAT' }),+ );+ const res = await request(makeApp())+ .post('/api/image-video/models/install/huggingface')+ .send({ url: 'unsloth/LTX-2.3-GGUF' });+ expect(res.status).toBe(422);+ expect(res.body.code).toBe('HF_UNSUPPORTED_FORMAT');+ });+});++describe('PATCH /custom/:id', () => {+ it('patches a user model', async () => {+ const res = await request(makeApp())+ .patch('/api/image-video/models/custom/hf-mine')+ .send({ name: 'Renamed', steps: 10 });+ expect(res.status).toBe(200);+ expect(patchUserModelEntry).toHaveBeenCalledWith('hf-mine', expect.objectContaining({ name: 'Renamed', steps: 10 }));+ });+});++describe('DELETE /custom/:id', () => {+ it('removes a user model', async () => {+ const res = await request(makeApp()).delete('/api/image-video/models/custom/hf-mine');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true, id: 'hf-mine' });+ expect(removeUserModelEntry).toHaveBeenCalledWith('hf-mine');+ });+});diff --git a/server/services/mediaModelInstall.js b/server/services/mediaModelInstall.jsnew file mode 100644index 0000000000..b66e2226fc--- /dev/null+++ b/server/services/mediaModelInstall.js@@ -0,0 +1,65 @@+/**+ * Add a custom base model (image or video) from a HuggingFace repo — the+ * self-service analogue of hand-editing data/media-models.json + restarting+ * (issue #2124). Mirrors the LoRA installer's structure (services/loras.js+ * installFromHuggingface): parse the ref → fetch repo metadata → classify the+ * runtime/format → refuse anything no runtime can load → append a registry+ * entry and hot-reload the boot-only cache.+ *+ * The actual multi-GB weight download is NOT done here: base models are+ * multi-file repos, so the existing per-model snapshot download SSE+ * (GET /api/{image,video}-gen/models/:id/download, backed by hfDownload.js)+ * handles the pull with progress once the entry exists. This endpoint is+ * metadata-only and returns fast, exactly like adding a row and letting the+ * download badge take over.+ *+ * No try/catch — errors bubble to centralized middleware; domain errors throw+ * ServerError.+ */++import { fetchHuggingfaceModel, parseHuggingfaceLoraRef } from '../lib/huggingfaceLora.js';+import {+ buildCustomModelEntry,+ classifyHfMediaModel,+} from '../lib/huggingfaceModel.js';+import { addUserModelEntry } from '../lib/mediaModels.js';+import { getHfToken } from '../lib/hfToken.js';++// Add a media model from a HuggingFace repo. `input.url` is any HF ref shape+// (URL or org/name@rev). Optional `kind` ('image'|'video'), `runtime` (video),+// `runner` (image) let the UI correct a mis-detected repo. `name`/`steps`/+// `guidance` override the derived defaults. Returns the new registry entry.+export const addModelFromHuggingface = async (input, { fetchImpl = fetch } = {}) => {+ const { repo, revision } = parseHuggingfaceLoraRef(input?.url);+ // Stored/env/CLI token — needed only for gated repos, harmless on public ones.+ const token = (typeof input?.token === 'string' && input.token.trim()) || (await getHfToken()) || '';+ const model = await fetchHuggingfaceModel(repo, { token, revision, fetchImpl });++ // Strict classification: throws HF_UNSUPPORTED_FORMAT (GGUF-only),+ // HF_NO_SAFETENSORS, HF_UNSUPPORTED_RUNTIME (wan/hunyuan),+ // HF_UNKNOWN_KIND/RUNNER, or the HF_BAD_* override-validation errors. A repo+ // no runtime can load never reaches the registry — that's the whole point:+ // a bad add would wedge the model picker.+ const classification = classifyHfMediaModel({+ repo,+ model,+ kind: input?.kind,+ runtime: input?.runtime,+ runner: input?.runner,+ });++ const entry = buildCustomModelEntry({+ repo,+ model,+ classification,+ name: input?.name,+ steps: Number.isFinite(input?.steps) ? input.steps : undefined,+ guidance: Number.isFinite(input?.guidance) ? input.guidance : undefined,+ });++ // addUserModelEntry throws MODEL_ALREADY_EXISTS on a duplicate id (repo+ // already added) and persists + hot-reloads the registry cache.+ addUserModelEntry(entry, { kind: classification.kind });+ console.log(`✅ Added HuggingFace media model: ${entry.id} [${classification.kind}/${classification.runtime || classification.runner}]`);+ return { entry, kind: classification.kind };+};diff --git a/server/services/mediaModelInstall.test.js b/server/services/mediaModelInstall.test.jsnew file mode 100644index 0000000000..c2c995599a--- /dev/null+++ b/server/services/mediaModelInstall.test.js@@ -0,0 +1,63 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/hfToken.js', () => ({ getHfToken: vi.fn(async () => '') }));+vi.mock('../lib/mediaModels.js', () => ({ addUserModelEntry: vi.fn((entry) => entry) }));++const { addModelFromHuggingface } = await import('./mediaModelInstall.js');+const { addUserModelEntry } = await import('../lib/mediaModels.js');++// Minimal fetch mock returning an HF `/api/models/{repo}` body.+const mockFetch = (body) => vi.fn(async () => ({+ ok: true,+ text: async () => JSON.stringify(body),+}));++beforeEach(() => { vi.clearAllMocks(); });++describe('addModelFromHuggingface', () => {+ it('classifies an LTX safetensors repo, builds a video entry, and registers it', async () => {+ const fetchImpl = mockFetch({+ id: 'notapalindrome/ltx23-mlx-av-q4',+ siblings: [{ rfilename: 'model.safetensors' }],+ tags: ['ltx-video'],+ });+ const result = await addModelFromHuggingface(+ { url: 'notapalindrome/ltx23-mlx-av-q4' },+ { fetchImpl },+ );+ expect(result.kind).toBe('video');+ expect(result.entry).toMatchObject({+ id: 'hf-notapalindrome-ltx23-mlx-av-q4',+ runtime: 'mlx_video',+ source: 'user',+ });+ expect(addUserModelEntry).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'hf-notapalindrome-ltx23-mlx-av-q4' }),+ { kind: 'video' },+ );+ });++ it('refuses a GGUF-only repo before registering anything', async () => {+ const fetchImpl = mockFetch({+ id: 'unsloth/LTX-2.3-GGUF',+ siblings: [{ rfilename: 'ltx-2.3-Q4_K_M.gguf' }],+ tags: ['ltx'],+ });+ await expect(+ addModelFromHuggingface({ url: 'unsloth/LTX-2.3-GGUF' }, { fetchImpl }),+ ).rejects.toThrow(/GGUF/);+ expect(addUserModelEntry).not.toHaveBeenCalled();+ });++ it('honors explicit kind + runner overrides', async () => {+ const fetchImpl = mockFetch({+ id: 'someone/custom',+ siblings: [{ rfilename: 'model.safetensors' }],+ });+ const result = await addModelFromHuggingface(+ { url: 'someone/custom', kind: 'image', runner: 'mflux' },+ { fetchImpl },+ );+ expect(result.entry).toMatchObject({ runner: 'mflux', source: 'user' });+ });+});