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.

Merge branch 'feat/2.6.0' into feat/mac-local-mode

purplee71fae4efe62
diff --cc src-tauri/src/commands/mlx.rs
index aba8f18c,00000000..9580a5c9
mode 100644,000000..100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@@ -1,817 -1,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;
++pub 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 --cc src-tauri/src/commands/mod.rs
index ecaab92a,3fde7051..21791221
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@@ -18,8 -17,8 +19,9 @@@ pub mod search
pub mod secret;
pub mod shell;
pub mod system;
+ pub mod trainer;
pub mod tts;
+pub mod video;
pub mod waitlist;
pub mod whisper;
diff --cc src-tauri/src/commands/remote.rs
index 20d68df0,c452e348..7cabbeec
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@@ -1545,7 -2143,7 +2143,7 @@@ button{-webkit-appearance:none;appearan
parameters:[]},
{name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',
parameters:[]},
-- {name:'image_generate', description:'Generate an image from a text prompt via the local ComfyUI pipeline. Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE: on a single-GPU machine LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap (longer on a cold ComfyUI start). This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — ComfyUI serializes generations internally so parallel calls will queue, not speed up. Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',
++ {name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',
parameters:[{name:'prompt',type:'string',description:'Positive text description of the desired image',required:true},
{name:'negativePrompt',type:'string',description:'Things to avoid (blurry, deformed, etc.)',required:false},
{name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},
diff --cc src-tauri/src/commands/system.rs
index 2c321c80,0d1d027a..e30c5abb
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@@ -4,18 -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.
++/// Disk-space preflight shim for `commands::video::video_install_model`
++/// (originally the bridge's 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!({
@@@ -64,71 -52,83 +64,101 @@@ pub fn process_list() -> Result<serde_j
Ok(serde_json::json!({ "processes": processes, "count": processes.len() }))
}
+ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread,
+ // so every millisecond spent here is a frozen window. Same treatment
+ // `lmstudio_server_status` already got — this one was simply missed.
#[tauri::command]
- pub fn screenshot() -> Result<serde_json::Value, String> {
- // Use PowerShell to capture screen on Windows
- #[cfg(target_os = "windows")]
- {
- let tmp = std::env::temp_dir().join("lu-screenshot.png");
- let ps_script = format!(
- r#"
- Add-Type -AssemblyName System.Windows.Forms
- Add-Type -AssemblyName System.Drawing
- $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
- $bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
- $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
- $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
- $bitmap.Save('{}')
- $graphics.Dispose()
- $bitmap.Dispose()
- "#,
- tmp.to_string_lossy().replace('\\', "\\\\")
- );
+ pub async fn screenshot() -> Result<serde_json::Value, String> {
+ tokio::task::spawn_blocking(screenshot_blocking)
+ .await
+ .map_err(|e| format!("screenshot task: {e}"))?
+ }
- let output = std::process::Command::new("powershell")
- .args(["-NoProfile", "-NonInteractive", "-Command", &ps_script])
- .creation_flags(0x08000000) // CREATE_NO_WINDOW
- .output()
- .map_err(|e| format!("Screenshot failed: {}", e))?;
+ fn screenshot_blocking() -> Result<serde_json::Value, String> {
+ // Unique per call. The capture used to land on a fixed `lu-screenshot.png`,
+ // and TWO callers reach this: the agent's screenshot tool and the phone
+ // bridge (remote.rs). Overlapping calls read each other's half-written PNG,
+ // or one deleted the file the other was about to read ("Read screenshot: no
+ // such file"), or a caller simply got the other one's screen.
+ let tmp = std::env::temp_dir().join(format!("lu-screenshot-{}.png", uuid::Uuid::new_v4()));
+ let captured = capture_screen_to(&tmp)
+ .and_then(|()| std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", e)));
+ // Always — the old code returned early on a read error and left a full
+ // picture of the user's screen sitting in the temp directory.
+ let _ = std::fs::remove_file(&tmp);
+
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&captured?);
+ Ok(serde_json::json!({ "image": b64, "format": "png", "encoding": "base64" }))
+ }
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- return Err(format!("Screenshot failed: {}", stderr));
- }
+ /// Quote a path for a PowerShell SINGLE-quoted string literal: only `'` is
+ /// special there, and it escapes by doubling.
+ ///
+ /// The old code doubled BACKSLASHES instead, which is C/JSON escaping, not
+ /// PowerShell — inside single quotes that produced a literal `C:\\Users\\…`
+ /// and only worked because Windows collapses repeated separators. It also left
+ /// `'` untouched, so any user whose profile contains an apostrophe
+ /// (C:\Users\O'Brien\AppData\Local\Temp) ended the string early and the script
+ /// died with a parse error.
+ // Only the Windows capture path calls this; its tests run on every platform.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ fn ps_single_quoted(s: &str) -> String {
+ s.replace('\'', "''")
+ }
- let bytes = std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", e))?;
- let _ = std::fs::remove_file(&tmp);
- let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
- Ok(serde_json::json!({ "image": b64, "format": "png", "encoding": "base64" }))
+ #[cfg(target_os = "windows")]
+ fn capture_screen_to(tmp: &std::path::Path) -> Result<(), String> {
+ let ps_script = format!(
+ r#"
+ Add-Type -AssemblyName System.Windows.Forms
+ Add-Type -AssemblyName System.Drawing
+ $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
+ $bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
+ $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
+ $bitmap.Save('{}')
+ $graphics.Dispose()
+ $bitmap.Dispose()
+ "#,
+ ps_single_quoted(&tmp.to_string_lossy())
+ );
+
+ let output = std::process::Command::new("powershell")
+ .args(["-NoProfile", "-NonInteractive", "-Command", &ps_script])
+ .creation_flags(0x08000000) // CREATE_NO_WINDOW
+ .output()
+ .map_err(|e| format!("Screenshot failed: {}", e))?;
+
+ if !output.status.success() {
+ return Err(format!(
+ "Screenshot failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ ));
}
+ Ok(())
+ }
- // macOS: the native `screencapture` CLI. `-x` = silent (no shutter sound),
- // `-t png` = PNG. Needs the app to hold Screen Recording permission (TCC);
- // without it macOS returns a desktop-only capture rather than erroring.
- #[cfg(target_os = "macos")]
- {
- let tmp = std::env::temp_dir().join("lu-screenshot.png");
- let status = std::process::Command::new("/usr/sbin/screencapture")
- .args(["-x", "-t", "png"])
- .arg(&tmp)
- .status()
- .map_err(|e| format!("Screenshot failed: {}", e))?;
- // screencapture fails (non-zero, "could not create image from display")
- // when the app lacks Screen Recording permission — give an actionable hint.
- if !status.success() || !tmp.exists() {
- let _ = std::fs::remove_file(&tmp);
- return Err("Screenshot failed — grant LU the Screen Recording permission in System Settings ▸ Privacy & Security ▸ Screen Recording, then try again.".to_string());
- }
- let bytes = std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", e))?;
- let _ = std::fs::remove_file(&tmp);
- let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
- Ok(serde_json::json!({ "image": b64, "format": "png", "encoding": "base64" }))
-#[cfg(not(target_os = "windows"))]
++// macOS: the native `screencapture` CLI. `-x` = silent (no shutter sound),
++// `-t png` = PNG. Needs the app to hold Screen Recording permission (TCC);
++// without it screencapture exits non-zero ("could not create image from
++// display") and writes nothing, so give an actionable hint instead of a
++// generic failure.
++#[cfg(target_os = "macos")]
++fn capture_screen_to(tmp: &std::path::Path) -> Result<(), String> {
++ let status = std::process::Command::new("/usr/sbin/screencapture")
++ .args(["-x", "-t", "png"])
++ .arg(tmp)
++ .status()
++ .map_err(|e| format!("Screenshot failed: {}", e))?;
++ if !status.success() || !tmp.exists() {
++ return Err("Screenshot failed — grant LU the Screen Recording permission in System Settings ▸ Privacy & Security ▸ Screen Recording, then try again.".to_string());
+ }
++ Ok(())
++}
+
- #[cfg(not(any(target_os = "windows", target_os = "macos")))]
- {
- Err("Screenshot not implemented for this platform yet".to_string())
- }
++#[cfg(not(any(target_os = "windows", target_os = "macos")))]
+ fn capture_screen_to(_tmp: &std::path::Path) -> Result<(), String> {
+ Err("Screenshot not implemented for this platform yet".to_string())
}
#[tauri::command]
diff --cc src-tauri/src/state.rs
index c083dbc8,85f10f80..0e55c6d9
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@@ -245,27 -268,6 +268,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.
++ // no separate 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 {
@@@ -458,32 -429,16 +491,36 @@@ impl AppState
}
}
+ // 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!("[MLX] video subprocess stopped (explicit shutdown)");
+ }
+ *proc = None;
+ }
+
- if let Ok(mut proc) = self.claude_code_process.lock() {
- if let Some(ref mut child) = *proc {
- let pid = child.id();
- #[cfg(windows)]
- {
- let _ = std::process::Command::new("taskkill")
- .args(["/pid", &pid.to_string(), "/T", "/F"])
- .creation_flags(CREATE_NO_WINDOW)
- .output();
- }
- #[cfg(not(windows))]
- {
- let _ = child.kill();
- let _ = pid;
- }
- println!("[ClaudeCode] Stopped (explicit shutdown)");
++ // MLX image sidecar (server.py on MLX_PORT). `mlx_start` deliberately
++ // drops the Child handle — the sidecar outlives individual renders and
++ // is addressed over loopback — so quitting used to orphan the venv
++ // Python forever (observed live: LU gone, server.py still resident).
++ // Kill it by its listening port, same mechanism as the Stop button.
++ #[cfg(target_os = "macos")]
++ {
++ crate::process_util::kill_listeners_on_port(crate::commands::mlx::MLX_PORT);
++ println!("[MLX] image sidecar stopped (explicit shutdown)");
++ }
+
+ // Character-LoRA training. The PID sits in AppState like every other
+ // long-running child, but shutdown skipped it — so quitting during a
+ // training run left an orphaned Python process holding the GPU, and
+ // the UI that could have cancelled it was gone. Training is the
+ // longest-lived and most VRAM-hungry child the app spawns.
+ if let Ok(mut slot) = self.trainer_process.lock() {
+ if let Some(pid) = slot.take() {
+ crate::commands::trainer::kill_trainer_tree(pid);
+ println!("[Trainer] Training stopped (explicit shutdown)");
}
}
diff --cc src/api/mcp/builtin-tools.ts
index 092aadf0,8fdae68f..d9a2494a
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@@ -8,14 -8,16 +8,18 @@@ import { useAgentWorkflowStore } from '
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
+ import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'
+import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, cancelVideo, readVideoAsBlobUrl, type VideoModel } from '../mlx-video'
/**
- * Helper: current chat id as a plain `{ chatId }` fragment to spread into
- * backendCall payloads. Returns `{}` when no agent loop is active — the
- * Rust side then falls back to `agent-workspace/default/` for relative
- * paths (and uses absolute paths as-is regardless).
+ * Helper: current chat id (+ folder workspace) as a fragment to spread into
+ * backendCall payloads. Returns `{}` when no agent loop is active — the Rust
+ * side then falls back to `agent-workspace/default/` as the jail root. NOTE:
+ * absolute paths are NOT used as-is — the backend jails every path (relative OR
+ * absolute) to the resolved workspace root and rejects anything outside it, so
+ * a caller that needs an absolute project path to resolve MUST pass the real
+ * `workingDirectory` here (it becomes the root).
*/
function chatCtx(): { chatId?: string; workingDirectory?: string } {
const id = getActiveChatId()
diff --cc src/components/auth/AccountPanel.tsx
index f1560f89,9e2c0f56..fa5730c5
--- a/src/components/auth/AccountPanel.tsx
+++ b/src/components/auth/AccountPanel.tsx
@@@ -165,7 -163,7 +163,18 @@@ export function AccountPanel()
disabled={busy || !email || !password}
className="flex items-center gap-1.5 px-3 py-1.5 rounded text-[0.7rem] font-medium bg-gray-900 text-white dark:bg-white dark:text-gray-900 disabled:opacity-40 hover:opacity-90 transition-opacity"
>
- {busy ? <Loader2 size={11} className="animate-spin" /> : <img src="/LU-monogram-bw.png" alt="" width={12} height={12} draggable={false} className="pointer-events-none select-none invert-0 dark:invert" />}
- {busy ? <Loader2 size={11} className="animate-spin" /> : <Cloud size={11} />}
++ {busy ? <Loader2 size={11} className="animate-spin" /> : (
++ /* Monogram, not the stock cloud glyph. The button is dark on light
++ and light on dark, so the invert flips the other way here. */
++ <img
++ src="/LU-monogram-bw.png"
++ alt=""
++ width={12}
++ height={12}
++ draggable={false}
++ className="shrink-0 select-none invert-0 dark:invert"
++ />
++ )}
{mode === 'signin' ? 'Sign in' : 'Create account'}
</button>
<button
diff --cc src/components/chat/FileTree.tsx
index f92978bf,5c9fa767..2ca327b2
--- a/src/components/chat/FileTree.tsx
+++ b/src/components/chat/FileTree.tsx
@@@ -1,8 -1,7 +1,7 @@@
import { useState, useEffect, useRef } from 'react'
import { FolderOpen, Folder, FileText, ArrowLeft, RefreshCw } from 'lucide-react'
import { useCodexStore } from '../../stores/codexStore'
- import { toolRegistry } from '../../api/mcp'
- import { isTauri, isMacOS } from '../../api/backend'
-import { isTauri, backendCall } from '../../api/backend'
++import { isTauri, isMacOS, backendCall } from '../../api/backend'
import type { FileTreeNode } from '../../types/codex'
export function FileTree() {
diff --cc src/components/cloud/CloudExampleModal.tsx
index 00000000,a2d0894f..fbcb51a1
mode 000000,100644..100644
--- a/src/components/cloud/CloudExampleModal.tsx
+++ b/src/components/cloud/CloudExampleModal.tsx
@@@ -1,0 -1,142 +1,149 @@@
+ // Example video popup (2.5.8): the step between a teaser sheet's "See plans"
+ // and the CloudGateModal. Shows a short looping clip of the tool actually
+ // doing its thing (real footage from recorded cloud runs, produced by
+ // scripts/teasers and shipped in public/teasers/<intent>.webm with a webp
+ // poster). Only intent surfaces have clips; model-row teasers keep the
+ // direct path to the gate. A missing or broken asset skips straight to the
+ // gate so the flow never dead-ends on a black box.
+
+ import { useEffect, useRef, useState } from 'react'
+ import { AnimatePresence, motion } from 'framer-motion'
+ import { X, Cloud, Sparkles, Volume2, VolumeX, MonitorDown } from 'lucide-react'
+ import { useUIStore, type CloudTeaserTarget } from '../../stores/uiStore'
-import { useCreateStore, LOCAL_LANE_OPS, type CloudOp } from '../../stores/createStore'
++import { useCreateStore, type CreateIntent } from '../../stores/createStore'
++import { isIntentAvailable } from '../create/experimental/intents'
++import { isMlxImageHost } from '../../api/mlx-image'
+
+ type ExampleIntent = Extract<CloudTeaserTarget, { surface: 'intent' }>['intent']
+
+ const TITLES: Record<ExampleIntent, string> = {
+ upscale: 'Upscale',
+ eraser: 'Erase Object',
+ character: 'Character Studio',
+ lipsync: 'Talking Character',
+ music: 'Music',
+ extend: 'Extend Video',
+ motion: 'Motion Control',
+ }
+
+ export function CloudExampleModal() {
+ const target = useUIStore((s) => s.cloudExampleVideo)
+ const setTarget = useUIStore((s) => s.setCloudExampleVideo)
+ const setCloudGateOpen = useUIStore((s) => s.setCloudGateOpen)
+ const setIntent = useCreateStore((s) => s.setIntent)
+ // Lanes that also run locally (2.5.8): the clip stays REAL CLOUD FOOTAGE
+ // (David's call — the example always shows cloud), but the CTAs fork.
- const localLane = target && LOCAL_LANE_OPS.has(target.intent as CloudOp) ? target.intent : null
++ // Same rule the IntentBar renders from, not a static op list — on the Mac
++ // only MLX image/video run locally (MAC-2).
++ const localLane =
++ target && isIntentAvailable(target.intent as CreateIntent, 'local', isMlxImageHost())
++ ? target.intent
++ : null
+ // The music clip carries the generated track; it still starts muted
+ // (autoplay policy + not startling anyone) with a tap-to-listen toggle.
+ const [muted, setMuted] = useState(true)
+ const videoRef = useRef<HTMLVideoElement | null>(null)
+ useEffect(() => { setMuted(true) }, [target?.intent])
+ // React's `muted` attribute is unreliable on re-renders; set the property.
+ useEffect(() => { if (videoRef.current) videoRef.current.muted = muted }, [muted, target])
+
+ const close = () => setTarget(null)
+ const toPlans = () => { setTarget(null); setCloudGateOpen(true) }
+
+ return (
+ <AnimatePresence>
+ {target && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="fixed inset-0 z-[90] flex items-center justify-center bg-black/60 backdrop-blur-sm"
+ onClick={close}
+ >
+ <motion.div
+ initial={{ opacity: 0, y: 10, scale: 0.97 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 10, scale: 0.97 }}
+ transition={{ duration: 0.15, ease: 'easeOut' }}
+ onClick={(e) => e.stopPropagation()}
+ className="w-[440px] max-w-[94vw] rounded-2xl bg-[#232323] border border-white/[0.08] shadow-2xl shadow-black/50 overflow-hidden"
+ >
+ {/* Clip stage: 16:9, poster paints instantly, clip loops. */}
+ <div className="relative aspect-video bg-[#1b1b1b] border-b border-white/[0.06]">
+ <video
+ ref={videoRef}
+ key={target.intent}
+ className="w-full h-full object-cover"
+ src={`/teasers/${target.intent}.webm`}
+ poster={`/teasers/${target.intent}-poster.webp`}
+ autoPlay
+ muted
+ loop
+ playsInline
+ onError={toPlans}
+ />
+ <button
+ onClick={close}
+ className="absolute top-2 right-2 p-1.5 rounded-md text-gray-400 hover:text-gray-100 bg-black/30 hover:bg-black/50 transition-colors"
+ title="Close"
+ aria-label="Close"
+ >
+ <X size={14} />
+ </button>
+ {target.intent === 'music' && (
+ <button
+ onClick={() => setMuted((m) => !m)}
+ className="absolute bottom-2 right-2 flex items-center gap-1.5 px-2 py-1.5 rounded-md text-[0.62rem] text-gray-200 bg-black/40 hover:bg-black/60 transition-colors"
+ aria-label={muted ? 'Unmute' : 'Mute'}
+ >
+ {muted ? <VolumeX size={13} /> : <Volume2 size={13} />}
+ {muted ? 'Hear it' : 'Mute'}
+ </button>
+ )}
+ </div>
+
+ <div className="p-4 space-y-3">
+ <div className="flex items-center gap-2">
+ {/* Panel is fixed dark in both themes, so always use the dark
+ tints; arbitrary text color dodges the `.light .text-white`
+ remap (same rule as ModelTiles). */}
+ <Cloud size={14} className="text-violet-300" />
+ <h3 className="text-[0.85rem] font-semibold text-[#fafafa]">{TITLES[target.intent]}</h3>
+ <span className="ml-auto text-[0.55rem] font-medium uppercase tracking-widest text-violet-300/80">
+ LU Cloud
+ </span>
+ </div>
+ <p className="text-[0.68rem] leading-relaxed text-gray-400">
+ {localLane
+ ? 'Real output, straight from LU Cloud. Run it there, or fully on your own PC.'
+ : 'Real output, straight from LU Cloud. This is what the tool makes.'}
+ </p>
+ <div className="flex items-center gap-2 pt-1">
+ <button
+ onClick={toPlans}
+ className="flex-1 flex items-center justify-center gap-1.5 h-8 rounded-lg bg-white text-black text-[0.7rem] font-semibold hover:bg-gray-200 transition-colors"
+ >
+ <Sparkles size={12} /> {localLane ? 'Try cloud' : 'See plans'}
+ </button>
+ {localLane && (
+ <button
+ onClick={() => { close(); setIntent(localLane) }}
+ className="flex-1 flex items-center justify-center gap-1.5 h-8 rounded-lg border border-white/15 text-gray-200 text-[0.7rem] font-semibold hover:bg-white/[0.06] transition-colors"
+ >
+ <MonitorDown size={12} /> Try local
+ </button>
+ )}
+ <button
+ onClick={close}
+ className="px-3 h-8 rounded-lg text-[0.7rem] text-gray-400 hover:text-gray-200 hover:bg-white/[0.06] transition-colors"
+ >
+ Not now
+ </button>
+ </div>
+ </div>
+ </motion.div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+ }
diff --cc src/components/cloud/CloudSwitch.tsx
index 84dd9062,f15187c0..67d4e7e3
--- a/src/components/cloud/CloudSwitch.tsx
+++ b/src/components/cloud/CloudSwitch.tsx
@@@ -53,7 -49,7 +48,14 @@@ export function CloudSwitch()
: 'border-gray-200 dark:border-white/10 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:border-gray-300 dark:hover:border-white/20',
)}
>
- <img src="/LU-monogram-bw.png" alt="" width={12} height={12} draggable={false} className="shrink-0 pointer-events-none select-none dark:invert-0 invert" />
- <Cloud size={12} strokeWidth={on ? 2.25 : 1.75} className="shrink-0" />
++ <img
++ src="/LU-monogram-bw.png"
++ alt=""
++ width={12}
++ height={12}
++ draggable={false}
++ className="shrink-0 select-none dark:invert-0 invert"
++ />
<span className="text-[0.65rem] font-medium leading-none">Cloud</span>
<span
aria-hidden
diff --cc src/components/cloud/CloudTeaserModal.tsx
index 00000000,c2183a1e..afbd829d
mode 000000,100644..100644
--- a/src/components/cloud/CloudTeaserModal.tsx
+++ b/src/components/cloud/CloudTeaserModal.tsx
@@@ -1,0 -1,365 +1,371 @@@
+ // Cloud discovery sheet (2.5.8): Local mode surfaces the hosted-only Create
+ // tools + hosted models as tappable teasers, and THIS is what a tap opens — a
+ // small sheet with an animated "show me" demo of the tool, one line of copy,
+ // and the path into LU Cloud. Never blocks a local flow (it only opens from
+ // explicitly cloud-tagged surfaces), never shows in cloud mode, and the
+ // footer link turns the whole discovery layer off (Settings can re-enable).
+
+ import { AnimatePresence, motion } from 'framer-motion'
+ import { X, Cloud, Sparkles, MonitorDown } from 'lucide-react'
+ import { useUIStore, type CloudTeaserTarget } from '../../stores/uiStore'
+ import { useSettingsStore } from '../../stores/settingsStore'
+ import { cloudModelById } from '../../stores/cloudCatalogStore'
-import { useCreateStore, LOCAL_LANE_OPS, type CloudOp } from '../../stores/createStore'
++import { useCreateStore, type CreateIntent } from '../../stores/createStore'
++import { isIntentAvailable } from '../create/experimental/intents'
++import { isMlxImageHost } from '../../api/mlx-image'
+
+ interface TeaserCopy {
+ title: string
+ line: string
+ }
+
+ const INTENT_COPY: Record<Extract<CloudTeaserTarget, { surface: 'intent' }>['intent'], TeaserCopy> = {
+ upscale: {
+ title: 'Upscale',
+ line: 'Blow any image up to crisp 2K, 4K or 8K. No VRAM needed.',
+ },
+ eraser: {
+ title: 'Erase Object',
+ line: 'Paint over anything and it’s gone. Clean fill, no trace.',
+ },
+ character: {
+ title: 'Character Studio',
+ line: 'Train a character from a few photos, then put them in any scene.',
+ },
+ lipsync: {
+ title: 'Talking Character',
+ line: 'A portrait plus any voice becomes a talking video.',
+ },
+ music: {
+ title: 'Music',
+ line: 'Describe a track, get a full song. Up to four minutes.',
+ },
+ extend: {
+ title: 'Extend Video',
+ line: 'Keep a clip going. The cloud continues it seamlessly.',
+ },
+ motion: {
+ title: 'Motion Control',
+ line: 'Your character copies the moves from any dance or pose video.',
+ },
+ }
+
+ export function CloudTeaserModal() {
+ const target = useUIStore((s) => s.cloudTeaser)
+ const setCloudTeaser = useUIStore((s) => s.setCloudTeaser)
+ const setCloudGateOpen = useUIStore((s) => s.setCloudGateOpen)
+ const setCloudExampleVideo = useUIStore((s) => s.setCloudExampleVideo)
+ const setIntent = useCreateStore((s) => s.setIntent)
+ const { updateSettings } = useSettingsStore()
+ const teasersEnabled = useSettingsStore((s) => s.settings.cloudTeasersEnabled)
+
+ // One-time onboarding (David 2026-07-19): the Cloud discovery layer is meant
+ // to appear ONCE per user, never again — not after updates either. Any
+ // dismissal of this sheet (button, backdrop, X, Try local / Try cloud) retires
+ // the whole discovery layer permanently; the persisted flag survives updates,
+ // and Settings can re-enable it. Cloud-only *features* (upscale / eraser) stay
+ // accessible regardless — their sheet renders on tap, not on this flag.
+ const close = () => {
+ if (teasersEnabled) updateSettings({ cloudTeasersEnabled: false })
+ setCloudTeaser(null)
+ }
+ // 2.5.8: the lanes that ALSO run locally get a "Try local" path — the sheet
+ // stops being a pure upsell and becomes the fork between the two lanes.
++ // Ask the same rule the IntentBar renders from, not a static op list: on the
++ // Mac only MLX image/video run locally, so a list-based answer offered a
++ // "Try local" button for lanes the bar doesn't even show (MAC-2).
+ const localLane =
- target?.surface === 'intent' && LOCAL_LANE_OPS.has(target.intent as CloudOp)
++ target?.surface === 'intent' &&
++ isIntentAvailable(target.intent as CreateIntent, 'local', isMlxImageHost())
+ ? target.intent
+ : null
+ const copy: TeaserCopy | null =
+ target?.surface === 'intent'
+ ? INTENT_COPY[target.intent]
+ : target?.surface === 'create-model'
+ ? {
+ title: cloudModelById(target.modelId)?.label ?? 'Hosted model',
+ line:
+ target.kind === 'video'
+ ? 'Cinema grade video models on datacenter GPUs. No download, no VRAM limit.'
+ : 'Frontier image models on datacenter GPUs. No download, no VRAM limit.',
+ }
+ : null
+
+ return (
+ <AnimatePresence>
+ {target && copy && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="fixed inset-0 z-[90] flex items-center justify-center bg-black/60 backdrop-blur-sm"
+ onClick={close}
+ >
+ <motion.div
+ initial={{ opacity: 0, y: 10, scale: 0.97 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 10, scale: 0.97 }}
+ transition={{ duration: 0.15, ease: 'easeOut' }}
+ onClick={(e) => e.stopPropagation()}
+ className="w-[360px] max-w-[92vw] rounded-2xl bg-[#232323] border border-white/[0.08] shadow-2xl shadow-black/50 overflow-hidden"
+ >
+ {/* Demo stage */}
+ <div className="relative h-[130px] bg-[#1b1b1b] border-b border-white/[0.06] overflow-hidden">
+ <TeaserDemo target={target} />
+ <button
+ onClick={close}
+ className="absolute top-2 right-2 p-1.5 rounded-md text-gray-500 hover:text-gray-200 hover:bg-white/10 transition-colors"
+ title="Close"
+ aria-label="Close"
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-3">
+ <div className="flex items-center gap-2">
+ <Cloud size={14} className="text-violet-300" />
+ <h3 className="text-[0.85rem] font-semibold text-white">{copy.title}</h3>
+ <span className="ml-auto text-[0.55rem] font-medium uppercase tracking-widest text-violet-300/80">
+ LU Cloud
+ </span>
+ </div>
+ <p className="text-[0.7rem] leading-relaxed text-gray-400">{copy.line}</p>
+ <p className="text-[0.62rem] leading-relaxed text-gray-500">
+ {localLane
+ ? 'Runs on your PC with downloaded models, or on LU Cloud where datacenter GPUs do the heavy lifting.'
+ : 'Runs on LU Cloud. Your PC stays cool while datacenter GPUs do the heavy lifting.'}
+ </p>
+ <div className="flex items-center gap-2 pt-1">
+ <button
+ onClick={() => {
+ // Intent teasers detour through the example video popup
+ // (real footage of the tool); model rows go straight to
+ // the gate since there is no per model clip.
+ const t = target
+ close()
+ if (t.surface === 'intent') setCloudExampleVideo(t)
+ else setCloudGateOpen(true)
+ }}
+ className="flex-1 flex items-center justify-center gap-1.5 h-8 rounded-lg bg-white text-black text-[0.7rem] font-semibold hover:bg-gray-200 transition-colors"
+ >
+ <Sparkles size={12} /> {localLane ? 'Try cloud' : 'See plans'}
+ </button>
+ {localLane && (
+ <button
+ onClick={() => { close(); setIntent(localLane) }}
+ className="flex-1 flex items-center justify-center gap-1.5 h-8 rounded-lg border border-white/15 text-gray-200 text-[0.7rem] font-semibold hover:bg-white/[0.06] transition-colors"
+ >
+ <MonitorDown size={12} /> Try local
+ </button>
+ )}
+ <button
+ onClick={close}
+ className="px-3 h-8 rounded-lg text-[0.7rem] text-gray-400 hover:text-gray-200 hover:bg-white/[0.06] transition-colors"
+ >
+ Not now
+ </button>
+ </div>
+ </div>
+ </motion.div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+ }
+
+ // ── "Show me" demos — tiny looping motion sketches, one per tool. Pure
+ // CSS/SVG so they ship inside the bundle (no media assets, theme-crisp). ──
+
+ function TeaserDemo({ target }: { target: CloudTeaserTarget }) {
+ const kind = target.surface === 'intent' ? target.intent : target.kind === 'video' ? 'video-model' : 'image-model'
+ switch (kind) {
+ case 'upscale': return <UpscaleDemo />
+ case 'eraser': return <EraserDemo />
+ case 'character': return <CharacterDemo />
+ case 'lipsync': return <LipsyncDemo />
+ case 'music': return <MusicDemo />
+ case 'extend': return <ExtendDemo />
+ case 'motion': return <MotionDemo />
+ default: return <ModelDemo video={kind === 'video-model'} />
+ }
+ }
+
+ const LOOP = { duration: 2.6, repeat: Infinity, ease: 'easeInOut' as const }
+
+ function Stage({ children }: { children: React.ReactNode }) {
+ return <div className="absolute inset-0 flex items-center justify-center">{children}</div>
+ }
+
+ function UpscaleDemo() {
+ return (
+ <Stage>
+ <motion.div
+ className="w-20 h-20 rounded-lg bg-gradient-to-br from-violet-500/60 to-sky-500/60"
+ animate={{ filter: ['blur(6px)', 'blur(0px)', 'blur(0px)', 'blur(6px)'], scale: [0.8, 1.05, 1.05, 0.8] }}
+ transition={{ ...LOOP, duration: 3.2, times: [0, 0.4, 0.7, 1] }}
+ />
+ <motion.span
+ className="absolute text-[0.55rem] font-mono text-white/70"
+ animate={{ opacity: [0, 0, 1, 0] }}
+ transition={{ ...LOOP, duration: 3.2, times: [0, 0.4, 0.6, 1] }}
+ >
+ 4K
+ </motion.span>
+ </Stage>
+ )
+ }
+
+ function EraserDemo() {
+ return (
+ <Stage>
+ <div className="relative w-24 h-16 rounded-lg bg-gradient-to-br from-emerald-800/60 to-emerald-600/40">
+ <motion.div
+ className="absolute left-3 bottom-3 w-6 h-8 rounded-sm bg-amber-400/80"
+ animate={{ opacity: [1, 1, 0, 0, 1] }}
+ transition={{ ...LOOP, duration: 3, times: [0, 0.35, 0.55, 0.85, 1] }}
+ />
+ <motion.div
+ className="absolute w-3.5 h-3.5 rounded-full border-2 border-white/80 bg-white/20"
+ animate={{ x: [8, 20, 8], y: [18, 30, 18], opacity: [0, 1, 0] }}
+ transition={{ ...LOOP, duration: 3 }}
+ />
+ </div>
+ </Stage>
+ )
+ }
+
+ function CharacterDemo() {
+ return (
+ <Stage>
+ <div className="flex items-center gap-3">
+ <div className="grid grid-cols-2 gap-1">
+ {[0, 1, 2, 3].map((i) => (
+ <motion.div
+ key={i}
+ className="w-5 h-5 rounded-sm bg-white/25"
+ animate={{ opacity: [0.4, 1, 0.4] }}
+ transition={{ ...LOOP, delay: i * 0.18 }}
+ />
+ ))}
+ </div>
+ <motion.div animate={{ x: [0, 3, 0] }} transition={LOOP} className="text-gray-500 text-[0.7rem]">→</motion.div>
+ <motion.div
+ className="w-12 h-12 rounded-full bg-gradient-to-br from-violet-400/70 to-fuchsia-400/70 flex items-center justify-center"
+ animate={{ scale: [0.92, 1.06, 0.92] }}
+ transition={LOOP}
+ >
+ <Sparkles size={14} className="text-white/90" />
+ </motion.div>
+ </div>
+ </Stage>
+ )
+ }
+
+ function LipsyncDemo() {
+ return (
+ <Stage>
+ <div className="flex items-center gap-4">
+ <div className="relative w-14 h-14 rounded-full bg-white/15 flex items-end justify-center pb-3">
+ <div className="absolute top-4 flex gap-2.5">
+ <span className="w-1.5 h-1.5 rounded-full bg-white/70" />
+ <span className="w-1.5 h-1.5 rounded-full bg-white/70" />
+ </div>
+ <motion.div
+ className="w-4 rounded-full bg-rose-300/90"
+ animate={{ height: [2, 6, 3, 7, 2] }}
+ transition={{ duration: 1.1, repeat: Infinity, ease: 'easeInOut' }}
+ />
+ </div>
+ <div className="flex items-end gap-0.5 h-8">
+ {[10, 18, 26, 16, 22, 12, 20].map((h, i) => (
+ <motion.span
+ key={i}
+ className="w-1 rounded-full bg-violet-300/80"
+ animate={{ height: [h * 0.4, h, h * 0.4] }}
+ transition={{ duration: 0.9, repeat: Infinity, ease: 'easeInOut', delay: i * 0.09 }}
+ />
+ ))}
+ </div>
+ </div>
+ </Stage>
+ )
+ }
+
+ function MusicDemo() {
+ return (
+ <Stage>
+ <div className="flex items-end gap-1 h-12">
+ {[14, 26, 38, 22, 34, 18, 30, 24, 40, 16].map((h, i) => (
+ <motion.span
+ key={i}
+ className="w-1.5 rounded-full bg-gradient-to-t from-violet-500/80 to-sky-400/80"
+ animate={{ height: [h * 0.35, h, h * 0.35] }}
+ transition={{ duration: 1.1, repeat: Infinity, ease: 'easeInOut', delay: i * 0.07 }}
+ />
+ ))}
+ </div>
+ </Stage>
+ )
+ }
+
+ function ExtendDemo() {
+ return (
+ <Stage>
+ <div className="flex items-center gap-1">
+ {[0, 1, 2].map((i) => (
+ <div key={i} className="w-8 h-12 rounded-sm bg-white/20 border border-white/10" />
+ ))}
+ {[3, 4].map((i) => (
+ <motion.div
+ key={i}
+ className="w-8 h-12 rounded-sm bg-violet-400/50 border border-violet-300/30"
+ animate={{ opacity: [0, 0, 1, 1, 0], x: [-6, -6, 0, 0, -6] }}
+ transition={{ duration: 3, repeat: Infinity, ease: 'easeOut', times: [0, 0.2 + i * 0.12, 0.35 + i * 0.12, 0.85, 1] }}
+ />
+ ))}
+ </div>
+ </Stage>
+ )
+ }
+
+ function MotionDemo() {
+ return (
+ <Stage>
+ <div className="flex items-center gap-5">
+ <motion.div
+ className="w-8 h-14 rounded-md border-2 border-dashed border-white/40"
+ animate={{ rotate: [-9, 9, -9] }}
+ transition={LOOP}
+ />
+ <motion.div animate={{ opacity: [0.3, 1, 0.3] }} transition={LOOP} className="text-gray-500 text-[0.7rem]">→</motion.div>
+ <motion.div
+ className="w-8 h-14 rounded-md bg-gradient-to-b from-violet-400/80 to-fuchsia-500/70"
+ animate={{ rotate: [-9, 9, -9] }}
+ transition={{ ...LOOP, delay: 0.12 }}
+ />
+ </div>
+ </Stage>
+ )
+ }
+
+ function ModelDemo({ video }: { video: boolean }) {
+ return (
+ <Stage>
+ <motion.div
+ className={
+ video
+ ? 'w-24 h-14 rounded-lg bg-gradient-to-br from-sky-500/50 to-violet-500/50'
+ : 'w-16 h-16 rounded-lg bg-gradient-to-br from-violet-500/50 to-fuchsia-500/50'
+ }
+ animate={{ scale: [0.94, 1.04, 0.94], opacity: [0.7, 1, 0.7] }}
+ transition={LOOP}
+ >
+ <div className="w-full h-full flex items-center justify-center">
+ <Cloud size={18} className="text-white/80" />
+ </div>
+ </motion.div>
+ </Stage>
+ )
+ }
diff --cc src/components/create/experimental/CreateContext.tsx
index 08410383,0f4bfc9f..5b24daed
--- a/src/components/create/experimental/CreateContext.tsx
+++ b/src/components/create/experimental/CreateContext.tsx
@@@ -3,10 -3,12 +3,12 @@@ import { useCreate } from '../../../hoo
import { useCloudCreate, hasActiveCloudRun } from '../../../hooks/useCloudCreate'
import { useCloudSession } from '../../../hooks/useCloudSession'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
- import { getLoraModels, getVAEModels } from '../../../api/comfyui'
+ import { getLoraModels, getVAEModels, checkComfyConnection, refreshComfyModels } from '../../../api/comfyui'
import { getAllNodeInfo, clearNodeCache } from '../../../api/comfyui-nodes'
- import { installCustomNodes } from '../../../api/discover'
+ import { installCustomNodes, getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, startModelDownload, getDownloadProgress } from '../../../api/discover'
-import { backendCall } from '../../../api/backend'
+import { backendCall, isMacOS } from '../../../api/backend'
+ import { useDownloadStore } from '../../../stores/downloadStore'
+ import { downloadBundleFiles, waitOrAbort } from '../../../lib/bundle-install'
import { ensureLocalFilename } from './loadImage'
import type { CloudQuota } from '../../../lib/render/cloud-jobs'
@@@ -90,13 -133,9 +133,17 @@@ export function CreateExpProvider({ chi
}
}, [backend, connected])
- // Bootstrap the backend exactly like the old CreateView mount did. On
- // macOS skip the ComfyUI probe entirely — hard rule: Mac local media is
- // MLX-only and ComfyUI never auto-starts there (process.rs::auto_start_
- // comfyui). fetchModels() still runs unconditionally: it's what loads the
- // MLX image/video catalogs on Mac.
- // Bootstrap the backend exactly like the old CreateView mount did.
++ // Bootstrap the backend exactly like the old CreateView mount did. On macOS
++ // skip the ComfyUI probe entirely — hard rule: Mac local media is MLX-only
++ // and ComfyUI never auto-starts there (process.rs::auto_start_comfyui).
++ // Probing would pin `connected` to false, which is what the Stage's
++ // ModelInstallCard reads as "no models" — it would cover a perfectly working
++ // MLX catalog with a ComfyUI install card. Leaving it null means "not
++ // applicable", which every ComfyUI-gated surface already treats as neutral.
++ // fetchModels() still runs unconditionally: it's what loads the MLX
++ // image/video catalogs on Mac.
useEffect(() => {
- checkConnection()
+ if (!isMacOS()) checkConnection()
fetchModels()
}, [checkConnection, fetchModels])
diff --cc src/components/create/experimental/CreateExperimental.tsx
index a4b44be8,b542cc11..d44f5ff0
--- a/src/components/create/experimental/CreateExperimental.tsx
+++ b/src/components/create/experimental/CreateExperimental.tsx
@@@ -11,7 -12,7 +12,8 @@@ import { Lightbox } from './Lightbox
import { AdvancedDrawer } from './AdvancedDrawer'
import { MaskEditor } from './MaskEditor'
import { VhsInstallModal } from './VhsInstallModal'
--import { INTENT_MAP } from './intents'
++import { INTENT_MAP, isIntentAvailable } from './intents'
++import { isMlxImageHost } from '../../../api/mlx-image'
import { fetchGalleryItemBlob } from './galleryUrl'
import { loadImageRef } from './loadImage'
@@@ -57,6 -84,6 +85,13 @@@ function CreateExperimentalInner()
const displayed = shownId ? gallery.find((g) => g.id === shownId) : undefined
const banner = error ?? modelLoadError
++ // "Edit with mask" on a finished image force-sets the 'edit' intent. On the
++ // MLX Mac that lane does not exist (no ComfyUI inpaint nodes, and MLX
++ // generate DROPS the source + mask — it silently produced an unrelated fresh
++ // text-to-image instead of an edit). Hide the action where the lane can't
++ // run, using the same rule the IntentBar renders from.
++ const editAvailable = isIntentAvailable('edit', backend, isMlxImageHost())
++
// Pull a finished result back in as the working source (ImageRef). Needed
// because a text-to-image run leaves `source` empty — without this, "Edit
// with mask" on a result and switching to Edit/Upscale/Eraser/Animate were
@@@ -129,22 -156,71 +164,71 @@@
</div>
)}
- {/* Stage+Composer on the left, the Gallery bubble as a right rail —
- matched 1:1 with the web companion (the old bottom strip is gone). */}
- <div className="flex-1 min-h-0 flex overflow-hidden">
- <div className="flex-1 min-w-0 relative flex flex-col">
- <Stage
- displayed={displayed}
- onOpenMaskEditor={() => setMaskOpen(true)}
- onEditResult={backend === 'cloud' ? (it) => { void editResultWithMask(it) } : undefined}
- onFullscreen={(it) => setLightbox(it)}
- />
- <Composer onOpenAdvanced={() => setAdvancedOpen(true)} />
-
- <AdvancedDrawer open={advancedOpen} onClose={() => setAdvancedOpen(false)} />
- <MaskEditor open={maskOpen} onClose={() => setMaskOpen(false)} />
+ {/* Cross-origin block (#75, cinemazverev): a user-managed ComfyUI 0.19+
+ answers the WebView's media/WS requests with a Sec-Fetch 403, so results
+ couldn't be viewed. LU proxies the bytes so they still display, but the
+ live progress bar + native video seeking degrade. David 2026-07-17: keep
+ the message short and offer a one-click fix — LU restarts ComfyUI under
+ its own management, which always passes the CORS flag. Local only,
+ dismissible; the long manual-flag hint only appears if the fix fails. */}
+ {backend === 'local' && comfyCorsBlocked && (
+ <div className="flex items-start gap-2 px-4 py-2 bg-yellow-500/5 border-b border-yellow-500/10 text-yellow-300 text-xs shrink-0">
+ <AlertTriangle size={12} className="shrink-0 mt-0.5" />
+ <span className="flex-1 min-w-0">
+ {corsFixError
+ ? corsFixError
+ : corsFixing
+ ? 'Restarting ComfyUI with the fix… this takes a moment.'
+ : 'Your ComfyUI blocks direct loads (v0.19+), so previews use a slower fallback.'}
+ </span>
+ {!corsFixing && (
+ <button
+ onClick={() => { void fixCorsForMe() }}
+ disabled={isGenerating}
+ title={isGenerating ? 'Waiting for the current generation to finish' : 'LU restarts ComfyUI with the CORS flag for you'}
+ className="shrink-0 px-2 py-0.5 rounded bg-yellow-500/15 hover:bg-yellow-500/25 text-yellow-200 transition-colors whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ Let me do it for you!
+ </button>
+ )}
+ <button onClick={() => { setComfyCorsBlocked(false); setCorsFixError(null) }} className="shrink-0 text-yellow-300/70 hover:text-yellow-100" title="Dismiss">
+ <X size={14} />
+ </button>
</div>
+ )}
+ {/* Cloud gallery retention (David 2026-07-24). Cloud renders live on our
+ servers, not on this machine, so the gallery is not permanent storage.
+ Cloud mode only. One time ever: no close X and no auto-hide, the only
+ way out is the explicit "Do not show again", and it stays dismissed
+ across updates (persisted in lu_cloud_notice). */}
+ {shouldShowRetentionNotice(backend, retentionNoticeSeen) && (
+ <div className="flex items-start gap-2 px-4 py-2 bg-purple-500/5 border-b border-purple-500/10 text-purple-200 text-xs shrink-0">
+ <Cloud size={12} className="shrink-0 mt-0.5" />
+ <span className="flex-1 min-w-0">
+ Cloud results are stored for {CLOUD_RETENTION_DAYS} days and then deleted.
+ Download anything you want to keep from the gallery.
+ </span>
+ <button
+ onClick={() => setRetentionNoticeSeen(true)}
+ className="shrink-0 px-2 py-0.5 rounded bg-purple-500/15 hover:bg-purple-500/25 text-purple-100 transition-colors whitespace-nowrap"
+ >
+ Do not show again
+ </button>
+ </div>
+ )}
+
+ {/* The viewer (Stage) and the Gallery bubble share ONE row, so they're
+ always the exact same height; the prompt window spans the full width
+ beneath them. (Previously the Gallery ran full-height alongside both the
+ viewer AND the composer, so it was taller than the viewer.) */}
+ <div className="flex-1 min-h-0 flex overflow-hidden">
+ <Stage
+ displayed={displayed}
+ onOpenMaskEditor={() => setMaskOpen(true)}
- onEditResult={(it) => { void editResultWithMask(it) }}
++ onEditResult={editAvailable ? (it) => { void editResultWithMask(it) } : undefined}
+ onFullscreen={(it) => setLightbox(it)}
+ />
<CreatePanel open={panelOpen} onOpenChange={setPanelOpen} activeId={shownId} onSelect={openGalleryItem} />
</div>
diff --cc src/components/create/experimental/IntentBar.tsx
index 7cc0962d,3b790d0a..157596c9
--- a/src/components/create/experimental/IntentBar.tsx
+++ b/src/components/create/experimental/IntentBar.tsx
@@@ -1,6 -1,7 +1,8 @@@
+ import { Cloud } from 'lucide-react'
import { useCreateStore } from '../../../stores/createStore'
- import { visibleIntents } from './intents'
+ import { useUIStore, type CloudTeaserTarget } from '../../../stores/uiStore'
-import { INTENTS } from './intents'
++import { isIntentLocked, visibleIntents } from './intents'
+import { isMlxImageHost } from '../../../api/mlx-image'
import { cn } from '../ui/cn'
// Pure-CSS expand: no Framer layout projection anywhere, so nothing can snap or
@@@ -14,10 -17,14 +18,19 @@@ export function IntentBar()
const intent = useCreateStore((s) => s.intent())
const setIntent = useCreateStore((s) => s.setIntent)
const backend = useCreateStore((s) => s.backend)
- // setIntent's base already clears a stale utilityOp when the mode flips back
- // and the user picks any normal intent. Filtering (hosted-only ops + Mac's
- // missing RMBG node) lives in visibleIntents so it stays unit-tested.
- const intents = visibleIntents(backend, isMlxImageHost())
+ const setCloudTeaser = useUIStore((s) => s.setCloudTeaser)
+ // Every tool is always in the bar. The 2.5.8 lanes with hasLocalLane
+ // (lipsync / music / extend / motion) are REAL local tabs — plain selectable
+ // pills with NO cloud glyph (David 2026-07-19: the top row only carries a
+ // cloud badge for the genuinely hosted-only tools). Only upscale, eraser and
+ // character training (cloudOnly, no local backend) render as locked,
+ // cloud-tagged pills in local mode; a tap opens the teaser sheet / plans gate.
- const intents = INTENTS
++ //
++ // On an MLX Mac (no ComfyUI at all) those lanes have no local implementation
++ // either, so they lock there too. Both rules live in intents.ts so they stay
++ // pure + unit tested; this component only renders the verdict.
++ const mlxHost = isMlxImageHost()
++ const intents = visibleIntents(backend, mlxHost)
return (
<div
@@@ -29,7 -36,8 +42,8 @@@
style={{ transform: 'scale(0.763)', transformOrigin: 'center' }}
>
{intents.map((meta) => {
- const selected = intent === meta.id
- const locked = meta.cloudOnly === true && !meta.hasLocalLane && backend !== 'cloud'
++ const locked = isIntentLocked(meta, backend, mlxHost)
+ const selected = !locked && intent === meta.id
const Icon = meta.icon
return (
<button
diff --cc src/components/create/experimental/ParamGroups.tsx
index 4a6bba1a,7d930b80..7b94a1f7
--- a/src/components/create/experimental/ParamGroups.tsx
+++ b/src/components/create/experimental/ParamGroups.tsx
@@@ -2,8 -2,8 +2,9 @@@ import { Gauge, Boxes, FlaskConical, Ro
import { useCreateStore } from '../../../stores/createStore'
import { useCreateExp } from './CreateContext'
import { cloudModelById, defaultCloudModel } from '../../../stores/cloudCatalogStore'
- import { INTENT_MAP } from './intents'
+ import { classifyModel } from '../../../api/comfyui'
+import { isMlxImageHost } from '../../../api/mlx-image'
+ import { INTENT_MAP } from './intents'
import { SAMPLERS as SAMPLERS_FALLBACK, SCHEDULERS as SCHEDULERS_FALLBACK } from './badges'
import { Section } from '../ui/Section'
import { Slider } from '../ui/Slider'
@@@ -23,11 -30,9 +31,15 @@@ export function ParamGroups()
const isVideo = meta.isVideo
const isEdit = meta.id === 'edit'
const isCloud = s.backend === 'cloud'
+ // The Mac's MLX pipeline only honours prompt/steps/seed/size/negative — every
- // Expert knob (sampler, scheduler, VAE, clip-skip; LoRA/denoise/mask are
- // already hidden locally) is silently dropped there, so the whole Expert
- // section is dead on the local Mac. Keep it on Mac-cloud and Windows/Linux.
++ // Expert knob (sampler, scheduler, VAE, clip-skip; LoRA has no list without
++ // ComfyUI, and denoise/mask belong to intents that aren't local there) is
++ // silently dropped, so the whole Expert section is dead on the local Mac.
++ // Keep it on Mac-cloud and on the ComfyUI hosts (Windows/Linux).
+ const isMlxLocal = !isCloud && isMlxImageHost()
+ // LoRA is a local-only knob; for video it's offered only on families whose
+ // builder actually applies it (see VIDEO_LORA_FAMILIES). Image always qualifies.
+ const loraSupported = !isCloud && (!isVideo || VIDEO_LORA_FAMILIES.has(classifyModel(s.videoModel)))
// On cloud the worker only honours steps for images and guidance_scale for
// the flux family — hide the sliders elsewhere rather than show a dead
@@@ -70,9 -75,7 +82,9 @@@
)}
</Section>
- {/* EXPERT — every control here is dropped by the Mac MLX pipeline, so the
- whole section is hidden on the local Mac (shown on cloud + ComfyUI). */}
- {/* EXPERT */}
++ {/* EXPERT — every control in here is dropped by the Mac MLX pipeline, so
++ the whole section is hidden on the local Mac (kept on cloud + ComfyUI). */}
+ {!isMlxLocal && (
<Section title="Expert" icon={FlaskConical} defaultOpen={false}>
{/* Sampler/Scheduler are ComfyUI-only knobs — the hosted WaveSpeed
endpoints don't accept them, so hide them on the cloud backend
diff --cc src/components/create/experimental/Stage.tsx
index 6938a5d1,19d5f6d1..889aadae
--- a/src/components/create/experimental/Stage.tsx
+++ b/src/components/create/experimental/Stage.tsx
@@@ -15,9 -16,8 +16,10 @@@ interface Props
displayed?: GalleryItem
onOpenMaskEditor: () => void
/** Adopt a finished result as the edit source, THEN open the mask editor —
-- * a t2i run leaves `source` empty, and the editor always reads `source`. */
- /** Absent on the local backend — inpainting/edit is a cloud-only op. */
- onEditResult: (item: GalleryItem) => void
++ * a t2i run leaves `source` empty, and the editor always reads `source`.
++ * Absent where the Edit intent has no working local lane (the MLX Mac),
++ * so the button only shows where inpainting actually runs. */
+ onEditResult?: (item: GalleryItem) => void
onFullscreen: (item: GalleryItem) => void
}
diff --cc src/components/create/experimental/__tests__/intents.test.ts
index be7b5e1b,612c3083..2391082d
--- a/src/components/create/experimental/__tests__/intents.test.ts
+++ b/src/components/create/experimental/__tests__/intents.test.ts
@@@ -1,13 -1,21 +1,31 @@@
import { describe, it, expect } from 'vitest'
- import { INTENT_MAP, visibleIntents } from '../intents'
-import { INTENTS, INTENT_MAP } from '../intents'
++import { INTENTS, INTENT_MAP, isIntentAvailable, isIntentLocked, visibleIntents } from '../intents'
+ import { LOCAL_LANE_OPS } from '../../../../stores/createStore'
+
+ // David 2026-07-10 made the advanced ops cloud-only; David 2026-07-12 brought
+ // Edit BACK to local as the 4th local tab (checkpoint mask inpaint —
+ // VAEEncodeForInpaint / InpaintModelConditioning); David 2026-07-17 brought
+ // Animate (local I2V) back as the 5th. 2.5.8 gives FOUR specialized categories
+ // REAL local lanes (hasLocalLane): music / lipsync / extend / motion on core
+ // ComfyUI node families (motion additionally needs the DWPose pack, which
+ // loads fine on Windows via the OpenCV CPU fallback). Upscale, eraser AND
+ // character stay hosted-only — character training is cloud-first (David
+ // 2026-07-19) until a local trainer runtime ships.
++/** The pills the bar shows, in order. */
++const shown = (backend: 'local' | 'cloud', mlxHost: boolean) =>
++ visibleIntents(backend, mlxHost).map((m) => m.id)
++/** The pills a user can actually select (no cloud-teaser lock). */
++const unlocked = (backend: 'local' | 'cloud', mlxHost: boolean) =>
++ visibleIntents(backend, mlxHost).filter((m) => !isIntentLocked(m, backend, mlxHost)).map((m) => m.id)
++/** The pills shown as locked, cloud-tagged teasers. */
++const teasers = (backend: 'local' | 'cloud', mlxHost: boolean) =>
++ visibleIntents(backend, mlxHost).filter((m) => isIntentLocked(m, backend, mlxHost)).map((m) => m.id)
+
- // David 2026-07-10: the advanced ops have no local models — they exist only on
- // the cloud backend. Only plain generation and removebg (local RMBG node,
- // rhodium92/e9aab21) keep a local lane.
describe('intent cloud gating', () => {
- it('edit, animate, upscale and eraser are cloud-only', () => {
- for (const id of ['edit', 'animate', 'upscale', 'eraser'] as const) {
+ it('upscale, eraser and character stay hosted-only (no local lane)', () => {
+ for (const id of ['upscale', 'eraser', 'character'] as const) {
expect(INTENT_MAP[id].cloudOnly, id).toBe(true)
+ expect(INTENT_MAP[id].hasLocalLane, id).toBeUndefined()
}
})
@@@ -17,20 -25,47 +35,114 @@@
}
})
- it('the local (non-Mac) IntentBar filter keeps exactly the local lane', () => {
- const local = visibleIntents('local', false).map((m) => m.id)
- expect(local).toEqual(['image', 'removebg', 'video'])
+ it('the 2.5.8 lanes are dual: hosted clip AND a local lane', () => {
+ for (const id of ['music', 'lipsync', 'extend', 'motion'] as const) {
+ expect(INTENT_MAP[id].cloudOnly, id).toBe(true)
+ expect(INTENT_MAP[id].hasLocalLane, id).toBe(true)
+ }
+ })
+
+ it('intent metadata mirrors the store LOCAL_LANE_OPS set exactly', () => {
+ const fromMeta = INTENTS.filter((m) => m.hasLocalLane).map((m) => m.id).sort()
+ expect(fromMeta).toEqual([...LOCAL_LANE_OPS].sort())
+ })
+
+ it('the local IntentBar filter keeps the 5 classic tabs plus the 4 lanes selectable', () => {
+ const selectable = INTENTS.filter((m) => !m.cloudOnly || m.hasLocalLane).map((m) => m.id)
+ expect(selectable).toEqual(['image', 'edit', 'removebg', 'video', 'animate', 'lipsync', 'music', 'extend', 'motion'])
++ // …and that IS what the pure filter reports for a ComfyUI local host.
++ expect(unlocked('local', false)).toEqual(selectable)
})
- it('the local Mac filter drops removebg (no ComfyUI RMBG node there)', () => {
- // MLX-only Mac has no ComfyUI, so RMBG can't run locally — only plain image
- // and video generation remain on the local Mac lane.
- const localMac = visibleIntents('local', true).map((m) => m.id)
- expect(localMac).toEqual(['image', 'video'])
+ it('local edit gates on the inpaint capability + image models', () => {
+ expect(INTENT_MAP.edit.capability).toBe('inpaint-nodes')
+ expect(INTENT_MAP.edit.requiresModels).toBe('image')
+ expect(INTENT_MAP.edit.allowsMask).toBe(true)
+ // The fresh-PC Download & install card also covers plain generation.
+ expect(INTENT_MAP.image.requiresModels).toBe('image')
+ expect(INTENT_MAP.video.requiresModels).toBe('video')
})
- it('cloud keeps every intent regardless of host', () => {
- const cloud = visibleIntents('cloud', true).map((m) => m.id)
- expect(cloud).toEqual(['image', 'edit', 'removebg', 'upscale', 'eraser', 'video', 'animate'])
+ it('local animate needs a source image and gates on video models', () => {
+ expect(INTENT_MAP.animate.needsSource).toBe(true)
+ expect(INTENT_MAP.animate.isVideo).toBe(true)
+ expect(INTENT_MAP.animate.requiresModels).toBe('video')
+ })
+
+ it('the lanes gate on their own model kinds', () => {
+ expect(INTENT_MAP.music.requiresModels).toBe('audio')
+ expect(INTENT_MAP.lipsync.requiresModels).toBe('lipsync')
+ // Extend rides the regular i2v-capable video list (last-frame continue).
+ expect(INTENT_MAP.extend.requiresModels).toBe('video')
+ // Motion gates on the VACE/Animate model list AND the DWPose pack.
+ expect(INTENT_MAP.motion.requiresModels).toBe('motion')
+ expect(INTENT_MAP.motion.capability).toBe('dwpose')
+ // Character is hosted-only — no local model gate.
+ expect(INTENT_MAP.character.requiresModels).toBeUndefined()
+ })
+ })
++
++// The Mac has NO ComfyUI (hard product rule): its local media is the
++// in-process MLX path, which runs plain text-to-image and text-to-video and
++// nothing else. Every other lane's "local" implementation is a ComfyUI graph
++// (RMBG cutout, inpaint nodes, ACE music, Wan S2V, VACE/DWPose) and every
++// source-needing lane additionally stages its input through ComfyUI's
++// /upload/image, which does not exist there either. So on a local MLX Mac an
++// intent must never render as an active local tab unless MLX really runs it.
++describe('intent gating on a local MLX Mac (no ComfyUI)', () => {
++ it('only image and video stay real local tabs', () => {
++ expect(unlocked('local', true)).toEqual(['image', 'video'])
++ })
++
++ it('the hosted-only tools AND the 2.5.8 lanes become cloud teasers', () => {
++ // Same locked pill + ", runs on LU Cloud" label the 2.6.0 bar already
++ // uses — visible, honest, and it opens the teaser sheet on tap.
++ expect(teasers('local', true)).toEqual(['upscale', 'eraser', 'character', 'lipsync', 'music', 'extend', 'motion'])
++ })
++
++ it('every Mac teaser has a cloud endpoint to teased about', () => {
++ for (const id of teasers('local', true)) {
++ expect(INTENT_MAP[id].cloudOnly, id).toBe(true)
++ }
++ })
++
++ it('edit, removebg and animate are hidden rather than shown as dead tabs', () => {
++ // No hosted-only flag means no teaser sheet exists for them, and MLX
++ // silently DROPS a source + mask (it only takes prompt/steps/seed/size/
++ // negative) — which produced an unrelated fresh image instead of an edit.
++ // Hiding is the only honest state left.
++ const hidden = INTENTS.map((m) => m.id).filter((id) => !shown('local', true).includes(id))
++ expect(hidden).toEqual(['edit', 'removebg', 'animate'])
++ })
++
++ it('nothing is hidden on cloud or on a ComfyUI local host', () => {
++ expect(shown('cloud', true)).toEqual(INTENTS.map((m) => m.id))
++ expect(shown('cloud', false)).toEqual(INTENTS.map((m) => m.id))
++ expect(shown('local', false)).toEqual(INTENTS.map((m) => m.id))
++ })
++
++ it('cloud unlocks every intent regardless of host', () => {
++ expect(unlocked('cloud', true)).toEqual(INTENTS.map((m) => m.id))
++ expect(teasers('cloud', true)).toEqual([])
++ })
++
++ it('a Mac on the cloud backend is unaffected by the MLX rule', () => {
++ expect(unlocked('cloud', true)).toEqual(unlocked('cloud', false))
++ })
++
++ it("isIntentAvailable gates the result's 'Edit with mask' action the same way", () => {
++ // The action force-sets 'edit'; it must vanish exactly where the tab does.
++ expect(isIntentAvailable('edit', 'local', true)).toBe(false)
++ expect(isIntentAvailable('edit', 'local', false)).toBe(true)
++ expect(isIntentAvailable('edit', 'cloud', true)).toBe(true)
++ // And it agrees with the bar for every intent, on every backend/host.
++ for (const backend of ['local', 'cloud'] as const) {
++ for (const mlxHost of [true, false]) {
++ for (const m of INTENTS) {
++ expect(isIntentAvailable(m.id, backend, mlxHost), `${m.id}/${backend}/${mlxHost}`)
++ .toBe(unlocked(backend, mlxHost).includes(m.id))
++ }
++ }
++ }
+ })
+})
diff --cc src/components/create/experimental/intents.ts
index 661a33ed,d40e4116..70ba1f77
--- a/src/components/create/experimental/intents.ts
+++ b/src/components/create/experimental/intents.ts
@@@ -1,6 -1,9 +1,9 @@@
- import { Image as ImageIcon, Wand2, Scissors, Video, Film, Maximize2, Eraser } from 'lucide-react'
+ import {
+ Image as ImageIcon, Wand2, Scissors, Video, Film, Maximize2, Eraser,
+ UserRound, Mic, Music, FastForward, PersonStanding,
+ } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
--import type { CreateIntent } from '../../../stores/createStore'
++import type { CreateBackend, CreateIntent } from '../../../stores/createStore'
export interface IntentMeta {
id: CreateIntent
@@@ -75,19 -158,3 +158,59 @@@ export const INTENTS: IntentMeta[] =
export const INTENT_MAP: Record<CreateIntent, IntentMeta> =
Object.fromEntries(INTENTS.map((i) => [i.id, i])) as Record<CreateIntent, IntentMeta>
+
+/**
- * The intents to surface for a given backend + host. Utility intents
- * (edit/upscale/eraser/animate) are hosted-only endpoints. Remove-Background
- * runs through the ComfyUI RMBG node, which never exists on the Mac (MLX-only,
- * no ComfyUI) — so on the local Mac it is hidden too, otherwise it's a dead
- * affordance that only errors on submit. Cloud and non-Mac local keep it.
++ * The intents that have a REAL local pipeline on an MLX host (Apple Silicon
++ * Mac). Every local lane above is a ComfyUI graph, and the Mac has no ComfyUI
++ * at all — its local media is the in-process MLX path (api/mlx-image.ts,
++ * api/mlx-video.ts). MLX generate accepts prompt / steps / seed / size /
++ * negative and nothing else, and there is no ComfyUI /upload/image to stage a
++ * source through (loadImageRef's local branch uploads there), so plain
++ * text-to-image and text-to-video are the only intents that actually run.
++ *
++ * Everything else must NOT look like a working local tab — see visibleIntents
++ * / isIntentLocked below.
++ */
++const MLX_LOCAL_INTENTS: ReadonlySet<CreateIntent> = new Set<CreateIntent>(['image', 'video'])
++
++/**
++ * The intents to surface for a given backend + host. Pure so the rule is unit
++ * tested instead of buried in the IntentBar's JSX.
++ *
++ * Cloud shows everything. Local (ComfyUI, Windows/Linux) also shows
++ * everything — the hosted-only tools render as locked cloud teasers rather
++ * than disappearing. Local on an MLX Mac hides the intents that have neither a
++ * local MLX path nor a hosted teaser sheet (edit, removebg, animate): they
++ * need a ComfyUI node or a ComfyUI-staged source image, so leaving them
++ * selectable is a dead affordance that either errors on submit or — worse, the
++ * MLX case — silently drops the source and returns an unrelated fresh image.
++ */
++export function visibleIntents(backend: CreateBackend, mlxHost: boolean): IntentMeta[] {
++ if (backend === 'cloud' || !mlxHost) return INTENTS
++ return INTENTS.filter((m) => MLX_LOCAL_INTENTS.has(m.id) || m.cloudOnly === true)
++}
++
++/**
++ * Whether an intent renders as a locked cloud teaser instead of a selectable
++ * local tab. Cloud never locks. On local ComfyUI hosts only the genuinely
++ * hosted-only tools lock (the 2.5.8 lanes with hasLocalLane are real local
++ * tabs). On an MLX Mac every non-MLX intent that survives visibleIntents locks
++ * — those lanes' "local" implementation is a ComfyUI graph this host does not
++ * have, so the honest state is the cloud teaser, not a working-looking pill.
++ */
++export function isIntentLocked(meta: IntentMeta, backend: CreateBackend, mlxHost: boolean): boolean {
++ if (backend === 'cloud') return false
++ if (mlxHost) return !MLX_LOCAL_INTENTS.has(meta.id)
++ return meta.cloudOnly === true && !meta.hasLocalLane
++}
++
++/**
++ * Whether an intent is reachable as a working tab (shown AND not a locked
++ * teaser) for this backend + host. Same rule as the IntentBar, exposed for the
++ * result actions that FORCE-switch to an intent — "Edit with mask" on a
++ * finished image used to set 'edit' even where that lane cannot run.
+ */
- export function visibleIntents(backend: 'local' | 'cloud', mlxHost: boolean): IntentMeta[] {
- const localMac = backend !== 'cloud' && mlxHost
- return INTENTS.filter((m) => {
- if (m.cloudOnly && backend !== 'cloud') return false
- if (m.capability === 'rmbg' && localMac) return false
- return true
- })
++export function isIntentAvailable(id: CreateIntent, backend: CreateBackend, mlxHost: boolean): boolean {
++ const meta = INTENT_MAP[id]
++ return visibleIntents(backend, mlxHost).includes(meta) && !isIntentLocked(meta, backend, mlxHost)
+}
diff --cc src/components/models/ModelManager.tsx
index bbd70e67,938400c5..9c17d8a2
--- a/src/components/models/ModelManager.tsx
+++ b/src/components/models/ModelManager.tsx
@@@ -13,19 -13,20 +13,21 @@@ import { DiscoverModels } from './Disco
import { Modal } from '../ui/Modal'
import { GlowButton } from '../ui/GlowButton'
import { showModel } from '../../api/ollama'
- import { checkComfyConnection } from '../../api/comfyui'
+ import { checkComfyConnection, refreshComfyModels } from '../../api/comfyui'
+import { isMlxImageHost } from '../../api/mlx-image'
+ import { backendCall } from '../../api/backend'
import type { ModelCategory, AIModel } from '../../types/models'
- // Three-mode filter shared by both Installed and Discover banners. There is no
- // "All" tab — the Installed view shows the active mode's section instead, so
- // the toggle stays a clean three-choice control.
+ // One category drives BOTH views (Discover + Installed) — the old split
+ // discoverMode/categoryFilter pair collapsed into the persisted store value.
type Mode = Extract<ModelCategory, 'text' | 'image' | 'video'>
- const MODE_TABS: { key: Mode; label: string; icon: typeof MessageSquare; accent: string }[] = [
- { key: 'text', label: 'Text', icon: MessageSquare, accent: 'text-blue-400' },
- { key: 'image', label: 'Image', icon: Image, accent: 'text-purple-400' },
- { key: 'video', label: 'Video', icon: Video, accent: 'text-emerald-400' },
+ // Monochrome on purpose — the active state is carried by the pill background,
+ // not by per-category accent colors (David 2026-07-17 design pass).
+ const RAIL_ITEMS: { key: Mode; label: string; icon: typeof MessagesSquare }[] = [
+ { key: 'text', label: 'Chat', icon: MessagesSquare },
+ { key: 'image', label: 'Image', icon: Images },
+ { key: 'video', label: 'Video', icon: Clapperboard },
]
export function ModelManager() {
@@@ -63,16 -55,9 +56,17 @@@
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
- // The Installed banner is driven by the same Mode tuple as Discover. On the
- // Mac, image/video models are ComfyUI-only here (MLX has no manager surface
- // yet), so the whole media lane is dead — pin the mode to text so a persisted
- // image/video filter never renders the "Start ComfyUI" dead state.
- const mode: Mode = (categoryFilter === 'text' || categoryFilter === 'image' || categoryFilter === 'video')
- ? categoryFilter
- : 'text'
++ // On the Mac, image/video models are ComfyUI-only here (MLX has no manager
++ // surface yet), so the whole media lane is dead — Discover → Install rejects
++ // with "ComfyUI path not set" and Installed shows a "Start ComfyUI" state that
++ // can never resolve. Pin the mode to text so a persisted image/video filter
++ // never lands on it, and drop the two rail items below.
+ const macTextOnly = isMlxImageHost()
- const installedMode: Mode = macTextOnly
++ const mode: Mode = macTextOnly
+ ? 'text'
+ : (categoryFilter === 'text' || categoryFilter === 'image' || categoryFilter === 'video')
+ ? categoryFilter
+ : 'text'
useEffect(() => {
fetchModels()
@@@ -122,11 -123,45 +132,45 @@@
// ── Render ──────────────────────────────────────────────────────
return (
- <div className="h-full overflow-y-auto scrollbar-thin p-4">
- {/* Header — bounded to the same column as the model list so the back
- arrow and title line up with the cards beneath. */}
- <div className="max-w-4xl mx-auto">
- <div className="flex items-center justify-between mb-4">
+ <div className="h-full flex overflow-hidden">
+ {/* Category rail — the big, labeled home of Chat / Image / Video */}
+ <aside className="shrink-0 w-12 lg:w-36 border-r border-gray-200 dark:border-white/[0.06] bg-gray-50/60 dark:bg-white/[0.015] flex flex-col py-3 px-1.5 lg:px-2 gap-1">
- {RAIL_ITEMS.map(({ key, label, icon: Icon }) => {
++ {RAIL_ITEMS.filter((r) => !macTextOnly || r.key === 'text').map(({ key, label, icon: Icon }) => {
+ const active = mode === key
+ const count = models.filter((m) => m.type === key).length
+ return (
+ <button
+ key={key}
+ onClick={() => setCategoryFilter(key)}
+ title={label}
+ aria-pressed={active}
+ className={`flex items-center justify-center lg:justify-start gap-2 px-2 py-2 rounded-lg transition-colors ${
+ active
+ ? 'bg-white dark:bg-white/[0.08] shadow-sm border border-gray-200 dark:border-white/[0.08]'
+ : 'border border-transparent hover:bg-gray-100 dark:hover:bg-white/[0.04]'
+ }`}
+ >
+ <Icon size={15} className={active ? 'text-gray-800 dark:text-gray-100' : 'text-gray-400 dark:text-gray-500'} />
+ <span className={`hidden lg:block text-[0.68rem] font-medium ${active ? 'text-gray-900 dark:text-white' : 'text-gray-500 dark:text-gray-400'}`}>
+ {label}
+ </span>
+ {count > 0 && (
+ <span className="hidden lg:block ml-auto text-[0.55rem] text-gray-400 dark:text-gray-500 tabular-nums">{count}</span>
+ )}
+ </button>
+ )
+ })}
+ <div className="mt-auto hidden lg:block px-2 pb-1 text-[0.5rem] leading-relaxed text-gray-400 dark:text-gray-600">
+ Models run 100% on your computer.
+ </div>
+ </aside>
+
+ {/* Content */}
+ <div className="flex-1 min-w-0 overflow-y-auto scrollbar-thin">
+ {/* Full pane width like the chat area — no centered max-w cap, so wide
+ windows get more grid columns instead of side gutters. */}
+ <div className="p-4 space-y-4">
+ {/* Top bar */}
<div className="flex items-center gap-2">
<button
onClick={() => setView('chat')}
@@@ -208,152 -240,127 +249,127 @@@
</button>
)}
</div>
- </div>
- </div>
- {/* Banner — rendered OUTSIDE the max-w-4xl column so it sits at the true
- horizontal centre of the view. */}
- <div className="flex justify-center items-center gap-2 mb-5">
- <div className="flex gap-0.5 p-0.5 bg-gray-100 dark:bg-white/[0.04] rounded-lg border border-gray-200 dark:border-white/[0.06]">
- {MODE_TABS.filter((t) => !macTextOnly || t.key === 'text').map(({ key, label, icon: Icon, accent }) => {
- const active = tab === 'installed' ? installedMode === key : discoverMode === key
- const count = tab === 'installed' ? models.filter((m) => m.type === key).length : null
- return (
- <button
- key={key}
- onClick={() => {
- if (tab === 'installed') setCategoryFilter(key)
- else setDiscoverMode(key)
- }}
- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[0.6rem] font-medium transition-all ${
- active
- ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm'
- : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
- }`}
- >
- <Icon size={10} className={active ? accent : ''} />
- <span>{label}</span>
- {count !== null && (
- <span className={`text-[0.55rem] font-normal ${active ? 'text-gray-400 dark:text-gray-500' : 'text-gray-400 dark:text-gray-600'}`}>
- {count}
- </span>
- )}
- </button>
- )
- })}
- </div>
- </div>
-
- {/* Content column */}
- <div className="max-w-4xl mx-auto">
- {tab === 'installed' && (
- <>
- {imageOrVideo && filteredModels.length === 0 && comfyReachable !== true ? (
- // comfyReachable: null = still probing, false = confirmed down.
- // Never show the misleading "no models installed" here while the
- // probe is pending — on desktop checkComfyConnection has to time
- // out when ComfyUI is down (a few seconds), and that flashed the
- // wrong message before the hint appeared (caught in desktop E2E).
- comfyReachable === null ? (
- <div className="text-center py-16 px-6">
- <p className="text-[0.7rem] text-gray-500">Checking ComfyUI…</p>
+ {/* Views */}
+ {tab === 'installed' && (
+ <>
+ {imageOrVideo && filteredModels.length === 0 && comfyReachable !== true ? (
+ // comfyReachable: null = still probing, false = confirmed down.
+ // Never show the misleading "no models installed" here while the
+ // probe is pending — on desktop checkComfyConnection has to time
+ // out when ComfyUI is down (a few seconds), and that flashed the
+ // wrong message before the hint appeared (caught in desktop E2E).
+ comfyReachable === null ? (
+ <div className="text-center py-16 px-6">
+ <p className="text-[0.7rem] text-gray-500">Checking ComfyUI…</p>
+ </div>
+ ) : (
+ <div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">
+ <div className="w-14 h-14 rounded-full bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] flex items-center justify-center">
+ {mode === 'video' ? <VideoIcon size={22} className="text-gray-400 dark:text-gray-500" /> : <ImageIcon size={22} className="text-gray-400 dark:text-gray-500" />}
+ </div>
+ <div className="space-y-1">
+ <p className="text-[0.75rem] font-medium text-gray-800 dark:text-gray-200">Start ComfyUI to see your {mode} models</p>
+ <p className="text-[0.6rem] text-gray-500 max-w-[300px] leading-relaxed">
+ {mode === 'image' ? 'Image' : 'Video'} models are served by ComfyUI, which isn't running right now, so the ones you've downloaded can't be listed yet. Open the Create tab and start ComfyUI (the power button next to the model picker), then come back.
+ </p>
+ </div>
+ <button
+ onClick={() => setView('create')}
+ className="flex items-center gap-1.5 mt-1 px-3 py-1.5 rounded-md bg-gray-900 dark:bg-white/10 hover:bg-gray-800 dark:hover:bg-white/15 text-white text-[0.65rem] font-medium transition-colors"
+ >
+ <Sparkles size={11} /> Go to Create
+ </button>
</div>
- ) : (
- <div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">
- <div className="w-14 h-14 rounded-full bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] flex items-center justify-center">
- {installedMode === 'video' ? <Video size={22} className="text-gray-400 dark:text-gray-500" /> : <Image size={22} className="text-gray-400 dark:text-gray-500" />}
- </div>
- <div className="space-y-1">
- <p className="text-[0.75rem] font-medium text-gray-800 dark:text-gray-200">Start ComfyUI to see your {installedMode} models</p>
- <p className="text-[0.6rem] text-gray-500 max-w-[300px] leading-relaxed">
- {installedMode === 'image' ? 'Image' : 'Video'} models are served by ComfyUI, which isn't running right now — so the ones you've downloaded can't be listed yet. Open the Create tab and start ComfyUI (the power button next to the model picker), then come back.
- </p>
- </div>
- <button
- onClick={() => setView('create')}
- className="flex items-center gap-1.5 mt-1 px-3 py-1.5 rounded-md bg-gray-900 dark:bg-white/10 hover:bg-gray-800 dark:hover:bg-white/15 text-white text-[0.65rem] font-medium transition-colors"
- >
- <Sparkles size={11} /> Go to Create
- </button>
- </div>
- )
- ) : models.length === 0 ? (
- <div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">
- <div className="w-14 h-14 rounded-full bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] flex items-center justify-center">
- <PackageOpen size={22} className="text-gray-400 dark:text-gray-500" />
+ )
+ ) : models.length === 0 ? (
+ <div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">
+ <div className="w-14 h-14 rounded-full bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] flex items-center justify-center">
+ <PackageOpen size={22} className="text-gray-400 dark:text-gray-500" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[0.75rem] font-medium text-gray-800 dark:text-gray-200">No models installed yet</p>
+ <p className="text-[0.6rem] text-gray-500 max-w-[280px] leading-relaxed">
+ Browse curated chat, image and video models and install them with one click.
+ </p>
+ </div>
+ <button
+ onClick={() => setTab('discover')}
+ className="flex items-center gap-1.5 mt-1 px-3 py-1.5 rounded-md bg-gray-900 dark:bg-white/10 hover:bg-gray-800 dark:hover:bg-white/15 text-white text-[0.65rem] font-medium transition-colors"
+ >
+ <Sparkles size={11} /> Discover models
+ </button>
</div>
- <div className="space-y-1">
- <p className="text-[0.75rem] font-medium text-gray-800 dark:text-gray-200">No models installed yet</p>
- <p className="text-[0.6rem] text-gray-500 max-w-[280px] leading-relaxed">
- Browse curated text, image and video models in Discover and install them with one click.
+ ) : filteredModels.length === 0 ? (
+ <div className="text-center py-10 space-y-2">
+ <p className="text-[0.7rem] text-gray-500">
+ No {modeMeta.label.toLowerCase()} models installed
</p>
+ <button
+ onClick={() => setTab('discover')}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-[0.65rem] text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"
+ >
+ <Sparkles size={11} /> Discover {modeMeta.label.toLowerCase()} models
+ </button>
</div>
- <button
- onClick={() => setTab('discover')}
- className="flex items-center gap-1.5 mt-1 px-3 py-1.5 rounded-md bg-gray-900 dark:bg-white/10 hover:bg-gray-800 dark:hover:bg-white/15 text-white text-[0.65rem] font-medium transition-colors"
- >
- <Sparkles size={11} /> Discover models
- </button>
- </div>
- ) : filteredModels.length === 0 ? (
- <div className="text-center py-10 space-y-2">
- <p className="text-[0.7rem] text-gray-500">
- No {installedMode} models installed
- </p>
- <button
- onClick={() => setTab('discover')}
- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-[0.65rem] text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"
- >
- <Sparkles size={11} /> Discover {installedMode} models
- </button>
- </div>
- ) : (
- (() => {
- const meta = MODE_TABS.find((s) => s.key === installedMode)!
- const SectionIcon = meta.icon
- return (
- <section className="space-y-1.5">
- <div className="flex items-center gap-2 px-1">
- <SectionIcon size={11} className={meta.accent} />
- <h2 className="text-[0.62rem] font-semibold uppercase tracking-[0.12em] text-gray-700 dark:text-gray-300">
- {meta.label}
- </h2>
- <span className="text-[0.55rem] text-gray-400 dark:text-gray-500 tabular-nums">{filteredModels.length}</span>
- <div className="flex-1 h-px bg-gray-200 dark:bg-white/[0.06]" />
- </div>
- <div className="space-y-1.5">
- {filteredModels.map((model, i) => (
- <motion.div
- key={model.name}
- initial={{ opacity: 0, y: 4 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: i * 0.015 }}
- >
- <ModelCard
- model={model}
- isActive={model.name === activeModel}
- onSelect={() => setActiveModel(model.name)}
- onDelete={() => setConfirmDelete(model.name)}
- onInfo={() => handleInfo(model.name)}
- canDelete={ollamaEnabled && model.type === 'text' && (!('provider' in model) || model.provider === 'ollama')}
- />
- </motion.div>
- ))}
- </div>
- </section>
- )
- })()
- )}
- </>
- )}
+ ) : (
+ (() => {
+ const SectionIcon = modeMeta.icon
+ const shown = searchQuery
+ ? filteredModels.filter(m => m.name.toLowerCase().includes(searchQuery.toLowerCase()))
+ : filteredModels
+ return (
+ <section className="space-y-1.5">
+ <div className="flex items-center gap-2 px-1">
- <SectionIcon size={11} className={modeMeta.accent} />
++ <SectionIcon size={11} />
+ <h2 className="text-[0.62rem] font-semibold uppercase tracking-[0.12em] text-gray-700 dark:text-gray-300">
+ {modeMeta.label}
+ </h2>
+ <span className="text-[0.55rem] text-gray-400 dark:text-gray-500 tabular-nums">{shown.length}</span>
+ <div className="flex-1 h-px bg-gray-200 dark:bg-white/[0.06]" />
+ </div>
+ <div className="space-y-1.5">
+ {shown.map((model, i) => (
+ <motion.div
+ key={model.name}
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ delay: i * 0.015 }}
+ >
+ <ModelCard
+ model={model}
+ isActive={model.name === activeModel}
+ onSelect={() => setActiveModel(model.name)}
+ onDelete={() => setConfirmDelete(model.name)}
+ onInfo={() => handleInfo(model.name)}
+ canDelete={
+ // Ollama text models via the Ollama API; image/video
+ // models are ComfyUI files we can delete from disk.
+ (ollamaEnabled && model.type === 'text' && (!('provider' in model) || model.provider === 'ollama'))
+ || model.type === 'image' || model.type === 'video'
+ }
+ />
+ </motion.div>
+ ))}
+ {shown.length === 0 && (
+ <p className="text-center text-[0.65rem] text-gray-500 py-6">No installed {modeMeta.label.toLowerCase()} models match "{searchQuery}"</p>
+ )}
+ </div>
+ </section>
+ )
+ })()
+ )}
+ </>
+ )}
- {tab === 'discover' && (
- <DiscoverModels
- category={macTextOnly ? 'text' : discoverMode}
- search={searchQuery}
- searchSubmitToken={searchSubmitToken}
- />
- )}
+ {tab === 'discover' && (
+ <DiscoverModels
+ category={mode}
+ search={searchQuery}
+ searchSubmitToken={searchSubmitToken}
+ />
+ )}
+ </div>
</div>
<PullModelDialog open={pullOpen} onClose={() => setPullOpen(false)} />
diff --cc src/components/settings/MlxMediaSettings.tsx
index 00000000,00000000..d66426f6
new file mode 100644
--- /dev/null
+++ b/src/components/settings/MlxMediaSettings.tsx
@@@ -1,0 -1,0 +1,335 @@@
++// MAC-3 (2.6.0) — the install surface for local media on macOS.
++//
++// Every Rust command this drives (install_mlx_diffusion, mlx_image_install_model,
++// video_install_mlx, video_install_model, …) already existed and was reachable
++// from nowhere: a fresh Mac had no way to set up the MLX engine or pull a model,
++// so Create's local lanes failed with a setup error the user couldn't act on.
++// This panel is that missing path. ComfyUI is never involved on macOS.
++//
++// Install state lives in Rust (one slot per install kind), so the panel polls
++// while something runs instead of holding progress in React.
++
++import { useCallback, useEffect, useRef, useState } from 'react'
++import { Cpu, Download, Trash2, Loader2, Check, AlertTriangle, Film, Image as ImageIcon } from 'lucide-react'
++import {
++ mlxStatus,
++ listMlxImageModels,
++ installMlxImageModel,
++ getMlxImageInstallStatus,
++ deleteMlxImageModel,
++ installMlxImageEngine,
++ getMlxImageEngineStatus,
++ type MlxStatus,
++ type MlxImageModel,
++} from '../../api/mlx-image'
++import {
++ getVideoStatus,
++ listVideoModels,
++ installMlxVideo,
++ getMlxInstallStatus,
++ installVideoModel,
++ getModelInstallStatus,
++ deleteVideoModel,
++ type VideoStatus,
++ type VideoModel,
++} from '../../api/mlx-video'
++import { formatBytes } from '../../lib/formatters'
++
++const POLL_MS = 1500
++
++type Busy =
++ | { kind: 'image-engine' }
++ | { kind: 'video-engine' }
++ | { kind: 'image-model'; id: string }
++ | { kind: 'video-model'; id: string }
++ | null
++
++const rowCls =
++ 'flex items-start justify-between gap-3 p-2.5 rounded-lg border border-gray-200 dark:border-white/8'
++const btnCls =
++ 'inline-flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] transition-colors disabled:opacity-40 disabled:cursor-not-allowed'
++const primaryCls = `${btnCls} bg-purple-600/90 hover:bg-purple-600 text-white`
++const ghostCls = `${btnCls} text-gray-500 hover:text-gray-700 dark:hover:text-gray-300`
++
++/** Download line for the video installer, which reports real byte counts. */
++function progressLine(p: { download_progress: number; download_total: number; download_speed: number }): string | null {
++ if (!p.download_total) return null
++ const pct = Math.min(100, Math.round((p.download_progress / p.download_total) * 100))
++ const speed = p.download_speed > 0 ? ` · ${formatBytes(p.download_speed)}/s` : ''
++ return `${pct}% — ${formatBytes(p.download_progress)} of ${formatBytes(p.download_total)}${speed}`
++}
++
++export function MlxMediaSettings() {
++ const [engine, setEngine] = useState<MlxStatus | null>(null)
++ const [images, setImages] = useState<MlxImageModel[]>([])
++ const [video, setVideo] = useState<VideoStatus | null>(null)
++ const [videos, setVideos] = useState<VideoModel[]>([])
++
++ const [busy, setBusy] = useState<Busy>(null)
++ const [log, setLog] = useState<string[]>([])
++ const [progress, setProgress] = useState<string | null>(null)
++ const [error, setError] = useState<string | null>(null)
++ const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
++
++ // Keep the latest busy kind readable from inside the interval callback
++ // without re-arming the timer on every state change.
++ const busyRef = useRef<Busy>(null)
++ busyRef.current = busy
++
++ const refresh = useCallback(async () => {
++ const [e, i, v, vm] = await Promise.all([
++ mlxStatus().catch(() => null),
++ listMlxImageModels().catch(() => [] as MlxImageModel[]),
++ getVideoStatus().catch(() => null),
++ listVideoModels().catch(() => [] as VideoModel[]),
++ ])
++ setEngine(e)
++ setImages(i)
++ setVideo(v)
++ setVideos(vm)
++ }, [])
++
++ useEffect(() => {
++ void refresh()
++ }, [refresh])
++
++ // Poll the Rust install slot for whichever install is running.
++ useEffect(() => {
++ if (!busy) return
++ let cancelled = false
++ const tick = async () => {
++ const current = busyRef.current
++ if (!current) return
++ try {
++ if (current.kind === 'image-engine' || current.kind === 'image-model') {
++ const s = current.kind === 'image-engine'
++ ? await getMlxImageEngineStatus()
++ : await getMlxImageInstallStatus()
++ if (cancelled) return
++ setLog(s.logs.slice(-6))
++ if (s.status === 'error') {
++ setError(s.error || 'Install failed.')
++ setBusy(null)
++ void refresh()
++ } else if (s.status === 'complete') {
++ setBusy(null)
++ setProgress(null)
++ void refresh()
++ }
++ } else {
++ const s = current.kind === 'video-engine'
++ ? await getMlxInstallStatus()
++ : await getModelInstallStatus()
++ if (cancelled) return
++ setLog(s.logs.slice(-6))
++ setProgress(progressLine(s))
++ if (s.status === 'error') {
++ setError(s.error || 'Install failed.')
++ setBusy(null)
++ void refresh()
++ } else if (s.status === 'complete') {
++ setBusy(null)
++ setProgress(null)
++ void refresh()
++ }
++ }
++ } catch {
++ /* transient — the next tick retries */
++ }
++ }
++ const id = setInterval(tick, POLL_MS)
++ void tick()
++ return () => {
++ cancelled = true
++ clearInterval(id)
++ }
++ }, [busy, refresh])
++
++ const start = async (next: NonNullable<Busy>, fn: () => Promise<unknown>) => {
++ setError(null)
++ setLog([])
++ setProgress(null)
++ setBusy(next)
++ try {
++ await fn()
++ } catch (e) {
++ setError(e instanceof Error ? e.message : String(e))
++ setBusy(null)
++ }
++ }
++
++ const remove = async (kind: 'image' | 'video', id: string) => {
++ setError(null)
++ try {
++ if (kind === 'image') await deleteMlxImageModel(id)
++ else await deleteVideoModel(id)
++ setConfirmDelete(null)
++ await refresh()
++ } catch (e) {
++ setError(e instanceof Error ? e.message : String(e))
++ }
++ }
++
++ const imageEngineReady = !!engine?.installed
++ const videoEngineReady = !!video?.mlxInstalled
++ const anyBusy = busy !== null
++
++ const modelRow = (
++ kind: 'image' | 'video',
++ m: { id: string; name: string; sizeGB: number; minRamGB: number; unfiltered: boolean; description: string; installed: boolean },
++ engineReady: boolean,
++ ) => {
++ const installing = busy?.kind === `${kind}-model` && 'id' in busy && busy.id === m.id
++ return (
++ <div key={m.id} className={rowCls}>
++ <div className="min-w-0">
++ <div className="flex items-center gap-1.5">
++ <span className="text-[0.7rem] text-gray-800 dark:text-gray-200">{m.name}</span>
++ {m.installed && <Check size={11} className="text-green-500 shrink-0" />}
++ {m.unfiltered && (
++ <span className="px-1 rounded text-[0.55rem] bg-purple-500/15 text-purple-500 dark:text-purple-300">unfiltered</span>
++ )}
++ </div>
++ <div className="text-[0.6rem] text-gray-500 leading-relaxed mt-0.5">{m.description}</div>
++ <div className="text-[0.55rem] text-gray-500 mt-0.5 font-mono">
++ {m.sizeGB} GB download · needs {m.minRamGB} GB unified memory
++ </div>
++ </div>
++ <div className="shrink-0">
++ {m.installed ? (
++ confirmDelete === `${kind}:${m.id}` ? (
++ <div className="flex gap-1">
++ <button className={`${btnCls} text-red-500 hover:text-red-400`} onClick={() => remove(kind, m.id)}>
++ Delete
++ </button>
++ <button className={ghostCls} onClick={() => setConfirmDelete(null)}>
++ Cancel
++ </button>
++ </div>
++ ) : (
++ <button className={ghostCls} onClick={() => setConfirmDelete(`${kind}:${m.id}`)} disabled={anyBusy}>
++ <Trash2 size={11} /> Remove
++ </button>
++ )
++ ) : (
++ <button
++ className={primaryCls}
++ disabled={anyBusy || !engineReady}
++ title={engineReady ? undefined : 'Install the engine first'}
++ onClick={() =>
++ start(
++ { kind: kind === 'image' ? 'image-model' : 'video-model', id: m.id },
++ () => (kind === 'image' ? installMlxImageModel(m.id) : installVideoModel(m.id)),
++ )
++ }
++ >
++ {installing ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}
++ {installing ? 'Installing…' : 'Install'}
++ </button>
++ )}
++ </div>
++ </div>
++ )
++ }
++
++ return (
++ <div className="space-y-3">
++ <div className="flex items-start gap-2.5 p-2.5 rounded-lg border border-gray-200 dark:border-white/8 bg-gray-50 dark:bg-white/[0.03]">
++ <Cpu size={14} className="mt-0.5 shrink-0 text-purple-500" />
++ <div className="text-[0.65rem] leading-relaxed text-gray-600 dark:text-gray-400">
++ <strong className="text-gray-800 dark:text-gray-200">Local media on this Mac runs on Apple MLX.</strong> Images
++ and video generate on the GPU with no server involved. The engine is a one-time setup; each model is a separate
++ download you can remove again.
++ </div>
++ </div>
++
++ {error && (
++ <div className="flex items-start gap-2 p-2.5 rounded-lg border border-red-300 dark:border-red-500/25 bg-red-50 dark:bg-red-500/[0.08] text-red-700 dark:text-red-300">
++ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
++ <div className="text-[0.65rem] leading-relaxed break-words">{error}</div>
++ </div>
++ )}
++
++ {/* ── Image ─────────────────────────────────────────── */}
++ <div className="flex items-center gap-1.5 pt-1">
++ <ImageIcon size={12} className="text-gray-500" />
++ <span className="text-[0.7rem] text-gray-700 dark:text-gray-300">Images</span>
++ </div>
++
++ <div className={rowCls}>
++ <div>
++ <div className="text-[0.7rem] text-gray-800 dark:text-gray-200">Image engine</div>
++ <div className="text-[0.6rem] text-gray-500 mt-0.5">
++ {imageEngineReady
++ ? `Installed${engine?.running ? ' · running' : ''}${engine?.modelRepo ? ` · ${engine.modelRepo}` : ''}`
++ : 'Not installed — about 3 GB of Python packages (torch, diffusers).'}
++ </div>
++ </div>
++ {!imageEngineReady && (
++ <button className={primaryCls} disabled={anyBusy} onClick={() => start({ kind: 'image-engine' }, installMlxImageEngine)}>
++ {busy?.kind === 'image-engine' ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}
++ {busy?.kind === 'image-engine' ? 'Installing…' : 'Install engine'}
++ </button>
++ )}
++ </div>
++
++ {images.map((m) => modelRow('image', m, imageEngineReady))}
++
++ {/* ── Video ─────────────────────────────────────────── */}
++ <div className="flex items-center gap-1.5 pt-1">
++ <Film size={12} className="text-gray-500" />
++ <span className="text-[0.7rem] text-gray-700 dark:text-gray-300">Video</span>
++ </div>
++
++ {video && !video.appleSilicon && (
++ <div className="text-[0.6rem] text-gray-500">
++ Local video needs Apple Silicon. Video generation is available in LU Cloud on this machine.
++ </div>
++ )}
++
++ <div className={rowCls}>
++ <div>
++ <div className="text-[0.7rem] text-gray-800 dark:text-gray-200">Video engine</div>
++ <div className="text-[0.6rem] text-gray-500 mt-0.5">
++ {videoEngineReady
++ ? `Installed${video?.mlxVersion ? ` · mlx ${video.mlxVersion}` : ''}`
++ : 'Not installed — MLX video packages.'}
++ </div>
++ </div>
++ {!videoEngineReady && (
++ <button
++ className={primaryCls}
++ disabled={anyBusy || (video ? !video.appleSilicon : false)}
++ onClick={() => start({ kind: 'video-engine' }, installMlxVideo)}
++ >
++ {busy?.kind === 'video-engine' ? <Loader2 size={11} className="animate-spin" /> : <Download size={11} />}
++ {busy?.kind === 'video-engine' ? 'Installing…' : 'Install engine'}
++ </button>
++ )}
++ </div>
++
++ {videos.map((m) => modelRow('video', m, videoEngineReady))}
++
++ <div className="text-[0.6rem] text-gray-500 leading-relaxed">
++ Video models are large and generation is slow — minutes per clip, not seconds. Start with the smallest model.
++ </div>
++
++ {/* ── Live install output ───────────────────────────── */}
++ {(anyBusy || log.length > 0) && (
++ <div className="p-2.5 rounded-lg border border-gray-200 dark:border-white/8 bg-gray-50 dark:bg-black/20">
++ {progress && <div className="text-[0.6rem] text-gray-600 dark:text-gray-300 font-mono mb-1">{progress}</div>}
++ <div className="text-[0.55rem] text-gray-500 font-mono space-y-0.5 max-h-24 overflow-y-auto">
++ {log.map((l, i) => (
++ <div key={i} className="truncate">{l}</div>
++ ))}
++ </div>
++ {anyBusy && (
++ <div className="text-[0.6rem] text-gray-500 mt-1.5">
++ This keeps running if you close Settings. Large downloads can take a while.
++ </div>
++ )}
++ </div>
++ )}
++ </div>
++ )
++}
diff --cc src/components/settings/PermissionSettings.tsx
index f9477776,c6886b81..220f61b6
--- a/src/components/settings/PermissionSettings.tsx
+++ b/src/components/settings/PermissionSettings.tsx
@@@ -22,7 -25,8 +25,8 @@@ const CATEGORIES:
{ key: 'web', label: 'Web Access', description: 'Search & fetch web pages', icon: Globe, risk: 'low' },
{ key: 'system', label: 'System Info', description: 'OS info, process list', icon: Cpu, risk: 'low' },
{ key: 'filesystem', label: 'Filesystem', description: 'Read, write, search files anywhere', icon: FolderOpen, risk: 'medium' },
- { key: 'image', label: 'Image Generation', description: 'Generate images and video', icon: Image, risk: 'medium' },
- { key: 'image', label: 'Image Generation', description: 'Generate images via ComfyUI', icon: Image, risk: 'medium' },
- { key: 'video', label: 'Video Generation', description: 'Generate video via ComfyUI', icon: Film, risk: 'medium' },
++ { key: 'image', label: 'Image Generation', description: 'Generate images', icon: Image, risk: 'medium' },
++ { key: 'video', label: 'Video Generation', description: 'Generate video', icon: Film, risk: 'medium' },
{ key: 'workflow', label: 'Workflows', description: 'Execute saved agent workflows', icon: GitBranch, risk: 'medium' },
{ key: 'terminal', label: 'Terminal / Shell', description: 'Execute commands, run code', icon: Terminal, risk: 'high' },
{ key: 'desktop', label: 'Desktop Control', description: 'Screenshots, screen interaction', icon: Monitor, risk: 'high' },
diff --cc src/components/settings/SettingsPage.tsx
index b0afba99,df067f1e..c0f75838
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@@ -48,13 -48,14 +48,16 @@@ import { RemoteAccessDocs } from './Rem
import { HardwareSettings } from './HardwareSettings'
import { ChatbotImporter } from '../import/ChatbotImporter'
import { ProviderSettings } from './ProviderConfig'
+ import { BuiltinEngineSettings } from './BuiltinEngineSettings'
++import { MlxMediaSettings } from './MlxMediaSettings'
+ import { useProviderStore } from '../../stores/providerStore'
import { PermissionSettings } from './PermissionSettings'
import { MCPServerSettings } from './MCPServerSettings'
import { WorkflowList } from '../agents/WorkflowList'
import { WorkflowBuilder } from '../agents/WorkflowBuilder'
import { useUpdateStore, isNewerVersion } from '../../stores/updateStore'
- import { backendCall, isCloudOnly } from '../../api/backend'
+ import { backendCall } from '../../api/backend'
+import { isMlxImageHost } from '../../api/mlx-image'
import { ArrowUpCircle } from 'lucide-react'
// ── User profile picture (Appearance) ───────────────────────────
@@@ -574,6 -581,48 +583,48 @@@ function ComfyUISettings()
{status?.complete === false ? 'Re-install ComfyUI' : 'Install ComfyUI'}
</button>
)}
+ {status?.found && status?.complete !== false && installPhase === 'idle' && (
+ // 2.5.8: the specialized local lanes (music / talking character /
+ // motion) need node families that ship with current cores — this is
+ // the one-click git pull + dependency refresh the lane errors point
+ // to. Reuses the installer's status channel and log panel.
+ <button
+ onClick={async () => {
+ setInstallPhase('comfyui')
- setInstallErr(null)
++ setInstallErr('')
+ setInstallLogs(['Updating ComfyUI…'])
+ try {
+ await backendCall('update_comfyui')
+ const poll = setInterval(async () => {
+ try {
+ const data: any = await backendCall('install_comfyui_status')
+ setInstallLogs(data.logs || [])
+ if (data.status === 'complete') {
+ clearInterval(poll)
+ setInstallPhase('idle')
+ } else if (data.status === 'error') {
+ clearInterval(poll)
+ const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string
+ setInstallErr(lastLog || 'ComfyUI update failed')
+ setInstallPhase('error')
+ }
+ } catch { /* keep polling */ }
+ }, 2000)
+ } catch (err) {
+ setInstallPhase('error')
+ setInstallErr(err instanceof Error ? err.message : 'Failed to start the update')
+ }
+ }}
+ className="px-2 py-1 rounded text-[0.6rem] bg-white/5 text-gray-400 hover:text-gray-200 hover:bg-white/10 transition-colors"
+ >
+ Update ComfyUI
+ </button>
+ )}
+ {(!status?.found || status?.complete === false) && installPhase === 'idle' && (
+ <p className="w-full text-[0.55rem] text-gray-600">
+ Installs to your home folder by default. Set Path above (e.g. D:\ComfyUI) to install on another drive.
+ </p>
+ )}
{installPhase !== 'idle' && (
<div className="w-full mt-2 space-y-1">
<div className="flex items-center gap-1.5 text-[0.6rem] text-gray-400">
@@@ -1050,12 -1171,11 +1173,12 @@@ export function SettingsPage()
<ChatBackupSettings />
</Section>
- {/* ComfyUI-only knobs — cloud renders use server-side limits. */}
- {settings.appMode !== 'cloud' && (
+ {/* ComfyUI-only knobs — cloud renders use server-side limits, and the
+ Mac's MLX pipeline has its own fixed timeout, so hide there too. */}
+ {settings.appMode !== 'cloud' && !isMlxImageHost() && (
<Section title="Image / Video Generation Timeouts">
<div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed pb-1.5">
- Maximum minutes a ComfyUI generation can run before LU aborts it. Bump these up if you run on iGPU or CPU only — a 1024px image on integrated graphics can take 30+ min.
+ Maximum minutes a ComfyUI generation can run before LU aborts it. Bump these up if you run on iGPU or CPU only, because a 1024px image on integrated graphics can take 30+ min.
</div>
<div className="flex items-center justify-between">
<span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Image timeout (min)</span>
@@@ -1162,18 -1282,20 +1285,35 @@@
<HfDownloadPathSetting />
</Section>
+ {builtinManaged && (
+ <Section title="Built-in Engine (expert)">
+ <BuiltinEngineSettings />
+ </Section>
+ )}
+
- <Section title="ComfyUI (Image & Video)">
- {settings.appMode === 'cloud' && (
- <p className="text-[0.55rem] text-gray-500 leading-snug pb-1">
- Local mode only. Cloud renders run on lu-labs.ai and never use ComfyUI.
- </p>
- )}
- <ComfyUISettings />
- </Section>
+ {/* ComfyUI never runs on the Mac (MLX-only local media) — hide the whole
- panel there so it isn't a dead Install/Start surface. */}
- {!isMlxImageHost() && (
++ panel there so it isn't a dead Install/Start surface. The Mac gets
++ the MLX installer in its place; without it a fresh Mac has no way
++ to set up local image/video at all (MAC-3). */}
++ {!isMlxImageHost() ? (
+ <Section title="ComfyUI (Image & Video)">
+ {settings.appMode === 'cloud' && (
+ <p className="text-[0.55rem] text-gray-500 leading-snug pb-1">
- Local mode only — cloud renders run on lu-labs.ai and never use ComfyUI.
++ Local mode only. Cloud renders run on lu-labs.ai and never use ComfyUI.
+ </p>
+ )}
+ <ComfyUISettings />
+ </Section>
++ ) : (
++ <Section title="Local Media (Apple MLX)">
++ {settings.appMode === 'cloud' && (
++ <p className="text-[0.55rem] text-gray-500 leading-snug pb-1">
++ Local mode only. Cloud renders run on lu-labs.ai and never touch these models.
++ </p>
++ )}
++ <MlxMediaSettings />
++ </Section>
+ )}
</>)}
{/* ── Agent tab ─────────────────────────────────── */}
@@@ -1597,8 -1736,8 +1754,7 @@@ function TroubleshootSection()
<div className="space-y-3 py-2">
<p className="text-[0.6rem] text-gray-500 leading-relaxed">
One-shot probe of the local backends and host facts. Use this when
- the app behaves oddly — most "model not found" / "ComfyUI doesn't
- the app behaves oddly. Most "model not found" / "ComfyUI doesn't
-- respond" issues become obvious here.
++ the app behaves oddly. Most "model not found" / {isMlxImageHost() ? '"backend doesn\'t respond"' : '"ComfyUI doesn\'t respond"'} issues become obvious here.
</p>
{error && (
diff --cc src/hooks/useCodex.ts
index 78db98a6,af407d61..c620ca17
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@@ -84,12 -99,13 +99,13 @@@ Workflow per task
Rules:
- Always read a file before modifying it
- - PATHS: use paths relative to the working directory shown below (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`) — that escapes the workspace and fails.
+ - To CHANGE part of an existing file, use file_edit (replace a UNIQUE old_string with new_string), it is far cheaper and safer than rewriting the whole file with file_write, and never truncates a large file. Use file_write only to CREATE a new file or fully replace one. If file_edit reports the old_string is missing or not unique, read the file and retry with more surrounding lines.
+ - PATHS: use paths relative to the working directory shown below (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`), that escapes the workspace and fails.
- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool
- - If a command fails, diagnose and retry with a different approach — don't hand back to the user unless truly stuck
+ - If a command fails, diagnose and retry with a different approach, don't hand back to the user unless truly stuck
- Be concise in text. All the work happens in tool calls.
- - Asset generation: when the task needs an image or a short video (placeholder art, hero image, demo clip), call image_generate / video_generate as a real tool call — they run on-device (Apple MLX on macOS, ComfyUI elsewhere). To animate a generated image, call video_generate with inputImage set to that image's filename.
- - FINISH with a short natural-language sentence summarising what you did or found. NEVER end your turn with only a raw JSON object or a bare code block — the user needs a human-readable answer, not a data dump.`
-- Asset generation: when the task needs an image or a short video (placeholder art, hero image, demo clip), call image_generate / video_generate as a real tool call, ComfyUI runs locally. To animate a generated image, call video_generate with inputImage set to that image's filename.
++- Asset generation: when the task needs an image or a short video (placeholder art, hero image, demo clip), call image_generate / video_generate as a real tool call, they run on-device (Apple MLX on macOS, ComfyUI elsewhere). To animate a generated image, call video_generate with inputImage set to that image's filename.
+ - FINISH with a short natural-language sentence summarising what you did or found. NEVER end your turn with only a raw JSON object or a bare code block, the user needs a human-readable answer, not a data dump.`
// Small-Model Mode (Knob 2): a lean Codex prompt (~500 chars vs ~1700 above)
// for 3B-8B models. Research (LongFuncEval, arXiv 2505.10570) shows long
diff --cc src/hooks/useCreate.ts
index e39b4b25,ef167c0d..cd1be364
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@@ -96,50 -105,17 +113,66 @@@ export function useCreate()
setModelLoadError(null)
try {
- // Apple Silicon: MLX is a first-class local image backend (hard rule —
- // Mac local media is MLX-via-lu-bridge, never ComfyUI). Load the installed
- // MLX catalog first (this also spins up the bundled bridge sidecar) so
- // images work even when ComfyUI is absent — the normal Mac case.
++ // Apple Silicon: MLX is a first-class local media backend (hard rule —
++ // Mac local image/video is the in-process MLX path, never ComfyUI). Load
++ // the installed MLX catalogs FIRST so Create works on the normal Mac,
++ // which has no ComfyUI at all.
++ const mlxHost = isMlxImageHost()
+ let mlxImageModels: ClassifiedModel[] = []
- // Video has no ComfyUI counterpart on Mac (hard rule: Mac video is
- // MLX-only, ComfyUI never even auto-starts there — see
- // process.rs::auto_start_comfyui). The video list IS the MLX catalog.
++ // Video has no ComfyUI counterpart on Mac (ComfyUI never even auto-starts
++ // there — see process.rs::auto_start_comfyui). The video list IS the MLX
++ // catalog.
+ let mlxVideoModels: ClassifiedModel[] = []
- if (isMlxImageHost()) {
++ if (mlxHost) {
+ try {
+ const mlx = await mlxStatus()
+ if (mlx.installed) mlxImageModels = buildMlxImageModels(await listMlxImageModels())
- } catch { /* bridge/sidecar not up yet — treat as no MLX models */ }
++ } catch { /* MLX engine not set up yet — treat as no MLX models */ }
+ try {
+ mlxVideoModels = buildMlxVideoModels(await listVideoModels())
+ } catch { /* mlx-video status unavailable yet — treat as no MLX video models */ }
+ }
+
- // Check connection — if ComfyUI is down, don't waste time on its queries.
+ // Check connection first — if ComfyUI is down, don't waste time on model queries.
+ // Sync the connected state on EVERY fetch: the mount-time checkConnection can
+ // race ComfyUI's autostart (exe boots faster than the engine), and nothing
+ // else ever flipped `connected` back to true — the Stage then kept showing
+ // the Download & install card while the model chip was happily populated
+ // (live-caught on the 2.5.8 extend lane E2E).
++ // NOT on Mac: there is no ComfyUI to be connected to, and pinning
++ // `connected` to false is exactly what makes the Stage cover a working
++ // MLX catalog with the ComfyUI "Download & install" card. Left at null
++ // ("not applicable"), which every ComfyUI-gated surface treats as neutral.
const comfyOk = await checkComfyConnection()
- setConnected(comfyOk)
- useCreateStore.getState().setComfyRunning(comfyOk)
++ if (!mlxHost) {
++ setConnected(comfyOk)
++ useCreateStore.getState().setComfyRunning(comfyOk)
++ }
if (!comfyOk) {
- setModelLoadError('ComfyUI is not running. Start it from Settings or wait for auto-start.')
+ // On Apple Silicon MLX alone is a valid image/video backend — don't bail.
+ if (mlxImageModels.length > 0 || mlxVideoModels.length > 0) {
+ const st = useCreateStore.getState()
+ setImageModels(mlxImageModels)
+ st.setImageModelList(mlxImageModels)
- if (mlxImageModels.length > 0 && !st.imageModel) {
++ if (mlxImageModels.length > 0 && !mlxImageModels.find(m => m.name === st.imageModel)) {
+ st.setImageModel(mlxImageModels[0].name, mlxImageModels[0].type)
+ }
+ setVideoModelsList(mlxVideoModels)
+ st.setVideoModelList(mlxVideoModels)
+ if (mlxVideoModels.length > 0 && !mlxVideoModels.find(m => m.name === st.videoModel)) {
+ st.setVideoModel(mlxVideoModels[0].name)
+ }
+ zeroModelRetries.current = 0
+ setModelsLoaded(true)
+ return
+ }
++ // Honest copy: there is no "Model Manager → Mac Image/Video" surface to
++ // point at, and naming the raw install command leaks an internal path.
+ setModelLoadError(
- isMlxImageHost()
++ mlxHost
+ ? 'The local image engine is not set up on this Mac yet — a one-time setup is needed before local generation works.'
+ : 'ComfyUI is not running. Start it from Settings or wait for auto-start.'
+ )
return
}
@@@ -148,22 -124,20 +181,27 @@@
// and its internal cache hasn't updated yet.
await refreshComfyModels()
- const [comfyImgModels, comfyVidModels, samplers, schedulers, vBackend, _nodeInfo] = await Promise.all([
- const [comfyImgModels, vidModels, samplers, schedulers, vBackend, _nodeInfo, audModels, lipModels, motModels] = await Promise.all([
++ const [comfyImgModels, comfyVidModels, samplers, schedulers, vBackend, _nodeInfo, audModels, lipModels, motModels] = await Promise.all([
getImageModels(),
getVideoModels(),
getSamplers(),
getSchedulers(),
detectVideoBackend(),
getAllNodeInfo().catch(() => null),
+ // 2.5.8 specialized lane lists — best-effort so a probe failure never
+ // blocks the classic image/video surfaces.
+ getAudioModels().catch(() => [] as ClassifiedModel[]),
+ getLipsyncModels().catch(() => [] as ClassifiedModel[]),
+ getMotionModels().catch(() => [] as ClassifiedModel[]),
])
- const imgModels = comfyImgModels
+ // MLX entries go first so one is the default on a fresh Apple-Silicon box.
+ const imgModels = mlxImageModels.length
+ ? mergeImageModels(comfyImgModels, mlxImageModels)
+ : comfyImgModels
+ // Mac video is MLX-only — never surface ComfyUI video checkpoints there,
- // even in the rare case ComfyUI happens to be reachable (e.g. a manual
- // install the user started outside LU).
- const vidModels = isMlxImageHost() ? mlxVideoModels : comfyVidModels
++ // even in the rare case ComfyUI happens to be reachable (a manual install
++ // the user started outside LU).
++ const vidModels = mlxHost ? mlxVideoModels : comfyVidModels
setImageModels(imgModels)
setVideoModelsList(vidModels)
setSamplerList(samplers)
@@@ -284,12 -261,6 +325,12 @@@
if (!modelLoadError) return // No error — nothing to retry
if (modelsLoaded) return // modelsLoaded + error = gave up after max retries, don't loop
const retryInterval = setInterval(async () => {
- // No ComfyUI to poll for on Mac (hard rule: MLX-only) — retry the MLX
- // catalog directly instead of waiting on a connection that never comes.
++ // No ComfyUI to wait for on Mac (hard rule: MLX-only) — retry the MLX
++ // catalog directly instead of gating on a connection that never comes.
+ if (isMlxImageHost()) {
+ fetchModels()
+ return
+ }
const ok = await checkComfyConnection()
if (ok) {
console.log('[useCreate] Retrying model fetch...')
@@@ -327,168 -384,40 +454,202 @@@
const maskFilename = mask?.filename
const isRemoveBg = mode === 'image' && removebg
- // ── MLX image pipeline (Apple Silicon) — hard rule: Mac local image is
- // MLX-via-lu-bridge, never ComfyUI. Routes on the SELECTED model being the
- // synthetic MLX entry (a stale videoBackend must not hijack a real ComfyUI
- // checkpoint). Generation returns a base64 PNG stored as a data URL on the
- // gallery item, so display + download work with no ComfyUI /view route. ──
- if (mode === 'image' && isMlxImageHost() && isMlxImageModel(imageModel) && !isRemoveBg) {
+ // ── 2.5.8 specialized local lanes. music / lipsync / motion build their
+ // own core-node graphs (buildLocalOpWorkflow); extend rides the regular
+ // I2V flow below — its source IS the extracted last frame. character
+ // trained already branched off above (Rust musubi trainer); its use
+ // surface is a plain image generate with the LoRA active. ──
+ const localOp =
+ state.cloudOp === 'music' || state.cloudOp === 'lipsync' || state.cloudOp === 'motion'
+ ? state.cloudOp
+ : null
+ const localOpList =
+ localOp === 'music' ? state.audioModelList
+ : localOp === 'lipsync' ? state.lipsyncModelList
+ : localOp === 'motion' ? state.motionModelList
+ : []
+ const localOpModel = localOp ? resolveLocalOpPick(state.localOpModel, localOpList) : ''
+
- // Desktop port: the MLX video/image pipelines (Apple Silicon) are not
- // part of this build — ComfyUI is the only local backend.
++ // ── MLX image pipeline (Apple Silicon) — hard rule: Mac local image is the
++ // in-process MLX path, never ComfyUI. Gated on the derived `image` intent
++ // (which already means: no cloudOp, no utilityOp, no removebg, text2img)
++ // AND on the SELECTED model being a synthetic MLX entry, so a real ComfyUI
++ // checkpoint from a manual install is never hijacked. Generation returns a
++ // base64 PNG stored as a data URL on the gallery item, so display +
++ // download work with no ComfyUI /view route. ──
++ if (intent === 'image' && isMlxImageHost() && isMlxImageModel(imageModel)) {
+ setError(null)
+ if (!prompt.trim()) { setError('Please enter a prompt.'); return }
+ setIsGenerating(true)
+ state.setProgressPhase('loading-model')
+ setProgress(10, 'Starting MLX image generation...')
+ addToPromptHistory(prompt)
+ const startTime = Date.now()
+ try {
+ state.setProgressPhase('sampling')
+ setProgress(40, 'Generating with MLX...')
+ const { dataUrl, width: outW, height: outH } = await generateMlxImageDataUrl({
+ prompt, steps, seed, width, height,
+ model: mlxModelIdFor(imageModel),
+ negativePrompt: negativePrompt || undefined,
+ })
+ const elapsed = Math.round((Date.now() - startTime) / 1000)
+ state.setProgressPhase('complete')
+ setProgress(100, 'Complete!')
+ state.setLastGenTime(`${elapsed}s`)
+ addToGallery({
+ id: uuid(), type: 'image', filename: `mlx-${Date.now()}.png`, subfolder: '',
+ dataUrl, prompt, negativePrompt, model: imageModel, modelType: 'unknown',
+ seed: seed === -1 ? 0 : seed, steps, cfgScale, sampler, scheduler,
+ width: outW || width, height: outH || height, batchSize: 1,
+ createdAt: Date.now(), builderUsed: 'dynamic', intent,
+ })
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e)
+ useCreateStore.getState().setError(`Generation failed: ${msg}`)
+ } finally {
+ useCreateStore.getState().setIsGenerating(false)
+ useCreateStore.getState().setProgress(0)
+ }
+ return
+ }
+
- // ── MLX video pipeline (Apple Silicon) — hard rule: Mac local video is
- // MLX-via-mlx-video, never ComfyUI. Unlike the image branch this doesn't
- // need to check the selected model against a synthetic-name marker: on
- // Mac the video picker IS the MLX catalog (Task 1 — ComfyUI never even
- // auto-starts there, see process.rs::auto_start_comfyui), so every video
- // generation routes here. Generation is a subprocess polled via
- // video_progress every 2s (no WebSocket/node-graph like ComfyUI). ──
- if (mode === 'video' && isMlxImageHost()) {
++ // ── MLX video pipeline (Apple Silicon) — hard rule: Mac local video is the
++ // in-process mlx-video path, never ComfyUI. Unlike the image branch this
++ // needs no model-name marker: on Mac the video picker IS the MLX catalog
++ // (fetchModels above), so every local video generation routes here. Gated
++ // on the derived `video` intent, which is text-to-video by definition —
++ // animate/extend/motion have no local lane on this host (the IntentBar
++ // shows them hidden / as cloud teasers), and their source images are staged
++ // through a ComfyUI upload that doesn't exist here. Generation is a
++ // subprocess polled via video_progress every 2s (no WebSocket/node graph). ──
++ if (intent === 'video' && isMlxImageHost()) {
+ setError(null)
+ if (!prompt.trim()) { setError('Please enter a prompt.'); return }
+ if (!videoModel) { setError('No local video model selected — pick one from the model picker.'); return }
+ const catalogId = mlxVideoModelIdFor(videoModel)
+ if (!catalogId) { setError(`Unknown MLX video model "${videoModel}" — re-select it from the picker.`); return }
+ try {
+ const status = await getVideoStatus()
- if (!status.available) { setError('MLX video is Apple Silicon only.'); return }
++ if (!status.available) { setError('Local video generation is Apple Silicon only.'); return }
+ if (!status.mlxInstalled) { setError('The local video engine is not set up on this Mac yet (a one-time setup is needed before local video works).'); return }
+ if (!status.installedModels.includes(catalogId)) { setError(`The local video model "${videoModel}" isn't downloaded yet.`); return }
+ } catch (e) {
- setError(`MLX video status check failed: ${e instanceof Error ? e.message : String(e)}`)
++ setError(`Local video status check failed: ${e instanceof Error ? e.message : String(e)}`)
+ return
+ }
+
+ setIsGenerating(true)
+ state.setProgressPhase('loading-model')
+ setProgress(0, 'Starting MLX video generation...')
+ addToPromptHistory(prompt)
+ const startTime = Date.now()
+ abortRef.current = new AbortController()
+ let result: Awaited<ReturnType<typeof generateVideo>>
+ try {
+ result = await generateVideo({
+ id: catalogId,
+ prompt,
+ seconds: Math.max(0.5, frames / Math.max(1, fps)),
+ fps,
+ seed: seed === -1 ? undefined : seed,
- initImage: effI2vImage ?? undefined,
+ })
+ } catch (e) {
+ useCreateStore.getState().setError(`Failed to start: ${e instanceof Error ? e.message : String(e)}`)
+ useCreateStore.getState().setIsGenerating(false)
+ abortRef.current = null
+ return
+ }
+ try {
+ state.setProgressPhase('sampling')
+ await new Promise<void>((resolve, reject) => {
+ const tick = async () => {
+ if (abortRef.current?.signal.aborted) {
+ try { await cancelVideo() } catch { /* already finished/gone */ }
+ reject(new Error('Cancelled'))
+ return
+ }
- // Safety net: local MLX video is slow (tens of minutes), so give it
- // a full hour — but never poll forever. On the cap, kill the
- // mlx-video subprocess so it stops pinning the machine.
++ // Safety net (David: the machine glowed for hours). Local MLX video
++ // is slow — tens of minutes — so give it a full hour, but never
++ // poll forever. On the cap, KILL the mlx-video subprocess so it
++ // stops pinning the machine; before this it kept running after the
++ // UI had given up.
+ if (Date.now() - startTime > 60 * 60 * 1000) {
+ try { await cancelVideo() } catch { /* already finished/gone */ }
+ reject(new Error('Generation timed out after 60 minutes'))
+ return
+ }
+ try {
+ const prog = await getVideoProgress()
+ const elapsed = Math.round((Date.now() - startTime) / 1000)
+ setProgress(Math.min(95, elapsed * 2), `Generating with MLX... ${elapsed}s`)
+ if (prog.status === 'complete') {
+ setProgress(100, 'Complete!')
+ useCreateStore.getState().setLastGenTime(`${elapsed}s`)
- // The mp4 lives on disk only (no lu-bridge :47711/videos/<file>
- // route anymore) — read it via the guarded `read_media_file`
- // Rust command and hand the frontend a `blob:` URL, which the
- // CSP's media-src allows (unlike `data:`). Reuse `dataUrl`:
- // galleryItemUrl()/OutputView/Lightbox/download already prefer
- // it over the ComfyUI /view path, and a blob: URL is just a
- // string src as far as <video>/fetch are concerned.
++ // The mp4 lives on disk only (no ComfyUI /view route here) —
++ // read it via the guarded `read_media_file` Rust command and
++ // hand the frontend a `blob:` URL, which the CSP's media-src
++ // allows (unlike `data:`). Reuse `dataUrl`: galleryItemUrl() /
++ // OutputView / Lightbox / download already prefer it over the
++ // ComfyUI /view path, and a blob: URL is just a string src as
++ // far as <video>/fetch are concerned.
+ let dataUrl: string | undefined
+ try {
+ dataUrl = await readVideoAsBlobUrl(result.output)
+ } catch (e) {
+ console.error('read_media_file failed for MLX video output', e)
+ }
+ addToGallery({
+ id: uuid(), type: 'video', filename: '', subfolder: '',
+ dataUrl,
- // Keep the real on-disk path too, in case a future
- // download-to-disk path wants to reference it directly.
++ // Keep the real on-disk path too, for a future
++ // download-to-disk path that wants to reference it directly.
+ localPath: result.output,
+ prompt, negativePrompt, model: videoModel, modelType: 'wan',
+ seed: seed === -1 ? 0 : seed, steps, cfgScale, sampler, scheduler,
+ width, height, batchSize: 1,
+ createdAt: Date.now(), builderUsed: 'dynamic', intent,
+ })
+ resolve()
+ return
+ }
+ if (prog.status === 'error') {
- reject(new Error(prog.error || 'mlx-video failed'))
++ reject(new Error(prog.error || 'local video generation failed'))
+ return
+ }
+ setTimeout(tick, 2000)
+ } catch (e) {
+ reject(e instanceof Error ? e : new Error(String(e)))
+ }
+ }
+ tick()
+ })
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e)
+ if (msg !== 'Cancelled') useCreateStore.getState().setError(`Generation failed: ${msg}`)
+ } finally {
+ useCreateStore.getState().setIsGenerating(false)
+ useCreateStore.getState().setProgress(0)
+ abortRef.current = null
+ }
+ return
+ }
setError(null)
- const activeModel = mode === 'image' ? imageModel : videoModel
+ let activeModel = localOp ? localOpModel : (mode === 'image' ? imageModel : videoModel)
+ // Chip↔run agreement (live-caught on the extend E2E): the picker DISPLAYS
+ // the first capable model when the stored pick can't run the current
+ // intent, but submit read the raw store — the run then used a model the
+ // user never saw. Apply the picker's coercion here too (same one-rule
+ // philosophy as the cloud op resolver after take-01).
+ if (!localOp && mode === 'video' && state.videoModelList.length > 0) {
+ const capable = intent === 'animate' || intent === 'extend'
+ ? state.videoModelList.filter((m) => isI2VModel(m.name))
+ : state.videoModelList.filter((m) => isT2VCapable(m.name))
+ if (capable.length > 0 && !capable.some((m) => m.name === activeModel)) {
+ activeModel = capable[0].name
+ }
+ }
// Always re-classify from model name to avoid stale type
const imageModelType = classifyModel(activeModel)
diff --cc src/hooks/useModels.ts
index e7d4a421,db82426a..a104263e
--- a/src/hooks/useModels.ts
+++ b/src/hooks/useModels.ts
@@@ -178,11 -171,8 +171,11 @@@ export function useModels()
.map(m => ({ ...m, provider: 'ollama' as const, providerName: 'Ollama' })))
} catch { /* Ollama might not be running */ }
}
+ let comfyModels: AIModel[] = []
- const comfyOk = await checkComfyConnection()
+ // Hard rule: Mac local media is MLX-only — ComfyUI never auto-starts
+ // there (process.rs::auto_start_comfyui), so skip the probe outright
+ // instead of a doomed connection check on every model-list refresh.
- let comfyModels: AIModel[] = []
+ const comfyOk = !isMacOS() && (await checkComfyConnection())
if (comfyOk) {
try {
const [checkpoints, diffusionModels] = await Promise.all([getComfyCheckpoints(), getComfyDiffusionModels()])
diff --cc src/stores/__tests__/settingsStore-migrate-mac-appmode.test.ts
index 947a39e4,00000000..2944d5a6
mode 100644,000000..100644
--- a/src/stores/__tests__/settingsStore-migrate-mac-appmode.test.ts
+++ b/src/stores/__tests__/settingsStore-migrate-mac-appmode.test.ts
@@@ -1,79 -1,0 +1,88 @@@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+
- // v14 migration: the macOS Cloud-only wall is lifted, so existing Mac installs
++// v19 migration: the macOS Cloud-only wall is lifted, so existing Mac installs
+// that were force-pinned to appMode 'cloud' must be reset ONCE to the local
+// default. Windows/Linux (a real user choice) must never be touched. This is a
+// persist-time migration, so we drive it black-box: seed a versioned blob in
+// localStorage, stub navigator for the platform, then fresh-import the store
+// and assert the hydrated appMode — same approach as createStore-migrate.test.
+
+const backing = new Map<string, string>()
+const localStorageShim = {
+ getItem: (k: string) => backing.get(k) ?? null,
+ setItem: (k: string, v: string) => void backing.set(k, String(v)),
+ removeItem: (k: string) => void backing.delete(k),
+ clear: () => backing.clear(),
+ key: (i: number) => [...backing.keys()][i] ?? null,
+ get length() {
+ return backing.size
+ },
+} as Storage
+
+const KEY = 'chat-settings'
++const CURRENT = 19
+
+const MAC_NAV = { platform: 'MacIntel', userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' }
+const WIN_NAV = { platform: 'Win32', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' }
+
+function seed(settings: Record<string, unknown>, version: number) {
+ backing.set(
+ KEY,
+ JSON.stringify({
+ state: { settings, personas: [], activePersonaId: 'unrestricted', _version: version },
+ version,
+ })
+ )
+}
+
+async function freshStore(nav: { platform: string; userAgent: string }) {
+ vi.resetModules()
+ vi.stubGlobal('window', globalThis)
+ vi.stubGlobal('localStorage', localStorageShim)
+ vi.stubGlobal('navigator', nav)
+ const mod = await import('../settingsStore')
+ return mod.useSettingsStore
+}
+
- describe('settingsStore v14 migration (Mac cloud-lock → local)', () => {
++describe('settingsStore migration (Mac cloud-lock → local)', () => {
+ beforeEach(() => backing.clear())
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('resets a force-pinned Mac install from cloud to local', async () => {
- seed({ appMode: 'cloud', temperature: 0.42 }, 13)
++ seed({ appMode: 'cloud', temperature: 0.42 }, CURRENT - 1)
+ const store = await freshStore(MAC_NAV)
+ const s = store.getState().settings
+ expect(s.appMode).toBe('local')
+ // Unrelated settings survive the migration.
+ expect(s.temperature).toBe(0.42)
+ })
+
- it('leaves a Windows install on its real cloud choice', async () => {
++ it('resets a Mac install coming from the cloud-only 2.5.x line', async () => {
++ // The Mac shipped cloud-only through 2.5.10 (store v13–v18), so every
++ // upgrade path below CURRENT has to land in local mode.
+ seed({ appMode: 'cloud' }, 13)
++ const store = await freshStore(MAC_NAV)
++ expect(store.getState().settings.appMode).toBe('local')
++ })
++
++ it('leaves a Windows install on its real cloud choice', async () => {
++ seed({ appMode: 'cloud' }, CURRENT - 1)
+ const store = await freshStore(WIN_NAV)
+ expect(store.getState().settings.appMode).toBe('cloud')
+ })
+
- it('does not touch a Mac install that already chose cloud on v14', async () => {
++ it('does not touch a Mac install that chose cloud after the wall was lifted', async () => {
+ // version === current → migrate is not invoked, so a legit later cloud
- // pick is preserved (we only reset the one-time forced pin from < 14).
- seed({ appMode: 'cloud' }, 14)
++ // pick is preserved (we only reset the one-time forced pin).
++ seed({ appMode: 'cloud' }, CURRENT)
+ const store = await freshStore(MAC_NAV)
+ expect(store.getState().settings.appMode).toBe('cloud')
+ })
+
+ it('rebuilds built-in personas while migrating', async () => {
- seed({ appMode: 'cloud' }, 13)
++ seed({ appMode: 'cloud' }, CURRENT - 1)
+ const store = await freshStore(MAC_NAV)
+ expect(store.getState().personas.length).toBeGreaterThan(0)
+ expect(store.getState().personas.some(p => p.isBuiltIn)).toBe(true)
+ })
+})
diff --cc src/stores/createStore.ts
index 72b30873,571501d7..fae5afd0
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@@ -110,14 -144,10 +144,14 @@@ export interface GalleryItem
builderUsed?: 'dynamic' | 'legacy' | 'custom'
resolvedVAE?: string
resolvedCLIP?: string
- /** Self-contained PNG data URL for backends that don't serve files over
- * ComfyUI's /view route (e.g. MLX on Apple Silicon). When set, display +
- * download read from this instead of filename/subfolder. In-memory only —
- * partialize strips it so media bytes never hit the localStorage quota. */
+ /** Self-contained media URL for backends that don't serve files over
+ * ComfyUI's /view route (e.g. MLX on Apple Silicon): a `data:` PNG URL for
+ * MLX images, or a `blob:` URL for MLX video (built from bytes read via
- * the `read_media_file` Tauri command — the CSP's media-src allows
- * `blob:` but not `data:` for video). When set, display + download read
- * from this instead of filename/subfolder. In-memory only — partialize
- * strips it so media bytes never hit the localStorage quota (and a
- * blob: URL wouldn't survive a reload anyway). */
++ * the `read_media_file` Tauri command — the CSP's media-src allows `blob:`
++ * but not `data:` for video). When set, display + download read from this
++ * instead of filename/subfolder. In-memory only — partialize strips it so
++ * media bytes never hit the localStorage quota (and a blob: URL wouldn't
++ * survive a reload anyway). */
dataUrl?: string
/** Cloud jobs: signed result URL from the render queue. Display prefers
* `remoteUrl` → `dataUrl` → the ComfyUI /view path (filename/subfolder). */
diff --cc src/stores/settingsStore.ts
index 2852b46d,b71cb8a7..d591b72e
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@@ -33,15 -33,28 +33,33 @@@ import { DEFAULT_SETTINGS, BUILT_IN_PER
// v12 (2.5.7): added settings.comfyGpuMode ('auto'|'cpu'|'gpu', default
// 'auto') for the AMD ComfyUI GPU path (rhodium92). Additive — the merge
// fills the default while preserving every existing value; NVIDIA unaffected.
- // v13 (2.5.7): added settings.cloudOnboardingSeen (one-time Cloud onboarding
- // on the first successful switch flip, default false). Additive merge.
- // v14 (2026-07-22): the macOS Cloud-only wall is lifted — the Mac app is a full
- // local+cloud app again (local mode built + tested). Existing Mac installs were
- // force-pinned to appMode 'cloud' with no real choice, so reset them to the
- // local default ONCE so they land in the now-built local mode; the visible
- // switch lets them flip back to cloud anytime. Windows/Linux appMode reflects a
- // real user choice and is never touched.
- const STORE_VERSION = 14
+ // v13 (2.5.7): added settings.cloudOnboardingSeen — REMOVED in 2.6.0: the
+ // one-time onboarding moved into the web checkout (#91); stale persisted
+ // values are ignored by the merge.
+ // v14 (2.5.8): added settings.cloudTeasersEnabled (Cloud discovery in Local
+ // mode: locked Create tabs + hosted-model picker rows, default true). Additive.
+ // v15 (2.5.9): added settings.codexCloudConfirmShell (default true). The cloud
+ // shell-confirm was hard-wired in useCodex, so the existing confirm toggle did
+ // nothing on a cloud model. Additive merge backfills the default — behaviour is
+ // byte-for-byte what 2.5.8 did until the user turns the new switch off.
+ // v16 (2.5.9): added settings.loopMaxPasses (default 0 = unlimited). Additive,
+ // but the bump is what makes the merge RUN — without it an existing profile
+ // keeps the field undefined and the Settings number box renders empty, which
+ // is how this was caught on the ship exe (2026-07-25). Behaviour was already
+ // correct via `?? 0`; this is so the UI shows the real value.
+ // v17 (2.5.10): added settings.codexAutoApply (default false) — auto-apply
+ // staged changes when the run finishes. Additive merge backfills the default;
+ // stage-mode behaviour is unchanged until the user turns the new switch on.
+ // v18 (2.6.0): added settings.builtinEngine (expert tuning for the bundled
+ // llama-server: ctx, flash attention, KV-cache quant, threads, GPU layers,
+ // mlock/mmap; defaults = the exact pre-2.6.0 argv). Additive merge backfills
+ // the default object; engine behaviour is unchanged until the user edits it.
-const STORE_VERSION = 18
++// v19 (2.6.0): the macOS Cloud-only wall is lifted — the Mac app is a full
++// local+cloud app again. Existing Mac installs were force-pinned to appMode
++// 'cloud' with no real choice, so reset them to the local default ONCE so they
++// land in the now-built local mode; the visible switch flips back anytime.
++// Windows/Linux appMode reflects a real user choice and is never touched.
++const STORE_VERSION = 19
interface SettingsState {
settings: Settings
@@@ -122,13 -135,6 +140,13 @@@ export const useSettingsStore = create<
mergedSettings.preferredVideoT2VModel = ''
mergedSettings.preferredVideoI2VModel = ''
}
- // v14: reset the force-pinned Mac cloud lock to the local default.
- if (version < 14) {
++ // v19: release the Mac cloud lock (see the version log above).
++ if (version < 19) {
+ const isMac = typeof navigator !== 'undefined' &&
+ (/Mac|iPhone|iPad|iPod/.test(navigator.platform || '') ||
+ /Mac OS X|Macintosh/.test(navigator.userAgent || ''))
+ if (isMac) mergedSettings.appMode = 'local'
+ }
return {
...persisted,
settings: mergedSettings,