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): FLUX.2-klein on macOS via PyTorch + diffusers + MPS (#190)

[._.]/ Adam Eivy3c08cf59765c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 880f92dd1a..e9e4b1691e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **FLUX.2-klein image generation on macOS (Apple Silicon).** Three quantized variants ship: 4B SDNQ-4bit (~8 GB @ 512px, recommended), 9B SDNQ-4bit (~12 GB, needs 32+ GB RAM), and 4B Int8 (~16 GB). Runs through PyTorch + diffusers + MPS in a separate `~/.portos/venv-flux2` to avoid colliding with mflux's older torch. `INSTALL_FLUX2=1 bash scripts/setup-image-video.sh` bootstraps the venv (idempotent — skips re-install when `Flux2KleinPipeline` already imports). The runner (`scripts/flux2_macos.py`) mirrors `mflux-generate`'s CLI surface so the existing local-image dispatcher just swaps the binary path; live preview frames, metadata sidecar, gallery, and Remix all work unchanged. Stepwise preview decodes latents on a `@torch.no_grad()` callback and writes capped 512-px PNGs so fs.watch + base64 stays cheap. Models are gated on HuggingFace — accept the license at https://huggingface.co/black-forest-labs/FLUX.2-klein-4B and export `HF_TOKEN`; the Image Gen page surfaces a yellow banner when the venv is missing or the token isn't set. The legacy `flux2-klein-{4b,9b}` registry entries (which had `broken: 'macos'`) auto-upgrade in place — user customizations like a custom name or steps are preserved.
+
- **Media model registry at `data/media-models.json`** — single source of truth for video and image model definitions, the LTX text encoder, and per-platform defaults. Replaces hardcoded model catalogs in `videoGen/local.js`, `imageGen/local.js`, and `imageVideoModels.js`. Seeded automatically on first run; edit + restart the server to swap models. New `gemma-bf16` (now default, best output quality), `gemma-qat-4bit` (auto-detected if LM Studio installed it), and `gemma-4bit` text-encoder options. Loader resolves `~/...` and prefers a local `localPath` when it exists.
- **`+faststart` mp4 post-processing** — every video render is remuxed (no re-encoding, ~hundreds of ms) to move the moov atom to the front of the file. Gallery tiles with `preload="metadata"` now render their poster frame on page load instead of flashing black until clicked.
- **`caffeinate -i -w <pid>`** spawned alongside the LTX Python child on macOS so a 90s+ render isn't aborted by display/system sleep on a laptop. `-w` makes it self-exit when our pid does — no manual lifecycle management.
diff --git a/.gitignore b/.gitignore
index d75486314a..2ad72435b0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -55,3 +55,4 @@ browser/node_modules/
browser/package-lock.json
client/package-lock.json
server/package-lock.json
+__pycache__/
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index b263cfdb82..23a6fc1c13 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -56,6 +56,10 @@ export default function ImageGen() {
const [gallery, setGallery] = useState([]);
const [preview, setPreview] = useState(null);
const [showHidden, setShowHidden] = useState(false);
+ // FLUX.2 readiness — drives the gating banner. Lazy-fetched on the first
+ // selection of a flux2 model so we don't make an extra request when the
+ // user is only using mflux/external/codex.
+ const [flux2Status, setFlux2Status] = useState(null);
const [selectedMode, setSelectedMode] = useState(null);
const [availableBackends, setAvailableBackends] = useState([]);
@@ -272,6 +276,24 @@ export default function ImageGen() {
const currentModel = models.find((m) => m.id === modelId);
const matchedResolution = RESOLUTIONS.find((r) => r.w === width && r.h === height);
const resolutionLabel = matchedResolution?.label || `${width}×${height}`;
+ const isFlux2Model = currentModel?.runner === 'flux2';
+
+ useEffect(() => {
+ if (!isFlux2Model) { setFlux2Status(null); return; }
+ // Abort the in-flight request when the user switches models before it
+ // resolves — otherwise a stale response could re-show the banner for
+ // a non-flux2 selection.
+ const controller = new AbortController();
+ fetch('/api/image-gen/setup/flux2-status', { signal: controller.signal })
+ .then((r) => r.ok ? r.json() : null)
+ .then((s) => { if (s) setFlux2Status(s); })
+ .catch(() => {});
+ return () => controller.abort();
+ }, [isFlux2Model, modelId]);
+
+ const flux2Issue = isFlux2Model && flux2Status
+ ? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)
+ : null;
const { visibleGallery, hiddenGallery } = useMemo(() => ({
visibleGallery: gallery.filter((img) => !img.hidden),
hiddenGallery: gallery.filter((img) => img.hidden),
@@ -566,6 +588,22 @@ export default function ImageGen() {
</div>
</div>
+ {flux2Issue === 'venv' && (
+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">
+ FLUX.2 venv not found at <code className="text-white">{flux2Status.expectedVenvPath}</code>.
+ Run <code className="text-white">INSTALL_FLUX2=1 bash scripts/setup-image-video.sh</code> to bootstrap it.
+ </div>
+ )}
+ {flux2Issue === 'token' && (
+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">
+ FLUX.2-klein is gated. Accept the license at{' '}
+ <a href={flux2Status.licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">
+ huggingface.co/black-forest-labs/FLUX.2-klein-4B
+ </a>{' '}
+ and export <code className="text-white">HF_TOKEN=…</code> before running PortOS.
+ </div>
+ )}
+
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{isLocalMode && models.length > 0 && (
<div>
@@ -653,17 +691,19 @@ export default function ImageGen() {
className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
/>
</div>
- <div>
- <label className="block text-xs font-medium text-gray-400 mb-1">Quantize (bits)</label>
- <select
- value={quantize}
- onChange={(e) => setQuantize(e.target.value)}
- disabled={generating}
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
- >
- {['3', '4', '5', '6', '8'].map((q) => <option key={q} value={q}>{q}-bit{q === '8' ? ' (default)' : q === '4' ? ' (fast)' : ''}</option>)}
- </select>
- </div>
+ {!isFlux2Model && (
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">Quantize (bits)</label>
+ <select
+ value={quantize}
+ onChange={(e) => setQuantize(e.target.value)}
+ disabled={generating}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ >
+ {['3', '4', '5', '6', '8'].map((q) => <option key={q} value={q}>{q}-bit{q === '8' ? ' (default)' : q === '4' ? ' (fast)' : ''}</option>)}
+ </select>
+ </div>
+ )}
</>
) : (
<div>
@@ -679,7 +719,7 @@ export default function ImageGen() {
))}
</div>
- {isLocalMode && availableLoras.length > 0 && (
+ {isLocalMode && !isFlux2Model && 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">
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
new file mode 100755
index 0000000000..5677bf49d0
--- /dev/null
+++ b/scripts/flux2_macos.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python3
+"""
+PortOS FLUX.2-klein runner.
+
+Spawned by `server/services/imageGen/local.js` when the active model has
+`runner: 'flux2'` in `data/media-models.json`. Mirrors `mflux-generate`'s
+CLI surface so the dispatcher only needs to swap the binary path; all the
+progress / metadata / stepwise / cancel plumbing on the JS side stays the
+same.
+
+Quantization branches:
+ - `sdnq`: Disty0/FLUX.2-klein-{4B,9B}-SDNQ-4bit-dynamic*. Tokenizer is
+ pulled from the gated `black-forest-labs/...` base repo because the
+ SDNQ packages ship without vocab files.
+ - `int8`: aydin99/FLUX.2-klein-4B-int8 — uses the QuantizedFlux2Transformer
+ shim from flux2_quantized.py to rehydrate optimum-quanto weights, then
+ stitches them into a Flux2KleinPipeline that draws VAE/scheduler from
+ the gated base repo.
+
+Both branches need an HF_TOKEN with the FLUX.2-klein license accepted.
+"""
+
+import argparse
+import inspect
+import json
+import os
+import sys
+from pathlib import Path
+
+# Must precede `import torch` — enables the fast-math kernel path on MPS,
+# matches the upstream reference implementation.
+os.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")
+
+import torch
+from PIL import Image
+
+
+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 probe_hf_auth(repo: str) -> None:
+ """Fail early with a clear message when HF_TOKEN is missing or the
+ license hasn't been accepted. Without this probe, the user sees a vague
+ HTTP 401 stack trace mid-pipeline-load."""
+ from huggingface_hub import HfApi
+ from huggingface_hub.utils import GatedRepoError, HfHubHTTPError, RepositoryNotFoundError
+ try:
+ HfApi().model_info(repo)
+ except GatedRepoError:
+ print(
+ f"❌ HF gated repo: accept license at https://huggingface.co/{repo} "
+ f"and set HF_TOKEN before generating.",
+ file=sys.stderr,
+ )
+ sys.exit(2)
+ except RepositoryNotFoundError:
+ print(f"❌ HF repo not found: {repo}", file=sys.stderr)
+ sys.exit(2)
+ except HfHubHTTPError as err:
+ if getattr(err.response, "status_code", None) == 401:
+ print(
+ f"❌ HF auth required for {repo}. Set HF_TOKEN (and accept the "
+ f"license at https://huggingface.co/{repo}).",
+ file=sys.stderr,
+ )
+ sys.exit(2)
+ # Network blip / HF down — let the pipeline call retry.
+ print(f"⚠️ HF probe non-fatal error: {err}", file=sys.stderr)
+
+
+def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):
+ # `sdnq` registers a custom config type at import-time. The Flux2KleinPipeline
+ # `from_pretrained` call below pulls a config that references it, so the
+ # import has to happen first. Keep it inside the function so the runner
+ # also works for the int8 branch on systems without sdnq installed.
+ import sdnq # noqa: F401 (registration side-effect)
+ from diffusers import Flux2KleinPipeline
+ from transformers import AutoTokenizer
+
+ print(f"🔧 sdnq: tokenizer ← {tokenizer_repo}", file=sys.stderr)
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_repo, subfolder="tokenizer", use_fast=False)
+ print(f"🔧 sdnq: pipeline ← {repo}", file=sys.stderr)
+ pipe = Flux2KleinPipeline.from_pretrained(
+ repo,
+ tokenizer=tokenizer,
+ torch_dtype=dtype,
+ low_cpu_mem_usage=True,
+ )
+ pipe.to(device)
+ return pipe
+
+
+def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):
+ from accelerate import init_empty_weights
+ from diffusers import Flux2KleinPipeline
+ from huggingface_hub import snapshot_download
+ from optimum.quanto import requantize
+ from safetensors.torch import load_file
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
+
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ from flux2_quantized import QuantizedFlux2Transformer2DModel
+
+ print(f"🔧 int8: snapshot ← {repo}", file=sys.stderr)
+ model_path = snapshot_download(repo)
+
+ print("🔧 int8: transformer …", file=sys.stderr)
+ qtransformer = QuantizedFlux2Transformer2DModel.from_pretrained(model_path)
+ qtransformer.to(device=device, dtype=dtype)
+
+ print("🔧 int8: text encoder …", file=sys.stderr)
+ # AutoModelForCausalLM picks the right class from the config
+ # (Qwen3ForCausalLM here). transformers>=4.51 ships Qwen3 in-tree so we
+ # don't need trust_remote_code; passing it would let a maliciously edited
+ # model registry point at a repo that executes arbitrary Python at load.
+ config = AutoConfig.from_pretrained(f"{model_path}/text_encoder")
+ with init_empty_weights():
+ text_encoder = AutoModelForCausalLM.from_config(config)
+ with open(f"{model_path}/text_encoder/quanto_qmap.json", "r") as f:
+ te_qmap = json.load(f)
+ te_state = load_file(f"{model_path}/text_encoder/model.safetensors")
+ requantize(text_encoder, state_dict=te_state, quantization_map=te_qmap)
+ text_encoder.eval()
+ text_encoder.to(device, dtype=dtype)
+
+ tokenizer = AutoTokenizer.from_pretrained(f"{model_path}/tokenizer")
+
+ print(f"🔧 int8: VAE/scheduler ← {base_repo}", file=sys.stderr)
+ pipe = Flux2KleinPipeline.from_pretrained(
+ base_repo,
+ transformer=None,
+ text_encoder=None,
+ tokenizer=None,
+ torch_dtype=dtype,
+ )
+ pipe.transformer = qtransformer._wrapped
+ pipe.text_encoder = text_encoder
+ pipe.tokenizer = tokenizer
+ pipe.to(device)
+ return 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):
+ """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. Match mflux's filename
+ shape (`step_<N>.png`, no zero padding) so the existing parser sorts
+ by mtime and picks the latest correctly."""
+
+ 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", None)
+ if scaling is None:
+ scaling = 1.0
+ shift = getattr(vae.config, "shift_factor", None)
+ if shift is None:
+ shift = 0.0
+
+ @torch.no_grad()
+ def cb(pipe, step_index, _timestep, callback_kwargs):
+ latents = callback_kwargs.get("latents")
+ if latents is None:
+ return callback_kwargs
+ # Best-effort decode. Errors here must not abort generation — the
+ # final image is still produced after the last step.
+ try:
+ 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)
+ # Cap preview size — fs.watch + base64 encode every step is fine
+ # for 256px thumbnails but wasteful at 1024px.
+ img.thumbnail((512, 512), Image.LANCZOS)
+ img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
+ except Exception as err:
+ print(f"⚠️ stepwise preview failed at step {step_index}: {err}", file=sys.stderr)
+ return callback_kwargs
+
+ 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 FLUX.2-klein runner")
+ p.add_argument("--model", required=True, help="model id (e.g. flux2-klein-4b)")
+ p.add_argument("--quantization", required=True, choices=["sdnq", "int8"])
+ p.add_argument("--repo", required=True, help="HF repo for the quantized weights")
+ p.add_argument("--tokenizer-repo", default=None, help="HF repo for tokenizer (sdnq variants)")
+ p.add_argument("--base-pipeline-repo", default=None, help="HF repo for VAE/scheduler (int8 variant)")
+ 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=3.5)
+ 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"])
+ 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
+
+ if args.quantization == "sdnq":
+ if not args.tokenizer_repo:
+ print("❌ --tokenizer-repo is required for sdnq variants", file=sys.stderr)
+ sys.exit(64)
+ probe_hf_auth(args.tokenizer_repo)
+ pipe = load_pipeline_sdnq(args.repo, args.tokenizer_repo, device, dtype)
+ elif args.quantization == "int8":
+ if not args.base_pipeline_repo:
+ print("❌ --base-pipeline-repo is required for int8 variants", file=sys.stderr)
+ sys.exit(64)
+ probe_hf_auth(args.base_pipeline_repo)
+ pipe = load_pipeline_int8(args.repo, args.base_pipeline_repo, device, dtype)
+ else:
+ print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)
+ sys.exit(64)
+
+ apply_memory_optimizations(pipe)
+
+ seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())
+ generator = make_generator(device, seed)
+
+ 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
+ )
+
+ callback = make_stepwise_callback(args.stepwise_image_output_dir, pipe)
+ # Flux2KleinPipeline.__call__ doesn't always accept negative_prompt or
+ # strength — passing an unsupported kwarg raises TypeError. Filter to
+ # what the live signature actually accepts.
+ 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
+ # Some pipelines accept the callback but not the explicit input list;
+ # only set when supported.
+ 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 the reference impl).
+ 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(
+ f"🎨 flux2 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 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),
+ "quantization": args.quantization,
+ "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,
+ },
+ )
+
+ # Free VRAM eagerly so a back-to-back generation in the same process
+ # doesn't OOM. The PortOS runner respawns per request right now, so this
+ # is mostly belt-and-suspenders.
+ 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"✅ flux2 saved {args.output} (seed={seed})", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/flux2_quantized.py b/scripts/flux2_quantized.py
new file mode 100644
index 0000000000..3655db0e65
--- /dev/null
+++ b/scripts/flux2_quantized.py
@@ -0,0 +1,159 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+# Adapted for FLUX.2-klein by adding Flux2Transformer2DModel and Qwen3 support.
+# Vendored from https://github.com/newideas99/ultra-fast-image-gen
+# (quantized_flux2.py) so we can rehydrate aydin99/FLUX.2-klein-4B-int8 without
+# pulling that whole project as a dependency.
+"""
+QuantizedFlux2Transformer2DModel — wrapper that loads an int8/optimum-quanto
+quantized Flux2 transformer back into a `Flux2Transformer2DModel` shape that
+`diffusers.Flux2KleinPipeline` accepts as `transformer=...`.
+
+The shim is needed because optimum-quanto stores its quantization map in a
+`quanto_qmap.json` sidecar instead of the standard diffusers config, so the
+default `from_pretrained` path can't reconstruct the model.
+"""
+
+import json
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Union
+
+from huggingface_hub import ModelHubMixin, snapshot_download
+
+from optimum.quanto import freeze, qtype, quantization_map, quantize, requantize, Optimizer
+
+from diffusers.models.model_loading_utils import load_state_dict
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import (
+ CONFIG_NAME,
+ SAFE_WEIGHTS_INDEX_NAME,
+ SAFETENSORS_WEIGHTS_NAME,
+ _get_checkpoint_shard_files,
+ is_accelerate_available,
+)
+from optimum.quanto.models.shared_dict import ShardedStateDict
+
+
+class QuantizedDiffusersModel(ModelHubMixin):
+ """Base class for quantized diffusers models."""
+
+ BASE_NAME = "quanto"
+ base_class: Optional[type] = None
+
+ def __init__(self, model: ModelMixin):
+ if not isinstance(model, ModelMixin) or len(quantization_map(model)) == 0:
+ raise ValueError("The source model must be a quantized diffusers model.")
+ self._wrapped = model
+
+ def __getattr__(self, name: str) -> Any:
+ try:
+ return super().__getattr__(name)
+ except AttributeError:
+ wrapped = self.__dict__["_wrapped"]
+ return getattr(wrapped, name)
+
+ def forward(self, *args, **kwargs):
+ return self._wrapped.forward(*args, **kwargs)
+
+ def __call__(self, *args, **kwargs):
+ return self._wrapped.forward(*args, **kwargs)
+
+ @staticmethod
+ def _qmap_name():
+ return f"{QuantizedDiffusersModel.BASE_NAME}_qmap.json"
+
+ @classmethod
+ def quantize(
+ cls,
+ model: ModelMixin,
+ weights: Optional[Union[str, qtype]] = None,
+ activations: Optional[Union[str, qtype]] = None,
+ optimizer: Optional[Optimizer] = None,
+ include: Optional[Union[str, List[str]]] = None,
+ exclude: Optional[Union[str, List[str]]] = None,
+ ):
+ if not isinstance(model, ModelMixin):
+ raise ValueError("The source model must be a diffusers model.")
+ quantize(
+ model,
+ weights=weights,
+ activations=activations,
+ optimizer=optimizer,
+ include=include,
+ exclude=exclude,
+ )
+ freeze(model)
+ return cls(model)
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs):
+ if cls.base_class is None:
+ raise ValueError("The `base_class` attribute needs to be configured.")
+
+ if not is_accelerate_available():
+ raise ValueError("Reloading a quantized diffusers model requires the accelerate library.")
+ from accelerate import init_empty_weights
+
+ if os.path.isdir(pretrained_model_name_or_path):
+ working_dir = pretrained_model_name_or_path
+ else:
+ working_dir = snapshot_download(pretrained_model_name_or_path, **kwargs)
+
+ qmap_path = os.path.join(working_dir, cls._qmap_name())
+ if not os.path.exists(qmap_path):
+ raise ValueError(
+ f"No quantization map found in {pretrained_model_name_or_path}: is this a quantized model ?"
+ )
+
+ model_config_path = os.path.join(working_dir, CONFIG_NAME)
+ if not os.path.exists(model_config_path):
+ raise ValueError(f"{CONFIG_NAME} not found in {pretrained_model_name_or_path}.")
+
+ with open(qmap_path, "r", encoding="utf-8") as f:
+ qmap = json.load(f)
+
+ with open(model_config_path, "r", encoding="utf-8") as f:
+ original_model_cls_name = json.load(f)["_class_name"]
+ configured_cls_name = cls.base_class.__name__
+ if configured_cls_name != original_model_cls_name:
+ raise ValueError(
+ f"Configured base class ({configured_cls_name}) differs from what was derived from the provided configuration ({original_model_cls_name})."
+ )
+
+ config = cls.base_class.load_config(pretrained_model_name_or_path, **kwargs)
+ with init_empty_weights():
+ model = cls.base_class.from_config(config)
+
+ checkpoint_file = os.path.join(working_dir, SAFE_WEIGHTS_INDEX_NAME)
+ if os.path.exists(checkpoint_file):
+ _, sharded_metadata = _get_checkpoint_shard_files(working_dir, checkpoint_file)
+ state_dict = ShardedStateDict(working_dir, sharded_metadata["weight_map"])
+ else:
+ checkpoint_file = os.path.join(working_dir, SAFETENSORS_WEIGHTS_NAME)
+ if not os.path.exists(checkpoint_file):
+ raise ValueError(f"No safetensor weights found in {pretrained_model_name_or_path}.")
+ state_dict = load_state_dict(checkpoint_file)
+
+ requantize(model, state_dict=state_dict, quantization_map=qmap)
+ model.eval()
+ return cls(model)
+
+ def _save_pretrained(self, save_directory: Path) -> None:
+ self._wrapped.save_pretrained(save_directory)
+ qmap_name = os.path.join(save_directory, self._qmap_name())
+ qmap = quantization_map(self._wrapped)
+ with open(qmap_name, "w", encoding="utf8") as f:
+ json.dump(qmap, f, indent=4)
+
+
+# Top-level diffusers import. This whole module uses diffusers internals
+# (ModelMixin, load_state_dict, etc.), so it can only be imported with
+# diffusers on the path — that's expected: callers run inside the flux2
+# venv that setup-image-video.sh provisions.
+from diffusers.models.transformers.transformer_flux2 import Flux2Transformer2DModel
+
+
+class QuantizedFlux2Transformer2DModel(QuantizedDiffusersModel):
+ """Quantized FLUX.2 Transformer model."""
+
+ base_class = Flux2Transformer2DModel
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index cf864d085d..98739b3f42 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -9,6 +9,7 @@
# PYTHON_BIN Python 3 binary to use (default: python3)
# PORTOS_DATA Path to PortOS data dir (default: ./data, resolved from $REPO_ROOT)
# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)
+# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)
set -euo pipefail
@@ -70,6 +71,56 @@ if [[ "$INSTALL_VIDEO" == "1" ]]; then
fi
fi
+INSTALL_FLUX2="${INSTALL_FLUX2:-$(is_macos && echo 1 || echo 0)}"
+
+if [[ "$INSTALL_FLUX2" == "1" ]]; then
+ # FLUX.2-klein needs torch>=2.5 + diffusers-from-git + sdnq + optimum-quanto.
+ # Mixing those into the mflux pip --user pile (mflux pulls older torch) is
+ # fragile, so we use a sibling venv. server/lib/pythonSetup.js looks for
+ # python3 here when the active model has runner=='flux2'.
+ FLUX2_VENV="${HOME}/.portos/venv-flux2"
+ FLUX2_PY="$FLUX2_VENV/bin/python3"
+ if [[ ! -x "$FLUX2_PY" ]]; then
+ echo "📦 Creating FLUX.2 venv at ${FLUX2_VENV}..."
+ mkdir -p "${HOME}/.portos"
+ "$PYTHON_BIN" -m venv "$FLUX2_VENV"
+ fi
+
+ # Skip the (slow, network-heavy) pip path when Flux2KleinPipeline already
+ # imports — diffusers-from-git is a git clone every run otherwise. Use
+ # FLUX2_FORCE_REINSTALL=1 to bypass.
+ if [[ "${FLUX2_FORCE_REINSTALL:-}" != "1" ]] && "$FLUX2_PY" -c "from diffusers import Flux2KleinPipeline" 2>/dev/null; then
+ echo "✅ FLUX.2 venv already ready: $FLUX2_PY"
+ else
+ echo "📦 Installing FLUX.2 packages into $FLUX2_VENV..."
+ "$FLUX2_PY" -m pip install --upgrade pip wheel setuptools >/dev/null
+ # diffusers-from-git is required because Flux2KleinPipeline isn't in any
+ # tagged release as of late 2025 / early 2026. sdnq is git-only too —
+ # registers a custom config type at import-time which
+ # Flux2KleinPipeline.from_pretrained relies on.
+ "$FLUX2_PY" -m pip install --upgrade \
+ "torch>=2.5" \
+ torchvision \
+ accelerate \
+ "transformers>=4.51" \
+ sentencepiece \
+ protobuf \
+ safetensors \
+ "huggingface_hub[hf_xet]" \
+ "diffusers @ git+https://github.com/huggingface/diffusers" \
+ "sdnq @ git+https://github.com/Disty0/sdnq.git" \
+ "peft>=0.17" \
+ "optimum-quanto>=0.2.7" \
+ pillow
+ if ! "$FLUX2_PY" -c "from diffusers import Flux2KleinPipeline" 2>/dev/null; then
+ echo "❌ flux2 venv built but 'from diffusers import Flux2KleinPipeline' failed." >&2
+ echo " Try: $FLUX2_PY -m pip install --upgrade --force-reinstall 'diffusers @ git+https://github.com/huggingface/diffusers'" >&2
+ exit 1
+ fi
+ echo "✅ FLUX.2 venv ready: $FLUX2_PY"
+ fi
+fi
+
# ffmpeg — required for thumbnails, last-frame extraction, and stitch.
if ! have ffmpeg; then
if is_macos && have brew; then
@@ -87,5 +138,12 @@ echo " Python: $PYTHON_PATH"
echo " HF cache: ~/.cache/huggingface (HF default)"
echo " LoRAs: ${PORTOS_DATA}/loras"
echo " Videos: ${PORTOS_DATA}/videos"
+if [[ "$INSTALL_FLUX2" == "1" ]]; then
+ echo " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"
+ echo ""
+ echo "⚠️ FLUX.2-klein needs HF auth: accept the license at"
+ echo " https://huggingface.co/black-forest-labs/FLUX.2-klein-4B"
+ echo " then export HF_TOKEN=... before running PortOS."
+fi
echo ""
echo "Set this Python path in PortOS Settings → Image Gen → Local."
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 66bf165d67..6ca21addfe 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -43,10 +43,43 @@ const DEFAULT_REGISTRY = {
defaultWindows: 'ltx_video',
},
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: 'flux2-klein-4b', name: 'Flux 2 Klein 4B', steps: 8, guidance: 3.5, broken: 'macos' },
- { id: 'flux2-klein-9b', name: 'Flux 2 Klein 9B', steps: 8, guidance: 3.5, broken: 'macos' },
+ // 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
+ // set HF_TOKEN before first use.
+ {
+ 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,
+ },
+ {
+ 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,
+ },
+ {
+ 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,
+ },
],
textEncoders: [
{ id: 'gemma-4bit', label: 'Gemma 3 12B 4-bit (smallest, ~7 GB)', repo: 'mlx-community/gemma-3-12b-it-4bit' },
@@ -90,13 +123,42 @@ const seedIfMissing = () => {
const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
const arrayOrDefault = (v, fallback) => (Array.isArray(v) ? v : fallback);
+// Pre-flux2 stored entries had `broken: 'macos'` and no `runner` field. Merge
+// missing flux2 fields from DEFAULT_REGISTRY when an entry id matches a known
+// flux2 model but is missing the runner discriminator. User overrides for
+// other fields (custom name, steps, repo) are preserved.
+const FLUX2_DEFAULTS_BY_ID = Object.fromEntries(
+ DEFAULT_REGISTRY.image.filter((m) => m.runner === 'flux2').map((m) => [m.id, m])
+);
+
+const upgradeImageEntries = (list) => {
+ if (!Array.isArray(list)) return list;
+ return list.map((entry) => {
+ if (!isPlainObject(entry) || typeof entry.id !== 'string') return entry;
+ const seed = FLUX2_DEFAULTS_BY_ID[entry.id];
+ // Only upgrade entries that DIDN'T set `runner` at all — a user who
+ // explicitly chose a different runner for a known flux2 id (e.g. to
+ // wire it up to a custom runner) keeps that override.
+ if (!seed || entry.runner !== undefined) return entry;
+ // Only strip `broken: 'macos'` (the legacy flag the upgrade is meant
+ // to clear). Any other broken value the user added is intentional and
+ // preserved.
+ const { broken, ...rest } = entry;
+ const merged = { ...seed, ...rest, runner: 'flux2' };
+ if (broken !== undefined && broken !== 'macos') merged.broken = broken;
+ return merged;
+ });
+};
+
+export const isFlux2 = (model) => model?.runner === 'flux2';
+
const normalizeRegistry = (parsed) => {
const safe = isPlainObject(parsed) ? parsed : {};
const safeVideo = isPlainObject(safe.video) ? safe.video : {};
return {
...DEFAULT_REGISTRY,
...safe,
- image: arrayOrDefault(safe.image, DEFAULT_REGISTRY.image),
+ image: upgradeImageEntries(arrayOrDefault(safe.image, DEFAULT_REGISTRY.image)),
textEncoders: arrayOrDefault(safe.textEncoders, DEFAULT_REGISTRY.textEncoders),
video: {
...DEFAULT_REGISTRY.video,
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 041850f0c6..80efafc909 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -68,6 +68,31 @@ export async function detectPython() {
return stdout.trim().split(/\r?\n/)[0] || null;
}
+// FLUX.2 runs in its own venv because mflux (MLX) and torch+diffusers-from-git
+// have hostile dependency trees. Bootstrap with `INSTALL_FLUX2=1
+// scripts/setup-image-video.sh`. We probe a small candidate list rather than
+// asking the user to configure it separately — first match wins.
+const FLUX2_VENV_CANDIDATES = IS_WIN
+ ? [
+ join(HOME, '.portos', 'venv-flux2', 'Scripts', 'python.exe'),
+ join(PATHS.data, 'python', 'venv-flux2', 'Scripts', 'python.exe'),
+ ]
+ : [
+ join(HOME, '.portos', 'venv-flux2', 'bin', 'python3'),
+ join(PATHS.data, 'python', 'venv-flux2', 'bin', 'python3'),
+ ];
+
+export const FLUX2_VENV_DEFAULT = FLUX2_VENV_CANDIDATES[0];
+
+let cachedFlux2Python = null;
+export function resolveFlux2Python() {
+ if (cachedFlux2Python && existsSync(cachedFlux2Python)) return cachedFlux2Python;
+ for (const p of FLUX2_VENV_CANDIDATES) {
+ if (existsSync(p)) { cachedFlux2Python = p; return p; }
+ }
+ return null;
+}
+
// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath
// before exec. Single-user / Tailnet model means we trust the operator, but
// "you can shell out to anything" is still too sharp — restrict to actual
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 498b0412dc..e0e31bc83d 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -22,6 +22,7 @@ import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
import {
REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,
isExternallyManaged, createVenv, isAllowedPython, pipNameFor,
+ resolveFlux2Python, FLUX2_VENV_DEFAULT,
} from '../lib/pythonSetup.js';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:path';
@@ -186,6 +187,28 @@ router.get('/setup/python', asyncHandler(async (_req, res) => {
res.json({ path });
}));
+// Used by the FLUX.2 model picker: surface a banner when the gated repo's
+// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.
+router.get('/setup/flux2-status', (_req, res) => {
+ // huggingface_hub reads HF_TOKEN (preferred) and the legacy
+ // HUGGINGFACEHUB_API_TOKEN / HUGGINGFACE_HUB_TOKEN names. Earlier rev of
+ // this code used HUGGING_FACE_HUB_TOKEN (extra underscore) which doesn't
+ // match what the library actually checks.
+ const hasToken = !!(
+ process.env.HF_TOKEN ||
+ process.env.HUGGINGFACE_HUB_TOKEN ||
+ process.env.HUGGINGFACEHUB_API_TOKEN
+ );
+ const venvPython = resolveFlux2Python();
+ res.json({
+ hfTokenPresent: hasToken,
+ venvInstalled: !!venvPython,
+ venvPath: venvPython,
+ expectedVenvPath: FLUX2_VENV_DEFAULT,
+ licenseUrl: 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B',
+ });
+});
+
const checkSchema = z.object({ pythonPath: z.string().min(1) });
router.get('/setup/check', asyncHandler(async (req, res) => {
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index f2f24ebba4..b5068cc241 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -22,13 +22,11 @@ import { ensureDir, PATHS, safeJSONParse } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
+import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
const IS_WIN = process.platform === 'win32';
-// Catalog comes from data/media-models.json (see server/lib/mediaModels.js).
-// `broken: 'macos' | 'windows'` in the registry hides a model per-platform
-// (e.g. Flux 2 Klein needs CUDA, so it's broken on macOS).
-import { getImageModels } from '../../lib/mediaModels.js';
+import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
export const IMAGE_MODELS = Object.fromEntries(getImageModels().map((m) => [m.id, m]));
@@ -66,7 +64,68 @@ export const cancel = () => {
return true;
};
-const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir, initImagePath, initImageStrength }) => {
+export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir, initImagePath, initImageStrength }) => {
+ const modelId = model?.id;
+ if (isFlux2(model)) {
+ if (!model.repo) {
+ throw new ServerError(
+ `FLUX.2 model "${modelId}" is missing the 'repo' field in data/media-models.json`,
+ { status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
+ );
+ }
+ const quantization = model.quantization || 'sdnq';
+ if (quantization !== 'sdnq' && quantization !== 'int8') {
+ throw new ServerError(
+ `FLUX.2 model "${modelId}" has unsupported quantization "${quantization}" (supported: sdnq, int8)`,
+ { status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
+ );
+ }
+ if (quantization === 'sdnq' && !model.tokenizerRepo) {
+ throw new ServerError(
+ `FLUX.2 SDNQ model "${modelId}" requires 'tokenizerRepo' (the gated base repo for the tokenizer)`,
+ { status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
+ );
+ }
+ if (quantization === 'int8' && !model.basePipelineRepo) {
+ throw new ServerError(
+ `FLUX.2 Int8 model "${modelId}" requires 'basePipelineRepo' (the gated base repo for VAE/scheduler)`,
+ { status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
+ );
+ }
+ const flux2Python = resolveFlux2Python();
+ if (!flux2Python) {
+ throw new ServerError(
+ `FLUX.2 venv not found. Run \`INSTALL_FLUX2=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected at ${FLUX2_VENV_DEFAULT}).`,
+ { status: 400, code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED' },
+ );
+ }
+ const scriptPath = join(PATHS.root, 'scripts', 'flux2_macos.py');
+ // No --metadata flag: local.js's proc.on('close') already writes the
+ // canonical sidecar at <jobId>.metadata.json after a successful exit.
+ // Letting the runner write its own would duplicate work and the JS
+ // sidecar would clobber any flux2-specific fields anyway.
+ const args = [
+ scriptPath,
+ '--model', modelId,
+ '--quantization', quantization,
+ '--repo', model.repo,
+ '--prompt', prompt,
+ '--height', String(height),
+ '--width', String(width),
+ '--steps', String(steps),
+ '--guidance', String(guidance ?? 0),
+ '--seed', String(seed),
+ '--output', outputPath,
+ ];
+ if (model.tokenizerRepo) args.push('--tokenizer-repo', model.tokenizerRepo);
+ if (model.basePipelineRepo) args.push('--base-pipeline-repo', model.basePipelineRepo);
+ 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);
+ return { bin: flux2Python, args };
+ }
+
if (IS_WIN) {
// imagine_win.py does not implement i2i — silently drop the init-image
// args here so the request still produces a normal txt2img result rather
@@ -82,7 +141,6 @@ const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height,
],
};
}
- // macOS: mflux-generate sits next to the python binary in the venv
const bin = join(dirname(pythonPath), 'mflux-generate');
const args = ['--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--steps', String(steps), '--seed', String(seed), '--quantize', String(quantize), '--output', outputPath, '--metadata'];
if (guidance > 0) args.push('--guidance', String(guidance));
@@ -99,14 +157,32 @@ const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height,
};
export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null }) {
- if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Enforce the single-activeProcess invariant the rest of this module relies
// on — without this, a double-click on Generate would orphan the first
// child (cancel() can only kill the one stored in activeProcess).
if (activeProcess) throw new ServerError('A generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });
- const model = IMAGE_MODELS[modelId];
- if (!model || model.broken) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
+ // Use the registry cache view (which applies the per-platform `broken`
+ // filter via getImageModels) rather than the module-load IMAGE_MODELS
+ // snapshot. Note: loadMediaModels memoizes on first read — on-disk edits
+ // to data/media-models.json still need a server restart to apply.
+ // Don't re-check model.broken here: getImageModels() already filtered
+ // current-platform entries; an extra truthiness check would also reject
+ // 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) {
+ 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' },
+ );
+ }
await ensureDir(PATHS.images);
await ensureDir(PATHS.loras);
@@ -159,7 +235,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// per inference step here; we watch and stream the latest as `currentImage`.
const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-stepwise-'));
- const { bin, args } = buildArgs({ pythonPath, modelId, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength });
+ const { bin, args } = buildArgs({ pythonPath, model, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir, initImagePath: validInitImagePath, initImageStrength: validInitImageStrength });
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);
imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
new file mode 100644
index 0000000000..c0c2b28f27
--- /dev/null
+++ b/server/services/imageGen/local.test.js
@@ -0,0 +1,197 @@
+import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+// FLUX.2 venv resolution mock — flip between "installed" and "missing" with
+// the .returnValue setter on each test.
+const mockResolveFlux2Python = vi.fn();
+vi.mock('../../lib/pythonSetup.js', () => ({
+ resolveFlux2Python: () => mockResolveFlux2Python(),
+ FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',
+}));
+
+// Point the registry at a temp dir so importing local.js (which calls
+// getImageModels() at module load and triggers seedIfMissing in
+// mediaModels.js) doesn't write to the repo's data/media-models.json.
+// Save + restore the prior env value and call vi.resetModules() so a
+// previously-cached mediaModels.js inside the same vitest worker doesn't
+// stick to the wrong file. Pattern matches server/lib/mediaModels.test.js.
+let tmpRegistryDir;
+let priorRegistryEnv;
+let buildArgs;
+
+beforeAll(async () => {
+ tmpRegistryDir = mkdtempSync(join(tmpdir(), 'portos-imagegen-local-test-'));
+ priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;
+ process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRegistryDir, 'media-models.json');
+ vi.resetModules();
+ ({ buildArgs } = await import('./local.js'));
+});
+
+afterAll(() => {
+ if (priorRegistryEnv === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;
+ else process.env.PORTOS_MEDIA_MODELS_FILE = priorRegistryEnv;
+ rmSync(tmpRegistryDir, { recursive: true, force: true });
+});
+
+describe('imageGen local.buildArgs flux2 dispatch', () => {
+ beforeEach(() => {
+ mockResolveFlux2Python.mockReset();
+ });
+
+ const baseInput = {
+ pythonPath: '/usr/bin/python3', // unused for flux2 but kept in shape
+ prompt: 'a red cube',
+ negativePrompt: '',
+ width: 512,
+ height: 512,
+ steps: 8,
+ guidance: 3.5,
+ seed: 42,
+ quantize: '8',
+ outputPath: '/tmp/out.png',
+ loraPaths: [],
+ loraScales: [],
+ stepwiseDir: '/tmp/stepwise',
+ initImagePath: null,
+ initImageStrength: null,
+ };
+
+ it('routes SDNQ flux2 models to the flux2 venv + flux2_macos.py', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { bin, args } = buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ expect(bin).toBe('/fake/venv-flux2/bin/python3');
+ // First arg is the script path
+ expect(args[0]).toMatch(/scripts[/\\]flux2_macos\.py$/);
+ // Required CLI fields land in the args list (order isn't important here,
+ // but we want presence + the exact repo/tokenizer values).
+ expect(args).toContain('--quantization');
+ expect(args[args.indexOf('--quantization') + 1]).toBe('sdnq');
+ expect(args).toContain('--repo');
+ expect(args[args.indexOf('--repo') + 1]).toBe('Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic');
+ expect(args).toContain('--tokenizer-repo');
+ expect(args[args.indexOf('--tokenizer-repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-4B');
+ expect(args).toContain('--prompt');
+ expect(args).toContain('a red cube');
+ expect(args).toContain('--seed');
+ expect(args[args.indexOf('--seed') + 1]).toBe('42');
+ // No --metadata flag: local.js writes the canonical sidecar itself.
+ expect(args).not.toContain('--metadata');
+ // Stepwise dir threads through so live preview frames land where local.js's watcher reads.
+ expect(args).toContain('--stepwise-image-output-dir');
+ expect(args[args.indexOf('--stepwise-image-output-dir') + 1]).toBe('/tmp/stepwise');
+ });
+
+ it('routes Int8 flux2 models with the base pipeline repo flag', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b-int8',
+ runner: 'flux2',
+ quantization: 'int8',
+ repo: 'aydin99/FLUX.2-klein-4B-int8',
+ basePipelineRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ expect(args[args.indexOf('--quantization') + 1]).toBe('int8');
+ expect(args[args.indexOf('--repo') + 1]).toBe('aydin99/FLUX.2-klein-4B-int8');
+ expect(args).toContain('--base-pipeline-repo');
+ expect(args[args.indexOf('--base-pipeline-repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-4B');
+ // SDNQ-only flag must NOT appear when the model didn't supply tokenizerRepo.
+ expect(args).not.toContain('--tokenizer-repo');
+ });
+
+ it('throws a setup hint when the flux2 venv is missing', () => {
+ mockResolveFlux2Python.mockReturnValue(null);
+ expect(() => buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ })).toThrow(/INSTALL_FLUX2=1/);
+ });
+
+ it('throws when an SDNQ flux2 model is missing tokenizerRepo', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ expect(() => buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ // tokenizerRepo missing — registry was edited badly
+ },
+ })).toThrow(/tokenizerRepo/);
+ });
+
+ it('throws when an Int8 flux2 model is missing basePipelineRepo', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ expect(() => buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b-int8',
+ runner: 'flux2',
+ quantization: 'int8',
+ repo: 'aydin99/FLUX.2-klein-4B-int8',
+ },
+ })).toThrow(/basePipelineRepo/);
+ });
+
+ it('throws when a flux2 model is missing repo entirely', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ expect(() => buildArgs({
+ ...baseInput,
+ model: { id: 'flux2-broken', runner: 'flux2', quantization: 'sdnq' },
+ })).toThrow(/missing the 'repo' field/);
+ });
+
+ it('passes init-image args for flux2 i2i', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ initImagePath: '/safe/path/init.png',
+ initImageStrength: 0.7,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ 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.7');
+ });
+
+ it('falls back to mflux dispatch for non-flux2 models on macOS', () => {
+ // No flux2 mock needed — the branch shouldn't be taken at all.
+ mockResolveFlux2Python.mockReturnValue(null);
+ const { bin, args } = buildArgs({
+ ...baseInput,
+ model: { id: 'dev', steps: 20, guidance: 3.5 },
+ });
+ // mflux-generate sits next to the python binary in the venv.
+ expect(bin).toMatch(/mflux-generate$/);
+ expect(args).toContain('--model');
+ expect(args[args.indexOf('--model') + 1]).toBe('dev');
+ expect(args).toContain('--quantize');
+ });
+});