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

feat(loras): pre-scan Civitai for suggested LoRAs with previews + sample prompts

Adam Eivyffbbb1ae3b4d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a2b9003b3e..eda0e0d8f3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Suggested LoRAs panel on the manager page.** `/media/loras` now leads with a "Suggested LoRAs" section that surfaces (1) a hand-curated list of picks that work well across the family — initially `hyperdetailed-colored-pencil`, `anime-art`, `dark-ghibli-fairytales`, `ars-midjourney-watercolor` — and (2) per-runner-family top-N from Civitai's "Most Downloaded" endpoint (Flux 1 / Flux 2 / Z-Image). Each card shows the preview thumbnail, runner-compat badges (derived from the model's actual `modelVersions[].baseModel`, so a multi-base-model upload shows all the badges it deserves), creator, downloads count, and an expandable "Sample prompt" section pulled from `images[0].meta.prompt`. **Quick install** routes through the same path as URL-paste, so the auth-prompt modal still fires for gated LoRAs and the same lockfile-collision protection applies. Cards already installed render as a green "Installed ✓" pill instead of the install button. Server: new `server/services/civitaiSuggestions.js` (in-memory 1-hour TTL cache per family, independent caches so a Z-Image search returning zero doesn't poison Flux), new `searchCivitaiLoras()` + `extractSamplePrompt()` helpers in `civitai.js`, new `GET /api/loras/suggestions` route (with `?force=1` to bust cache). 5 new tests cover the curated/runners shape, partial-failure tolerance, cache hit/miss, force-refresh, and runner-family derivation from multi-version models.
- **In-UI Civitai API key prompt.** When a Civitai install fails because the LoRA is gated (HTTP 401/403 from either the metadata or download endpoint), PortOS now opens an inline modal asking for an API key — paste it, click "Save key & retry install", and the same install fires again with the freshly-saved key in scope. The Manager page also surfaces a green "Key saved" / blue "Key (env)" / grey "Add API key" pill in the install form so users see at a glance whether a key is configured, and the modal includes a "Clear" button to remove a settings-level key (with a hint that the env-var key, if set, takes over after clearing). New endpoints: `GET /api/loras/auth/civitai` (returns `{ hasKey, source }` — the key itself never round-trips), `POST /api/loras/auth/civitai`, `DELETE /api/loras/auth/civitai`. Client API: `getCivitaiAuth`, `setCivitaiAuth`, `clearCivitaiAuth`. The install client now also takes `silent: true` so the auth-error path bypasses the auto-toast and reaches the modal cleanly.
- **Civitai LoRA manager.** A new `Media Gen → LoRAs` tab (`/media/loras`) lets you paste any Civitai model URL — `https://civitai.com/models/...`, `https://civitai.red/...`, a numeric model id, or `civitai:<id>` shortcut — and PortOS fetches the metadata, picks the primary `.safetensors`, streams the download into `data/loras/`, and writes a sidecar JSON next to it with trigger words, recommended scale, base model, creator, preview image URL, and the Civitai version id. Each card shows the preview thumbnail, a runner-family badge (Flux 1 / Flux 2 / Z-Image / Unsupported), trigger words, recommended scale, file size, and three actions: **Test** (deep-links into `/media/image?lora=<filename>` which preselects the LoRA and seeds its scale from the recommended value), **Open on Civitai**, and **Delete**. The Image Gen LoRA picker now reads the same registry, filters down to LoRAs whose `runnerFamily` matches the selected model's runner (or has no family — legacy/unknown), shows trigger words inline, and applies the recommended scale by default when you tick a LoRA. Restricted/adult LoRAs that need a logged-in download work via either the `CIVITAI_API_KEY` env var or `civitai.apiKey` in `data/settings.json`. New endpoints: `GET /api/loras`, `POST /api/loras/install`, `GET /api/loras/:filename`, `PATCH /api/loras/:filename`, `DELETE /api/loras/:filename`. Server: `server/lib/civitai.js` (URL parsing, version/file picking, sidecar shape) + `server/services/loras.js` (install/list/patch/delete with stream-to-disk + .partial finalizer). The runner side gets a best-effort `apply_loras()` helper added to `scripts/flux2_macos.py` and `scripts/z_image_turbo.py` (calls diffusers' `pipe.load_lora_weights()` + `pipe.set_adapters()` and logs+continues on shape mismatch rather than aborting the render); `mflux` continues to receive LoRAs through its existing `--lora-paths` / `--lora-scales` CLI surface. The `IMAGE_GEN_FLUX2_LORA_UNSUPPORTED` guard is removed — flux2 and z-image runners now plumb LoRAs through too. 45 new tests cover the Civitai URL-shape parser, version/file/preview picking, the auth header / download token plumbing, sidecar shape, and the install/list/delete service path (using a fake fetchImpl + temp loras dir).
- **Z-Image-Turbo support in image gen.** A new `runner: 'z-image'` lets PortOS render through Tongyi/Alibaba's Z-Image-Turbo (~6B distilled DiT, ~8 steps, Apache 2.0 — no HF token / license-acceptance required, unlike FLUX.2). Two registry entries seed by default in `data/media-models.json`: `z-image-turbo-bf16` (Tongyi-MAI/Z-Image-Turbo, ~13 GB on a 32 GB+ Mac or 16 GB+ CUDA card) and a hidden `z-image-turbo-quant` template (set the `repo` and clear `broken: true` to point at a community quantized port). The runner reuses the FLUX.2 venv at `~/.portos/venv-flux2` (already has `diffusers` from git HEAD + `torch` + MPS support), so no extra setup step. Wires through both txt2img and i2i (init image + strength) on day one, with stepwise live-preview frames and the same SSE / cancel / metadata-sidecar plumbing the FLUX.2 runner already uses. New script: `scripts/z_image_turbo.py`. Registry now also tracks `_shippedDefaults.image` so future built-in models land on existing installs without overwriting user customisations or undoing user deletions. 9 new tests cover the dispatch branch (`server/services/imageGen/local.test.js`) and the image upgrade path (`server/lib/mediaModels.test.js`).
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 7c29d1b744..4101a23d95 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -9,7 +9,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
-import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X } from 'lucide-react';
+import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import { formatBytes } from '../utils/formatters';
import {
@@ -19,6 +19,7 @@ import {
getCivitaiAuth,
setCivitaiAuth,
clearCivitaiAuth,
+ getCivitaiSuggestions,
} from '../services/api';
const RUNNER_LABEL = {
@@ -45,6 +46,10 @@ export default function Loras() {
// so users don't have to remember what they were installing.
const [auth, setAuth] = useState({ hasKey: false, source: 'none' });
const [authPrompt, setAuthPrompt] = useState(null);
+ // suggestions: { runners: { mflux: [...], flux2: [...], 'z-image': [...] }, fetchedAt }
+ const [suggestions, setSuggestions] = useState(null);
+ const [loadingSuggestions, setLoadingSuggestions] = useState(true);
+ const [installingSuggestion, setInstallingSuggestion] = useState(null);
const refresh = useCallback(() => {
setError(null);
@@ -55,10 +60,19 @@ export default function Loras() {
.finally(() => setLoading(false));
}, []);
+ const refreshSuggestions = useCallback(({ force = false } = {}) => {
+ setLoadingSuggestions(true);
+ getCivitaiSuggestions({ force })
+ .then(setSuggestions)
+ .catch((err) => toast.error(err?.message || 'Failed to load suggestions'))
+ .finally(() => setLoadingSuggestions(false));
+ }, []);
+
useEffect(() => {
refresh();
getCivitaiAuth().then(setAuth).catch(() => {});
- }, [refresh]);
+ refreshSuggestions();
+ }, [refresh, refreshSuggestions]);
// silent:true so the auth-error path goes through the modal instead of a
// one-shot toast the user can't act on. Shared by the initial install
@@ -164,26 +178,179 @@ export default function Loras() {
/>
)}
- {loading && <div className="text-sm text-gray-500">Loading…</div>}
- {error && (
- <div className="bg-port-error/10 border border-port-error/30 rounded p-3 text-sm text-port-error flex items-center gap-2">
- <AlertTriangle size={16} />
- {error}
- </div>
- )}
- {!loading && !error && loras.length === 0 && (
- <div className="text-sm text-gray-500 italic">
- No LoRAs installed yet. Try <code className="bg-port-card px-1 rounded">https://civitai.com/models/2600698/realstagram</code>.
- </div>
+ <SuggestionsPanel
+ suggestions={suggestions}
+ loading={loadingSuggestions}
+ installedFilenames={new Set(loras.map((l) => l.filename))}
+ installingSuggestionKey={installingSuggestion}
+ onRefresh={() => refreshSuggestions({ force: true })}
+ onInstall={async (card) => {
+ const key = `${card.modelId}-${card.versionId}`;
+ setInstallingSuggestion(key);
+ await performInstall(card.installUrl);
+ setInstallingSuggestion(null);
+ }}
+ />
+
+ <div>
+ <h2 className="text-lg font-semibold text-white mb-3">Installed</h2>
+ {loading && <div className="text-sm text-gray-500">Loading…</div>}
+ {error && (
+ <div className="bg-port-error/10 border border-port-error/30 rounded p-3 text-sm text-port-error flex items-center gap-2">
+ <AlertTriangle size={16} />
+ {error}
+ </div>
+ )}
+ {!loading && !error && loras.length === 0 && (
+ <div className="text-sm text-gray-500 italic">
+ No LoRAs installed yet — pick one from the suggestions above, or paste a Civitai URL.
+ </div>
+ )}
+ {loras.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+ {loras.map((lora) => (
+ <LoraCard key={lora.filename} lora={lora} onDelete={() => handleDelete(lora.filename)} deleting={deleting === lora.filename} />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function SuggestionsPanel({ suggestions, loading, installedFilenames, installingSuggestionKey, onRefresh, onInstall }) {
+ const curated = suggestions?.curated || [];
+ const runners = suggestions?.runners || {};
+ const sections = [
+ { key: 'curated', label: 'Curated picks', cards: curated, hint: 'Hand-picked LoRAs that work across multiple base models.' },
+ { key: 'mflux', label: 'Top for Flux 1', cards: runners.mflux || [], hint: 'Most-downloaded LoRAs trained against Flux.1 D / Flux.1 S.' },
+ { key: 'flux2', label: 'Top for Flux 2', cards: runners.flux2 || [], hint: 'Most-downloaded LoRAs trained against Flux.2 Klein.' },
+ { key: 'z-image', label: 'Top for Z-Image', cards: runners['z-image'] || [], hint: 'Z-Image LoRAs are still rare on Civitai — expect a sparse list.' },
+ ];
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Wand2 size={18} className="text-port-accent" />
+ Suggested LoRAs
+ </h2>
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={loading}
+ className="text-xs text-gray-400 hover:text-gray-200 flex items-center gap-1 disabled:opacity-50"
+ title="Re-fetch from Civitai (busts the 1-hour cache)"
+ >
+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
+ Refresh
+ </button>
+ </div>
+ {loading && !suggestions && (
+ <div className="text-sm text-gray-500">Loading suggestions…</div>
)}
+ {sections.map((section) => (
+ <SuggestionsSection
+ key={section.key}
+ label={section.label}
+ hint={section.hint}
+ cards={section.cards}
+ installedFilenames={installedFilenames}
+ installingSuggestionKey={installingSuggestionKey}
+ onInstall={onInstall}
+ />
+ ))}
+ </div>
+ );
+}
- {loras.length > 0 && (
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
- {loras.map((lora) => (
- <LoraCard key={lora.filename} lora={lora} onDelete={() => handleDelete(lora.filename)} deleting={deleting === lora.filename} />
- ))}
+function SuggestionsSection({ label, hint, cards, installedFilenames, installingSuggestionKey, onInstall }) {
+ if (!cards || cards.length === 0) return null;
+ return (
+ <div>
+ <div className="flex items-baseline gap-3 mb-2">
+ <h3 className="text-sm font-medium text-gray-300">{label}</h3>
+ <span className="text-xs text-gray-600">{cards.length}</span>
+ </div>
+ {hint && <p className="text-xs text-gray-500 mb-2">{hint}</p>}
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
+ {cards.map((card) => (
+ <SuggestionCard
+ key={`${card.modelId}-${card.versionId}`}
+ card={card}
+ installed={[...installedFilenames].some((f) => f.includes(`-v${card.versionId}.safetensors`))}
+ installing={installingSuggestionKey === `${card.modelId}-${card.versionId}`}
+ onInstall={() => onInstall(card)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+const RUNNER_LABELS_SHORT = { mflux: 'Flux 1', flux2: 'Flux 2', 'z-image': 'Z-Image' };
+
+function SuggestionCard({ card, installed, installing, onInstall }) {
+ const families = Array.isArray(card.runnerFamilies) && card.runnerFamilies.length
+ ? card.runnerFamilies
+ : (card.runnerFamily ? [card.runnerFamily] : []);
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
+ {card.previewImageUrl ? (
+ <img src={card.previewImageUrl} alt="" className="w-full h-32 object-cover bg-port-bg" loading="lazy" />
+ ) : (
+ <div className="w-full h-32 bg-port-bg flex items-center justify-center text-gray-700">
+ <Sparkles size={24} />
</div>
)}
+ <div className="p-3 flex-1 flex flex-col gap-2">
+ <div className="flex items-start justify-between gap-2">
+ <h4 className="font-semibold text-white text-sm truncate flex-1" title={card.name}>{card.name}</h4>
+ {card.curated && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-warning/20 text-port-warning border border-port-warning/30 whitespace-nowrap">curated</span>
+ )}
+ </div>
+ {families.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {families.map((f) => (
+ <span key={f} className={`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${RUNNER_BADGE_CLASS[f] || 'bg-gray-600/20 text-gray-300 border-gray-500/30'}`}>
+ {RUNNER_LABELS_SHORT[f] || f}
+ </span>
+ ))}
+ </div>
+ )}
+ {card.note && <p className="text-[11px] text-gray-400 italic line-clamp-2">{card.note}</p>}
+ {card.samplePrompt && (
+ <details className="text-[11px] text-gray-500">
+ <summary className="cursor-pointer hover:text-gray-300">Sample prompt</summary>
+ <p className="mt-1 font-mono text-[10px] leading-snug bg-port-bg p-1.5 rounded border border-port-border line-clamp-4">{card.samplePrompt}</p>
+ </details>
+ )}
+ <div className="text-[10px] text-gray-600 flex items-center gap-3 mt-auto">
+ {card.creator && <span className="truncate" title={card.creator}>by {card.creator}</span>}
+ {typeof card.downloads === 'number' && <span>↓ {card.downloads.toLocaleString()}</span>}
+ </div>
+ <div className="flex items-center gap-2">
+ {installed ? (
+ <button disabled className="flex-1 bg-port-success/20 text-port-success border border-port-success/30 px-3 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1">
+ <Check size={12} /> Installed
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={onInstall}
+ disabled={installing}
+ className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 disabled:opacity-50"
+ >
+ {installing ? 'Installing…' : 'Quick install'}
+ </button>
+ )}
+ {card.civitaiUrl && (
+ <a href={card.civitaiUrl} target="_blank" rel="noopener noreferrer" className="text-gray-400 hover:text-gray-200 p-1.5 rounded hover:bg-port-bg" title="Open on Civitai">
+ <ExternalLink size={12} />
+ </a>
+ )}
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 872aabe3a0..8501401ed2 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -134,6 +134,11 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(
silent,
});
+// Civitai LoRA suggestions per runner family. Cached server-side for 1h.
+// Pass `force: true` to bust the cache and re-fetch from Civitai.
+export const getCivitaiSuggestions = ({ force = false } = {}) =>
+ request(`/loras/suggestions${force ? '?force=1' : ''}`);
+
// Civitai auth — read/save/clear the API key. The key never round-trips back
// to the client; the GET only returns `{ hasKey, source }`.
export const getCivitaiAuth = () => request('/loras/auth/civitai');
diff --git a/server/lib/civitai.js b/server/lib/civitai.js
index 5232828bbb..fc02424715 100644
--- a/server/lib/civitai.js
+++ b/server/lib/civitai.js
@@ -228,6 +228,72 @@ export const buildSidecar = ({ model, version, file, filename }) => {
};
};
+// Map a PortOS runner family back to the `baseModels` query param values
+// Civitai's search endpoint expects. Civitai uses %20-encoded display names
+// (`Flux.1 D`, `Flux.1 S`, `Flux.2`, etc.). The Z-Image ecosystem on Civitai
+// is nascent — searches there often return zero; the UI handles that.
+const RUNNER_TO_BASE_MODELS = {
+ mflux: ['Flux.1 D', 'Flux.1 S'],
+ flux2: ['Flux.2'],
+ 'z-image': ['Z-Image'],
+};
+
+// Search Civitai for LoRA-family models targeting the given runner family.
+// Returns the raw `items` array from `/api/v1/models` (each entry has its
+// own `modelVersions[]` etc — let the suggestion service shape them).
+// fetchImpl is injectable for tests.
+export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Most Downloaded', nsfw = false, apiKey, fetchImpl = fetch } = {}) => {
+ const baseModels = RUNNER_TO_BASE_MODELS[runnerFamily];
+ if (!baseModels) {
+ throw new ServerError(`Unknown runner family for Civitai search: ${runnerFamily}`, { status: 400, code: 'CIVITAI_BAD_RUNNER' });
+ }
+ // Civitai accepts repeated `baseModels` query params for OR semantics.
+ // URLSearchParams handles the repeated-key + display-name URL-encoding.
+ const params = new URLSearchParams();
+ params.set('types', 'LORA');
+ params.set('limit', String(Math.max(1, Math.min(100, limit))));
+ params.set('sort', sort);
+ params.set('nsfw', String(!!nsfw));
+ for (const bm of baseModels) params.append('baseModels', bm);
+ const url = `${CIVITAI_API}/models?${params.toString()}`;
+ const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildAuthHeaders(apiKey) } });
+ if (!res.ok) {
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Civitai search rejected (${res.status}) — set CIVITAI_API_KEY in PortOS Settings if NSFW content is enabled`,
+ { status: res.status, code: 'CIVITAI_AUTH' },
+ );
+ }
+ throw new ServerError(`Civitai search failed: ${res.status}`, { status: 502, code: 'CIVITAI_SEARCH_FAILED' });
+ }
+ const body = await res.json();
+ return Array.isArray(body?.items) ? body.items : [];
+};
+
+// Pull a sample prompt from Civitai's preview image metadata. The `meta`
+// field's shape varies wildly — sometimes `{ prompt: '...' }`, sometimes a
+// stringified JSON, sometimes absent. Returns the first usable prompt or
+// null. Skips images flagged at NSFW level > 1 to keep suggestions safe.
+export const extractSamplePrompt = (version) => {
+ const images = Array.isArray(version?.images) ? version.images : [];
+ for (const img of images) {
+ if ((img?.nsfwLevel ?? 0) > 1) continue;
+ const meta = img?.meta;
+ if (meta && typeof meta === 'object' && typeof meta.prompt === 'string' && meta.prompt.trim()) {
+ return meta.prompt.trim();
+ }
+ if (typeof meta === 'string') {
+ // Some entries serialize meta as a JSON string. Defensive parse.
+ let parsed = null;
+ try { parsed = JSON.parse(meta); } catch { /* ignore */ }
+ if (parsed && typeof parsed === 'object' && typeof parsed.prompt === 'string' && parsed.prompt.trim()) {
+ return parsed.prompt.trim();
+ }
+ }
+ }
+ return null;
+};
+
// Sanitize a model name into a safe filename slug. Civitai model names can
// contain `/`, `\`, weird unicode, mixed case, etc. — we want a portable
// filename that also keeps the .safetensors extension predictable. Limits
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 8f3e10abee..0c13c156a2 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -17,6 +17,7 @@ import {
listLoras,
patchLoraSidecar,
} from '../services/loras.js';
+import { getSuggestions } from '../services/civitaiSuggestions.js';
import { getSettings, saveSettings } from '../services/settings.js';
const router = Router();
@@ -25,6 +26,14 @@ router.get('/', asyncHandler(async (_req, res) => {
res.json(await listLoras());
}));
+// Civitai LoRA suggestions per runner family (mflux / flux2 / z-image).
+// Cached server-side for 1h. `?force=1` busts the cache for a manual refresh.
+router.get('/suggestions', asyncHandler(async (req, res) => {
+ const force = req.query.force === '1' || req.query.force === 'true';
+ const limit = Math.max(1, Math.min(24, Number(req.query.limit) || 12));
+ res.json(await getSuggestions({ force, limit }));
+}));
+
// Civitai auth status — returns just whether a key is configured (the key
// itself never leaves the server). The 2-segment path keeps it from
// colliding with the `/:filename` LoRA endpoints below. `source` lets the
diff --git a/server/services/civitaiSuggestions.js b/server/services/civitaiSuggestions.js
new file mode 100644
index 0000000000..eba8d1e6c0
--- /dev/null
+++ b/server/services/civitaiSuggestions.js
@@ -0,0 +1,178 @@
+/**
+ * Civitai LoRA suggestions — pre-scans top LoRAs per runner family
+ * (mflux / flux2 / z-image) so users land on /media/loras with a curated
+ * "quick-install" list instead of a blank install form.
+ *
+ * Cached in-memory with a 1-hour TTL. The cache survives the lifetime of
+ * the server process — first request after a restart fetches fresh.
+ * Each runner family is cached independently so a Z-Image search returning
+ * zero doesn't block re-fetching mflux/flux2.
+ */
+
+import {
+ baseModelToRunner,
+ fetchCivitaiModel,
+ pickPreviewImage,
+ pickVersion,
+ searchCivitaiLoras,
+ extractSamplePrompt,
+} from '../lib/civitai.js';
+import { resolveCivitaiKey } from './loras.js';
+
+const TTL_MS = 60 * 60 * 1000; // 1 hour
+const RUNNER_FAMILIES = ['mflux', 'flux2', 'z-image'];
+
+// Hand-curated picks that always lead the suggestion panel regardless of
+// whether they crack Civitai's "Most Downloaded" leaderboard. Compat per
+// runner is DERIVED from the model's actual modelVersions[].baseModel at
+// fetch time — no need to keep a manual "runnerFamilies" list in sync with
+// what the creator has actually published.
+const CURATED_SUGGESTIONS = [
+ { modelId: 1155749, note: 'Hyperdetailed colored-pencil illustration look — published for multiple base models.' },
+ { modelId: 832858, note: 'Stylized anime-art rendering.' },
+ { modelId: 1349631, note: 'Dark Ghibli-fairytale aesthetic — moody storybook scenes.' },
+ { modelId: 551903, note: 'Ars Midjourney watercolor — soft, painterly fills with bleeding edges.' },
+];
+
+// runnerFamily -> { fetchedAt: number, items: SuggestionCard[] }
+const cache = new Map();
+
+// Shape one Civitai model into the lightweight suggestion-card payload the
+// /media/loras UI consumes. Defensive: any field can be missing on Civitai.
+const buildCard = (model) => {
+ if (!model || typeof model !== 'object') return null;
+ const version = pickVersion(model, null);
+ if (!version) return null;
+ const file = (() => {
+ // pickPrimaryFile throws when no .safetensors — for a suggestion card we
+ // tolerate that and skip the entry rather than poison the whole list.
+ const files = Array.isArray(version.files) ? version.files : [];
+ const safetensors = files.filter((f) => /\.safetensors$/i.test(f?.name || ''));
+ return safetensors.find((f) => f.primary) || safetensors[0] || null;
+ })();
+ if (!file) return null;
+ const previewImage = pickPreviewImage(version);
+ const baseModel = version.baseModel || null;
+ return {
+ modelId: model.id,
+ versionId: version.id,
+ name: model.name || '(unnamed)',
+ description: typeof model.description === 'string' ? model.description.slice(0, 240) : '',
+ creator: model.creator?.username || null,
+ baseModel,
+ runnerFamily: baseModelToRunner(baseModel),
+ triggerWords: Array.isArray(version.trainedWords) ? version.trainedWords : [],
+ samplePrompt: extractSamplePrompt(version),
+ previewImageUrl: previewImage?.url || null,
+ downloads: model.stats?.downloadCount ?? null,
+ rating: model.stats?.rating ?? null,
+ nsfw: !!model.nsfw,
+ fileSizeKB: file.sizeKB ?? null,
+ civitaiUrl: `https://civitai.com/models/${model.id}?modelVersionId=${version.id}`,
+ // The same URL we'd accept on /api/loras/install — the UI passes this
+ // back without re-deriving so adding new URL shapes later only changes
+ // one place.
+ installUrl: `https://civitai.com/models/${model.id}?modelVersionId=${version.id}`,
+ };
+};
+
+// For a curated entry: walk all `modelVersions[]` (not just the primary)
+// to collect every runner family the model has a published version for.
+// `runnerFamilies` on the returned card is what the UI uses to badge
+// "works on Flux 1, Flux 2, Z-Image."
+const buildCuratedCard = (model, note) => {
+ const card = buildCard(model);
+ if (!card) return null;
+ const versions = Array.isArray(model?.modelVersions) ? model.modelVersions : [];
+ const families = new Set();
+ for (const v of versions) {
+ const fam = baseModelToRunner(v?.baseModel);
+ if (fam) families.add(fam);
+ }
+ return {
+ ...card,
+ note: note || '',
+ curated: true,
+ runnerFamilies: [...families],
+ };
+};
+
+const now = () => Date.now();
+
+// Fetch + build curated cards. Each curated entry hits the metadata
+// endpoint independently; one failure (404 / network) doesn't poison the
+// rest. Returns the cards in CURATED_SUGGESTIONS order.
+const fetchCurated = async ({ fetchImpl }) => {
+ const apiKey = await resolveCivitaiKey();
+ const out = await Promise.all(CURATED_SUGGESTIONS.map(async ({ modelId, note }) => {
+ const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl })
+ .catch((err) => {
+ console.log(`⚠️ Curated suggestion ${modelId} fetch failed: ${err?.message || err}`);
+ return null;
+ });
+ if (!model) return null;
+ return buildCuratedCard(model, note);
+ }));
+ return out.filter(Boolean);
+};
+
+// Curated cache is independent from the per-runner cache — same TTL, same
+// stale-fallback behavior on a fetch failure.
+let curatedCache = null;
+
+const getCurated = async ({ fetchImpl, force = false }) => {
+ if (!force && curatedCache && now() - curatedCache.fetchedAt < TTL_MS) return curatedCache.items;
+ const items = await fetchCurated({ fetchImpl }).catch((err) => {
+ console.log(`⚠️ Curated suggestions fetch failed: ${err?.message || err}`);
+ return curatedCache?.items || [];
+ });
+ curatedCache = { fetchedAt: now(), items };
+ return items;
+};
+
+const fetchSuggestionsFor = async (runnerFamily, { fetchImpl, limit, force = false } = {}) => {
+ const cached = cache.get(runnerFamily);
+ if (!force && cached && now() - cached.fetchedAt < TTL_MS) return cached.items;
+ const apiKey = await resolveCivitaiKey();
+ // Civitai's API doesn't strictly require auth for SFW LoRA search but a
+ // configured key gets cleaner ranking and avoids anonymous rate limits.
+ const items = await searchCivitaiLoras({
+ runnerFamily,
+ limit,
+ apiKey,
+ fetchImpl,
+ });
+ const cards = items.map(buildCard).filter(Boolean);
+ cache.set(runnerFamily, { fetchedAt: now(), items: cards });
+ return cards;
+};
+
+// Public API. Returns:
+// - curated: hand-picked cards (always shown first; multi-runner badged)
+// - runners: per-family top-N from Civitai's search endpoint
+// Never throws on partial failure — a Z-Image search returning zero or a
+// transient curated 404 shouldn't kill the whole panel.
+export const getSuggestions = async ({ fetchImpl, limit = 12, force = false } = {}) => {
+ const [curated, runnerEntries] = await Promise.all([
+ getCurated({ fetchImpl, force }),
+ Promise.all(RUNNER_FAMILIES.map(async (family) => {
+ const cards = await fetchSuggestionsFor(family, { fetchImpl, limit, force })
+ .catch((err) => {
+ console.log(`⚠️ Civitai suggestion fetch failed for ${family}: ${err?.message || err}`);
+ return cache.get(family)?.items || [];
+ });
+ return [family, cards];
+ })),
+ ]);
+ return {
+ curated,
+ runners: Object.fromEntries(runnerEntries),
+ fetchedAt: new Date().toISOString(),
+ };
+};
+
+// Test seam — clear all caches between tests.
+export const _resetSuggestionsCache = () => {
+ cache.clear();
+ curatedCache = null;
+};
diff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.js
new file mode 100644
index 0000000000..fca7449d4e
--- /dev/null
+++ b/server/services/civitaiSuggestions.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+let svc;
+
+beforeEach(async () => {
+ vi.resetModules();
+ // Stub settings so resolveCivitaiKey doesn't read data/settings.json.
+ vi.doMock('./settings.js', () => ({ getSettings: async () => ({}) }));
+ svc = await import('./civitaiSuggestions.js');
+ svc._resetSuggestionsCache();
+});
+
+const buildModel = (id, name, baseModel) => ({
+ id,
+ name,
+ type: 'LORA',
+ description: `${name} description`,
+ creator: { username: 'someone' },
+ stats: { downloadCount: 12345, rating: 4.8 },
+ modelVersions: [
+ {
+ id: id * 10,
+ baseModel,
+ trainedWords: [`${name.toLowerCase()}-trigger`],
+ images: [{ url: `https://civitai.com/${id}.jpg`, nsfwLevel: 1, meta: { prompt: `a sample for ${name}` } }],
+ files: [{ name: `${name.replace(/\s/g, '_')}.safetensors`, primary: true, sizeKB: 50000 }],
+ },
+ ],
+});
+
+describe('getSuggestions', () => {
+ it('returns curated + per-runner shape', async () => {
+ const fetchImpl = async (url) => {
+ // Curated direct fetches go through /models/<id>; search goes through /models?...
+ const m = url.match(/api\/v1\/models\/(\d+)$/);
+ if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated-${m[1]}`, 'Flux.1 D') };
+ // Search endpoint — return a list with entries matching the requested baseModel.
+ const search = new URL(url);
+ const baseModels = search.searchParams.getAll('baseModels');
+ const items = baseModels.map((bm, i) => buildModel(9000 + i, `Top-${bm}-${i}`, bm));
+ return { ok: true, status: 200, json: async () => ({ items }) };
+ };
+ const out = await svc.getSuggestions({ fetchImpl, limit: 5 });
+ expect(Array.isArray(out.curated)).toBe(true);
+ expect(out.curated.length).toBeGreaterThan(0);
+ expect(out.runners).toHaveProperty('mflux');
+ expect(out.runners).toHaveProperty('flux2');
+ expect(out.runners).toHaveProperty('z-image');
+ expect(out.runners.mflux.length).toBeGreaterThan(0);
+ // Curated entries are flagged + carry a note.
+ expect(out.curated[0].curated).toBe(true);
+ expect(typeof out.curated[0].note).toBe('string');
+ expect(typeof out.fetchedAt).toBe('string');
+ });
+
+ it('survives a curated fetch failure (one bad id) without dropping the rest', async () => {
+ let calls = 0;
+ const fetchImpl = async (url) => {
+ const m = url.match(/api\/v1\/models\/(\d+)$/);
+ if (m) {
+ calls += 1;
+ // First curated call 404s; rest succeed.
+ if (calls === 1) return { ok: false, status: 404 };
+ return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Ok-${m[1]}`, 'Flux.1 D') };
+ }
+ return { ok: true, status: 200, json: async () => ({ items: [buildModel(9999, 'Search', 'Flux.1 D')] }) };
+ };
+ const out = await svc.getSuggestions({ fetchImpl });
+ // The first curated entry was dropped, but we should still have the others.
+ expect(out.curated.length).toBeGreaterThan(0);
+ expect(out.runners.mflux.length).toBe(1);
+ });
+
+ it('caches per-runner results across calls (no re-fetch within TTL)', async () => {
+ let calls = 0;
+ const fetchImpl = async (url) => {
+ calls += 1;
+ const m = url.match(/api\/v1\/models\/(\d+)$/);
+ if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };
+ return { ok: true, status: 200, json: async () => ({ items: [buildModel(1, 'Cached', 'Flux.1 D')] }) };
+ };
+ await svc.getSuggestions({ fetchImpl });
+ const callsAfterFirst = calls;
+ await svc.getSuggestions({ fetchImpl });
+ // Second call should hit cache for both curated and runners — no new HTTP.
+ expect(calls).toBe(callsAfterFirst);
+ });
+
+ it('force=true busts the cache', async () => {
+ let calls = 0;
+ const fetchImpl = async (url) => {
+ calls += 1;
+ const m = url.match(/api\/v1\/models\/(\d+)$/);
+ if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `C`, 'Flux.1 D') };
+ return { ok: true, status: 200, json: async () => ({ items: [] }) };
+ };
+ await svc.getSuggestions({ fetchImpl });
+ const callsAfterFirst = calls;
+ await svc.getSuggestions({ fetchImpl, force: true });
+ expect(calls).toBeGreaterThan(callsAfterFirst);
+ });
+
+ it('curated card derives runnerFamilies from ALL the model versions', async () => {
+ const fetchImpl = async (url) => {
+ const m = url.match(/api\/v1\/models\/(\d+)$/);
+ if (m) {
+ // Multi-version model — Flux.1 D + Flux.2.
+ const id = Number(m[1]);
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ ...buildModel(id, 'Multi', 'Flux.1 D'),
+ modelVersions: [
+ { id: id * 10, baseModel: 'Flux.1 D', trainedWords: [], images: [], files: [{ name: 'a.safetensors', primary: true }] },
+ { id: id * 10 + 1, baseModel: 'Flux.2', trainedWords: [], images: [], files: [{ name: 'b.safetensors', primary: true }] },
+ ],
+ }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({ items: [] }) };
+ };
+ const out = await svc.getSuggestions({ fetchImpl });
+ const card = out.curated[0];
+ expect(card.runnerFamilies).toContain('mflux');
+ expect(card.runnerFamilies).toContain('flux2');
+ });
+});