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(image-gen): Z-Image-Turbo runner + Civitai LoRA manager

Adam Eivy67c09a55faff
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1055e59529..a2b9003b3e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,13 +2,18 @@
## Added
+- **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`).
- **World Builder for Media Gen.** A new `Media Gen → World Builder` tab (`/media/world-builder`) takes a one-line starter prompt — e.g. "moebius and scavengers reign meets Prophet inspired sci fi universe" — and asks the LLM of your choice to expand it into a structured prompt set: a positive `stylePrompt` prefix, a `negativePrompt`, and 6–10 variations across five canonical buckets (landscapes, environments, characters, structures, vehicles). You can edit any field, save the world, then kick off a batch render that compiles `stylePrompt + variation.prompt` for every selected bucket and queues them through the existing image-gen pipeline (local mflux or Codex; external SD-API not supported for batches). Each batch lands in an auto-named Media Collection ("World: <name> — <timestamp>") so the renders stay grouped with the template that produced them. Worlds support full CRUD, the LLM provider/model is per-template (falls back to active provider), and runs are logged with deep-links into the resulting collection. Backed by `server/services/worldBuilder.js` (storage + prompt compilation), `server/services/worldBuilderExpand.js` (LLM call), `server/routes/worldBuilder.js` (REST surface), and `server/services/worldBuilderCollectionHook.js` (hooks media-job completion → collection assignment). State persists in `data/world-builder.json`. 20 new tests cover sanitizers, compile-prompts logic, and the route surface.
- **Workflow tab in Chief of Staff with canonical project-maintenance ordering.** A new `/cos/workflow` page (and a `Workflow` tab in the CoS panel) renders the full set of scheduled tasks and autonomous jobs as a left-to-right pipeline grouped into seven canonical stages — Hygiene → Review → Plan → Audit → Build → Report → Ambient — so it's obvious which work happens before which. Each card surfaces its own schedule, last-run time, run count, enabled state, and live "due / waiting / disabled / waiting-on-dependencies" badge, plus inline `runAfter` arrows showing hard prerequisites. Backed by a new `GET /api/cos/workflow` endpoint and `server/services/workflow.js` with stage definitions, gate state for jobs, and dependency edges. Two default `runAfter` wirings ship with this: `do-replan` runs after `pr-reviewer` and `branch-cleanup` (so the plan reflects merged reality), and `feature-ideas` runs after `do-replan` (so new feature work lands on a fresh plan). Both can be overridden per task or per app from the existing Schedule tab.
- **Clean button on Image Gen lightbox.** Generated images now expose a Clean control with `Light` and `Aggressive` options that runs the dev-tool Image Cleaner (median denoise + C2PA strip + sharp re-encode) over the file in place and writes the result back to the gallery as `<base>_clean-<level>.png` with the source's prompt/seed/model carried forward in a sidecar. New endpoint `POST /api/image-gen/:filename/clean` (refactors the cleaning core out of `imageClean.js` so both the base64 and file paths share `cleanImageBuffer()`) and a `cleanGalleryImage(filename, level)` client API. Idempotent at a level (re-running Light overwrites the previous Light copy) and the new image is spliced to the top of the gallery without a refetch. 10 new tests cover happy path, level differences, idempotency, traversal/PNG-only/missing-source rejections, and sidecar lineage.
+- **Render queue embedded on Image Gen and Video Gen pages; standalone `/media/queue` page removed.** Both `/media/image` and `/media/video` now render a compact, kind-filtered live queue inline beneath the form — live job rows (with cancel) plus a collapsible "recent" toggle — backed by the existing `/api/media-jobs?kind=image|video` endpoint (no new server surface). The dedicated `/media/queue` page (`pages/RenderQueue.jsx`), its `Render Queue` tab in the Media Gen tab strip, the App.jsx route, and the `nav.media.queue` ⌘K / voice-nav entry are all gone — the new inline component (`client/src/components/media/MediaJobsQueue.jsx`) replaces it everywhere.
- **Dismissible AI Recommendations on the Learning tab.** Each recommendation in the Chief of Staff Learning Analytics panel now has an X to dismiss it. Dismissals persist to `data/cos/dismissed-recommendations.json` and are filtered out of future loads. For count-based alerts (e.g., "unknown errors occurred 74 times"), the dismissal records the count snapshot and only re-surfaces if the count grows materially worse (≥1.5× and at least +20). Rate-based recommendations stay dismissed until restored. A "Show dismissed" expander lets you restore individual entries or clear them all.
## Fixed
+- **Guidance input hidden for distilled image models; runner stops emitting "Guidance scale X is ignored" warnings.** Step-wise distilled image models (Flux 1 Schnell, FLUX.2 Klein 4B/9B/Int8, Z-Image-Turbo) bake classifier-free guidance internally — any guidance scale > 1.0 is silently dropped by diffusers, which logs a noisy `"Guidance scale 7.0 is ignored for step-wise distilled models."` line on every render. The registry now flags those entries with `cfgDisabled: true` (backfilled on existing installs by id, in `server/lib/mediaModels.js → backfillCfgDisabled`), the Image Gen / World Builder Guidance input is hidden when the selected model has the flag set, and `server/services/imageGen/local.js` pins the resolved guidance to `1.0` for cfgDisabled models so the runner's diffusers call stays quiet and the saved metadata sidecar reflects the value the model actually used. Any user override of `cfgDisabled` (true OR false) on a custom registry entry wins.
- **World Builder expansion no longer 0-variations on Codex CLI responses.** The expand-starter step had three failure modes against Codex's CLI provider that all manifested as "Expanded into 0 variations": (1) Codex echoes the user prompt back to stdout before the model's reply, and the prompt itself contains a JSON-shaped *schema example* (`{ "label": string (max 80 chars), "prompt": … }`) — its braces balance but its contents are not valid JSON, so the previous first-balanced-block extractor crashed on it; (2) Codex occasionally emits an orphan `}` between a variation's close-brace and the array's `]` (`…blister"}}]}}}`), making `JSON.parse` throw on otherwise-recoverable output; (3) some prompt variants embed small literal `{ "label": …, "prompt": … }` example variations that parse cleanly but are not the response, so the extractor would happily return the wrong object. `extractJson` now (a) walks every top-level brace-balanced block and tries each in order, (b) prefers a block that has any of `stylePrompt` / `negativePrompt` / `categories` at the top level over an example-shaped one, and (c) attempts cheap repairs for trailing commas and the orphan-brace `}}]` → `}]` corruption before giving up. The expand path also logs the toolkit `runId` plus per-category variation counts so a 0-variation outcome is debuggable from `data/runs/<id>/output.txt`. Four new tests cover the Codex prompt-echo, orphan-brace, trailing-comma, and shape-preference cases.
- **CoS review-loop tasks now actually loop until clean and merge the PR.** Previously, scheduled or user tasks running with worktree + openPR + reviewLoop only fired one Copilot review request and stopped — the worktree got cleaned up immediately, the PR sat with whatever feedback Copilot returned, and nothing addressed comments or merged. The fix adds a follow-up internal task that the original cleanup hook spawns once the PR is open and the initial Copilot review has been requested. The follow-up agent attaches a fresh worktree to the PR branch (via a new `existingBranch` option on `createWorktree`), runs the full `/do:rpr`-style poll/fix/push/re-request loop until Copilot returns zero unresolved comments (or hits a 10-iteration guardrail), then merges the PR with `gh pr merge --squash --auto --delete-branch`. The follow-up's own cleanup pass passes `skipMerge: true` so the worktree branch isn't re-merged locally on top of the squash-merge gh just executed. GitLab MRs and other non-GitHub forges still skip the loop entirely (Copilot reviewer is GitHub-only). See `server/services/agentLifecycle.js` (`spawnReviewLoopFollowUp`) and `server/services/agentPromptBuilder.js` (`reviewLoopFollowUpSection`).
- **Dashboard form input no longer wipes when rotating between portrait and landscape.** `DashboardGrid` was returning two structurally different render trees on either side of the 640px breakpoint — a flat `<div className="space-y-4">` on mobile and a relative-positioned absolute-grid wrapper on desktop. Crossing the breakpoint (which happens any time you rotate an iPhone, since portrait ~390px is below it and landscape ~844px is above) put the widget at a different DOM depth, so React unmounted every widget and remounted a new one — taking any in-progress `useState` value with it. The Quick Capture text field reset to empty mid-typing. The grid now uses a single render tree across both modes, toggling only `className`/`style` between flow and absolute layouts. Widget components keep their state across rotation.
diff --git a/CLAUDE.md b/CLAUDE.md
index 384f31cc67..8cc3006697 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -167,6 +167,7 @@ port-error: #ef4444
- **Changelog**: Append entries to `.changelog/NEXT.md` during development; `/do:release` (Claude Code slash command) finalizes it into a versioned file
- **Versioning**: Version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles version bumps
- After each feature or bug fix, run `/simplify` and then commit and push code
+- **Capture deferred work before finishing.** If during a task you identify a refactor, cleanup, abstraction, or enhancement that you decide *not* to do (out of scope, risk, time), append it to `PLAN.md` as a `- [ ]` item under the most relevant section (or a new sub-heading) with enough specificity that it can be picked up cold — file paths, line numbers, why it was skipped. Examples: code-review findings rated "skip for this PR," `/simplify` items deferred for scope, "we should also do X but later." Don't end a session with these living only in chat — they evaporate.
- If we have created enough commits to wrap up a feature or issue to warrant a production release, pull the latest main and release branches and then run `/do:release` from main
See `.changelog/README.md` for detailed format and best practices.
diff --git a/PLAN.md b/PLAN.md
index d817ee0973..1152505afa 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -41,6 +41,19 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
- [ ] **Multi-reference image editing for FLUX.2** — UI on the Image Gen page that accepts 2+ reference images plus an edit prompt (e.g. "put the subject from image A into the scene from image B"). When this lands, swap the model registry's 9B entry to [`black-forest-labs/FLUX.2-klein-9B-kv`](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B-kv) — KV-cache optimization gives up to 2.5× speedup on multi-reference workflows. Work involves: schema for multi-image payload (`referenceImages: [...]`), client multi-uploader, server FormData parsing, and adapting `flux2_macos.py` to call the multi-reference pipeline API. Separately-gated repo on HF — user must request access.
- [ ] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** The shipped batch render only supports local mflux + Codex. Wire the existing external SD-API providers (Together, Replicate, Fal) into the world-builder batch path so high-end renders are practical, and let each bucket pick its own model (e.g. characters → SDXL portrait LoRA, environments → Flux-pro). Single touchpoint: `server/services/worldBuilder.js#compileBatchPrompts` + `worldBuilderCollectionHook.js`. (Surfaced from PR #211 follow-ups.)
+### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)
+
+These were flagged by the post-merge code review pass on the Z-Image + Civitai LoRA work but deliberately deferred to keep the original PR scoped.
+
+- [ ] **Detect `_shippedDefaults` ↔ `image[]` drift in mediaModels.js.** A real-install case (2026-05-09) hit a state where `_shippedDefaults.image.list` recorded all default ids but the user's `image[]` array was missing several of them — possibly from a partial editor save or a write race. The deletion-survives-upgrade contract then permanently skipped re-adding those built-ins on every restart. Add a boot-time check in `loadMediaModels()`: for any id present in `_shippedDefaults.image.list` AND `DEFAULT_REGISTRY.image` but missing from the user's `image[]`, log a clear warning (`⚠️ media-models drift: built-in <id> was shipped but is missing from image[] — restore it manually or delete _shippedDefaults.image to re-bootstrap`). Don't auto-recover (would defeat real deletions), just make the drift loud. Same pattern applies to video.
+
+- [ ] **Extract `scripts/_runner_common.py`** — `scripts/flux2_macos.py` and `scripts/z_image_turbo.py` still duplicate `pick_device`, `make_generator`, `apply_memory_optimizations`, `write_sidecar`, `make_stepwise_callback` (~95% identical, only the latents-unpack branch differs), `_emit_user_error`, and the entire bottom-of-file HF cause-chain walker (`_repo_from_hf_error` + the gated/notfound/401 dispatch in `__main__`). Roughly 200 lines of byte-for-byte duplication. Extract into a shared module with `make_stepwise_callback(pipe, h, w, dir, *, unpack_latents=None)` and `install_hf_error_handler()` (decorator/context manager wrapping `main`). The `apply_loras` extraction already shipped via `scripts/lora_utils.py`; this is the same pattern, larger blast radius.
+- [ ] **`RUNNER_FAMILIES` constants module** — runner ids `'mflux' | 'flux2' | 'z-image'` are bare strings in `server/lib/civitai.js`, `server/lib/mediaModels.js`, `client/src/pages/ImageGen.jsx`, and the `RUNNER_LABEL` / `RUNNER_BADGE_CLASS` maps in `client/src/pages/Loras.jsx`. Export `RUNNER_FAMILIES = { MFLUX, FLUX2, Z_IMAGE }` from `server/lib/runners.js` (mirror to a small client constant) so a typo can't silently break the LoRA picker's compat filter. `isFlux2()` / `isZImage()` already wrap the server-side comparisons; this is mostly client + civitai.js cleanup.
+- [ ] **Two `listLoras` exports collision** — `server/services/imageGen/local.js#listLoras` returns minimal `{ filename, name }` (powers `/api/image-gen/loras`); `server/services/loras.js#listLoras` returns the rich Civitai-aware shape (powers `/api/loras`). Same name, two modules, two shapes — a future caller importing the wrong one gets `undefined` for `civitai` / `runnerFamily`. Rename the legacy one to `listLoraFilenames` (or have it project from the new list) to make the distinction explicit.
+- [ ] **Generic `deepMerge` utility** — three call sites now do hand-rolled deep-merge: `server/services/voice/config.js`, `server/services/meatspacePost.js`, and the new `server/routes/loras.js#POST /auth/civitai`. Promote the cleanest impl (voice/config.js) into `server/lib/objects.js` and consolidate. Then loras.js, voice config, and meatspacePost all consume one helper — and `updateSettings()`-via-shallow-merge stops being a footgun for any future settings sub-object.
+- [ ] **Project-wide `<Modal>` component** — every modal in the app (`Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `MediaLightbox`, `LayoutEditor`, `KeyboardHelp`, `RapidReader`, `DeployPanel`'s confirm, the new `CivitaiAuthModal` in `Loras.jsx`) rolls its own `fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4` backdrop + click-outside + close-button + ESC handler. Extract `client/src/components/ui/Modal.jsx` with backdrop + dialog props and a slot for the body, then convert all call sites. ~300 LOC of duplicated chrome across the codebase.
+- [ ] **`assertSafeFilename(filename, { extensions })` in `fileUtils.js`** — `server/services/loras.js#assertSafeLoraFilename` (`.safetensors` whitelist) and `server/services/imageGen/local.js#assertGalleryFilename` (`.png` whitelist) are the same validation pattern with different extensions. One small helper in `fileUtils.js` consolidates both call sites.
+
### Better Audit follow-ups
- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test-specific hack in prod boot path).
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 5c4e4e15fd..c59ab9baef 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -50,12 +50,12 @@ const MediaHistory = lazyWithReload(() => import('./pages/MediaHistory'));
const MediaCollections = lazyWithReload(() => import('./pages/MediaCollections'));
const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollectionDetail'));
const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));
+const Loras = lazyWithReload(() => import('./pages/Loras'));
const WorldBuilder = lazyWithReload(() => import('./pages/WorldBuilder'));
const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));
const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));
-const RenderQueue = lazyWithReload(() => import('./pages/RenderQueue'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
const Templates = lazyWithReload(() => import('./pages/Templates'));
const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));
@@ -199,10 +199,10 @@ export default function App() {
<Route path="creative-director" element={<CreativeDirector />} />
<Route path="creative-director/:id" element={<Navigate to="overview" replace />} />
<Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />
- <Route path="queue" element={<RenderQueue />} />
<Route path="timeline" element={<VideoTimeline />} />
<Route path="timeline/:projectId" element={<VideoTimelineEditor />} />
<Route path="models" element={<MediaModels />} />
+ <Route path="loras" element={<Loras />} />
<Route path="world-builder" element={<WorldBuilder />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index c470b2390e..2f0185befb 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -125,7 +125,11 @@ export default function ImageGenControls({
</div>
)}
- {!isCodex && isLocal && (
+ {/* Step-wise distilled models (Flux Schnell, FLUX.2 Klein, Z-Image-Turbo)
+ have classifier-free guidance baked in — the diffusers runner ignores
+ any guidance scale we pass and prints a warning. Hide the input for
+ those models so the user doesn't waste a knob-turn on a no-op. */}
+ {!isCodex && isLocal && !currentModel?.cfgDisabled && (
<div>
<label className="block text-xs font-medium text-gray-400 mb-1">
Guidance {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}
diff --git a/client/src/pages/RenderQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
similarity index 57%
rename from client/src/pages/RenderQueue.jsx
rename to client/src/components/media/MediaJobsQueue.jsx
index b91e2cb6df..d8215b4290 100644
--- a/client/src/pages/RenderQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback } from 'react';
-import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw } from 'lucide-react';
-import toast from '../components/ui/Toast';
-import { listMediaJobs, cancelMediaJob } from '../services/apiMediaJobs.js';
+import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight } from 'lucide-react';
+import toast from '../ui/Toast';
+import { listMediaJobs, cancelMediaJob } from '../../services/apiMediaJobs.js';
const STATUS_BADGE = {
queued: 'bg-port-border text-port-text-muted',
@@ -11,20 +11,25 @@ const STATUS_BADGE = {
canceled: 'bg-port-warning/30 text-port-warning',
};
-const KIND_ICON = {
- video: Film,
- image: ImageIcon,
-};
+const KIND_ICON = { video: Film, image: ImageIcon };
-export default function RenderQueue() {
+// Embeds the live render queue inline on the Image / Video gen pages so the
+// user can watch in-flight jobs (and cancel them) without leaving the page.
+//
+// Props:
+// kind — 'image' | 'video' | undefined (no filter; shows both)
+// recentLimit — how many recent rows to show (default 5)
+// className — extra classes on the outer card
+export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }) {
const [jobs, setJobs] = useState([]);
const [loading, setLoading] = useState(true);
+ const [showRecent, setShowRecent] = useState(false);
const fetchJobs = useCallback(() => {
- listMediaJobs()
+ listMediaJobs(kind ? { kind } : {})
.then((data) => { setJobs(data || []); setLoading(false); })
.catch(() => setLoading(false));
- }, []);
+ }, [kind]);
useEffect(() => {
fetchJobs();
@@ -35,14 +40,10 @@ export default function RenderQueue() {
const handleCancel = async (id) => {
try {
await cancelMediaJob(id);
- // Optimistic update: queued jobs flip straight to 'canceled' (the worker
- // never picks them up so the next poll will show the same). For running
- // jobs we leave the server status as-is and track a UI-only
- // `cancelRequested` flag so the badge stays valid (the server status
- // model only knows queued|running|completed|failed|canceled — using a
- // synthetic 'canceling' here would render an unstyled badge until the
- // next poll). The next /jobs poll resolves the row to 'canceled' once
- // the worker observes the cancellation.
+ // Optimistic update: queued jobs flip to 'canceled' immediately (the
+ // worker won't pick them up). For running jobs leave the server status
+ // alone and track a UI-only `cancelRequested` flag — the next poll
+ // resolves to 'canceled' once the worker observes it.
setJobs((prev) => prev.map((j) => {
if (j.id !== id) return j;
if (j.status === 'queued') return { ...j, status: 'canceled', cancelRequested: false };
@@ -54,42 +55,49 @@ export default function RenderQueue() {
}
};
- if (loading) return <div className="text-port-text-muted text-sm">Loading…</div>;
-
const live = jobs.filter((j) => j.status === 'queued' || j.status === 'running');
- const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, 30);
+ const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, recentLimit);
+ const headerLabel = kind ? `${kind === 'image' ? 'Image' : 'Video'} Render Queue` : 'Render Queue';
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <ListOrdered className="w-5 h-5 text-port-accent" />
- <h2 className="text-lg font-semibold">Render Queue</h2>
+ <div className={`bg-port-card border border-port-border rounded-xl p-4 space-y-2 ${className}`}>
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2 min-w-0">
+ <ListOrdered className="w-4 h-4 text-port-accent shrink-0" />
+ <h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide truncate">{headerLabel}</h2>
<span className="text-xs text-port-text-muted">
- {live.length} active • {recent.length} recent
+ {live.length} active{recent.length > 0 ? ` • ${recent.length} recent` : ''}
</span>
</div>
- <button onClick={fetchJobs} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">
- <RefreshCw className="w-3 h-3" /> Refresh
+ <button
+ onClick={fetchJobs}
+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ title="Refresh"
+ >
+ <RefreshCw className="w-3.5 h-3.5" />
</button>
</div>
- {live.length === 0 && (
- <div className="text-port-text-muted text-sm">No image or video renders in flight.</div>
- )}
-
- {live.length > 0 && (
- <section className="space-y-2">
- <h3 className="text-xs font-semibold text-port-text-muted uppercase tracking-wide">Active</h3>
+ {loading ? (
+ <div className="text-port-text-muted text-xs">Loading…</div>
+ ) : live.length === 0 && recent.length === 0 ? (
+ <div className="text-port-text-muted text-xs">No {kind || 'media'} renders queued.</div>
+ ) : (
+ <div className="space-y-2">
{live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}
- </section>
- )}
- {recent.length > 0 && (
- <section className="space-y-2">
- <h3 className="text-xs font-semibold text-port-text-muted uppercase tracking-wide">Recent (last 24h)</h3>
- {recent.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}
- </section>
+ {recent.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setShowRecent((s) => !s)}
+ className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-300 pt-1"
+ >
+ {showRecent ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
+ {showRecent ? 'Hide' : 'Show'} recent ({recent.length})
+ </button>
+ )}
+ {showRecent && recent.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}
+ </div>
)}
</div>
);
@@ -99,7 +107,7 @@ function JobRow({ job, onCancel }) {
const Icon = KIND_ICON[job.kind] || Film;
const canCancel = job.status === 'queued' || job.status === 'running';
return (
- <div className="bg-port-card border border-port-border rounded p-3">
+ <div className="bg-port-bg border border-port-border rounded p-2.5">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<Icon className="w-4 h-4 text-port-accent shrink-0" />
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 7e0ac432ac..1f8055d4e9 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -20,6 +20,7 @@ import { normalizeImage } from '../components/media/normalize';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
+import MediaJobsQueue from '../components/media/MediaJobsQueue';
import {
Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,
AlertTriangle, X, Film,
@@ -30,7 +31,7 @@ import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import { useImageGenProgress } from '../hooks/useImageGenProgress';
import {
- getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,
+ getImageGenStatus, generateImage, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
buildFormData, listMediaJobs,
} from '../services/api';
@@ -193,7 +194,9 @@ export default function ImageGen() {
setModels(m);
if (m.length && !modelId) setModelId(m[0].id);
}).catch(() => {});
- listLoras().then(setAvailableLoras).catch(() => {});
+ // Use the richer /api/loras surface so the picker can show trigger
+ // words + recommended scale + Civitai-derived runnerFamily.
+ listLorasFull().then(setAvailableLoras).catch(() => {});
refreshGallery();
reloadBackends();
// Resume an in-flight job so the user can navigate away mid-render and
@@ -248,6 +251,24 @@ export default function ImageGen() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams]);
+ // ?lora=<filename> preselects a LoRA when the user clicks "Test" on the
+ // /media/loras manager page. Defers until availableLoras has loaded so the
+ // metadata (recommendedScale, name) is available; once applied, strip the
+ // param so a refresh doesn't keep re-adding the LoRA.
+ useEffect(() => {
+ const fromUrl = searchParams.get('lora');
+ if (!fromUrl || !availableLoras.length) return;
+ const match = availableLoras.find((l) => l.filename === fromUrl);
+ if (!match) return;
+ setSelectedLoras((prev) => prev.find((s) => s.filename === fromUrl) ? prev : [...prev, {
+ filename: match.filename,
+ name: match.name,
+ scale: typeof match.recommendedScale === 'number' ? match.recommendedScale : 1.0,
+ }]);
+ setSearchParams((prev) => { const next = new URLSearchParams(prev); next.delete('lora'); return next; }, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchParams, availableLoras]);
+
// Remix payload from Media History (?prompt=…&modelId=…&seed=…). Populate
// form state once on mount, then strip the params so a hot-reload or back-
// nav doesn't re-clobber edits the user has made since.
@@ -324,6 +345,13 @@ export default function ImageGen() {
const currentModel = models.find((m) => m.id === modelId);
const isFlux2Model = currentModel?.runner === 'flux2';
+ // mflux is the default runner for entries with no explicit `runner` field.
+ // Used to filter the LoRA picker so users only see compatible weights for
+ // the selected model. LoRAs with `runnerFamily === null` (legacy / unknown
+ // base) are shown too with a warning indicator — the runner may still
+ // accept them, or surface a clear error.
+ const currentRunnerFamily = currentModel?.runner || 'mflux';
+ const compatibleLoras = availableLoras.filter((l) => !l.runnerFamily || l.runnerFamily === currentRunnerFamily);
const refreshFlux2Status = useCallback((signal) => {
return fetch('/api/image-gen/setup/flux2-status', { signal })
@@ -769,46 +797,61 @@ export default function ImageGen() {
disabled={statusLoading}
/>
- {isLocalMode && !isFlux2Model && availableLoras.length > 0 && (
+ {isLocalMode && availableLoras.length > 0 && (
<div>
- <label className="block text-xs font-medium text-gray-400 mb-1">LoRAs</label>
- <div className="space-y-1.5 max-h-32 overflow-y-auto pr-1">
- {availableLoras.map((lora) => {
- const selected = selectedLoras.find((s) => s.filename === lora.filename);
- return (
- <div key={lora.filename} className="flex items-center gap-2">
- <label className="flex items-center gap-2 cursor-pointer flex-1 min-w-0">
- <input
- type="checkbox"
- checked={!!selected}
- disabled={statusLoading}
- onChange={(e) => {
- if (e.target.checked) setSelectedLoras((p) => [...p, { filename: lora.filename, name: lora.name, scale: 1.0 }]);
- else setSelectedLoras((p) => p.filter((s) => s.filename !== lora.filename));
- }}
- className="rounded"
- />
- <span className="text-xs text-gray-300 truncate">{lora.name}</span>
- </label>
- {selected && (
- <div className="flex items-center gap-2">
- <span className="text-xs text-gray-500">Scale</span>
+ <div className="flex items-center justify-between mb-1">
+ <label className="block text-xs font-medium text-gray-400">
+ LoRAs <span className="text-gray-600 font-normal">({compatibleLoras.length}/{availableLoras.length} compatible)</span>
+ </label>
+ <a href="/media/loras" className="text-[11px] text-port-accent hover:underline">Manage →</a>
+ </div>
+ {compatibleLoras.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">No LoRAs match this model's runner. Install one matching <code>{currentRunnerFamily}</code> on the LoRAs page.</p>
+ ) : (
+ <div className="space-y-1.5 max-h-40 overflow-y-auto pr-1">
+ {compatibleLoras.map((lora) => {
+ const selected = selectedLoras.find((s) => s.filename === lora.filename);
+ const recommended = typeof lora.recommendedScale === 'number' ? lora.recommendedScale : 1.0;
+ return (
+ <div key={lora.filename} className="flex items-center gap-2">
+ <label className="flex items-center gap-2 cursor-pointer flex-1 min-w-0">
<input
- type="number" min={0} max={2} step={0.1}
- value={selected.scale}
+ type="checkbox"
+ checked={!!selected}
disabled={statusLoading}
onChange={(e) => {
- const scale = parseFloat(e.target.value) || 0;
- setSelectedLoras((p) => p.map((s) => s.filename === lora.filename ? { ...s, scale } : s));
+ if (e.target.checked) setSelectedLoras((p) => [...p, { filename: lora.filename, name: lora.name, scale: recommended }]);
+ else setSelectedLoras((p) => p.filter((s) => s.filename !== lora.filename));
}}
- className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
+ className="rounded"
/>
- </div>
- )}
- </div>
- );
- })}
- </div>
+ <span className="text-xs text-gray-300 truncate flex-1" title={(lora.triggerWords || []).length ? `Trigger words: ${lora.triggerWords.join(', ')}` : lora.name}>
+ {lora.name}
+ {(lora.triggerWords || []).length > 0 && (
+ <span className="ml-2 text-[10px] text-gray-500 font-mono">{lora.triggerWords.slice(0, 2).join(', ')}{lora.triggerWords.length > 2 ? '…' : ''}</span>
+ )}
+ </span>
+ </label>
+ {selected && (
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-500" title={`Recommended: ${recommended.toFixed(2)}`}>Scale</span>
+ <input
+ type="number" min={0} max={2} step={0.1}
+ value={selected.scale}
+ disabled={statusLoading}
+ onChange={(e) => {
+ const scale = parseFloat(e.target.value) || 0;
+ setSelectedLoras((p) => p.map((s) => s.filename === lora.filename ? { ...s, scale } : s));
+ }}
+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
</div>
)}
@@ -972,6 +1015,8 @@ export default function ImageGen() {
</div>
</form>
+ <MediaJobsQueue kind="image" compact />
+
{visibleGallery.length > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">
<div className="flex items-center justify-between">
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
new file mode 100644
index 0000000000..7c29d1b744
--- /dev/null
+++ b/client/src/pages/Loras.jsx
@@ -0,0 +1,401 @@
+/**
+ * LoRA Manager — install / browse / delete Civitai LoRAs.
+ *
+ * Paste a Civitai URL to download and install. Each LoRA card shows the
+ * Civitai preview, base model (Flux.1 / Flux.2 / Z-Image / Other), trigger
+ * words, recommended scale, and a "Test in Image Gen" deep-link that
+ * preselects the LoRA on the generation page.
+ */
+
+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 toast from '../components/ui/Toast';
+import { formatBytes } from '../utils/formatters';
+import {
+ listLorasFull,
+ installLoraFromCivitai,
+ deleteLoraFull,
+ getCivitaiAuth,
+ setCivitaiAuth,
+ clearCivitaiAuth,
+} from '../services/api';
+
+const RUNNER_LABEL = {
+ mflux: 'Flux 1',
+ flux2: 'Flux 2',
+ 'z-image': 'Z-Image',
+};
+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',
+};
+
+export default function Loras() {
+ const [loras, setLoras] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [installUrl, setInstallUrl] = useState('');
+ const [installing, setInstalling] = useState(false);
+ const [deleting, setDeleting] = useState(null);
+ // Civitai auth — `auth` is `{ hasKey, source }`; `authPrompt` is set to a
+ // pending install URL when a 401/403 redirects the user to the inline key
+ // form. The form saves the key and retries the same install in one click
+ // so users don't have to remember what they were installing.
+ const [auth, setAuth] = useState({ hasKey: false, source: 'none' });
+ const [authPrompt, setAuthPrompt] = useState(null);
+
+ const refresh = useCallback(() => {
+ setError(null);
+ setLoading(true);
+ listLorasFull()
+ .then(setLoras)
+ .catch((err) => setError(err?.message || 'Failed to load LoRAs'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ getCivitaiAuth().then(setAuth).catch(() => {});
+ }, [refresh]);
+
+ // 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
+ // submit and the post-key-save retry so both behave identically.
+ const performInstall = useCallback(async (url) => {
+ if (!url || installing) return;
+ setInstalling(true);
+ await installLoraFromCivitai({ url, silent: true })
+ .then((sidecar) => {
+ toast.success(`Installed ${sidecar.name}`);
+ setLoras((prev) => [
+ { ...sidecar, sizeBytes: sidecar.file?.sizeKB ? sidecar.file.sizeKB * 1024 : null },
+ ...prev.filter((l) => l.filename !== sidecar.filename),
+ ]);
+ setInstallUrl('');
+ })
+ .catch((err) => {
+ if (err?.code === 'CIVITAI_AUTH') {
+ setAuthPrompt({ url, message: err.message || 'This LoRA needs an API key.' });
+ } else {
+ toast.error(err?.message || 'Install failed');
+ }
+ })
+ .finally(() => setInstalling(false));
+ }, [installing]);
+
+ const handleInstall = (e) => {
+ e?.preventDefault?.();
+ return performInstall(installUrl.trim());
+ };
+
+ const handleDelete = async (filename) => {
+ setDeleting(filename);
+ await deleteLoraFull(filename)
+ .then(() => {
+ toast.success('LoRA deleted');
+ setLoras((prev) => prev.filter((l) => l.filename !== filename));
+ })
+ .catch((err) => toast.error(err?.message || 'Delete failed'))
+ .finally(() => setDeleting(null));
+ };
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold text-white mb-1">LoRA Manager</h1>
+ <p className="text-sm text-gray-400">
+ Install LoRA fine-tunes from Civitai and apply them to your Image Gen renders.
+ </p>
+ </div>
+
+ <form
+ onSubmit={handleInstall}
+ className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm font-medium text-gray-300">
+ <Download size={16} />
+ <span>Install from Civitai</span>
+ </div>
+ <CivitaiKeyBadge auth={auth} onManage={() => setAuthPrompt({ url: null, message: '' })} />
+ </div>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={installUrl}
+ onChange={(e) => setInstallUrl(e.target.value)}
+ placeholder="https://civitai.com/models/2600698/realstagram"
+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600"
+ disabled={installing}
+ autoFocus
+ />
+ <button
+ type="submit"
+ disabled={installing || !installUrl.trim()}
+ className="bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
+ >
+ {installing ? 'Downloading…' : 'Install'}
+ </button>
+ </div>
+ <p className="text-xs text-gray-500">
+ Paste any <code className="bg-port-bg px-1 rounded">civitai.com</code> /{' '}
+ <code className="bg-port-bg px-1 rounded">civitai.red</code> model URL — or just the
+ numeric model id. Restricted LoRAs need an API key — PortOS will prompt you for one if a download is rejected.
+ </p>
+ </form>
+
+ {authPrompt && (
+ <CivitaiAuthModal
+ pendingUrl={authPrompt.url}
+ message={authPrompt.message}
+ auth={auth}
+ onClose={() => setAuthPrompt(null)}
+ onSaved={(updatedAuth) => setAuth(updatedAuth)}
+ onRetry={() => {
+ // After save, retry with the original URL — the server now reads
+ // the freshly-saved key from settings. performInstall handles the
+ // bad-key reopen by re-setting authPrompt.
+ const url = authPrompt.url;
+ setAuthPrompt(null);
+ if (url) performInstall(url);
+ }}
+ />
+ )}
+
+ {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>
+ )}
+
+ {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>
+ );
+}
+
+function CivitaiKeyBadge({ auth, onManage }) {
+ if (auth?.hasKey) {
+ const label = auth.source === 'env' ? 'Key (env)' : 'Key saved';
+ return (
+ <button
+ type="button"
+ onClick={onManage}
+ className="text-[11px] flex items-center gap-1 px-2 py-1 rounded border bg-port-success/10 text-port-success border-port-success/30 hover:bg-port-success/20"
+ title={auth.source === 'env' ? 'CIVITAI_API_KEY env var is active' : 'API key saved in PortOS settings'}
+ >
+ <Check size={11} />
+ {label}
+ </button>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onManage}
+ className="text-[11px] flex items-center gap-1 px-2 py-1 rounded border bg-port-bg text-gray-400 border-port-border hover:text-gray-200 hover:border-port-accent/30"
+ >
+ <KeyRound size={11} />
+ Add API key
+ </button>
+ );
+}
+
+function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry }) {
+ const [apiKey, setApiKey] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [clearing, setClearing] = useState(false);
+
+ const handleSave = async (e) => {
+ e?.preventDefault?.();
+ if (!apiKey.trim() || saving) return;
+ setSaving(true);
+ await setCivitaiAuth(apiKey.trim())
+ .then((updated) => {
+ toast.success('Civitai API key saved');
+ onSaved?.(updated);
+ if (pendingUrl) {
+ // Hand control back to the page so it can re-attempt the install
+ // — the modal closes itself in the retry path.
+ onRetry?.();
+ } else {
+ onClose?.();
+ }
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to save API key'))
+ .finally(() => setSaving(false));
+ };
+
+ const handleClear = async () => {
+ setClearing(true);
+ await clearCivitaiAuth()
+ .then((updated) => {
+ toast.success(updated.hasKey ? 'Saved key cleared (env CIVITAI_API_KEY still active)' : 'Civitai API key cleared');
+ onSaved?.(updated);
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to clear API key'))
+ .finally(() => setClearing(false));
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4" onClick={onClose}>
+ <div
+ className="bg-port-card border border-port-border rounded-lg p-5 w-full max-w-md space-y-4"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <KeyRound size={18} className="text-port-accent" />
+ <h2 className="text-base font-semibold text-white">Civitai API key</h2>
+ </div>
+ <button onClick={onClose} className="text-gray-400 hover:text-gray-200" aria-label="Close">
+ <X size={16} />
+ </button>
+ </div>
+
+ {message && (
+ <div className="text-xs bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2 text-port-warning flex items-start gap-2">
+ <AlertTriangle size={14} className="shrink-0 mt-0.5" />
+ <span>{message}</span>
+ </div>
+ )}
+
+ <p className="text-xs text-gray-400 leading-relaxed">
+ Some Civitai LoRAs require a logged-in token to download (adult or restricted content). Generate one at{' '}
+ <a href="https://civitai.com/user/account" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">
+ civitai.com/user/account
+ </a>{' '}
+ → API Keys. PortOS stores it in <code className="bg-port-bg px-1 rounded">data/settings.json</code>.
+ </p>
+
+ <form onSubmit={handleSave} className="space-y-2">
+ <label className="block text-xs font-medium text-gray-400">API key</label>
+ <input
+ type="password"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder={auth?.hasKey ? '•••• key already set — paste a new one to replace' : 'paste your Civitai API key'}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600 font-mono"
+ disabled={saving}
+ autoFocus
+ />
+ <div className="flex items-center gap-2 pt-1">
+ <button
+ type="submit"
+ disabled={saving || !apiKey.trim()}
+ className="flex-1 bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {saving ? 'Saving…' : (pendingUrl ? 'Save key & retry install' : 'Save key')}
+ </button>
+ {auth?.hasKey && auth?.source === 'settings' && (
+ <button
+ type="button"
+ onClick={handleClear}
+ disabled={clearing}
+ className="px-3 py-2 rounded text-xs text-port-error hover:bg-port-error/10 border border-port-error/30 disabled:opacity-50"
+ >
+ {clearing ? 'Clearing…' : 'Clear'}
+ </button>
+ )}
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+}
+
+function LoraCard({ lora, onDelete, deleting }) {
+ const family = lora.runnerFamily;
+ const familyLabel = family ? (RUNNER_LABEL[family] || family) : 'Unsupported base';
+ const badgeClass = family ? (RUNNER_BADGE_CLASS[family] || 'bg-gray-600/20 text-gray-300 border-gray-500/30') : 'bg-port-warning/20 text-port-warning border-port-warning/30';
+ const triggerWords = lora.triggerWords || [];
+ const civitai = lora.civitai;
+ // Image Gen page reads ?lora=<filename> as a preselect hint via query string;
+ // keeps the manager → gen handoff URL-driven (deep-linkable).
+ const testHref = `/media/image?lora=${encodeURIComponent(lora.filename)}`;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
+ {lora.previewImageUrl ? (
+ <img
+ src={lora.previewImageUrl}
+ alt=""
+ className="w-full h-48 object-cover bg-port-bg"
+ loading="lazy"
+ />
+ ) : (
+ <div className="w-full h-48 bg-port-bg flex items-center justify-center text-gray-700">
+ <Sparkles size={32} />
+ </div>
+ )}
+ <div className="p-3 flex-1 flex flex-col">
+ <div className="flex items-start justify-between gap-2 mb-2">
+ <h3 className="font-semibold text-white text-sm truncate flex-1" title={lora.name}>{lora.name}</h3>
+ <span className={`text-[10px] px-2 py-0.5 rounded border whitespace-nowrap ${badgeClass}`} title={civitai?.baseModel || 'Unknown'}>
+ {familyLabel}
+ </span>
+ </div>
+
+ {triggerWords.length > 0 && (
+ <div className="mb-2">
+ <div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">Trigger words</div>
+ <div className="flex flex-wrap gap-1">
+ {triggerWords.map((w) => (
+ <code key={w} className="text-[11px] bg-port-bg px-1.5 py-0.5 rounded text-gray-300 border border-port-border">{w}</code>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="text-[11px] text-gray-500 grid grid-cols-2 gap-x-2 gap-y-0.5 mb-3">
+ <span>Recommended scale</span><span className="text-gray-300 font-mono text-right">{Number(lora.recommendedScale ?? 1).toFixed(2)}</span>
+ <span>Size</span><span className="text-gray-300 font-mono text-right">{formatBytes(lora.sizeBytes)}</span>
+ {civitai?.creator && (<><span>Creator</span><span className="text-gray-300 truncate text-right" title={civitai.creator}>{civitai.creator}</span></>)}
+ {civitai?.baseModel && (<><span>Base model</span><span className="text-gray-300 truncate text-right" title={civitai.baseModel}>{civitai.baseModel}</span></>)}
+ </div>
+
+ <div className="mt-auto flex items-center gap-2">
+ <Link
+ to={testHref}
+ className="flex-1 bg-port-accent text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-port-accent/90 text-center"
+ >
+ Test
+ </Link>
+ {civitai?.url && (
+ <a
+ href={civitai.url}
+ 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={14} />
+ </a>
+ )}
+ <button
+ onClick={onDelete}
+ disabled={deleting}
+ className="text-port-error hover:text-port-error/80 p-1.5 rounded hover:bg-port-error/10 disabled:opacity-50"
+ title="Delete LoRA"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsx
index f2226c5e69..df4ac8789b 100644
--- a/client/src/pages/MediaGen.jsx
+++ b/client/src/pages/MediaGen.jsx
@@ -1,5 +1,5 @@
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, ListOrdered, Globe2 } from 'lucide-react';
+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, Globe2, Sparkles } from 'lucide-react';
const TABS = [
{ id: 'image', label: 'Image', icon: ImageIcon },
@@ -7,9 +7,9 @@ const TABS = [
{ id: 'world-builder', label: 'World Builder', icon: Globe2 },
{ id: 'timeline', label: 'Timeline', icon: Scissors },
{ id: 'creative-director', label: 'Creative Director', icon: Clapperboard },
- { id: 'queue', label: 'Render Queue', icon: ListOrdered },
{ id: 'history', label: 'History', icon: History },
{ id: 'collections', label: 'Collections', icon: FolderOpen },
+ { id: 'loras', label: 'LoRAs', icon: Sparkles },
{ id: 'models', label: 'Models', icon: HardDrive }
];
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index c1d2dacd96..47f33f6e09 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -40,6 +40,7 @@ import {
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import BatchQueuePanel from '../components/media/BatchQueuePanel';
+import MediaJobsQueue from '../components/media/MediaJobsQueue';
import {
getVideoGenStatus, generateVideo, cancelVideoGen,
listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,
@@ -1263,6 +1264,8 @@ export default function VideoGen() {
)}
/>
+ <MediaJobsQueue kind="video" compact />
+
{visibleHistory.length > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">
<div className="flex items-center justify-between">
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 4db5f9f500..872aabe3a0 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -120,3 +120,31 @@ export const removeMediaCollectionItem = (id, key) => request(`/media/collection
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' });
+
+// 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.
+export const listLorasFull = () => request('/loras');
+// `silent: true` suppresses the auto-toast in apiCore so the page can route
+// CIVITAI_AUTH errors into the in-UI key prompt instead of a fire-and-forget
+// red toast the user can't act on.
+export const installLoraFromCivitai = ({ url, silent = false } = {}) => request('/loras/install', {
+ method: 'POST',
+ body: JSON.stringify({ url }),
+ silent,
+});
+
+// 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');
+export const setCivitaiAuth = (apiKey) => request('/loras/auth/civitai', {
+ method: 'POST',
+ body: JSON.stringify({ apiKey }),
+});
+export const clearCivitaiAuth = () => request('/loras/auth/civitai', { method: 'DELETE' });
+export const getLora = (filename) => request(`/loras/${encodeURIComponent(filename)}`);
+export const patchLora = (filename, patch) => request(`/loras/${encodeURIComponent(filename)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+});
+export const deleteLoraFull = (filename) => request(`/loras/${encodeURIComponent(filename)}`, { method: 'DELETE' });
diff --git a/data.sample/media-models.json b/data.sample/media-models.json
new file mode 100644
index 0000000000..f70475695d
--- /dev/null
+++ b/data.sample/media-models.json
@@ -0,0 +1,144 @@
+{
+ "_doc": "PortOS media model registry. Edit to add models, tune defaults, or switch the text encoder. Restart the server to apply changes.",
+ "video": {
+ "macos": [
+ {
+ "id": "ltx2_unified",
+ "name": "LTX-2 Unified (~42 GB)",
+ "repo": "notapalindrome/ltx2-mlx-av",
+ "runtime": "mlx_video",
+ "steps": 30,
+ "guidance": 3
+ },
+ {
+ "id": "ltx23_unified",
+ "name": "LTX-2.3 Unified Beta (~48 GB)",
+ "repo": "notapalindrome/ltx23-mlx-av",
+ "runtime": "mlx_video",
+ "steps": 25,
+ "guidance": 3
+ },
+ {
+ "id": "ltx23_distilled_q4",
+ "name": "LTX-2.3 Distilled Q4 (~22 GB)",
+ "repo": "notapalindrome/ltx23-mlx-av-q4",
+ "runtime": "mlx_video",
+ "steps": 25,
+ "guidance": 3
+ },
+ {
+ "id": "ltx23_dgrauet_q4",
+ "name": "LTX-2.3 dgrauet Q4 (~16 GB, true keyframes)",
+ "repo": "dgrauet/ltx-2.3-mlx-q4",
+ "runtime": "ltx2",
+ "steps": 8,
+ "guidance": 3
+ },
+ {
+ "id": "ltx23_dgrauet_q8",
+ "name": "LTX-2.3 dgrauet Q8 (~25 GB, true keyframes)",
+ "repo": "dgrauet/ltx-2.3-mlx-q8",
+ "runtime": "ltx2",
+ "steps": 8,
+ "guidance": 3
+ }
+ ],
+ "windows": [
+ {
+ "id": "ltx_video",
+ "name": "LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)",
+ "runtime": "mlx_video",
+ "steps": 25,
+ "guidance": 3
+ }
+ ],
+ "defaultMacos": "ltx23_distilled_q4",
+ "defaultWindows": "ltx_video"
+ },
+ "image": [
+ {
+ "id": "dev",
+ "name": "Flux 1 Dev",
+ "steps": 20,
+ "guidance": 3.5
+ },
+ {
+ "id": "schnell",
+ "name": "Flux 1 Schnell",
+ "steps": 4,
+ "guidance": 0,
+ "cfgDisabled": true
+ },
+ {
+ "id": "flux2-klein-4b",
+ "name": "Flux 2 Klein 4B (SDNQ 4-bit, ~8 GB @ 512px)",
+ "runner": "flux2",
+ "quantization": "sdnq",
+ "repo": "Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic",
+ "tokenizerRepo": "black-forest-labs/FLUX.2-klein-4B",
+ "steps": 8,
+ "guidance": 3.5,
+ "cfgDisabled": true
+ },
+ {
+ "id": "flux2-klein-9b",
+ "name": "Flux 2 Klein 9B (SDNQ 4-bit, ~12 GB — needs 32+ GB RAM)",
+ "runner": "flux2",
+ "quantization": "sdnq",
+ "repo": "Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32",
+ "tokenizerRepo": "black-forest-labs/FLUX.2-klein-9B",
+ "steps": 8,
+ "guidance": 3.5,
+ "cfgDisabled": true
+ },
+ {
+ "id": "flux2-klein-4b-int8",
+ "name": "Flux 2 Klein 4B (Int8, ~16 GB)",
+ "runner": "flux2",
+ "quantization": "int8",
+ "repo": "aydin99/FLUX.2-klein-4B-int8",
+ "basePipelineRepo": "black-forest-labs/FLUX.2-klein-4B",
+ "steps": 8,
+ "guidance": 3.5,
+ "cfgDisabled": true
+ },
+ {
+ "id": "z-image-turbo-bf16",
+ "name": "Z-Image-Turbo (bf16, ~13 GB)",
+ "runner": "z-image",
+ "repo": "Tongyi-MAI/Z-Image-Turbo",
+ "steps": 8,
+ "guidance": 1,
+ "cfgDisabled": true
+ },
+ {
+ "id": "z-image-turbo-quant",
+ "name": "Z-Image-Turbo (community quantized)",
+ "runner": "z-image",
+ "repo": "",
+ "steps": 8,
+ "guidance": 1,
+ "cfgDisabled": true,
+ "broken": true
+ }
+ ],
+ "textEncoders": [
+ {
+ "id": "gemma-4bit",
+ "label": "Gemma 3 12B 4-bit (smallest, ~7 GB)",
+ "repo": "mlx-community/gemma-3-12b-it-4bit"
+ },
+ {
+ "id": "gemma-qat-4bit",
+ "label": "Gemma 3 12B QAT 4-bit (better, ~8 GB, LM Studio)",
+ "repo": "mlx-community/gemma-3-12b-it-qat-4bit",
+ "localPath": "~/.lmstudio/models/mlx-community/gemma-3-12b-it-qat-4bit"
+ },
+ {
+ "id": "gemma-bf16",
+ "label": "Gemma 3 12B bf16 (default, best quality, ~24 GB)",
+ "repo": "mlx-community/gemma-3-12b-it-bf16"
+ }
+ ],
+ "selectedTextEncoder": "gemma-bf16"
+}
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 5a178d9285..c6ddad384c 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -34,6 +34,9 @@ os.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")
import torch
from PIL import Image
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from lora_utils import apply_loras # noqa: E402
+
def pick_device(requested: str) -> str:
if requested == "auto":
@@ -281,6 +284,8 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--image-strength", type=float, default=None, help="0..1 i2i denoise strength")
p.add_argument("--stepwise-image-output-dir", default=None)
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")
return p.parse_args()
@@ -307,6 +312,7 @@ def main() -> None:
sys.exit(64)
apply_memory_optimizations(pipe)
+ apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])
seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())
generator = make_generator(device, seed)
diff --git a/scripts/lora_utils.py b/scripts/lora_utils.py
new file mode 100644
index 0000000000..e0c9891cd3
--- /dev/null
+++ b/scripts/lora_utils.py
@@ -0,0 +1,52 @@
+"""
+Shared LoRA application helpers used by `flux2_macos.py` and
+`z_image_turbo.py`. Both runners go through diffusers' `load_lora_weights`
++ `set_adapters` surface — pulling the body out keeps them in lockstep when
+diffusers' LoRA API gains new knobs (e.g. fused-scale paths).
+"""
+
+import sys
+from pathlib import Path
+
+
+def apply_loras(pipe, lora_paths, lora_scales) -> None:
+ """Best-effort LoRA application. On per-LoRA failure (e.g. shape
+ mismatch from a Flux.1 LoRA loaded onto Flux.2 / Z-Image) we log and
+ continue without that LoRA — the runner still produces a base render
+ rather than aborting the whole job."""
+ if not lora_paths:
+ return
+ if not hasattr(pipe, "load_lora_weights"):
+ print(
+ f"⚠️ pipeline {type(pipe).__name__} doesn't expose load_lora_weights — "
+ f"skipping {len(lora_paths)} LoRA(s)",
+ file=sys.stderr,
+ )
+ return
+ adapter_names = []
+ for i, path in enumerate(lora_paths):
+ adapter = f"lora_{i}"
+ print(f"🎚️ loading LoRA: {Path(path).name} (adapter={adapter})", file=sys.stderr, flush=True)
+ try:
+ pipe.load_lora_weights(path, adapter_name=adapter)
+ adapter_names.append(adapter)
+ except Exception as err:
+ print(
+ f"⚠️ LoRA load failed for {Path(path).name}: {type(err).__name__}: {err}",
+ file=sys.stderr,
+ )
+ if not adapter_names:
+ return
+ scales = []
+ for i, _ in enumerate(adapter_names):
+ raw = lora_scales[i] if i < len(lora_scales) else "1.0"
+ try:
+ scales.append(float(raw))
+ except (TypeError, ValueError):
+ scales.append(1.0)
+ if hasattr(pipe, "set_adapters"):
+ try:
+ pipe.set_adapters(adapter_names, adapter_weights=scales)
+ print(f"✅ active LoRA adapters: {list(zip(adapter_names, scales))}", file=sys.stderr)
+ except Exception as err:
+ print(f"⚠️ set_adapters failed: {type(err).__name__}: {err}", file=sys.stderr)
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index d75ad16c51..17007d9d1f 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -209,6 +209,7 @@ if [[ "$INSTALL_LTX2" == "1" ]]; then
fi
if [[ "$INSTALL_FLUX2" == "1" ]]; then
echo " 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 ""
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.py
new file mode 100644
index 0000000000..6edc2ba502
--- /dev/null
+++ b/scripts/z_image_turbo.py
@@ -0,0 +1,339 @@
+#!/usr/bin/env python3
+"""
+PortOS Z-Image-Turbo runner.
+
+Spawned by `server/services/imageGen/local.js` when the active model has
+`runner: 'z-image'` in `data/media-models.json`. Mirrors the CLI surface of
+`flux2_macos.py` so the dispatcher only needs to swap the binary path; all
+the SSE / stage-marker / stepwise / cancel plumbing on the JS side stays the
+same.
+
+Z-Image-Turbo (Tongyi/Alibaba) is Apache 2.0 — no HF token / license probe
+needed. Runs on MPS (Apple Silicon) or CUDA via diffusers. Reuses the FLUX.2
+venv at ~/.portos/venv-flux2 (already has diffusers from git HEAD + torch).
+"""
+
+import argparse
+import inspect
+import json
+import os
+import sys
+from pathlib import Path
+
+os.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")
+
+import torch
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from lora_utils import apply_loras # noqa: E402
+
+
+def pick_device(requested: str) -> str:
+ if requested == "auto":
+ if torch.backends.mps.is_available():
+ return "mps"
+ if torch.cuda.is_available():
+ return "cuda"
+ return "cpu"
+ if requested == "mps" and not torch.backends.mps.is_available():
+ print("⚠️ MPS requested but unavailable — falling back to CPU", file=sys.stderr)
+ return "cpu"
+ if requested == "cuda" and not torch.cuda.is_available():
+ print("⚠️ CUDA requested but unavailable — falling back to CPU", file=sys.stderr)
+ return "cpu"
+ return requested
+
+
+def make_generator(device: str, seed: int) -> torch.Generator:
+ if device in ("cuda", "mps"):
+ return torch.Generator(device).manual_seed(int(seed))
+ 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
+
+ print(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("STAGE:move-to-device", file=sys.stderr, flush=True)
+ pipe.to(device)
+ return pipe
+
+
+def to_i2i_pipeline(pipe):
+ # AutoPipelineForImage2Image.from_pipe reuses the loaded weights — no
+ # second download. If the loaded pipeline class has no registered i2i
+ # sibling, this raises and we fall back to txt2img.
+ from diffusers import AutoPipelineForImage2Image
+ return AutoPipelineForImage2Image.from_pipe(pipe)
+
+
+def apply_memory_optimizations(pipe) -> None:
+ if hasattr(pipe, "enable_attention_slicing"):
+ pipe.enable_attention_slicing()
+ if hasattr(pipe, "enable_vae_slicing"):
+ pipe.enable_vae_slicing()
+ vae = getattr(pipe, "vae", None)
+ if hasattr(pipe, "enable_vae_tiling"):
+ pipe.enable_vae_tiling()
+ elif vae is not None and hasattr(vae, "enable_tiling"):
+ vae.enable_tiling()
+
+
+def make_stepwise_callback(stepwise_dir: str, pipe, height: int, width: int):
+ """Return a `callback_on_step_end` that decodes the running latent into a
+ small preview PNG. local.js's `processLatestFrame` watches this dir and
+ streams the freshest frame to the SSE client.
+
+ Z-Image latents come back in the standard `(B, C, H_lat, W_lat)` layout
+ (unlike FLUX.2's packed transformer latents) so the decode path is a
+ plain VAE call — no unpack helper needed.
+ """
+ if not stepwise_dir:
+ return None
+ out = Path(stepwise_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ vae = pipe.vae
+ scaling = getattr(vae.config, "scaling_factor", 1.0) or 1.0
+ shift = getattr(vae.config, "shift_factor", 0.0) or 0.0
+
+ fired = {"count": 0, "saved": 0}
+
+ @torch.no_grad()
+ def cb(pipe, step_index, _timestep, callback_kwargs):
+ fired["count"] += 1
+ latents = callback_kwargs.get("latents")
+ if latents is None:
+ if step_index == 0:
+ print("⚠️ stepwise: latents missing from callback_kwargs", file=sys.stderr)
+ return callback_kwargs
+ if step_index == 0:
+ print(f"🖼️ stepwise: callback live, latents.shape={tuple(latents.shape)}", file=sys.stderr)
+ try:
+ if latents.dim() != 4:
+ # Some pipelines return packed latents. Skip preview rather
+ # than guess the unpack shape — the final image still saves.
+ return callback_kwargs
+ decoded = vae.decode(latents / scaling + shift, return_dict=False)[0]
+ decoded = (decoded.clamp(-1, 1) + 1) / 2
+ arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")
+ img = Image.fromarray(arr)
+ img.thumbnail((512, 512), Image.LANCZOS)
+ img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
+ fired["saved"] += 1
+ except Exception as err:
+ print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)
+ return callback_kwargs
+
+ cb._stats = fired
+ return cb
+
+
+def write_sidecar(output: str, payload: dict) -> None:
+ sidecar = Path(output).with_suffix(".metadata.json")
+ sidecar.write_text(json.dumps(payload, indent=2))
+
+
+def parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser(description="PortOS Z-Image-Turbo runner")
+ p.add_argument("--model", required=True, help="model id (e.g. z-image-turbo-bf16)")
+ p.add_argument("--repo", required=True, help="HF repo for the pipeline weights")
+ p.add_argument("--prompt", required=True)
+ p.add_argument("--negative-prompt", default="")
+ p.add_argument("--width", type=int, default=1024)
+ p.add_argument("--height", type=int, default=1024)
+ p.add_argument("--steps", type=int, default=8)
+ p.add_argument("--guidance", type=float, default=1.0)
+ p.add_argument("--seed", type=int, default=None)
+ p.add_argument("--output", required=True)
+ p.add_argument("--metadata", action="store_true", help="write <output>.metadata.json sidecar")
+ p.add_argument("--image-path", default=None, help="optional init image for i2i")
+ p.add_argument("--image-strength", type=float, default=None, help="0..1 i2i denoise strength")
+ p.add_argument("--stepwise-image-output-dir", default=None)
+ 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")
+ return p.parse_args()
+
+
+def main() -> None:
+ args = parse_args()
+
+ device = pick_device(args.device)
+ dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32
+
+ pipe = load_pipeline(args.repo, device, dtype)
+
+ init_image = None
+ if args.image_path:
+ init_image = Image.open(args.image_path).convert("RGB").resize(
+ (int(args.width), int(args.height)), Image.LANCZOS
+ )
+ # Promote the txt2img pipe to its i2i sibling. If the model family
+ # doesn't expose an i2i variant, fall through to txt2img with a warning
+ # — better than failing the request outright.
+ try:
+ pipe = to_i2i_pipeline(pipe)
+ except Exception as err:
+ print(
+ f"⚠️ z-image: i2i sibling unavailable ({type(err).__name__}: {err}); "
+ f"falling back to txt2img and ignoring init image",
+ file=sys.stderr,
+ )
+ init_image = None
+
+ apply_memory_optimizations(pipe)
+ apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])
+
+ seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())
+ generator = make_generator(device, seed)
+
+ callback = make_stepwise_callback(args.stepwise_image_output_dir, pipe, int(args.height), int(args.width))
+
+ accepted = set(inspect.signature(pipe.__call__).parameters.keys())
+ pipe_kwargs = dict(
+ prompt=args.prompt,
+ height=int(args.height),
+ width=int(args.width),
+ num_inference_steps=int(args.steps),
+ guidance_scale=float(args.guidance),
+ generator=generator,
+ )
+ if args.negative_prompt and "negative_prompt" in accepted:
+ pipe_kwargs["negative_prompt"] = args.negative_prompt
+ if callback is not None and "callback_on_step_end" in accepted:
+ pipe_kwargs["callback_on_step_end"] = callback
+ if "callback_on_step_end_tensor_inputs" in accepted:
+ pipe_kwargs["callback_on_step_end_tensor_inputs"] = ["latents"]
+ if init_image is not None and "image" in accepted:
+ pipe_kwargs["image"] = init_image
+ # Disable VAE tiling for i2i — tiled encode of a small image
+ # produces seams on the output (matches flux2 reference).
+ vae = getattr(pipe, "vae", None)
+ if vae is not None and hasattr(vae, "disable_tiling"):
+ vae.disable_tiling()
+ if args.image_strength is not None and "strength" in accepted:
+ pipe_kwargs["strength"] = float(args.image_strength)
+
+ print("STAGE:inference", file=sys.stderr, flush=True)
+ print(
+ f"🎨 z-image generate seed={seed} {args.width}x{args.height} steps={args.steps} "
+ f"guidance={args.guidance} device={device}",
+ file=sys.stderr,
+ )
+
+ with torch.inference_mode():
+ result = pipe(**pipe_kwargs)
+ image = result.images[0]
+ image.save(args.output)
+
+ if callback is not None and hasattr(callback, "_stats"):
+ s = callback._stats
+ print(f"🖼️ stepwise summary: callback fired {s['count']} times, saved {s['saved']} previews", file=sys.stderr)
+
+ if args.metadata:
+ write_sidecar(
+ args.output,
+ {
+ "id": Path(args.output).stem,
+ "prompt": args.prompt,
+ "negativePrompt": args.negative_prompt,
+ "modelId": args.model,
+ "seed": seed,
+ "width": int(args.width),
+ "height": int(args.height),
+ "steps": int(args.steps),
+ "guidance": float(args.guidance),
+ "filename": Path(args.output).name,
+ "initImageFilename": Path(args.image_path).name if args.image_path else None,
+ "initImageStrength": float(args.image_strength) if args.image_strength is not None else None,
+ },
+ )
+
+ if torch.backends.mps.is_available():
+ torch.mps.empty_cache()
+ torch.mps.synchronize()
+ elif torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ torch.cuda.synchronize()
+
+ print(f"✅ z-image saved {args.output} (seed={seed})", file=sys.stderr)
+
+
+def _emit_user_error(kind: str, message: str, repo: str = "") -> None:
+ line = f"USER_ERROR:{kind}"
+ if repo:
+ line += f":{repo}"
+ print(line, file=sys.stderr, flush=True)
+ print(f"❌ {message}", file=sys.stderr, flush=True)
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except KeyboardInterrupt:
+ sys.exit(130)
+ except SystemExit:
+ raise
+ except Exception as err:
+ # Friendly USER_ERROR markers for common HF failure modes so the UI
+ # surfaces actionable text instead of raw "Exit code 1".
+ from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError, HfHubHTTPError
+ chain = []
+ cur = err
+ while cur is not None:
+ chain.append(cur)
+ cur = cur.__cause__ or cur.__context__
+
+ def _repo_from_hf_error(hf_err):
+ repo = getattr(hf_err, "repo_id", None) or ""
+ if repo:
+ return repo
+ url = getattr(getattr(hf_err, "response", None), "url", None) or \
+ getattr(getattr(hf_err, "request", None), "url", None)
+ if url is None:
+ return ""
+ path = str(url).split("huggingface.co", 1)[-1].lstrip("/")
+ parts = path.split("/")
+ if parts[:1] == ["api"] and len(parts) >= 4 and parts[1] in {"models", "datasets", "spaces"}:
+ return f"{parts[2]}/{parts[3]}"
+ if len(parts) >= 2 and parts[0] not in {"api", "settings", "join"}:
+ return f"{parts[0]}/{parts[1]}"
+ return ""
+
+ gated = next((e for e in chain if isinstance(e, GatedRepoError)), None)
+ notfound = next((e for e in chain if isinstance(e, RepositoryNotFoundError)), None)
+ http = next((e for e in chain if isinstance(e, HfHubHTTPError)), None)
+ if gated is not None:
+ repo = _repo_from_hf_error(gated)
+ url = f"https://huggingface.co/{repo}" if repo else "https://huggingface.co/"
+ _emit_user_error(
+ "gated_repo",
+ f"Access to {repo or 'the model repo'} is restricted. Visit {url} "
+ f"to request access, then make sure your HF token is set in PortOS.",
+ repo,
+ )
+ sys.exit(2)
+ status = getattr(getattr(http, "response", None), "status_code", None) if http else None
+ if status == 401:
+ _emit_user_error(
+ "hf_unauthorized",
+ "HuggingFace rejected the token (401). Check that the token is valid "
+ "and has read access, then re-paste it in PortOS.",
+ )
+ sys.exit(2)
+ if notfound is not None:
+ repo = _repo_from_hf_error(notfound)
+ _emit_user_error("repo_not_found", f"HF repo not found: {repo or '(unknown)'}", repo)
+ sys.exit(2)
+ _emit_user_error("unknown", f"{type(err).__name__}: {err}")
+ raise
diff --git a/server/index.js b/server/index.js
index 451f24be6a..bca693e3c2 100644
--- a/server/index.js
+++ b/server/index.js
@@ -91,6 +91,7 @@ import { initWorldBuilderCollectionHook } from './services/worldBuilderCollectio
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
import imageVideoModelsRoutes from './routes/imageVideoModels.js';
+import lorasRoutes from './routes/loras.js';
import sdapiRoutes from './routes/sdapi.js';
import openclawRoutes from './routes/openclaw.js';
import askRoutes from './routes/ask.js';
@@ -331,6 +332,7 @@ app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/world-builder', worldBuilderRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
+app.use('/api/loras', lorasRoutes);
// AUTOMATIC1111-compatible surface for tailnet clients — gated by
// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.
app.use('/sdapi/v1', sdapiRoutes);
diff --git a/server/lib/civitai.js b/server/lib/civitai.js
new file mode 100644
index 0000000000..1def8b34f5
--- /dev/null
+++ b/server/lib/civitai.js
@@ -0,0 +1,237 @@
+/**
+ * Civitai integration — pure helpers for parsing Civitai URLs, fetching
+ * model metadata, and picking the right file/version to download.
+ *
+ * All metadata calls go to civitai.com regardless of which mirror frontend
+ * the user pasted (civitai.com / civitai.red / civitai.green) — the API is
+ * only published on civitai.com, and going through the mirrors' frontends
+ * would mean parsing HTML.
+ *
+ * Auth: optional API key (`settings.civitai.apiKey` or env CIVITAI_API_KEY).
+ * Some restricted/adult LoRAs require a token to download; metadata for
+ * public models is always anonymous-readable.
+ *
+ * No try/catch — errors bubble to the centralized middleware via the
+ * project convention. Domain-specific errors throw ServerError.
+ */
+
+import { ServerError } from './errorHandler.js';
+
+const CIVITAI_API = 'https://civitai.com/api/v1';
+const CIVITAI_HOSTS = new Set(['civitai.com', 'civitai.red', 'civitai.green', 'www.civitai.com']);
+
+// Maps a Civitai `baseModel` string (e.g. "Flux.1 D", "Flux.2 Klein", "SDXL 1.0",
+// "Z-Image") to a PortOS runner family. The runner family is what the LoRA
+// picker filters on so users only see compatible LoRAs for their selected
+// model. Unknown base models map to `null` (incompatible with current runners).
+export const baseModelToRunner = (baseModel) => {
+ if (typeof baseModel !== 'string') return null;
+ const b = baseModel.trim().toLowerCase();
+ if (!b) return null;
+ // Match Flux.1 *, Flux 1 *, FLUX.1 D, FLUX.1 S
+ 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';
+ // 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.
+ return null;
+};
+
+// Extracts model id and optional modelVersionId from any Civitai URL shape:
+// https://civitai.com/models/123456
+// https://civitai.com/models/123456/some-slug
+// https://civitai.com/models/123456?modelVersionId=789
+// https://civitai.red/models/123456/realstagram
+// Returns { modelId: string, versionId: string | null }. Throws on garbage.
+export const parseCivitaiUrl = (raw) => {
+ if (typeof raw !== 'string' || !raw.trim()) {
+ throw new ServerError('Empty Civitai URL', { status: 400, code: 'CIVITAI_BAD_URL' });
+ }
+ const trimmed = raw.trim();
+ // Accept bare model ids too — `123456` and `civitai:123456` shortcuts.
+ const bareId = trimmed.match(/^(?:civitai:)?(\d{1,12})$/);
+ if (bareId) return { modelId: bareId[1], versionId: null };
+
+ // URL.parse can throw on malformed input — wrap in a guard rather than try/catch.
+ if (!/^https?:\/\//i.test(trimmed)) {
+ throw new ServerError(
+ `Civitai URL must start with http(s):// — got "${trimmed.slice(0, 60)}"`,
+ { status: 400, code: 'CIVITAI_BAD_URL' },
+ );
+ }
+ let parsed;
+ // URL constructor throws on truly malformed inputs; the regex above already
+ // accepted the http(s) prefix shape so this is the catch-all for invalid
+ // hostnames / ports / encoded segments.
+ parsed = new URL(trimmed);
+ if (!CIVITAI_HOSTS.has(parsed.hostname.toLowerCase())) {
+ throw new ServerError(
+ `Not a Civitai URL: ${parsed.hostname}`,
+ { status: 400, code: 'CIVITAI_BAD_URL' },
+ );
+ }
+ const segments = parsed.pathname.split('/').filter(Boolean);
+ // Expected shape: ['models', '<id>', '<optional slug>']
+ if (segments[0] !== 'models' || !segments[1] || !/^\d+$/.test(segments[1])) {
+ throw new ServerError(
+ `Civitai URL must point at /models/<id> — got "${parsed.pathname}"`,
+ { status: 400, code: 'CIVITAI_BAD_URL' },
+ );
+ }
+ const modelId = segments[1];
+ const versionId = parsed.searchParams.get('modelVersionId');
+ if (versionId && !/^\d+$/.test(versionId)) {
+ throw new ServerError(
+ `Civitai modelVersionId must be numeric — got "${versionId}"`,
+ { status: 400, code: 'CIVITAI_BAD_URL' },
+ );
+ }
+ return { modelId, versionId: versionId || null };
+};
+
+// Pick the modelVersion to install. If the URL specified a versionId, use it.
+// Otherwise fall back to the first published version (Civitai sorts these by
+// recency in the API response). Throws if the requested version isn't on the
+// model — usually means the user pasted a stale link after the creator
+// removed a version.
+export const pickVersion = (model, versionId) => {
+ const versions = Array.isArray(model?.modelVersions) ? model.modelVersions : [];
+ if (!versions.length) {
+ throw new ServerError(
+ `Civitai model "${model?.name || model?.id}" has no published versions`,
+ { status: 422, code: 'CIVITAI_NO_VERSIONS' },
+ );
+ }
+ if (versionId) {
+ const match = versions.find((v) => String(v.id) === String(versionId));
+ if (!match) {
+ throw new ServerError(
+ `Civitai version ${versionId} not found on model ${model?.id}`,
+ { status: 404, code: 'CIVITAI_VERSION_NOT_FOUND' },
+ );
+ }
+ return match;
+ }
+ return versions[0];
+};
+
+// Pick the .safetensors file to download from a version. Civitai hosts
+// occasional `.bin` / `.ckpt` siblings (older formats) and sometimes a
+// thumbnail or training-config JSON — we only want .safetensors. Prefers
+// the file marked `primary: true`; falls back to the first .safetensors.
+export const pickPrimaryFile = (version) => {
+ const files = Array.isArray(version?.files) ? version.files : [];
+ const safetensors = files.filter((f) => /\.safetensors$/i.test(f?.name || ''));
+ if (!safetensors.length) {
+ throw new ServerError(
+ `Civitai version ${version?.id} has no .safetensors file`,
+ { status: 422, code: 'CIVITAI_NO_SAFETENSORS' },
+ );
+ }
+ return safetensors.find((f) => f.primary) || safetensors[0];
+};
+
+// Pick a representative preview image URL for a version (for the LoRA card
+// thumbnail). Civitai returns nsfwLevel as a numeric flag — 1 is "None", 2
+// is "Soft", 4 is "Mature", 8 is "X". We prefer the lowest-rated image so
+// the manager UI thumbnail isn't unexpectedly explicit; users who want the
+// full preview can click through to civitai.com.
+export const pickPreviewImage = (version) => {
+ const images = Array.isArray(version?.images) ? version.images : [];
+ if (!images.length) return null;
+ const sorted = [...images].sort((a, b) => (a.nsfwLevel ?? 0) - (b.nsfwLevel ?? 0));
+ return sorted[0] || null;
+};
+
+// Build the auth header for HTTP requests when an API key is set.
+// Civitai's API also accepts the token as a `?token=` query param on
+// download URLs, but Authorization: Bearer is documented for /api/v1 calls.
+export const buildAuthHeaders = (apiKey) => {
+ if (typeof apiKey !== 'string' || !apiKey.trim()) return {};
+ return { Authorization: `Bearer ${apiKey.trim()}` };
+};
+
+// Fetch model metadata. `fetchImpl` is injectable for tests — defaults to
+// global fetch which is available in Node 18+. Returns the parsed JSON
+// body; throws ServerError on HTTP failures with a helpful message.
+export const fetchCivitaiModel = async (modelId, { apiKey, fetchImpl = fetch } = {}) => {
+ if (!/^\d+$/.test(String(modelId))) {
+ throw new ServerError(`Invalid Civitai model id: ${modelId}`, { status: 400, code: 'CIVITAI_BAD_URL' });
+ }
+ const url = `${CIVITAI_API}/models/${modelId}`;
+ const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildAuthHeaders(apiKey) } });
+ if (!res.ok) {
+ if (res.status === 404) {
+ throw new ServerError(`Civitai model ${modelId} not found`, { status: 404, code: 'CIVITAI_NOT_FOUND' });
+ }
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Civitai rejected the request (${res.status}) — set CIVITAI_API_KEY in PortOS Settings if this model is gated`,
+ { status: res.status, code: 'CIVITAI_AUTH' },
+ );
+ }
+ throw new ServerError(`Civitai metadata fetch failed: ${res.status}`, { status: 502, code: 'CIVITAI_FETCH_FAILED' });
+ }
+ return res.json();
+};
+
+// Apply the auth token to a Civitai download URL. The download endpoint
+// accepts either Authorization header or `?token=` query param; the query
+// form survives 302-redirects to the CDN whereas the header doesn't, so we
+// use the query param for download URLs.
+export const applyDownloadToken = (downloadUrl, apiKey) => {
+ if (typeof apiKey !== 'string' || !apiKey.trim()) return downloadUrl;
+ if (typeof downloadUrl !== 'string') return downloadUrl;
+ const sep = downloadUrl.includes('?') ? '&' : '?';
+ return `${downloadUrl}${sep}token=${encodeURIComponent(apiKey.trim())}`;
+};
+
+// Build the canonical sidecar shape. Stored next to the .safetensors file as
+// `<filename>.metadata.json`. Decoupled from fetchCivitaiModel so callers can
+// build it from a known model+version pair without a second API hit (the
+// install path already has both in hand).
+export const buildSidecar = ({ model, version, file, filename }) => {
+ const previewImage = pickPreviewImage(version);
+ const baseModel = version?.baseModel || null;
+ return {
+ filename,
+ name: model?.name || filename,
+ description: model?.description || '',
+ civitai: {
+ modelId: model?.id ?? null,
+ versionId: version?.id ?? null,
+ url: model?.id ? `https://civitai.com/models/${model.id}?modelVersionId=${version?.id}` : null,
+ baseModel,
+ type: model?.type || null, // "LORA" / "Checkpoint" / etc.
+ tags: Array.isArray(model?.tags) ? model.tags : [],
+ creator: model?.creator?.username || null,
+ nsfw: !!model?.nsfw,
+ },
+ runnerFamily: baseModelToRunner(baseModel), // 'mflux' | 'flux2' | 'z-image' | null
+ triggerWords: Array.isArray(version?.trainedWords) ? version.trainedWords : [],
+ recommendedScale: typeof version?.settings?.strength === 'number' ? version.settings.strength : 1.0,
+ file: {
+ sizeKB: file?.sizeKB ?? null,
+ hashes: file?.hashes || {},
+ downloadUrl: file?.downloadUrl || null,
+ },
+ previewImageUrl: previewImage?.url || null,
+ installedAt: new Date().toISOString(),
+ };
+};
+
+// Sanitize a model name into a safe filename slug. Civitai model names can
+// contain `/`, `\`, weird unicode, etc. — we want a portable filename that
+// also keeps the .safetensors extension predictable. Limits length to keep
+// the path well under most filesystems' 255-byte cap (the sidecar adds
+// `.metadata.json` and the project may add prefixes).
+export const slugifyForFilename = (name) => {
+ const safe = String(name || 'lora')
+ .normalize('NFKD')
+ .replace(/[^\w\-.]+/g, '-') // anything that isn't a word char, dash, or dot → dash
+ .replace(/-+/g, '-') // collapse runs
+ .replace(/^[-.]+|[-.]+$/g, '') // trim leading/trailing dashes/dots
+ .slice(0, 80);
+ return safe || 'lora';
+};
diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.js
new file mode 100644
index 0000000000..b7ef793cae
--- /dev/null
+++ b/server/lib/civitai.test.js
@@ -0,0 +1,224 @@
+import { describe, it, expect } from 'vitest';
+import {
+ applyDownloadToken,
+ baseModelToRunner,
+ buildAuthHeaders,
+ buildSidecar,
+ fetchCivitaiModel,
+ parseCivitaiUrl,
+ pickPrimaryFile,
+ pickPreviewImage,
+ pickVersion,
+ slugifyForFilename,
+} from './civitai.js';
+
+describe('parseCivitaiUrl', () => {
+ it('parses canonical /models/<id> URLs', () => {
+ expect(parseCivitaiUrl('https://civitai.com/models/2600698')).toEqual({ modelId: '2600698', versionId: null });
+ });
+ it('strips slug segments', () => {
+ expect(parseCivitaiUrl('https://civitai.com/models/2600698/realstagram')).toEqual({ modelId: '2600698', versionId: null });
+ });
+ it('honors the civitai.red mirror', () => {
+ expect(parseCivitaiUrl('https://civitai.red/models/2600698/realstagram')).toEqual({ modelId: '2600698', versionId: null });
+ });
+ it('extracts modelVersionId when present', () => {
+ expect(parseCivitaiUrl('https://civitai.com/models/2600698?modelVersionId=999')).toEqual({ modelId: '2600698', versionId: '999' });
+ });
+ it('accepts bare model ids', () => {
+ expect(parseCivitaiUrl('2600698')).toEqual({ modelId: '2600698', versionId: null });
+ expect(parseCivitaiUrl('civitai:2600698')).toEqual({ modelId: '2600698', versionId: null });
+ });
+ it('rejects non-civitai hosts', () => {
+ expect(() => parseCivitaiUrl('https://huggingface.co/models/2600698')).toThrow(/Not a Civitai URL/);
+ });
+ it('rejects garbage', () => {
+ expect(() => parseCivitaiUrl('')).toThrow();
+ expect(() => parseCivitaiUrl('not a url')).toThrow();
+ expect(() => parseCivitaiUrl('https://civitai.com/users/123')).toThrow(/must point at \/models/);
+ expect(() => parseCivitaiUrl('https://civitai.com/models/')).toThrow();
+ expect(() => parseCivitaiUrl('https://civitai.com/models/abc')).toThrow();
+ });
+ it('rejects non-numeric modelVersionId', () => {
+ expect(() => parseCivitaiUrl('https://civitai.com/models/123?modelVersionId=abc')).toThrow(/numeric/);
+ });
+});
+
+describe('baseModelToRunner', () => {
+ it('maps Flux.1 variants to mflux', () => {
+ expect(baseModelToRunner('Flux.1 D')).toBe('mflux');
+ expect(baseModelToRunner('Flux.1 S')).toBe('mflux');
+ expect(baseModelToRunner('flux 1')).toBe('mflux');
+ });
+ it('maps Flux.2 variants to flux2', () => {
+ expect(baseModelToRunner('Flux.2 Klein')).toBe('flux2');
+ expect(baseModelToRunner('flux 2')).toBe('flux2');
+ });
+ it('maps Z-Image variants to z-image', () => {
+ expect(baseModelToRunner('Z-Image Turbo')).toBe('z-image');
+ expect(baseModelToRunner('zimage')).toBe('z-image');
+ });
+ it('returns null for unsupported families', () => {
+ expect(baseModelToRunner('SDXL 1.0')).toBe(null);
+ expect(baseModelToRunner('SD 1.5')).toBe(null);
+ expect(baseModelToRunner('Pony')).toBe(null);
+ expect(baseModelToRunner('')).toBe(null);
+ expect(baseModelToRunner(null)).toBe(null);
+ });
+});
+
+describe('pickVersion', () => {
+ const model = {
+ id: 1,
+ name: 'M',
+ modelVersions: [
+ { id: 100, baseModel: 'Flux.1 D' },
+ { id: 99, baseModel: 'Flux.1 D' },
+ ],
+ };
+ it('returns the first version when no id is given', () => {
+ expect(pickVersion(model, null).id).toBe(100);
+ });
+ it('finds an explicit version id', () => {
+ expect(pickVersion(model, '99').id).toBe(99);
+ });
+ it('throws when the requested version is missing', () => {
+ expect(() => pickVersion(model, '404')).toThrow(/version 404 not found/);
+ });
+ it('throws when the model has no versions', () => {
+ expect(() => pickVersion({ modelVersions: [] }, null)).toThrow(/no published versions/);
+ expect(() => pickVersion({}, null)).toThrow(/no published versions/);
+ });
+});
+
+describe('pickPrimaryFile', () => {
+ it('prefers files marked primary', () => {
+ const v = { files: [
+ { name: 'old.safetensors', primary: false },
+ { name: 'new.safetensors', primary: true },
+ ] };
+ expect(pickPrimaryFile(v).name).toBe('new.safetensors');
+ });
+ it('falls back to first .safetensors when none flagged', () => {
+ const v = { files: [
+ { name: 'cover.png' },
+ { name: 'first.safetensors' },
+ { name: 'second.safetensors' },
+ ] };
+ expect(pickPrimaryFile(v).name).toBe('first.safetensors');
+ });
+ it('throws when no .safetensors is present', () => {
+ expect(() => pickPrimaryFile({ files: [{ name: 'cover.png' }] })).toThrow(/no .safetensors file/);
+ expect(() => pickPrimaryFile({})).toThrow(/no .safetensors file/);
+ });
+});
+
+describe('pickPreviewImage', () => {
+ it('returns the lowest-NSFW image', () => {
+ const v = { images: [
+ { url: 'spicy.jpg', nsfwLevel: 8 },
+ { url: 'mild.jpg', nsfwLevel: 1 },
+ { url: 'mid.jpg', nsfwLevel: 4 },
+ ] };
+ expect(pickPreviewImage(v).url).toBe('mild.jpg');
+ });
+ it('returns null for an empty list', () => {
+ expect(pickPreviewImage({ images: [] })).toBe(null);
+ expect(pickPreviewImage({})).toBe(null);
+ });
+});
+
+describe('buildAuthHeaders / applyDownloadToken', () => {
+ it('returns empty headers for empty key', () => {
+ expect(buildAuthHeaders('')).toEqual({});
+ expect(buildAuthHeaders(null)).toEqual({});
+ });
+ it('builds a Bearer header', () => {
+ expect(buildAuthHeaders('xyz')).toEqual({ Authorization: 'Bearer xyz' });
+ expect(buildAuthHeaders(' k ')).toEqual({ Authorization: 'Bearer k' });
+ });
+ it('appends ?token=... to download URLs', () => {
+ expect(applyDownloadToken('https://civitai.com/api/download/models/1', 'k')).toBe('https://civitai.com/api/download/models/1?token=k');
+ expect(applyDownloadToken('https://civitai.com/api/download/models/1?foo=bar', 'k')).toBe('https://civitai.com/api/download/models/1?foo=bar&token=k');
+ });
+ it('passes through when no key', () => {
+ expect(applyDownloadToken('https://x', '')).toBe('https://x');
+ expect(applyDownloadToken('https://x', null)).toBe('https://x');
+ });
+});
+
+describe('slugifyForFilename', () => {
+ it('strips path-unsafe chars', () => {
+ expect(slugifyForFilename('Real / Stagram')).toBe('Real-Stagram');
+ expect(slugifyForFilename('Foo!@#Bar')).toBe('Foo-Bar');
+ });
+ it('caps length at 80 chars', () => {
+ const long = 'a'.repeat(200);
+ expect(slugifyForFilename(long).length).toBeLessThanOrEqual(80);
+ });
+ it('falls back to "lora" for empty / pure-junk names', () => {
+ expect(slugifyForFilename('')).toBe('lora');
+ expect(slugifyForFilename('!!!')).toBe('lora');
+ expect(slugifyForFilename(null)).toBe('lora');
+ });
+});
+
+describe('fetchCivitaiModel', () => {
+ it('hits the canonical metadata endpoint', async () => {
+ let calledUrl = null;
+ const fetchImpl = async (url, opts) => {
+ calledUrl = url;
+ expect(opts.headers.Accept).toBe('application/json');
+ expect(opts.headers.Authorization).toBe('Bearer k');
+ return { ok: true, status: 200, json: async () => ({ id: 1, name: 'X' }) };
+ };
+ const out = await fetchCivitaiModel('123', { apiKey: 'k', fetchImpl });
+ expect(calledUrl).toBe('https://civitai.com/api/v1/models/123');
+ expect(out.name).toBe('X');
+ });
+ it('throws CIVITAI_NOT_FOUND on 404', async () => {
+ const fetchImpl = async () => ({ ok: false, status: 404 });
+ await expect(fetchCivitaiModel('123', { fetchImpl })).rejects.toThrow(/not found/);
+ });
+ it('throws CIVITAI_AUTH on 401/403', async () => {
+ const fetchImpl = async () => ({ ok: false, status: 401 });
+ await expect(fetchCivitaiModel('123', { fetchImpl })).rejects.toThrow(/Civitai rejected/);
+ });
+ it('rejects non-numeric modelId without hitting the network', async () => {
+ let called = false;
+ const fetchImpl = async () => { called = true; return { ok: true, status: 200, json: async () => ({}) }; };
+ await expect(fetchCivitaiModel('abc', { fetchImpl })).rejects.toThrow(/Invalid Civitai model id/);
+ expect(called).toBe(false);
+ });
+});
+
+describe('buildSidecar', () => {
+ it('compiles all the pieces into a stable shape', () => {
+ const model = { id: 42, name: 'RealStagram', description: 'photoreal', type: 'LORA', tags: ['photo'], creator: { username: 'someone' }, nsfw: false };
+ const version = { id: 7, baseModel: 'Flux.1 D', trainedWords: ['rstgrm'], settings: { strength: 0.85 }, images: [{ url: 'p.jpg', nsfwLevel: 1 }] };
+ const file = { sizeKB: 102400, hashes: { SHA256: 'abc' }, downloadUrl: 'https://civitai.com/api/download/models/7' };
+ const sc = buildSidecar({ model, version, file, filename: 'lora-realstagram-v7.safetensors' });
+ expect(sc.filename).toBe('lora-realstagram-v7.safetensors');
+ expect(sc.civitai.modelId).toBe(42);
+ expect(sc.civitai.versionId).toBe(7);
+ expect(sc.civitai.url).toBe('https://civitai.com/models/42?modelVersionId=7');
+ expect(sc.runnerFamily).toBe('mflux');
+ expect(sc.triggerWords).toEqual(['rstgrm']);
+ expect(sc.recommendedScale).toBe(0.85);
+ expect(sc.previewImageUrl).toBe('p.jpg');
+ expect(sc.file.sizeKB).toBe(102400);
+ expect(typeof sc.installedAt).toBe('string');
+ });
+ it('falls back when version has no settings/preview/trainedWords', () => {
+ const sc = buildSidecar({
+ model: { id: 1, name: 'Lite' },
+ version: { id: 2, baseModel: 'SDXL 1.0' },
+ file: {},
+ filename: 'lora-lite-v2.safetensors',
+ });
+ expect(sc.runnerFamily).toBe(null);
+ expect(sc.recommendedScale).toBe(1.0);
+ expect(sc.triggerWords).toEqual([]);
+ expect(sc.previewImageUrl).toBe(null);
+ });
+});
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index e34d858325..02b11e8b6b 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -52,7 +52,7 @@ const DEFAULT_REGISTRY = {
image: [
// mflux runner — MLX-only, Flux 1 (dev/schnell). `runner` defaults to 'mflux'.
{ id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },
- { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0 },
+ { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0, cfgDisabled: true },
// flux2 runner — PyTorch + diffusers + MPS (Apple Silicon) or CUDA (Win/Linux).
// Models are quantized to fit on consumer hardware; tokenizer comes from the
// gated base repo, so users must accept the license at huggingface.co and
@@ -66,6 +66,7 @@ const DEFAULT_REGISTRY = {
tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
steps: 8,
guidance: 3.5,
+ cfgDisabled: true,
},
{
id: 'flux2-klein-9b',
@@ -76,6 +77,7 @@ const DEFAULT_REGISTRY = {
tokenizerRepo: 'black-forest-labs/FLUX.2-klein-9B',
steps: 8,
guidance: 3.5,
+ cfgDisabled: true,
},
{
id: 'flux2-klein-4b-int8',
@@ -86,6 +88,31 @@ const DEFAULT_REGISTRY = {
basePipelineRepo: 'black-forest-labs/FLUX.2-klein-4B',
steps: 8,
guidance: 3.5,
+ cfgDisabled: true,
+ },
+ // z-image runner — Apache 2.0, ungated, reuses the FLUX.2 venv. Turbo
+ // distillation runs ~8 steps with CFG disabled (guidance 1.0).
+ {
+ id: 'z-image-turbo-bf16',
+ name: 'Z-Image-Turbo (bf16, ~13 GB)',
+ runner: 'z-image',
+ repo: 'Tongyi-MAI/Z-Image-Turbo',
+ steps: 8,
+ guidance: 1.0,
+ cfgDisabled: true,
+ },
+ {
+ id: 'z-image-turbo-quant',
+ name: 'Z-Image-Turbo (community quantized)',
+ runner: 'z-image',
+ repo: '',
+ steps: 8,
+ guidance: 1.0,
+ cfgDisabled: true,
+ // Hidden from the UI until the user picks a community quant repo and
+ // clears this flag. Keeping the entry here gives them a copy-paste
+ // template instead of having to remember the schema.
+ broken: true,
},
],
textEncoders: [
@@ -157,18 +184,47 @@ const upgradeImageEntries = (list) => {
});
};
+// IDs whose underlying pipeline is step-wise distilled (Flux Schnell, FLUX.2
+// Klein, Z-Image-Turbo). For these models, classifier-free guidance is fixed
+// internally and any user-supplied guidance scale is silently ignored — the
+// diffusers runner literally prints "Guidance scale X is ignored for step-
+// wise distilled models." into the log on every render. Surface this as an
+// explicit flag on each registry entry so the UI can hide the Guidance input
+// and the runners can skip passing the flag.
+const CFG_DISABLED_IDS = new Set([
+ 'schnell',
+ 'flux2-klein-4b',
+ 'flux2-klein-9b',
+ 'flux2-klein-4b-int8',
+ 'z-image-turbo-bf16',
+ 'z-image-turbo-quant',
+]);
+
+const backfillCfgDisabled = (list) => {
+ if (!Array.isArray(list)) return list;
+ return list.map((entry) => {
+ if (!isPlainObject(entry) || typeof entry.id !== 'string') return entry;
+ if ('cfgDisabled' in entry) return entry; // user override (true OR false) wins
+ if (!CFG_DISABLED_IDS.has(entry.id)) return entry;
+ return { ...entry, cfgDisabled: true };
+ });
+};
+
export const isFlux2 = (model) => model?.runner === 'flux2';
+export const isZImage = (model) => model?.runner === 'z-image';
+export const isCfgDisabled = (model) => model?.cfgDisabled === true;
-// Append video models that are genuinely new in this release (not in
+// Append models that are genuinely new in this release (not in
// _shippedDefaults) to the user's list, while respecting deletions the user
// already made. Returns both the merged entry list and the newly-added ids so
-// the caller can record them in _shippedDefaults.
+// the caller can record them in _shippedDefaults. Used for both video and
+// image lists — the deletion-survives-upgrade contract is identical.
//
// Semantics:
// - id already in userList → keep as-is (user customisations intact)
// - id in shippedIds but not userList → user explicitly deleted it; skip
// - id NOT in shippedIds → genuinely new built-in; add + record
-const appendNewlyShippedVideoEntries = (userList, defaultList, shippedIds) => {
+const appendNewlyShippedEntries = (userList, defaultList, shippedIds) => {
const safeList = Array.isArray(userList) ? userList : [];
const safeDefaults = Array.isArray(defaultList) ? defaultList : [];
const userIds = new Set(safeList.map((e) => e?.id).filter((id) => typeof id === 'string'));
@@ -183,6 +239,8 @@ const appendNewlyShippedVideoEntries = (userList, defaultList, shippedIds) => {
}
return { entries: result, newlyShipped };
};
+// Back-compat alias — kept so any external imports of the old name keep working.
+const appendNewlyShippedVideoEntries = appendNewlyShippedEntries;
// Existing installs predate the `runtime` field on video entries — fill it
// with 'mlx_video' (the legacy default) for known-legacy ids so the
@@ -231,25 +289,26 @@ const normalizeRegistry = (parsed) => {
const safe = isPlainObject(parsed) ? parsed : {};
const safeVideo = isPlainObject(safe.video) ? safe.video : {};
- // _shippedDefaults tracks which built-in video ids have ever been delivered
+ // _shippedDefaults tracks which built-in ids have ever been delivered
// to this install, so we can distinguish "user deleted it" from "genuinely
- // new in this release".
+ // new in this release". Tracked separately for video (per-platform) and
+ // image (single list — image entries cover both platforms).
const shippedVideo = isPlainObject(safe._shippedDefaults?.video) ? safe._shippedDefaults.video : null;
- const isBootstrap = shippedVideo === null;
+ const isVideoBootstrap = shippedVideo === null;
- const shippedMacosIds = isBootstrap
+ const shippedMacosIds = isVideoBootstrap
? bootstrapShippedIds(safeVideo.macos, DEFAULT_REGISTRY.video.macos)
: new Set(arrayOrDefault(shippedVideo.macos, []));
- const shippedWindowsIds = isBootstrap
+ const shippedWindowsIds = isVideoBootstrap
? bootstrapShippedIds(safeVideo.windows, DEFAULT_REGISTRY.video.windows)
: new Set(arrayOrDefault(shippedVideo.windows, []));
- const macosResult = appendNewlyShippedVideoEntries(
+ const macosResult = appendNewlyShippedEntries(
safeVideo.macos,
DEFAULT_REGISTRY.video.macos,
shippedMacosIds,
);
- const windowsResult = appendNewlyShippedVideoEntries(
+ const windowsResult = appendNewlyShippedEntries(
safeVideo.windows,
DEFAULT_REGISTRY.video.windows,
shippedWindowsIds,
@@ -260,10 +319,41 @@ const normalizeRegistry = (parsed) => {
windows: [...shippedWindowsIds, ...windowsResult.newlyShipped],
};
+ // Image upgrade path. Same shape as video, single list. The flux2 upgrade
+ // (upgradeImageEntries) runs first so legacy `broken: 'macos'` entries get
+ // promoted to runner-aware ones before the new-entry append step looks at
+ // their ids. Skips bootstrap union when the image key was missing entirely
+ // (treat as fresh install — let the new entries land).
+ const shippedImage = isPlainObject(safe._shippedDefaults?.image) ? safe._shippedDefaults.image : null;
+ const isImageBootstrap = shippedImage === null;
+ const upgradedImage = backfillCfgDisabled(
+ upgradeImageEntries(arrayOrDefault(safe.image, DEFAULT_REGISTRY.image)),
+ );
+ // Image bootstrap deliberately uses userIds ONLY (not union with defaults).
+ // Image is getting `_shippedDefaults` for the first time in this release, so
+ // there's no prior history of deletions to preserve via the union trick the
+ // video side uses. Pre-existing installs will pick up the new built-ins
+ // (z-image-turbo-*, etc.) on next boot. Subsequent loads use the persisted
+ // list so user deletions stick.
+ const upgradedImageIds = (Array.isArray(upgradedImage) ? upgradedImage : [])
+ .map((e) => e?.id)
+ .filter((id) => typeof id === 'string');
+ const shippedImageIds = isImageBootstrap
+ ? new Set(upgradedImageIds)
+ : new Set(arrayOrDefault(shippedImage.list, []));
+ const imageResult = appendNewlyShippedEntries(
+ upgradedImage,
+ DEFAULT_REGISTRY.image,
+ shippedImageIds,
+ );
+ const updatedShippedImage = {
+ list: [...shippedImageIds, ...imageResult.newlyShipped],
+ };
+
return {
...DEFAULT_REGISTRY,
...safe,
- image: upgradeImageEntries(arrayOrDefault(safe.image, DEFAULT_REGISTRY.image)),
+ image: imageResult.entries,
textEncoders: arrayOrDefault(safe.textEncoders, DEFAULT_REGISTRY.textEncoders),
video: {
...DEFAULT_REGISTRY.video,
@@ -274,6 +364,7 @@ const normalizeRegistry = (parsed) => {
_shippedDefaults: {
...(safe._shippedDefaults || {}),
video: updatedShippedVideo,
+ image: updatedShippedImage,
},
};
};
@@ -299,15 +390,22 @@ export const loadMediaModels = () => {
// ids (bootstrap run or a new built-in model shipped in this release). This
// ensures user deletions survive the next server restart.
if (readOk) {
- const parsedShipped = isPlainObject(parsed._shippedDefaults?.video)
+ const parsedShippedVideo = isPlainObject(parsed._shippedDefaults?.video)
? parsed._shippedDefaults.video
: null;
- const normalizedShipped = cached._shippedDefaults.video;
- const changed =
- parsedShipped === null ||
- normalizedShipped.macos.length !== (parsedShipped.macos?.length ?? 0) ||
- normalizedShipped.windows.length !== (parsedShipped.windows?.length ?? 0);
- if (changed) {
+ const parsedShippedImage = isPlainObject(parsed._shippedDefaults?.image)
+ ? parsed._shippedDefaults.image
+ : null;
+ const normalizedVideo = cached._shippedDefaults.video;
+ const normalizedImage = cached._shippedDefaults.image;
+ const videoChanged =
+ parsedShippedVideo === null ||
+ normalizedVideo.macos.length !== (parsedShippedVideo.macos?.length ?? 0) ||
+ normalizedVideo.windows.length !== (parsedShippedVideo.windows?.length ?? 0);
+ const imageChanged =
+ parsedShippedImage === null ||
+ normalizedImage.list.length !== (parsedShippedImage.list?.length ?? 0);
+ if (videoChanged || imageChanged) {
writeFileSync(REGISTRY_FILE, JSON.stringify(cached, null, 2) + '\n');
console.log(`📝 Updated media model registry _shippedDefaults: ${REGISTRY_FILE}`);
}
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index ce11ff4c4c..a7b611f088 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -1,7 +1,11 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
import { tmpdir, homedir } from 'os';
-import { join } from 'path';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname_self = dirname(fileURLToPath(import.meta.url));
+const SAMPLE_REGISTRY_PATH = join(__dirname_self, '..', '..', 'data.sample', 'media-models.json');
let tmpDir;
let registryFile;
@@ -18,6 +22,21 @@ afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
+// data.sample/media-models.json must mirror the in-code DEFAULT_REGISTRY so
+// `npm run setup:data` (which copies data.sample → data on fresh installs)
+// produces the same starting state as the runtime `seedIfMissing()` fallback.
+// Compares the seed file to a freshly-bootstrapped registry with
+// _shippedDefaults stripped (that's a runtime-only field).
+describe('data.sample seed file', () => {
+ it('matches the runtime-seeded DEFAULT_REGISTRY', async () => {
+ const sample = JSON.parse(readFileSync(SAMPLE_REGISTRY_PATH, 'utf-8'));
+ const { loadMediaModels } = await import('./mediaModels.js');
+ const live = loadMediaModels();
+ const { _shippedDefaults: _omit, ...liveSeed } = live;
+ expect(sample).toEqual(liveSeed);
+ });
+});
+
describe('mediaModels registry', () => {
it('seeds the registry file on first load', async () => {
expect(existsSync(registryFile)).toBe(false);
@@ -370,6 +389,79 @@ describe('mediaModels registry', () => {
logSpy.mockRestore();
});
+ // Image-side _shippedDefaults — same contract as video, but tracked as a
+ // single list (image entries are platform-agnostic).
+
+ it('fresh install: z-image and flux2 entries seeded; _shippedDefaults.image populated', async () => {
+ const { loadMediaModels, getImageModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const ids = getImageModels().map((m) => m.id);
+ expect(ids).toContain('z-image-turbo-bf16');
+ expect(ids).toContain('flux2-klein-4b');
+ // Quantized z-image stub is gated off behind broken:true until the user
+ // fills in a community repo, so it shouldn't appear in the platform list.
+ expect(ids).not.toContain('z-image-turbo-quant');
+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));
+ expect(onDisk._shippedDefaults?.image?.list?.length).toBeGreaterThan(0);
+ expect(onDisk._shippedDefaults.image.list).toContain('z-image-turbo-bf16');
+ });
+
+ it('existing install without _shippedDefaults.image gains the new z-image entries on upgrade', async () => {
+ // Simulate a pre-z-image registry: only flux2 and Flux 1 entries, no
+ // _shippedDefaults.image at all.
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [
+ { id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },
+ { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0 },
+ ],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: { video: { macos: [], windows: [] } }, // image key missing
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels, getImageModels } = await import('./mediaModels.js');
+ const reg = loadMediaModels();
+ const ids = getImageModels().map((m) => m.id);
+ // New z-image entry must be present after upgrade
+ expect(ids).toContain('z-image-turbo-bf16');
+ // Pre-existing user entries preserved
+ expect(ids).toContain('dev');
+ expect(ids).toContain('schnell');
+ // _shippedDefaults.image written out
+ expect(reg._shippedDefaults.image.list).toContain('z-image-turbo-bf16');
+ expect(reg._shippedDefaults.image.list).toContain('dev');
+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));
+ expect(onDisk._shippedDefaults.image.list).toContain('z-image-turbo-bf16');
+ logSpy.mockRestore();
+ });
+
+ it('user deletion of z-image entry survives next load', async () => {
+ // _shippedDefaults.image already records z-image-turbo-bf16, but the user
+ // has removed it from their image list.
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [
+ { id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },
+ // z-image-turbo-bf16 deliberately absent
+ ],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ _shippedDefaults: {
+ video: { macos: [], windows: [] },
+ image: { list: ['dev', 'z-image-turbo-bf16', 'flux2-klein-4b', 'flux2-klein-9b', 'flux2-klein-4b-int8', 'schnell', 'z-image-turbo-quant'] },
+ },
+ }));
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { loadMediaModels, getImageModels } = await import('./mediaModels.js');
+ const reg = loadMediaModels();
+ const ids = getImageModels().map((m) => m.id);
+ expect(ids).not.toContain('z-image-turbo-bf16');
+ // Still recorded in _shippedDefaults so subsequent loads also honour the deletion
+ expect(reg._shippedDefaults.image.list).toContain('z-image-turbo-bf16');
+ logSpy.mockRestore();
+ });
+
it('user deletes a model that was newly added; deletion survives next load', async () => {
const platformKey = process.platform === 'win32' ? 'windows' : 'macos';
const otherKey = process.platform === 'win32' ? 'macos' : 'windows';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 1f239c2460..095e1e5edb 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -16,10 +16,10 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },
- { id: 'nav.media.queue', path: '/media/queue', label: 'Render Queue', section: 'Create', aliases: ['render-queue', 'queue', 'media-queue', 'media-jobs'], keywords: ['render', 'queue', 'pending', 'jobs', 'pipeline'] },
{ 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', 'loras'], keywords: ['hf cache', 'lora', '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'] },
{ id: 'nav.media.world-builder', path: '/media/world-builder', label: 'World Builder', section: 'Create', aliases: ['world-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },
+ { id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },
{ id: 'nav.settings.prompts', path: '/prompts', label: 'Prompts', section: 'Settings', aliases: ['prompts'] },
diff --git a/server/routes/loras.js b/server/routes/loras.js
new file mode 100644
index 0000000000..64cb1a6727
--- /dev/null
+++ b/server/routes/loras.js
@@ -0,0 +1,106 @@
+/**
+ * LoRA management routes.
+ *
+ * REST surface for the new `/media/loras` manager UI. The legacy delete
+ * endpoint at `DELETE /api/image-video/models/lora/:filename` is kept for
+ * backward compat (the Models page still calls it); the new manager uses
+ * these endpoints exclusively so it can also surface Civitai metadata.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler } from '../lib/errorHandler.js';
+import {
+ deleteLora,
+ getLora,
+ installFromCivitai,
+ listLoras,
+ patchLoraSidecar,
+} from '../services/loras.js';
+import { getSettings, saveSettings } from '../services/settings.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await listLoras());
+}));
+
+// 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
+// UI explain why a key is in effect (env var vs. saved-in-settings) so the
+// user understands whether deleting via the API is meaningful.
+router.get('/auth/civitai', asyncHandler(async (_req, res) => {
+ const settings = await getSettings();
+ const fromSettings = !!(settings?.civitai?.apiKey || '').trim();
+ const fromEnv = !!(process.env.CIVITAI_API_KEY || '').trim();
+ res.json({
+ hasKey: fromSettings || fromEnv,
+ source: fromSettings ? 'settings' : (fromEnv ? 'env' : 'none'),
+ });
+}));
+
+const authPostSchema = z.object({ apiKey: z.string().min(1).max(256) });
+router.post('/auth/civitai', asyncHandler(async (req, res) => {
+ const { apiKey } = authPostSchema.parse(req.body);
+ // Manual deep-merge so future civitai sub-fields don't get clobbered by
+ // updateSettings' shallow-merge contract.
+ const current = await getSettings();
+ await saveSettings({ ...current, civitai: { ...(current.civitai || {}), apiKey: apiKey.trim() } });
+ res.json({ hasKey: true, source: 'settings' });
+}));
+
+router.delete('/auth/civitai', asyncHandler(async (_req, res) => {
+ const current = await getSettings();
+ const next = { ...current };
+ if (next.civitai && typeof next.civitai === 'object') {
+ const { apiKey: _omit, ...rest } = next.civitai;
+ next.civitai = rest;
+ }
+ await saveSettings(next);
+ // The env var (if set) still wins after a delete — surface that so the
+ // UI can explain "you cleared the saved key but CIVITAI_API_KEY is still
+ // active in the shell environment."
+ const envActive = !!(process.env.CIVITAI_API_KEY || '').trim();
+ res.json({ hasKey: envActive, source: envActive ? 'env' : 'none' });
+}));
+
+const installSchema = z.object({
+ url: z.string().min(1).max(1024),
+ // Optional one-shot key override — useful if the user wants to test a
+ // restricted LoRA without persisting their key in Settings yet.
+ apiKey: z.string().min(1).max(256).optional(),
+});
+
+router.post('/install', asyncHandler(async (req, res) => {
+ const data = installSchema.parse(req.body);
+ const sidecar = await installFromCivitai(data);
+ res.status(201).json(sidecar);
+}));
+
+router.get('/:filename', asyncHandler(async (req, res) => {
+ const lora = await getLora(req.params.filename);
+ res.json(lora);
+}));
+
+const patchSchema = z.object({
+ // Only user-editable fields. Civitai-derived blocks (`civitai`, `file`,
+ // `runnerFamily`, `triggerWords`) are not patchable through this surface
+ // — the user would have to delete + reinstall to refresh those.
+ name: z.string().min(1).max(200).optional(),
+ description: z.string().max(2000).optional(),
+ recommendedScale: z.number().min(0).max(2).optional(),
+ notes: z.string().max(2000).optional(),
+});
+
+router.patch('/:filename', asyncHandler(async (req, res) => {
+ const patch = patchSchema.parse(req.body);
+ const next = await patchLoraSidecar(req.params.filename, patch);
+ res.json(next);
+}));
+
+router.delete('/:filename', asyncHandler(async (req, res) => {
+ res.json(await deleteLora(req.params.filename));
+}));
+
+export default router;
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index f0584bf54b..7905d194d8 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 } from '../../lib/mediaModels.js';
+import { getImageModels, isFlux2, isZImage } from '../../lib/mediaModels.js';
export const IMAGE_MODELS = Object.fromEntries(getImageModels().map((m) => [m.id, m]));
@@ -67,6 +67,44 @@ 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 (!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' },
+ );
+ }
+ // 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) {
+ 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.`,
+ { status: 400, code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED' },
+ );
+ }
+ const scriptPath = join(PATHS.root, 'scripts', 'z_image_turbo.py');
+ const args = [
+ scriptPath,
+ '--model', modelId,
+ '--repo', model.repo,
+ '--prompt', prompt,
+ '--height', String(height),
+ '--width', String(width),
+ '--steps', String(steps),
+ '--guidance', String(guidance ?? 1.0),
+ '--seed', String(seed),
+ '--output', outputPath,
+ ];
+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);
+ if (initImagePath) args.push('--image-path', initImagePath);
+ if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));
+ if (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 (isFlux2(model)) {
if (!model.repo) {
throw new ServerError(
@@ -124,6 +162,8 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
if (initImagePath) args.push('--image-path', initImagePath);
if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));
if (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: flux2Python, args };
}
@@ -172,18 +212,18 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// entries broken on the OTHER platform (e.g. 'windows' on a macOS box).
const model = getImageModels().find((m) => m.id === modelId);
if (!model) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
- if (!isFlux2(model) && !pythonPath) {
+ // 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) {
throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
}
- // FLUX.2 runner doesn't apply LoRAs yet — reject up-front so the user
- // doesn't end up with a metadata sidecar that records LoRAs the renderer
- // silently dropped.
- if (isFlux2(model) && (loraFilenames.length > 0 || loraPaths.length > 0)) {
- throw new ServerError(
- 'LoRAs are not supported for FLUX.2 models yet — clear the LoRA selection or pick a Flux 1 model.',
- { status: 400, code: 'IMAGE_GEN_FLUX2_LORA_UNSUPPORTED' },
- );
- }
+ // FLUX.2 and Z-Image runners now load LoRAs via diffusers'
+ // pipe.load_lora_weights — but only LoRAs trained against the matching
+ // base model will produce sensible output. The LoRA picker UI uses the
+ // sidecar's `runnerFamily` field to filter; we don't enforce here so a
+ // user can deliberately experiment with off-family weights and see what
+ // happens (the runner will surface a shape-mismatch error from diffusers).
await ensureDir(PATHS.images);
await ensureDir(PATHS.loras);
@@ -193,7 +233,13 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
const outputPath = join(PATHS.images, filename);
const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
const actualSteps = steps ? Number(steps) : model.steps;
- const actualGuidance = guidance != null && guidance !== '' ? Number(guidance) : model.guidance;
+ // Step-wise distilled models (Schnell / FLUX.2 Klein / Z-Image-Turbo) ignore
+ // any guidance scale > 1.0 internally; passing a real value just produces a
+ // "Guidance scale X is ignored for step-wise distilled models." warning on
+ // every render. Pin to 1.0 for those so the runner's diffusers call stays
+ // quiet and the sidecar metadata reflects what the model actually used.
+ const requestedGuidance = guidance != null && guidance !== '' ? Number(guidance) : model.guidance;
+ const actualGuidance = model.cfgDisabled ? 1.0 : requestedGuidance;
// The new client-side surface sends `loraFilenames` (basenames only); the
// server resolves them against PATHS.loras. `loraPaths` is kept as a
// back-compat input for old gallery sidecars that stored absolute paths
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index c0c2b28f27..4b91642ad3 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -195,3 +195,114 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {
expect(args).toContain('--quantize');
});
});
+
+describe('imageGen local.buildArgs z-image dispatch', () => {
+ beforeEach(() => {
+ mockResolveFlux2Python.mockReset();
+ });
+
+ const baseInput = {
+ pythonPath: '/usr/bin/python3', // unused for z-image but kept in shape
+ prompt: 'a green dragon',
+ negativePrompt: '',
+ width: 1024,
+ height: 1024,
+ steps: 8,
+ guidance: 1.0,
+ seed: 99,
+ quantize: '8',
+ outputPath: '/tmp/out.png',
+ loraPaths: [],
+ loraScales: [],
+ stepwiseDir: '/tmp/stepwise',
+ initImagePath: null,
+ initImageStrength: null,
+ };
+
+ it('routes z-image models to the FLUX.2 venv + z_image_turbo.py', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { bin, args } = buildArgs({
+ ...baseInput,
+ model: {
+ id: 'z-image-turbo-bf16',
+ runner: 'z-image',
+ repo: 'Tongyi-MAI/Z-Image-Turbo',
+ },
+ });
+ expect(bin).toBe('/fake/venv-flux2/bin/python3');
+ expect(args[0]).toMatch(/scripts[/\\]z_image_turbo\.py$/);
+ expect(args).toContain('--repo');
+ expect(args[args.indexOf('--repo') + 1]).toBe('Tongyi-MAI/Z-Image-Turbo');
+ expect(args).toContain('--prompt');
+ expect(args[args.indexOf('--prompt') + 1]).toBe('a green dragon');
+ expect(args).toContain('--guidance');
+ expect(args[args.indexOf('--guidance') + 1]).toBe('1');
+ // No --metadata flag: local.js writes the canonical sidecar itself.
+ expect(args).not.toContain('--metadata');
+ // Stepwise dir threads through.
+ expect(args).toContain('--stepwise-image-output-dir');
+ expect(args[args.indexOf('--stepwise-image-output-dir') + 1]).toBe('/tmp/stepwise');
+ // Z-Image doesn't take FLUX.2's quantization/tokenizer/base flags.
+ expect(args).not.toContain('--quantization');
+ expect(args).not.toContain('--tokenizer-repo');
+ expect(args).not.toContain('--base-pipeline-repo');
+ });
+
+ it('throws a setup hint when the FLUX.2 venv is missing for z-image', () => {
+ mockResolveFlux2Python.mockReturnValue(null);
+ expect(() => buildArgs({
+ ...baseInput,
+ model: { id: 'z-image-turbo-bf16', runner: 'z-image', repo: 'Tongyi-MAI/Z-Image-Turbo' },
+ })).toThrow(/INSTALL_FLUX2=1/);
+ });
+
+ it('throws when a z-image model is missing repo', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ expect(() => buildArgs({
+ ...baseInput,
+ model: { id: 'z-image-broken', runner: 'z-image' },
+ })).toThrow(/missing the 'repo' field/);
+ });
+
+ it('throws when a z-image model has empty repo string', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ expect(() => buildArgs({
+ ...baseInput,
+ model: { id: 'z-image-quant', runner: 'z-image', repo: '' },
+ })).toThrow(/missing the 'repo' field/);
+ });
+
+ it('passes init-image args for z-image i2i', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ initImagePath: '/safe/path/init.png',
+ initImageStrength: 0.6,
+ model: {
+ id: 'z-image-turbo-bf16',
+ runner: 'z-image',
+ repo: 'Tongyi-MAI/Z-Image-Turbo',
+ },
+ });
+ expect(args).toContain('--image-path');
+ expect(args[args.indexOf('--image-path') + 1]).toBe('/safe/path/init.png');
+ expect(args).toContain('--image-strength');
+ expect(args[args.indexOf('--image-strength') + 1]).toBe('0.6');
+ });
+
+ it('passes negative prompt only when non-empty', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args: withoutNeg } = buildArgs({
+ ...baseInput,
+ model: { id: 'z-image-turbo-bf16', runner: 'z-image', repo: 'Tongyi-MAI/Z-Image-Turbo' },
+ });
+ expect(withoutNeg).not.toContain('--negative-prompt');
+ const { args: withNeg } = buildArgs({
+ ...baseInput,
+ negativePrompt: 'blurry',
+ model: { id: 'z-image-turbo-bf16', runner: 'z-image', repo: 'Tongyi-MAI/Z-Image-Turbo' },
+ });
+ expect(withNeg).toContain('--negative-prompt');
+ expect(withNeg[withNeg.indexOf('--negative-prompt') + 1]).toBe('blurry');
+ });
+});
diff --git a/server/services/loras.js b/server/services/loras.js
new file mode 100644
index 0000000000..2450ec287d
--- /dev/null
+++ b/server/services/loras.js
@@ -0,0 +1,222 @@
+/**
+ * LoRA service — install/list/delete + sidecar metadata management.
+ *
+ * Files live in `data/loras/<filename>.safetensors`; metadata lives next to
+ * them in `<filename>.metadata.json`. The sidecar is the source of truth for
+ * Civitai-derived info (trigger words, base model, recommended weight,
+ * preview image URL) — the .safetensors file alone has no such surface.
+ *
+ * Install flow: parse Civitai URL → fetch model metadata → pick version +
+ * primary .safetensors → stream-download to disk → write sidecar. The whole
+ * thing is one POST; progress is reported through the existing image-gen
+ * SSE channel (TBD — for v1 the client polls).
+ *
+ * No try/catch — errors bubble. Network errors during download leave a
+ * partial file on disk; the cleanup happens via a finalizer below.
+ */
+
+import { existsSync } from 'fs';
+import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'fs/promises';
+import { createWriteStream } from 'fs';
+import { Readable } from 'stream';
+import { pipeline } from 'stream/promises';
+import { join, basename } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
+import {
+ applyDownloadToken,
+ buildAuthHeaders,
+ buildSidecar,
+ fetchCivitaiModel,
+ parseCivitaiUrl,
+ pickPrimaryFile,
+ pickVersion,
+ slugifyForFilename,
+} from '../lib/civitai.js';
+import { getSettings } from './settings.js';
+
+const SIDECAR_SUFFIX = '.metadata.json';
+
+const sidecarPath = (loraFilename) => join(PATHS.loras, `${loraFilename}${SIDECAR_SUFFIX}`);
+
+// Reads the sidecar JSON next to a LoRA file. Returns `null` when the
+// sidecar is absent or unparseable — calling code can fall back to filename
+// inference for legacy LoRAs the user dropped in manually pre-Civitai.
+export const readSidecar = async (filename) => {
+ const raw = await readFile(sidecarPath(filename), 'utf-8').catch(() => null);
+ if (raw == null) return null;
+ // JSON.parse can throw on malformed sidecars — treat them as absent
+ // rather than crashing the list endpoint.
+ let parsed = null;
+ try { parsed = JSON.parse(raw); } catch { return null; }
+ return parsed && typeof parsed === 'object' ? parsed : null;
+};
+
+// Validate a basename so it can't escape PATHS.loras. The `.safetensors`
+// extension check also blocks dotfiles and traversal because `..` doesn't
+// end in `.safetensors`.
+export const assertSafeLoraFilename = (filename) => {
+ if (!filename || typeof filename !== 'string') {
+ throw new ServerError('Filename required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (!filename.endsWith('.safetensors') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {
+ throw new ServerError('Invalid LoRA filename', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+};
+
+// LoRAs without sidecars get a minimal "legacy" entry with sensible defaults
+// so the manager UI can still render LoRAs the user dropped in pre-Civitai.
+export const listLoras = async () => {
+ if (!existsSync(PATHS.loras)) return [];
+ const files = await readdir(PATHS.loras);
+ const safetensors = files.filter((f) => f.endsWith('.safetensors'));
+ const out = await Promise.all(safetensors.map(async (filename) => {
+ const fullPath = join(PATHS.loras, filename);
+ const s = await stat(fullPath).catch(() => null);
+ if (!s) return null;
+ const sidecar = await readSidecar(filename);
+ const fallbackName = filename.replace(/^lora-/, '').replace(/\.safetensors$/, '');
+ return {
+ filename,
+ name: sidecar?.name || fallbackName,
+ sizeBytes: s.size,
+ installedAt: sidecar?.installedAt || s.birthtime?.toISOString?.() || null,
+ // sidecar fields surfaced for the picker / manager UI:
+ civitai: sidecar?.civitai || null,
+ runnerFamily: sidecar?.runnerFamily || null,
+ triggerWords: sidecar?.triggerWords || [],
+ recommendedScale: sidecar?.recommendedScale ?? 1.0,
+ previewImageUrl: sidecar?.previewImageUrl || null,
+ description: sidecar?.description || '',
+ };
+ }));
+ return out.filter(Boolean).sort((a, b) => (b.installedAt || '').localeCompare(a.installedAt || ''));
+};
+
+export const getLora = async (filename) => {
+ assertSafeLoraFilename(filename);
+ const fullPath = join(PATHS.loras, filename);
+ if (!existsSync(fullPath)) {
+ throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ const list = await listLoras();
+ return list.find((l) => l.filename === filename) || null;
+};
+
+export const deleteLora = async (filename) => {
+ assertSafeLoraFilename(filename);
+ const filePath = join(PATHS.loras, filename);
+ if (!existsSync(filePath)) {
+ throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ await rm(filePath, { force: true });
+ await rm(sidecarPath(filename), { force: true });
+ console.log(`🗑️ Deleted LoRA: ${filename}`);
+ return { ok: true, filename };
+};
+
+// Patch the sidecar with user-editable fields (name, recommendedScale, notes).
+// Civitai-derived fields are passed through but the route layer scopes the
+// patch so callers can't trample those.
+export const patchLoraSidecar = async (filename, patch) => {
+ assertSafeLoraFilename(filename);
+ if (!existsSync(join(PATHS.loras, filename))) {
+ throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ const current = (await readSidecar(filename)) || { filename };
+ const next = { ...current, ...patch, filename };
+ await writeFile(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
+ return next;
+};
+
+// Resolve the active Civitai API key — either from settings (`civitai.apiKey`)
+// or the CIVITAI_API_KEY env var. Settings wins so a user can override the
+// env without restarting. Returns empty string for "no key", which the
+// downstream helpers treat as anonymous.
+export const resolveCivitaiKey = async () => {
+ const env = (process.env.CIVITAI_API_KEY || '').trim();
+ // getSettings reads the JSON every call; cheap and avoids stale-cache bugs.
+ const s = await getSettings();
+ const fromSettings = (s?.civitai?.apiKey || '').trim();
+ return fromSettings || env || '';
+};
+
+// Stream-download a URL to a temp file in PATHS.loras then rename into place.
+// The temp suffix prevents the listLoras endpoint from picking up a
+// half-downloaded file. fetchImpl is injectable for tests.
+const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} } = {}) => {
+ const tmpPath = `${destPath}.partial`;
+ const res = await fetchImpl(url, { headers, redirect: 'follow' });
+ if (!res.ok) {
+ if (res.status === 401 || res.status === 403) {
+ throw new ServerError(
+ `Civitai download rejected (${res.status}) — this LoRA may require an API key. Set CIVITAI_API_KEY in Settings and retry.`,
+ { status: res.status, code: 'CIVITAI_AUTH' },
+ );
+ }
+ throw new ServerError(`Civitai download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
+ }
+ if (!res.body) {
+ throw new ServerError('Civitai download returned no body', { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
+ }
+ // Node 18+ fetch returns a web ReadableStream; pipeline accepts it directly
+ // when wrapped in Readable.fromWeb (also handles backpressure correctly).
+ // On stream failure (network drop, disk full) the .partial would otherwise
+ // accumulate in PATHS.loras across retries.
+ const writer = createWriteStream(tmpPath);
+ await pipeline(Readable.fromWeb(res.body), writer).catch(async (err) => {
+ await rm(tmpPath, { force: true }).catch(() => {});
+ throw err;
+ });
+ await rename(tmpPath, destPath);
+};
+
+// Install a LoRA from a Civitai URL. Returns the new sidecar JSON so the
+// client can render it immediately without a second list round-trip.
+export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
+ const { modelId, versionId } = parseCivitaiUrl(input?.url);
+ const apiKey = (typeof input?.apiKey === 'string' && input.apiKey.trim()) || (await resolveCivitaiKey());
+ const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl });
+ const version = pickVersion(model, versionId);
+ const file = pickPrimaryFile(version);
+ if (!file?.downloadUrl) {
+ throw new ServerError(
+ `Civitai version ${version?.id} has no downloadUrl — try selecting a different version`,
+ { status: 422, code: 'CIVITAI_NO_DOWNLOAD' },
+ );
+ }
+ if (model?.type && model.type !== 'LORA' && model.type !== 'LoCon' && model.type !== 'LyCORIS') {
+ throw new ServerError(
+ `Civitai model "${model.name}" is type "${model.type}", not a LoRA — refusing to install`,
+ { status: 400, code: 'CIVITAI_NOT_A_LORA' },
+ );
+ }
+
+ // Build a stable filename: `lora-<slug>-<versionId>.safetensors`. The
+ // versionId suffix prevents collisions if a user installs two versions of
+ // the same model. The `lora-` prefix keeps it distinguishable from base
+ // model weights if they ever coexist in the same dir.
+ const slug = slugifyForFilename(model.name || file.name?.replace(/\.safetensors$/i, ''));
+ const filename = `lora-${slug}-v${version.id}.safetensors`;
+ const destPath = join(PATHS.loras, filename);
+ if (existsSync(destPath)) {
+ throw new ServerError(
+ `Already installed: ${filename}. Delete it first or pick a different version.`,
+ { status: 409, code: 'CIVITAI_ALREADY_INSTALLED' },
+ );
+ }
+
+ await mkdir(PATHS.loras, { recursive: true });
+
+ console.log(`📥 Installing Civitai LoRA: ${model.name} v${version.id} → ${filename} (${file.sizeKB ? Math.round(file.sizeKB / 1024) + ' MB' : 'size unknown'})`);
+ const tokenized = applyDownloadToken(file.downloadUrl, apiKey);
+ await downloadToFile(tokenized, destPath, {
+ fetchImpl,
+ headers: { 'User-Agent': 'PortOS/civitai-installer', ...buildAuthHeaders(apiKey) },
+ });
+
+ const sidecar = buildSidecar({ model, version, file, filename });
+ await writeFile(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ console.log(`✅ Installed Civitai LoRA: ${filename}`);
+ return sidecar;
+};
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
new file mode 100644
index 0000000000..2c568d1172
--- /dev/null
+++ b/server/services/loras.test.js
@@ -0,0 +1,204 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Point PATHS.loras at a temp dir for the duration of each test. PATHS is
+// computed at module load against process.cwd / __dirname, so the cleanest
+// way to swap it is to mock fileUtils for the loras service.
+let tmpRoot;
+let tmpLoras;
+let lorasService;
+let civitaiLib;
+
+beforeEach(async () => {
+ tmpRoot = mkdtempSync(join(tmpdir(), 'portos-loras-test-'));
+ tmpLoras = join(tmpRoot, 'loras');
+
+ vi.resetModules();
+ vi.doMock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, loras: tmpLoras },
+ };
+ });
+ // Stub settings so resolveCivitaiKey doesn't read the real data/settings.json.
+ vi.doMock('./settings.js', () => ({
+ getSettings: async () => ({}),
+ }));
+ lorasService = await import('./loras.js');
+ civitaiLib = await import('../lib/civitai.js');
+});
+
+afterEach(() => {
+ vi.doUnmock('../lib/fileUtils.js');
+ vi.doUnmock('./settings.js');
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+describe('listLoras', () => {
+ it('returns an empty list when the loras dir is missing', async () => {
+ expect(await lorasService.listLoras()).toEqual([]);
+ });
+
+ it('lists .safetensors files and merges sidecar metadata', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'lora-realstagram-v7.safetensors'), 'fake-weights');
+ await fs.writeFile(join(tmpLoras, 'lora-realstagram-v7.safetensors.metadata.json'), JSON.stringify({
+ filename: 'lora-realstagram-v7.safetensors',
+ name: 'RealStagram',
+ runnerFamily: 'mflux',
+ triggerWords: ['rstgrm'],
+ recommendedScale: 0.85,
+ installedAt: '2026-05-09T00:00:00.000Z',
+ }));
+ // A legacy file the user dropped in pre-Civitai (no sidecar).
+ await fs.writeFile(join(tmpLoras, 'lora-legacy.safetensors'), 'older-weights');
+
+ const list = await lorasService.listLoras();
+ const realstagram = list.find((l) => l.filename === 'lora-realstagram-v7.safetensors');
+ const legacy = list.find((l) => l.filename === 'lora-legacy.safetensors');
+ expect(realstagram.name).toBe('RealStagram');
+ expect(realstagram.runnerFamily).toBe('mflux');
+ expect(realstagram.triggerWords).toEqual(['rstgrm']);
+ expect(realstagram.recommendedScale).toBe(0.85);
+ expect(legacy.name).toBe('legacy');
+ expect(legacy.runnerFamily).toBe(null);
+ expect(legacy.recommendedScale).toBe(1.0);
+ });
+
+ it('survives an unparseable sidecar', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'lora-broken.safetensors'), 'w');
+ await fs.writeFile(join(tmpLoras, 'lora-broken.safetensors.metadata.json'), '{ this is not json');
+ const list = await lorasService.listLoras();
+ expect(list).toHaveLength(1);
+ expect(list[0].filename).toBe('lora-broken.safetensors');
+ expect(list[0].runnerFamily).toBe(null);
+ });
+});
+
+describe('deleteLora', () => {
+ it('removes file + sidecar', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'lora-x.safetensors'), 'w');
+ await fs.writeFile(join(tmpLoras, 'lora-x.safetensors.metadata.json'), '{}');
+ await lorasService.deleteLora('lora-x.safetensors');
+ expect(existsSync(join(tmpLoras, 'lora-x.safetensors'))).toBe(false);
+ expect(existsSync(join(tmpLoras, 'lora-x.safetensors.metadata.json'))).toBe(false);
+ });
+ it('rejects path traversal', async () => {
+ await expect(lorasService.deleteLora('../escape.safetensors')).rejects.toThrow(/Invalid LoRA filename/);
+ await expect(lorasService.deleteLora('foo/bar.safetensors')).rejects.toThrow(/Invalid LoRA filename/);
+ await expect(lorasService.deleteLora('foo.bin')).rejects.toThrow(/Invalid LoRA filename/);
+ });
+ it('404s for missing files', async () => {
+ await expect(lorasService.deleteLora('lora-missing.safetensors')).rejects.toThrow(/not found/);
+ });
+});
+
+describe('patchLoraSidecar', () => {
+ it('creates a sidecar when none exists', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'lora-y.safetensors'), 'w');
+ const patched = await lorasService.patchLoraSidecar('lora-y.safetensors', { recommendedScale: 0.5, name: 'Custom' });
+ expect(patched.recommendedScale).toBe(0.5);
+ expect(patched.name).toBe('Custom');
+ expect(JSON.parse(readFileSync(join(tmpLoras, 'lora-y.safetensors.metadata.json'), 'utf-8')).name).toBe('Custom');
+ });
+});
+
+describe('installFromCivitai', () => {
+ // Build a fake Civitai model JSON we can hand to the fetchImpl.
+ const FAKE_MODEL = {
+ id: 2600698,
+ name: 'RealStagram',
+ description: 'photoreal LoRA',
+ type: 'LORA',
+ creator: { username: 'someone' },
+ tags: ['photo'],
+ nsfw: false,
+ modelVersions: [
+ {
+ id: 7,
+ baseModel: 'Flux.1 D',
+ trainedWords: ['rstgrm'],
+ settings: { strength: 0.85 },
+ images: [{ url: 'https://civitai.com/p.jpg', nsfwLevel: 1 }],
+ files: [
+ { name: 'realstagram.safetensors', primary: true, sizeKB: 1024, hashes: { SHA256: 'abc' }, downloadUrl: 'https://civitai.com/api/download/models/7' },
+ ],
+ },
+ ],
+ };
+
+ it('downloads, writes the file, writes the sidecar', async () => {
+ const downloadedBytes = Buffer.from('fake-lora-weights');
+ const calls = [];
+ const fetchImpl = async (url) => {
+ calls.push(url);
+ if (url.startsWith('https://civitai.com/api/v1/models/2600698')) {
+ return { ok: true, status: 200, json: async () => FAKE_MODEL };
+ }
+ if (url.startsWith('https://civitai.com/api/download/models/7')) {
+ // Return a Web ReadableStream so Readable.fromWeb can consume it.
+ const stream = new ReadableStream({
+ start(c) { c.enqueue(new Uint8Array(downloadedBytes)); c.close(); },
+ });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const sidecar = await lorasService.installFromCivitai({ url: 'https://civitai.red/models/2600698/realstagram' }, { fetchImpl });
+ expect(sidecar.filename).toMatch(/^lora-RealStagram-v7\.safetensors$/);
+ expect(sidecar.civitai.modelId).toBe(2600698);
+ expect(sidecar.civitai.versionId).toBe(7);
+ expect(sidecar.runnerFamily).toBe('mflux');
+ expect(sidecar.triggerWords).toEqual(['rstgrm']);
+ expect(sidecar.recommendedScale).toBe(0.85);
+ // File on disk
+ const installedPath = join(tmpLoras, sidecar.filename);
+ expect(existsSync(installedPath)).toBe(true);
+ expect(readFileSync(installedPath, 'utf-8')).toBe('fake-lora-weights');
+ // Sidecar on disk
+ const sidecarPath = `${installedPath}.metadata.json`;
+ expect(JSON.parse(readFileSync(sidecarPath, 'utf-8')).civitai.modelId).toBe(2600698);
+ // Two HTTP calls — metadata + download
+ expect(calls).toHaveLength(2);
+ });
+
+ it('refuses to install non-LoRA model types', async () => {
+ const fetchImpl = async () => ({ ok: true, status: 200, json: async () => ({ ...FAKE_MODEL, type: 'Checkpoint' }) });
+ await expect(
+ lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),
+ ).rejects.toThrow(/not a LoRA/);
+ });
+
+ it('refuses to clobber an already-installed file', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'lora-RealStagram-v7.safetensors'), 'pre-existing');
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };
+ throw new Error(`should not download: ${url}`);
+ };
+ await expect(
+ lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),
+ ).rejects.toThrow(/Already installed/);
+ });
+
+ it('surfaces a friendly auth error when download is gated', async () => {
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };
+ return { ok: false, status: 401, statusText: 'Unauthorized' };
+ };
+ await expect(
+ lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),
+ ).rejects.toThrow(/may require an API key/);
+ });
+});