Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(mlx): port MLX media in-process — standalone Mac app, no lu-bridge

purple4a4f552b14b3
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 83cbbfba..3799e0dd 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -151,7 +151,7 @@ dependencies = [
"futures-lite",
"parking",
"polling",
- "rustix",
+ "rustix 1.1.4",
"slab",
"windows-sys 0.61.2",
]
@@ -193,7 +193,7 @@ dependencies = [
"cfg-if",
"event-listener",
"futures-lite",
- "rustix",
+ "rustix 1.1.4",
]
[[package]]
@@ -219,7 +219,7 @@ dependencies = [
"cfg-if",
"futures-core",
"futures-io",
- "rustix",
+ "rustix 1.1.4",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
@@ -1869,6 +1869,15 @@ dependencies = [
"digest",
]
+[[package]]
+name = "home"
+version = "0.5.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "hostname"
version = "0.4.2"
@@ -2503,6 +2512,12 @@ dependencies = [
"redox_syscall 0.7.3",
]
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2568,6 +2583,7 @@ dependencies = [
"urlencoding",
"uuid",
"walkdir",
+ "which",
"whoami",
"windows-sys 0.59.0",
"winreg",
@@ -3529,7 +3545,7 @@ dependencies = [
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
- "rustix",
+ "rustix 1.1.4",
"windows-sys 0.61.2",
]
@@ -4074,6 +4090,19 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags 2.11.0",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -4083,7 +4112,7 @@ dependencies = [
"bitflags 2.11.0",
"errno",
"libc",
- "linux-raw-sys",
+ "linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
]
@@ -5259,7 +5288,7 @@ dependencies = [
"fastrand",
"getrandom 0.4.2",
"once_cell",
- "rustix",
+ "rustix 1.1.4",
"windows-sys 0.61.2",
]
@@ -6128,7 +6157,7 @@ checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d"
dependencies = [
"cc",
"downcast-rs",
- "rustix",
+ "rustix 1.1.4",
"scoped-tls",
"smallvec",
"wayland-sys",
@@ -6141,7 +6170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144"
dependencies = [
"bitflags 2.11.0",
- "rustix",
+ "rustix 1.1.4",
"wayland-backend",
"wayland-scanner",
]
@@ -6291,6 +6320,18 @@ dependencies = [
"windows-core 0.61.2",
]
+[[package]]
+name = "which"
+version = "6.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
+dependencies = [
+ "either",
+ "home",
+ "rustix 0.38.44",
+ "winsafe",
+]
+
[[package]]
name = "whoami"
version = "1.6.1"
@@ -6824,6 +6865,12 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "winsafe"
+version = "0.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
+
[[package]]
name = "wit-bindgen"
version = "0.51.0"
@@ -6990,7 +7037,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
- "rustix",
+ "rustix 1.1.4",
]
[[package]]
@@ -7047,7 +7094,7 @@ dependencies = [
"hex",
"libc",
"ordered-stream",
- "rustix",
+ "rustix 1.1.4",
"serde",
"serde_repr",
"tracing",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 591903b2..a25e381d 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -19,6 +19,9 @@ tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["stream", "blocking", "json", "multipart"] }
zip = "2"
dirs = "6"
+# Python interpreter discovery for the in-process MLX media engine
+# (os_paths::find_python, mlx.rs::locate_python_311).
+which = "6"
regex = "1"
glob = "0.3"
sysinfo = "0.33"
diff --git a/src-tauri/resources/mlx/requirements.txt b/src-tauri/resources/mlx/requirements.txt
new file mode 100644
index 00000000..2bca48f3
--- /dev/null
+++ b/src-tauri/resources/mlx/requirements.txt
@@ -0,0 +1,26 @@
+# MLX-Stable-Diffusion stack — what we pip-install into the dedicated
+# venv at ~/Library/Application Support/lu-labs/mlx/venv. PyTorch is
+# pinned to a version with stable MPS (Metal) support; older 2.x
+# releases had race conditions in MPS-flash-attention paths.
+#
+# Apple's diffusers + torch-mps story keeps shifting — re-check this
+# file when MLX-native SD pipelines become available; we'd swap
+# `torch` + `diffusers` for `mlx-stable-diffusion` at that point.
+
+# torch 2.4+ has stable MPS bfloat16 (Z-Image/Qwen-Image run in bf16);
+# diffusers 0.36+ ships ZImagePipeline + QwenImagePipeline.
+torch>=2.4.0
+diffusers>=0.36.0
+transformers>=4.51.0
+accelerate>=0.30.0
+safetensors>=0.4.0
+huggingface_hub>=0.26.0
+sentencepiece>=0.2.0
+
+# HTTP server hosting /generate. uvicorn is the production-quality
+# choice; fastapi gives us a typed request schema for free.
+fastapi>=0.110.0
+uvicorn[standard]>=0.29.0
+
+# Image post-processing + return-as-PNG path.
+pillow>=10.0.0
diff --git a/src-tauri/resources/mlx/server.py b/src-tauri/resources/mlx/server.py
new file mode 100644
index 00000000..3341f3a0
--- /dev/null
+++ b/src-tauri/resources/mlx/server.py
@@ -0,0 +1,201 @@
+"""MLX-Stable-Diffusion FastAPI sidecar.
+
+Run by `commands::mlx::mlx_start` once the install slot has filled the
+venv. Hosts a single POST /generate endpoint that the bridge proxies for
+the web UI.
+
+Model-agnostic: every request carries the full load config (repo, dtype,
+fp16 variant, cfg kwarg name) resolved by the bridge from its image
+catalog (commands/mlx.rs IMAGE_CATALOG). The sidecar keeps exactly one
+pipeline in memory and swaps it out when a request names a different
+repo — unified memory can't hold two big pipelines at once.
+"""
+
+import base64
+import gc
+import io
+import os
+import sys
+import threading
+import time
+from typing import Optional
+
+import uvicorn
+from fastapi import FastAPI, HTTPException
+from pydantic import BaseModel
+
+
+# Lazy: importing torch + diffusers takes ~3 s on a cold start. We defer
+# it until the first request so /health stays sub-millisecond, which the
+# bridge uses for the "is the MLX server up?" probe in mlx_status.
+_pipe = None
+_pipe_repo = None
+# One lock guards every pipeline mutation (load / release / generate) so the
+# idle-unload thread can't free the model out from under an in-flight request,
+# and two concurrent requests can't both trigger a load.
+_pipe_lock = threading.RLock()
+_last_activity = time.monotonic()
+
+# A resident image pipeline pins multiple GB of unified memory. On a local
+# machine that must not linger forever after the user walks away, so a
+# background thread releases it once idle. 0 disables (set via env for tests).
+IDLE_UNLOAD_SECONDS = int(os.environ.get("LU_MLX_IDLE_UNLOAD_SECONDS", "600"))
+
+
+def _release_pipe():
+ global _pipe, _pipe_repo
+ with _pipe_lock:
+ if _pipe is None:
+ return
+ import torch
+
+ _pipe = None
+ _pipe_repo = None
+ gc.collect()
+ if torch.backends.mps.is_available():
+ torch.mps.empty_cache()
+
+
+def _idle_unload_loop():
+ """Free the resident pipeline after IDLE_UNLOAD_SECONDS of no requests.
+ Keeps the server itself up (fast to reload), just drops the weights."""
+ while True:
+ time.sleep(30)
+ if IDLE_UNLOAD_SECONDS <= 0 or _pipe is None:
+ continue
+ if time.monotonic() - _last_activity >= IDLE_UNLOAD_SECONDS:
+ _release_pipe()
+
+
+def _ensure_pipe(repo: str, dtype: str, variant: Optional[str], disable_safety_checker: bool):
+ global _pipe, _pipe_repo
+ # Caller already holds _pipe_lock.
+ if _pipe is not None and _pipe_repo == repo:
+ return _pipe
+ _release_pipe()
+
+ import torch
+ from diffusers import AutoPipelineForText2Image
+
+ device = "mps" if torch.backends.mps.is_available() else "cpu"
+ torch_dtype = torch.float32
+ if device == "mps":
+ torch_dtype = torch.bfloat16 if dtype == "bfloat16" else torch.float16
+
+ kwargs = {"torch_dtype": torch_dtype}
+ if variant:
+ kwargs["variant"] = variant
+ if disable_safety_checker:
+ # SD1.5 repos bundle a safety_checker component; skipping it here
+ # also means the install never had to download its weights.
+ kwargs["safety_checker"] = None
+ kwargs["requires_safety_checker"] = False
+
+ # No attention/VAE slicing here: on torch 2.12 + MPS it corrupts the
+ # forward pass into all-NaN latents (verified live — plain runs are
+ # clean, sliced runs decode to black frames).
+ _pipe = AutoPipelineForText2Image.from_pretrained(repo, **kwargs).to(device)
+ _pipe_repo = repo
+ return _pipe
+
+
+app = FastAPI(title="LU MLX server")
+
+
+class GenerateRequest(BaseModel):
+ prompt: str
+ steps: int = 4
+ seed: Optional[int] = None
+ width: int = 512
+ height: int = 512
+ negative_prompt: Optional[str] = None
+ # Model config resolved by the bridge catalog. Defaults keep the
+ # historical sd-turbo behaviour for old callers.
+ model_repo: str = "stabilityai/sd-turbo"
+ dtype: str = "float16"
+ variant: Optional[str] = "fp16"
+ guidance: float = 0.0
+ cfg_param: str = "guidance_scale"
+ disable_safety_checker: bool = False
+
+
+def health():
+ idle = None if _pipe is None else round(time.monotonic() - _last_activity, 1)
+ return {
+ "ok": True,
+ "model_loaded": _pipe is not None,
+ "model_repo": _pipe_repo,
+ "idle_seconds": idle,
+ "idle_unload_seconds": IDLE_UNLOAD_SECONDS,
+ }
+
+
+def unload():
+ """Free the resident model now, keeping the server up. Idempotent — the
+ bridge's `mlx_unload` calls this so the UI can reclaim memory on demand."""
+ was_loaded = _pipe is not None
+ _release_pipe()
+ return {"ok": True, "was_loaded": was_loaded}
+
+
[email protected]("/generate")
+def generate(req: GenerateRequest):
+ global _last_activity
+ import torch
+
+ with _pipe_lock:
+ try:
+ pipe = _ensure_pipe(req.model_repo, req.dtype, req.variant, req.disable_safety_checker)
+ except Exception as exc:
+ # A half-loaded pipeline must not shadow the previous model.
+ _release_pipe()
+ raise HTTPException(status_code=500, detail=f"pipeline init: {exc}") from exc
+
+ # MPS generators are unstable; seeds work better via a CPU generator.
+ generator = None
+ if req.seed is not None:
+ generator = torch.Generator(device="cpu").manual_seed(req.seed)
+
+ gen_kwargs = {
+ "prompt": req.prompt,
+ "num_inference_steps": req.steps,
+ "width": req.width,
+ "height": req.height,
+ "generator": generator,
+ # Turbo/distilled models want 0.0 here; regular models their CFG.
+ # Qwen-Image reads "true_cfg_scale" instead of "guidance_scale".
+ req.cfg_param: req.guidance,
+ }
+ if req.negative_prompt:
+ gen_kwargs["negative_prompt"] = req.negative_prompt
+
+ try:
+ result = pipe(**gen_kwargs)
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=f"generate: {exc}") from exc
+ finally:
+ # Reset the idle clock AFTER the work, so a slow generation can't be
+ # unloaded mid-run and the countdown starts from completion.
+ _last_activity = time.monotonic()
+
+ img = result.images[0]
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return {
+ "image_base64": base64.b64encode(buf.getvalue()).decode("ascii"),
+ "width": req.width,
+ "height": req.height,
+ "steps": req.steps,
+ "model_repo": req.model_repo,
+ }
+
+
+if __name__ == "__main__":
+ port = int(os.environ.get("LU_MLX_PORT", "47712"))
+ threading.Thread(target=_idle_unload_loop, daemon=True).start()
+ try:
+ uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
+ except KeyboardInterrupt:
+ sys.exit(0)
diff --git a/src-tauri/src/commands/bridge.rs b/src-tauri/src/commands/bridge.rs
deleted file mode 100644
index b93eee90..00000000
--- a/src-tauri/src/commands/bridge.rs
+++ /dev/null
@@ -1,178 +0,0 @@
-// Phase 6 — lu-bridge media sidecar (macOS Apple-Silicon MLX local media).
-//
-// Hard rule (David): Mac local image/video is MLX-via-`lu-bridge` ONLY, never
-// ComfyUI. Rather than re-implement the MLX engine, we bundle the existing
-// `lu-bridge` binary (from uselu/apps/bridge) as a managed sidecar — the same
-// pattern the app already uses for `llama-server` (see `commands::engine`).
-//
-// The bridge binds 127.0.0.1:47711 and serves every `/cmd/:name` locally with
-// NO auth (loopback bind IS the security boundary — see bridge `main.rs`). We
-// spawn it headless (`LU_BRIDGE_NO_WINDOW=1`, so no second native window) and
-// fully offline (`LU_REQUIRE_AUTH=0`, no cloud JWKS). The MLX image/video
-// commands (`mlx_*`, `video_*`) are then reachable from the desktop frontend
-// over plain localhost HTTP. The child handle lives in `AppState.media_bridge`
-// and is reaped in `shutdown_subprocesses`.
-
-use std::path::PathBuf;
-use std::process::{Command, Stdio};
-use std::time::{Duration, Instant};
-
-use tauri::{AppHandle, Manager, State};
-
-use crate::state::AppState;
-
-#[cfg(target_os = "windows")]
-use std::os::windows::process::CommandExt;
-#[cfg(target_os = "windows")]
-const CREATE_NO_WINDOW: u32 = 0x08000000;
-
-/// Loopback port the bridge listens on. Matches the bridge default
-/// (`LU_BRIDGE_ADDR`) and the web client (`NEXT_PUBLIC_BRIDGE_URL`).
-pub const BRIDGE_PORT: u16 = 47711;
-
-/// How long to wait for `/health` after spawn. The bridge is a small Rust
-/// daemon (no model load), so it comes up in well under a second — but a cold
-/// first launch on a busy box can lag, hence a generous ceiling.
-const HEALTH_TIMEOUT: Duration = Duration::from_secs(15);
-
-/// Bundled sidecar file name Tauri produces from `externalBin: ["bin/lu-bridge"]`
-/// (target-triple suffix stripped inside the .app; `.exe` on Windows).
-fn sidecar_binary_name() -> &'static str {
- if cfg!(target_os = "windows") {
- "lu-bridge.exe"
- } else {
- "lu-bridge"
- }
-}
-
-/// Locate the bridge binary: bundled next to the app exe, in the resource dir,
-/// or the dev-time `src-tauri/bin/lu-bridge-<triple>` produced at build prep.
-/// Mirrors `engine::resolve_engine_binary`.
-fn resolve_bridge_binary(app: &AppHandle) -> Option<PathBuf> {
- if let Ok(exe) = std::env::current_exe() {
- if let Some(dir) = exe.parent() {
- let candidate = dir.join(sidecar_binary_name());
- if candidate.exists() {
- return Some(candidate);
- }
- }
- }
- if let Ok(res) = app.path().resource_dir() {
- let candidate = res.join(sidecar_binary_name());
- if candidate.exists() {
- return Some(candidate);
- }
- }
- let triple = crate::commands::engine::host_target_triple();
- let suffix = if cfg!(target_os = "windows") { ".exe" } else { "" };
- let dev_name = format!("lu-bridge-{triple}{suffix}");
- let mut dev_candidates: Vec<PathBuf> = Vec::new();
- if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
- dev_candidates.push(PathBuf::from(&manifest).join("bin").join(&dev_name));
- }
- if let Ok(cwd) = std::env::current_dir() {
- dev_candidates.push(cwd.join("src-tauri").join("bin").join(&dev_name));
- dev_candidates.push(cwd.join("bin").join(&dev_name));
- }
- dev_candidates.into_iter().find(|p| p.exists())
-}
-
-fn bridge_healthy(port: u16) -> bool {
- reqwest::blocking::Client::builder()
- .timeout(Duration::from_millis(800))
- .build()
- .ok()
- .and_then(|c| c.get(format!("http://127.0.0.1:{port}/health")).send().ok())
- .map(|r| r.status().is_success())
- .unwrap_or(false)
-}
-
-fn wait_for_bridge_health(port: u16) -> Result<(), String> {
- let start = Instant::now();
- while start.elapsed() < HEALTH_TIMEOUT {
- if bridge_healthy(port) {
- return Ok(());
- }
- std::thread::sleep(Duration::from_millis(150));
- }
- Err(format!(
- "lu-bridge did not become healthy on port {port} within {}s",
- HEALTH_TIMEOUT.as_secs()
- ))
-}
-
-/// Start the bundled `lu-bridge` sidecar headless on 127.0.0.1:47711. Idempotent:
-/// if it's already healthy (ours or a user-run bridge), returns `already_running`.
-#[tauri::command]
-pub fn start_media_bridge(
- app: AppHandle,
- state: State<'_, AppState>,
-) -> Result<serde_json::Value, String> {
- // Already serving (our child or an externally-run bridge) → no-op.
- if bridge_healthy(BRIDGE_PORT) {
- return Ok(serde_json::json!({ "status": "already_running", "port": BRIDGE_PORT }));
- }
-
- // A dead handle lingering from a previous crash → reap before respawn.
- stop_bridge_locked(&state);
-
- let binary = resolve_bridge_binary(&app).ok_or_else(|| {
- format!(
- "lu-bridge binary not found ({}). The MLX media sidecar is bundled on Apple Silicon only.",
- sidecar_binary_name()
- )
- })?;
-
- println!("[Bridge] Starting lu-bridge media sidecar on port {BRIDGE_PORT}");
- let mut cmd = Command::new(&binary);
- cmd.env("LU_BRIDGE_NO_WINDOW", "1") // headless — the desktop app owns the window
- .env("LU_REQUIRE_AUTH", "0") // fully local, no cloud JWKS
- .env("LU_BRIDGE_ADDR", format!("127.0.0.1:{BRIDGE_PORT}"))
- .stdin(Stdio::null())
- .stdout(Stdio::null())
- .stderr(Stdio::null());
- #[cfg(target_os = "windows")]
- cmd.creation_flags(CREATE_NO_WINDOW);
-
- let child = cmd
- .spawn()
- .map_err(|e| format!("Failed to spawn lu-bridge: {e}"))?;
-
- *state.media_bridge.lock().unwrap() = Some(child);
-
- if let Err(e) = wait_for_bridge_health(BRIDGE_PORT) {
- stop_bridge_locked(&state);
- return Err(e);
- }
-
- println!("[Bridge] lu-bridge healthy on port {BRIDGE_PORT}");
- Ok(serde_json::json!({ "status": "started", "port": BRIDGE_PORT }))
-}
-
-/// Stop the managed bridge, killing the child. Idempotent.
-#[tauri::command]
-pub fn stop_media_bridge(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
- let killed = stop_bridge_locked(&state);
- Ok(serde_json::json!({ "status": if killed { "stopped" } else { "not_running" } }))
-}
-
-/// `running` reflects our child handle; `healthy` the HTTP probe (true even for
-/// a user-run bridge we didn't spawn).
-#[tauri::command]
-pub fn media_bridge_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
- let running = state.media_bridge.lock().unwrap().is_some();
- Ok(serde_json::json!({
- "running": running,
- "healthy": bridge_healthy(BRIDGE_PORT),
- "port": BRIDGE_PORT,
- }))
-}
-
-fn stop_bridge_locked(state: &State<'_, AppState>) -> bool {
- let mut guard = state.media_bridge.lock().unwrap();
- if let Some(mut child) = guard.take() {
- let _ = child.kill();
- return true;
- }
- false
-}
diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rs
new file mode 100644
index 00000000..ca716309
--- /dev/null
+++ b/src-tauri/src/commands/media_cmds.rs
@@ -0,0 +1,124 @@
+//! Tauri command wrappers for the in-process MLX media engine (image + video).
+//!
+//! Thin pass-through to `commands::mlx` / `commands::video`, which were
+//! ported verbatim from `uselu/apps/bridge` (an axum HTTP daemon) and take a
+//! single `args: serde_json::Value` blob per call instead of individually
+//! named parameters. That matches the existing `shell_task_*` convention in
+//! this codebase (see `bg_tasks.rs`'s "Tauri-callable wrappers" section) —
+//! every wrapper below takes exactly one `args: Value` parameter, and the
+//! frontend MUST invoke with the payload nested as `{ args: {...} }` (see
+//! `src/api/agents/bg-tasks.ts` for the precedent and its "missing required
+//! key args" warning). `src/api/mlx-image.ts` / `src/api/mlx-video.ts` do
+//! this via a small `invokeMedia` helper.
+//!
+//! No separate lu-bridge daemon: the app spawns its own MLX Python sidecar
+//! (server.py on 127.0.0.1:47712) directly from `commands::mlx`, exactly
+//! like the existing ComfyUI/whisper sidecars.
+
+use crate::state::AppState;
+use serde_json::Value;
+use tauri::State;
+
+// ── MLX image (MLX-Stable-Diffusion) ────────────────────────────────────
+
+#[tauri::command]
+pub async fn mlx_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_status(state.inner(), &args).await
+}
+
+#[tauri::command]
+pub fn mlx_start(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_start(state.inner(), &args)
+}
+
+#[tauri::command]
+pub async fn mlx_unload(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_unload(state.inner(), &args).await
+}
+
+#[tauri::command]
+pub async fn mlx_generate(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_generate(state.inner(), &args).await
+}
+
+#[tauri::command]
+pub fn mlx_image_models(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_image_models(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn mlx_image_install_model(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_image_install_model(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn mlx_image_install_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_image_install_status(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn mlx_image_delete_model(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::mlx_image_delete_model(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn install_mlx_diffusion(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::install_mlx_diffusion(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn install_mlx_diffusion_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::mlx::install_mlx_diffusion_status(state.inner(), &args)
+}
+
+// ── MLX video ────────────────────────────────────────────────────────────
+
+#[tauri::command]
+pub fn video_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_status(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_list_models(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_list_models(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_install_mlx(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_install_mlx(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_install_mlx_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_install_mlx_status(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_install_model(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_install_model(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_install_model_status(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_install_model_status(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_delete_model(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_delete_model(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_generate(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_generate(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_progress(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_progress(state.inner(), &args)
+}
+
+#[tauri::command]
+pub fn video_cancel(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
+ crate::commands::video::video_cancel(state.inner(), &args)
+}
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
new file mode 100644
index 00000000..aba8f18c
--- /dev/null
+++ b/src-tauri/src/commands/mlx.rs
@@ -0,0 +1,817 @@
+//! MLX-Stable-Diffusion image provider for macOS (Apple Silicon
+//! recommended image stack).
+//!
+//! Layout under `~/Library/Application Support/lu-labs/mlx/`:
+//! venv/ — dedicated Python venv we own
+//! server.py — FastAPI sidecar (embedded via include_str!)
+//! requirements.txt — pip dependencies (embedded via include_str!)
+//! cache/ — HF_HOME for model weights
+//!
+//! Install flow (`install_mlx_diffusion`):
+//! 1. Locate Python ≥ 3.11. Fail with a brew hint if missing.
+//! 2. Create the venv if absent.
+//! 3. Drop server.py + requirements.txt into mlx root.
+//! 4. pip install -r requirements.txt.
+//! 5. Pre-pull stabilityai/sd-turbo so the first generate isn't a
+//! surprise 1.4 GB download.
+//!
+//! Run flow (`mlx_start`): spawn `venv/bin/python server.py` with
+//! LU_MLX_PORT and HF_HOME env vars. server.py owns the actual model
+//! lifecycle and stays up until the user picks "Quit" from the tray.
+//!
+//! Generate (`mlx_generate`): proxy a JSON request to 127.0.0.1:47712,
+//! return the base64 PNG to the web UI.
+
+use crate::commands::CmdResult;
+use crate::state::AppState;
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::process::Command;
+
+const MLX_PORT: u16 = 47712;
+
+fn mlx_root() -> PathBuf {
+ crate::os_paths::data_dir().join("mlx")
+}
+
+fn venv_python() -> PathBuf {
+ mlx_root().join("venv/bin/python")
+}
+
+fn venv_pip() -> PathBuf {
+ mlx_root().join("venv/bin/pip")
+}
+
+fn sidecar_running() -> bool {
+ std::net::TcpStream::connect_timeout(
+ &format!("127.0.0.1:{MLX_PORT}").parse().unwrap(),
+ std::time::Duration::from_millis(200),
+ )
+ .is_ok()
+}
+
+pub async fn mlx_status(_state: &AppState, _args: &Value) -> CmdResult {
+ let installed = venv_python().exists();
+ let running = sidecar_running();
+ // When the sidecar is up, surface what it's holding so the UI can show a
+ // "free memory" control while a model is resident.
+ let (model_loaded, model_repo, idle_seconds) = if running {
+ probe_health().await
+ } else {
+ (false, Value::Null, Value::Null)
+ };
+ Ok(json!({
+ "installed": installed,
+ "running": running,
+ "port": MLX_PORT,
+ "venv": venv_python().to_string_lossy(),
+ "modelLoaded": model_loaded,
+ "modelRepo": model_repo,
+ "idleSeconds": idle_seconds,
+ }))
+}
+
+/// GET /health on the sidecar → (model_loaded, model_repo, idle_seconds).
+/// Best-effort: any failure reads as "nothing loaded" so mlx_status never hangs.
+async fn probe_health() -> (bool, Value, Value) {
+ let none = (false, Value::Null, Value::Null);
+ let Ok(client) = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_millis(500))
+ .build()
+ else {
+ return none;
+ };
+ match client.get(format!("http://127.0.0.1:{MLX_PORT}/health")).send().await {
+ Ok(resp) => match resp.json::<Value>().await {
+ Ok(v) => (
+ v.get("model_loaded").and_then(|b| b.as_bool()).unwrap_or(false),
+ v.get("model_repo").cloned().unwrap_or(Value::Null),
+ v.get("idle_seconds").cloned().unwrap_or(Value::Null),
+ ),
+ Err(_) => none,
+ },
+ Err(_) => none,
+ }
+}
+
+/// Free the resident image model but keep the sidecar running (fast reload on
+/// the next generate). The web calls this to reclaim unified memory on demand;
+/// the sidecar also auto-unloads after an idle timeout on its own.
+pub async fn mlx_unload(_state: &AppState, _args: &Value) -> CmdResult {
+ if !sidecar_running() {
+ return Ok(json!({ "ok": true, "was_loaded": false, "running": false }));
+ }
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .map_err(|e| crate::commands::internal(e.to_string()))?;
+ match client.post(format!("http://127.0.0.1:{MLX_PORT}/unload")).send().await {
+ Ok(resp) => {
+ let v: Value = resp.json().await.unwrap_or_else(|_| json!({ "ok": true }));
+ Ok(json!({
+ "ok": true,
+ "was_loaded": v.get("was_loaded").and_then(|b| b.as_bool()).unwrap_or(false),
+ "running": true,
+ }))
+ }
+ Err(e) => Err(crate::commands::internal(format!("mlx unload: {e}"))),
+ }
+}
+
+pub fn install_mlx_diffusion(state: &AppState, _args: &Value) -> CmdResult {
+ if std::env::consts::OS != "macos" {
+ return Err(crate::commands::bad_request(
+ "MLX-Stable-Diffusion is macOS-only in v1",
+ ));
+ }
+ let slot = state.install_mlx_diffusion();
+ if slot.is_running() {
+ return Ok(json!({"ok": true, "status": "installing"}));
+ }
+ slot.start();
+ slot.log("preparing MLX-Stable-Diffusion install");
+
+ // AppState isn't Clone (it owns non-cloneable subprocess handles) — move
+ // just the InstallSlot into the thread instead of the whole state. Slot
+ // is already an Arc-backed handle from `state.install_mlx_diffusion()`
+ // above, so cloning it again is cheap and shares the same progress state.
+ let slot_thread = slot.clone();
+ std::thread::spawn(move || {
+ match install_mlx_steps(&slot_thread) {
+ Ok(()) => slot_thread.complete("MLX-Stable-Diffusion ready".to_string()),
+ Err(e) => slot_thread.fail(e),
+ }
+ });
+
+ Ok(json!({"ok": true, "status": "installing"}))
+}
+
+pub fn install_mlx_diffusion_status(state: &AppState, _args: &Value) -> CmdResult {
+ Ok(serde_json::to_value(state.install_mlx_diffusion().snapshot()).unwrap())
+}
+
+fn install_mlx_steps(slot: &crate::install_state::InstallSlot) -> Result<(), String> {
+ let python = locate_python_311().ok_or_else(|| {
+ "Python ≥ 3.11 not found. Install via `brew install [email protected]` and retry."
+ .to_string()
+ })?;
+ slot.log(format!("Python: {}", python.display()));
+
+ let venv_dir = mlx_root().join("venv");
+ if !venv_dir.exists() {
+ slot.log(format!("creating venv at {}", venv_dir.display()));
+ std::fs::create_dir_all(mlx_root()).map_err(|e| e.to_string())?;
+ let out = Command::new(&python)
+ .args(["-m", "venv", venv_dir.to_str().unwrap()])
+ .output()
+ .map_err(|e| format!("venv create failed to spawn: {e}"))?;
+ if !out.status.success() {
+ return Err(format!(
+ "venv create failed: {}",
+ String::from_utf8_lossy(&out.stderr)
+ ));
+ }
+ }
+
+ let req_path = mlx_root().join("requirements.txt");
+ let server_path = mlx_root().join("server.py");
+ std::fs::write(&req_path, REQUIREMENTS_TXT)
+ .map_err(|e| format!("write requirements.txt: {e}"))?;
+ std::fs::write(&server_path, SERVER_PY).map_err(|e| format!("write server.py: {e}"))?;
+
+ slot.log("running pip install (this pulls torch + diffusers, ~3 GB)");
+ let out = Command::new(venv_pip())
+ .args(["install", "--upgrade", "-r", req_path.to_str().unwrap()])
+ .output()
+ .map_err(|e| format!("pip install spawn: {e}"))?;
+ if !out.status.success() {
+ return Err(format!(
+ "pip install failed: {}",
+ truncate(&String::from_utf8_lossy(&out.stderr), 800)
+ ));
+ }
+ slot.log("pip install complete");
+
+ // Same pattern set as the catalog entry, so the fp32 duplicates (10+ GB)
+ // stay on HuggingFace and image_model_is_installed() flips true.
+ let starter = &IMAGE_CATALOG[0];
+ slot.log(format!(
+ "pre-pulling {} (~{} GB)",
+ starter.repo, starter.size_gb
+ ));
+ let patterns = starter
+ .allow
+ .iter()
+ .map(|p| format!("{p:?}"))
+ .collect::<Vec<_>>()
+ .join(",");
+ let prefetch = format!(
+ "from huggingface_hub import snapshot_download; snapshot_download({r:?}, allow_patterns=[{p}])",
+ r = starter.repo,
+ p = patterns,
+ );
+ let prefetch = prefetch.as_str();
+ let out = Command::new(venv_python())
+ .args(["-c", prefetch])
+ .env("HF_HOME", mlx_root().join("cache"))
+ .output()
+ .map_err(|e| format!("model prefetch spawn: {e}"))?;
+ if !out.status.success() {
+ return Err(format!(
+ "model prefetch failed: {}",
+ truncate(&String::from_utf8_lossy(&out.stderr), 800)
+ ));
+ }
+ slot.log("model pre-pull complete");
+
+ Ok(())
+}
+
+fn locate_python_311() -> Option<PathBuf> {
+ for candidate in ["python3.12", "python3.11", "python3"] {
+ let Ok(p) = which::which(candidate) else {
+ continue;
+ };
+ if let Some(version) = python_version(&p) {
+ if version_at_least(&version, 3, 11) {
+ return Some(p);
+ }
+ }
+ }
+ None
+}
+
+fn python_version(python: &PathBuf) -> Option<String> {
+ let out = Command::new(python).arg("--version").output().ok()?;
+ let v = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ let v = if v.is_empty() {
+ String::from_utf8_lossy(&out.stderr).trim().to_string()
+ } else {
+ v
+ };
+ Some(v.trim_start_matches("Python ").to_string())
+}
+
+fn version_at_least(version: &str, major: u32, minor: u32) -> bool {
+ let parts: Vec<&str> = version.split('.').take(2).collect();
+ if parts.len() < 2 {
+ return false;
+ }
+ let (Ok(maj), Ok(min)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>()) else {
+ return false;
+ };
+ maj > major || (maj == major && min >= minor)
+}
+
+fn truncate(s: &str, max: usize) -> String {
+ if s.len() <= max {
+ s.to_string()
+ } else {
+ format!("{}…", &s[..max])
+ }
+}
+
+// ── Image model catalog ───────────────────────────────────────────────
+//
+// Every entry is a diffusers-layout HuggingFace repo verified to exist,
+// ungated, and loadable via `AutoPipelineForText2Image.from_pretrained`
+// (fp16-variant repos additionally verified to carry per-subfolder fp16
+// weights — a root-level `*_fp16.safetensors` alone does NOT load). The
+// sidecar downloads into `HF_HOME = <mlx_root>/cache`, so install and
+// runtime share one cache and "installed" == snapshot dir present.
+
+#[derive(serde::Serialize, Clone)]
+pub struct ImageCatalogEntry {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub repo: &'static str,
+ /// Approximate size of the files the install actually pulls (see
+ /// `allow` — not the full repo, which often carries fp32 + onnx dupes).
+ pub size_gb: f32,
+ pub min_ram_gb: u32,
+ pub steps: u32,
+ pub guidance: f32,
+ /// Pipeline kwarg carrying the guidance value ("guidance_scale" for
+ /// SD/SDXL/Z-Image, "true_cfg_scale" for Qwen-Image).
+ pub cfg_param: &'static str,
+ pub dtype: &'static str, // "float16" | "bfloat16"
+ /// Load with `variant="fp16"` (repo ships .fp16.safetensors subfiles).
+ pub fp16_variant: bool,
+ /// SD1.5 repos bundle a safety_checker component; we skip it at load.
+ pub disable_safety_checker: bool,
+ pub default_size: u32,
+ pub unfiltered: bool,
+ pub description: &'static str,
+ /// `snapshot_download` allow_patterns — hf_hub fnmatch, `*` crosses `/`.
+ #[serde(skip)]
+ allow: &'static [&'static str],
+}
+
+macro_rules! allow {
+ ($($p:expr),*) => { &["*.json", "*.txt", $($p),*] };
+}
+
+pub const IMAGE_CATALOG: &[ImageCatalogEntry] = &[
+ ImageCatalogEntry {
+ id: "sd-turbo",
+ name: "SD Turbo",
+ repo: "stabilityai/sd-turbo",
+ size_gb: 2.6,
+ min_ram_gb: 8,
+ steps: 4,
+ guidance: 0.0,
+ cfg_param: "guidance_scale",
+ dtype: "float16",
+ fp16_variant: true,
+ disable_safety_checker: false,
+ default_size: 512,
+ unfiltered: false,
+ description: "Instant 512px drafts in 1–4 steps. Runs on every Apple Silicon Mac — the starter pick.",
+ allow: allow!["tokenizer/*", "text_encoder/*fp16*", "unet/*fp16*", "vae/*fp16*"],
+ },
+ ImageCatalogEntry {
+ id: "realistic-vision-v51",
+ name: "Realistic Vision V5.1",
+ repo: "SG161222/Realistic_Vision_V5.1_noVAE",
+ size_gb: 4.4,
+ min_ram_gb: 8,
+ steps: 28,
+ guidance: 5.0,
+ cfg_param: "guidance_scale",
+ dtype: "float16",
+ fp16_variant: false,
+ disable_safety_checker: true,
+ default_size: 512,
+ unfiltered: true,
+ description: "The classic photoreal SD1.5 — people, skin, portraits. Unfiltered, runs on 8 GB Macs.",
+ allow: allow![
+ "tokenizer/*",
+ "text_encoder/model.safetensors",
+ "unet/diffusion_pytorch_model.safetensors",
+ "vae/diffusion_pytorch_model.safetensors"
+ ],
+ },
+ ImageCatalogEntry {
+ id: "dreamshaper-xl-turbo",
+ name: "DreamShaper XL v2 Turbo",
+ repo: "Lykon/dreamshaper-xl-v2-turbo",
+ size_gb: 6.9,
+ min_ram_gb: 16,
+ steps: 8,
+ guidance: 2.0,
+ cfg_param: "guidance_scale",
+ dtype: "float16",
+ fp16_variant: true,
+ disable_safety_checker: false,
+ default_size: 1024,
+ unfiltered: false,
+ description: "SDXL turbo allrounder — art, fantasy, photo, 1024px in ~8 steps. Best quality/speed on 16 GB.",
+ allow: allow![
+ "tokenizer/*", "tokenizer_2/*",
+ "text_encoder/*fp16*", "text_encoder_2/*fp16*",
+ "unet/*fp16*", "vae/*fp16*"
+ ],
+ },
+ ImageCatalogEntry {
+ id: "realvisxl-v5",
+ name: "RealVisXL V5.0",
+ repo: "SG161222/RealVisXL_V5.0",
+ size_gb: 7.0,
+ min_ram_gb: 16,
+ steps: 25,
+ guidance: 5.0,
+ cfg_param: "guidance_scale",
+ dtype: "float16",
+ fp16_variant: true,
+ disable_safety_checker: false,
+ default_size: 1024,
+ unfiltered: true,
+ description: "Top photoreal SDXL — the RealVis series is the realism benchmark. Unfiltered.",
+ allow: allow![
+ "tokenizer/*", "tokenizer_2/*",
+ "text_encoder/*fp16*", "text_encoder_2/*fp16*",
+ "unet/*fp16*", "vae/*fp16*"
+ ],
+ },
+ ImageCatalogEntry {
+ id: "nsfw-gen-v2",
+ name: "NSFW-gen v2",
+ repo: "UnfilteredAI/NSFW-gen-v2",
+ size_gb: 5.3,
+ min_ram_gb: 16,
+ steps: 30,
+ guidance: 7.0,
+ cfg_param: "guidance_scale",
+ dtype: "float16",
+ fp16_variant: true,
+ disable_safety_checker: false,
+ default_size: 1024,
+ unfiltered: true,
+ description: "Explicitly unfiltered SDXL by UnfilteredAI — no content restrictions, adult themes included.",
+ allow: allow![
+ "tokenizer/*", "tokenizer_2/*",
+ "text_encoder/*fp16*", "text_encoder_2/*fp16*",
+ "unet/*fp16*", "vae/*fp16*"
+ ],
+ },
+ ImageCatalogEntry {
+ id: "z-image-turbo",
+ name: "Z-Image Turbo",
+ repo: "Tongyi-MAI/Z-Image-Turbo",
+ size_gb: 25.0,
+ min_ram_gb: 32,
+ steps: 9,
+ guidance: 0.0,
+ cfg_param: "guidance_scale",
+ dtype: "bfloat16",
+ fp16_variant: false,
+ disable_safety_checker: false,
+ default_size: 1024,
+ unfiltered: false,
+ description: "Alibaba's 6B flagship turbo — photoreal + text rendering at 1024px in 9 steps. Needs 32 GB.",
+ allow: allow![
+ "tokenizer/*",
+ "transformer/*.safetensors",
+ "text_encoder/*.safetensors",
+ "vae/*.safetensors"
+ ],
+ },
+ ImageCatalogEntry {
+ id: "qwen-image",
+ name: "Qwen-Image",
+ repo: "Qwen/Qwen-Image",
+ size_gb: 55.0,
+ min_ram_gb: 64,
+ steps: 40,
+ guidance: 4.0,
+ cfg_param: "true_cfg_scale",
+ dtype: "bfloat16",
+ fp16_variant: false,
+ disable_safety_checker: false,
+ default_size: 1024,
+ unfiltered: false,
+ description: "20B MMDiT — the strongest open image model for complex prompts and in-image text. 64 GB Macs.",
+ allow: allow![
+ "tokenizer/*",
+ "transformer/*.safetensors",
+ "text_encoder/*.safetensors",
+ "vae/*.safetensors"
+ ],
+ },
+];
+
+fn image_catalog_lookup(id: &str) -> Option<&'static ImageCatalogEntry> {
+ IMAGE_CATALOG.iter().find(|c| c.id == id)
+}
+
+/// HF hub cache dir for a repo inside our HF_HOME
+/// (`cache/hub/models--org--name`).
+fn image_model_cache_dir(repo: &str) -> PathBuf {
+ mlx_root()
+ .join("cache")
+ .join("hub")
+ .join(format!("models--{}", repo.replace('/', "--")))
+}
+
+fn image_model_is_installed(entry: &ImageCatalogEntry) -> bool {
+ let snaps = image_model_cache_dir(entry.repo).join("snapshots");
+ let Ok(read) = std::fs::read_dir(&snaps) else {
+ return false;
+ };
+ // At least one snapshot dir with a model_index.json — a bare refs/blobs
+ // skeleton from an aborted download must not count as installed.
+ read.flatten()
+ .any(|e| e.path().join("model_index.json").exists())
+}
+
+pub fn mlx_image_models(_state: &AppState, _args: &Value) -> CmdResult {
+ let out: Vec<Value> = IMAGE_CATALOG
+ .iter()
+ .map(|c| {
+ json!({
+ "id": c.id,
+ "name": c.name,
+ "repo": c.repo,
+ "sizeGB": c.size_gb,
+ "minRamGB": c.min_ram_gb,
+ "steps": c.steps,
+ "guidance": c.guidance,
+ "defaultSize": c.default_size,
+ "unfiltered": c.unfiltered,
+ "description": c.description,
+ "installed": image_model_is_installed(c),
+ })
+ })
+ .collect();
+ Ok(Value::Array(out))
+}
+
+pub fn mlx_image_install_model(state: &AppState, args: &Value) -> CmdResult {
+ if std::env::consts::OS != "macos" {
+ return Err(crate::commands::bad_request(
+ "MLX image models are macOS-only",
+ ));
+ }
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| crate::commands::bad_request("missing id"))?;
+ let entry = image_catalog_lookup(id)
+ .ok_or_else(|| crate::commands::bad_request(format!("unknown image model id: {id}")))?;
+ if !venv_python().exists() {
+ return Err(crate::commands::bad_request(
+ "MLX image engine not installed — run install_mlx_diffusion first",
+ ));
+ }
+ // The venv binary appears seconds into the engine install, long before
+ // pip has filled it — a model install started in that window dies with
+ // a cryptic ModuleNotFoundError.
+ if state.install_mlx_diffusion().is_running() {
+ return Err(crate::commands::bad_request(
+ "the MLX image engine is still installing — wait for it to finish first",
+ ));
+ }
+ let slot = state.install_mlx_image_model();
+ if slot.is_running() {
+ return Ok(json!({ "ok": true, "status": "installing" }));
+ }
+ if image_model_is_installed(entry) {
+ slot.complete(format!("{} already installed", entry.id));
+ return Ok(json!({ "ok": true, "status": "complete", "id": entry.id }));
+ }
+ slot.start();
+ slot.log(format!("pulling {} ({} GB)", entry.repo, entry.size_gb));
+ let slot2 = slot.clone();
+ let entry2 = entry.clone();
+ std::thread::spawn(move || {
+ let python = venv_python().to_string_lossy().to_string();
+ if let Err(e) = crate::commands::video::ensure_python_module(
+ &slot2,
+ &python,
+ "huggingface_hub",
+ "huggingface_hub",
+ ) {
+ slot2.fail(e);
+ return;
+ }
+ let patterns = entry2
+ .allow
+ .iter()
+ .map(|p| format!("{p:?}"))
+ .collect::<Vec<_>>()
+ .join(",");
+ let script = format!(
+ "from huggingface_hub import snapshot_download; snapshot_download(repo_id={r:?}, allow_patterns=[{p}])",
+ r = entry2.repo,
+ p = patterns,
+ );
+ let mut cmd = Command::new(&python);
+ cmd.args(["-c", &script])
+ .env("HF_HOME", mlx_root().join("cache"));
+ if let Err(e) = crate::commands::video::run_streamed(&slot2, &mut cmd) {
+ slot2.fail(e);
+ } else if !image_model_is_installed(&entry2) {
+ slot2.fail("download finished but the model snapshot is incomplete");
+ } else {
+ slot2.complete(format!("{} installed", entry2.id));
+ }
+ });
+ Ok(json!({ "ok": true, "status": "installing", "id": entry.id }))
+}
+
+pub fn mlx_image_install_status(state: &AppState, _args: &Value) -> CmdResult {
+ Ok(serde_json::to_value(state.install_mlx_image_model().snapshot()).unwrap())
+}
+
+pub fn mlx_image_delete_model(state: &AppState, args: &Value) -> CmdResult {
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| crate::commands::bad_request("missing id"))?;
+ let entry = image_catalog_lookup(id)
+ .ok_or_else(|| crate::commands::bad_request(format!("unknown image model id: {id}")))?;
+ if state.install_mlx_image_model().is_running() {
+ return Err(crate::commands::bad_request(
+ "a model install is running — wait for it to finish first",
+ ));
+ }
+ let dir = image_model_cache_dir(entry.repo);
+ if !dir.is_dir() {
+ return Err(crate::commands::not_found(format!("{id} is not installed")));
+ }
+ std::fs::remove_dir_all(&dir)
+ .map_err(|e| crate::commands::internal(format!("delete {id}: {e}")))?;
+ Ok(json!({ "ok": true, "id": id }))
+}
+
+#[derive(Deserialize)]
+struct GenerateArgs {
+ prompt: String,
+ #[serde(default)]
+ model: Option<String>,
+ #[serde(default)]
+ steps: Option<u32>,
+ #[serde(default)]
+ seed: Option<u64>,
+ #[serde(default)]
+ width: Option<u32>,
+ #[serde(default)]
+ height: Option<u32>,
+ #[serde(default)]
+ negative_prompt: Option<String>,
+}
+
+pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {
+ let req: GenerateArgs = serde_json::from_value(args.clone())
+ .map_err(|e| crate::commands::bad_request(e.to_string()))?;
+
+ // Resolve the catalog entry — the sidecar is model-agnostic and gets the
+ // full load config per request; unknown/absent id falls back to sd-turbo.
+ let entry = req
+ .model
+ .as_deref()
+ .and_then(image_catalog_lookup)
+ .unwrap_or(&IMAGE_CATALOG[0]);
+
+ let client = reqwest::Client::builder()
+ // Big pipelines (Z-Image, Qwen-Image) take minutes to page in from
+ // disk on first use — the old 120 s timeout aborted mid-load.
+ .timeout(std::time::Duration::from_secs(900))
+ .build()
+ .map_err(|e| crate::commands::internal(e.to_string()))?;
+
+ let body = json!({
+ "prompt": req.prompt,
+ "negative_prompt": req.negative_prompt,
+ "steps": req.steps.unwrap_or(entry.steps),
+ "seed": req.seed,
+ "width": req.width.unwrap_or(entry.default_size),
+ "height": req.height.unwrap_or(entry.default_size),
+ "model_repo": entry.repo,
+ "dtype": entry.dtype,
+ "variant": if entry.fp16_variant { Some("fp16") } else { None::<&str> },
+ "guidance": entry.guidance,
+ "cfg_param": entry.cfg_param,
+ "disable_safety_checker": entry.disable_safety_checker,
+ });
+ let res = client
+ .post(format!("http://127.0.0.1:{MLX_PORT}/generate"))
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| crate::commands::internal(format!("mlx unreachable: {e}")))?;
+ if !res.status().is_success() {
+ let s = res.status();
+ let text = res.text().await.unwrap_or_default();
+ return Err(crate::commands::internal(format!("HTTP {s}: {text}")));
+ }
+ let payload: Value = res
+ .json()
+ .await
+ .map_err(|e| crate::commands::internal(e.to_string()))?;
+ Ok(payload)
+}
+
+pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {
+ if !venv_python().exists() {
+ return Err(crate::commands::bad_request(
+ "MLX not installed yet — run install_mlx_diffusion first",
+ ));
+ }
+ let server = mlx_root().join("server.py");
+ // Refresh the deployed sidecar from the embedded copy — otherwise a
+ // bridge update keeps spawning whatever install_mlx_diffusion wrote
+ // months ago.
+ std::fs::write(&server, SERVER_PY)
+ .map_err(|e| crate::commands::internal(format!("write server.py: {e}")))?;
+ let log_path = mlx_root().join("server.log");
+ let stdout = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&log_path)
+ .map_err(|e| crate::commands::internal(format!("log open: {e}")))?;
+ let stderr = stdout
+ .try_clone()
+ .map_err(|e| crate::commands::internal(e.to_string()))?;
+
+ Command::new(venv_python())
+ .arg(&server)
+ .env("LU_MLX_PORT", MLX_PORT.to_string())
+ .env("HF_HOME", mlx_root().join("cache"))
+ .stdout(stdout)
+ .stderr(stderr)
+ .spawn()
+ .map_err(|e| crate::commands::internal(format!("spawn mlx server: {e}")))?;
+
+ Ok(json!({"ok": true, "port": MLX_PORT, "log": log_path.to_string_lossy()}))
+}
+
+/// Stop the MLX sidecar (the long-lived image/video server on MLX_PORT). We
+/// didn't keep a Child handle, so stop it by its listening port — the "Stop"
+/// button counterpart to `mlx_start`.
+pub fn mlx_stop(_state: &AppState, _args: &Value) -> CmdResult {
+ crate::process_util::kill_listeners_on_port(MLX_PORT);
+ Ok(json!({ "ok": true, "port": MLX_PORT }))
+}
+
+const REQUIREMENTS_TXT: &str = include_str!("../../resources/mlx/requirements.txt");
+const SERVER_PY: &str = include_str!("../../resources/mlx/server.py");
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mlx_root_lives_under_data_dir() {
+ let r = mlx_root();
+ let d = crate::os_paths::data_dir();
+ assert!(r.starts_with(&d), "mlx root should live inside data dir");
+ assert!(r.ends_with("mlx"));
+ }
+
+ #[test]
+ fn venv_python_path_is_unix_style() {
+ let p = venv_python();
+ let s = p.to_string_lossy();
+ assert!(s.ends_with("venv/bin/python"));
+ }
+
+ #[test]
+ fn version_at_least_accepts_higher_minor() {
+ assert!(version_at_least("3.12.1", 3, 11));
+ assert!(version_at_least("3.11.0", 3, 11));
+ }
+
+ #[test]
+ fn version_at_least_rejects_lower_minor() {
+ assert!(!version_at_least("3.10.5", 3, 11));
+ assert!(!version_at_least("2.7.0", 3, 11));
+ }
+
+ #[test]
+ fn version_at_least_rejects_garbage() {
+ assert!(!version_at_least("abc", 3, 11));
+ assert!(!version_at_least("", 3, 11));
+ assert!(!version_at_least("3", 3, 11));
+ }
+
+ #[test]
+ fn truncate_appends_ellipsis_when_over_limit() {
+ assert_eq!(truncate("abc", 10), "abc");
+ assert_eq!(truncate("abcdefghijkl", 5), "abcde…");
+ }
+
+ #[test]
+ fn image_catalog_ids_are_unique_and_complete() {
+ let mut ids: Vec<&str> = IMAGE_CATALOG.iter().map(|c| c.id).collect();
+ ids.sort();
+ ids.dedup();
+ assert_eq!(ids.len(), IMAGE_CATALOG.len(), "duplicate catalog id");
+ assert_eq!(IMAGE_CATALOG.len(), 7);
+ assert_eq!(
+ IMAGE_CATALOG.iter().filter(|c| c.unfiltered).count(),
+ 3,
+ "exactly three unfiltered picks"
+ );
+ // Small-to-large hardware coverage.
+ assert!(IMAGE_CATALOG.iter().any(|c| c.min_ram_gb <= 8));
+ assert!(IMAGE_CATALOG.iter().any(|c| c.min_ram_gb >= 64));
+ }
+
+ #[test]
+ fn image_catalog_entries_are_wellformed() {
+ for c in IMAGE_CATALOG {
+ assert!(c.repo.contains('/'), "{} repo must be org/name", c.id);
+ assert!(!c.allow.is_empty(), "{} needs allow patterns", c.id);
+ assert!(c.allow.contains(&"*.json"), "{} must pull configs", c.id);
+ assert!(c.steps > 0 && c.size_gb > 0.0);
+ assert!(
+ c.cfg_param == "guidance_scale" || c.cfg_param == "true_cfg_scale",
+ "{} unknown cfg_param",
+ c.id
+ );
+ assert!(c.dtype == "float16" || c.dtype == "bfloat16");
+ // fp16-variant repos must restrict weights to fp16 subfiles so we
+ // don't pull the fp32 duplicates.
+ if c.fp16_variant {
+ assert!(c.allow.iter().any(|p| p.contains("fp16")), "{}", c.id);
+ }
+ }
+ }
+
+ #[test]
+ fn image_cache_dir_follows_hub_layout() {
+ let d = image_model_cache_dir("stabilityai/sd-turbo");
+ assert!(d.ends_with("cache/hub/models--stabilityai--sd-turbo"));
+ }
+
+ #[test]
+ fn embedded_assets_are_non_empty() {
+ // include_str! at compile time guarantees these are populated;
+ // the assertion turns a typo'd path into a build-time failure
+ // instead of an empty-write at install time.
+ assert!(REQUIREMENTS_TXT.contains("torch"));
+ assert!(SERVER_PY.contains("FastAPI"));
+ }
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index a4953f45..ecaab92a 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,6 +1,5 @@
pub mod agent;
pub mod bg_tasks;
-pub mod bridge;
pub mod repo_map;
pub mod claude_code;
pub mod download;
@@ -9,6 +8,8 @@ pub mod filesystem;
pub mod gpu;
pub mod health;
pub mod install;
+pub mod media_cmds;
+pub mod mlx;
pub mod oauth;
pub mod process;
pub mod proxy;
@@ -18,6 +19,7 @@ pub mod secret;
pub mod shell;
pub mod system;
pub mod tts;
+pub mod video;
pub mod waitlist;
pub mod whisper;
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 05732c08..81e46142 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -4,6 +4,18 @@ use sysinfo::System;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
+/// Disk-space preflight shim for the ported `commands::video::video_install_model`
+/// (originally the bridge's real statvfs-based free/total/used probe). Not
+/// wired up to a real disk-usage check here — returning `None` makes the
+/// preflight a no-op (video installs proceed without a disk-space guard, same
+/// as every other model-download path in this codebase, none of which check
+/// free space today). Signature (`Option<(free, total, used)>` in bytes)
+/// matches the call site's `if let Some((free, _, _)) = ...` destructure.
+#[allow(dead_code)]
+pub fn volume_space_for(_path: &std::path::Path) -> Option<(u64, u64, u64)> {
+ None
+}
+
#[tauri::command]
pub fn system_info() -> Result<serde_json::Value, String> {
Ok(serde_json::json!({
diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rs
new file mode 100644
index 00000000..4989663a
--- /dev/null
+++ b/src-tauri/src/commands/video.rs
@@ -0,0 +1,859 @@
+//! MLX-video pipeline.
+//!
+//! Driven via subprocess against the [`mlx-video`](https://github.com/Blaizzy/mlx-video)
+//! Python package. Apple Silicon only — the Bridge guards every entry point
+//! with an arch check so Windows/Linux clients hitting these commands by
+//! accident get a clear 400 instead of a hung subprocess.
+//!
+//! Models are downloaded into `~/.cache/lu-labs/mlx-video/<id>/` (the
+//! `--model-dir` argument passed to `mlx_video.<family>.generate`).
+//! Generated videos land in `~/.config/lu-labs/videos/<job_id>.mp4`.
+
+use crate::commands::{bad_request, internal, CmdResult};
+use crate::state::AppState;
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+
+// ── Hardware guard ────────────────────────────────────────────────────
+
+fn ensure_apple_silicon() -> Result<(), String> {
+ if std::env::consts::OS == "macos" && std::env::consts::ARCH == "aarch64" {
+ Ok(())
+ } else {
+ Err(bad_request(
+ "MLX video is Apple Silicon only — use the ComfyUI backend on this OS",
+ ))
+ }
+}
+
+// ── Model catalog ─────────────────────────────────────────────────────
+//
+// Curated list of models that `mlx-video` can drive today. The frontend
+// renders one card per entry; the user clicks Install and the Bridge pulls
+// the HF repo into `models_root()/<id>/`.
+
+#[derive(serde::Serialize, Clone)]
+struct CatalogEntry {
+ id: &'static str,
+ name: &'static str,
+ family: &'static str, // mlx_video.models.<family>.generate
+ repo: &'static str,
+ /// ltx_2 `--pipeline {distilled,dev,dev-two-stage,...}` — unused by wan_2.
+ pipeline: &'static str,
+ size_gb: f32,
+ min_ram_gb: u32,
+ /// Default `-n`/`--num-frames` (wan_2 requires 4n+1).
+ default_frames: u32,
+ default_width: u32,
+ default_height: u32,
+ /// wan_2 repos ship PyTorch checkpoints — install runs the one-time
+ /// `mlx_video.models.wan_2.convert` step (needs ~2× the size on disk
+ /// while converting; the source checkpoint is removed afterwards).
+ needs_convert: bool,
+ unfiltered: bool,
+ description: &'static str,
+}
+
+// Only repos that ACTUALLY exist on HuggingFace (every one verified HTTP 200,
+// ungated, sizes from the API) and that `mlx-video` can drive today:
+// - ltx_2 → prince-canuma/LTX-2* — the package author's PRE-CONVERTED
+// modular repos. This replaces the mlx-community bf16 single-file repos,
+// whose flat layout crashed generation (BUG-022) — resolved by repo swap.
+// - wan_2 → the original Wan-AI checkpoints + the package's convert step
+// (`--model-dir <converted>`); Wan has no built-in content filter.
+const CATALOG: &[CatalogEntry] = &[
+ CatalogEntry {
+ id: "wan21-t2v-1.3b",
+ name: "Wan 2.1 T2V 1.3B",
+ family: "wan_2",
+ repo: "Wan-AI/Wan2.1-T2V-1.3B",
+ pipeline: "",
+ size_gb: 18.0,
+ min_ram_gb: 16,
+ default_frames: 81,
+ default_width: 832,
+ default_height: 480,
+ needs_convert: true,
+ unfiltered: true,
+ description: "The smallest real video model on Apple Silicon — 480p text-to-video, unfiltered, runs on 16 GB Macs. One-time convert to MLX after download.",
+ },
+ CatalogEntry {
+ id: "wan22-ti2v-5b",
+ name: "Wan 2.2 TI2V 5B",
+ family: "wan_2",
+ repo: "Wan-AI/Wan2.2-TI2V-5B",
+ pipeline: "",
+ size_gb: 35.0,
+ min_ram_gb: 32,
+ default_frames: 81,
+ default_width: 1280,
+ default_height: 704,
+ needs_convert: true,
+ unfiltered: true,
+ description: "720p text- AND image-to-video in one 5B model — the sweet spot on 32 GB Macs. Unfiltered.",
+ },
+ CatalogEntry {
+ id: "ltx-2.3-dev",
+ name: "LTX-2.3 Dev",
+ family: "ltx_2",
+ repo: "prince-canuma/LTX-2.3-dev",
+ pipeline: "dev",
+ size_gb: 58.0,
+ min_ram_gb: 48,
+ default_frames: 49,
+ default_width: 768,
+ default_height: 512,
+ needs_convert: false,
+ unfiltered: false,
+ description: "Latest LTX generation with CFG — text/image-to-video with audio, pre-converted MLX weights.",
+ },
+ CatalogEntry {
+ id: "wan21-t2v-14b",
+ name: "Wan 2.1 T2V 14B",
+ family: "wan_2",
+ repo: "Wan-AI/Wan2.1-T2V-14B",
+ pipeline: "",
+ size_gb: 70.0,
+ min_ram_gb: 48,
+ default_frames: 81,
+ default_width: 1280,
+ default_height: 704,
+ needs_convert: true,
+ unfiltered: true,
+ description: "720p Wan at full 14B quality — the classic uncensored heavyweight. One-time convert after download.",
+ },
+ CatalogEntry {
+ id: "ltx-2.3-distilled",
+ name: "LTX-2.3 Distilled",
+ family: "ltx_2",
+ repo: "prince-canuma/LTX-2.3-distilled",
+ pipeline: "distilled",
+ size_gb: 96.0,
+ min_ram_gb: 64,
+ default_frames: 49,
+ default_width: 768,
+ default_height: 512,
+ needs_convert: false,
+ unfiltered: false,
+ description: "LTX-2.3 distilled incl. 2× upscaler stages — fast high-res video with audio on 64 GB Macs.",
+ },
+ CatalogEntry {
+ id: "ltx-2-distilled",
+ name: "LTX-2 Distilled",
+ family: "ltx_2",
+ repo: "prince-canuma/LTX-2-distilled",
+ pipeline: "distilled",
+ size_gb: 109.0,
+ min_ram_gb: 64,
+ default_frames: 49,
+ default_width: 768,
+ default_height: 512,
+ needs_convert: false,
+ unfiltered: false,
+ description: "The 19B LTX-2 distilled — text/image-to-video with audio, pre-converted modular MLX weights.",
+ },
+ CatalogEntry {
+ id: "wan22-t2v-a14b",
+ name: "Wan 2.2 T2V A14B",
+ family: "wan_2",
+ repo: "Wan-AI/Wan2.2-T2V-A14B",
+ pipeline: "",
+ size_gb: 127.0,
+ min_ram_gb: 64,
+ default_frames: 81,
+ default_width: 1280,
+ default_height: 704,
+ needs_convert: true,
+ unfiltered: true,
+ description: "Wan 2.2's dual-model MoE flagship — the strongest open video model that runs on a Mac. Unfiltered, 64 GB+ only.",
+ },
+];
+
+fn catalog_lookup(id: &str) -> Option<&'static CatalogEntry> {
+ CATALOG.iter().find(|c| c.id == id)
+}
+
+// ── Filesystem layout ─────────────────────────────────────────────────
+
+fn models_root() -> PathBuf {
+ dirs::cache_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("lu-labs")
+ .join("mlx-video")
+}
+
+pub(crate) fn outputs_root() -> PathBuf {
+ dirs::config_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("lu-labs")
+ .join("videos")
+}
+
+fn model_dir(id: &str) -> PathBuf {
+ models_root().join(id)
+}
+
+/// Directory the generate CLI actually points at: the converted MLX weights
+/// for wan_2 (`<id>/mlx`), the pre-converted download itself for ltx_2.
+fn weights_dir(entry: &CatalogEntry) -> PathBuf {
+ if entry.needs_convert {
+ model_dir(entry.id).join("mlx")
+ } else {
+ model_dir(entry.id)
+ }
+}
+
+fn dir_non_empty(dir: &PathBuf) -> bool {
+ dir.is_dir() && std::fs::read_dir(dir).map(|mut it| it.next().is_some()).unwrap_or(false)
+}
+
+fn model_is_installed(entry: &CatalogEntry) -> bool {
+ dir_non_empty(&weights_dir(entry))
+}
+
+// ── mlx-video CLI detection ───────────────────────────────────────────
+
+fn python_for(state: &AppState) -> Option<String> {
+ // Prefer the MLX venv interpreter created by install_mlx_diffusion: it
+ // already has huggingface_hub + torch (so snapshot_download and the wan
+ // convert work without re-installing them), and it is the shared
+ // Apple-Silicon ML interpreter, so mlx-video installs there too. The
+ // onboarding python_bin comes second — it's a bare interpreter that
+ // ensure_python_module has to bootstrap first (BUG-018).
+ let venv = crate::os_paths::data_dir()
+ .join("mlx")
+ .join("venv")
+ .join("bin")
+ .join("python");
+ venv.exists()
+ .then(|| venv.to_string_lossy().to_string())
+ .or_else(|| state.python_bin())
+ .or_else(|| crate::os_paths::find_python().map(|p| p.to_string_lossy().to_string()))
+}
+
+fn mlx_video_installed(python: &str) -> bool {
+ Command::new(python)
+ .args(["-c", "import mlx_video"])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false)
+}
+
+fn python_has_module(python: &str, module: &str) -> bool {
+ Command::new(python)
+ .args(["-c", &format!("import {module}")])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false)
+}
+
+/// Idempotent module bootstrap: the bridge's python is whatever the machine
+/// has (system python, uv-managed, or our MLX venv) — `huggingface_hub`,
+/// `torch` (wan convert reads .pth) and `mlx_video` itself are NOT givens.
+/// Without this, installs died with a bare "command exited 1"
+/// (ModuleNotFoundError swallowed in the worker thread).
+pub(crate) fn ensure_python_module(
+ slot: &crate::install_state::InstallSlot,
+ python: &str,
+ module: &str,
+ pip_spec: &str,
+) -> Result<(), String> {
+ if python_has_module(python, module) {
+ return Ok(());
+ }
+ slot.log(format!("installing {pip_spec} (one-time)"));
+ let mut cmd = Command::new(python);
+ cmd.args(["-m", "pip", "install", "--upgrade", pip_spec]);
+ run_streamed(slot, &mut cmd)
+ .map_err(|e| format!("pip install {pip_spec}: {e}"))?;
+ if !python_has_module(python, module) {
+ return Err(format!(
+ "installed {pip_spec} but `import {module}` still fails"
+ ));
+ }
+ Ok(())
+}
+
+fn mlx_video_version(python: &str) -> Option<String> {
+ let out = Command::new(python)
+ .args([
+ "-c",
+ "import importlib.metadata as m; print(m.version('mlx-video'))",
+ ])
+ .output()
+ .ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let v = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ if v.is_empty() {
+ None
+ } else {
+ Some(v)
+ }
+}
+
+// ── Commands ──────────────────────────────────────────────────────────
+
+pub fn video_status(state: &AppState, _args: &Value) -> CmdResult {
+ let apple_silicon =
+ std::env::consts::OS == "macos" && std::env::consts::ARCH == "aarch64";
+ let python = python_for(state);
+ let mlx_ok = python.as_deref().map(mlx_video_installed).unwrap_or(false);
+ let version = if mlx_ok {
+ python.as_deref().and_then(mlx_video_version)
+ } else {
+ None
+ };
+ let installed_ids: Vec<&str> = CATALOG
+ .iter()
+ .filter(|c| model_is_installed(c))
+ .map(|c| c.id)
+ .collect();
+ let running = state.video_process().lock().unwrap().is_some();
+ Ok(json!({
+ "available": apple_silicon,
+ "appleSilicon": apple_silicon,
+ "mlxInstalled": mlx_ok,
+ "mlxVersion": version,
+ "pythonBin": python,
+ "modelsRoot": models_root(),
+ "outputsRoot": outputs_root(),
+ "installedModels": installed_ids,
+ "running": running,
+ }))
+}
+
+/// Remove an installed MLX-video model's weights. The id must be a catalog
+/// entry, so the delete is confined to `<models_root>/<known-id>/`.
+pub fn video_delete_model(state: &AppState, args: &Value) -> CmdResult {
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| crate::commands::bad_request("missing id".to_string()))?;
+ let entry = catalog_lookup(id)
+ .ok_or_else(|| crate::commands::bad_request(format!("unknown video model id: {id}")))?;
+ if state.video_process().lock().unwrap().is_some() {
+ return Err(crate::commands::bad_request(
+ "a video job is running — cancel it before deleting the model".to_string(),
+ ));
+ }
+ // The installer's snapshot_download is writing into this very directory —
+ // model_is_installed() flips true at the first file, so the UI can offer
+ // Delete mid-install without this guard.
+ if state.install_video_model().is_running() {
+ return Err(crate::commands::bad_request(
+ "this model is still installing — wait for it to finish first".to_string(),
+ ));
+ }
+ let dir = model_dir(entry.id);
+ if !dir.is_dir() {
+ return Err(crate::commands::not_found(format!("{id} is not installed")));
+ }
+ std::fs::remove_dir_all(&dir).map_err(|e| internal(format!("delete {id}: {e}")))?;
+ Ok(json!({ "ok": true, "id": id }))
+}
+
+pub fn video_list_models(_state: &AppState, _args: &Value) -> CmdResult {
+ let mut out: Vec<Value> = Vec::with_capacity(CATALOG.len());
+ for c in CATALOG {
+ out.push(json!({
+ "id": c.id,
+ "name": c.name,
+ "family": c.family,
+ "repo": c.repo,
+ "sizeGB": c.size_gb,
+ "minRamGB": c.min_ram_gb,
+ "defaultFrames": c.default_frames,
+ "needsConvert": c.needs_convert,
+ "unfiltered": c.unfiltered,
+ "description": c.description,
+ "installed": model_is_installed(c),
+ }));
+ }
+ Ok(Value::Array(out))
+}
+
+pub fn video_install_mlx(state: &AppState, _args: &Value) -> CmdResult {
+ ensure_apple_silicon()?;
+ let slot = state.install_mlx_video();
+ if slot.is_running() {
+ return Ok(json!({ "ok": true, "status": "installing" }));
+ }
+ let python = python_for(state)
+ .ok_or_else(|| bad_request("Python not available — run install_python first"))?;
+ if mlx_video_installed(&python) {
+ slot.complete("mlx-video already installed");
+ return Ok(json!({ "ok": true, "status": "complete" }));
+ }
+ slot.start();
+ let slot2 = slot.clone();
+ std::thread::spawn(move || {
+ let mut cmd = Command::new(&python);
+ cmd.args([
+ "-m",
+ "pip",
+ "install",
+ "--upgrade",
+ "git+https://github.com/Blaizzy/mlx-video.git",
+ ]);
+ if let Err(e) = run_streamed(&slot2, &mut cmd) {
+ slot2.fail(e);
+ } else if !mlx_video_installed(&python) {
+ slot2.fail("pip install finished but `import mlx_video` still fails");
+ } else {
+ slot2.complete("mlx-video installed");
+ }
+ });
+ Ok(json!({ "ok": true, "status": "installing" }))
+}
+
+pub fn video_install_mlx_status(state: &AppState, _args: &Value) -> CmdResult {
+ Ok(serde_json::to_value(state.install_mlx_video().snapshot()).unwrap())
+}
+
+#[derive(Deserialize)]
+struct InstallModelArgs {
+ id: String,
+}
+
+pub fn video_install_model(state: &AppState, args: &Value) -> CmdResult {
+ ensure_apple_silicon()?;
+ let a: InstallModelArgs =
+ serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;
+ let entry = catalog_lookup(&a.id)
+ .ok_or_else(|| bad_request(format!("unknown video model id: {}", a.id)))?;
+ let slot = state.install_video_model();
+ if slot.is_running() {
+ return Ok(json!({ "ok": true, "status": "installing" }));
+ }
+ if model_is_installed(entry) {
+ slot.complete(format!("{} already installed", entry.id));
+ return Ok(json!({ "ok": true, "status": "complete", "id": entry.id }));
+ }
+ let python = python_for(state)
+ .ok_or_else(|| bad_request("Python not available — run install_python first"))?;
+
+ // Authoritative disk preflight — wan repos briefly need download + MLX
+ // copy side by side during the convert step.
+ let factor: f64 = if entry.needs_convert { 2.0 } else { 1.0 };
+ let need = (entry.size_gb as f64 * factor * 1e9) as u64 + 2_000_000_000;
+ if let Some((free, _, _)) = crate::commands::system::volume_space_for(&models_root()) {
+ if free < need {
+ return Err(bad_request(format!(
+ "not enough disk space: {} needs ~{:.0} GB{} but only {:.0} GB are free",
+ entry.name,
+ need as f64 / 1e9,
+ if entry.needs_convert { " (incl. one-time convert)" } else { "" },
+ free as f64 / 1e9,
+ )));
+ }
+ }
+
+ let target = model_dir(entry.id);
+ if let Some(parent) = target.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| internal(e.to_string()))?;
+ }
+ slot.start();
+ let slot2 = slot.clone();
+ let entry2 = entry.clone();
+ std::thread::spawn(move || {
+ if let Err(e) = install_model_steps(&slot2, &python, &entry2) {
+ slot2.fail(e);
+ } else if !model_is_installed(&entry2) {
+ slot2.fail("download finished but model directory is empty");
+ } else {
+ slot2.complete(format!("{} installed", entry2.id));
+ }
+ });
+ Ok(json!({ "ok": true, "status": "installing", "id": entry.id }))
+}
+
+fn install_model_steps(
+ slot: &crate::install_state::InstallSlot,
+ python: &str,
+ entry: &CatalogEntry,
+) -> Result<(), String> {
+ ensure_python_module(slot, python, "huggingface_hub", "huggingface_hub")?;
+ // Generation needs the mlx-video package for BOTH families — installing
+ // it here (not just for the wan convert) means a model installed from
+ // the Discover tab generates on the first click instead of erroring
+ // with "mlx-video not installed".
+ ensure_python_module(
+ slot,
+ python,
+ "mlx_video",
+ "git+https://github.com/Blaizzy/mlx-video.git",
+ )?;
+
+ // wan_2: download the PyTorch checkpoint to <id>/src, convert to
+ // <id>/mlx, then drop the source to give the disk back.
+ let download_to = if entry.needs_convert {
+ model_dir(entry.id).join("src")
+ } else {
+ model_dir(entry.id)
+ };
+
+ // `huggingface_hub.snapshot_download` is the supported way to pull
+ // an HF repo with resume + progress. We invoke it inline so the
+ // bridge doesn't need to ship the huggingface-cli binary.
+ slot.log(format!("downloading {} ({} GB)", entry.repo, entry.size_gb));
+ let script = format!(
+ "from huggingface_hub import snapshot_download; snapshot_download(repo_id={r:?}, local_dir={t:?})",
+ r = entry.repo,
+ t = download_to.to_string_lossy(),
+ );
+ let mut cmd = Command::new(python);
+ cmd.args(["-c", &script]);
+ run_streamed(slot, &mut cmd)?;
+
+ if !entry.needs_convert {
+ return Ok(());
+ }
+
+ // Convert additionally needs torch to read the .pth text encoder/VAE.
+ ensure_python_module(slot, python, "torch", "torch")?;
+
+ let out_dir = weights_dir(entry);
+ slot.log(format!("converting {} to MLX (one-time)", entry.name));
+ let mut convert = Command::new(python);
+ convert
+ .arg("-m")
+ .arg("mlx_video.models.wan_2.convert")
+ .arg("--checkpoint-dir")
+ .arg(download_to.as_os_str())
+ .arg("--output-dir")
+ .arg(out_dir.as_os_str());
+ run_streamed(slot, &mut convert).map_err(|e| format!("convert: {e}"))?;
+ if !dir_non_empty(&out_dir) {
+ return Err("convert finished but produced no MLX weights".to_string());
+ }
+
+ slot.log("removing the source checkpoint (converted copy is kept)");
+ let _ = std::fs::remove_dir_all(&download_to);
+ Ok(())
+}
+
+pub fn video_install_model_status(state: &AppState, _args: &Value) -> CmdResult {
+ Ok(serde_json::to_value(state.install_video_model().snapshot()).unwrap())
+}
+
+#[derive(Deserialize)]
+struct GenerateArgs {
+ id: String,
+ prompt: String,
+ #[serde(default)]
+ seconds: Option<f32>,
+ #[serde(default)]
+ fps: Option<u32>,
+ #[serde(default)]
+ init_image: Option<String>,
+ #[serde(default)]
+ seed: Option<i64>,
+}
+
+pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {
+ ensure_apple_silicon()?;
+ let a: GenerateArgs =
+ serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;
+ let entry = catalog_lookup(&a.id)
+ .ok_or_else(|| bad_request(format!("unknown video model id: {}", a.id)))?;
+ if !model_is_installed(entry) {
+ return Err(bad_request(format!(
+ "model {} not installed — run video_install_model first",
+ entry.id
+ )));
+ }
+ let python = python_for(state)
+ .ok_or_else(|| bad_request("Python not available — run install_python first"))?;
+ if !mlx_video_installed(&python) {
+ return Err(bad_request("mlx-video not installed — run video_install_mlx first"));
+ }
+ {
+ let video_process = state.video_process();
+ let g = video_process.lock().unwrap();
+ if g.is_some() {
+ return Err(bad_request(
+ "a video generation is already running — cancel it first",
+ ));
+ }
+ }
+
+ // Validate init_image BEFORE spawning: chat models sometimes hallucinate
+ // a filename. A crisp, self-describing error lets the agent loop retry
+ // without the image instead of surfacing an opaque subprocess exit(1).
+ if let Some(img) = a.init_image.as_deref() {
+ if !std::path::Path::new(img).is_file() {
+ return Err(bad_request(format!(
+ "init_image not found: {img} — pass the absolute path of a real image file, or omit init_image for text-to-video"
+ )));
+ }
+ }
+
+ let out_dir = outputs_root();
+ std::fs::create_dir_all(&out_dir).map_err(|e| internal(e.to_string()))?;
+ let job_id = uuid::Uuid::new_v4().simple().to_string();
+ let out_path = out_dir.join(format!("{}.mp4", job_id));
+
+ let mdir = weights_dir(entry);
+
+ // Frame count: caller can override via `seconds * fps`; otherwise use
+ // the catalog default. mlx-video's frame flags count frames, not seconds.
+ let fps = a.fps.unwrap_or(24).max(1);
+ let frames = a
+ .seconds
+ .map(|s| (s * fps as f32).max(1.0) as u32)
+ .unwrap_or(entry.default_frames);
+ let frames = clamp_frames(entry.family, frames);
+
+ // The two families take different CLIs (both verified against
+ // Blaizzy/mlx-video):
+ // ltx_2 → --model-repo <dir> --pipeline <p> -o <out> -n <frames>
+ // wan_2 → --model-dir <dir> --num-frames (4n+1) --output-path <out>
+ let mut cmd = Command::new(&python);
+ cmd.arg("-m")
+ .arg(format!("mlx_video.models.{}.generate", entry.family))
+ .arg("--prompt")
+ .arg(&a.prompt);
+ if entry.family == "wan_2" {
+ cmd.arg("--model-dir")
+ .arg(mdir.as_os_str())
+ .arg("--width")
+ .arg(entry.default_width.to_string())
+ .arg("--height")
+ .arg(entry.default_height.to_string())
+ .arg("--num-frames")
+ .arg(frames.to_string())
+ .arg("--output-path")
+ .arg(out_path.as_os_str());
+ } else {
+ cmd.arg("--model-repo")
+ .arg(mdir.as_os_str())
+ .arg("--pipeline")
+ .arg(entry.pipeline)
+ .arg("-o")
+ .arg(out_path.as_os_str())
+ .arg("-n")
+ .arg(frames.to_string());
+ }
+ if let Some(seed) = a.seed {
+ cmd.arg("--seed").arg(seed.to_string());
+ }
+ if let Some(img) = a.init_image.as_deref() {
+ cmd.arg("--image").arg(img);
+ }
+
+ // Reset the live progress slot — every new job starts clean.
+ let progress = state.video_progress();
+ progress.start();
+ progress.log(format!("job {} → {}", job_id, out_path.display()));
+ progress.log(format!(
+ "python -m mlx_video.models.{}.generate --prompt … {} … ({} frames)",
+ entry.family,
+ mdir.display(),
+ frames
+ ));
+
+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ let mut child = cmd
+ .spawn()
+ .map_err(|e| internal(format!("spawn mlx_video: {e}")))?;
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+ let pid = child.id();
+ *state.video_process().lock().unwrap() = Some(child);
+
+ // Stdout / stderr pumps → progress slot.
+ let p_out = progress.clone();
+ let p_err = progress.clone();
+ std::thread::spawn(move || {
+ use std::io::{BufRead, BufReader};
+ if let Some(s) = stdout {
+ for line in BufReader::new(s).lines().map_while(Result::ok) {
+ p_out.log(line);
+ }
+ }
+ });
+ std::thread::spawn(move || {
+ use std::io::{BufRead, BufReader};
+ if let Some(s) = stderr {
+ for line in BufReader::new(s).lines().map_while(Result::ok) {
+ p_err.log(line);
+ }
+ }
+ });
+
+ // Reaper thread — polls try_wait, flips slot to complete/error, clears
+ // the handle. It must NOT take the Child out of the mutex up front:
+ // that made `video_progress.running` false the moment generation
+ // started and left `video_cancel` with nothing to kill (the job ran on
+ // uncancellable).
+ //
+ // AppState isn't Clone, so instead of cloning the whole state we clone
+ // just the two Arc-backed handles the thread needs: the video-process
+ // mutex itself (`video_process()` returns a cloned `Arc<Mutex<...>>`,
+ // pointing at the same child the caller just stored) and the progress
+ // InstallSlot.
+ let video_process = state.video_process();
+ let video_progress_slot = state.video_progress();
+ let out_path2 = out_path.clone();
+ let job_id_for_thread = job_id.clone();
+ std::thread::spawn(move || loop {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ let mut guard = video_process.lock().unwrap();
+ let Some(child) = guard.as_mut() else {
+ // video_cancel took and killed it — the slot is already failed.
+ return;
+ };
+ let status = match child.try_wait() {
+ Ok(None) => continue,
+ Ok(Some(s)) => Ok(s),
+ Err(e) => Err(e),
+ };
+ *guard = None;
+ drop(guard);
+ match status {
+ Ok(s) if s.success() && out_path2.exists() => {
+ video_progress_slot.complete(format!("job {} complete → {}", job_id_for_thread, out_path2.display()));
+ }
+ Ok(s) => video_progress_slot.fail(format!("mlx_video exited {:?}", s.code())),
+ Err(e) => video_progress_slot.fail(format!("wait failed: {e}")),
+ }
+ return;
+ });
+
+ Ok(json!({
+ "ok": true,
+ "jobId": job_id,
+ "pid": pid,
+ "output": out_path,
+ }))
+}
+
+pub fn video_progress(state: &AppState, _args: &Value) -> CmdResult {
+ let running = state.video_process().lock().unwrap().is_some();
+ let snap = state.video_progress().snapshot();
+ Ok(json!({
+ "running": running,
+ "status": snap.status,
+ "logs": snap.logs,
+ "error": snap.error,
+ }))
+}
+
+pub fn video_cancel(state: &AppState, _args: &Value) -> CmdResult {
+ let video_process = state.video_process();
+ let mut g = video_process.lock().unwrap();
+ if let Some(mut child) = g.take() {
+ let _ = crate::process_util::kill_tree(&mut child);
+ state.video_progress().fail("cancelled");
+ return Ok(json!({ "ok": true }));
+ }
+ Ok(json!({ "ok": true, "was_running": false }))
+}
+
+// ── helpers ───────────────────────────────────────────────────────────
+
+/// wan_2's temporal VAE requires `num_frames % 4 == 1`; ltx_2 takes any.
+fn clamp_frames(family: &str, frames: u32) -> u32 {
+ if family != "wan_2" {
+ return frames.max(1);
+ }
+ let f = frames.max(5);
+ f - ((f - 1) % 4)
+}
+
+pub(crate) fn run_streamed(slot: &crate::install_state::InstallSlot, cmd: &mut Command) -> Result<(), String> {
+ use std::io::{BufRead, BufReader};
+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(crate::process_util::no_window());
+ }
+ let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?;
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+ let so = slot.clone();
+ let se = slot.clone();
+ let t1 = std::thread::spawn(move || {
+ if let Some(s) = stdout {
+ for line in BufReader::new(s).lines().map_while(Result::ok) {
+ so.log(line);
+ }
+ }
+ });
+ let t2 = std::thread::spawn(move || {
+ if let Some(s) = stderr {
+ for line in BufReader::new(s).lines().map_while(Result::ok) {
+ se.log(line);
+ }
+ }
+ });
+ let status = child.wait().map_err(|e| format!("wait: {e}"))?;
+ let _ = t1.join();
+ let _ = t2.join();
+ if !status.success() {
+ return Err(format!("command exited {:?}", status.code()));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn catalog_ids_unique_and_covers_hardware_range() {
+ let mut ids: Vec<&str> = CATALOG.iter().map(|c| c.id).collect();
+ ids.sort();
+ ids.dedup();
+ assert_eq!(ids.len(), CATALOG.len(), "duplicate catalog id");
+ assert_eq!(CATALOG.len(), 7);
+ assert!(CATALOG.iter().filter(|c| c.unfiltered).count() >= 3);
+ assert!(CATALOG.iter().any(|c| c.min_ram_gb <= 16));
+ assert!(CATALOG.iter().any(|c| c.min_ram_gb >= 64));
+ }
+
+ #[test]
+ fn catalog_families_match_cli_expectations() {
+ for c in CATALOG {
+ match c.family {
+ "ltx_2" => {
+ assert!(!c.pipeline.is_empty(), "{} needs a --pipeline", c.id);
+ assert!(!c.needs_convert, "{}: ltx repos are pre-converted", c.id);
+ }
+ "wan_2" => {
+ assert!(c.needs_convert, "{}: wan checkpoints need convert", c.id);
+ assert_eq!(c.default_frames % 4, 1, "{}: wan frames must be 4n+1", c.id);
+ }
+ other => panic!("{}: unknown family {other}", c.id),
+ }
+ assert!(c.repo.contains('/'));
+ assert!(c.size_gb > 0.0 && c.default_width > 0 && c.default_height > 0);
+ }
+ }
+
+ #[test]
+ fn clamp_frames_enforces_wan_4n_plus_1() {
+ assert_eq!(clamp_frames("wan_2", 81), 81);
+ assert_eq!(clamp_frames("wan_2", 80), 77);
+ assert_eq!(clamp_frames("wan_2", 1), 5);
+ assert_eq!(clamp_frames("ltx_2", 80), 80);
+ assert_eq!(clamp_frames("ltx_2", 0), 1);
+ }
+
+ #[test]
+ fn weights_dir_points_at_converted_output_for_wan() {
+ let wan = CATALOG.iter().find(|c| c.family == "wan_2").unwrap();
+ let ltx = CATALOG.iter().find(|c| c.family == "ltx_2").unwrap();
+ assert!(weights_dir(wan).ends_with(format!("{}/mlx", wan.id)));
+ assert!(weights_dir(ltx).ends_with(ltx.id));
+ }
+}
diff --git a/src-tauri/src/install_state.rs b/src-tauri/src/install_state.rs
new file mode 100644
index 00000000..41c21787
--- /dev/null
+++ b/src-tauri/src/install_state.rs
@@ -0,0 +1,84 @@
+//! Shared install-progress state. Each long-running installer (Python, ComfyUI,
+//! LM Studio, Claude Code, SearXNG) owns one of these and the frontend polls
+//! `install_*_status` to render progress + logs.
+
+use serde::Serialize;
+use std::sync::{Arc, Mutex};
+
+#[derive(Debug, Clone, Serialize)]
+pub struct InstallProgress {
+ pub status: String,
+ pub logs: Vec<String>,
+ pub download_progress: u64,
+ pub download_total: u64,
+ pub download_speed: u64,
+ pub error: Option<String>,
+}
+
+impl Default for InstallProgress {
+ fn default() -> Self {
+ Self {
+ status: "idle".into(),
+ logs: Vec::new(),
+ download_progress: 0,
+ download_total: 0,
+ download_speed: 0,
+ error: None,
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+pub struct InstallSlot {
+ inner: Arc<Mutex<InstallProgress>>,
+}
+
+impl InstallSlot {
+ pub fn snapshot(&self) -> InstallProgress {
+ self.inner.lock().unwrap().clone()
+ }
+
+ pub fn is_running(&self) -> bool {
+ self.inner.lock().unwrap().status == "installing"
+ }
+
+ pub fn start(&self) {
+ let mut g = self.inner.lock().unwrap();
+ *g = InstallProgress {
+ status: "installing".into(),
+ ..Default::default()
+ };
+ }
+
+ pub fn log(&self, line: impl Into<String>) {
+ let mut g = self.inner.lock().unwrap();
+ let entry = line.into();
+ tracing::info!("[install] {entry}");
+ g.logs.push(entry);
+ if g.logs.len() > 200 {
+ let drop = g.logs.len() - 200;
+ g.logs.drain(..drop);
+ }
+ }
+
+ pub fn set_download(&self, progress: u64, total: u64) {
+ let mut g = self.inner.lock().unwrap();
+ g.download_progress = progress;
+ g.download_total = total;
+ }
+
+ pub fn complete(&self, msg: impl Into<String>) {
+ let mut g = self.inner.lock().unwrap();
+ g.status = "complete".into();
+ g.logs.push(msg.into());
+ }
+
+ pub fn fail(&self, msg: impl Into<String>) {
+ let mut g = self.inner.lock().unwrap();
+ let m = msg.into();
+ tracing::error!("[install] failed: {m}");
+ g.status = "error".into();
+ g.error = Some(m.clone());
+ g.logs.push(format!("ERROR: {m}"));
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index c9827ac4..eba9ec68 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,6 +2,9 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod commands;
+mod install_state;
+mod os_paths;
+mod process_util;
mod python;
mod state;
@@ -190,10 +193,28 @@ fn main() {
commands::engine::start_bundled_embed,
commands::engine::stop_bundled_embed,
commands::engine::bundled_embed_status,
- // lu-bridge media sidecar (macOS Apple-Silicon MLX local media, Phase 6)
- commands::bridge::start_media_bridge,
- commands::bridge::stop_media_bridge,
- commands::bridge::media_bridge_status,
+ // In-process MLX media engine (macOS Apple-Silicon local image/video,
+ // spawned in-process — no separate bridge daemon). See media_cmds.rs.
+ commands::media_cmds::mlx_status,
+ commands::media_cmds::mlx_start,
+ commands::media_cmds::mlx_unload,
+ commands::media_cmds::mlx_generate,
+ commands::media_cmds::mlx_image_models,
+ commands::media_cmds::mlx_image_install_model,
+ commands::media_cmds::mlx_image_install_status,
+ commands::media_cmds::mlx_image_delete_model,
+ commands::media_cmds::install_mlx_diffusion,
+ commands::media_cmds::install_mlx_diffusion_status,
+ commands::media_cmds::video_status,
+ commands::media_cmds::video_list_models,
+ commands::media_cmds::video_install_mlx,
+ commands::media_cmds::video_install_mlx_status,
+ commands::media_cmds::video_install_model,
+ commands::media_cmds::video_install_model_status,
+ commands::media_cmds::video_delete_model,
+ commands::media_cmds::video_generate,
+ commands::media_cmds::video_progress,
+ commands::media_cmds::video_cancel,
// Provider API-key keychain (H5)
commands::secret::secret_set,
commands::secret::secret_get,
diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rs
new file mode 100644
index 00000000..89fef1d0
--- /dev/null
+++ b/src-tauri/src/os_paths.rs
@@ -0,0 +1,369 @@
+//! Cross-platform path helpers — Python lookup, LM Studio CLI, common
+//! install destinations. Mirrors the path-resolution logic from the old
+//! Locally Uncensored Tauri binary.
+
+use std::path::PathBuf;
+
+pub fn home() -> PathBuf {
+ dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
+}
+
+pub fn data_dir() -> PathBuf {
+ dirs::data_local_dir()
+ .or_else(dirs::data_dir)
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("lu-labs")
+}
+
+pub fn cache_dir() -> PathBuf {
+ dirs::cache_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("lu-labs")
+}
+
+/// Locate a usable Python interpreter. Returns the absolute path to the
+/// binary, or `None` if no real Python is on the system.
+///
+/// On Windows we explicitly skip the WindowsApps stub that opens the
+/// Microsoft Store instead of running Python, and every candidate is
+/// verified with `--version` before we commit to it — a path that exists
+/// but doesn't run (broken uninstall leftovers, the Store stub) must not
+/// poison the cached python. Probe order: `where` → the `py -3` launcher
+/// (present even when "Add to PATH" was skipped) → `C:\PythonXX` →
+/// `C:\Program Files\Python*` (all-users installs) → `%LOCALAPPDATA%`.
+pub fn find_python() -> Option<PathBuf> {
+ #[cfg(target_os = "windows")]
+ {
+ find_python_windows()
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ for c in unix_python_candidates() {
+ if let Ok(p) = which::which(c) {
+ return Some(p);
+ }
+ }
+ None
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn find_python_windows() -> Option<PathBuf> {
+ python_via_where()
+ .or_else(python_via_py_launcher)
+ .or_else(python_in_fixed_paths)
+ .or_else(python_in_program_files)
+ .or_else(python_in_appdata)
+}
+
+/// Run a candidate interpreter and confirm it's real (exits 0 — the MS Store
+/// stub prints an install nag and exits non-zero).
+#[cfg(target_os = "windows")]
+fn verify_python_path(path: &str) -> bool {
+ if path.is_empty() || path.to_lowercase().contains("windowsapps") {
+ return false;
+ }
+ let mut cmd = std::process::Command::new(path);
+ cmd.arg("--version");
+ crate::process_util::suppress_window(&mut cmd);
+ cmd.output().map(|o| o.status.success()).unwrap_or(false)
+}
+
+/// `where python` on PATH, skipping the WindowsApps Store-stub alias.
+#[cfg(target_os = "windows")]
+fn python_via_where() -> Option<PathBuf> {
+ let mut cmd = std::process::Command::new("where");
+ cmd.arg("python");
+ crate::process_util::suppress_window(&mut cmd);
+ let out = cmd.output().ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ for line in String::from_utf8_lossy(&out.stdout).lines() {
+ let p = line.trim();
+ if !p.is_empty() && verify_python_path(p) {
+ return Some(PathBuf::from(p));
+ }
+ }
+ None
+}
+
+/// The Windows `py -3` launcher (C:\Windows\py.exe) is installed system-wide
+/// by the python.org installer regardless of the "Add to PATH" checkbox and
+/// the install dir, so it finds Pythons that `where` + fixed-path scans miss.
+/// We ask Python for its own `sys.executable` so we return the concrete
+/// python.exe (needed for venv creation / pip), not the launcher shim.
+#[cfg(target_os = "windows")]
+fn python_via_py_launcher() -> Option<PathBuf> {
+ let mut cmd = std::process::Command::new("py");
+ cmd.args(["-3", "-c", "import sys; print(sys.executable)"]);
+ crate::process_util::suppress_window(&mut cmd);
+ let out = cmd.output().ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ if verify_python_path(&path) {
+ Some(PathBuf::from(path))
+ } else {
+ None
+ }
+}
+
+/// Standard single-version python.org install dirs at the drive root.
+#[cfg(target_os = "windows")]
+fn python_in_fixed_paths() -> Option<PathBuf> {
+ for ver in ["313", "312", "311", "310", "39"] {
+ let p = PathBuf::from(format!("C:\\Python{ver}\\python.exe"));
+ if p.exists() && verify_python_path(&p.to_string_lossy()) {
+ return Some(p);
+ }
+ }
+ None
+}
+
+/// All-users python.org installs land in `C:\Program Files\PythonXX` (and the
+/// 32-bit build under Program Files (x86)) — invisible to `where` when "Add
+/// to PATH" was skipped.
+#[cfg(target_os = "windows")]
+fn python_in_program_files() -> Option<PathBuf> {
+ for env_key in ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"] {
+ if let Ok(base) = std::env::var(env_key) {
+ if let Some(p) = scan_python_subdirs(std::path::Path::new(&base)) {
+ return Some(p);
+ }
+ }
+ }
+ None
+}
+
+/// Per-user python.org installs: `%LOCALAPPDATA%\Programs\Python\Python3xx`.
+#[cfg(target_os = "windows")]
+fn python_in_appdata() -> Option<PathBuf> {
+ let local = std::env::var("LOCALAPPDATA").ok()?;
+ scan_python_subdirs(&std::path::Path::new(&local).join("Programs").join("Python"))
+}
+
+/// Scan `base` for `Python*\python.exe`, newest version first, verifying each
+/// candidate actually runs before returning it.
+#[cfg(target_os = "windows")]
+fn scan_python_subdirs(base: &std::path::Path) -> Option<PathBuf> {
+ let entries = std::fs::read_dir(base).ok()?;
+ let mut dirs: Vec<_> = entries
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ e.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
+ && e.file_name().to_string_lossy().to_lowercase().starts_with("python")
+ })
+ .collect();
+ dirs.sort_by(|a, b| b.file_name().cmp(&a.file_name()));
+ for dir in dirs {
+ let exe = dir.path().join("python.exe");
+ if exe.exists() && verify_python_path(&exe.to_string_lossy()) {
+ return Some(exe);
+ }
+ }
+ None
+}
+
+/// Candidate interpreter names for macOS/Linux, ordered so a known-good minor
+/// (3.12 / 3.11 — they have torch/mlx/diffusers wheels) beats a bare `python3`,
+/// which on some machines is 3.14, too new for ML wheels (BUG-008). Keeps the
+/// video + RAG path on the same interpreter the MLX image install picks.
+#[cfg(not(target_os = "windows"))]
+fn unix_python_candidates() -> [&'static str; 5] {
+ ["python3.12", "python3.11", "python3.13", "python3", "python"]
+}
+
+#[cfg(test)]
+#[allow(clippy::items_after_test_module)]
+mod python_candidate_tests {
+ #[cfg(not(target_os = "windows"))]
+ use super::unix_python_candidates;
+
+ #[cfg(not(target_os = "windows"))]
+ #[test]
+ fn prefers_3_12_and_3_11_over_bare_python3() {
+ let c = unix_python_candidates();
+ let i312 = c.iter().position(|x| *x == "python3.12").unwrap();
+ let i311 = c.iter().position(|x| *x == "python3.11").unwrap();
+ let i3 = c.iter().position(|x| *x == "python3").unwrap();
+ assert!(
+ i312 < i3 && i311 < i3,
+ "must prefer python3.12/3.11 over a bare python3 (BUG-008)"
+ );
+ }
+
+ // ── Windows resolver (upstream 68de216) ─────────────────────────
+
+ #[cfg(target_os = "windows")]
+ #[test]
+ fn verify_rejects_stub_and_empty() {
+ assert!(!super::verify_python_path(""));
+ assert!(!super::verify_python_path(
+ "C:\\Users\\u\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe"
+ ));
+ assert!(!super::verify_python_path("C:\\no\\such\\python.exe"));
+ }
+
+ #[cfg(target_os = "windows")]
+ #[test]
+ fn scan_python_subdirs_prefers_newest_and_verifies() {
+ // A dir tree with a fake (non-runnable) python.exe: exists() passes
+ // but --version fails → the scan must reject it, not return it blind.
+ let tmp = tempfile::tempdir().unwrap();
+ let d = tmp.path().join("Python312");
+ std::fs::create_dir_all(&d).unwrap();
+ std::fs::write(d.join("python.exe"), b"not a real exe").unwrap();
+ assert!(super::scan_python_subdirs(tmp.path()).is_none());
+ }
+
+ #[test]
+ fn find_python_returns_verified_or_none() {
+ // Cross-platform smoke: whatever comes back must exist on disk.
+ if let Some(p) = super::find_python() {
+ assert!(p.exists(), "find_python returned a non-existent path: {p:?}");
+ }
+ }
+}
+
+/// Look for the LM Studio CLI (`lms`). Three locations:
+/// 1. Post-bootstrap install (`~/.lmstudio/bin/lms`)
+/// 2. Pre-bootstrap (Windows package layout)
+/// 3. PATH
+pub fn find_lms_cli() -> Option<PathBuf> {
+ let ext = if cfg!(target_os = "windows") { ".exe" } else { "" };
+ let post = home().join(".lmstudio").join("bin").join(format!("lms{ext}"));
+ if post.exists() {
+ return Some(post);
+ }
+ if cfg!(target_os = "windows") {
+ if let Ok(local) = std::env::var("LOCALAPPDATA") {
+ let pre = PathBuf::from(local)
+ .join("Programs")
+ .join("LM Studio")
+ .join("resources")
+ .join("app")
+ .join(".webpack")
+ .join("lms.exe");
+ if pre.exists() {
+ return Some(pre);
+ }
+ }
+ }
+ which::which("lms").ok()
+}
+
+/// macOS Spotlight lookup for an app bundle by its on-disk name (e.g.
+/// "LM Studio.app"). Finds installs buried in deep or hidden folders that PATH
+/// and the fixed /Applications check miss — people drop apps in the weirdest
+/// nested places. No-op (None) off macOS.
+fn spotlight_app(fs_name: &str) -> Option<PathBuf> {
+ #[cfg(target_os = "macos")]
+ {
+ let out = std::process::Command::new("mdfind")
+ .arg(format!("kMDItemFSName == '{fs_name}'"))
+ .output()
+ .ok()?;
+ String::from_utf8_lossy(&out.stdout)
+ .lines()
+ .map(|l| PathBuf::from(l.trim()))
+ .find(|p| p.exists())
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = fs_name;
+ None
+ }
+}
+
+/// Locate the LM Studio app bundle anywhere on disk: the standard install dirs
+/// first, then Spotlight for hidden / deeply-nested installs.
+pub fn find_lmstudio_app() -> Option<PathBuf> {
+ for p in [
+ PathBuf::from("/Applications/LM Studio.app"),
+ home().join("Applications").join("LM Studio.app"),
+ ] {
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ spotlight_app("LM Studio.app")
+}
+
+/// Is LM Studio installed anywhere — the `lms` CLI or the app bundle?
+pub fn lmstudio_installed() -> bool {
+ find_lms_cli().is_some() || find_lmstudio_app().is_some()
+}
+
+/// Locate the Ollama app bundle anywhere on disk (fixed dirs, then Spotlight).
+pub fn find_ollama_app() -> Option<PathBuf> {
+ for p in [
+ PathBuf::from("/Applications/Ollama.app"),
+ home().join("Applications").join("Ollama.app"),
+ ] {
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ spotlight_app("Ollama.app")
+}
+
+/// Locate the `ollama` CLI binary: PATH, common prefixes, then inside a
+/// discovered Ollama.app bundle.
+pub fn find_ollama_bin() -> Option<PathBuf> {
+ if let Ok(p) = which::which("ollama") {
+ return Some(p);
+ }
+ for c in [
+ "/opt/homebrew/bin/ollama",
+ "/usr/local/bin/ollama",
+ "/usr/bin/ollama",
+ ] {
+ let p = PathBuf::from(c);
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ if let Some(app) = find_ollama_app() {
+ for rel in [
+ "Contents/Resources/ollama",
+ "Contents/MacOS/Ollama",
+ "Contents/MacOS/ollama",
+ ] {
+ let p = app.join(rel);
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ }
+ None
+}
+
+/// Is Ollama installed anywhere — CLI binary or app bundle?
+pub fn ollama_installed() -> bool {
+ find_ollama_bin().is_some() || find_ollama_app().is_some()
+}
+
+/// Reasonable places to look for an existing ComfyUI install.
+pub fn comfyui_search_roots() -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ let h = home();
+ out.push(h.clone());
+ out.push(h.join("Desktop"));
+ out.push(h.join("Documents"));
+ out.push(h.join("Downloads"));
+ if cfg!(target_os = "windows") {
+ if let Ok(user_profile) = std::env::var("USERPROFILE") {
+ out.push(PathBuf::from(user_profile.clone()).join("StabilityMatrix"));
+ out.push(PathBuf::from(user_profile).join("Packages"));
+ }
+ }
+ out
+}
+
+/// Default ComfyUI install target — where install_comfyui will drop the
+/// portable bundle on Windows / clone the repo on macOS+Linux.
+pub fn default_comfyui_dir() -> PathBuf {
+ data_dir().join("ComfyUI")
+}
diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rs
new file mode 100644
index 00000000..a54b1b7f
--- /dev/null
+++ b/src-tauri/src/process_util.rs
@@ -0,0 +1,148 @@
+//! Process spawning + lifecycle helpers used by ComfyUI / LM Studio / Claude
+//! Code lifecycle commands.
+//!
+//! On Windows we use Job Objects (KILL_ON_JOB_CLOSE) so any child process tree
+//! gets cleaned up when the bridge exits, and prefer `taskkill /T /F` for
+//! recursive kills. On Unix we use a process-group kill via `kill -- -PGID` so
+//! Python subprocess trees don't leak.
+
+use std::process::{Child, Command, Stdio};
+
+#[cfg(windows)]
+pub fn no_window() -> u32 {
+ 0x08000000 // CREATE_NO_WINDOW
+}
+
+/// Suppress the console window for a std `Command` on Windows (CREATE_NO_WINDOW);
+/// no-op elsewhere. Use for every CLI we shell out to (lms, git, python probes)
+/// so users don't get console flashes.
+pub fn suppress_window(cmd: &mut Command) {
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(no_window());
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = cmd;
+ }
+}
+
+/// Spawn a command with stdout+stderr piped, console suppressed on Windows.
+pub fn spawn_piped(mut cmd: Command) -> std::io::Result<Child> {
+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(no_window());
+ }
+ #[cfg(unix)]
+ {
+ // Create our own process group so we can kill the whole tree later.
+ use std::os::unix::process::CommandExt;
+ unsafe {
+ cmd.pre_exec(|| {
+ if libc_setpgid_self() != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+ });
+ }
+ }
+ cmd.spawn()
+}
+
+/// Recursive process-tree kill. On Windows uses `taskkill /T /F /PID`; on
+/// Unix sends SIGTERM to the process group then SIGKILL after a grace.
+pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {
+ let pid = child.id();
+ #[cfg(windows)]
+ {
+ let _ = Command::new("taskkill")
+ .args(["/T", "/F", "/PID", &pid.to_string()])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+ }
+ #[cfg(unix)]
+ {
+ unsafe {
+ // Negative PID kills the process group.
+ libc::kill(-(pid as i32), libc::SIGTERM);
+ }
+ std::thread::sleep(std::time::Duration::from_millis(800));
+ unsafe {
+ libc::kill(-(pid as i32), libc::SIGKILL);
+ }
+ }
+ let _ = child.kill();
+ let _ = child.wait();
+ Ok(())
+}
+
+/// Best-effort stop of whatever process is LISTENING on a local TCP port.
+/// Used by the "Stop" buttons for port-bound backends the bridge didn't spawn
+/// itself (so there's no `Child` handle to kill) — the MLX sidecar and the
+/// Ollama server. Only the listener is targeted (`-sTCP:LISTEN`), so the
+/// bridge's own client connections to that port aren't hit.
+pub fn kill_listeners_on_port(port: u16) {
+ #[cfg(unix)]
+ {
+ if let Ok(out) = Command::new("lsof")
+ .args(["-ti", &format!("tcp:{port}"), "-sTCP:LISTEN"])
+ .stderr(Stdio::null())
+ .output()
+ {
+ for pid in String::from_utf8_lossy(&out.stdout)
+ .split_whitespace()
+ .filter_map(|s| s.parse::<i32>().ok())
+ {
+ unsafe {
+ libc::kill(pid, libc::SIGTERM);
+ }
+ }
+ }
+ }
+ #[cfg(windows)]
+ {
+ if let Ok(out) = Command::new("cmd")
+ .args(["/C", &format!("netstat -ano -p tcp | findstr LISTENING | findstr :{port}")])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .output()
+ {
+ for line in String::from_utf8_lossy(&out.stdout).lines() {
+ if let Some(pid) = line.split_whitespace().last() {
+ let _ = Command::new("taskkill")
+ .args(["/F", "/PID", pid])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+ }
+ }
+ }
+ }
+}
+
+#[cfg(unix)]
+extern "C" {
+ fn setpgid(pid: libc::pid_t, pgid: libc::pid_t) -> libc::c_int;
+}
+
+#[cfg(unix)]
+fn libc_setpgid_self() -> libc::c_int {
+ unsafe { setpgid(0, 0) }
+}
+
+// Minimal libc binding so we can avoid an extra crate.
+#[cfg(unix)]
+#[allow(non_camel_case_types)]
+mod libc {
+ pub type pid_t = i32;
+ pub type c_int = i32;
+ pub const SIGTERM: c_int = 15;
+ pub const SIGKILL: c_int = 9;
+ extern "C" {
+ pub fn kill(pid: pid_t, sig: c_int) -> c_int;
+ }
+}
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 8e7a85b3..c083dbc8 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -135,12 +135,6 @@ pub(crate) fn load_ollama_base() -> String {
pub struct AppState {
pub comfy_process: Mutex<Option<Child>>,
- /// Managed lu-bridge sidecar (Apple-Silicon MLX local media, macOS only).
- /// `None` until `start_media_bridge` spawns the bundled `lu-bridge` binary
- /// headless on 127.0.0.1:47711. The lifecycle lives in `commands::bridge`;
- /// this is just the handle so shutdown can reap it. See the hard rule:
- /// Mac local image/video is MLX-via-bridge only, never ComfyUI.
- pub media_bridge: Mutex<Option<Child>>,
/// Child handle for an Ollama daemon LU spawned itself (kj103x bug, Discord
/// 2026-05-23 #help-chat). The Drop impl below kills the tree on shutdown
/// so `ollama.exe` doesn't linger eating ~200 MB after the tray quit.
@@ -251,6 +245,27 @@ pub struct AppState {
/// ran on the CPU). None = LU hasn't started ComfyUI this session.
/// Surfaced to the Create tab via `get_comfy_gpu_status`.
pub comfy_started_cpu: Mutex<Option<bool>>,
+ // ── In-process MLX media engine (macOS Apple-Silicon local image/video) ──
+ // Ported from uselu/apps/bridge's `commands::mlx` / `commands::video`. The
+ // app spawns its OWN Python MLX sidecar (server.py on 127.0.0.1:47712) —
+ // no separate lu-bridge daemon. Hard rule: Mac local image/video is MLX
+ // only, never ComfyUI.
+ /// Install progress for the MLX-Stable-Diffusion engine (venv + torch +
+ /// diffusers). `commands::mlx::install_mlx_diffusion`.
+ pub install_mlx_diffusion: crate::install_state::InstallSlot,
+ /// Install progress for a single MLX image-catalog model download.
+ pub install_mlx_image_model: crate::install_state::InstallSlot,
+ /// Install progress for the `mlx-video` pip package.
+ pub install_mlx_video: crate::install_state::InstallSlot,
+ /// Install progress for a single MLX video-catalog model download/convert.
+ pub install_video_model: crate::install_state::InstallSlot,
+ /// Live progress/log of the currently running (or last) video generation.
+ pub video_progress: crate::install_state::InstallSlot,
+ /// Handle to the running `mlx_video.*.generate` subprocess, if any. `Arc`-
+ /// wrapped (unlike the other `Mutex<Option<Child>>` handles above) so the
+ /// video-generation reaper thread can hold its own clone of the same
+ /// mutex instead of needing a clone of the whole (non-`Clone`) `AppState`.
+ pub video_process: Arc<Mutex<Option<Child>>>,
}
impl AppState {
@@ -284,7 +299,6 @@ impl AppState {
Self {
comfy_process: Mutex::new(None),
- media_bridge: Mutex::new(None),
ollama_process: Mutex::new(None),
bundled_engine: Mutex::new(None),
bundled_embed: Mutex::new(None),
@@ -321,10 +335,51 @@ impl AppState {
comfy_gpu_cache: Mutex::new(HashMap::new()),
comfy_gpu_mode: Mutex::new("auto".to_string()),
comfy_started_cpu: Mutex::new(None),
+ install_mlx_diffusion: crate::install_state::InstallSlot::default(),
+ install_mlx_image_model: crate::install_state::InstallSlot::default(),
+ install_mlx_video: crate::install_state::InstallSlot::default(),
+ install_video_model: crate::install_state::InstallSlot::default(),
+ video_progress: crate::install_state::InstallSlot::default(),
+ video_process: Arc::new(Mutex::new(None)),
}
}
}
+impl AppState {
+ /// Install-progress accessors for the in-process MLX media engine — each
+ /// returns a cloned handle (`InstallSlot` is a cheap `Arc`-backed clone),
+ /// matching the accessor-method convention the ported `commands::mlx` /
+ /// `commands::video` code expects (`state.install_mlx_diffusion()` etc.).
+ pub fn install_mlx_diffusion(&self) -> crate::install_state::InstallSlot {
+ self.install_mlx_diffusion.clone()
+ }
+ pub fn install_mlx_image_model(&self) -> crate::install_state::InstallSlot {
+ self.install_mlx_image_model.clone()
+ }
+ pub fn install_mlx_video(&self) -> crate::install_state::InstallSlot {
+ self.install_mlx_video.clone()
+ }
+ pub fn install_video_model(&self) -> crate::install_state::InstallSlot {
+ self.install_video_model.clone()
+ }
+ pub fn video_progress(&self) -> crate::install_state::InstallSlot {
+ self.video_progress.clone()
+ }
+ /// Cloned `Arc` handle to the video-subprocess mutex — cheap, and lets a
+ /// spawned reaper thread hold its own reference without needing the
+ /// (non-`Clone`) `AppState` itself. See the `video_process` field doc.
+ pub fn video_process(&self) -> Arc<Mutex<Option<Child>>> {
+ self.video_process.clone()
+ }
+ /// Resolved Python binary path, or `None` when no real Python was found
+ /// on this box (`python_bin` stores `""` as that sentinel — see the field
+ /// doc comment above).
+ pub fn python_bin(&self) -> Option<String> {
+ let bin = self.python_bin.lock().unwrap().clone();
+ if bin.is_empty() { None } else { Some(bin) }
+ }
+}
+
// On Windows, spawn child processes without flashing a console window.
// Applied to every taskkill/kill call so LU's process lifecycle stays invisible
// to the user. 0x08000000 = CREATE_NO_WINDOW.
@@ -403,12 +458,12 @@ impl AppState {
}
}
- // lu-bridge media sidecar (macOS MLX). Plain kill of the bridge parent;
- // the bridge reaps its own MLX Python sidecar (:47712) on shutdown.
- if let Ok(mut proc) = self.media_bridge.lock() {
+ // In-process MLX video subprocess (`mlx_video.*.generate`). Plain kill —
+ // it's a single Python process, no child tree to walk.
+ if let Ok(mut proc) = self.video_process.lock() {
if let Some(ref mut child) = *proc {
let _ = child.kill();
- println!("[Bridge] lu-bridge media sidecar stopped (explicit shutdown)");
+ println!("[MLX] video subprocess stopped (explicit shutdown)");
}
*proc = None;
}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 4623d314..c743d240 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -51,8 +51,7 @@
"../dist"
],
"externalBin": [
- "bin/llama-server",
- "bin/lu-bridge"
+ "bin/llama-server"
],
"icon": [
"icons/32x32.png",
diff --git a/src/api/bridge-client.ts b/src/api/bridge-client.ts
deleted file mode 100644
index 6c146de5..00000000
--- a/src/api/bridge-client.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * lu-bridge media client (macOS Apple-Silicon MLX local media).
- *
- * Hard rule: Mac local image/video is MLX-via-lu-bridge only, never ComfyUI.
- * The bundled `lu-bridge` sidecar (spawned by `start_media_bridge`, see
- * src-tauri/src/commands/bridge.rs) serves `/cmd/:name` on 127.0.0.1:47711 with
- * NO auth (loopback bind IS the boundary). This is the single transport the
- * MLX image/video API wrappers use — the desktop analogue of the web app's
- * `backendCall` (which POSTs to the same `/cmd/*` on a paired bridge URL).
- */
-import { localFetch, backendCall, isTauri } from './backend'
-
-const BRIDGE_BASE = 'http://127.0.0.1:47711'
-
-// Memoized "ensure the sidecar is up" promise. `start_media_bridge` is
-// idempotent (no-op if already healthy), so we only pay the spawn+health-wait
-// once per session; a failure clears the memo so the next call retries.
-// In a plain browser (Vite dev, no Tauri invoke) we assume the bridge runs
-// externally — mirroring the web app, where it's a separately-launched daemon.
-let _bridgeReady: Promise<void> | null = null
-
-export function ensureMediaBridge(): Promise<void> {
- if (!isTauri()) return Promise.resolve()
- if (!_bridgeReady) {
- _bridgeReady = backendCall('start_media_bridge')
- .then(() => undefined)
- .catch((e) => {
- _bridgeReady = null
- throw e
- })
- }
- return _bridgeReady
-}
-
-/**
- * POST a bridge command. Ensures the sidecar is running first, then proxies
- * the call to `127.0.0.1:47711/cmd/<command>` through `localFetch` (Tauri Rust
- * proxy → bypasses CORS). `timeoutMs` defaults to 30 s for status/catalog
- * calls; generation calls (a single long-blocking request) pass a large value.
- */
-export async function bridgeCmd<T = unknown>(
- command: string,
- args?: Record<string, unknown>,
- timeoutMs = 30_000,
-): Promise<T> {
- await ensureMediaBridge()
- const res = await localFetch(`${BRIDGE_BASE}/cmd/${command}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(args ?? {}),
- timeoutMs,
- })
- if (!res.ok) {
- const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as { error?: string }
- throw new Error(body.error || `HTTP ${res.status}`)
- }
- return res.json() as Promise<T>
-}
diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.ts
index fb577cf5..fec5f13c 100644
--- a/src/api/mlx-image.ts
+++ b/src/api/mlx-image.ts
@@ -1,16 +1,31 @@
/**
- * MLX-Stable-Diffusion image pipeline (Apple Silicon), via the bundled
- * lu-bridge sidecar. Ported from uselu/apps/web/api/mlx-image.ts — the only
- * change is the transport (`bridgeCmd` → 127.0.0.1:47711/cmd/*) plus a
- * readiness wait: the FastAPI sidecar (:47712) binds a beat after `mlx_start`
- * returns, so a cold first generate can race and 500 with "mlx unreachable".
+ * MLX-Stable-Diffusion image pipeline (Apple Silicon), running IN-PROCESS —
+ * the app spawns its own MLX Python sidecar (server.py on 127.0.0.1:47712)
+ * directly from Rust (`commands::mlx`), no separate lu-bridge daemon. Ported
+ * from uselu/apps/web/api/mlx-image.ts; the transport is a direct Tauri
+ * `invoke` via `invokeMedia` (see below) plus a readiness wait: the FastAPI
+ * sidecar binds a beat after `mlx_start` returns, so a cold first generate
+ * can race and 500 with "mlx unreachable".
*
* Hard rule: this is the Mac local image backend, NOT ComfyUI.
*/
-import { bridgeCmd } from './bridge-client'
-import { isMacOS } from './backend'
+import { backendCall, isMacOS } from './backend'
import type { ClassifiedModel } from './comfyui'
+/**
+ * Invoke an in-process MLX media Tauri command. The Rust wrappers
+ * (`src-tauri/src/commands/media_cmds.rs`) each take a single
+ * `args: serde_json::Value` parameter — matching the existing `shell_task_*`
+ * convention in this codebase (see `src/api/agents/bg-tasks.ts`) — so the
+ * payload must be nested under an `args` key, not passed at the top level.
+ */
+async function invokeMedia<T = unknown>(
+ command: string,
+ args?: Record<string, unknown>,
+): Promise<T> {
+ return backendCall<T>(command, { args: args ?? {} })
+}
+
export interface MlxStatus {
installed: boolean
running: boolean
@@ -58,15 +73,15 @@ export interface MlxGenerateResult {
}
export async function mlxStatus(): Promise<MlxStatus> {
- return bridgeCmd<MlxStatus>('mlx_status')
+ return invokeMedia<MlxStatus>('mlx_status')
}
export async function mlxStart(): Promise<{ ok: boolean; port: number }> {
- return bridgeCmd<{ ok: boolean; port: number }>('mlx_start')
+ return invokeMedia<{ ok: boolean; port: number }>('mlx_start')
}
export async function mlxUnload(): Promise<{ ok: boolean; was_loaded: boolean; running: boolean }> {
- return bridgeCmd('mlx_unload')
+ return invokeMedia('mlx_unload')
}
export async function mlxGenerate(args: MlxGenerateArgs): Promise<MlxGenerateResult> {
@@ -77,35 +92,36 @@ export async function mlxGenerate(args: MlxGenerateArgs): Promise<MlxGenerateRes
if (args.width != null) body.width = args.width
if (args.height != null) body.height = args.height
if (args.negativePrompt) body.negative_prompt = args.negativePrompt
- // A single long-blocking request (model load + diffusion) — allow 5 min.
- return bridgeCmd<MlxGenerateResult>('mlx_generate', body, 300_000)
+ // A single long-blocking request (model load + diffusion) — in-process
+ // invoke has no per-call timeout to pass (unlike the old HTTP bridgeCmd).
+ return invokeMedia<MlxGenerateResult>('mlx_generate', body)
}
export async function listMlxImageModels(): Promise<MlxImageModel[]> {
- return bridgeCmd<MlxImageModel[]>('mlx_image_models')
+ return invokeMedia<MlxImageModel[]>('mlx_image_models')
}
export async function installMlxImageModel(
id: string,
): Promise<{ ok: boolean; status: string; id?: string }> {
- return bridgeCmd('mlx_image_install_model', { id })
+ return invokeMedia('mlx_image_install_model', { id })
}
export async function getMlxImageInstallStatus(): Promise<MlxInstallStatus> {
- return bridgeCmd<MlxInstallStatus>('mlx_image_install_status')
+ return invokeMedia<MlxInstallStatus>('mlx_image_install_status')
}
export async function deleteMlxImageModel(id: string): Promise<{ ok: boolean; id: string }> {
- return bridgeCmd('mlx_image_delete_model', { id })
+ return invokeMedia('mlx_image_delete_model', { id })
}
/** Install the MLX image engine itself (venv + torch/diffusers sidecar). */
export async function installMlxImageEngine(): Promise<{ ok: boolean; status: string }> {
- return bridgeCmd('install_mlx_diffusion', {}, 1_800_000)
+ return invokeMedia('install_mlx_diffusion')
}
export async function getMlxImageEngineStatus(): Promise<MlxInstallStatus> {
- return bridgeCmd<MlxInstallStatus>('install_mlx_diffusion_status')
+ return invokeMedia<MlxInstallStatus>('install_mlx_diffusion_status')
}
export type MlxImageDecision = 'use' | 'start' | 'comfyui' | 'unavailable'
diff --git a/src/api/mlx-video.ts b/src/api/mlx-video.ts
index 56be60d4..8fb605d6 100644
--- a/src/api/mlx-video.ts
+++ b/src/api/mlx-video.ts
@@ -1,14 +1,26 @@
/**
- * MLX-video pipeline (Apple Silicon), via the bundled lu-bridge sidecar.
- * Ported from uselu/apps/web/api/video.ts — transport swapped to `bridgeCmd`
- * (127.0.0.1:47711/cmd/*). The bridge spawns `python -m mlx_video.<family>.
- * generate` as a subprocess and exposes progress the frontend polls.
+ * MLX-video pipeline (Apple Silicon), running IN-PROCESS — Rust
+ * (`commands::video`) spawns `python -m mlx_video.<family>.generate` as a
+ * subprocess directly, no separate lu-bridge daemon. Ported from
+ * uselu/apps/web/api/video.ts; the transport is a direct Tauri `invoke` via
+ * `invokeMedia` (see mlx-image.ts) and progress is exposed for the frontend
+ * to poll.
*
* Hard rule: this is the Mac local video backend, NOT ComfyUI. Only Apple
* Silicon Macs see a real surface — every call returns `available:false`
* elsewhere so the UI can dim/skip it.
*/
-import { bridgeCmd } from './bridge-client'
+import { backendCall } from './backend'
+
+/** See the `invokeMedia` doc comment in `mlx-image.ts` — the Rust wrappers
+ * take a single `args: serde_json::Value` param, so the payload must be
+ * nested under an `args` key. */
+async function invokeMedia<T = unknown>(
+ command: string,
+ args?: Record<string, unknown>,
+): Promise<T> {
+ return backendCall<T>(command, { args: args ?? {} })
+}
export interface VideoStatus {
available: boolean
@@ -69,33 +81,33 @@ export interface GenerateResult {
}
export async function getVideoStatus(): Promise<VideoStatus> {
- return bridgeCmd<VideoStatus>('video_status')
+ return invokeMedia<VideoStatus>('video_status')
}
export async function listVideoModels(): Promise<VideoModel[]> {
- return bridgeCmd<VideoModel[]>('video_list_models')
+ return invokeMedia<VideoModel[]>('video_list_models')
}
export async function installMlxVideo(): Promise<{ ok: boolean; status: string }> {
- return bridgeCmd<{ ok: boolean; status: string }>('video_install_mlx', {}, 1_800_000)
+ return invokeMedia<{ ok: boolean; status: string }>('video_install_mlx')
}
export async function getMlxInstallStatus(): Promise<InstallStatus> {
- return bridgeCmd<InstallStatus>('video_install_mlx_status')
+ return invokeMedia<InstallStatus>('video_install_mlx_status')
}
export async function installVideoModel(
id: string,
): Promise<{ ok: boolean; status: string; id?: string }> {
- return bridgeCmd('video_install_model', { id })
+ return invokeMedia('video_install_model', { id })
}
export async function getModelInstallStatus(): Promise<InstallStatus> {
- return bridgeCmd<InstallStatus>('video_install_model_status')
+ return invokeMedia<InstallStatus>('video_install_model_status')
}
export async function deleteVideoModel(id: string): Promise<{ ok: boolean; id: string }> {
- return bridgeCmd('video_delete_model', { id })
+ return invokeMedia('video_delete_model', { id })
}
export async function generateVideo(params: GenerateParams): Promise<GenerateResult> {
@@ -108,16 +120,13 @@ export async function generateVideo(params: GenerateParams): Promise<GenerateRes
seed: params.seed,
}
// Kick off the subprocess; generation itself is polled via video_progress.
- return bridgeCmd<GenerateResult>('video_generate', body, 120_000)
+ return invokeMedia<GenerateResult>('video_generate', body)
}
export async function getVideoProgress(): Promise<VideoProgress> {
- return bridgeCmd<VideoProgress>('video_progress')
+ return invokeMedia<VideoProgress>('video_progress')
}
export async function cancelVideo(): Promise<{ ok: boolean }> {
- return bridgeCmd<{ ok: boolean }>('video_cancel')
+ return invokeMedia<{ ok: boolean }>('video_cancel')
}
-
-/** Bridge base for <video src> playback of a finished clip (served at /videos/:file). */
-export const MLX_VIDEO_BASE = 'http://127.0.0.1:47711'