Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
chore(rust): fix all clippy warnings across main crate and plugins
Akarshan6a6e0611e57a
diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/cpu.rs b/src-tauri/plugins/tauri-plugin-hardware/src/cpu.rsindex 926ca04a2..ad09ba82a 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/cpu.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/cpu.rs@@ -2,6 +2,12 @@ use sysinfo::System;use crate::types::CpuStaticInfo;+impl Default for CpuStaticInfo {+ fn default() -> Self {+ Self::new()+ }+}+impl CpuStaticInfo {pub fn new() -> Self {let mut system = System::new();diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/tests.rs b/src-tauri/plugins/tauri-plugin-hardware/src/tests.rsindex f27554579..64dd1e302 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/tests.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/tests.rs@@ -1,6 +1,5 @@use crate::commands::*;use crate::types::CpuStaticInfo;-use tauri::test::mock_app;#[test]fn test_system_info() {@@ -57,7 +56,6 @@ mod cpu_tests {fn test_cpu_name_not_empty() {let cpu_info = CpuStaticInfo::new();assert!(!cpu_info.name.is_empty());- assert!(cpu_info.name.len() > 0);}#[test]diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/amd.rs b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/amd.rsindex 7521fd2b0..fb7d26165 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/amd.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/amd.rs@@ -58,7 +58,7 @@ impl GpuInfo {used_memory: read_mem(&device_path.join("mem_info_vram_used")),});}- Err(format!("GPU not found").into())+ Err("GPU not found".to_string().into())};match closure() {diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rsindex 4779b0386..63324d2ed 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs@@ -54,7 +54,7 @@ where}}}- return f(guard.as_ref());+ f(guard.as_ref())}}@@ -166,8 +166,8 @@ fn create_gpu_info(nvml: &Nvml, index: u32, driver_version: &str) -> Result<GpuIlet compute_capability = device.cuda_compute_capability()?;let uuid = device.uuid()?;- let clean_uuid = if uuid.starts_with("GPU-") {- uuid[4..].to_string()+ let clean_uuid = if let Some(stripped) = uuid.strip_prefix("GPU-") {+ stripped.to_string()} else {uuid};diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/tests.rs b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/tests.rsindex d683e4d91..4f1681462 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/tests.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/tests.rs@@ -26,7 +26,7 @@ fn test_get_vulkan_gpus_on_desktop() {let gpus = vulkan::get_vulkan_gpus();// Test that function returns without panicking on desktop platforms- assert!(gpus.len() >= 0);+ let _ = gpus.len();// If GPUs are found, verify they have valid propertiesfor (i, gpu) in gpus.iter().enumerate() {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rsindex 24eefa82d..811f3fe07 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs@@ -144,7 +144,7 @@ pub async fn get_local_installed_backends(/// Helper function to check if a backend is properly installed/// Checks for the existence of llama-server executable in the expected locations-fn is_backend_installed(backend_dir: &PathBuf) -> bool {+fn is_backend_installed(backend_dir: &Path) -> bool {if !backend_dir.exists() || !backend_dir.is_dir() {return false;}@@ -904,8 +904,8 @@ fn find_gpu_libs(bin_dir: &Path, keyword: &str) -> Vec<PathBuf> {}fn verify_backend_dependencies(- bin_dir: &PathBuf,- exe_path: &PathBuf,+ bin_dir: &Path,+ exe_path: &Path,backend: &str,) -> Result<BackendVerificationResult, crate::error::LlamacppError> {if !bin_dir.exists() {@@ -1545,7 +1545,7 @@ mod tests {let backend_a = v1_path.join("backend-a");let backend_empty = v1_path.join("backend-empty");- fs::create_dir_all(&backend_a.join("build").join("bin")).unwrap();+ fs::create_dir_all(backend_a.join("build").join("bin")).unwrap();fs::create_dir_all(&backend_empty).unwrap();// Create mock executablediff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex 50c181346..5eb09b9d4 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -335,7 +335,7 @@ pub async fn load_llama_model<R: Runtime>() -> ServerResult<SessionInfo> {let (port, api_key, pid) = router_endpoint(&app_handle).await- .map_err(|e| ServerError::InvalidArgument(e))?;+ .map_err(ServerError::InvalidArgument)?;post_load(port, &api_key, &model_id).await?;Ok(SessionInfo {pid: pid as i32,@@ -353,7 +353,7 @@ pub async fn unload_llama_model<R: Runtime>() -> ServerResult<UnloadResult> {let (port, api_key, _pid) = router_endpoint(&app_handle).await- .map_err(|e| ServerError::InvalidArgument(e))?;+ .map_err(ServerError::InvalidArgument)?;match post_unload(port, &api_key, &model_id).await {Ok(()) => Ok(UnloadResult { success: true, error: None }),Err(e) => Ok(UnloadResult { success: false, error: Some(e) }),diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rsindex 466b6d2fa..8465933c3 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs@@ -166,9 +166,9 @@ fn parse_device_line(line: &str) -> ServerResult<Option<DeviceInfo>> {fn find_memory_pattern(text: &str) -> Option<(usize, &str)> {// Find the last parenthesis that contains the memory patternlet mut last_match = None;- let mut chars = text.char_indices().peekable();+ let chars = text.char_indices();- while let Some((start_idx, ch)) = chars.next() {+ for (start_idx, ch) in chars {if ch == '(' {// Find the closing parenthesislet remaining = &text[start_idx + 1..];@@ -203,7 +203,7 @@ fn is_memory_pattern(content: &str) -> bool {// Each part should start with a number and contain "MiB"part.split_whitespace().next()- .map_or(false, |first_word| first_word.parse::<i32>().is_ok())+ .is_some_and(|first_word| first_word.parse::<i32>().is_ok())&& part.contains("MiB")})}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rsindex 375913ba2..667dd36ef 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs@@ -1,5 +1,4 @@use serde::{Deserialize, Serialize};-use thiserror;#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rsindex 6ba37a2dd..1058e4ca9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs@@ -8,7 +8,7 @@ use tauri_plugin_hardware::{get_system_info, SystemInfo};/// Read GGUF metadata from a model file#[tauri::command]pub async fn read_gguf_metadata(path: String) -> Result<GgufMetadata, String> {- return read_gguf_metadata_internal(path).await;+ read_gguf_metadata_internal(path).await}#[tauri::command]@@ -139,11 +139,7 @@ pub async fn is_model_supported(log::info!("Total VRAM reported/calculated (in bytes): {}", &total_vram);- let usable_vram = if total_vram > RESERVE_BYTES {- total_vram - RESERVE_BYTES- } else {- 0- };+ let usable_vram = total_vram.saturating_sub(RESERVE_BYTES);let usable_total_memory = if total_system_memory > RESERVE_BYTES {(total_system_memory - RESERVE_BYTES) + usable_vramdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rsindex b728522c3..ffbb2e848 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs@@ -42,10 +42,10 @@ pub fn read_gguf_metadata<R: Read + Seek>(reader: R) -> io::Result<GgufMetadata>})}-fn read_metadata_entry<R: Read + Seek>(reader: &mut R, index: u64) -> io::Result<(String, String)>-where- R: ReadBytesExt,-{+fn read_metadata_entry<R: Read + Seek + ReadBytesExt>(+ reader: &mut R,+ index: u64,+) -> io::Result<(String, String)> {let key = read_gguf_string(reader).map_err(|e| {io::Error::new(io::ErrorKind::InvalidData,@@ -60,10 +60,7 @@ whereOk((key, value))}-fn read_gguf_string<R: Read>(reader: &mut R) -> io::Result<String>-where- R: ReadBytesExt,-{+fn read_gguf_string<R: Read + ReadBytesExt>(reader: &mut R) -> io::Result<String> {let len = reader.read_u64::<LittleEndian>()?;if len > (1024 * 1024) {return Err(io::Error::new(@@ -73,13 +70,13 @@ where}let mut buf = vec![0u8; len as usize];reader.read_exact(&mut buf)?;- Ok(String::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?)+ String::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))}-fn read_gguf_value<R: Read + Seek>(reader: &mut R, value_type: GgufValueType) -> io::Result<String>-where- R: ReadBytesExt,-{+fn read_gguf_value<R: Read + Seek + ReadBytesExt>(+ reader: &mut R,+ value_type: GgufValueType,+) -> io::Result<String> {match value_type {GgufValueType::Uint8 => Ok(reader.read_u8()?.to_string()),GgufValueType::Int8 => Ok(reader.read_i8()?.to_string()),@@ -122,14 +119,11 @@ where}}-fn skip_array_data<R: Read + Seek>(+fn skip_array_data<R: Read + Seek + ReadBytesExt>(reader: &mut R,elem_type: GgufValueType,len: u64,-) -> io::Result<()>-where- R: ReadBytesExt,-{+) -> io::Result<()> {match elem_type {GgufValueType::Uint8 | GgufValueType::Int8 | GgufValueType::Bool => {reader.seek(io::SeekFrom::Current(len as i64))?;diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rsindex c6cf9d360..392c9d803 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs@@ -89,6 +89,7 @@ pub fn router_args(////// On readiness-detection failure or spawn failure, the child is killed before/// returning the error.+#[allow(clippy::too_many_arguments)]pub async fn start_router(backend_exe: PathBuf,preset_path: PathBuf,diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rsindex 3b2a45fb7..1bd63b05b 100644--- a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs@@ -35,6 +35,7 @@ pub struct MlxConfig {/// Core model-loading logic, decoupled from Tauri AppHandle./// `binary_path` must point to the mlx-server executable./// `process_map_arc` is the shared session map from MlxState.+#[allow(clippy::too_many_arguments)]pub async fn load_mlx_model_impl(process_map_arc: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,binary_path: &Path,@@ -274,6 +275,7 @@ pub async fn load_mlx_model_impl(/// Load a model using the MLX server binary (Tauri command wrapper)#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn load_mlx_model<R: Runtime>(app_handle: tauri::AppHandle<R>,model_id: String,diff --git a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs b/src-tauri/plugins/tauri-plugin-rag/src/parser.rsindex 626cb707e..1dd2dc21e 100644--- a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs+++ b/src-tauri/plugins/tauri-plugin-rag/src/parser.rs@@ -6,8 +6,6 @@ use std::panic::{catch_unwind, AssertUnwindSafe};use calamine::{open_workbook_auto, DataType, Reader as _};use chardetng::EncodingDetector;use csv as csv_crate;-use html2text;-use infer;use quick_xml::events::Event;use quick_xml::Reader;use zip::read::ZipArchive;@@ -249,7 +247,7 @@ fn parse_spreadsheet(file_path: &str) -> Result<String, RagError> {out.push_str(&cells);out.push('\n');}- out.push_str("\n");+ out.push('\n');}}Ok(out)diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rsindex 9996a9083..edb38d951 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs@@ -43,13 +43,13 @@ pub async fn get_status(state: State<'_, VectorDBState>) -> Result<Status, Vectofor p in paths {println!("[VectorDB] Trying: {}", p);unsafe {- if let Ok(_) = conn.load_extension(&p, Some("sqlite3_vec_init")) {- if conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok() {- let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);- println!("[VectorDB] ✓ sqlite-vec loaded from: {}", p);- found = true;- break;- }+ if conn.load_extension(&p, Some("sqlite3_vec_init")).is_ok()+ && conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok()+ {+ let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);+ println!("[VectorDB] ✓ sqlite-vec loaded from: {}", p);+ found = true;+ break;}}}@@ -128,6 +128,7 @@ pub async fn delete_file<R: tauri::Runtime>(}#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn search_collection<R: tauri::Runtime>(_app: tauri::AppHandle<R>,state: State<'_, VectorDBState>,diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rsindex a81275f82..f00633073 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs@@ -3,7 +3,7 @@ use crate::utils::{cosine_similarity, from_le_bytes_vec, to_le_bytes_vec};use rusqlite::{params, Connection, OptionalExtension};use serde::{Deserialize, Serialize};use std::fs;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use uuid::Uuid;#[derive(Debug, Serialize, Deserialize, Clone)]@@ -48,8 +48,8 @@ pub struct MinimalChunkInput {// Connection & Path Management// ============================================================================-pub fn collection_path(base: &PathBuf, name: &str) -> PathBuf {- let mut p = base.clone();+pub fn collection_path(base: &Path, name: &str) -> PathBuf {+ let mut p = base.to_path_buf();let clean = name.replace(['/', '\\'], "_");let filename = format!("{}.db", clean);p.push(&filename);@@ -82,11 +82,11 @@ pub fn try_load_sqlite_vec(conn: &Connection) -> bool {let paths = possible_sqlite_vec_paths();for p in paths {unsafe {- if let Ok(_) = conn.load_extension(&p, Some("sqlite3_vec_init")) {- if conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok() {- let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);- return true;- }+ if conn.load_extension(&p, Some("sqlite3_vec_init")).is_ok()+ && conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok()+ {+ let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);+ return true;}}}diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/state.rsindex 8813625e2..8243883e0 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/state.rs@@ -4,6 +4,12 @@ pub struct VectorDBState {pub base_dir: PathBuf,}+impl Default for VectorDBState {+ fn default() -> Self {+ Self::new()+ }+}+impl VectorDBState {pub fn new() -> Self {// Default vector db path: /Jan/data/dbdiff --git a/src-tauri/plugins/yarn.lock b/src-tauri/plugins/yarn.lockindex 8a524ef9f..ec6cad55b 100644--- a/src-tauri/plugins/yarn.lock+++ b/src-tauri/plugins/yarn.lock@@ -28,18 +28,6 @@ __metadata:languageName: nodelinkType: hard-"@janhq/tauri-plugin-foundation-models-api@workspace:tauri-plugin-foundation-models":- version: 0.0.0-use.local- resolution: "@janhq/tauri-plugin-foundation-models-api@workspace:tauri-plugin-foundation-models"- dependencies:- "@rollup/plugin-typescript": "npm:^12.0.0"- "@tauri-apps/api": "npm:>=2.0.0-beta.6"- rollup: "npm:^4.9.6"- tslib: "npm:^2.6.2"- typescript: "npm:^5.3.3"- languageName: unknown- linkType: soft-"@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware"diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rsindex 4a689a492..df46ce161 100644--- a/src-tauri/src/bin/jan-cli.rs+++ b/src-tauri/src/bin/jan-cli.rs@@ -760,11 +760,13 @@ fn spawn_detached(model_id: &str, args: &ServeArgs) {cmd.pre_exec(|| {nix::unistd::setsid().map(|_| ())- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))+ .map_err(|e| std::io::Error::other(e.to_string()))});}}+ // child is intentionally detached via setsid; reaping is the OS's job+ #[allow(clippy::zombie_processes)]let child = cmd.spawn().unwrap_or_else(|e| {eprintln!("Failed to spawn detached process: {e}");std::process::exit(1);@@ -973,6 +975,7 @@ struct RouterServeInfo {api_key: String,}+#[allow(clippy::too_many_arguments)]async fn ensure_router_and_load(llama_state: &std::sync::Arc<LlamacppState>,bin_path: &str,@@ -1284,6 +1287,7 @@ fn configure_openclaw(v1_url: &str, api_key: &str, model_id: &str) {/// Start the model server and return `(pid, actual_port)`./// Resolves the engine automatically (LlamaCPP or MLX).+#[allow(clippy::too_many_arguments)]async fn start_model_server(model_id: &str,bin: Option<String>,diff --git a/src-tauri/src/core/app/models.rs b/src-tauri/src/core/app/models.rsindex bb425c01c..889407424 100644--- a/src-tauri/src/core/app/models.rs+++ b/src-tauri/src/core/app/models.rs@@ -6,11 +6,10 @@ pub struct AppConfiguration {// Add other fields as needed}-impl AppConfiguration {- pub fn default() -> Self {+impl Default for AppConfiguration {+ fn default() -> Self {Self {- data_folder: String::from("./data"), // Set a default value for the data_folder- // Add other fields with default values as needed+ data_folder: String::from("./data"),}}}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 1d9241c78..6080bede4 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -93,6 +93,7 @@ pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {// ── Server operations ──────────────────────────────────────────────────────/// Start the OpenAI-compatible proxy server. Returns the port it's listening on.+#[allow(clippy::too_many_arguments)]pub async fn cli_start_server(app_state: Arc<AppState>,llama_state: Arc<LlamacppState>,@@ -296,7 +297,7 @@ pub fn discover_llamacpp_binary() -> Option<PathBuf> {.filter_map(|e| e.ok()).filter(|e| e.path().is_dir()).collect();- version_entries.sort_by(|a, b| b.file_name().cmp(&a.file_name()));+ version_entries.sort_by_key(|b| std::cmp::Reverse(b.file_name()));for version_entry in version_entries {let version_dir = version_entry.path();@@ -305,7 +306,7 @@ pub fn discover_llamacpp_binary() -> Option<PathBuf> {.filter_map(|e| e.ok()).filter(|e| e.path().is_dir()).collect();- backend_entries.sort_by(|a, b| a.file_name().cmp(&b.file_name()));+ backend_entries.sort_by_key(|a| a.file_name());for backend_entry in backend_entries {let backend_dir = backend_entry.path();@@ -530,7 +531,7 @@ pub async fn download_hf_model("llamacpp/models/{}/{}",repo_id, file.filename);- let display_name = repo_id.split('/').last().unwrap_or(repo_id);+ let display_name = repo_id.split('/').next_back().unwrap_or(repo_id);let mut yml = format!("model_path: {rel_path}\nname: {display_name}\nsize_bytes: {}\nembedding: false\n",diff --git a/src-tauri/src/core/downloads/helpers.rs b/src-tauri/src/core/downloads/helpers.rsindex b3ed09956..7618b9fee 100644--- a/src-tauri/src/core/downloads/helpers.rs+++ b/src-tauri/src/core/downloads/helpers.rs@@ -109,8 +109,7 @@ async fn validate_downloaded_file(// Path structure: llamacpp/models/{modelId}/model.gguf or llamacpp/models/{modelId}/mmproj.gguflet model_id = item.model_id- .as_ref()- .map(|s| s.as_str())+ .as_deref().unwrap_or_else(|| {save_path.parent() // get parent directory (modelId folder)diff --git a/src-tauri/src/core/filesystem/helpers.rs b/src-tauri/src/core/filesystem/helpers.rsindex 5f5d457a3..af6f55cf2 100644--- a/src-tauri/src/core/filesystem/helpers.rs+++ b/src-tauri/src/core/filesystem/helpers.rs@@ -98,6 +98,14 @@ pub fn resolve_path_within_jan_data_folder(Ok((canonical_data, canonical_path))}+pub fn resolve_app_path_within_jan_data_folder<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ path: &str,+) -> Result<(PathBuf, PathBuf), String> {+ let jan_data_folder = get_jan_data_folder_path(app_handle);+ resolve_path_within_jan_data_folder(&jan_data_folder, path)+}+#[cfg(test)]mod tests {use super::*;@@ -182,11 +190,3 @@ mod tests {assert!(resolved.ends_with("file.txt"));}}--pub fn resolve_app_path_within_jan_data_folder<R: Runtime>(- app_handle: tauri::AppHandle<R>,- path: &str,-) -> Result<(PathBuf, PathBuf), String> {- let jan_data_folder = get_jan_data_folder_path(app_handle);- resolve_path_within_jan_data_folder(&jan_data_folder, path)-}diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex bda7c7cf6..88fa9a3a9 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -297,7 +297,7 @@ pub async fn get_tools<R: Runtime>(app: AppHandle<R>,state: State<'_, AppState>,) -> Result<Vec<ToolWithServer>, String> {- collect_mcp_tools(&app, &*state, None).await+ collect_mcp_tools(&app, &state, None).await}/// Retrieves tools from a specific subset of MCP servers by name.@@ -391,7 +391,7 @@ pub async fn call_tool(arguments: Option<Map<String, Value>>,cancellation_token: Option<String>,) -> Result<CallToolResult, String> {- let timeout_duration = tool_call_timeout(&*state).await;+ let timeout_duration = tool_call_timeout(&state).await;// Set up cancellation if token is providedlet (cancel_tx, cancel_rx) = oneshot::channel::<()>();diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rsindex df4a6014e..2f987d1cd 100644--- a/src-tauri/src/core/mcp/helpers.rs+++ b/src-tauri/src/core/mcp/helpers.rs@@ -398,7 +398,10 @@ async fn schedule_mcp_start_task<R: Runtime>(let config_params = extract_command_args(&config).ok_or_else(|| format!("Failed to extract command args from config for {name}"))?;- if config_params.transport_type.as_deref() == Some("http") && config_params.url.is_some() {+ if let (Some("http"), Some(url)) = (+ config_params.transport_type.as_deref(),+ config_params.url.clone(),+ ) {let transport = StreamableHttpClientTransport::with_client(reqwest::Client::builder().default_headers({@@ -425,7 +428,7 @@ async fn schedule_mcp_start_task<R: Runtime>(.build().unwrap(),StreamableHttpClientTransportConfig {- uri: config_params.url.unwrap().into(),+ uri: url.into(),..Default::default()},);@@ -460,8 +463,10 @@ async fn schedule_mcp_start_task<R: Runtime>(return Err(format!("Failed to connect to server: {e}"));}}- } else if config_params.transport_type.as_deref() == Some("sse") && config_params.url.is_some()- {+ } else if let (Some("sse"), Some(url)) = (+ config_params.transport_type.as_deref(),+ config_params.url.clone(),+ ) {let transport = SseClientTransport::start_with_client(reqwest::Client::builder().default_headers({@@ -488,7 +493,7 @@ async fn schedule_mcp_start_task<R: Runtime>(.build().unwrap(),rmcp::transport::sse_client::SseClientConfig {- sse_endpoint: config_params.url.unwrap().into(),+ sse_endpoint: url.into(),..Default::default()},)diff --git a/src-tauri/src/core/mcp/lockfile.rs b/src-tauri/src/core/mcp/lockfile.rsindex f834f1e2f..541716e5c 100644--- a/src-tauri/src/core/mcp/lockfile.rs+++ b/src-tauri/src/core/mcp/lockfile.rs@@ -152,20 +152,21 @@ pub async fn cleanup_all_stale_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(let pattern = app_data_dir.join("mcp_lock_*.json");let pattern_str = pattern.to_string_lossy();- for entry in glob::glob(&pattern_str).map_err(|e| format!("Glob error: {}", e))? {- if let Ok(path) = entry {- if let Some(file_name) = path.file_name() {- let file_name_str = file_name.to_string_lossy();- if let Some(port_str) = file_name_str- .strip_prefix("mcp_lock_")- .and_then(|s| s.strip_suffix(".json"))- {- if let Ok(port) = port_str.parse::<u16>() {- match check_and_cleanup_stale_lock(app, port).await {- Ok(true) => log::info!("Cleaned up stale lock for port {}", port),- Err(e) => log::warn!("Failed to cleanup lock for port {}: {}", port, e),- _ => {}- }+ for path in glob::glob(&pattern_str)+ .map_err(|e| format!("Glob error: {}", e))?+ .flatten()+ {+ if let Some(file_name) = path.file_name() {+ let file_name_str = file_name.to_string_lossy();+ if let Some(port_str) = file_name_str+ .strip_prefix("mcp_lock_")+ .and_then(|s| s.strip_suffix(".json"))+ {+ if let Ok(port) = port_str.parse::<u16>() {+ match check_and_cleanup_stale_lock(app, port).await {+ Ok(true) => log::info!("Cleaned up stale lock for port {}", port),+ Err(e) => log::warn!("Failed to cleanup lock for port {}: {}", port, e),+ _ => {}}}}@@ -185,14 +186,15 @@ pub fn cleanup_own_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {let pattern_str = pattern.to_string_lossy();let current_pid = std::process::id();- for entry in glob::glob(&pattern_str).map_err(|e| format!("Glob error: {}", e))? {- if let Ok(path) = entry {- if let Ok(content) = fs::read_to_string(&path) {- if let Ok(lock) = serde_json::from_str::<McpLockFile>(&content) {- if lock.pid == current_pid {- fs::remove_file(&path).ok();- log::debug!("Removed own lock file: {:?}", path);- }+ for path in glob::glob(&pattern_str)+ .map_err(|e| format!("Glob error: {}", e))?+ .flatten()+ {+ if let Ok(content) = fs::read_to_string(&path) {+ if let Ok(lock) = serde_json::from_str::<McpLockFile>(&content) {+ if lock.pid == current_pid {+ fs::remove_file(&path).ok();+ log::debug!("Removed own lock file: {:?}", path);}}}diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rsindex fdbe6a2d9..7364bf205 100644--- a/src-tauri/src/core/mcp/tests.rs+++ b/src-tauri/src/core/mcp/tests.rs@@ -506,7 +506,7 @@ fn test_default_constants_values() {assert_eq!(DEFAULT_MCP_BASE_RESTART_DELAY_MS, 1000);assert_eq!(DEFAULT_MCP_MAX_RESTART_DELAY_MS, 30000);assert!((DEFAULT_MCP_BACKOFF_MULTIPLIER - 2.0).abs() < f64::EPSILON);- assert!(DEFAULT_MCP_BASE_RESTART_DELAY_MS < DEFAULT_MCP_MAX_RESTART_DELAY_MS);+ const _: () = assert!(DEFAULT_MCP_BASE_RESTART_DELAY_MS < DEFAULT_MCP_MAX_RESTART_DELAY_MS);}#[test]@@ -572,8 +572,10 @@ fn test_mcp_settings_default_matches_constants() {#[test]fn test_mcp_settings_tool_call_timeout_duration_enforces_minimum() {use super::models::McpSettings;- let mut s = McpSettings::default();- s.tool_call_timeout_seconds = 0;+ let mut s = McpSettings {+ tool_call_timeout_seconds: 0,+ ..McpSettings::default()+ };assert_eq!(s.tool_call_timeout_duration(), Duration::from_secs(1));s.tool_call_timeout_seconds = 5;assert_eq!(s.tool_call_timeout_duration(), Duration::from_secs(5));@@ -612,11 +614,13 @@ impl PartialEq for super::models::McpSettings {#[test]fn test_mcp_settings_round_trip_camel_case() {use super::models::McpSettings;- let mut s = McpSettings::default();- s.tool_call_timeout_seconds = 42;- s.router_model_provider = "openai".into();- s.router_model_id = "gpt-4".into();- s.use_lightweight_router_model = true;+ let s = McpSettings {+ tool_call_timeout_seconds: 42,+ router_model_provider: "openai".into(),+ router_model_id: "gpt-4".into(),+ use_lightweight_router_model: true,+ ..McpSettings::default()+ };let json = serde_json::to_string(&s).unwrap();assert!(json.contains("\"toolCallTimeoutSeconds\":42"));assert!(json.contains("\"routerModelProvider\":\"openai\""));@@ -822,7 +826,7 @@ fn test_is_process_alive_for_almost_certainly_dead_pid() {// PID 0 is the scheduler / not a real signalable process on Linux/macOS// and PID 999999 is extremely unlikely to exist// (i32::MAX as u32) exceeds Linux pid_max → kernel returns ESRCH/EINVAL- assert!(!is_process_alive((i32::MAX as u32)));+ assert!(!is_process_alive(i32::MAX as u32));}#[test]@@ -903,7 +907,7 @@ async fn test_check_and_cleanup_stale_lock_removes_dead_pid_lock() {let lock_path = app_data_dir.join(format!("mcp_lock_{}.json", port));// PID above pid_max guarantees ESRCH/EINVAL on Unix → reported as not alive- let dead_pid: u32 = (i32::MAX as u32);+ let dead_pid: u32 = i32::MAX as u32;let lock = McpLockFile {pid: dead_pid,port,diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex e38a98015..5839a12a5 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -304,10 +304,7 @@ pub(crate) fn convert_messages(continue;}- let content_array = match content.as_array() {- Some(arr) => arr,- None => return None,- };+ let content_array = content.as_array()?;match role {"assistant" => {@@ -1006,6 +1003,8 @@ async fn call_openai_chat_completions(Err(last_err)}+// orchestration coordinator threads state from multiple subsystems+#[allow(clippy::too_many_arguments)]async fn run_server_side_openai_orchestration(json_body: &serde_json::Value,client: &Client,@@ -1155,6 +1154,7 @@ async fn run_server_side_openai_orchestration(}/// Handles the proxy request logic+#[allow(clippy::too_many_arguments)]async fn proxy_request(req: Request<Body>,client: Client,@@ -2774,6 +2774,7 @@ pub async fn start_server(.await}+#[allow(clippy::too_many_arguments)]async fn start_server_internal(server_handle: Arc<Mutex<Option<ServerHandle>>>,llama_state: Arc<LlamacppState>,diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rsindex 4ca4a5d93..4a2a0b5d4 100644--- a/src-tauri/src/core/server/tests.rs+++ b/src-tauri/src/core/server/tests.rs@@ -1,5 +1,5 @@#[cfg(test)]-mod tests {+mod server_tests {use crate::core::server::proxy;use serde_json::json;@@ -1060,7 +1060,7 @@ mod tests {fn get_destination_path_trailing_slash() {let result = proxy::get_destination_path("/v1/", "/v1");// remove_prefix should leave "/" or "" — either way no panic, deterministic.- assert!(result == "/" || result == "");+ assert!(result == "/" || result.is_empty());}#[test]diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 95097e16f..6d8e6b52f 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -193,8 +193,9 @@ pub fn factory_reset<R: Runtime>(// Reset app configuration to defaults unless user chose to keep configsif !keep_models_and_configs {- let mut default_config = AppConfiguration::default();- default_config.data_folder = default_data_folder_path(app_handle.clone());+ let default_config = AppConfiguration {+ data_folder: default_data_folder_path(app_handle.clone()),+ };let _ = update_app_configuration(app_handle.clone(), default_config);}@@ -349,11 +350,12 @@ pub fn launch_claude_code_with_config(match std::fs::OpenOptions::new().write(true).create(true)+ .truncate(false).open(&env_file_path){Ok(_) => {write_env_to_shell(&env_file_path, &env_vars)?;- return Ok(());+ Ok(())}Err(_) => {// Use admin privileges to write@@ -397,7 +399,7 @@ pub fn launch_claude_code_with_config("Env vars written to {} with admin privileges",env_file_path);- return Ok(());+ Ok(())}}} else if cfg!(target_os = "linux") {@@ -412,17 +414,18 @@ pub fn launch_claude_code_with_config(match std::fs::OpenOptions::new().write(true).create(true)+ .truncate(false).open(&env_file_path){Ok(_) => {write_env_to_shell(&env_file_path, &env_vars)?;- return Ok(());+ Ok(())}Err(_) => {let jan_config_dir = format!("{}/.config/jan", home_dir);let ext = if shell_name == "bash" { "bash" } else { "zsh" };let env_file = format!("{}/claude-code-env.{}", jan_config_dir, ext);- return Err(format!("NEED_PERMISSION:{}", env_file));+ Err(format!("NEED_PERMISSION:{}", env_file))}}} else {@@ -441,7 +444,7 @@ pub fn launch_claude_code_with_config(}log::info!("Environment variables set permanently in Windows registry.");- return Ok(());+ Ok(())}}@@ -664,11 +667,12 @@ pub fn clear_claude_code_env() -> Result<(), String> {match std::fs::OpenOptions::new().write(true).create(true)+ .truncate(false).open(&env_file_path){Ok(_) => {std::fs::write(&env_file_path, &cleaned).map_err(|e| e.to_string())?;- return Ok(());+ Ok(())}Err(_) => {// Write cleaned content to a temp file, then use osascript to move it@@ -690,7 +694,7 @@ pub fn clear_claude_code_env() -> Result<(), String> {"CC env cleared from {} with admin privileges",env_file_path);- return Ok(());+ Ok(())}}} else if cfg!(target_os = "linux") {@@ -707,6 +711,7 @@ pub fn clear_claude_code_env() -> Result<(), String> {match std::fs::OpenOptions::new().write(true).create(true)+ .truncate(false).open(&env_file_path){Ok(_) => {diff --git a/src-tauri/src/core/updater/session.rs b/src-tauri/src/core/updater/session.rsindex 83ff0ff59..4409b309e 100644--- a/src-tauri/src/core/updater/session.rs+++ b/src-tauri/src/core/updater/session.rs@@ -1,11 +1,9 @@-/**- * Session Management Module- *- * Manages persistent session identifier for request signing and caching.- * Uses tauri-plugin-store for persistence (compatible with TypeScript).- *- * Storage location: {app_data_dir}/updater.json- */+//! Session Management Module+//!+//! Manages persistent session identifier for request signing and caching.+//! Uses tauri-plugin-store for persistence (compatible with TypeScript).+//!+//! Storage location: {app_data_dir}/updater.jsonuse std::sync::OnceLock;use tauri::{AppHandle, Runtime};