Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: handle errors instead of panicking or swallowing them
Akarshand4ecd0692bff
diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs b/src-tauri/plugins/tauri-plugin-hardware/src/commands.rsindex a8f4b4213..c263cb0a7 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs@@ -52,7 +52,7 @@ fn compute_system_info() -> SystemInfo {pub fn get_system_info() -> SystemInfo {// Fast path: use cache if present{- let guard = SYSTEM_INFO.read().expect("RwLock poisoned");+ let guard = SYSTEM_INFO.read().unwrap_or_else(|e| e.into_inner());if let Some(ref info) = *guard {return info.clone();}@@ -60,7 +60,7 @@ pub fn get_system_info() -> SystemInfo {// Cache miss or invalidated: compute and storelet info = compute_system_info();{- let mut guard = SYSTEM_INFO.write().expect("RwLock poisoned");+ let mut guard = SYSTEM_INFO.write().unwrap_or_else(|e| e.into_inner());*guard = Some(info.clone());}info@@ -73,7 +73,7 @@ pub fn get_system_info() -> SystemInfo {pub fn refresh_system_info() {#[cfg(target_os = "linux")]nvidia::invalidate_nvml();- let mut guard = SYSTEM_INFO.write().expect("RwLock poisoned");+ let mut guard = SYSTEM_INFO.write().unwrap_or_else(|e| e.into_inner());*guard = None;}diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rsindex 63324d2ed..a084dfa7b 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs@@ -26,14 +26,14 @@ where{// Try read first for the common case (already initialized){- let guard = NVML.read().expect("RwLock poisoned");+ let guard = NVML.read().unwrap_or_else(|e| e.into_inner());if guard.is_some() {return f(guard.as_ref());}}// Not initialized or was invalidated: try to init{- let mut guard = NVML.write().expect("RwLock poisoned");+ let mut guard = NVML.write().unwrap_or_else(|e| e.into_inner());if guard.is_none() {let result = Nvml::init().or_else(|e| {if cfg!(target_os = "linux") {@@ -62,7 +62,7 @@ where/// resume on Linux when the GPU driver state has been reset.#[cfg(target_os = "linux")]pub fn invalidate_nvml() {- let mut guard = NVML.write().expect("RwLock poisoned");+ let mut guard = NVML.write().unwrap_or_else(|e| e.into_inner());*guard = None;log::debug!("NVML invalidated (e.g. after resume); will re-init on next use");}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rsindex 392c9d803..3b09c6a43 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs@@ -254,7 +254,10 @@ pub async fn start_router(// Early-exit check.if let Some(status) = child.try_wait()? {- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("Router stderr task join failed: {e}");+ String::new()+ });log::error!("llama-server router exited early with status {:?}", status);return Err(LlamacppError::from_stderr(&stderr_output).into());}@@ -271,14 +274,20 @@ pub async fn start_router(}_ = tokio::time::sleep(Duration::from_millis(50)) => {if let Some(status) = child.try_wait()? {- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("Router stderr task join failed: {e}");+ String::new()+ });log::error!("llama-server router exited before readiness: {:?}", status);return Err(LlamacppError::from_stderr(&stderr_output).into());}if start_time.elapsed() > timeout_duration {log::error!("Timeout waiting for router to be ready");let _ = child.kill().await;- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("Router stderr task join failed: {e}");+ String::new()+ });return Err(LlamacppError::new(ErrorCode::ModelLoadTimedOut,"Router took too long to start and timed out.".into(),diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rsindex 1bd63b05b..9f99b5dde 100644--- a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs@@ -201,7 +201,10 @@ pub async fn load_mlx_model_impl(// Check if process exited earlyif let Some(status) = child.try_wait()? {if !status.success() {- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("MLX stderr task join failed: {e}");+ String::new()+ });log::error!("MLX server failed early with code {:?}", status);log::error!("{}", stderr_output);return Err(MlxError::from_stderr(&stderr_output).into());@@ -221,7 +224,10 @@ pub async fn load_mlx_model_impl(}_ = tokio::time::sleep(Duration::from_millis(50)) => {if let Some(status) = child.try_wait()? {- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("MLX stderr task join failed: {e}");+ String::new()+ });if !status.success() {log::error!("MLX server exited with error code {:?}", status);return Err(MlxError::from_stderr(&stderr_output).into());@@ -234,7 +240,10 @@ pub async fn load_mlx_model_impl(if start_time.elapsed() > timeout_duration {log::error!("Timeout waiting for MLX server to be ready");let _ = child.kill().await;- let stderr_output = stderr_task.await.unwrap_or_default();+ let stderr_output = stderr_task.await.unwrap_or_else(|e| {+ log::warn!("MLX stderr task join failed: {e}");+ String::new()+ });return Err(MlxError::new(ErrorCode::ModelLoadTimedOut,"The MLX model took too long to load and timed out.".into(),diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 352cdd285..2c63d7157 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -340,9 +340,9 @@ pub fn setup_mcp<R: Runtime>(app: &App<R>) {if let Err(e) = run_mcp_commands(&app_handle, servers).await {log::error!("Failed to run mcp commands: {e}");}- app_handle- .emit("mcp-update", "MCP servers updated")- .unwrap();+ if let Err(e) = app_handle.emit("mcp-update", "MCP servers updated") {+ log::warn!("Failed to emit mcp-update event: {e}");+ }});}diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 6d8e6b52f..a262cbf1e 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -209,30 +209,29 @@ pub fn relaunch<R: Runtime>(app: AppHandle<R>) {}#[tauri::command]-pub fn open_app_directory<R: Runtime>(app: AppHandle<R>) {- let app_path = app.path().app_data_dir().unwrap();- if cfg!(target_os = "windows") {- std::process::Command::new("explorer")- .arg(app_path)- .status()- .expect("Failed to open app directory");+pub fn open_app_directory<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {+ let app_path = app+ .path()+ .app_data_dir()+ .map_err(|e| format!("Failed to resolve app data dir: {e}"))?;+ let program = if cfg!(target_os = "windows") {+ "explorer"} else if cfg!(target_os = "macos") {- std::process::Command::new("open")- .arg(app_path)- .status()- .expect("Failed to open app directory");+ "open"} else {- std::process::Command::new("xdg-open")- .arg(app_path)- .status()- .expect("Failed to open app directory");- }+ "xdg-open"+ };+ std::process::Command::new(program)+ .arg(app_path)+ .status()+ .map_err(|e| format!("Failed to open app directory: {e}"))?;+ Ok(())}#[tauri::command]-pub fn open_file_explorer(path: String) {+pub fn open_file_explorer(path: String) -> Result<(), String> {let path = PathBuf::from(path);- if cfg!(target_os = "windows") {+ let (program, arg): (&str, std::ffi::OsString) = if cfg!(target_os = "windows") {// Normalize extended-length paths (\\?\...) for explorer compatibility.let mut path_str = path.to_string_lossy().into_owned();if let Some(stripped) = path_str.strip_prefix(r"\\?\UNC\") {@@ -240,21 +239,17 @@ pub fn open_file_explorer(path: String) {} else if let Some(stripped) = path_str.strip_prefix(r"\\?\") {path_str = stripped.to_string();}- std::process::Command::new("explorer")- .arg(path_str)- .status()- .expect("Failed to open file explorer");+ ("explorer", path_str.into())} else if cfg!(target_os = "macos") {- std::process::Command::new("open")- .arg(path)- .status()- .expect("Failed to open file explorer");+ ("open", path.into())} else {- std::process::Command::new("xdg-open")- .arg(path)- .status()- .expect("Failed to open file explorer");- }+ ("xdg-open", path.into())+ };+ std::process::Command::new(program)+ .arg(arg)+ .status()+ .map_err(|e| format!("Failed to open file explorer: {e}"))?;+ Ok(())}#[tauri::command]diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex 6764e446d..69be88672 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -338,7 +338,13 @@ export function createCustomFetch(return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {let rawBody: Record<string, unknown> | null = nullif (init?.method === 'POST' || !init?.method) {- rawBody = init?.body ? JSON.parse(init.body as string) : {}+ try {+ rawBody = init?.body ? JSON.parse(init.body as string) : {}+ } catch (e) {+ throw new Error(+ `Failed to parse request body as JSON: ${e instanceof Error ? e.message : String(e)}`+ )+ }init = { ...init, body: JSON.stringify(buildBody(rawBody!, true)) }}@@ -776,7 +782,16 @@ export class ModelFactory {init?: RequestInit): Promise<Response> => {if (init?.method === 'POST' || !init?.method) {- const body = init?.body ? JSON.parse(init.body as string) : {}+ let body: Record<string, unknown> = {}+ if (init?.body) {+ try {+ body = JSON.parse(init.body as string)+ } catch (e) {+ throw new Error(+ `Failed to parse MLX request body as JSON: ${e instanceof Error ? e.message : String(e)}`+ )+ }+ }const mergedBody = { ...body, ...parameters }init = { ...init, body: JSON.stringify(mergedBody) }}diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsxindex bf0594814..46a19953a 100644--- a/web-app/src/routes/settings/mcp-servers.tsx+++ b/web-app/src/routes/settings/mcp-servers.tsx@@ -407,10 +407,18 @@ function MCPServersDesktop() {let unlisten: (() => void) | undefinedconst setupListener = async () => {unlisten = await listen(SystemEvent.MCP_UPDATE, () => {- serviceHub.mcp().getConnectedServers().then(setConnectedServers)+ serviceHub+ .mcp()+ .getConnectedServers()+ .then(setConnectedServers)+ .catch((error) =>+ console.error('Failed to refresh MCP servers:', error)+ )})}- setupListener()+ setupListener().catch((error) =>+ console.error('Failed to set up MCP update listener:', error)+ )return () => {unlisten?.()diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 75b5b146b..2ae607980 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -624,6 +624,9 @@ function ThreadDetail() {currentThread.current = threadId}})+ .catch((error) =>+ console.error('Failed to fetch messages for thread:', threadId, error)+ )// eslint-disable-next-line react-hooks/exhaustive-deps}, [threadId, serviceHub])