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
feat(image-gen): ERNIE-Image runner + per-runner multi-version curated cards
Adam Eivyec75449f17d6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bf23b760e1..16504cf59d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **ERNIE-Image runner.** Adds `runner: 'ernie'` so PortOS can drive Baidu's ERNIE-Image (8B DiT, Apache 2.0, no HF login) — both the SFT model (`baidu/ERNIE-Image`, 50 steps, guidance 4.0) and the Turbo distilled variant (`baidu/ERNIE-Image-Turbo`, 8 steps, CFG-disabled). Reuses the FLUX.2 venv (same diffusers + torch stack, no extra setup step). The runner script gains a generic `--pipeline-class` arg (used here for `ErnieImagePipeline` since it isn't yet in `AutoPipelineForText2Image`'s registry) and a `--use-pe` flag for ERNIE's built-in Prompt Enhancer module — both passed only when the loaded pipe accepts them, so existing Z-Image renders are unaffected. LoRA picker, suggestion search, and Civitai's `baseModel` mapping all gain the `'ernie'` family.+- **Multi-version curated cards** — a curated suggestion (e.g. `hyperdetailed-colored-pencil`) typically has separate Civitai versions per base model (Flux.1, Flux 2 Klein 4B, Klein 9B, Z-Image-Turbo, ERNIE…). The card now renders one **Install for X** button per available family, each installing the family-specific version via that family's `?modelVersionId=...`. Buttons flip to ✓ Installed independently, so you can install the Flux 2 version today and the Z-Image one later. Server-side `buildCuratedCard()` walks every `modelVersions[]` entry and builds an `installs: { mflux, flux2, 'z-image', ernie }` map (first match per family wins; versions without a `.safetensors` file are skipped).- **One-click LoRA trigger-word insertion.** Each selected LoRA in the Image Gen picker now exposes a small `+ trigger` button next to its scale input — click it to append the LoRA's trigger words to the prompt, comma-separated, deduped (case-insensitive substring match against the existing prompt so re-clicking is a no-op). The "Test" deep-link from the LoRAs manager page (`/media/image?lora=<filename>`) also auto-inserts the trigger words on preselect — when a user clicks "Test this LoRA," they want to actually see the LoRA fire, which most LoRAs only do once the trigger is in the prompt. Helper `appendTriggerWords()` lives in `ImageGen.jsx` for now; would extract to `genUtils.js` if reused elsewhere.- **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.diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex 1040bd3c65..070f606675 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -26,11 +26,13 @@ const RUNNER_LABEL = {mflux: 'Flux 1',flux2: 'Flux 2','z-image': 'Z-Image',+ ernie: 'ERNIE',};const RUNNER_BADGE_CLASS = {mflux: 'bg-port-accent/20 text-port-accent border-port-accent/30',flux2: 'bg-purple-600/20 text-purple-300 border-purple-500/30','z-image': 'bg-emerald-600/20 text-emerald-300 border-emerald-500/30',+ ernie: 'bg-amber-600/20 text-amber-300 border-amber-500/30',};export default function Loras() {@@ -184,10 +186,13 @@ export default function Loras() {installedFilenames={new Set(loras.map((l) => l.filename))}installingSuggestionKey={installingSuggestion}onRefresh={() => refreshSuggestions({ force: true })}- onInstall={async (card) => {- const key = `${card.modelId}-${card.versionId}`;+ onInstall={async (card, url, versionId) => {+ // Curated cards pass a family-specific (url, versionId); non-curated+ // cards omit versionId and we fall back to the card's primary.+ const vid = versionId ?? card.versionId;+ const key = `${card.modelId}-${vid}`;setInstallingSuggestion(key);- await performInstall(card.installUrl);+ await performInstall(url || card.installUrl);setInstallingSuggestion(null);}}/>@@ -226,6 +231,7 @@ function SuggestionsPanel({ suggestions, loading, installedFilenames, installing{ 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.' },+ { key: 'ernie', label: 'Top for ERNIE', cards: runners.ernie || [], hint: 'ERNIE-Image LoRAs are still rare on Civitai — expect a sparse list.' },];return (<div className="space-y-4">@@ -277,9 +283,9 @@ function SuggestionsSection({ label, hint, cards, installedFilenames, installing<SuggestionCardkey={`${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)}+ installedFilenames={installedFilenames}+ installingSuggestionKey={installingSuggestionKey}+ onInstall={onInstall}/>))}</div>@@ -287,12 +293,20 @@ function SuggestionsSection({ label, hint, cards, installedFilenames, installing);}-const RUNNER_LABELS_SHORT = { mflux: 'Flux 1', flux2: 'Flux 2', 'z-image': 'Z-Image' };+const RUNNER_LABELS_SHORT = { mflux: 'Flux 1', flux2: 'Flux 2', 'z-image': 'Z-Image', ernie: 'ERNIE' };-function SuggestionCard({ card, installed, installing, onInstall }) {- const families = Array.isArray(card.runnerFamilies) && card.runnerFamilies.length- ? card.runnerFamilies- : (card.runnerFamily ? [card.runnerFamily] : []);+function SuggestionCard({ card, installedFilenames, installingSuggestionKey, onInstall }) {+ const installs = card.curated && card.installs && Object.keys(card.installs).length > 0 ? card.installs : null;+ // Badges: prefer the installs map's keys (per-family with versions), else+ // the runnerFamilies array, else the single primary-version family.+ const badgeFamilies = installs+ ? Object.keys(installs)+ : (Array.isArray(card.runnerFamilies) && card.runnerFamilies.length+ ? card.runnerFamilies+ : (card.runnerFamily ? [card.runnerFamily] : []));+ const isInstalled = (versionId) => versionId != null+ && [...installedFilenames].some((f) => f.includes(`-v${versionId}.safetensors`));+ const isInstalling = (versionId) => installingSuggestionKey === `${card.modelId}-${versionId}`;return (<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">{card.previewImageUrl ? (@@ -309,9 +323,9 @@ function SuggestionCard({ card, installed, installing, onInstall }) {<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 && (+ {badgeFamilies.length > 0 && !installs && (<div className="flex flex-wrap gap-1">- {families.map((f) => (+ {badgeFamilies.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>@@ -329,27 +343,55 @@ function SuggestionCard({ card, installed, installing, onInstall }) {{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>+ {installs ? (+ <div className="flex flex-col gap-1">+ <p className="text-[10px] uppercase tracking-wide text-gray-500">Install for</p>+ <div className="flex flex-wrap gap-1.5">+ {Object.entries(installs).map(([family, info]) => {+ const installed = isInstalled(info.versionId);+ const installing = isInstalling(info.versionId);+ const baseClass = installed+ ? 'bg-port-success/20 text-port-success border-port-success/30'+ : (RUNNER_BADGE_CLASS[family] || 'bg-port-accent/20 text-port-accent border-port-accent/30');+ return (+ <button+ key={family}+ type="button"+ onClick={() => onInstall(card, info.installUrl, info.versionId)}+ disabled={installed || installing}+ title={installed ? 'Already installed' : `Install ${info.baseModel || family} version`}+ className={`text-[11px] px-2 py-1 rounded border flex items-center gap-1 ${baseClass} hover:brightness-125 disabled:opacity-60 disabled:cursor-not-allowed`}+ >+ {installed ? <Check size={11} /> : null}+ {installing ? 'Installing…' : (RUNNER_LABELS_SHORT[family] || family)}+ </button>+ );+ })}+ </div>+ </div>+ ) : (+ <div className="flex items-center gap-2">+ {isInstalled(card.versionId) ? (+ <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(card, card.installUrl, card.versionId)}+ disabled={isInstalling(card.versionId)}+ 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"+ >+ {isInstalling(card.versionId) ? 'Installing…' : 'Quick install'}+ </button>+ )}+ </div>+ )}+ {card.civitaiUrl && (+ <a href={card.civitaiUrl} target="_blank" rel="noopener noreferrer" className="text-[10px] text-gray-500 hover:text-gray-300 inline-flex items-center gap-1 self-start" title="Open on Civitai">+ <ExternalLink size={11} /> View on Civitai+ </a>+ )}</div></div>);diff --git a/data.sample/media-models.json b/data.sample/media-models.jsonindex f70475695d..233f85dae9 100644--- a/data.sample/media-models.json+++ b/data.sample/media-models.json@@ -111,6 +111,27 @@"guidance": 1,"cfgDisabled": true},+ {+ "id": "ernie-image",+ "name": "ERNIE-Image (~16 GB @ bf16, 50 steps)",+ "runner": "ernie",+ "repo": "baidu/ERNIE-Image",+ "pipelineClass": "ErnieImagePipeline",+ "usePromptEnhancer": true,+ "steps": 50,+ "guidance": 4+ },+ {+ "id": "ernie-image-turbo",+ "name": "ERNIE-Image-Turbo (~16 GB @ bf16, 8 steps)",+ "runner": "ernie",+ "repo": "baidu/ERNIE-Image-Turbo",+ "pipelineClass": "ErnieImagePipeline",+ "usePromptEnhancer": true,+ "steps": 8,+ "guidance": 1,+ "cfgDisabled": true+ },{"id": "z-image-turbo-quant","name": "Z-Image-Turbo (community quantized)",diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 17007d9d1f..3b6075bc44 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -210,6 +210,7 @@ fiif [[ "$INSTALL_FLUX2" == "1" ]]; thenecho " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"echo " Z-Image: reuses the FLUX.2 venv (Apache 2.0, no HF login needed)"+ echo " ERNIE: reuses the FLUX.2 venv (Apache 2.0, no HF login needed)"echo ""echo "⚠️ FLUX.2-klein needs HF auth: accept the license at"echo " https://huggingface.co/black-forest-labs/FLUX.2-klein-4B"diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.pyindex 6edc2ba502..9a9db30429 100644--- a/scripts/z_image_turbo.py+++ b/scripts/z_image_turbo.py@@ -51,19 +51,28 @@ def make_generator(device: str, seed: int) -> torch.Generator:return torch.Generator().manual_seed(int(seed))-def load_pipeline(repo: str, device: str, dtype):- # AutoPipelineForText2Image reads the repo's model_index.json and resolves- # the right pipeline class — works for ZImagePipeline as well as community- # quantized ports that subclass it.- from diffusers import AutoPipelineForText2Image+def load_pipeline(repo: str, device: str, dtype, pipeline_class: str = ""):+ # When the registry pins a pipeline class (e.g. ErnieImagePipeline,+ # which isn't yet in AutoPipelineForText2Image's registry) load it+ # directly. Falls back to AutoPipelineForText2Image so Z-Image-Turbo+ # and any future registered model continues to work without a flag.+ import diffusersprint(f"STAGE:download-pipeline:{repo}", file=sys.stderr, flush=True)- print(f"🔧 z-image: pipeline ← {repo}", file=sys.stderr)- pipe = AutoPipelineForText2Image.from_pretrained(- repo,- torch_dtype=dtype,- low_cpu_mem_usage=True,- )+ print(f"🔧 diffusers runner: pipeline ← {repo} (class={pipeline_class or 'auto'})", file=sys.stderr)+ if pipeline_class:+ cls = getattr(diffusers, pipeline_class, None)+ if cls is None:+ print(f"❌ Unknown diffusers pipeline class: {pipeline_class}", file=sys.stderr)+ sys.exit(2)+ pipe = cls.from_pretrained(repo, torch_dtype=dtype, low_cpu_mem_usage=True)+ else:+ from diffusers import AutoPipelineForText2Image+ pipe = AutoPipelineForText2Image.from_pretrained(+ repo,+ torch_dtype=dtype,+ low_cpu_mem_usage=True,+ )print("STAGE:move-to-device", file=sys.stderr, flush=True)pipe.to(device)return pipe@@ -162,6 +171,8 @@ def parse_args() -> argparse.Namespace:p.add_argument("--device", default="auto", choices=["auto", "mps", "cuda", "cpu"])p.add_argument("--lora-paths", nargs="*", default=[], help="absolute paths to LoRA .safetensors files")p.add_argument("--lora-scales", nargs="*", default=[], help="scale per LoRA, parallel to --lora-paths")+ p.add_argument("--pipeline-class", default="", help="optional explicit diffusers pipeline class (e.g. ErnieImagePipeline)")+ p.add_argument("--use-pe", action="store_true", help="enable the prompt enhancer (ERNIE-Image's use_pe kwarg)")return p.parse_args()@@ -171,7 +182,7 @@ def main() -> None:device = pick_device(args.device)dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32- pipe = load_pipeline(args.repo, device, dtype)+ pipe = load_pipeline(args.repo, device, dtype, pipeline_class=args.pipeline_class)init_image = Noneif args.image_path:@@ -223,6 +234,11 @@ def main() -> None:vae.disable_tiling()if args.image_strength is not None and "strength" in accepted:pipe_kwargs["strength"] = float(args.image_strength)+ # ERNIE-Image's prompt enhancer — only pass when the loaded pipeline+ # exposes the kwarg (signature filter keeps Z-Image and other models+ # unaffected).+ if args.use_pe and "use_pe" in accepted:+ pipe_kwargs["use_pe"] = Trueprint("STAGE:inference", file=sys.stderr, flush=True)print(diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex 67ec73a967..a6a2ef403c 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -32,6 +32,7 @@ export const baseModelToRunner = (baseModel) => {if (b.startsWith('flux.1') || b.startsWith('flux 1') || b === 'flux1') return 'mflux';if (b.startsWith('flux.2') || b.startsWith('flux 2') || b === 'flux2') return 'flux2';if (b.startsWith('z-image') || b.startsWith('zimage') || b.startsWith('z image')) return 'z-image';+ if (b.startsWith('ernie-image') || b.startsWith('ernie image') || b.startsWith('ernieimage') || b === 'ernie') return 'ernie';// SDXL / SD1.5 / Pony / Illustrious / etc. — none currently supported by// any PortOS runner. Surfacing them in the UI as "incompatible" is more// useful than hiding them entirely.@@ -258,6 +259,7 @@ const RUNNER_TO_BASE_MODELS = {mflux: ['Flux.1 D', 'Flux.1 S'],flux2: ['Flux.2'],'z-image': ['Z-Image'],+ ernie: ['Ernie-Image', 'ERNIE-Image'],};// Search Civitai for LoRA-family models targeting the given runner family.diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex dce5afe573..6c44c35783 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -65,6 +65,11 @@ describe('baseModelToRunner', () => {expect(baseModelToRunner('Z-Image Turbo')).toBe('z-image');expect(baseModelToRunner('zimage')).toBe('z-image');});+ it('maps ERNIE-Image variants to ernie', () => {+ expect(baseModelToRunner('Ernie-Image')).toBe('ernie');+ expect(baseModelToRunner('ERNIE-Image-Turbo')).toBe('ernie');+ expect(baseModelToRunner('ernieimage')).toBe('ernie');+ });it('returns null for unsupported families', () => {expect(baseModelToRunner('SDXL 1.0')).toBe(null);expect(baseModelToRunner('SD 1.5')).toBe(null);diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 02b11e8b6b..4847fdb8bc 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -101,6 +101,31 @@ const DEFAULT_REGISTRY = {guidance: 1.0,cfgDisabled: true,},+ // ernie runner — Baidu's ERNIE-Image (8B DiT). Apache 2.0, ungated,+ // reuses the FLUX.2 venv. Pipeline class isn't in AutoPipelineForText2Image's+ // registry yet so we pass `pipelineClass: 'ErnieImagePipeline'` for+ // explicit dispatch. `usePromptEnhancer` activates the built-in PE module.+ {+ id: 'ernie-image',+ name: 'ERNIE-Image (~16 GB @ bf16, 50 steps)',+ runner: 'ernie',+ repo: 'baidu/ERNIE-Image',+ pipelineClass: 'ErnieImagePipeline',+ usePromptEnhancer: true,+ steps: 50,+ guidance: 4.0,+ },+ {+ id: 'ernie-image-turbo',+ name: 'ERNIE-Image-Turbo (~16 GB @ bf16, 8 steps)',+ runner: 'ernie',+ repo: 'baidu/ERNIE-Image-Turbo',+ pipelineClass: 'ErnieImagePipeline',+ usePromptEnhancer: true,+ steps: 8,+ guidance: 1.0,+ cfgDisabled: true,+ },{id: 'z-image-turbo-quant',name: 'Z-Image-Turbo (community quantized)',@@ -198,6 +223,7 @@ const CFG_DISABLED_IDS = new Set(['flux2-klein-4b-int8','z-image-turbo-bf16','z-image-turbo-quant',+ 'ernie-image-turbo',]);const backfillCfgDisabled = (list) => {@@ -212,6 +238,7 @@ const backfillCfgDisabled = (list) => {export const isFlux2 = (model) => model?.runner === 'flux2';export const isZImage = (model) => model?.runner === 'z-image';+export const isErnie = (model) => model?.runner === 'ernie';export const isCfgDisabled = (model) => model?.cfgDisabled === true;// Append models that are genuinely new in this release (not indiff --git a/server/services/civitaiSuggestions.js b/server/services/civitaiSuggestions.jsindex 993526ea24..de5a7a22a3 100644--- a/server/services/civitaiSuggestions.js+++ b/server/services/civitaiSuggestions.js@@ -21,7 +21,7 @@ import {import { resolveCivitaiKey } from './loras.js';const TTL_MS = 60 * 60 * 1000; // 1 hour-const RUNNER_FAMILIES = ['mflux', 'flux2', 'z-image'];+const RUNNER_FAMILIES = ['mflux', 'flux2', 'z-image', 'ernie'];// Hand-curated picks that always lead the suggestion panel regardless of// whether they crack Civitai's "Most Downloaded" leaderboard. Compat per@@ -78,24 +78,40 @@ const buildCard = (model) => {};};-// 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."+// For a curated entry: walk every modelVersions[] entry (not just the+// primary) and build a per-runner-family install map. The UI renders one+// "Install for X" button per entry — clicking it installs the family-+// specific version, not whatever version happens to be most recent overall.+//+// Civitai authors typically publish multiple versions of the same model+// (one per base model — Flux.1 D, Flux.2 Klein 9B, Z-Image-Turbo, ERNIE,+// etc.). We pick the FIRST (most-recent in API order) version per family+// so users get the latest re-train without picking versions by hand.const buildCuratedCard = (model, note) => {const card = buildCard(model);if (!card) return null;const versions = Array.isArray(model?.modelVersions) ? model.modelVersions : [];- const families = new Set();+ const installs = {};for (const v of versions) {const fam = baseModelToRunner(v?.baseModel);- if (fam) families.add(fam);+ if (!fam || installs[fam]) continue; // first match wins per family+ const files = Array.isArray(v.files) ? v.files : [];+ const safetensors = files.filter((f) => /\.safetensors$/i.test(f?.name || ''));+ if (!safetensors.length) continue; // no installable file for this family+ const file = safetensors.find((f) => f.primary) || safetensors[0];+ installs[fam] = {+ versionId: v.id,+ baseModel: v.baseModel || null,+ sizeKB: file.sizeKB ?? null,+ installUrl: model?.id ? `https://civitai.com/models/${model.id}?modelVersionId=${v.id}` : null,+ };}return {...card,note: note || '',curated: true,- runnerFamilies: [...families],+ runnerFamilies: Object.keys(installs),+ installs,};};diff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.jsindex fca7449d4e..f8ee3d85fc 100644--- a/server/services/civitaiSuggestions.test.js+++ b/server/services/civitaiSuggestions.test.js@@ -100,6 +100,45 @@ describe('getSuggestions', () => {expect(calls).toBeGreaterThan(callsAfterFirst);});+ it('curated card produces a per-runner-family installs map (one entry per family, first version wins)', async () => {+ const fetchImpl = async (url) => {+ const m = url.match(/api\/v1\/models\/(\d+)$/);+ if (m) {+ const id = Number(m[1]);+ return {+ ok: true,+ status: 200,+ json: async () => ({+ ...buildModel(id, 'Multi', 'Flux.1 D'),+ modelVersions: [+ // Most recent (first) per family wins. Two flux2 versions —+ // only the first should be in installs.flux2.+ { id: 100, baseModel: 'Flux.2', files: [{ name: 'a.safetensors', primary: true, sizeKB: 1024 }] },+ { id: 99, baseModel: 'Flux.2', files: [{ name: 'older.safetensors', primary: true, sizeKB: 900 }] },+ { id: 80, baseModel: 'Z-Image', files: [{ name: 'z.safetensors', primary: true, sizeKB: 800 }] },+ { id: 70, baseModel: 'Ernie-Image', files: [{ name: 'e.safetensors', primary: true, sizeKB: 700 }] },+ { id: 60, baseModel: 'Flux.1 D', files: [{ name: 'f1.safetensors', primary: true, sizeKB: 600 }] },+ // Unsupported base — shouldn't appear in installs+ { id: 50, baseModel: 'SDXL 1.0', files: [{ name: 's.safetensors', primary: true, sizeKB: 500 }] },+ ],+ }),+ };+ }+ return { ok: true, status: 200, json: async () => ({ items: [] }) };+ };+ const out = await svc.getSuggestions({ fetchImpl });+ const card = out.curated[0];+ expect(card.installs).toBeDefined();+ expect(card.installs.flux2.versionId).toBe(100); // first match wins+ expect(card.installs['z-image'].versionId).toBe(80);+ expect(card.installs.ernie.versionId).toBe(70);+ expect(card.installs.mflux.versionId).toBe(60);+ // Unsupported base model excluded+ expect(card.installs.sdxl).toBeUndefined();+ // installUrl carries modelVersionId so the install path picks the right version+ expect(card.installs.flux2.installUrl).toMatch(/modelVersionId=100/);+ });+it('curated card derives runnerFamilies from ALL the model versions', async () => {const fetchImpl = async (url) => {const m = url.match(/api\/v1\/models\/(\d+)$/);diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex d861680879..31c18c0502 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -27,7 +27,7 @@ import { hfTokenEnv } from '../../lib/hfToken.js';const IS_WIN = process.platform === 'win32';-import { getImageModels, isFlux2, isZImage } from '../../lib/mediaModels.js';+import { getImageModels, isFlux2, isZImage, isErnie } from '../../lib/mediaModels.js';export const IMAGE_MODELS = Object.fromEntries(getImageModels().map((m) => [m.id, m]));@@ -67,20 +67,20 @@ export const cancel = () => {export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths = [], loraScales = [], stepwiseDir, initImagePath, initImageStrength }) => {const modelId = model?.id;- if (isZImage(model)) {+ if (isZImage(model) || isErnie(model)) {if (!model.repo) {throw new ServerError(- `Z-Image model "${modelId}" is missing the 'repo' field in data/media-models.json`,- { status: 500, code: 'IMAGE_GEN_Z_IMAGE_MISCONFIGURED' },+ `${isErnie(model) ? 'ERNIE' : 'Z-Image'} model "${modelId}" is missing the 'repo' field in data/media-models.json`,+ { status: 500, code: isErnie(model) ? 'IMAGE_GEN_ERNIE_MISCONFIGURED' : 'IMAGE_GEN_Z_IMAGE_MISCONFIGURED' },);}- // Z-Image reuses the FLUX.2 venv — same diffusers/torch stack, no extra- // setup step. Same not-installed error code as flux2 so the UI's existing- // "run setup" CTA fires for both runners.- const zImagePython = resolveFlux2Python();- if (!zImagePython) {+ // Z-Image / ERNIE both reuse the FLUX.2 venv (same diffusers + torch+ // stack, no extra setup). Same not-installed error code so the UI's+ // existing "run setup" CTA fires for any of these runners.+ const torchPython = resolveFlux2Python();+ if (!torchPython) {throw new ServerError(- `Image-gen torch venv not found. Run \`INSTALL_FLUX2=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected at ${FLUX2_VENV_DEFAULT}). Z-Image and FLUX.2 share this venv.`,+ `Image-gen torch venv not found. Run \`INSTALL_FLUX2=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected at ${FLUX2_VENV_DEFAULT}). FLUX.2, Z-Image, and ERNIE share this venv.`,{ status: 400, code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED' },);}@@ -103,7 +103,9 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, heif (stepwiseDir) args.push('--stepwise-image-output-dir', stepwiseDir);if (loraPaths?.length) args.push('--lora-paths', ...loraPaths);if (loraScales?.length) args.push('--lora-scales', ...loraScales.map(String));- return { bin: zImagePython, args };+ if (model.pipelineClass) args.push('--pipeline-class', String(model.pipelineClass));+ if (model.usePromptEnhancer) args.push('--use-pe');+ return { bin: torchPython, args };}if (isFlux2(model)) {if (!model.repo) {@@ -215,7 +217,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m// Both flux2 and z-image runners resolve their own Python via the FLUX.2// venv — only the legacy mflux/imagine_win path needs the user-configured// Settings > Image Gen pythonPath.- if (!isFlux2(model) && !isZImage(model) && !pythonPath) {+ if (!isFlux2(model) && !isZImage(model) && !isErnie(model) && !pythonPath) {throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });}// FLUX.2 and Z-Image runners now load LoRAs via diffusers'diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex 4b91642ad3..376217db37 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -305,4 +305,34 @@ describe('imageGen local.buildArgs z-image dispatch', () => {expect(withNeg).toContain('--negative-prompt');expect(withNeg[withNeg.indexOf('--negative-prompt') + 1]).toBe('blurry');});++ it('routes ERNIE models through the same script with --pipeline-class + --use-pe', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { bin, args } = buildArgs({+ ...baseInput,+ model: {+ id: 'ernie-image',+ runner: 'ernie',+ repo: 'baidu/ERNIE-Image',+ pipelineClass: 'ErnieImagePipeline',+ usePromptEnhancer: true,+ },+ });+ expect(bin).toBe('/fake/venv-flux2/bin/python3');+ expect(args[0]).toMatch(/scripts[/\\]z_image_turbo\.py$/);+ expect(args).toContain('--pipeline-class');+ expect(args[args.indexOf('--pipeline-class') + 1]).toBe('ErnieImagePipeline');+ expect(args).toContain('--use-pe');+ expect(args[args.indexOf('--repo') + 1]).toBe('baidu/ERNIE-Image');+ });++ it('omits --pipeline-class and --use-pe when the registry entry doesn\'t set them', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { args } = buildArgs({+ ...baseInput,+ model: { id: 'z-image-turbo-bf16', runner: 'z-image', repo: 'Tongyi-MAI/Z-Image-Turbo' },+ });+ expect(args).not.toContain('--pipeline-class');+ expect(args).not.toContain('--use-pe');+ });});