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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix: Tauri .exe fully working — CORS proxy, download manager, model bundles
PurpleDoubleDec2cb6249a9a
diff --git a/CLAUDE.md b/CLAUDE.mdindex d1ac06b9..5f0d6234 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -49,7 +49,7 @@ docs/ — Static landing pages and blog (GitHub Pages)- **Model Types**: `flux | flux2 | sdxl | sd15 | wan | hunyuan | unknown`- **Dynamic Builder**: Queries `/object_info` for all 600+ nodes, auto-selects strategy (unet_flux, unet_video, checkpoint, animatediff)- **Legacy Builders**: `buildSDXLImgWorkflow`, `buildFluxImgWorkflow`, `buildWanVideoWorkflow`, `buildAnimateDiffWorkflow` — kept as fallback-- **VAE/CLIP Resolution**: `findMatchingVAE()` and `findMatchingCLIP()` match by model type keywords+- **VAE/CLIP Resolution**: `findMatchingVAE()` and `findMatchingCLIP()` match by model type keywords (flux→ae/flux, wan→wan, hunyuan→hunyuanvideo/qwen)## Generation Flow@@ -61,7 +61,7 @@ User clicks Generate→ If incompatible (wrong loader type): skip, use auto→ buildDynamicWorkflow() — queries /object_info, picks strategy→ Fallback: legacy builders if dynamic fails-→ submitWorkflow() via POST /comfyui/prompt (custom middleware)+→ submitWorkflow() via localFetch to ComfyUI /prompt→ Poll /history/{promptId} every 1s→ On complete: extract outputs, show execution time, add to gallery```@@ -94,22 +94,39 @@ npm run tauri:build # Build desktop .exe- **State**: Zustand stores with `persist` middleware for user data- **Commits**: Conventional commits (feat/fix/docs), Co-Authored-By Claude- **No emojis** in code/UI unless explicitly requested-- **WIP Features**: RAG, Voice, AI Agents — code stays, marked "work in progress"+- **Default View**: Model Manager (not Chat) — configured in `uiStore.ts`## Tauri Production (.exe) — CRITICALEvery feature that works in dev mode MUST also work in the Tauri .exe. The #1 source of bugs:+- **CORS blocking**: In Tauri, the WebView origin is `http://tauri.localhost`. Direct `fetch()` to `http://localhost:11434` or `http://localhost:8188` is blocked by CORS. ALL localhost calls MUST go through `localFetch()` / `localFetchStream()` from `backend.ts`, which routes through Rust `invoke('proxy_localhost')` in production.+- **NEVER use `fetch(ollamaUrl(...))` or `fetch(comfyuiUrl(...))`** — always use `localFetch(ollamaUrl(...))` or `localFetch(comfyuiUrl(...))`+- **CSP must include `http://ipc.localhost`** — Tauri IPC uses this origin, CSP blocks invoke() without it- **Dual-mode routing**: `src/api/backend.ts` routes `backendCall()` to Vite middleware (dev) or Rust `invoke()` (production)-- **External API calls**: NEVER use `fetch('/civitai-api/...')` directly. Use `fetchExternal()` from `backend.ts` which works in both modes-- **External downloads**: NEVER use `fetch('/local-api/proxy-download?url=...')` directly. Use `fetchExternalBytes()` from `backend.ts`+- **External API calls**: NEVER use `fetch('/civitai-api/...')` directly. Use `fetchExternal()` from `backend.ts`- **New Vite middleware = new Rust command**: If you add a `/local-api/*` endpoint to `vite.config.ts`, you MUST also implement the equivalent `#[tauri::command]` in `src-tauri/src/commands/`- **Endpoint map**: All dev-mode routes must be in the `endpointMap` in `backend.ts`-- **Download progress**: Uses `Arc<Mutex<HashMap>>` shared between spawned task and progress endpoint. Never use `State<'_>` directly in `tokio::spawn`+- **Ollama URL**: `ollamaUrl()` returns `http://localhost:11434/api{path}` in Tauri (the `/api` prefix is required!)+- **Download manager**: Uses `CancellationToken` for pause/cancel, `Range` header for resume. Downloads tracked in `Arc<Mutex<HashMap>>` shared between spawned task and progress endpoint- **Process stdout/stderr**: Always drain piped outputs in background threads or ComfyUI will deadlock-- **CSP**: `tauri.conf.json` must whitelist external domains for fetch (civitai.com, huggingface.co)+- **ComfyUI path discovery**: Deep scans user home (depth 7), also checks running process. Falls back to manual path input in UI.- **Test the .exe**: After any backend change, verify with `cargo check` in `src-tauri/`+## Model Bundles (Image + Video)++Complete packages in `src/api/discover.ts` — "Install All" downloads everything needed:++**Image (3):** Juggernaut XL V9 (SDXL), FLUX.1 schnell FP8, FLUX.1 dev FP8+- SDXL: single checkpoint file (includes VAE+CLIP)+- FLUX: 4 files each (UNET + VAE + T5-XXL + CLIP_L)++**Video (3):** Wan 2.1 1.3B, Wan 2.1 14B FP8, HunyuanVideo 1.5 T2V FP8+- Wan: 3 files (Model + VAE + UMT5)+- HunyuanVideo: 4 files (Model + VAE + Qwen2.5 + CLIP_L)++All URLs verified working (HTTP 200) from Comfy-Org / comfyanonymous HuggingFace repos.+## Common Pitfalls- **Vite 8 POST blocking**: All POST to ComfyUI must go through the custom middleware in vite.config.ts, not the standard proxy@@ -118,3 +135,4 @@ Every feature that works in dev mode MUST also work in the Tauri .exe. The #1 so- **CivitAI downloads**: Need API key (user enters in Workflow Finder). Downloads are ZIP archives, not raw JSON- **ComfyUI workflow formats**: Two formats exist — API format (`class_type` nodes) and Web/UI format (`nodes[]` + `links[]`). The app handles both via `convertWebToApiFormat()`- **CLIP/VAE fallback**: Never silently use wrong model type. Throw descriptive error with download instructions instead+- **HunyuanVideo VAE/CLIP**: Uses `hunyuanvideo` VAE (not Wan VAE) and `qwen` text encoder (not UMT5). Matchers in `comfyui.ts` handle this separately.diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 1778b102..f82917a3 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -1874,6 +1874,7 @@ dependencies = ["tauri-plugin-shell","tempfile","tokio",+ "tokio-util","urlencoding",]diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 1752c11c..6db66a33 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -9,7 +9,7 @@ edition = "2021"tauri-build = { version = "2", features = [] }[dependencies]-tauri = { version = "2", features = [] }+tauri = { version = "2", features = ["devtools"] }tauri-plugin-shell = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"@@ -20,6 +20,7 @@ regex = "1"base64 = "0.22"tempfile = "3"futures-util = "0.3"+tokio-util = "0.7"urlencoding = "2"[profile.release]diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex ce0c2e61..77f6876f 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -6,6 +6,7 @@ use std::time::Instant;use futures_util::StreamExt;use tauri::State;+use tokio_util::sync::CancellationToken;use crate::state::{AppState, DownloadProgress};@@ -24,7 +25,13 @@ pub async fn download_model(state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let comfy_path = {- let p = state.comfy_path.lock().unwrap();+ let mut p = state.comfy_path.lock().unwrap();+ if p.is_none() {+ if let Some(found) = crate::commands::process::find_comfyui_path() {+ println!("[Download] Auto-discovered ComfyUI at: {}", found);+ *p = Some(found);+ }+ }p.clone()};@@ -35,13 +42,29 @@ pub async fn download_model(return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));}- let id = format!("{}-{}", subfolder, filename);+ // Use filename as ID (matches frontend lookup)+ let id = filename.clone();++ // Check for existing partial download (resume support)+ let tmp_path = dest_file.with_extension("download");+ let resume_offset = if tmp_path.exists() {+ tmp_path.metadata().map(|m| m.len()).unwrap_or(0)+ } else {+ 0+ };++ // Create cancellation token+ let token = CancellationToken::new();+ {+ let mut tokens = state.download_tokens.lock().unwrap();+ tokens.insert(id.clone(), token.clone());+ }// Initialize progress{let mut downloads = state.downloads.lock().unwrap();downloads.insert(id.clone(), DownloadProgress {- progress: 0,+ progress: resume_offset,total: 0,speed: 0.0,filename: filename.clone(),@@ -50,13 +73,13 @@ pub async fn download_model(});}- // Clone the Arc so the spawned task can update progresslet downloads_arc = Arc::clone(&state.downloads);+ let tokens_arc = Arc::clone(&state.download_tokens);let id_clone = id.clone();let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -66,15 +89,32 @@ pub async fn download_model(println!("[Download] Complete: {}", filename_clone);}Err(e) => {- if let Ok(mut dl) = downloads_arc.lock() {- if let Some(p) = dl.get_mut(&id_clone) {- p.status = "error".to_string();- p.error = Some(e.clone());+ if e == "paused" {+ println!("[Download] Paused: {}", filename_clone);+ // Status already set to "paused" in do_download+ } else if e == "cancelled" {+ // Clean up temp file+ let tmp = dest_file.with_extension("download");+ let _ = std::fs::remove_file(&tmp);+ if let Ok(mut dl) = downloads_arc.lock() {+ dl.remove(&id_clone);}+ println!("[Download] Cancelled: {}", filename_clone);+ } else {+ if let Ok(mut dl) = downloads_arc.lock() {+ if let Some(p) = dl.get_mut(&id_clone) {+ p.status = "error".to_string();+ p.error = Some(e.clone());+ }+ }+ println!("[Download] Failed: {} - {}", filename_clone, e);}- println!("[Download] Failed: {} - {}", filename_clone, e);}}+ // Clean up token+ if let Ok(mut tokens) = tokens_arc.lock() {+ tokens.remove(&id_clone);+ }});Ok(serde_json::json!({"status": "started", "id": id}))@@ -85,24 +125,41 @@ async fn do_download(dest: &PathBuf,downloads: &Arc<Mutex<HashMap<String, DownloadProgress>>>,id: &str,+ token: CancellationToken,+ resume_offset: u64,) -> Result<(), String> {let client = reqwest::Client::builder().user_agent("LocallyUncensored/1.5").redirect(reqwest::redirect::Policy::limited(10))- .timeout(std::time::Duration::from_secs(7200)) // 2 hours for large models+ .timeout(std::time::Duration::from_secs(7200)).build().map_err(|e| e.to_string())?;- let response = client.get(url)+ let mut request = client.get(url);++ // Resume support: request only remaining bytes+ if resume_offset > 0 {+ request = request.header("Range", format!("bytes={}-", resume_offset));+ println!("[Download] Resuming from byte {}", resume_offset);+ }++ let response = request.send().await.map_err(|e| format!("Request failed: {}", e))?;- if !response.status().is_success() {- return Err(format!("HTTP {}", response.status()));+ let status = response.status();+ if !status.is_success() && status.as_u16() != 206 {+ return Err(format!("HTTP {}", status));}- let total = response.content_length().unwrap_or(0);+ // For resumed downloads, total = content_length + offset+ let content_length = response.content_length().unwrap_or(0);+ let total = if resume_offset > 0 && status.as_u16() == 206 {+ content_length + resume_offset+ } else {+ content_length+ };// Update total sizeif let Ok(mut dl) = downloads.lock() {@@ -113,31 +170,83 @@ async fn do_download(}let tmp_path = dest.with_extension("download");- let mut file = tokio::fs::File::create(&tmp_path)- .await- .map_err(|e| format!("Create file: {}", e))?;++ // Open file for writing (append if resuming)+ let mut file = if resume_offset > 0 && status.as_u16() == 206 {+ tokio::fs::OpenOptions::new()+ .append(true)+ .open(&tmp_path)+ .await+ .map_err(|e| format!("Open file for resume: {}", e))?+ } else {+ tokio::fs::File::create(&tmp_path)+ .await+ .map_err(|e| format!("Create file: {}", e))?+ };let mut stream = response.bytes_stream();- let mut downloaded: u64 = 0;+ let mut downloaded: u64 = resume_offset;let start = Instant::now();let mut last_update = Instant::now();use tokio::io::AsyncWriteExt;- while let Some(chunk) = stream.next().await {- let chunk = chunk.map_err(|e| format!("Stream error: {}", e))?;- file.write_all(&chunk).await.map_err(|e| format!("Write: {}", e))?;- downloaded += chunk.len() as u64;-- // Update progress every 500ms- if last_update.elapsed().as_millis() > 500 {- last_update = Instant::now();- let elapsed = start.elapsed().as_secs_f64();- let speed = if elapsed > 0.0 { downloaded as f64 / elapsed } else { 0.0 };-- if let Ok(mut dl) = downloads.lock() {- if let Some(p) = dl.get_mut(id) {- p.progress = downloaded;- p.speed = speed;++ loop {+ tokio::select! {+ _ = token.cancelled() => {+ file.flush().await.ok();+ drop(file);++ // Check if this is a pause or cancel+ let is_paused = if let Ok(dl) = downloads.lock() {+ dl.get(id).map(|p| p.status == "pausing").unwrap_or(false)+ } else {+ false+ };++ if is_paused {+ if let Ok(mut dl) = downloads.lock() {+ if let Some(p) = dl.get_mut(id) {+ p.status = "paused".to_string();+ p.progress = downloaded;+ }+ }+ return Err("paused".to_string());+ } else {+ return Err("cancelled".to_string());+ }+ }+ chunk = stream.next() => {+ match chunk {+ Some(Ok(bytes)) => {+ file.write_all(&bytes).await.map_err(|e| format!("Write: {}", e))?;+ downloaded += bytes.len() as u64;++ // Update progress every 500ms+ if last_update.elapsed().as_millis() > 500 {+ last_update = Instant::now();+ let elapsed = start.elapsed().as_secs_f64();+ let speed = if elapsed > 0.0 {+ (downloaded - resume_offset) as f64 / elapsed+ } else {+ 0.0+ };++ if let Ok(mut dl) = downloads.lock() {+ if let Some(p) = dl.get_mut(id) {+ p.progress = downloaded;+ p.speed = speed;+ }+ }+ }+ }+ Some(Err(e)) => {+ return Err(format!("Stream error: {}", e));+ }+ None => {+ // Stream complete+ break;+ }}}}@@ -162,6 +271,154 @@ async fn do_download(Ok(())}+#[tauri::command]+pub fn pause_download(id: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ // Set status to "pausing" so the download loop knows it's a pause, not cancel+ if let Ok(mut dl) = state.downloads.lock() {+ if let Some(p) = dl.get_mut(&id) {+ if p.status != "downloading" && p.status != "connecting" {+ return Ok(serde_json::json!({"status": "not_active"}));+ }+ p.status = "pausing".to_string();+ }+ }++ // Cancel the token (the download loop checks for "pausing" status to distinguish pause from cancel)+ if let Ok(tokens) = state.download_tokens.lock() {+ if let Some(token) = tokens.get(&id) {+ token.cancel();+ }+ }++ Ok(serde_json::json!({"status": "pausing"}))+}++#[tauri::command]+pub fn cancel_download(id: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ // Cancel the token+ if let Ok(tokens) = state.download_tokens.lock() {+ if let Some(token) = tokens.get(&id) {+ token.cancel();+ }+ }++ // If paused (no active token), clean up directly+ let was_paused = if let Ok(dl) = state.downloads.lock() {+ dl.get(&id).map(|p| p.status == "paused").unwrap_or(false)+ } else {+ false+ };++ if was_paused {+ // Remove from progress+ if let Ok(mut dl) = state.downloads.lock() {+ dl.remove(&id);+ }+ // Delete temp file — need comfy_path to find it+ // The temp file cleanup is best-effort+ if let Ok(comfy_path) = state.comfy_path.lock() {+ if let Some(ref path) = *comfy_path {+ // Try common subfolders+ for subfolder in &["diffusion_models", "checkpoints", "vae", "text_encoders", "loras"] {+ let tmp = PathBuf::from(path).join("models").join(subfolder).join(&id).with_extension("download");+ let _ = std::fs::remove_file(&tmp);+ }+ }+ }+ }++ Ok(serde_json::json!({"status": "cancelled"}))+}++#[tauri::command]+pub async fn resume_download(+ id: String,+ url: String,+ subfolder: String,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let comfy_path = {+ let p = state.comfy_path.lock().unwrap();+ p.clone()+ };++ let dest_dir = models_dir(&comfy_path, &subfolder)?;+ let dest_file = dest_dir.join(&id);+ let tmp_path = dest_file.with_extension("download");++ let resume_offset = if tmp_path.exists() {+ tmp_path.metadata().map(|m| m.len()).unwrap_or(0)+ } else {+ 0+ };++ // Create new cancellation token+ let token = CancellationToken::new();+ {+ let mut tokens = state.download_tokens.lock().unwrap();+ tokens.insert(id.clone(), token.clone());+ }++ // Update status+ {+ let mut downloads = state.downloads.lock().unwrap();+ if let Some(p) = downloads.get_mut(&id) {+ p.status = "connecting".to_string();+ } else {+ downloads.insert(id.clone(), DownloadProgress {+ progress: resume_offset,+ total: 0,+ speed: 0.0,+ filename: id.clone(),+ status: "connecting".to_string(),+ error: None,+ });+ }+ }++ let downloads_arc = Arc::clone(&state.downloads);+ let tokens_arc = Arc::clone(&state.download_tokens);+ let id_clone = id.clone();++ tokio::spawn(async move {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ Ok(_) => {+ if let Ok(mut dl) = downloads_arc.lock() {+ if let Some(p) = dl.get_mut(&id_clone) {+ p.status = "complete".to_string();+ }+ }+ println!("[Download] Complete: {}", id_clone);+ }+ Err(e) => {+ if e == "paused" {+ println!("[Download] Paused: {}", id_clone);+ } else if e == "cancelled" {+ let tmp = dest_file.with_extension("download");+ let _ = std::fs::remove_file(&tmp);+ if let Ok(mut dl) = downloads_arc.lock() {+ dl.remove(&id_clone);+ }+ println!("[Download] Cancelled: {}", id_clone);+ } else {+ if let Ok(mut dl) = downloads_arc.lock() {+ if let Some(p) = dl.get_mut(&id_clone) {+ p.status = "error".to_string();+ p.error = Some(e.clone());+ }+ }+ println!("[Download] Failed: {} - {}", id_clone, e);+ }+ }+ }+ if let Ok(mut tokens) = tokens_arc.lock() {+ tokens.remove(&id_clone);+ }+ });++ Ok(serde_json::json!({"status": "resuming", "offset": resume_offset}))+}+#[tauri::command]pub fn download_progress(state: State<'_, AppState>) -> Result<serde_json::Value, String> {let downloads = state.downloads.lock().unwrap();diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex db27da5d..faf8afe1 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -15,9 +15,15 @@ fn scan_for_comfyui(dir: &Path, depth: u32) -> Option<PathBuf> {if depth == 0 {return None;}- let entries = fs::read_dir(dir).ok()?;+ let entries = match fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return None,+ };for entry in entries.flatten() {- let file_type = entry.file_type().ok()?;+ let file_type = match entry.file_type() {+ Ok(ft) => ft,+ Err(_) => continue, // Skip entries with permission errors+ };if !file_type.is_dir() {continue;}@@ -63,15 +69,38 @@ pub fn find_comfyui_path() -> Option<String> {}}+ // 2b. Deep scan user home directory (finds ComfyUI in non-standard paths like Desktop/bs/IMage Gen/ComfyUI)+ let home2 = dirs::home_dir().unwrap_or_default();+ if let Some(found) = scan_for_comfyui(&home2, 7) {+ println!("[ComfyUI] Found via deep home scan: {}", found.display());+ return Some(found.to_string_lossy().to_string());+ }+let home = dirs::home_dir().unwrap_or_default();- // 3. Check common fixed locations- let fixed = [+ // 3. Check common fixed locations (including Stability Matrix, portable installs)+ let mut fixed: Vec<PathBuf> = vec![home.join("ComfyUI"),home.join("Desktop").join("ComfyUI"),home.join("Documents").join("ComfyUI"),PathBuf::from("C:\\ComfyUI"),+ PathBuf::from("D:\\ComfyUI"),];++ if cfg!(target_os = "windows") {+ // Stability Matrix stores ComfyUI in AppData+ if let Ok(appdata) = std::env::var("APPDATA") {+ fixed.push(PathBuf::from(&appdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));+ }+ if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {+ fixed.push(PathBuf::from(&localappdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));+ }+ // Common Program Files locations+ fixed.push(PathBuf::from("C:\\Program Files\\ComfyUI"));+ fixed.push(PathBuf::from("C:\\AI\\ComfyUI"));+ fixed.push(PathBuf::from("D:\\AI\\ComfyUI"));+ }+for p in &fixed {if p.join("main.py").exists() {return Some(p.to_string_lossy().to_string());@@ -87,6 +116,7 @@ pub fn find_comfyui_path() -> Option<String> {if cfg!(target_os = "windows") {scan_roots.push(PathBuf::from("C:\\"));scan_roots.push(PathBuf::from("D:\\"));+ scan_roots.push(PathBuf::from("E:\\"));} else {scan_roots.push(PathBuf::from("/opt"));scan_roots.push(PathBuf::from("/usr/local"));@@ -94,7 +124,7 @@ pub fn find_comfyui_path() -> Option<String> {for root in &scan_roots {if root.exists() {- if let Some(found) = scan_for_comfyui(root, 4) {+ if let Some(found) = scan_for_comfyui(root, 5) {return Some(found.to_string_lossy().to_string());}}@@ -110,7 +140,7 @@ fn is_comfyui_running() -> bool {}#[tauri::command]-pub fn start_ollama(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+pub fn start_ollama(_state: State<'_, AppState>) -> Result<serde_json::Value, String> {// Check if already runningif let Ok(output) = Command::new("tasklist").args(["/FI", "IMAGENAME eq ollama.exe"])@@ -178,13 +208,8 @@ pub fn start_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, St.spawn().map_err(|e| format!("Failed to start ComfyUI (python={}): {}", python, e))?;- // Read stdout/stderr in background threads to prevent deadlock- let logs = state.comfy_logs.lock().unwrap().clone();- drop(logs);-+ // Drain stdout/stderr in background threads to prevent buffer deadlockif let Some(stdout) = child.stdout.take() {- let logs_ref = state.comfy_logs.lock().unwrap().clone();- drop(logs_ref);std::thread::spawn(move || {use std::io::{BufRead, BufReader};let reader = BufReader::new(stdout);@@ -310,7 +335,7 @@ pub fn set_comfyui_path(path: String, state: State<'_, AppState>) -> Result<serd}/// Auto-start Ollama on app launch (called from setup)-pub fn auto_start_ollama(state: &AppState) {+pub fn auto_start_ollama(_state: &AppState) {// Check if already runningif let Ok(output) = Command::new("tasklist").args(["/FI", "IMAGENAME eq ollama.exe"])@@ -338,6 +363,14 @@ pub fn auto_start_ollama(state: &AppState) {/// Auto-start ComfyUI on app launch (called from setup)pub fn auto_start_comfyui(state: &AppState) {+ // Always try to find and store the ComfyUI path (needed for downloads)+ if state.comfy_path.lock().unwrap().is_none() {+ if let Some(path) = find_comfyui_path() {+ println!("[ComfyUI] Found at: {}", path);+ *state.comfy_path.lock().unwrap() = Some(path);+ }+ }+if is_comfyui_running() {println!("[ComfyUI] Already running on port 8188");return;@@ -356,7 +389,31 @@ pub fn auto_start_comfyui(state: &AppState) {.stderr(Stdio::piped()).spawn(){- Ok(child) => {+ Ok(mut child) => {+ // Drain stdout/stderr in background threads to prevent buffer deadlock+ if let Some(stdout) = child.stdout.take() {+ std::thread::spawn(move || {+ use std::io::{BufRead, BufReader};+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if let Ok(line) = line {+ println!("[ComfyUI] {}", line);+ }+ }+ });+ }+ if let Some(stderr) = child.stderr.take() {+ std::thread::spawn(move || {+ use std::io::{BufRead, BufReader};+ let reader = BufReader::new(stderr);+ for line in reader.lines() {+ if let Ok(line) = line {+ println!("[ComfyUI] {}", line);+ }+ }+ });+ }+*state.comfy_process.lock().unwrap() = Some(child);println!("[ComfyUI] Started");}diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsindex 1535f593..2050edec 100644--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@ -42,6 +42,79 @@ pub async fn fetch_external_bytes(url: String) -> Result<Vec<u8>, String> {resp.bytes().await.map(|b| b.to_vec()).map_err(|e| e.to_string())}+/// Generic localhost proxy — fetch any localhost URL bypassing CORS.+/// Used for Ollama and ComfyUI API calls in production mode.+#[tauri::command]+pub async fn proxy_localhost(url: String, method: Option<String>, body: Option<String>) -> Result<String, String> {+ let client = reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.5")+ .timeout(std::time::Duration::from_secs(300))+ .build()+ .map_err(|e| e.to_string())?;++ let http_method = method.unwrap_or_else(|| "GET".to_string());++ let mut request = match http_method.as_str() {+ "POST" => client.post(&url),+ "DELETE" => client.delete(&url),+ "PUT" => client.put(&url),+ _ => client.get(&url),+ };++ if let Some(body_str) = body {+ request = request.header("Content-Type", "application/json").body(body_str);+ }++ let resp = request+ .send()+ .await+ .map_err(|e| format!("proxy_localhost: {}", e))?;++ if !resp.status().is_success() {+ let status = resp.status().as_u16();+ let text = resp.text().await.unwrap_or_default();+ return Err(format!("HTTP {}: {}", status, text));+ }++ resp.text().await.map_err(|e| e.to_string())+}++/// Streaming localhost proxy — returns raw bytes for streaming responses (Ollama pull/chat).+#[tauri::command]+pub async fn proxy_localhost_stream(url: String, method: Option<String>, body: Option<String>) -> Result<Vec<u8>, String> {+ let client = reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.5")+ .timeout(std::time::Duration::from_secs(7200))+ .build()+ .map_err(|e| e.to_string())?;++ let http_method = method.unwrap_or_else(|| "GET".to_string());++ let mut request = match http_method.as_str() {+ "POST" => client.post(&url),+ "DELETE" => client.delete(&url),+ "PUT" => client.put(&url),+ _ => client.get(&url),+ };++ if let Some(body_str) = body {+ request = request.header("Content-Type", "application/json").body(body_str);+ }++ let resp = request+ .send()+ .await+ .map_err(|e| format!("proxy_localhost_stream: {}", e))?;++ if !resp.status().is_success() {+ let status = resp.status().as_u16();+ let text = resp.text().await.unwrap_or_default();+ return Err(format!("HTTP {}: {}", status, text));+ }++ resp.bytes().await.map(|b| b.to_vec()).map_err(|e| e.to_string())+}+/// Proxy search requests to ollama.com (needed because frontend can't CORS to ollama.com)#[tauri::command]pub async fn ollama_search(query: String) -> Result<serde_json::Value, String> {diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex f4efa868..f1fb156c 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -7,6 +7,7 @@ mod state;use state::AppState;use tauri::Manager;+use tauri::WebviewWindowBuilder;fn main() {let app_state = AppState::new();@@ -35,6 +36,9 @@ fn main() {// Downloadscommands::download::download_model,commands::download::download_progress,+ commands::download::pause_download,+ commands::download::cancel_download,+ commands::download::resume_download,// Web searchcommands::search::web_search,commands::search::search_status,@@ -44,8 +48,15 @@ fn main() {commands::proxy::ollama_search,commands::proxy::fetch_external,commands::proxy::fetch_external_bytes,+ commands::proxy::proxy_localhost,+ commands::proxy::proxy_localhost_stream,]).setup(|app| {+ // Open DevTools for debugging+ if let Some(window) = app.get_webview_window("main") {+ window.open_devtools();+ }+let state = app.state::<AppState>();// Auto-start Ollamadiff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rsindex d355c746..fb1e7259 100644--- a/src-tauri/src/python.rs+++ b/src-tauri/src/python.rs@@ -1,25 +1,97 @@+use std::path::Path;use std::process::Command;/// Resolve the real Python binary path, filtering out Windows Store alias.pub fn get_python_bin() -> String {if cfg!(not(target_os = "windows")) {+ // On Linux/macOS, try python3 first, then python+ for bin in &["python3", "python"] {+ if let Ok(output) = Command::new(bin).arg("--version").output() {+ if output.status.success() {+ return bin.to_string();+ }+ }+ }return "python3".to_string();}- if let Ok(output) = Command::new("where")- .arg("python")- .output()- {+ // Windows: use `where python` and filter out WindowsApps alias+ if let Ok(output) = Command::new("where").arg("python").output() {if output.status.success() {let stdout = String::from_utf8_lossy(&output.stdout);for line in stdout.lines() {let path = line.trim();if !path.is_empty() && !path.contains("WindowsApps") {- return path.to_string();+ // Verify it actually runs+ if let Ok(check) = Command::new(path).arg("--version").output() {+ if check.status.success() {+ println!("[Python] Found via `where`: {}", path);+ return path.to_string();+ }+ }}}}}+ // Check common Windows Python install locations+ let common_paths = [+ // Standard Python.org installers+ "C:\\Python313\\python.exe",+ "C:\\Python312\\python.exe",+ "C:\\Python311\\python.exe",+ "C:\\Python310\\python.exe",+ "C:\\Python39\\python.exe",+ ];++ for p in &common_paths {+ if Path::new(p).exists() {+ println!("[Python] Found at fixed path: {}", p);+ return p.to_string();+ }+ }++ // Check user-local Python (AppData\Local\Programs\Python)+ if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {+ let programs_python = Path::new(&localappdata).join("Programs").join("Python");+ if programs_python.exists() {+ // Scan for Python3xx directories, newest first+ if let Ok(entries) = std::fs::read_dir(&programs_python) {+ let mut dirs: Vec<_> = entries+ .filter_map(|e| e.ok())+ .filter(|e| e.file_type().ok().map_or(false, |ft| ft.is_dir()))+ .collect();+ dirs.sort_by(|a, b| b.file_name().cmp(&a.file_name()));++ for dir in dirs {+ let python_exe = dir.path().join("python.exe");+ if python_exe.exists() {+ let path = python_exe.to_string_lossy().to_string();+ println!("[Python] Found in AppData: {}", path);+ return path;+ }+ }+ }+ }+ }++ // Check Conda environments+ if let Ok(userprofile) = std::env::var("USERPROFILE") {+ let conda_paths = [+ Path::new(&userprofile).join("miniconda3").join("python.exe"),+ Path::new(&userprofile).join("anaconda3").join("python.exe"),+ Path::new(&userprofile).join("miniconda3").join("Scripts").join("python.exe"),+ Path::new(&userprofile).join("anaconda3").join("Scripts").join("python.exe"),+ ];+ for p in &conda_paths {+ if p.exists() {+ let path = p.to_string_lossy().to_string();+ println!("[Python] Found Conda: {}", path);+ return path;+ }+ }+ }++ println!("[Python] WARNING: No reliable Python found, falling back to 'python'");"python".to_string()}diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 6826066d..09ae08a8 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -3,6 +3,8 @@ use std::process::Child;use std::sync::atomic::AtomicBool;use std::sync::{Arc, Mutex};+use tokio_util::sync::CancellationToken;+use crate::commands::whisper::WhisperServer;use crate::python::get_python_bin;@@ -34,10 +36,10 @@ impl Default for InstallState {pub struct AppState {pub comfy_process: Mutex<Option<Child>>,- pub comfy_logs: Mutex<Vec<String>>,pub comfy_path: Mutex<Option<String>>,pub whisper: Mutex<WhisperServer>,pub downloads: Arc<Mutex<HashMap<String, DownloadProgress>>>,+ pub download_tokens: Arc<Mutex<HashMap<String, CancellationToken>>>,pub install_status: Mutex<InstallState>,pub searxng_install: Mutex<InstallState>,pub searxng_available: AtomicBool,@@ -51,10 +53,10 @@ impl AppState {Self {comfy_process: Mutex::new(None),- comfy_logs: Mutex::new(Vec::new()),comfy_path: Mutex::new(None),whisper: Mutex::new(WhisperServer::new()),downloads: Arc::new(Mutex::new(HashMap::new())),+ download_tokens: Arc::new(Mutex::new(HashMap::new())),install_status: Mutex::new(InstallState::default()),searxng_install: Mutex::new(InstallState::default()),searxng_available: AtomicBool::new(false),diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 9796a977..3b3a57f6 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -21,7 +21,7 @@}],"security": {- "csp": "default-src 'self'; connect-src 'self' http://localhost:* http://127.0.0.1:* https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com ws://localhost:8188 ws://127.0.0.1:8188; img-src 'self' data: blob: http://localhost:8188 http://127.0.0.1:8188 https://*.civitai.com https://*.githubusercontent.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'"+ "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com ws://localhost:8188 ws://127.0.0.1:8188; img-src 'self' data: blob: http://localhost:8188 http://127.0.0.1:8188 https://*.civitai.com https://*.githubusercontent.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"}},"bundle": {diff --git a/src/api/agents.ts b/src/api/agents.tsindex 48b863a8..40b64b95 100644--- a/src/api/agents.ts+++ b/src/api/agents.ts@@ -1,5 +1,5 @@import type { Tool, ToolName, ToolCall, AgentLogEntry } from "../types/agents";-import { backendCall, ollamaUrl } from "./backend";+import { backendCall, ollamaUrl, localFetch } from "./backend";export const AGENT_TOOLS: Tool[] = [{@@ -337,9 +337,8 @@ export async function chatNonStreaming(model: string,messages: { role: string; content: string }[]): Promise<string> {- const res = await fetch(ollamaUrl("/chat"), {+ const res = await localFetch(ollamaUrl("/chat"), {method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({model,messages,diff --git a/src/api/backend.ts b/src/api/backend.tsindex 1e09be33..cfa58936 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -4,7 +4,8 @@* - DEV MODE (npm run dev): Routes to Vite middleware via fetch("/local-api/...")* - PRODUCTION (Tauri .exe): Routes to Rust backend via invoke()*- * Ollama/ComfyUI calls go directly to localhost in production (CSP allows it).+ * IMPORTANT: In Tauri, direct fetch() to localhost is blocked by CORS.+ * All Ollama/ComfyUI calls must go through invoke('proxy_localhost').*/let _invoke: ((cmd: string, args?: Record<string, unknown>) => Promise<unknown>) | null = null;@@ -22,6 +23,72 @@ async function getInvoke() {return _invoke;}+/**+ * Fetch a localhost URL, bypassing CORS in Tauri mode.+ * In dev mode: uses normal fetch().+ * In Tauri .exe: routes through Rust proxy_localhost command.+ */+export async function localFetch(+ url: string,+ options?: { method?: string; body?: string; headers?: Record<string, string> }+): Promise<Response> {+ if (!isTauri()) {+ return fetch(url, {+ method: options?.method || "GET",+ headers: options?.headers,+ body: options?.body,+ });+ }++ // In Tauri: route through Rust to bypass CORS+ const invoke = await getInvoke();+ const method = options?.method || "GET";++ try {+ const text = await invoke("proxy_localhost", {+ url,+ method,+ body: options?.body || null,+ }) as string;++ return new Response(text, { status: 200, headers: { "Content-Type": "application/json" } });+ } catch (err) {+ return new Response(JSON.stringify({ error: String(err) }), { status: 500 });+ }+}++/**+ * Streaming fetch for localhost — returns raw bytes in Tauri, normal Response in dev.+ * Used for Ollama streaming endpoints (pull, chat).+ */+export async function localFetchStream(+ url: string,+ options?: { method?: string; body?: string }+): Promise<Response> {+ if (!isTauri()) {+ return fetch(url, {+ method: options?.method || "GET",+ body: options?.body,+ headers: options?.body ? { "Content-Type": "application/json" } : undefined,+ });+ }++ // In Tauri: get all bytes at once through Rust proxy (no true streaming, but works)+ const invoke = await getInvoke();+ try {+ const bytes = await invoke("proxy_localhost_stream", {+ url,+ method: options?.method || "GET",+ body: options?.body || null,+ }) as number[];++ const uint8 = new Uint8Array(bytes);+ return new Response(uint8, { status: 200, headers: { "Content-Type": "application/x-ndjson" } });+ } catch (err) {+ return new Response(JSON.stringify({ error: String(err) }), { status: 500 });+ }+}+/*** Call a backend command. Routes to Tauri invoke() or Vite fetch() automatically.*/@@ -51,6 +118,9 @@ export async function backendCall<T = any>(file_write: { path: "/local-api/file-write", method: "POST" },download_model: { path: "/local-api/download-model", method: "POST" },download_progress: { path: "/local-api/download-progress" },+ pause_download: { path: "/local-api/pause-download", method: "POST" },+ cancel_download: { path: "/local-api/cancel-download", method: "POST" },+ resume_download: { path: "/local-api/resume-download", method: "POST" },web_search: { path: "/local-api/web-search", method: "POST" },search_status: { path: "/local-api/search-status" },install_searxng: { path: "/local-api/install-searxng", method: "POST" },@@ -95,7 +165,7 @@ export async function backendCall<T = any>(/** Get the base URL for Ollama API calls */export function ollamaUrl(path: string): string {if (isTauri()) {- return `http://localhost:11434${path}`;+ return `http://localhost:11434/api${path}`;}return `/api${path}`;}diff --git a/src/api/comfyui-nodes.ts b/src/api/comfyui-nodes.tsindex 0e3af18d..218379da 100644--- a/src/api/comfyui-nodes.ts+++ b/src/api/comfyui-nodes.ts@@ -1,4 +1,4 @@-import { comfyuiUrl } from './backend'+import { comfyuiUrl, localFetch } from './backend'// ─── Types ───@@ -48,7 +48,7 @@ export async function getAllNodeInfo(forceRefresh = false): Promise<Record<strinreturn nodeInfoCache}- const res = await fetch(comfyuiUrl('/object_info'), { signal: AbortSignal.timeout(10000) })+ const res = await localFetch(comfyuiUrl('/object_info'))if (!res.ok) throw new Error(`Failed to fetch node info: ${res.status}`)const data = await res.json()diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 8061fca1..d6a362f4 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -1,4 +1,4 @@-import { comfyuiUrl } from "./backend"+import { comfyuiUrl, localFetch } from "./backend"// ─── Types ───@@ -61,7 +61,7 @@ function isVideoModelType(type: ModelType): boolean {export async function checkComfyConnection(): Promise<boolean> {try {- const res = await fetch(comfyuiUrl('/system_stats'), { signal: AbortSignal.timeout(5000) })+ const res = await localFetch(comfyuiUrl('/system_stats'))return res.ok} catch {return false@@ -71,7 +71,7 @@ export async function checkComfyConnection(): Promise<boolean> {// Check if a specific node exists in ComfyUI (lightweight, single node check)async function nodeExists(nodeName: string): Promise<boolean> {try {- const res = await fetch(comfyuiUrl(`/object_info/${nodeName}`), { signal: AbortSignal.timeout(3000) })+ const res = await localFetch(comfyuiUrl(`/object_info/${nodeName}`))if (!res.ok) return falseconst data = await res.json()return !!(data && data[nodeName])@@ -82,7 +82,7 @@ async function nodeExists(nodeName: string): Promise<boolean> {export async function getCheckpoints(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/CheckpointLoaderSimple'))+ const res = await localFetch(comfyuiUrl('/object_info/CheckpointLoaderSimple'))if (!res.ok) return []const data = await res.json()return data?.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0] ?? []@@ -94,7 +94,7 @@ export async function getCheckpoints(): Promise<string[]> {export async function getDiffusionModels(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/UNETLoader'))+ const res = await localFetch(comfyuiUrl('/object_info/UNETLoader'))if (!res.ok) return []const data = await res.json()return data?.UNETLoader?.input?.required?.unet_name?.[0] ?? []@@ -106,7 +106,7 @@ export async function getDiffusionModels(): Promise<string[]> {export async function getVAEModels(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/VAELoader'))+ const res = await localFetch(comfyuiUrl('/object_info/VAELoader'))if (!res.ok) return []const data = await res.json()return data?.VAELoader?.input?.required?.vae_name?.[0] ?? []@@ -118,7 +118,7 @@ export async function getVAEModels(): Promise<string[]> {export async function getCLIPModels(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/CLIPLoader'))+ const res = await localFetch(comfyuiUrl('/object_info/CLIPLoader'))if (!res.ok) return []const data = await res.json()return data?.CLIPLoader?.input?.required?.clip_name?.[0] ?? []@@ -130,7 +130,7 @@ export async function getCLIPModels(): Promise<string[]> {export async function getSamplers(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/KSampler'))+ const res = await localFetch(comfyuiUrl('/object_info/KSampler'))if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.sampler_name?.[0] ?? []@@ -141,7 +141,7 @@ export async function getSamplers(): Promise<string[]> {export async function getSchedulers(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/KSampler'))+ const res = await localFetch(comfyuiUrl('/object_info/KSampler'))if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.scheduler?.[0] ?? []@@ -152,7 +152,7 @@ export async function getSchedulers(): Promise<string[]> {export async function getAnimateDiffModels(): Promise<string[]> {try {- const res = await fetch(comfyuiUrl('/object_info/ADE_LoadAnimateDiffModel'))+ const res = await localFetch(comfyuiUrl('/object_info/ADE_LoadAnimateDiffModel'))if (!res.ok) return []const data = await res.json()return data?.ADE_LoadAnimateDiffModel?.input?.required?.model_name?.[0] ?? []@@ -237,10 +237,19 @@ export async function findMatchingVAE(modelType: ModelType): Promise<string> {if (match) return matchthrow new Error(`No FLUX VAE found. Download "ae.safetensors" from the Model Manager (FLUX bundles include it).`)}- if (modelType === 'wan' || modelType === 'hunyuan') {- const match = vaes.find(v => lower(v).includes('wan') || lower(v).includes('hunyuan'))+ if (modelType === 'hunyuan') {+ // HunyuanVideo has its own VAE — prefer it, fall back to Wan VAE+ const match = vaes.find(v => lower(v).includes('hunyuanvideo'))+ || vaes.find(v => lower(v).includes('hunyuan'))+ || vaes.find(v => lower(v).includes('wan'))if (match) return match- throw new Error(`No Wan/Hunyuan VAE found. Download "wan_2.1_vae.safetensors" from the Model Manager.`)+ throw new Error(`No HunyuanVideo VAE found. Download "hunyuanvideo15_vae_fp16.safetensors" from the Model Manager.`)+ }+ if (modelType === 'wan') {+ const match = vaes.find(v => lower(v).includes('wan'))+ || vaes.find(v => lower(v).includes('hunyuan'))+ if (match) return match+ throw new Error(`No Wan VAE found. Download "wan_2.1_vae.safetensors" from the Model Manager.`)}// SDXL/SD1.5 checkpoints include VAE — any VAE works as fallbackreturn vaes[0]@@ -257,11 +266,19 @@ export async function findMatchingCLIP(modelType: ModelType): Promise<string> {if (match) return matchthrow new Error(`No FLUX text encoder (T5) found. Download "t5xxl_fp8_e4m3fn.safetensors" from the Model Manager.`)}- if (modelType === 'wan' || modelType === 'hunyuan') {+ if (modelType === 'hunyuan') {+ // HunyuanVideo 1.5 uses Qwen 2.5 VL, older versions use llava_llama3+ const match = clips.find(c => lower(c).includes('qwen'))+ || clips.find(c => lower(c).includes('llava'))+ || clips.find(c => lower(c).includes('umt5'))+ if (match) return match+ throw new Error(`No HunyuanVideo text encoder found. Download "qwen_2.5_vl_7b_fp8_scaled.safetensors" from the Model Manager.`)+ }+ if (modelType === 'wan') {const match = clips.find(c => lower(c).includes('umt5') || lower(c).includes('wan'))|| clips.find(c => lower(c).includes('t5'))if (match) return match- throw new Error(`No Wan/Hunyuan text encoder found. Download "umt5_xxl_fp8_e4m3fn_scaled.safetensors" from the Model Manager.`)+ throw new Error(`No Wan text encoder found. Download "umt5_xxl_fp8_e4m3fn_scaled.safetensors" from the Model Manager.`)}// SDXL/SD1.5 checkpoints include CLIP — any worksreturn clips[0]@@ -276,9 +293,8 @@ async function findAnimateDiffModel(): Promise<string> {// ─── Workflow Submission ───export async function submitWorkflow(workflow: Record<string, any>): Promise<string> {- const res = await fetch(comfyuiUrl('/prompt'), {+ const res = await localFetch(comfyuiUrl('/prompt'), {method: 'POST',- headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt: workflow }),})if (!res.ok) {@@ -308,15 +324,14 @@ export async function submitWorkflow(workflow: Record<string, any>): Promise<strexport async function cancelGeneration(): Promise<void> {try {- await fetch(comfyuiUrl('/interrupt'), { method: 'POST' })+ await localFetch(comfyuiUrl('/interrupt'), { method: 'POST' })} catch { /* best effort */ }}export async function freeMemory(): Promise<void> {try {- await fetch(comfyuiUrl('/free'), {+ await localFetch(comfyuiUrl('/free'), {method: 'POST',- headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ unload_models: true, free_memory: true }),})} catch { /* best effort */ }@@ -324,7 +339,7 @@ export async function freeMemory(): Promise<void> {export async function getHistory(promptId: string): Promise<any> {try {- const res = await fetch(comfyuiUrl(`/history/${promptId}`))+ const res = await localFetch(comfyuiUrl(`/history/${promptId}`))if (!res.ok) return nullconst data = await res.json()return data[promptId] ?? nulldiff --git a/src/api/discover.ts b/src/api/discover.tsindex f619132b..936e46a2 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -19,7 +19,7 @@ export interface DownloadProgress {total: numberspeed: numberfilename: string- status: 'connecting' | 'downloading' | 'complete' | 'error'+ status: 'connecting' | 'downloading' | 'pausing' | 'paused' | 'complete' | 'error'error?: string}@@ -37,6 +37,18 @@ export async function getDownloadProgress(): Promise<Record<string, DownloadProg}}+export async function pauseDownload(id: string): Promise<void> {+ await backendCall("pause_download", { id })+}++export async function cancelDownload(id: string): Promise<void> {+ await backendCall("cancel_download", { id })+}++export async function resumeDownload(id: string, url: string, subfolder: string): Promise<void> {+ await backendCall("resume_download", { id, url, subfolder })+}+// ─── Ollama Text Models ───export async function fetchAbliteratedModels(): Promise<DiscoverModel[]> {@@ -118,14 +130,14 @@ export function getImageBundles(): ModelBundle[] {tags: ['SDXL', 'Photorealistic', '1024px'],totalSizeGB: 6.5,vramRequired: '6-8 GB',- workflow: 'wan', // not used for image, just satisfies type- url: 'https://civitai.com/models/133005/juggernaut-xl',+ workflow: 'wan',+ url: 'https://huggingface.co/RunDiffusion/Juggernaut-XL-v9',files: [{- name: 'Juggernaut XL V9',+ name: 'Juggernaut XL V9 Photo v2',description: 'SDXL checkpoint — includes VAE and CLIP.',pulls: '', tags: ['Checkpoint', '6.5 GB'], updated: '',- downloadUrl: 'https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/resolve/main/Juggernaut-XL_v9_RunDiffusion.safetensors',+ downloadUrl: 'https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/resolve/main/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors',filename: 'Juggernaut-XL_v9.safetensors', subfolder: 'checkpoints', sizeGB: 6.5,},],@@ -134,67 +146,95 @@ export function getImageBundles(): ModelBundle[] {name: 'RealVisXL V5 (Photorealistic)',description: 'Great for portraits, landscapes, and product photos. Ready to use.',tags: ['SDXL', 'Photorealistic', '1024px'],- totalSizeGB: 6.5,+ totalSizeGB: 3.5,vramRequired: '6-8 GB',workflow: 'wan',- url: 'https://civitai.com/models/139562/realvisxl',+ url: 'https://huggingface.co/SG161222/RealVisXL_V5.0',files: [{- name: 'RealVisXL V5',+ name: 'RealVisXL V5 FP16',description: 'SDXL checkpoint — includes VAE and CLIP.',- pulls: '', tags: ['Checkpoint', '6.5 GB'], updated: '',- downloadUrl: 'https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0.safetensors',- filename: 'RealVisXL_V5.safetensors', subfolder: 'checkpoints', sizeGB: 6.5,+ pulls: '', tags: ['Checkpoint', '3.5 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0_fp16.safetensors',+ filename: 'RealVisXL_V5.safetensors', subfolder: 'checkpoints', sizeGB: 3.5,},],},{- name: 'FLUX.1 [schnell] (Fast & Modern)',- description: 'State-of-the-art image gen. 1-4 steps for fast results. Needs FLUX VAE + CLIP.',- tags: ['FLUX', 'Fast', '1024px'],- totalSizeGB: 11.8,- vramRequired: '10-12 GB',+ name: 'FLUX.1 [schnell] FP8 (Fast & Modern)',+ description: 'State-of-the-art image gen. 1-4 steps for fast results. Complete package with all required encoders.',+ tags: ['FLUX', 'Fast', 'FP8', '1024px'],+ totalSizeGB: 16,+ vramRequired: '8-10 GB',workflow: 'wan',- url: 'https://huggingface.co/black-forest-labs/FLUX.1-schnell',+ url: 'https://huggingface.co/Comfy-Org/flux1-schnell',files: [{- name: 'FLUX.1 schnell Model',- description: 'The main FLUX diffusion model.',+ name: 'FLUX.1 schnell FP8',+ description: 'The main FLUX diffusion model (quantized).',pulls: '', tags: ['Model', '11.5 GB'], updated: '',- downloadUrl: 'https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/flux1-schnell.safetensors',- filename: 'flux1-schnell.safetensors', subfolder: 'diffusion_models', sizeGB: 11.5,+ downloadUrl: 'https://huggingface.co/Comfy-Org/flux1-schnell/resolve/main/flux1-schnell-fp8.safetensors',+ filename: 'flux1-schnell-fp8.safetensors', subfolder: 'diffusion_models', sizeGB: 11.5,},{name: 'FLUX VAE',description: 'Required autoencoder for FLUX.',pulls: '', tags: ['VAE', '335 MB'], updated: '',- downloadUrl: 'https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/ae.safetensors',- filename: 'flux-ae.safetensors', subfolder: 'vae', sizeGB: 0.3,+ downloadUrl: 'https://huggingface.co/Comfy-Org/vae-text-encorder-for-flux-klein-4b/resolve/main/split_files/vae/flux2-vae.safetensors',+ filename: 'flux2-vae.safetensors', subfolder: 'vae', sizeGB: 0.3,+ },+ {+ name: 'T5-XXL Text Encoder (FP8)',+ description: 'Required text encoder for FLUX prompt understanding.',+ pulls: '', tags: ['Text Encoder', '3.9 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn.safetensors',+ filename: 't5xxl_fp8_e4m3fn.safetensors', subfolder: 'text_encoders', sizeGB: 3.9,+ },+ {+ name: 'CLIP-L Text Encoder',+ description: 'Required secondary text encoder for FLUX.',+ pulls: '', tags: ['Text Encoder', '240 MB'], updated: '',+ downloadUrl: 'https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors',+ filename: 'clip_l.safetensors', subfolder: 'text_encoders', sizeGB: 0.2,},],},{- name: 'FLUX.1 [dev] (High Quality)',- description: 'Highest quality FLUX. More steps but better results. Needs FLUX VAE + CLIP.',- tags: ['FLUX', 'Quality', '1024px'],- totalSizeGB: 11.8,- vramRequired: '10-12 GB',+ name: 'FLUX.1 [dev] FP8 (High Quality)',+ description: 'Highest quality FLUX. More steps but better results. Complete package with all required encoders.',+ tags: ['FLUX', 'Quality', 'FP8', '1024px'],+ totalSizeGB: 16,+ vramRequired: '8-10 GB',workflow: 'wan',- url: 'https://huggingface.co/black-forest-labs/FLUX.1-dev',+ url: 'https://huggingface.co/Comfy-Org/flux1-dev',files: [{- name: 'FLUX.1 dev Model',- description: 'The main FLUX diffusion model (dev variant).',+ name: 'FLUX.1 dev FP8',+ description: 'The main FLUX diffusion model (dev, quantized).',pulls: '', tags: ['Model', '11.5 GB'], updated: '',- downloadUrl: 'https://huggingface.co/black-forest-labs/FLUX.1-dev/resolve/main/flux1-dev.safetensors',- filename: 'flux1-dev.safetensors', subfolder: 'diffusion_models', sizeGB: 11.5,+ downloadUrl: 'https://huggingface.co/Comfy-Org/flux1-dev/resolve/main/flux1-dev-fp8.safetensors',+ filename: 'flux1-dev-fp8.safetensors', subfolder: 'diffusion_models', sizeGB: 11.5,},{name: 'FLUX VAE',description: 'Required autoencoder for FLUX.',pulls: '', tags: ['VAE', '335 MB'], updated: '',- downloadUrl: 'https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/ae.safetensors',- filename: 'flux-ae.safetensors', subfolder: 'vae', sizeGB: 0.3,+ downloadUrl: 'https://huggingface.co/Comfy-Org/vae-text-encorder-for-flux-klein-4b/resolve/main/split_files/vae/flux2-vae.safetensors',+ filename: 'flux2-vae.safetensors', subfolder: 'vae', sizeGB: 0.3,+ },+ {+ name: 'T5-XXL Text Encoder (FP8)',+ description: 'Required text encoder for FLUX prompt understanding.',+ pulls: '', tags: ['Text Encoder', '3.9 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn.safetensors',+ filename: 't5xxl_fp8_e4m3fn.safetensors', subfolder: 'text_encoders', sizeGB: 3.9,+ },+ {+ name: 'CLIP-L Text Encoder',+ description: 'Required secondary text encoder for FLUX.',+ pulls: '', tags: ['Text Encoder', '240 MB'], updated: '',+ downloadUrl: 'https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors',+ filename: 'clip_l.safetensors', subfolder: 'text_encoders', sizeGB: 0.2,},],},@@ -224,7 +264,7 @@ export interface ModelBundle {tags: string[]totalSizeGB: numbervramRequired: string- workflow: 'wan' | 'animatediff'+ workflow: 'wan' | 'hunyuan' | 'animatediff'files: DiscoverModel[]url?: string}@@ -295,6 +335,45 @@ export function getVideoBundles(): ModelBundle[] {},],},+ {+ name: 'HunyuanVideo 1.5 T2V FP8 (High Quality)',+ description: 'Tencent HunyuanVideo 1.5 — excellent temporal consistency and visual quality. 480p text-to-video with CFG distillation.',+ tags: ['HunyuanVideo 1.5', '480p', 'Quality'],+ totalSizeGB: 21.5,+ vramRequired: '12+ GB',+ workflow: 'hunyuan',+ url: 'https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged',+ files: [+ {+ name: 'HunyuanVideo 1.5 T2V FP8',+ description: 'The main video generation model (480p, CFG distilled, quantized).',+ pulls: '', tags: ['Model', '13.2 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/resolve/main/split_files/diffusion_models/hunyuanvideo1.5_480p_t2v_cfg_distilled_fp8_scaled.safetensors',+ filename: 'hunyuanvideo1.5_480p_t2v_fp8.safetensors', subfolder: 'diffusion_models', sizeGB: 13.2,+ },+ {+ name: 'HunyuanVideo 1.5 VAE',+ description: 'Required video encoder/decoder.',+ pulls: '', tags: ['VAE', '490 MB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/resolve/main/split_files/vae/hunyuanvideo15_vae_fp16.safetensors',+ filename: 'hunyuanvideo15_vae_fp16.safetensors', subfolder: 'vae', sizeGB: 0.5,+ },+ {+ name: 'Qwen 2.5 VL 7B Text Encoder (FP8)',+ description: 'Required text encoder for HunyuanVideo 1.5.',+ pulls: '', tags: ['Text Encoder', '7.5 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors',+ filename: 'qwen_2.5_vl_7b_fp8_scaled.safetensors', subfolder: 'text_encoders', sizeGB: 7.5,+ },+ {+ name: 'CLIP-L Text Encoder',+ description: 'Required secondary text encoder.',+ pulls: '', tags: ['Text Encoder', '240 MB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/HunyuanVideo_repackaged/resolve/main/split_files/text_encoders/clip_l.safetensors',+ filename: 'clip_l.safetensors', subfolder: 'text_encoders', sizeGB: 0.2,+ },+ ],+ },]}diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex e262ee36..d01ec36c 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -1,17 +1,16 @@import type { OllamaModel } from "../types/models"-import { ollamaUrl } from "./backend"+import { ollamaUrl, localFetch, localFetchStream } from "./backend"export async function listModels(): Promise<OllamaModel[]> {- const res = await fetch(ollamaUrl("/tags"))+ const res = await localFetch(ollamaUrl("/tags"))if (!res.ok) throw new Error("Failed to fetch models")const data = await res.json()return (data.models || []).map((m: any) => ({ ...m, type: "text" as const }))}export async function showModel(name: string) {- const res = await fetch(ollamaUrl("/show"), {+ const res = await localFetch(ollamaUrl("/show"), {method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),})if (!res.ok) throw new Error("Failed to show model")@@ -37,31 +36,26 @@ export async function chatStream(options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},signal?: AbortSignal): Promise<Response> {- const res = await fetch(ollamaUrl("/chat"), {+ const res = await localFetchStream(ollamaUrl("/chat"), {method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({ model, messages, options, stream: true }),- signal,})if (!res.ok) throw new Error("Failed to start chat")return res}export async function pullModel(name: string, signal?: AbortSignal): Promise<Response> {- const res = await fetch(ollamaUrl("/pull"), {+ const res = await localFetchStream(ollamaUrl("/pull"), {method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({ name, stream: true }),- signal,})if (!res.ok) throw new Error("Failed to pull model")return res}export async function deleteModel(name: string): Promise<void> {- const res = await fetch(ollamaUrl("/delete"), {+ const res = await localFetch(ollamaUrl("/delete"), {method: "DELETE",- headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),})if (!res.ok) throw new Error("Failed to delete model")@@ -69,7 +63,7 @@ export async function deleteModel(name: string): Promise<void> {export async function checkConnection(): Promise<boolean> {try {- await fetch(ollamaUrl("/tags"))+ await localFetch(ollamaUrl("/tags"))return true} catch {return falsediff --git a/src/api/rag.ts b/src/api/rag.tsindex 831eecb6..34080a5a 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -1,6 +1,6 @@import { v4 as uuid } from "uuid"import type { DocumentMeta, TextChunk, RAGContext, VectorSearchResult } from "../types/rag"-import { ollamaUrl } from "./backend"+import { ollamaUrl, localFetch } from "./backend"export async function extractText(file: File): Promise<string> {const ext = file.name.split(".").pop()?.toLowerCase()@@ -58,9 +58,8 @@ export async function generateEmbeddings(texts: string[],model = "nomic-embed-text"): Promise<number[][]> {- const res = await fetch(ollamaUrl("/embed"), {+ const res = await localFetch(ollamaUrl("/embed"), {method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({ model, input: texts }),})if (!res.ok) throw new Error("Embedding failed — is the model pulled?")diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 1f3c0c18..ec4a0772 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -61,11 +61,10 @@ export function Header() {</button><buttononClick={() => setView('agents')}- className={`relative p-2 rounded-lg transition-colors ${currentView === 'agents' ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}- title="AI Agents (Work in Progress)"+ className={`p-2 rounded-lg transition-colors ${currentView === 'agents' ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}+ title="AI Agents"><Bot size={18} />- <span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-amber-400" title="Work in Progress" /></button><buttononClick={() => setView('models')}diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex a7c71b1c..3ec341ce 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -1,9 +1,11 @@import { useState, useEffect, useRef } from 'react'import { motion } from 'framer-motion'import { Download, RefreshCw, ExternalLink, Search, Info, CheckCircle, XCircle, Loader2 } from 'lucide-react'+import { Pause, Play, X } from 'lucide-react'import {fetchAbliteratedModels, getImageBundles, getVideoBundles,startModelDownload, getDownloadProgress, searchCivitaiModels,+ pauseDownload, cancelDownload, resumeDownload,type DiscoverModel, type DownloadProgress, type ModelBundle, type CivitAIModelResult,} from '../../api/discover'import { useModels } from '../../hooks/useModels'@@ -26,6 +28,7 @@ export function DiscoverModels({ category }: Props) {const [loading, setLoading] = useState(false)const [search, setSearch] = useState('')const [downloads, setDownloads] = useState<Record<string, DownloadProgress>>({})+ const [downloadMeta, setDownloadMeta] = useState<Record<string, { url: string; subfolder: string }>>({})const { pullModel, isPulling, pullProgress, models: installedModels } = useModels()const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)@@ -39,21 +42,19 @@ export function DiscoverModels({ category }: Props) {// Poll download progressuseEffect(() => {- const hasActive = Object.values(downloads).some(d => d.status === 'downloading' || d.status === 'connecting')+ const hasActive = Object.values(downloads).some(d => d.status === 'downloading' || d.status === 'connecting' || d.status === 'pausing')if (hasActive && !pollRef.current) {pollRef.current = setInterval(async () => {const prog = await getDownloadProgress()setDownloads(prev => {- // Check if any download just completedfor (const [id, d] of Object.entries(prog)) {if (d.status === 'complete' && prev[id]?.status !== 'complete') {- // Trigger model list refresh across the appwindow.dispatchEvent(new CustomEvent('comfyui-model-downloaded'))}}return prog})- const stillActive = Object.values(prog).some(d => d.status === 'downloading' || d.status === 'connecting')+ const stillActive = Object.values(prog).some(d => d.status === 'downloading' || d.status === 'connecting' || d.status === 'pausing')if (!stillActive && pollRef.current) {clearInterval(pollRef.current)pollRef.current = null@@ -81,6 +82,8 @@ export function DiscoverModels({ category }: Props) {const handleDownload = async (model: DiscoverModel) => {if (!model.downloadUrl || !model.filename || !model.subfolder) return+ // Store meta for resume+ setDownloadMeta(prev => ({ ...prev, [model.filename!]: { url: model.downloadUrl!, subfolder: model.subfolder! } }))const result = await startModelDownload(model.downloadUrl, model.subfolder, model.filename)if (result.status === 'started' || result.status === 'already_exists') {const prog = await getDownloadProgress()@@ -91,6 +94,7 @@ export function DiscoverModels({ category }: Props) {const handleBundleInstall = async (bundle: ModelBundle) => {for (const file of bundle.files) {if (file.downloadUrl && file.filename && file.subfolder) {+ setDownloadMeta(prev => ({ ...prev, [file.filename!]: { url: file.downloadUrl!, subfolder: file.subfolder! } }))await startModelDownload(file.downloadUrl, file.subfolder, file.filename)}}@@ -98,6 +102,29 @@ export function DiscoverModels({ category }: Props) {setDownloads(prog)}+ const handlePause = async (id: string) => {+ await pauseDownload(id)+ const prog = await getDownloadProgress()+ setDownloads(prog)+ }++ const handleCancel = async (id: string) => {+ await cancelDownload(id)+ setDownloads(prev => {+ const updated = { ...prev }+ delete updated[id]+ return updated+ })+ }++ const handleResume = async (id: string) => {+ const meta = downloadMeta[id]+ if (!meta) return+ await resumeDownload(id, meta.url, meta.subfolder)+ const prog = await getDownloadProgress()+ setDownloads(prog)+ }+const handleCivitaiSearch = async () => {if (!civitaiQuery.trim()) returnsetCivitaiSearching(true)@@ -177,20 +204,37 @@ export function DiscoverModels({ category }: Props) {/></div>- {/* Active downloads summary */}- {Object.values(downloads).some(d => d.status === 'downloading' || d.status === 'connecting') && (+ {/* Download Manager */}+ {Object.values(downloads).some(d => d.status === 'downloading' || d.status === 'connecting' || d.status === 'pausing' || d.status === 'paused') && (<GlassCard className="p-3 space-y-2"><h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">- <Loader2 size={14} className="animate-spin" /> Active Downloads+ <Loader2 size={14} className={Object.values(downloads).some(d => d.status === 'downloading') ? 'animate-spin' : ''} /> Downloads</h3>- {Object.entries(downloads).filter(([, d]) => d.status === 'downloading' || d.status === 'connecting').map(([id, d]) => (+ {Object.entries(downloads).filter(([, d]) => d.status === 'downloading' || d.status === 'connecting' || d.status === 'pausing' || d.status === 'paused').map(([id, d]) => (<div key={id} className="space-y-1"><div className="flex items-center justify-between text-xs text-gray-500">- <span className="truncate">{d.filename}</span>- <span>- {d.total > 0 ? `${formatBytes(d.progress)} / ${formatBytes(d.total)}` : 'Connecting...'}- {d.speed > 0 && ` · ${formatBytes(d.speed)}/s`}- </span>+ <span className="truncate flex-1">{d.filename}</span>+ <div className="flex items-center gap-2 shrink-0">+ <span>+ {d.status === 'paused' ? 'Paused' : d.status === 'pausing' ? 'Pausing...' : d.total > 0 ? `${formatBytes(d.progress)} / ${formatBytes(d.total)}` : 'Connecting...'}+ {d.speed > 0 && d.status === 'downloading' && ` · ${formatBytes(d.speed)}/s`}+ </span>+ {/* Pause/Resume button */}+ {(d.status === 'downloading' || d.status === 'connecting') && (+ <button onClick={() => handlePause(id)} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-yellow-500 transition-colors" title="Pause">+ <Pause size={12} />+ </button>+ )}+ {d.status === 'paused' && (+ <button onClick={() => handleResume(id)} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-green-500 transition-colors" title="Resume">+ <Play size={12} />+ </button>+ )}+ {/* Cancel button */}+ <button onClick={() => handleCancel(id)} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-red-500 transition-colors" title="Cancel">+ <X size={12} />+ </button>+ </div></div>{d.total > 0 && <ProgressBar progress={(d.progress / d.total) * 100} />}</div>@@ -297,11 +341,28 @@ export function DiscoverModels({ category }: Props) {)}{fileErr && <span className="text-[10px] text-red-500">Failed: {dlState?.error}</span>}</div>- <div className="shrink-0">+ <div className="shrink-0 flex items-center gap-0.5">{fileDone ? (<CheckCircle size={14} className="text-green-500" />) : fileDl ? (- <Loader2 size={14} className="animate-spin text-blue-400" />+ <>+ <Loader2 size={14} className="animate-spin text-blue-400" />+ <button onClick={() => file.filename && handlePause(file.filename)} className="p-0.5 rounded text-gray-400 hover:text-yellow-500" title="Pause">+ <Pause size={12} />+ </button>+ <button onClick={() => file.filename && handleCancel(file.filename)} className="p-0.5 rounded text-gray-400 hover:text-red-500" title="Cancel">+ <X size={12} />+ </button>+ </>+ ) : dlState?.status === 'paused' ? (+ <>+ <button onClick={() => file.filename && handleResume(file.filename)} className="p-0.5 rounded text-gray-400 hover:text-green-500" title="Resume">+ <Play size={12} />+ </button>+ <button onClick={() => file.filename && handleCancel(file.filename)} className="p-0.5 rounded text-gray-400 hover:text-red-500" title="Cancel">+ <X size={12} />+ </button>+ </>) : (<button onClick={() => handleDownload(file)} className="p-1 rounded text-gray-400 hover:text-green-500 transition-colors" title="Download this file"><Download size={14} />diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsxindex 012d31f0..604c687f 100644--- a/src/components/models/ModelManager.tsx+++ b/src/components/models/ModelManager.tsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react'import { motion } from 'framer-motion'-import { Download, ArrowLeft, RefreshCw, MessageSquare, Image, Video, Layers } from 'lucide-react'+import { Download, ArrowLeft, RefreshCw, MessageSquare, Image, Video, Layers, AlertTriangle, FolderOpen } from 'lucide-react'import { useModels } from '../../hooks/useModels'import { useUIStore } from '../../stores/uiStore'import { ModelCard } from './ModelCard'@@ -9,6 +9,7 @@ import { DiscoverModels } from './DiscoverModels'import { Modal } from '../ui/Modal'import { GlowButton } from '../ui/GlowButton'import { showModel } from '../../api/ollama'+import { backendCall, isTauri } from '../../api/backend'import type { ModelCategory, AIModel } from '../../types/models'const CATEGORY_TABS: { key: ModelCategory; label: string; icon: typeof Layers }[] = [@@ -26,11 +27,36 @@ export function ModelManager() {const [modelInfo, setModelInfo] = useState<any>(null)const [confirmDelete, setConfirmDelete] = useState<string | null>(null)const [tab, setTab] = useState<'installed' | 'discover'>('installed')+ const [comfyStatus, setComfyStatus] = useState<{ running: boolean; found: boolean; path: string | null } | null>(null)+ const [comfyPathInput, setComfyPathInput] = useState('')+ const [comfyPathError, setComfyPathError] = useState('')+ const [comfyPathSaving, setComfyPathSaving] = useState(false)useEffect(() => {fetchModels()+ // Check ComfyUI status+ backendCall('comfyui_status').then(setComfyStatus).catch(() => {})}, [fetchModels])+ const handleSetComfyPath = async () => {+ if (!comfyPathInput.trim()) { setComfyPathError('Enter a path'); return }+ setComfyPathSaving(true)+ setComfyPathError('')+ try {+ const data = await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })+ if (data.status === 'saved' || data.status === 'ok') {+ setComfyStatus(prev => prev ? { ...prev, found: true, path: comfyPathInput.trim() } : null)+ setComfyPathInput('')+ fetchModels()+ } else {+ setComfyPathError(data.error || 'Invalid path')+ }+ } catch (err) {+ setComfyPathError(String(err))+ }+ setComfyPathSaving(false)+ }+const handleInfo = async (name: string) => {try {const info = await showModel(name)@@ -73,6 +99,42 @@ export function ModelManager() {</div></div>+ {/* ComfyUI path warning */}+ {comfyStatus && !comfyStatus.found && !comfyStatus.path && (+ <div className="mb-4 p-4 rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20">+ <div className="flex items-start gap-2 mb-2">+ <AlertTriangle size={16} className="text-amber-500 shrink-0 mt-0.5" />+ <div>+ <p className="text-sm font-medium text-amber-800 dark:text-amber-300">ComfyUI not found</p>+ <p className="text-xs text-amber-600 dark:text-amber-400 mt-0.5">Image/Video model downloads need the ComfyUI path. Enter it below or install ComfyUI first.</p>+ </div>+ </div>+ <div className="flex gap-2 mt-2">+ <div className="flex-1 flex items-center gap-2">+ <FolderOpen size={16} className="text-amber-500 shrink-0" />+ <input+ value={comfyPathInput}+ onChange={(e) => { setComfyPathInput(e.target.value); setComfyPathError('') }}+ placeholder="C:\Users\you\ComfyUI"+ className="flex-1 px-3 py-1.5 rounded-lg bg-white dark:bg-black/20 border border-amber-300 dark:border-amber-500/30 text-sm text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none"+ />+ </div>+ <button+ onClick={handleSetComfyPath}+ disabled={comfyPathSaving}+ className="px-3 py-1.5 rounded-lg bg-amber-500 hover:bg-amber-600 text-white text-sm font-medium transition-colors disabled:opacity-50"+ >+ {comfyPathSaving ? 'Saving...' : 'Set Path'}+ </button>+ </div>+ {comfyPathError && <p className="text-xs text-red-500 mt-1">{comfyPathError}</p>}+ </div>+ )}++ {comfyStatus?.path && (+ <p className="text-xs text-gray-400 mb-4">ComfyUI: {comfyStatus.path}</p>+ )}+{/* Main tabs: Installed / Discover */}<div className="flex gap-1 mb-4 p-1 bg-gray-100 dark:bg-white/5 rounded-lg w-fit"><buttondiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex fe9fa557..44d91d3c 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -6,7 +6,9 @@ import { useChatStore } from "../stores/chatStore"import { useModelStore } from "../stores/modelStore"import { useSettingsStore } from "../stores/settingsStore"import { useRAGStore } from "../stores/ragStore"+import { useVoiceStore } from "../stores/voiceStore"import { retrieveContext } from "../api/rag"+import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from "../api/voice"interface ChatChunk {message?: { content: string }@@ -167,6 +169,21 @@ export function useChat() {} finally {setIsGenerating(false)abortRef.current = null++ // Auto-speak response if TTS is enabled+ const voiceState = useVoiceStore.getState()+ if (voiceState.ttsEnabled && isSpeechSynthesisSupported() && contentRef.current.trim()) {+ try {+ let voice: SpeechSynthesisVoice | undefined+ if (voiceState.ttsVoice) {+ const voices = await getVoicesAsync()+ voice = voices.find((v) => v.name === voiceState.ttsVoice)+ }+ voiceState.setSpeaking(true)+ await speakStreaming(contentRef.current, voice, voiceState.ttsRate, voiceState.ttsPitch)+ } catch { /* TTS errors are non-critical */ }+ finally { voiceState.setSpeaking(false) }+ }}}, [])diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex acdad92f..5ff5b5db 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -1,6 +1,6 @@import { useCallback } from 'react'import { listModels, pullModel as pullModelApi, deleteModel as deleteModelApi } from '../api/ollama'-import { getCheckpoints as getComfyCheckpoints, checkComfyConnection } from '../api/comfyui'+import { getCheckpoints as getComfyCheckpoints, getDiffusionModels as getComfyDiffusionModels, checkComfyConnection } from '../api/comfyui'import { parseNDJSONStream } from '../api/stream'import { useModelStore } from '../stores/modelStore'import type { PullProgress, AIModel, ModelCategory, ImageModel, VideoModel } from '../types/models'@@ -27,27 +27,20 @@ export function useModels() {const comfyOk = await checkComfyConnection()if (comfyOk) {try {- const checkpoints = await getComfyCheckpoints()- comfyModels = checkpoints.map((name): AIModel => {+ const [checkpoints, diffusionModels] = await Promise.all([+ getComfyCheckpoints(),+ getComfyDiffusionModels(),+ ])+ const classifyComfyModel = (name: string, source: 'checkpoint' | 'diffusion_model'): AIModel => {if (isVideoModel(name)) {- return {- name,- model: name,- size: 0,- format: 'safetensors',- architecture: 'unknown',- type: 'video',- } as VideoModel+ return { name, model: name, size: 0, format: 'safetensors', architecture: 'unknown', type: 'video' } as VideoModel}- return {- name,- model: name,- size: 0,- format: 'safetensors',- architecture: 'unknown',- type: 'image',- } as ImageModel- })+ return { name, model: name, size: 0, format: 'safetensors', architecture: 'unknown', type: 'image' } as ImageModel+ }+ comfyModels = [+ ...checkpoints.map((name) => classifyComfyModel(name, 'checkpoint')),+ ...diffusionModels.map((name) => classifyComfyModel(name, 'diffusion_model')),+ ]} catch {// ComfyUI model fetch failed, continue with Ollama only}diff --git a/vite.config.ts b/vite.config.tsindex 300ac369..cd12dc1e 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -423,7 +423,6 @@ function comfyLauncher(): Plugin {const downloads: Record<string, any> = {}for (const [id, info] of activeDownloads.entries()) {downloads[id] = info- // Clean up completed downloads after 30sif (info.status === 'complete' || info.status === 'error') {setTimeout(() => activeDownloads.delete(id), 30000)}@@ -432,6 +431,52 @@ function comfyLauncher(): Plugin {res.end(JSON.stringify(downloads))})+ // API: Pause download (dev mode stub — sets status to paused)+ server.middlewares.use('/local-api/pause-download', (req, res) => {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }+ let body = ''+ req.on('data', (c: any) => { body += c })+ req.on('end', () => {+ const { id } = JSON.parse(body)+ const dl = activeDownloads.get(id)+ if (dl) dl.status = 'paused'+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'paused' }))+ })+ })++ // API: Cancel download (dev mode stub — removes from map)+ server.middlewares.use('/local-api/cancel-download', (req, res) => {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }+ let body = ''+ req.on('data', (c: any) => { body += c })+ req.on('end', () => {+ const { id } = JSON.parse(body)+ activeDownloads.delete(id)+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'cancelled' }))+ })+ })++ // API: Resume download (dev mode stub — restarts download)+ server.middlewares.use('/local-api/resume-download', (req, res) => {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }+ let body = ''+ req.on('data', (c: any) => { body += c })+ req.on('end', () => {+ const { id, url, subfolder } = JSON.parse(body)+ if (url && subfolder) {+ const comfyPath = findComfyUI()+ if (comfyPath) {+ const destPath = join(comfyPath, 'models', subfolder, id)+ downloadFile(url, destPath, id).catch(err => console.error(`[Download] Resume failed: ${err.message}`))+ }+ }+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'resuming' }))+ })+ })+// API: Set ComfyUI path (writes to .env and starts ComfyUI)server.middlewares.use('/local-api/set-comfyui-path', (req, res) => {if (req.method !== 'POST') { res.writeHead(405); res.end(); return }