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(v2.5.4): 5 bug fixes from the GitHub+Discord scan
purple8164f3cb11fe
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rsindex a7e0eaaf..23a361ef 100644--- a/src-tauri/src/commands/agent.rs+++ b/src-tauri/src/commands/agent.rs@@ -262,6 +262,7 @@ pub fn execute_code(code: String,timeout: Option<u64>,#[allow(non_snake_case)] chatId: Option<String>,+ #[allow(non_snake_case)] workingDirectory: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(30000);@@ -273,10 +274,14 @@ pub fn execute_code(fs::write(&script_path, &code).map_err(|e| format!("Write temp script: {}", e))?;- // cwd = per-chat workspace (auto-created). Python scripts that do- // relative file I/O land in the same isolated folder as file_read /- // file_write for this chat.- let workspace = agent_workspace(chatId.as_deref(), Some(&*state));+ // cwd: prefer the agent's folder workspace (the repo the user picked,+ // threaded from chatCtx as workingDirectory) so a script's relative file+ // I/O lands in that repo; otherwise the per-chat sandbox (#62). Same+ // resolution order as the file_* tools and shell_execute.+ let workspace = match workingDirectory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {+ Some(wd) => PathBuf::from(wd),+ None => agent_workspace(chatId.as_deref(), Some(&*state)),+ };let _ = fs::create_dir_all(&workspace);let python_bin = state.python_bin.lock().unwrap().clone();diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rsindex f881117f..5d511477 100644--- a/src-tauri/src/commands/filesystem.rs+++ b/src-tauri/src/commands/filesystem.rs@@ -30,30 +30,42 @@ fn normalize_duplicate_drive_prefix(path: &str) -> String {}}-/// Resolve path — supports absolute and relative (relative to the-/// per-chat workspace `~/agent-workspace/<chat_id>/`). Mirrors the-/// pattern in agent.rs. `chat_id` is sanitised to the charset-/// `[A-Za-z0-9_\-\.]` (anything else → `_`) and capped at 64 chars to+/// Resolve path — supports absolute and relative paths. A relative path+/// resolves against, in order: the agent's folder workspace `working_dir`+/// (the repo the user picked, threaded from the frontend as+/// `workingDirectory` via chatCtx) when set; otherwise the per-chat sandbox+/// `~/agent-workspace/<chat_id>/`. Honoring `working_dir` is what makes a+/// configured repo path actually win over the sandbox (#62) — before this,+/// the frontend sent it but every command dropped it. `chat_id` is sanitised+/// to `[A-Za-z0-9_\-\.]` (anything else → `_`) and capped at 64 chars to/// prevent path traversal. Missing chat_id falls back to `default`.-fn resolve_path(path: &str, chat_id: Option<&str>) -> PathBuf {+fn resolve_path(path: &str, chat_id: Option<&str>, working_dir: Option<&str>) -> PathBuf {let cleaned = normalize_duplicate_drive_prefix(path);let p = Path::new(&cleaned);if p.is_absolute() {- p.to_path_buf()- } else {- let id = chat_id.unwrap_or("default");- let safe: String = id- .chars()- .take(64)- .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' })- .collect();- let slug = if safe.is_empty() { "default".to_string() } else { safe };- dirs::home_dir()- .unwrap_or_default()- .join("agent-workspace")- .join(slug)- .join(&cleaned)+ return p.to_path_buf();+ }+ // Relative path: a configured folder workspace (the user's repo) wins over+ // the per-chat sandbox, so relative tool-call paths land where the user+ // expects. Blank/whitespace working_dir is treated as unset.+ if let Some(wd) = working_dir {+ let wd = wd.trim();+ if !wd.is_empty() {+ return PathBuf::from(wd).join(&cleaned);+ }}+ let id = chat_id.unwrap_or("default");+ let safe: String = id+ .chars()+ .take(64)+ .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' })+ .collect();+ let slug = if safe.is_empty() { "default".to_string() } else { safe };+ dirs::home_dir()+ .unwrap_or_default()+ .join("agent-workspace")+ .join(slug)+ .join(&cleaned)}/// True when `path` addresses the workspace ROOT itself ("", ".", "./",@@ -90,8 +102,8 @@ fn file_meta(path: &Path) -> serde_json::Value {#[tauri::command]#[allow(non_snake_case)]-pub fn fs_read(path: String, chatId: Option<String>) -> Result<serde_json::Value, String> {- let full = resolve_path(&path, chatId.as_deref());+pub fn fs_read(path: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {+ let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref());if !full.exists() {return Err(format!("File not found: {}", full.display()));}@@ -109,8 +121,8 @@ pub fn fs_read(path: String, chatId: Option<String>) -> Result<serde_json::Value#[tauri::command]#[allow(non_snake_case)]-pub fn fs_write(path: String, content: String, chatId: Option<String>) -> Result<serde_json::Value, String> {- let full = resolve_path(&path, chatId.as_deref());+pub fn fs_write(path: String, content: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {+ let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref());if let Some(parent) = full.parent() {fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;}@@ -125,8 +137,9 @@ pub fn fs_list(recursive: Option<bool>,pattern: Option<String>,chatId: Option<String>,+ workingDirectory: Option<String>,) -> Result<serde_json::Value, String> {- let dir = resolve_path(&path, chatId.as_deref());+ let dir = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref());if !dir.is_dir() {// A fresh per-chat agent sandbox (~/agent-workspace/<chat_id>) may not// exist yet. When the model lists the workspace ROOT with a relative@@ -184,8 +197,9 @@ pub fn fs_search(pattern: String,max_results: Option<u32>,chatId: Option<String>,+ workingDirectory: Option<String>,) -> Result<serde_json::Value, String> {- let dir = resolve_path(&path, chatId.as_deref());+ let dir = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref());if !dir.is_dir() {return Err(format!("Not a directory: {}", dir.display()));}@@ -238,8 +252,8 @@ pub fn fs_search(#[tauri::command]#[allow(non_snake_case)]-pub fn fs_info(path: String, chatId: Option<String>) -> Result<serde_json::Value, String> {- let full = resolve_path(&path, chatId.as_deref());+pub fn fs_info(path: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {+ let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref());if !full.exists() {return Err(format!("Path not found: {}", full.display()));}@@ -346,7 +360,7 @@ pub async fn save_binary_file_dialog(#[cfg(test)]mod tests {- use super::is_workspace_root_path;+ use super::{is_workspace_root_path, resolve_path};#[test]fn workspace_root_paths_match() {@@ -361,4 +375,34 @@ mod tests {assert!(!is_workspace_root_path(p), "expected NOT root-ish: {:?}", p);}}++ // ── #62: relative paths must honor the folder workspace ──────────+ #[test]+ fn relative_path_resolves_against_working_dir() {+ let got = resolve_path("src/main.rs", Some("chat-1"), Some("D:/Projects/site"));+ let s = got.to_string_lossy().replace('\\', "/");+ assert_eq!(s, "D:/Projects/site/src/main.rs");+ }++ #[test]+ fn relative_path_without_working_dir_uses_sandbox() {+ let got = resolve_path("notes.md", Some("chat-1"), None);+ let s = got.to_string_lossy().replace('\\', "/");+ assert!(s.contains("agent-workspace/chat-1/notes.md"), "got: {}", s);+ }++ #[test]+ fn blank_working_dir_falls_back_to_sandbox() {+ let got = resolve_path("a.txt", Some("c"), Some(" "));+ let s = got.to_string_lossy().replace('\\', "/");+ assert!(s.contains("agent-workspace/c/a.txt"), "got: {}", s);+ }++ #[test]+ fn absolute_path_ignores_working_dir() {+ let abs = if cfg!(windows) { "C:/abs/file.txt" } else { "/abs/file.txt" };+ let got = resolve_path(abs, Some("chat-1"), Some("D:/Projects/site"));+ let s = got.to_string_lossy().replace('\\', "/");+ assert_eq!(s, abs);+ }}diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 477fd49f..640cdfab 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -500,7 +500,7 @@ async fn handle_agent_tool(let code = body.args.get("code").and_then(|v| v.as_str()).unwrap_or("").to_string();let timeout = body.args.get("timeout").and_then(|v| v.as_u64());if code.is_empty() { Err("code_execute needs a non-empty `code` argument.".into()) }- else { crate::commands::agent::execute_code(code, timeout, chat_id.clone(), app_state) }+ else { crate::commands::agent::execute_code(code, timeout, chat_id.clone(), None, app_state) }}"web_search" => {let query = body.args.get("query").and_then(|v| v.as_str()).unwrap_or("").to_string();@@ -529,7 +529,7 @@ async fn handle_agent_tool(// fs_list itself doesn't see AppState — pass an absolute// path so it skips its own resolver.let resolved = resolve_remote_path(&raw_path, chat_id.as_deref(), &app_state);- crate::commands::filesystem::fs_list(resolved, recursive, pattern, None)+ crate::commands::filesystem::fs_list(resolved, recursive, pattern, None, None)}}"file_search" => {@@ -547,7 +547,7 @@ async fn handle_agent_tool(Err("file_search needs both `path` and `pattern` arguments.".into())} else {let resolved = resolve_remote_path(&raw_path, chat_id.as_deref(), &app_state);- crate::commands::filesystem::fs_search(resolved, pattern, max, None)+ crate::commands::filesystem::fs_search(resolved, pattern, max, None, None)}}"shell_execute" => {@@ -574,7 +574,7 @@ async fn handle_agent_tool(}let timeout = body.args.get("timeout").and_then(|v| v.as_u64());let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);- crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, chat_id.clone()).await+ crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, chat_id.clone(), None).await}}"system_info" => crate::commands::system::system_info(),@@ -4157,7 +4157,9 @@ pub async fn start_tunnel(// Start cloudflared tunnel (hidden — no terminal window for end users)let mut cmd = std::process::Command::new(&cf_path);- cmd.args(["tunnel", "--url", &format!("http://localhost:{}", port)])+ // 127.0.0.1 (not "localhost") avoids a ~2 s IPv6 (::1) connect detour on+ // some Windows boxes before cloudflared falls back to IPv4 (aldrich 2026-06).+ cmd.args(["tunnel", "--url", &format!("http://127.0.0.1:{}", port)]).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());#[cfg(target_os = "windows")]@@ -4212,6 +4214,29 @@ pub async fn start_tunnel(if !url.is_empty() { break; }}+ // #aldrich (Discord 2026-06-13, "Error HTTP:503" on the phone): a+ // trycloudflare quick-tunnel PRINTS its public URL several seconds before+ // Cloudflare's edge↔origin path is actually ready to serve — so a phone+ // that scans the QR immediately gets a transient 503. Poll the public+ // /mobile route (exactly what the QR points at) until it answers, before we+ // mark the URL ready. Bounded with a fallback: if it never becomes ready+ // within the budget we proceed anyway (old behaviour) rather than hang.+ if !url.is_empty() {+ if let Ok(client) = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(8))+ .no_proxy()+ .build()+ {+ let probe = format!("{}/mobile", url);+ for _ in 0..20 { // ~20 × 600 ms ≈ 12 s readiness budget+ match client.get(&probe).send().await {+ Ok(resp) if resp.status().is_success() => break,+ _ => tokio::time::sleep(std::time::Duration::from_millis(600)).await,+ }+ }+ }+ }+// Store tunnel PID{let mut remote = state.remote.lock().map_err(|e| e.to_string())?;diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex b4bb2b71..fa4f976d 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -37,9 +37,10 @@ pub async fn shell_execute(timeout: Option<u64>,shell: Option<String>,chatId: Option<String>,+ workingDirectory: Option<String>,) -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(move || {- shell_execute_sync(command, args, cwd, timeout, shell, chatId)+ shell_execute_sync(command, args, cwd, timeout, shell, chatId, workingDirectory)}).await.map_err(|e| format!("Task join error: {}", e))?@@ -52,6 +53,7 @@ fn shell_execute_sync(timeout: Option<u64>,shell: Option<String>,chat_id: Option<String>,+ working_directory: Option<String>,) -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(120_000);let shell_bin = shell.unwrap_or_else(|| {@@ -86,11 +88,16 @@ fn shell_execute_sync(// ~/Documents (David 2026-06-04). Mirrors the file tools' path resolution.let workdir: PathBuf = match cwd.as_ref().map(|d| Path::new(d)) {Some(p) if p.is_dir() => p.to_path_buf(),- _ => {- let w = workspace_cwd(chat_id.as_deref());- let _ = std::fs::create_dir_all(&w);- w- }+ _ => match working_directory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {+ // Folder workspace (the user's repo, from chatCtx.workingDirectory)+ // wins over the per-chat sandbox for relative commands (#62).+ Some(wd) => PathBuf::from(wd),+ None => {+ let w = workspace_cwd(chat_id.as_deref());+ let _ = std::fs::create_dir_all(&w);+ w+ }+ },};if workdir.is_dir() {cmd.current_dir(&workdir);diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 96be2a21..6cf802fb 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -955,21 +955,61 @@ export async function getHistory(promptId: string): Promise<any> {// ─── Upload image to ComfyUI (for I2V models like SVD, FramePack) ───export async function uploadImage(file: File): Promise<string> {+ // Guard: ComfyUI's /upload/image answers an opaque HTTP 400 for an empty or+ // unreadable file. Catch the empty-blob case up front with a clear message+ // (konata 2026-06-14: "Video generation failed: Failed to upload image: HTTP 400").+ if (!file || file.size === 0) {+ throw new Error('Failed to upload image: the source image is empty (0 bytes) — it could not be read from ComfyUI.')+ }++ // ComfyUI saves the file under the multipart filename and opens it with PIL by+ // extension, so it 400s on a missing/extension-less/odd name. Send an explicit,+ // sanitised filename with a real image extension rather than trusting file.name+ // (a Blob-derived File can carry "" or an extension-less name).+ const safeName = ensureImageFilename(file.name, file.type)const formData = new FormData()- formData.append('image', file)+ formData.append('image', file, safeName)formData.append('overwrite', 'true')// Direct fetch — localFetch only supports string body, not FormData.- // FormData needs multipart/form-data which fetch() sets automatically.+ // FormData needs multipart/form-data which fetch() sets automatically. A 400+ // here means the request reached ComfyUI and it rejected the content, so the+ // proxy/CORS is not at fault — surface ComfyUI's actual reason instead of a+ // bare status so the next failure is self-explanatory.const res = await fetch(comfyuiUrl('/upload/image'), {method: 'POST',body: formData,})- if (!res.ok) throw new Error(`Failed to upload image: HTTP ${res.status}`)+ if (!res.ok) {+ let detail = ''+ try { detail = (await res.text()).trim() } catch { /* body empty / already consumed */ }+ throw new Error(`Failed to upload image: HTTP ${res.status}${detail ? ` — ${detail.slice(0, 300)}` : ''}`)+ }const data = await res.json()return data.name // ComfyUI returns { name, subfolder, type }}+/** Ensure a ComfyUI-friendly image filename: a sane base plus a real image+ * extension inferred from the MIME type when the name lacks one. ComfyUI's+ * /upload/image needs a recognisable extension to open the file with PIL. */+export function ensureImageFilename(name: string | undefined, mime: string | undefined): string {+ const base = (name || '').replace(/^.*[\\/]/, '').trim()+ if (base && /\.(png|jpe?g|webp|gif|bmp|tiff?)$/i.test(base)) return base+ const ext = ((m) => {+ switch ((m || '').toLowerCase()) {+ case 'image/jpeg': return 'jpg'+ case 'image/webp': return 'webp'+ case 'image/gif': return 'gif'+ case 'image/bmp': return 'bmp'+ case 'image/tiff': return 'tiff'+ default: return 'png'+ }+ })(mime)+ const stem = (base ? base.replace(/\.[^.]*$/, '') : 'lu_input') || 'lu_input'+ const safeStem = stem.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 64) || 'lu_input'+ return `${safeStem}.${ext}`+}+export function getImageUrl(filename: string, subfolder: string = '', type: string = 'output', cacheBust?: string | number): string {const path = `/view?filename=${encodeURIComponent(filename)}&subfolder=${encodeURIComponent(subfolder)}&type=${type}`// A cache-buster is appended ONLY when an explicit, STABLE token is supplieddiff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex d11b5e7a..a00596ad 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -1322,6 +1322,9 @@ async function resolveInputImage(ref: string): Promise<ResolvedInputImage> {const resp = await fetch(url)if (!resp.ok) throw new Error(`could not read input image "${ref}" (HTTP ${resp.status})`)const blob = await resp.blob()+ if (!blob || blob.size === 0) {+ throw new Error(`could not read input image "${ref}" — ComfyUI returned an empty file`)+ }// Probe the source dimensions so the I2V path can pick the model's native// aspect ratio (David 2026-06-11: a portrait still forced into 768×448// landscape no longer resembled the source). Best-effort — a probe failurediff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 558c8eb1..784888fe 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -122,6 +122,15 @@ export function useModels() {await promisecompletePull(name)try { await fetchModels() } catch { /* model list refresh failed — non-critical */ }+ // Auto-activate the freshly downloaded chat model so the chat actually+ // switches to it instead of silently staying on the old default+ // (forte_exe 2026-06-14: downloaded models didn't appear selected and+ // the chat kept reverting). Chat models only — image/video live in the+ // Create view. Matched by exact list name so a mismatch just no-ops.+ {+ const freshly = useModelStore.getState().models.find((m) => m.name === name)+ if (freshly && freshly.type !== 'image' && freshly.type !== 'video') setActiveModel(name)+ }// Auto-dismiss after 5ssetTimeout(() => dismissPull(name), 5000)} catch (err) {@@ -157,6 +166,11 @@ export function useModels() {} else {completePull(name)try { await fetchModels() } catch { /* non-critical */ }+ // Auto-activate the freshly downloaded chat model (see note above).+ {+ const freshly = useModelStore.getState().models.find((m) => m.name === name)+ if (freshly && freshly.type !== 'image' && freshly.type !== 'video') setActiveModel(name)+ }setTimeout(() => dismissPull(name), 5000)}} catch (err) {@@ -166,7 +180,7 @@ export function useModels() {// On abort (pause): card stays with "Paused" status}},- [activePulls, fetchModels, startPull, updatePullProgress, completePull, dismissPull]+ [activePulls, fetchModels, startPull, updatePullProgress, completePull, dismissPull, setActiveModel])const isPullingModel = useCallback(diff --git a/vite.config.ts b/vite.config.tsindex 4fa787fa..7d62e6f0 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -332,12 +332,27 @@ function comfyLauncher(): Plugin {next();});- // Auto-start Ollama when dev server starts- try {- execSync('tasklist /FI "IMAGENAME eq ollama.exe" | find /I "ollama.exe"', { stdio: 'ignore' })+ // Auto-start Ollama when dev server starts (best-effort, NEVER fatal:+ // a from-source dev run may not have Ollama installed at all — #63+ // cpack299, Ubuntu 24).+ const ollamaAlreadyRunning = (() => {+ try {+ if (process.platform === 'win32') {+ execSync('tasklist /FI "IMAGENAME eq ollama.exe" | find /I "ollama.exe"', { stdio: 'ignore' })+ } else {+ // tasklist is Windows-only; on macOS/Linux use pgrep so a Linux+ // dev box doesn't fall through and needlessly re-spawn Ollama.+ execSync('pgrep -x ollama', { stdio: 'ignore' })+ }+ return true+ } catch {+ return false+ }+ })()+ if (ollamaAlreadyRunning) {console.log('[Ollama] Already running')- } catch {- console.log('[Ollama] Starting...')+ } else {+ console.log('[Ollama] Launching in background…')try {const ollamaProc = spawn('ollama', ['serve'], {detached: true,@@ -345,8 +360,19 @@ function comfyLauncher(): Plugin {shell: false,windowsHide: true,})+ // CRITICAL: spawn() reports a missing binary ASYNCHRONOUSLY via an+ // 'error' event, not a throw — so the try/catch around it does NOT+ // catch ENOENT. Without this handler, an absent Ollama crashes the+ // whole `npm run dev` with "Error: spawn ollama ENOENT" (#63). Handle+ // it so a missing Ollama is a friendly hint, not a fatal crash.+ ollamaProc.on('error', (err: NodeJS.ErrnoException) => {+ if (err && err.code === 'ENOENT') {+ console.warn('[Ollama] Not started — Ollama is not installed or not on PATH. Install it from https://ollama.com/download (release builds bundle it). The dev server keeps running.')+ } else {+ console.warn('[Ollama] Failed to start:', err?.message || err)+ }+ })ollamaProc.unref()- console.log('[Ollama] Started')} catch (err) {console.warn('[Ollama] Failed to start:', err)}