Skip to content

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

fix(errors): the operating system stops writing our error messages

David0e07ebee585c
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index fea6a14f..a6d47fcf 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
@@ -303,7 +304,7 @@ pub(crate) fn execute_code_blocking(
.unwrap_or(0)));
fs::write(&script_path, &code)
- .map_err(|e| format!("Write temp script: {}", e))?;
+ .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;
// cwd: prefer the agent's folder workspace (the repo the user picked,
// threaded from chatCtx as workingDirectory) so a script's relative file
@@ -332,7 +333,7 @@ pub(crate) fn execute_code_blocking(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn()
- .map_err(|e| format!("Spawn Python: {}", e))?;
+ .map_err(|e| format!("Spawn Python: {}", os_error::english(&e)))?;
// Both pipes are drained on their own threads from here on. A script that
// prints more than a pipe buffer would otherwise block on write and never
@@ -426,7 +427,7 @@ pub fn file_write(
) -> Result<serde_json::Value, String> {
let full_path = resolve_agent_path(&path, chatId.as_deref(), Some(&*state))?;
if let Some(parent) = full_path.parent() {
- fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;
+ fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", os_error::english(&e)))?;
}
// Same treatment the desktop path (fs_write) already gets: keep the file's
// EOL/BOM convention, skip an identical write, and swap the new bytes in
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index a41e3803..12166d53 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -17,6 +17,7 @@
//! every body is identical; only the outermost layer is wrapped in
//! `#[tauri::command]` for the desktop IPC bridge.
+use crate::os_error;
use crate::commands::{bad_request, internal, not_found, CmdResult};
use crate::state::AppState;
use once_cell::sync::Lazy;
@@ -200,7 +201,7 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {
}
let mut child = cmd
.spawn()
- .map_err(|e| internal(format!("spawn {}: {}", program, e)))?;
+ .map_err(|e| internal(format!("spawn {}: {}", program, os_error::english(&e))))?;
// Orphan-safety: tie the child to a kill-on-close Job Object so a true app
// Quit (tray Quit / parent death) tears these long-running background tasks
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rs
index 9666713d..7524574f 100644
--- a/src-tauri/src/commands/download.rs
+++ b/src-tauri/src/commands/download.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
@@ -130,7 +131,7 @@ pub fn delete_comfy_model(filename: String, state: State<'_, AppState>) -> Resul
1 => {
let f = &hits[0];
let bytes = fs::metadata(f).map(|m| m.len()).unwrap_or(0);
- fs::remove_file(f).map_err(|e| format!("Delete failed: {}", e))?;
+ fs::remove_file(f).map_err(|e| format!("Delete failed: {}", os_error::english(&e)))?;
// Sweep a stale resume-partial next to it (the timeout/abort case
// leaves both the file and its .download twin behind).
let _ = fs::remove_file(f.with_extension("download"));
@@ -153,7 +154,7 @@ fn models_dir(comfy_path: &Option<String>, subfolder: &str) -> Result<PathBuf, S
} else {
PathBuf::from(base).join("models").join(subfolder)
};
- fs::create_dir_all(&dir).map_err(|e| format!("Create models dir: {}", e))?;
+ fs::create_dir_all(&dir).map_err(|e| format!("Create models dir: {}", os_error::english(&e)))?;
Ok(dir)
}
@@ -426,7 +427,7 @@ async fn do_download(
.connect_timeout(std::time::Duration::from_secs(30))
.read_timeout(std::time::Duration::from_secs(120))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let mut request = client.get(url);
@@ -439,7 +440,7 @@ async fn do_download(
let response = request
.send()
.await
- .map_err(|e| format!("Request failed: {}", e))?;
+ .map_err(|e| format!("Request failed: {}", os_error::english(&e)))?;
let status = response.status();
if !status.is_success() && status.as_u16() != 206 {
@@ -485,11 +486,11 @@ async fn do_download(
.append(true)
.open(&tmp_path)
.await
- .map_err(|e| format!("Open file for resume: {}", e))?
+ .map_err(|e| format!("Open file for resume: {}", os_error::english(&e)))?
} else {
tokio::fs::File::create(&tmp_path)
.await
- .map_err(|e| format!("Create file: {}", e))?
+ .map_err(|e| format!("Create file: {}", os_error::english(&e)))?
};
let mut stream = response.bytes_stream();
@@ -527,7 +528,7 @@ async fn do_download(
chunk = stream.next() => {
match chunk {
Some(Ok(bytes)) => {
- file.write_all(&bytes).await.map_err(|e| format!("Write: {}", e))?;
+ file.write_all(&bytes).await.map_err(|e| format!("Write: {}", os_error::english(&e)))?;
downloaded += bytes.len() as u64;
// Update progress every 500ms
@@ -560,7 +561,7 @@ async fn do_download(
}
}
- file.flush().await.map_err(|e| format!("Flush: {}", e))?;
+ file.flush().await.map_err(|e| format!("Flush: {}", os_error::english(&e)))?;
drop(file);
// A body can end early without ever erroring — a CDN cutting the connection,
@@ -578,7 +579,7 @@ async fn do_download(
tokio::fs::rename(&tmp_path, dest)
.await
- .map_err(|e| format!("Rename: {}", e))?;
+ .map_err(|e| format!("Rename: {}", os_error::english(&e)))?;
// Final progress update
if let Ok(mut dl) = downloads.lock() {
@@ -859,12 +860,12 @@ pub fn detect_model_path(provider: String) -> Result<serde_json::Value, String>
match provider_lower.as_str() {
"ollama" => {
let p = home.join(".ollama").join("models");
- fs::create_dir_all(&p).map_err(|e| format!("Create Ollama models dir: {}", e))?;
+ fs::create_dir_all(&p).map_err(|e| format!("Create Ollama models dir: {}", os_error::english(&e)))?;
Ok(serde_json::json!(p.to_string_lossy()))
}
"lm studio" | "lmstudio" => {
let p = home.join(".lmstudio").join("models");
- fs::create_dir_all(&p).map_err(|e| format!("Create LM Studio models dir: {}", e))?;
+ fs::create_dir_all(&p).map_err(|e| format!("Create LM Studio models dir: {}", os_error::english(&e)))?;
Ok(serde_json::json!(p.to_string_lossy()))
}
_ => Err(format!(
@@ -886,7 +887,7 @@ pub async fn download_model_to_path(
let dest_dir = destDir;
let expected_bytes = expectedBytes;
let dir = PathBuf::from(&dest_dir);
- fs::create_dir_all(&dir).map_err(|e| format!("Create dest dir: {}", e))?;
+ fs::create_dir_all(&dir).map_err(|e| format!("Create dest dir: {}", os_error::english(&e)))?;
let dest_file = dir.join(sanitize_filename(&filename));
if dest_file.exists() {
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index c30591a0..110325f0 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -1,3 +1,5 @@
+use crate::os_error;
+
// P1 — Built-in inference engine (bundled llama.cpp `llama-server`).
//
// The whole point of 2.5.7's "onboarding without external providers" is that
@@ -376,7 +378,7 @@ pub fn builtin_models_dir() -> Result<PathBuf, String> {
let base = dirs::data_dir().ok_or("Cannot resolve app data directory")?;
let dir = base.join("Locally Uncensored").join("models");
std::fs::create_dir_all(&dir)
- .map_err(|e| format!("Create built-in models dir: {e}"))?;
+ .map_err(|e| format!("Create built-in models dir: {}", os_error::english(&e)))?;
Ok(dir)
}
@@ -490,13 +492,13 @@ pub async fn kv_slot_action(port: u16, action: String) -> Result<serde_json::Val
// Serializing a multi-GB KV cache to disk takes a while on slow disks.
.timeout(Duration::from_secs(120))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let res = client
.post(&url)
.json(&serde_json::json!({ "filename": "lu-handoff.bin" }))
.send()
.await
- .map_err(|e| format!("slot {action} failed: {e}"))?;
+ .map_err(|e| format!("slot {action} failed: {}", os_error::english(&e)))?;
let ok = res.status().is_success();
let body: serde_json::Value = res.json().await.unwrap_or_else(|_| serde_json::json!({}));
Ok(serde_json::json!({ "ok": ok, "body": body }))
@@ -690,7 +692,7 @@ fn start_bundled_engine_blocking(
let mut child = cmd
.spawn()
- .map_err(|e| format!("Failed to spawn bundled engine: {e}"))?;
+ .map_err(|e| format!("Failed to spawn bundled engine: {}", os_error::english(&e)))?;
let diagnostics = child.stderr.take().map(super::shell::drain);
*state.bundled_engine.lock().unwrap() = Some(BundledEngine {
@@ -1230,7 +1232,7 @@ fn start_bundled_embed_blocking(
let mut child = cmd
.spawn()
- .map_err(|e| format!("Failed to spawn embeddings server: {e}"))?;
+ .map_err(|e| format!("Failed to spawn embeddings server: {}", os_error::english(&e)))?;
let diagnostics = child.stderr.take().map(super::shell::drain);
*state.bundled_embed.lock().unwrap() = Some(BundledEngine {
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index b924f8f1..4d88b5c5 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
@@ -229,7 +230,7 @@ pub fn fs_read_bytes(
size, cap
));
}
- let bytes = fs::read(&full).map_err(|e| format!("Read error: {}", e))?;
+ let bytes = fs::read(&full).map_err(|e| format!("Read error: {}", os_error::english(&e)))?;
Ok(serde_json::json!({
"base64": base64::engine::general_purpose::STANDARD.encode(&bytes),
"bytes": bytes.len(),
@@ -275,7 +276,7 @@ pub(crate) fn write_atomic(target: &Path, bytes: &[u8]) -> Result<(), String> {
.unwrap_or_else(|| "file".to_string());
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let tmp = parent.join(format!(".{}.tmp{}-{}", base, std::process::id(), seq));
- fs::write(&tmp, bytes).map_err(|e| format!("Write error: {}", e))?;
+ fs::write(&tmp, bytes).map_err(|e| format!("Write error: {}", os_error::english(&e)))?;
if let Err(e) = fs::rename(&tmp, target) {
let _ = fs::remove_file(&tmp);
return Err(format!("Write error (rename): {}", e));
@@ -288,7 +289,7 @@ pub(crate) fn write_atomic(target: &Path, bytes: &[u8]) -> Result<(), String> {
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))?;
+ fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", os_error::english(&e)))?;
}
// Read the current bytes (if any) to preserve the file's EOL/BOM convention
// and to detect a no-op write.
@@ -385,7 +386,7 @@ pub fn fs_list(
entries.push(file_meta(entry.path()));
}
} else {
- let read_dir = fs::read_dir(&dir).map_err(|e| format!("Read dir: {}", e))?;
+ let read_dir = fs::read_dir(&dir).map_err(|e| format!("Read dir: {}", os_error::english(&e)))?;
for entry in read_dir.flatten() {
if entries.len() >= max_entries {
break;
@@ -471,7 +472,7 @@ pub fn fs_info(path: String, chatId: Option<String>, workingDirectory: Option<St
if !full.exists() {
return Err(format!("Path not found: {}", full.display()));
}
- let meta = fs::metadata(&full).map_err(|e| format!("Metadata error: {}", e))?;
+ let meta = fs::metadata(&full).map_err(|e| format!("Metadata error: {}", os_error::english(&e)))?;
let modified = meta
.modified()
.ok()
@@ -522,7 +523,7 @@ pub async fn save_text_file_dialog(
match file {
Some(handle) => {
let path = handle.path().to_path_buf();
- std::fs::write(&path, content).map_err(|e| format!("Write failed: {}", e))?;
+ std::fs::write(&path, content).map_err(|e| format!("Write failed: {}", os_error::english(&e)))?;
Ok(Some(path.to_string_lossy().into_owned()))
}
None => Ok(None),
@@ -565,7 +566,7 @@ pub async fn save_binary_file_dialog(
match file {
Some(handle) => {
let path = handle.path().to_path_buf();
- std::fs::write(&path, &bytes).map_err(|e| format!("Write failed: {}", e))?;
+ std::fs::write(&path, &bytes).map_err(|e| format!("Write failed: {}", os_error::english(&e)))?;
Ok(Some(path.to_string_lossy().into_owned()))
}
None => Ok(None),
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rs
index aad7dbd7..f140f8dc 100644
--- a/src-tauri/src/commands/install.rs
+++ b/src-tauri/src/commands/install.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::fs;
use std::io::{BufRead, BufReader, Read as IoRead};
use std::path::{Path, PathBuf};
@@ -200,7 +201,7 @@ pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> Result<PathB
let out = cmd
.output()
- .map_err(|e| format!("Could not spawn `python -m venv`: {}", e))?;
+ .map_err(|e| format!("Could not spawn `python -m venv`: {}", os_error::english(&e)))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
@@ -1383,7 +1384,7 @@ fn download_file_blocking(
.build()
.map_err(|e| format!("HTTP client error: {}", e))?;
- let response = client.get(url).send().map_err(|e| format!("Request failed: {}", e))?;
+ let response = client.get(url).send().map_err(|e| format!("Request failed: {}", os_error::english(&e)))?;
if !response.status().is_success() {
return Err(format!("HTTP {}", response.status()));
@@ -1395,7 +1396,7 @@ fn download_file_blocking(
s.status = "downloading".to_string();
}
- let mut file = fs::File::create(dest).map_err(|e| format!("Create file: {}", e))?;
+ let mut file = fs::File::create(dest).map_err(|e| format!("Create file: {}", os_error::english(&e)))?;
let mut reader = std::io::BufReader::new(response);
let mut downloaded: u64 = 0;
let start = Instant::now();
@@ -2451,7 +2452,7 @@ fn start_lmstudio_server_blocking() -> Result<serde_json::Value, String> {
#[cfg(target_os = "windows")]
srv.creation_flags(CREATE_NO_WINDOW);
srv.spawn()
- .map_err(|e| format!("spawn lms: {}", e))?;
+ .map_err(|e| format!("spawn lms: {}", os_error::english(&e)))?;
Ok(serde_json::json!({"status": "starting"}))
}
None => Err(
@@ -2601,7 +2602,7 @@ fn lmstudio_load_model_blocking(model: String, contextLength: Option<u32>) -> Re
cmd.creation_flags(CREATE_NO_WINDOW);
let output = cmd
.output()
- .map_err(|e| format!("spawn lms load: {e}"))?;
+ .map_err(|e| format!("spawn lms load: {}", os_error::english(&e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -2695,7 +2696,7 @@ fn lmstudio_unload_model_blocking(model: String) -> Result<serde_json::Value, St
cmd.creation_flags(CREATE_NO_WINDOW);
let output = cmd
.output()
- .map_err(|e| format!("spawn lms unload: {e}"))?;
+ .map_err(|e| format!("spawn lms unload: {}", os_error::english(&e)))?;
if !output.status.success() {
return Err(format!(
"lms unload failed: {}",
@@ -3392,7 +3393,7 @@ fn install_custom_node_blocking(
// Create custom_nodes dir if it doesn't exist
if !custom_nodes_dir.exists() {
fs::create_dir_all(&custom_nodes_dir)
- .map_err(|e| format!("Failed to create custom_nodes directory: {}", e))?;
+ .map_err(|e| format!("Failed to create custom_nodes directory: {}", os_error::english(&e)))?;
}
// Bug N — same git probe as install_comfyui. Block on missing git, log
@@ -3431,7 +3432,7 @@ fn install_custom_node_blocking(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let output = cmd.output()
- .map_err(|e| format!("Git pull failed: {}", e))?;
+ .map_err(|e| format!("Git pull failed: {}", os_error::english(&e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
error!(node = %node_name, "custom node git pull failed");
@@ -3461,7 +3462,7 @@ fn install_custom_node_blocking(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let output = cmd.output()
- .map_err(|e| format!("Git clone failed: {}", e))?;
+ .map_err(|e| format!("Git clone failed: {}", os_error::english(&e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
error!(node = %node_name, "custom node clone failed");
@@ -3541,7 +3542,7 @@ fn install_node_requirements(
#[cfg(target_os = "windows")]
pip.creation_flags(CREATE_NO_WINDOW);
pip.output()
- .map_err(|e| format!("Failed to spawn pip for {} requirements: {}", node_name, e))
+ .map_err(|e| format!("Failed to spawn pip for {} requirements: {}", node_name, os_error::english(&e)))
};
let pip_out = run_pip(&[])?;
if !pip_out.status.success() {
diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rs
index fa1b527b..223cc063 100644
--- a/src-tauri/src/commands/media_cmds.rs
+++ b/src-tauri/src/commands/media_cmds.rs
@@ -15,6 +15,7 @@
//! (server.py on 127.0.0.1:47712) directly from `commands::mlx`, exactly
//! like the existing ComfyUI/whisper sidecars.
+use crate::os_error;
use crate::state::AppState;
use base64::Engine;
use serde_json::Value;
@@ -191,6 +192,6 @@ pub fn read_media_file(path: String) -> Result<String, String> {
}
let bytes = std::fs::read(&canonical)
- .map_err(|e| format!("read_media_file: {}: {e}", canonical.display()))?;
+ .map_err(|e| format!("read_media_file: {}: {}", canonical.display(), os_error::english(&e)))?;
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
}
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
index 1cb7eee5..ca244c17 100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@ -22,6 +22,7 @@
//! Generate (`mlx_generate`): proxy a JSON request to 127.0.0.1:47712,
//! return the base64 PNG to the web UI.
+use crate::os_error;
use crate::commands::CmdResult;
use crate::state::AppState;
use serde::Deserialize;
@@ -204,11 +205,11 @@ fn install_mlx_steps(slot: &crate::install_state::InstallSlot) -> Result<(), Str
let venv_dir = mlx_root().join("venv");
if !venv_dir.exists() {
slot.log(format!("creating venv at {}", venv_dir.display()));
- std::fs::create_dir_all(mlx_root()).map_err(|e| e.to_string())?;
+ std::fs::create_dir_all(mlx_root()).map_err(|e| os_error::english(&e))?;
let out = Command::new(&python)
.args(["-m", "venv", venv_dir.to_str().unwrap()])
.output()
- .map_err(|e| format!("venv create failed to spawn: {e}"))?;
+ .map_err(|e| format!("venv create failed to spawn: {}", os_error::english(&e)))?;
if !out.status.success() {
return Err(format!(
"venv create failed: {}",
@@ -221,13 +222,13 @@ fn install_mlx_steps(slot: &crate::install_state::InstallSlot) -> Result<(), Str
let server_path = mlx_root().join("server.py");
std::fs::write(&req_path, REQUIREMENTS_TXT)
.map_err(|e| format!("write requirements.txt: {e}"))?;
- std::fs::write(&server_path, SERVER_PY).map_err(|e| format!("write server.py: {e}"))?;
+ std::fs::write(&server_path, SERVER_PY).map_err(|e| format!("write server.py: {}", os_error::english(&e)))?;
slot.log("running pip install (this pulls torch + diffusers, ~3 GB)");
let out = Command::new(venv_pip())
.args(["install", "--upgrade", "-r", req_path.to_str().unwrap()])
.output()
- .map_err(|e| format!("pip install spawn: {e}"))?;
+ .map_err(|e| format!("pip install spawn: {}", os_error::english(&e)))?;
if !out.status.success() {
return Err(format!(
"pip install failed: {}",
@@ -262,7 +263,7 @@ fn install_mlx_steps(slot: &crate::install_state::InstallSlot) -> Result<(), Str
apply_hf_token(&mut prefetch_cmd);
let out = prefetch_cmd
.output()
- .map_err(|e| format!("model prefetch spawn: {e}"))?;
+ .map_err(|e| format!("model prefetch spawn: {}", os_error::english(&e)))?;
if !out.status.success() {
return Err(format!(
"model prefetch failed: {}",
@@ -700,7 +701,7 @@ pub fn mlx_image_delete_model(state: &AppState, args: &Value) -> CmdResult {
return Err(crate::commands::not_found(format!("{id} is not installed")));
}
std::fs::remove_dir_all(&dir)
- .map_err(|e| crate::commands::internal(format!("delete {id}: {e}")))?;
+ .map_err(|e| crate::commands::internal(format!("delete {id}: {}", os_error::english(&e))))?;
Ok(json!({ "ok": true, "id": id }))
}
@@ -762,7 +763,7 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {
.json(&body)
.send()
.await
- .map_err(|e| crate::commands::internal(format!("mlx unreachable: {e}")))?;
+ .map_err(|e| crate::commands::internal(format!("mlx unreachable: {}", os_error::english(&e))))?;
if !res.status().is_success() {
let s = res.status();
let text = res.text().await.unwrap_or_default();
@@ -813,7 +814,7 @@ fn write_generated_png(b64: &str) -> Result<PathBuf, String> {
.decode(b64)
.map_err(|e| format!("decode: {e}"))?;
let dir = images_root();
- std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;
+ std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {}", dir.display(), os_error::english(&e)))?;
// Millisecond stamp + the process id: two renders inside the same
// millisecond (batching, a retry) must not overwrite each other.
let stamp = std::time::SystemTime::now()
@@ -821,7 +822,7 @@ fn write_generated_png(b64: &str) -> Result<PathBuf, String> {
.map(|d| d.as_millis())
.unwrap_or(0);
let path = dir.join(format!("mlx-{stamp}-{}.png", std::process::id()));
- std::fs::write(&path, bytes).map_err(|e| format!("write {}: {e}", path.display()))?;
+ std::fs::write(&path, bytes).map_err(|e| format!("write {}: {}", path.display(), os_error::english(&e)))?;
Ok(path)
}
@@ -836,7 +837,7 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {
// bridge update keeps spawning whatever install_mlx_diffusion wrote
// months ago.
std::fs::write(&server, SERVER_PY)
- .map_err(|e| crate::commands::internal(format!("write server.py: {e}")))?;
+ .map_err(|e| crate::commands::internal(format!("write server.py: {}", os_error::english(&e))))?;
let log_path = mlx_root().join("server.log");
let stdout = std::fs::OpenOptions::new()
.create(true)
@@ -859,7 +860,7 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {
apply_hf_token(&mut server_cmd);
server_cmd
.spawn()
- .map_err(|e| crate::commands::internal(format!("spawn mlx server: {e}")))?;
+ .map_err(|e| crate::commands::internal(format!("spawn mlx server: {}", os_error::english(&e))))?;
Ok(json!({"ok": true, "port": MLX_PORT, "log": log_path.to_string_lossy()}))
}
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 459a1653..ffb69d09 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
@@ -1386,8 +1387,11 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn()
.map_err(|e| {
+ // The log keeps whatever the OS wrote, in whatever language: it is
+ // ours to read and the original wording helps support. Only the
+ // line the user sees is rewritten.
error!(error = %e, python = %python, "comfyui start failed");
- format!("Failed to start ComfyUI (python={}): {}", python, e)
+ format!("Failed to start ComfyUI (python={}): {}", python, os_error::english(&e))
})?;
// Assign to Job Object so child dies when parent dies (even via Task Manager)
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index 114ca568..5db850aa 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use tauri::Emitter;
/// Validate that an external URL is safe to fetch (no SSRF).
@@ -62,18 +63,18 @@ pub async fn fetch_external(url: String) -> Result<String, String> {
.timeout(std::time::Duration::from_secs(60))
.redirect(ssrf_safe_redirect_policy(10))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let resp = client.get(&url)
.send()
.await
- .map_err(|e| format!("fetch_external: {}", e))?;
+ .map_err(|e| format!("fetch_external: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
}
- resp.text().await.map_err(|e| e.to_string())
+ resp.text().await.map_err(|e| os_error::english(&e))
}
/// Binary HTTP proxy — fetch any external URL and return bytes.
@@ -87,18 +88,18 @@ pub async fn fetch_external_bytes(url: String) -> Result<Vec<u8>, String> {
.timeout(std::time::Duration::from_secs(300))
.redirect(ssrf_safe_redirect_policy(10))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let resp = client.get(&url)
.send()
.await
- .map_err(|e| format!("fetch_external_bytes: {}", e))?;
+ .map_err(|e| format!("fetch_external_bytes: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
}
- resp.bytes().await.map(|b| b.to_vec()).map_err(|e| e.to_string())
+ resp.bytes().await.map(|b| b.to_vec()).map_err(|e| os_error::english(&e))
}
/// Extract the host from `ollama_base` + `comfy_host` so we can allow-list
@@ -439,7 +440,7 @@ pub async fn proxy_localhost(
.user_agent("LocallyUncensored/2.0")
.timeout(timeout)
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let http_method = method.unwrap_or_else(|| "GET".to_string());
@@ -455,7 +456,7 @@ pub async fn proxy_localhost(
let resp = request
.send()
.await
- .map_err(|e| format!("proxy_localhost: {}", e))?;
+ .map_err(|e| format!("proxy_localhost: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
let status = resp.status().as_u16();
@@ -463,7 +464,7 @@ pub async fn proxy_localhost(
return Err(format!("HTTP {}: {}", status, text));
}
- resp.text().await.map_err(|e| e.to_string())
+ resp.text().await.map_err(|e| os_error::english(&e))
}
/// Streaming localhost proxy — BUFFERS the whole body (no streaming). Kept for
@@ -477,7 +478,7 @@ pub async fn proxy_localhost_stream(url: String, method: Option<String>, body: O
.user_agent("LocallyUncensored/2.0")
.timeout(std::time::Duration::from_secs(7200))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let http_method = method.unwrap_or_else(|| "GET".to_string());
@@ -493,7 +494,7 @@ pub async fn proxy_localhost_stream(url: String, method: Option<String>, body: O
let resp = request
.send()
.await
- .map_err(|e| format!("proxy_localhost_stream: {}", e))?;
+ .map_err(|e| format!("proxy_localhost_stream: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
let status = resp.status().as_u16();
@@ -501,7 +502,7 @@ pub async fn proxy_localhost_stream(url: String, method: Option<String>, body: O
return Err(format!("HTTP {}: {}", status, text));
}
- resp.bytes().await.map(|b| b.to_vec()).map_err(|e| e.to_string())
+ resp.bytes().await.map(|b| b.to_vec()).map_err(|e| os_error::english(&e))
}
/// Chunked streaming localhost proxy for Ollama chat (David 2026-06-02).
@@ -546,7 +547,7 @@ pub async fn proxy_localhost_stream_chunked(
.user_agent("LocallyUncensored/2.0")
.timeout(std::time::Duration::from_secs(7200))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let http_method = method.unwrap_or_else(|| "GET".to_string());
@@ -562,7 +563,7 @@ pub async fn proxy_localhost_stream_chunked(
// Race the request against cancellation even during connect/headers.
let resp = tokio::select! {
_ = token.cancelled() => return Ok(()),
- r = request.send() => r.map_err(|e| format!("proxy_localhost_stream_chunked: {}", e))?,
+ r = request.send() => r.map_err(|e| format!("proxy_localhost_stream_chunked: {}", os_error::english(&e)))?,
};
if !resp.status().is_success() {
@@ -580,7 +581,7 @@ pub async fn proxy_localhost_stream_chunked(
_ = token.cancelled() => break,
item = stream.next() => match item {
Some(it) => {
- let bytes = it.map_err(|e| e.to_string())?;
+ let bytes = it.map_err(|e| os_error::english(&e))?;
if bytes.is_empty() { continue; }
// JS side gone (reader cancelled / window closed) → stop.
if on_chunk.send(bytes.to_vec()).is_err() { break; }
@@ -643,16 +644,16 @@ pub async fn comfy_upload_image(
let part = reqwest::multipart::Part::bytes(file_bytes)
.file_name(filename)
.mime_str(&ct)
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let form = reqwest::multipart::Form::new()
.part("image", part)
.text("overwrite", "true");
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let resp = client.post(&url).multipart(form).send().await
- .map_err(|e| format!("comfy_upload_image: {}", e))?;
+ .map_err(|e| format!("comfy_upload_image: {}", os_error::english(&e)))?;
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
if !status.is_success() {
@@ -682,7 +683,7 @@ pub async fn pull_model_stream(app: tauri::AppHandle, state: tauri::State<'_, cr
.user_agent("LocallyUncensored/2.0")
.timeout(std::time::Duration::from_secs(7200))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
// Route to the configured Ollama base (Issue #31 — was hardcoded
// http://localhost:11434 so remote Ollama hosts never got the pull).
@@ -697,7 +698,7 @@ pub async fn pull_model_stream(app: tauri::AppHandle, state: tauri::State<'_, cr
.body(format!(r#"{{"name":"{}","stream":true}}"#, name))
.send()
.await
- .map_err(|e| format!("pull_model_stream: {}", e))?;
+ .map_err(|e| format!("pull_model_stream: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
let status = resp.status().as_u16();
@@ -837,15 +838,15 @@ pub async fn ollama_search(query: String) -> Result<serde_json::Value, String> {
.user_agent("LocallyUncensored/2.0")
.timeout(std::time::Duration::from_secs(10))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| os_error::english(&e))?;
let resp = client.get(&url)
.header("Accept", "application/json")
.send()
.await
- .map_err(|e| format!("Ollama search: {}", e))?;
+ .map_err(|e| format!("Ollama search: {}", os_error::english(&e)))?;
- let text = resp.text().await.map_err(|e| e.to_string())?;
+ let text = resp.text().await.map_err(|e| os_error::english(&e))?;
// Try to parse as JSON; if it's HTML, return empty results
match serde_json::from_str::<serde_json::Value>(&text) {
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 1d094d60..6dc2ab39 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::sync::Arc;
use std::collections::HashMap;
use std::net::SocketAddr;
@@ -5347,7 +5348,7 @@ pub async fn start_tunnel(
let _ = std::fs::remove_file(&cf_path);
}
let dir = cf_path.parent().ok_or("Invalid cloudflared install path")?;
- std::fs::create_dir_all(dir).map_err(|e| format!("mkdir: {}", e))?;
+ std::fs::create_dir_all(dir).map_err(|e| format!("mkdir: {}", os_error::english(&e)))?;
let download_url = if cfg!(windows) {
"https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe"
@@ -5363,11 +5364,11 @@ pub async fn start_tunnel(
.build()
.map_err(|e| e.to_string())?;
- let resp = client.get(download_url).send().await.map_err(|e| format!("Download failed: {}", e))?;
+ let resp = client.get(download_url).send().await.map_err(|e| format!("Download failed: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
return Err(format!("Download HTTP {}", resp.status()));
}
- let bytes = resp.bytes().await.map_err(|e| e.to_string())?;
+ let bytes = resp.bytes().await.map_err(|e| os_error::english(&e))?;
// Integrity gate before we write + chmod +x + spawn a downloaded binary.
// cloudflared pins to `releases/latest` on purpose (the self-heal design:
@@ -5405,14 +5406,14 @@ pub async fn start_tunnel(
#[cfg(target_os = "macos")]
{
let tgz = dir.join("cloudflared.tgz");
- std::fs::write(&tgz, &bytes).map_err(|e| format!("write tgz: {}", e))?;
+ std::fs::write(&tgz, &bytes).map_err(|e| format!("write tgz: {}", os_error::english(&e)))?;
let status = std::process::Command::new("tar")
.arg("-xzf")
.arg(&tgz)
.arg("-C")
.arg(dir)
.status()
- .map_err(|e| format!("tar spawn: {}", e))?;
+ .map_err(|e| format!("tar spawn: {}", os_error::english(&e)))?;
let _ = std::fs::remove_file(&tgz);
if !status.success() {
return Err("Failed to extract cloudflared from its .tgz archive".into());
@@ -5422,7 +5423,7 @@ pub async fn start_tunnel(
}
}
#[cfg(not(target_os = "macos"))]
- std::fs::write(&cf_path, &bytes).map_err(|e| format!("write: {}", e))?;
+ std::fs::write(&cf_path, &bytes).map_err(|e| format!("write: {}", os_error::english(&e)))?;
// Make executable on Unix
#[cfg(unix)]
@@ -5446,7 +5447,7 @@ pub async fn start_tunnel(
let child = cmd.spawn()
.map_err(|e| {
error!(error = %e, "cloudflared tunnel spawn failed");
- format!("Failed to start cloudflared: {}", e)
+ format!("Failed to start cloudflared: {}", os_error::english(&e))
})?;
let pid = child.id();
diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rs
index eee4fad4..4d5c700e 100644
--- a/src-tauri/src/commands/search.rs
+++ b/src-tauri/src/commands/search.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::sync::atomic::Ordering;
use tauri::State;
@@ -24,7 +25,7 @@ async fn try_searxng(query: &str, count: usize) -> Result<Vec<SearchResult>, Str
let resp = client.get(&url)
.send()
.await
- .map_err(|e| format!("SearXNG: {}", e))?;
+ .map_err(|e| format!("SearXNG: {}", os_error::english(&e)))?;
let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
@@ -58,7 +59,7 @@ async fn try_ddg(query: &str, count: usize) -> Result<Vec<SearchResult>, String>
.form(&[("q", query)])
.send()
.await
- .map_err(|e| format!("DDG: {}", e))?;
+ .map_err(|e| format!("DDG: {}", os_error::english(&e)))?;
let html = resp.text().await.map_err(|e| e.to_string())?;
@@ -152,7 +153,7 @@ async fn try_brave(query: &str, count: usize, api_key: &str) -> Result<Vec<Searc
.header("X-Subscription-Token", api_key)
.send()
.await
- .map_err(|e| format!("Brave: {}", e))?;
+ .map_err(|e| format!("Brave: {}", os_error::english(&e)))?;
let status = resp.status();
if !status.is_success() {
return Err(format!("Brave: HTTP {} (check the API key)", status.as_u16()));
@@ -206,7 +207,7 @@ async fn try_tavily(query: &str, count: usize, api_key: &str) -> Result<Vec<Sear
}))
.send()
.await
- .map_err(|e| format!("Tavily: {}", e))?;
+ .map_err(|e| format!("Tavily: {}", os_error::english(&e)))?;
let status = resp.status();
if !status.is_success() {
return Err(format!("Tavily: HTTP {} (check the API key)", status.as_u16()));
@@ -234,7 +235,7 @@ async fn try_wikipedia(query: &str, count: usize) -> Result<Vec<SearchResult>, S
.get(&url)
.send()
.await
- .map_err(|e| format!("Wikipedia: {}", e))?;
+ .map_err(|e| format!("Wikipedia: {}", os_error::english(&e)))?;
let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
@@ -485,7 +486,7 @@ pub async fn web_fetch(url: String) -> Result<serde_json::Value, String> {
.header("Accept-Language", "en,de;q=0.8")
.send()
.await
- .map_err(|e| format!("Fetch failed: {}", e))?;
+ .map_err(|e| format!("Fetch failed: {}", os_error::english(&e)))?;
let status = resp.status().as_u16();
let final_url = resp.url().to_string();
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index 37781e25..32724bb7 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::io::Read;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
@@ -272,7 +273,7 @@ fn shell_execute_sync(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
- let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", e))?;
+ let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", os_error::english(&e)))?;
// Write on a thread: the child may fill its output pipes before it has
// consumed stdin, and a blocking write here would deadlock against the
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 06bdc7ec..476dcb43 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use base64::Engine;
use sysinfo::System;
@@ -82,7 +83,7 @@ fn screenshot_blocking() -> Result<serde_json::Value, String> {
// such file"), or a caller simply got the other one's screen.
let tmp = std::env::temp_dir().join(format!("lu-screenshot-{}.png", uuid::Uuid::new_v4()));
let captured = capture_screen_to(&tmp)
- .and_then(|()| std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", e)));
+ .and_then(|()| std::fs::read(&tmp).map_err(|e| format!("Read screenshot: {}", os_error::english(&e))));
// Always — the old code returned early on a read error and left a full
// picture of the user's screen sitting in the temp directory.
let _ = std::fs::remove_file(&tmp);
@@ -113,7 +114,7 @@ pub(crate) fn run_capture_bounded(
) -> Result<(), String> {
let mut child = cmd
.spawn()
- .map_err(|e| format!("Screenshot failed: {}", e))?;
+ .map_err(|e| format!("Screenshot failed: {}", os_error::english(&e)))?;
let deadline = std::time::Instant::now() + max;
loop {
match child.try_wait() {
@@ -332,7 +333,7 @@ pub(crate) fn merged_backup(previous: &str, incoming: &str, lost: &[String]) ->
#[tauri::command]
pub fn backup_stores(data: String) -> Result<(), String> {
let dir = persistent_dir()?;
- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
let target = dir.join("store_backup.json");
let tmp = dir.join("store_backup.tmp");
@@ -353,8 +354,8 @@ pub fn backup_stores(data: String) -> Result<(), String> {
merged_backup(&previous, &data, &lost)
};
- std::fs::write(&tmp, &payload).map_err(|e| e.to_string())?;
- std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;
+ std::fs::write(&tmp, &payload).map_err(|e| os_error::english(&e))?;
+ std::fs::rename(&tmp, &target).map_err(|e| os_error::english(&e))?;
Ok(())
}
@@ -363,7 +364,7 @@ pub fn backup_stores(data: String) -> Result<(), String> {
pub fn restore_stores() -> Result<Option<String>, String> {
let path = persistent_dir()?.join("store_backup.json");
if path.exists() {
- let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
+ let data = std::fs::read_to_string(&path).map_err(|e| os_error::english(&e))?;
Ok(Some(data))
} else {
Ok(None)
@@ -393,11 +394,11 @@ pub fn restore_stores() -> Result<Option<String>, String> {
#[tauri::command]
pub fn backup_rag_chunks(data: String) -> Result<(), String> {
let dir = persistent_dir()?;
- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
let target = dir.join("rag_chunks_backup.json");
let tmp = dir.join("rag_chunks_backup.tmp");
- std::fs::write(&tmp, &data).map_err(|e| e.to_string())?;
- std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;
+ std::fs::write(&tmp, &data).map_err(|e| os_error::english(&e))?;
+ std::fs::rename(&tmp, &target).map_err(|e| os_error::english(&e))?;
Ok(())
}
@@ -409,7 +410,7 @@ pub fn backup_rag_chunks(data: String) -> Result<(), String> {
pub fn restore_rag_chunks() -> Result<Option<String>, String> {
let path = persistent_dir()?.join("rag_chunks_backup.json");
if path.exists() {
- let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
+ let data = std::fs::read_to_string(&path).map_err(|e| os_error::english(&e))?;
Ok(Some(data))
} else {
Ok(None)
@@ -429,12 +430,12 @@ pub fn is_onboarding_done() -> bool {
#[tauri::command]
pub fn set_onboarding_done(done: Option<bool>) -> Result<(), String> {
let dir = persistent_dir()?;
- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
let path = dir.join("onboarding_done");
if done.unwrap_or(true) {
- std::fs::write(&path, "1").map_err(|e| e.to_string())?;
+ std::fs::write(&path, "1").map_err(|e| os_error::english(&e))?;
} else if path.exists() {
- std::fs::remove_file(&path).map_err(|e| e.to_string())?;
+ std::fs::remove_file(&path).map_err(|e| os_error::english(&e))?;
}
Ok(())
}
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index 07dc8cc3..a689c972 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -1,3 +1,5 @@
+use crate::os_error;
+
// 2.5.8 — local character trainer (Character Studio, local lane).
//
// Trains a character LoRA fully on the user's GPU with kohya's musubi-tuner,
@@ -580,7 +582,7 @@ fn run_streamed(
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd
.spawn()
- .map_err(|e| format!("{label} could not start: {e}"))?;
+ .map_err(|e| format!("{label} could not start: {}", os_error::english(&e)))?;
if let Ok(mut slot) = pid_slot.lock() {
*slot = Some(child.id());
}
@@ -975,15 +977,15 @@ pub fn stage_training_image(
return Err("image is empty or larger than 40 MB".to_string());
}
let img_dir = trainer_root(&app).join("train").join(&set).join("img");
- fs::create_dir_all(&img_dir).map_err(|e| format!("could not create the set dir: {e}"))?;
+ fs::create_dir_all(&img_dir).map_err(|e| format!("could not create the set dir: {}", os_error::english(&e)))?;
let base = if name.is_empty() { format!("photo_{}", fileBytes.len() % 100000) } else { name };
let stem = free_stem(&img_dir, &base, &ext, &fileBytes);
fs::write(img_dir.join(format!("{stem}.{ext}")), &fileBytes)
- .map_err(|e| format!("could not write the photo: {e}"))?;
+ .map_err(|e| format!("could not write the photo: {}", os_error::english(&e)))?;
// Caption sidecar: trigger word comes first — musubi has no trigger
// mechanism of its own, the token must live in every caption.
fs::write(img_dir.join(format!("{stem}.txt")), caption.trim())
- .map_err(|e| format!("could not write the caption: {e}"))?;
+ .map_err(|e| format!("could not write the caption: {}", os_error::english(&e)))?;
Ok(serde_json::json!({"staged": format!("{stem}.{ext}")}))
}
@@ -996,7 +998,7 @@ pub fn clear_training_set(app: tauri::AppHandle, setId: String) -> Result<(), St
}
let dir = trainer_root(&app).join("train").join(&set);
if dir.exists() {
- fs::remove_dir_all(&dir).map_err(|e| format!("could not clear the set: {e}"))?;
+ fs::remove_dir_all(&dir).map_err(|e| format!("could not clear the set: {}", os_error::english(&e)))?;
}
Ok(())
}
diff --git a/src-tauri/src/commands/tts.rs b/src-tauri/src/commands/tts.rs
index 55fbd654..1aed5318 100644
--- a/src-tauri/src/commands/tts.rs
+++ b/src-tauri/src/commands/tts.rs
@@ -8,6 +8,7 @@
//! avoids a long-lived process + version-specific Python API. Voice models are
//! downloaded on demand into `<app_data>/piper_voices/`.
+use crate::os_error;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
@@ -196,7 +197,7 @@ fn download_voice_blocking(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
- let output = cmd.output().map_err(|e| format!("could not start voice download: {}", e))?;
+ let output = cmd.output().map_err(|e| format!("could not start voice download: {}", os_error::english(&e)))?;
if !output.status.success() {
return Err(format!("voice download failed: {}", String::from_utf8_lossy(&output.stderr)));
}
@@ -291,7 +292,7 @@ fn synthesize_blocking(
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
- let mut child = cmd.spawn().map_err(|e| format!("Failed to start piper: {}", e))?;
+ let mut child = cmd.spawn().map_err(|e| format!("Failed to start piper: {}", os_error::english(&e)))?;
// Feed stdin from its own thread. Writing the whole text inline and only
// then draining piper's pipes deadlocks once the text outgrows the pipe
// buffer: piper blocks writing its log while we block writing the text.
@@ -313,7 +314,7 @@ fn synthesize_blocking(
));
}
- let bytes = std::fs::read(&out_wav).map_err(|e| format!("read wav: {}", e))?;
+ let bytes = std::fs::read(&out_wav).map_err(|e| format!("read wav: {}", os_error::english(&e)))?;
let _ = std::fs::remove_file(&out_wav);
if bytes.is_empty() {
return Err("piper produced an empty WAV".to_string());
@@ -379,7 +380,7 @@ pub async fn synthesize_external(
.json(&body)
.send()
.await
- .map_err(|e| format!("external TTS request failed: {}", e))?;
+ .map_err(|e| format!("external TTS request failed: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
let code = resp.status().as_u16();
@@ -399,7 +400,7 @@ pub async fn synthesize_external(
.filter(|s| s.starts_with("audio/"))
.unwrap_or_else(|| "audio/wav".to_string());
- let bytes = resp.bytes().await.map_err(|e| e.to_string())?;
+ let bytes = resp.bytes().await.map_err(|e| os_error::english(&e))?;
if bytes.is_empty() {
return Err("external TTS returned no audio".to_string());
}
diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rs
index 80c91284..e0855066 100644
--- a/src-tauri/src/commands/video.rs
+++ b/src-tauri/src/commands/video.rs
@@ -9,6 +9,7 @@
//! `--model-dir` argument passed to `mlx_video.<family>.generate`).
//! Generated videos land in `~/.config/lu-labs/videos/<job_id>.mp4`.
+use crate::os_error;
use crate::commands::{bad_request, internal, CmdResult};
use crate::state::AppState;
use serde::Deserialize;
@@ -356,7 +357,7 @@ pub fn video_delete_model(state: &AppState, args: &Value) -> CmdResult {
if !dir.is_dir() {
return Err(crate::commands::not_found(format!("{id} is not installed")));
}
- std::fs::remove_dir_all(&dir).map_err(|e| internal(format!("delete {id}: {e}")))?;
+ std::fs::remove_dir_all(&dir).map_err(|e| internal(format!("delete {id}: {}", os_error::english(&e))))?;
Ok(json!({ "ok": true, "id": id }))
}
@@ -460,7 +461,7 @@ pub fn video_install_model(state: &AppState, args: &Value) -> CmdResult {
let target = model_dir(entry.id);
if let Some(parent) = target.parent() {
- std::fs::create_dir_all(parent).map_err(|e| internal(e.to_string()))?;
+ std::fs::create_dir_all(parent).map_err(|e| internal(os_error::english(&e)))?;
}
slot.start();
crate::install_state::watch_dir_size(
@@ -605,7 +606,7 @@ pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {
}
let out_dir = outputs_root();
- std::fs::create_dir_all(&out_dir).map_err(|e| internal(e.to_string()))?;
+ std::fs::create_dir_all(&out_dir).map_err(|e| internal(os_error::english(&e)))?;
let job_id = uuid::Uuid::new_v4().simple().to_string();
let out_path = out_dir.join(format!("{}.mp4", job_id));
@@ -671,7 +672,7 @@ pub fn video_generate(state: &AppState, args: &Value) -> CmdResult {
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd
.spawn()
- .map_err(|e| internal(format!("spawn mlx_video: {e}")))?;
+ .map_err(|e| internal(format!("spawn mlx_video: {}", os_error::english(&e))))?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let pid = child.id();
@@ -785,7 +786,7 @@ pub(crate) fn run_streamed(slot: &crate::install_state::InstallSlot, cmd: &mut C
use std::os::windows::process::CommandExt;
cmd.creation_flags(crate::process_util::no_window());
}
- let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?;
+ let mut child = cmd.spawn().map_err(|e| format!("spawn: {}", os_error::english(&e)))?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let so = slot.clone();
diff --git a/src-tauri/src/commands/waitlist.rs b/src-tauri/src/commands/waitlist.rs
index e84b97c8..e3a93bcb 100644
--- a/src-tauri/src/commands/waitlist.rs
+++ b/src-tauri/src/commands/waitlist.rs
@@ -17,6 +17,7 @@
//! therefore returns 409, which we treat as success so "You're already on
//! the list" stays clean.
+use crate::os_error;
/// LU's own Supabase project (EU region). The project URL is public — it is
/// the `NEXT_PUBLIC_SUPABASE_URL` and ships in every Supabase client.
const SUPABASE_URL: &str = "https://gewbdlmziumhseftxgrr.supabase.co";
@@ -93,7 +94,7 @@ pub async fn waitlist_submit(
.body(payload.to_string())
.send()
.await
- .map_err(|e| format!("waitlist_submit: {}", e))?;
+ .map_err(|e| format!("waitlist_submit: {}", os_error::english(&e)))?;
let status = resp.status();
// 2xx = inserted (or duplicate ignored). 409 = duplicate without the
diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rs
index 99293cd1..d6f55f0e 100644
--- a/src-tauri/src/commands/whisper.rs
+++ b/src-tauri/src/commands/whisper.rs
@@ -1,3 +1,4 @@
+use crate::os_error;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, Command, Stdio};
use std::sync::{mpsc, Arc, Mutex};
@@ -75,7 +76,7 @@ impl WhisperServer {
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn()
- .map_err(|e| format!("Failed to start whisper server: {}", e))?;
+ .map_err(|e| format!("Failed to start whisper server: {}", os_error::english(&e)))?;
let stdin = child.stdin.take().ok_or("Failed to get stdin")?;
let stdout = child.stdout.take().ok_or("Failed to get stdout")?;
@@ -320,7 +321,7 @@ fn transcribe_blocking(
.unwrap_or(0), ext));
std::fs::write(&tmp_file, &audio_bytes)
- .map_err(|e| format!("Write temp file: {}", e))?;
+ .map_err(|e| format!("Write temp file: {}", os_error::english(&e)))?;
let audio_path = tmp_file.to_string_lossy().replace('\\', "/");
println!("[Whisper] Transcribing: {} ({:.1} KB)", audio_path, audio_bytes.len() as f64 / 1024.0);
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 91b5c4ed..2bd2cbed 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -3,6 +3,7 @@
mod commands;
mod install_state;
+mod os_error;
mod os_paths;
mod process_util;
mod python;
diff --git a/src-tauri/src/os_error.rs b/src-tauri/src/os_error.rs
new file mode 100644
index 00000000..7cacf6f9
--- /dev/null
+++ b/src-tauri/src/os_error.rs
@@ -0,0 +1,379 @@
+//! English text for errors the operating system worded itself.
+//!
+//! David, 2026-08-22, from the box: the app showed a proxy failure whose text
+//! was half German. No German word exists anywhere in this repo. Windows wrote
+//! it: `std::io::Error`'s Display calls FormatMessageW, which answers in the
+//! system language, so a German Windows hands us "Es konnte keine Verbindung
+//! hergestellt werden ... (os error 10061)" and we pass it straight through to
+//! a user who set the app to English.
+//!
+//! The rule is that our messages are English. The cure cannot be a translation
+//! table: we would be translating FROM an unknown language, and the set of
+//! codes is open. So we do the opposite and never show the OS wording at all.
+//! `ErrorKind` and the numeric code are language neutral, and between them they
+//! carry everything the message was worth: what went wrong, and the number to
+//! search for.
+//!
+//! This does NOT touch the output of foreign processes (pip, git, ComfyUI).
+//! Their stderr is theirs, we only promise that OUR frame around it is English.
+
+use std::io::ErrorKind;
+
+/// The English phrase for a language neutral `ErrorKind`.
+///
+/// `ErrorKind` is `#[non_exhaustive]` and most Windows codes land in the
+/// unstable `Uncategorized` arm, so this returns None more often than it
+/// looks. The numeric code carries those.
+fn kind_phrase(kind: ErrorKind) -> Option<&'static str> {
+ Some(match kind {
+ ErrorKind::NotFound => "not found",
+ ErrorKind::PermissionDenied => "permission denied",
+ ErrorKind::ConnectionRefused => "connection refused",
+ ErrorKind::ConnectionReset => "connection reset by peer",
+ ErrorKind::ConnectionAborted => "connection aborted",
+ ErrorKind::NotConnected => "not connected",
+ ErrorKind::AddrInUse => "address already in use",
+ ErrorKind::AddrNotAvailable => "address not available",
+ ErrorKind::BrokenPipe => "broken pipe",
+ ErrorKind::AlreadyExists => "already exists",
+ ErrorKind::WouldBlock => "operation would block",
+ ErrorKind::InvalidInput => "invalid input",
+ ErrorKind::InvalidData => "invalid data",
+ ErrorKind::TimedOut => "timed out",
+ ErrorKind::WriteZero => "write returned zero bytes",
+ ErrorKind::Interrupted => "interrupted",
+ ErrorKind::Unsupported => "unsupported operation",
+ ErrorKind::UnexpectedEof => "unexpected end of file",
+ ErrorKind::OutOfMemory => "out of memory",
+ _ => return None,
+ })
+}
+
+/// The handful of codes that reach a user often enough to be worth naming, and
+/// that Rust does not categorise on the platform where they occur.
+///
+/// Deliberately short. A code we cannot name is still printed as a number, and
+/// a number is what anyone searches for anyway. Guessing at a code we have not
+/// seen would be inventing an English error to replace a true German one.
+fn code_phrase(code: i32) -> Option<&'static str> {
+ Some(match code {
+ // Windows
+ 32 => "the file is in use by another process",
+ 33 => "the file is locked by another process",
+ 145 => "the directory is not empty",
+ 1224 => "the file is open by another process",
+ 10013 => "the port is blocked, by permissions or by a firewall",
+ 10048 => "the port is already in use",
+ 10049 => "the address is not available on this machine",
+ 10060 => "the connection timed out",
+ 10061 => "connection refused, nothing is listening on that port",
+ _ => return None,
+ })
+}
+
+/// One OS error, in English.
+///
+/// Order matters: the specific code wins over the broad kind, because
+/// "the port is already in use" is worth more than "address already in use",
+/// and a categorised kind wins over nothing. The number always rides along, so
+/// the answer is never less searchable than what Windows wrote.
+pub fn io_english(e: &std::io::Error) -> String {
+ match e.raw_os_error() {
+ Some(code) => {
+ let phrase = code_phrase(code)
+ .or_else(|| kind_phrase(e.kind()))
+ .unwrap_or("the operating system refused the operation");
+ format!("{} (os error {})", phrase, code)
+ }
+ // No OS code means Rust built this error itself, so the text is ours
+ // and it is already English.
+ None => e.to_string(),
+ }
+}
+
+/// Any error, with every OS worded part of it replaced by English.
+///
+/// The reason this is not simply `io_english` is reqwest and hyper. Their
+/// Display walks their own source chain, so the string we would have shown is
+/// "error sending request for url (...): error trying to connect: tcp connect
+/// error: <whatever Windows said>". The English scaffolding is worth keeping,
+/// and only the leaf is the OS talking, so we render the chain as usual and
+/// then swap out exactly the leaf.
+pub fn english_dyn(err: &(dyn std::error::Error + 'static)) -> String {
+ // The error IS an OS error: nothing to keep, answer outright.
+ if let Some(io) = err.downcast_ref::<std::io::Error>() {
+ return io_english(io);
+ }
+ let mut text = err.to_string();
+ let mut cur = err.source();
+ while let Some(e) = cur {
+ if let Some(io) = e.downcast_ref::<std::io::Error>() {
+ let os_worded = io.to_string();
+ let ours = io_english(io);
+ if os_worded != ours {
+ text = text.replace(&os_worded, &ours);
+ }
+ }
+ cur = e.source();
+ }
+ text
+}
+
+/// `english_dyn` for a concrete error type, so call sites read as
+/// `map_err(|e| format!("...: {}", os_error::english(&e)))`.
+pub fn english<E>(err: &E) -> String
+where
+ E: std::error::Error + 'static,
+{
+ english_dyn(err)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Error, ErrorKind};
+
+ /// An error that wraps another, the shape reqwest and hyper have.
+ #[derive(Debug)]
+ struct Wrapper {
+ head: String,
+ source: Error,
+ }
+ impl std::fmt::Display for Wrapper {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // Exactly what reqwest does: render the head, then the source.
+ write!(f, "{}: {}", self.head, self.source)
+ }
+ }
+ impl std::error::Error for Wrapper {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.source)
+ }
+ }
+
+ /// The connection-refused code of the machine the test runs on, so the
+ /// suite proves the same journey on every platform.
+ #[cfg(windows)]
+ const REFUSED: i32 = 10061;
+ #[cfg(target_os = "macos")]
+ const REFUSED: i32 = 61;
+ #[cfg(all(unix, not(target_os = "macos")))]
+ const REFUSED: i32 = 111;
+
+ #[test]
+ fn an_os_error_is_answered_in_our_words_not_the_systems() {
+ let e = Error::from_raw_os_error(REFUSED);
+ let ours = io_english(&e);
+ // The point of the whole module: the answer is fixed by us, not read
+ // off the operating system. On a German Windows e.to_string() is
+ // German; this assertion is the same either way.
+ assert!(ours.starts_with("connection refused"), "got: {}", ours);
+ assert!(ours.contains(&format!("os error {}", REFUSED)), "got: {}", ours);
+ }
+
+ #[test]
+ fn the_number_survives_even_when_the_code_has_no_name() {
+ // A code no table knows. It must still be searchable.
+ let e = Error::from_raw_os_error(31337);
+ let ours = io_english(&e);
+ assert!(ours.contains("os error 31337"), "got: {}", ours);
+ assert!(!ours.is_empty());
+ }
+
+ #[test]
+ fn an_error_rust_built_itself_is_left_alone() {
+ // No raw OS code means no FormatMessageW was involved, so the text is
+ // ours already and rewriting it would only lose detail.
+ let e = Error::new(ErrorKind::InvalidData, "the manifest has no version field");
+ assert_eq!(io_english(&e), "the manifest has no version field");
+ }
+
+ #[test]
+ fn a_wrapped_os_error_loses_the_system_wording_and_keeps_the_scaffolding() {
+ let inner = Error::from_raw_os_error(REFUSED);
+ let os_worded = inner.to_string();
+ let w = Wrapper { head: "error trying to connect".into(), source: inner };
+ let ours = english(&w);
+ assert!(ours.starts_with("error trying to connect: "), "got: {}", ours);
+ assert!(ours.contains("connection refused"), "got: {}", ours);
+ // The leaf the operating system wrote is gone from the message.
+ assert!(!ours.contains(&os_worded), "the OS wording survived: {}", ours);
+ }
+
+ #[test]
+ fn two_layers_deep_is_still_reached() {
+ // reqwest wraps hyper wraps io, which is the real depth on a refused
+ // localhost backend.
+ let inner = Error::from_raw_os_error(REFUSED);
+ let os_worded = inner.to_string();
+ let mid = Wrapper { head: "tcp connect error".into(), source: inner };
+ // A third layer that renders the second, the way reqwest renders hyper.
+ #[derive(Debug)]
+ struct Outer(Wrapper);
+ impl std::fmt::Display for Outer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "error sending request: {}", self.0)
+ }
+ }
+ impl std::error::Error for Outer {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.0)
+ }
+ }
+ let ours = english(&Outer(mid));
+ assert!(ours.starts_with("error sending request: tcp connect error: "), "got: {}", ours);
+ assert!(!ours.contains(&os_worded), "the OS wording survived: {}", ours);
+ }
+
+ #[test]
+ fn a_chain_without_an_os_error_is_returned_untouched() {
+ let inner = Error::new(ErrorKind::InvalidData, "bad json");
+ let w = Wrapper { head: "parse failed".into(), source: inner };
+ assert_eq!(english(&w), "parse failed: bad json");
+ }
+
+ #[test]
+ fn every_named_code_reads_as_a_sentence_and_none_is_empty() {
+ // A guard on the tables: an entry added with an empty or capitalised
+ // string would read wrong inside "Failed to X: <phrase>".
+ for code in [32, 33, 145, 1224, 10013, 10048, 10049, 10060, 10061] {
+ let p = code_phrase(code).expect("table entry vanished");
+ assert!(!p.is_empty());
+ assert!(p.chars().next().unwrap().is_lowercase(), "code {} is capitalised", code);
+ }
+ for kind in [ErrorKind::NotFound, ErrorKind::PermissionDenied, ErrorKind::TimedOut] {
+ let p = kind_phrase(kind).expect("kind entry vanished");
+ assert!(p.chars().next().unwrap().is_lowercase());
+ }
+ }
+}
+/// The drift guard: no new code may hand the operating system's own wording to
+/// the frontend.
+///
+/// The fix was 86 call sites. Without this the 87th arrives next week and
+/// nobody notices, because on an English machine the bug is invisible: the OS
+/// wording and our wording read the same, and only a German or French Windows
+/// tells them apart. So the check has to be static, and it has to run here.
+///
+/// It looks for one shape: a line that both performs an operation the OS can
+/// fail (a filesystem call, a process spawn, an HTTP send) and renders the
+/// error straight into a string, without going through this module.
+#[cfg(test)]
+mod drift_guard {
+ use std::path::{Path, PathBuf};
+
+ /// Calls whose error is written by the operating system.
+ const OS_CALLS: &[&str] = &[
+ "fs::read", "fs::write", "fs::create_dir", "fs::remove", "fs::copy",
+ "fs::rename", "fs::metadata", "fs::read_dir", "fs::read_to_string",
+ "File::create", "File::open", ".spawn()", ".output()",
+ // Deliberately NOT ".status()": Command::status and HTTP resp.status()
+ // read the same, and the HTTP one is everywhere. Spawn and output cover
+ // the process side of the same journey.
+ // The network calls, because the bug that started all of this was one
+ // of these: reqwest renders its own source chain, and the leaf of that
+ // chain on a refused localhost port is the operating system talking.
+ ".send()", ".bytes()", ".chunk()",
+ ];
+
+ /// How many lines a single call may be spread over.
+ ///
+ /// The reqwest shape is the reason this is not 1. A request reads
+ /// `.send()` / `.await` / `.map_err(...)` on three separate lines, which is
+ /// exactly the call that showed a German message on the box, and a
+ /// line-at-a-time check would have walked straight past it.
+ const WINDOW: usize = 4;
+
+ /// Rendering the error value itself into a message.
+ fn renders_the_error(line: &str) -> bool {
+ line.contains("map_err(|e|")
+ && (line.contains("{e}") || line.contains(", e)") || line.contains("e.to_string()"))
+ }
+
+ /// A line with its trailing comment removed, so prose about the pattern is
+ /// never mistaken for the pattern.
+ fn strip_comment(line: &str) -> &str {
+ match line.find("//") {
+ Some(at) => &line[..at],
+ None => line,
+ }
+ }
+
+ fn is_suspect(text: &str) -> bool {
+ let code = strip_comment(text);
+ if code.contains("os_error::") {
+ return false;
+ }
+ OS_CALLS.iter().any(|c| code.contains(c)) && renders_the_error(code)
+ }
+
+ fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
+ for entry in std::fs::read_dir(dir).expect("src is readable").flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ rust_files(&path, out);
+ } else if path.extension().is_some_and(|e| e == "rs") {
+ out.push(path);
+ }
+ }
+ }
+
+ #[test]
+ fn no_call_site_hands_the_system_wording_to_the_frontend() {
+ let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let mut files = Vec::new();
+ rust_files(&src, &mut files);
+ assert!(files.len() > 10, "the file walk found almost nothing");
+
+ let mut found = Vec::new();
+ for file in &files {
+ // This module's own tests talk about the shape on purpose.
+ if file.ends_with("os_error.rs") {
+ continue;
+ }
+ let text = std::fs::read_to_string(file).expect("readable");
+ let lines: Vec<&str> = text.lines().collect();
+ for i in 0..lines.len() {
+ let end = (i + WINDOW).min(lines.len());
+ // The call and its map_err may sit on different lines, so the
+ // window is joined and judged as one statement. Anchored on the
+ // OS call, so each offender is reported once, at the line the
+ // fix belongs on.
+ if !OS_CALLS.iter().any(|c| strip_comment(lines[i]).contains(c)) {
+ continue;
+ }
+ let joined: String = lines[i..end].iter().map(|l| strip_comment(l)).collect::<Vec<_>>().join(" ");
+ if is_suspect(&joined) {
+ found.push(format!("{}:{}: {}", file.display(), i + 1, lines[i].trim()));
+ }
+ }
+ }
+ assert!(
+ found.is_empty(),
+ "these render the operating system's own wording into a message the user reads.\n\
+ Windows answers FormatMessageW in the system language, so on a German machine this\n\
+ is a German error in an English app. Wrap the value in os_error::english(&e).\n\n{}",
+ found.join("\n")
+ );
+ }
+
+ #[test]
+ fn the_guard_would_actually_catch_one() {
+ // A guard that matches nothing passes forever. These are the exact
+ // shapes that were fixed, and the shapes that must keep failing.
+ assert!(is_suspect(r#"fs::read(&p).map_err(|e| format!("Read error: {}", e))?;"#));
+ assert!(is_suspect(r#"cmd.spawn().map_err(|e| format!("start failed: {e}"))?;"#));
+ assert!(is_suspect(r#"std::fs::write(&p, b).map_err(|e| e.to_string())?;"#));
+ // And the shapes that must not.
+ assert!(!is_suspect(
+ r#"fs::read(&p).map_err(|e| format!("Read error: {}", os_error::english(&e)))?;"#
+ ));
+ assert!(!is_suspect(r#"// fs::read(&p).map_err(|e| format!("x: {e}"))"#));
+ // The multi-line reqwest shape, joined the way the scan joins it.
+ assert!(is_suspect(r#".send() .await .map_err(|e| format!("proxy: {}", e))?"#));
+ assert!(!is_suspect(
+ r#".send() .await .map_err(|e| format!("proxy: {}", os_error::english(&e)))?"#
+ ));
+ assert!(!is_suspect(r#"let n = parse(s).map_err(|e| format!("bad number: {e}"))?;"#));
+ }
+}