Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: lockfile to kill conflict MCP's port

Vanalite75e9c10631ce
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index df68a9b34..08e2469c6 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -6,11 +6,14 @@ version = 3
name = "Jan"
version = "0.6.599"
dependencies = [
+ "chrono",
"dirs",
"env",
"fix-path-env",
"flate2",
"futures-util",
+ "glob",
+ "hostname",
"hyper 0.14.32",
"jan-utils",
"libc",
@@ -2256,6 +2259,17 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "hostname"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a56f203cd1c76362b69e3863fd987520ac36cf70a8c92627449b2f64a8cf7d65"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "windows-link 0.1.3",
+]
+
[[package]]
name = "html2text"
version = "0.11.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index b157cc63d..fb6ee83af 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -97,6 +97,9 @@ rfd = { version = "0.15.4", default-features = false, features = [
"xdg-portal",
"common-controls-v6",
] }
+chrono = { version = "0.4", features = ["serde"] }
+hostname = "0.4"
+glob = "0.3"
[dependencies.tauri]
version = "2.8.5"
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 5763512b2..0ff126de4 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -41,7 +41,11 @@ pub async fn activate_mcp_server<R: Runtime>(
}
#[tauri::command]
-pub async fn deactivate_mcp_server(state: State<'_, AppState>, name: String) -> Result<(), String> {
+pub async fn deactivate_mcp_server<R: Runtime>(
+ app: AppHandle<R>,
+ state: State<'_, AppState>,
+ name: String,
+) -> Result<(), String> {
log::info!("Deactivating MCP server: {name}");
// First, mark server as manually deactivated to prevent restart
@@ -87,6 +91,15 @@ pub async fn deactivate_mcp_server(state: State<'_, AppState>, name: String) ->
service.cancel().await.map_err(|e| e.to_string())?;
}
}
+
+ // Delete lock file if this is Jan Browser MCP
+ if name == "Jan Browser MCP" {
+ use crate::core::mcp::lockfile::delete_lock_file;
+ if let Err(e) = delete_lock_file(&app, 17389) {
+ log::warn!("Failed to delete lock file for port 17389: {}", e);
+ }
+ }
+
log::info!("Server {name} stopped successfully and marked as deactivated.");
Ok(())
}
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 8427feee7..8520de939 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -632,6 +632,30 @@ async fn schedule_mcp_start_task<R: Runtime>(
}
}
} else {
+ if name == "Jan Browser MCP" {
+ if let Some(port_str) = config_params.envs.get("BRIDGE_PORT") {
+ if let Some(port_str) = port_str.as_str() {
+ if let Ok(port) = port_str.parse::<u16>() {
+ if !jan_utils::network::is_port_available(port) {
+ log::warn!("Port {} occupied, attempting cleanup", port);
+ match kill_orphaned_mcp_process_with_app(&app, port).await {
+ Ok(true) => {
+ log::info!("Cleaned up orphaned process on port {}", port);
+ }
+ Ok(false) => {
+ return Err(format!(
+ "Port {} is already in use. Please close the application using this port or restart Jan.",
+ port
+ ));
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+ }
+ }
+ }
+
let mut cmd = Command::new(config_params.command.clone());
let bun_x_path = if cfg!(windows) {
bin_path.join("bun.exe")
@@ -742,6 +766,21 @@ async fn schedule_mcp_start_task<R: Runtime>(
connected.insert(name.clone(), true);
log::info!("Marked MCP server {name} as successfully connected");
}
+
+ // Create lock file for Jan Browser MCP
+ if name == "Jan Browser MCP" {
+ if let Some(port_str) = config_params.envs.get("BRIDGE_PORT") {
+ if let Some(port_str) = port_str.as_str() {
+ if let Ok(port) = port_str.parse::<u16>() {
+ use crate::core::mcp::lockfile::create_lock_file;
+ if let Err(e) = create_lock_file(&app, port, &name) {
+ log::warn!("Failed to create lock file for port {}: {}", port, e);
+ }
+ }
+ }
+ }
+ }
+
emit_mcp_update_event(&app, &name);
}
Ok(())
@@ -832,7 +871,122 @@ pub async fn restart_active_mcp_servers<R: Runtime>(
Ok(())
}
-pub async fn clean_up_mcp_servers(state: State<'_, AppState>) {
+pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
+ app: &AppHandle<R>,
+ port: u16,
+) -> Result<bool, String> {
+ use crate::core::mcp::lockfile::{check_and_cleanup_stale_lock, is_process_alive, read_lock_file};
+
+ if let Some(lock) = read_lock_file(app, port) {
+ log::debug!("Found lock file for port {}: PID={}", port, lock.pid);
+
+ if !is_process_alive(lock.pid) {
+ log::info!("Lock file stale, process {} is dead", lock.pid);
+ check_and_cleanup_stale_lock(app, port).await?;
+ return Ok(true);
+ }
+
+ log::info!(
+ "Process {} from lock file is alive, attempting kill",
+ lock.pid
+ );
+ kill_process_by_pid(lock.pid).await?;
+
+ use crate::core::mcp::lockfile::delete_lock_file;
+ delete_lock_file(app, port)?;
+
+ tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
+
+ if jan_utils::network::is_port_available(port) {
+ log::info!("Cleaned up orphaned process via lock file");
+ return Ok(true);
+ }
+ }
+
+ let process_info = match jan_utils::network::find_process_using_port(port) {
+ Some(info) => info,
+ None => return Ok(false),
+ };
+
+ log::info!(
+ "Found process on port {}: PID={}, name={}, cmd={:?}",
+ port,
+ process_info.pid,
+ process_info.name,
+ process_info.cmd
+ );
+
+ if !jan_utils::network::is_orphaned_mcp_process(&process_info) {
+ log::warn!(
+ "Port {} occupied by non-MCP process '{}' (PID {})",
+ port,
+ process_info.name,
+ process_info.pid
+ );
+ return Err(format!(
+ "Port {} is in use by '{}' (PID {}), which is not a Jan MCP process",
+ port, process_info.name, process_info.pid
+ ));
+ }
+
+ log::info!("Killing orphaned MCP process: PID {}", process_info.pid);
+ kill_process_by_pid(process_info.pid).await?;
+
+ tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
+
+ if jan_utils::network::is_port_available(port) {
+ log::info!("Cleaned up orphaned process on port {}", port);
+ Ok(true)
+ } else {
+ Err(format!(
+ "Port {} still in use after killing process",
+ port
+ ))
+ }
+}
+
+#[cfg(unix)]
+async fn kill_process_by_pid(pid: u32) -> Result<(), String> {
+ use nix::sys::signal::{kill, Signal};
+ use nix::unistd::Pid;
+
+ let nix_pid = Pid::from_raw(pid as i32);
+
+ kill(nix_pid, Signal::SIGTERM)
+ .map_err(|e| format!("Failed to send SIGTERM to PID {}: {}", pid, e))?;
+
+ for _ in 0..30 {
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ if kill(nix_pid, None).is_err() {
+ return Ok(());
+ }
+ }
+
+ log::warn!("Process {} unresponsive, sending SIGKILL", pid);
+ kill(nix_pid, Signal::SIGKILL)
+ .map_err(|e| format!("Failed to send SIGKILL to PID {}: {}", pid, e))?;
+
+ Ok(())
+}
+
+#[cfg(windows)]
+async fn kill_process_by_pid(pid: u32) -> Result<(), String> {
+ use std::process::Command;
+
+ let output = Command::new("taskkill")
+ .args(&["/F", "/PID", &pid.to_string()])
+ .output()
+ .map_err(|e| format!("Failed to run taskkill: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("taskkill failed: {}", stderr));
+ }
+
+ Ok(())
+}
+
+pub async fn clean_up_mcp_servers<R: Runtime>(app: &AppHandle<R>, state: State<'_, AppState>) {
log::info!("Cleaning up MCP servers");
// Stop all running MCP servers
@@ -847,6 +1001,13 @@ pub async fn clean_up_mcp_servers(state: State<'_, AppState>) {
let mut restart_counts = state.mcp_restart_counts.lock().await;
restart_counts.clear();
}
+
+ // Clean up all lock files created by this process
+ use crate::core::mcp::lockfile::cleanup_own_locks;
+ if let Err(e) = cleanup_own_locks(app) {
+ log::warn!("Failed to cleanup own lock files: {}", e);
+ }
+
log::info!("MCP servers cleaned up successfully");
}
diff --git a/src-tauri/src/core/mcp/lockfile.rs b/src-tauri/src/core/mcp/lockfile.rs
new file mode 100644
index 000000000..cab7d56e3
--- /dev/null
+++ b/src-tauri/src/core/mcp/lockfile.rs
@@ -0,0 +1,197 @@
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::PathBuf;
+use tauri::{AppHandle, Manager, Runtime};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct McpLockFile {
+ pub pid: u32,
+ pub port: u16,
+ pub server_name: String,
+ pub created_at: String,
+ pub hostname: String,
+}
+
+fn get_lock_file_path<R: Runtime>(app: &AppHandle<R>, port: u16) -> PathBuf {
+ let app_data_dir = app
+ .path()
+ .app_data_dir()
+ .expect("Failed to get app data dir");
+ app_data_dir.join(format!("mcp_lock_{}.json", port))
+}
+
+pub fn create_lock_file<R: Runtime>(
+ app: &AppHandle<R>,
+ port: u16,
+ server_name: &str,
+) -> Result<(), String> {
+ let lock_path = get_lock_file_path(app, port);
+
+ // Ensure parent directory exists
+ if let Some(parent) = lock_path.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create lock file directory: {}", e))?;
+ }
+
+ let lock = McpLockFile {
+ pid: std::process::id(),
+ port,
+ server_name: server_name.to_string(),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ hostname: hostname::get()
+ .map(|h| h.to_string_lossy().to_string())
+ .unwrap_or_else(|_| "unknown".to_string()),
+ };
+
+ let lock_json =
+ serde_json::to_string_pretty(&lock).map_err(|e| format!("Failed to serialize lock: {}", e))?;
+
+ fs::write(&lock_path, lock_json)
+ .map_err(|e| format!("Failed to write lock file: {}", e))?;
+
+ log::debug!("Created lock file for port {} at {:?}", port, lock_path);
+ Ok(())
+}
+
+pub fn read_lock_file<R: Runtime>(app: &AppHandle<R>, port: u16) -> Option<McpLockFile> {
+ let lock_path = get_lock_file_path(app, port);
+
+ if !lock_path.exists() {
+ return None;
+ }
+
+ let lock_json = fs::read_to_string(&lock_path).ok()?;
+ serde_json::from_str(&lock_json).ok()
+}
+
+pub fn delete_lock_file<R: Runtime>(app: &AppHandle<R>, port: u16) -> Result<(), String> {
+ let lock_path = get_lock_file_path(app, port);
+
+ if lock_path.exists() {
+ fs::remove_file(&lock_path)
+ .map_err(|e| format!("Failed to delete lock file: {}", e))?;
+ log::debug!("Deleted lock file for port {}", port);
+ }
+
+ Ok(())
+}
+
+pub fn is_process_alive(pid: u32) -> bool {
+ #[cfg(unix)]
+ {
+ use nix::sys::signal::kill;
+ use nix::unistd::Pid;
+
+ let nix_pid = Pid::from_raw(pid as i32);
+ kill(nix_pid, None).is_ok()
+ }
+
+ #[cfg(windows)]
+ {
+ use std::process::Command;
+
+ let output = Command::new("tasklist")
+ .args(&["/FI", &format!("PID eq {}", pid), "/NH"])
+ .output();
+
+ if let Ok(output) = output {
+ let output_str = String::from_utf8_lossy(&output.stdout);
+ output_str.contains(&pid.to_string())
+ } else {
+ false
+ }
+ }
+
+ #[cfg(not(any(unix, windows)))]
+ {
+ false
+ }
+}
+
+pub async fn check_and_cleanup_stale_lock<R: Runtime>(
+ app: &AppHandle<R>,
+ port: u16,
+) -> Result<bool, String> {
+ let lock = match read_lock_file(app, port) {
+ Some(l) => l,
+ None => return Ok(false),
+ };
+
+ log::debug!(
+ "Found lock file for port {}: PID={}, server={}",
+ port,
+ lock.pid,
+ lock.server_name
+ );
+
+ if !is_process_alive(lock.pid) {
+ log::info!(
+ "Lock file for port {} is stale (PID {} is dead), removing",
+ port,
+ lock.pid
+ );
+ delete_lock_file(app, port)?;
+ return Ok(true);
+ }
+
+ log::debug!("Process {} is still alive for port {}", lock.pid, port);
+ Ok(false)
+}
+
+pub async fn cleanup_all_stale_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {
+ let app_data_dir = app
+ .path()
+ .app_data_dir()
+ .expect("Failed to get app data dir");
+
+ 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),
+ _ => {}
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+pub fn cleanup_own_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {
+ let app_data_dir = app
+ .path()
+ .app_data_dir()
+ .expect("Failed to get app data dir");
+
+ let pattern = app_data_dir.join("mcp_lock_*.json");
+ 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);
+ }
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rs
index b9627f02f..6f6378667 100644
--- a/src-tauri/src/core/mcp/mod.rs
+++ b/src-tauri/src/core/mcp/mod.rs
@@ -1,6 +1,7 @@
pub mod commands;
mod constants;
pub mod helpers;
+pub mod lockfile;
pub mod models;
#[cfg(test)]
diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rs
index f8e886058..ddc403e00 100644
--- a/src-tauri/src/core/setup.rs
+++ b/src-tauri/src/core/setup.rs
@@ -238,6 +238,12 @@ pub fn setup_mcp<R: Runtime>(app: &App<R>) {
let servers = state.mcp_servers.clone();
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
+ use crate::core::mcp::lockfile::cleanup_all_stale_locks;
+
+ if let Err(e) = cleanup_all_stale_locks(&app_handle).await {
+ log::debug!("Lock file cleanup error: {}", e);
+ }
+
if let Err(e) = run_mcp_commands(&app_handle, servers).await {
log::error!("Failed to run mcp commands: {e}");
}
diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rs
index 9c72fd4da..01aea8d68 100644
--- a/src-tauri/src/core/system/commands.rs
+++ b/src-tauri/src/core/system/commands.rs
@@ -26,7 +26,7 @@ pub fn factory_reset<R: Runtime>(app_handle: tauri::AppHandle<R>, state: State<'
log::info!("Factory reset, removing data folder: {data_folder:?}");
tauri::async_runtime::block_on(async {
- clean_up_mcp_servers(state.clone()).await;
+ clean_up_mcp_servers(&app_handle, state.clone()).await;
let _ = cleanup_llama_processes(app_handle.clone()).await;
if data_folder.exists() {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index caedf787d..784b4448c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -222,7 +222,7 @@ pub fn run() {
// Quick cleanup with shorter timeout
let state = app_handle.state::<AppState>();
- let _ = clean_up_mcp_servers(state).await;
+ let _ = clean_up_mcp_servers(&app_handle, state).await;
let _ = cleanup_llama_processes(app.clone()).await;
});
});
diff --git a/src-tauri/utils/src/network.rs b/src-tauri/utils/src/network.rs
index 05704c12e..280e94033 100644
--- a/src-tauri/utils/src/network.rs
+++ b/src-tauri/utils/src/network.rs
@@ -146,3 +146,185 @@ pub fn convert_headers(
}
Ok(header_map)
}
+
+/// Information about a process using a specific port
+#[derive(Debug, Clone)]
+pub struct ProcessUsingPort {
+ pub pid: u32,
+ pub name: String,
+ pub cmd: Vec<String>,
+}
+
+/// Find the process ID using a specific port
+/// Returns None if port is available or process cannot be determined
+pub fn find_process_using_port(port: u16) -> Option<ProcessUsingPort> {
+ #[cfg(target_os = "macos")]
+ {
+ find_process_using_port_unix(port)
+ }
+
+ #[cfg(target_os = "linux")]
+ {
+ find_process_using_port_unix(port)
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ find_process_using_port_windows(port)
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
+ {
+ None
+ }
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn find_process_using_port_unix(port: u16) -> Option<ProcessUsingPort> {
+ use std::process::Command;
+
+ let output = Command::new("lsof")
+ .args(&["-i", &format!(":{}", port)])
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let output_str = String::from_utf8_lossy(&output.stdout);
+
+ for line in output_str.lines().skip(1) {
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if parts.len() > 9 {
+ let name = parts[0].to_string();
+ let pid_str = parts[1];
+ let state = parts.get(9).map(|s| s.to_uppercase());
+
+ if let Some(state_val) = state {
+ if state_val.contains("LISTEN") {
+ if let Ok(pid) = pid_str.parse::<u32>() {
+ let cmd = get_process_command_line(pid).unwrap_or_else(|| vec![name.clone()]);
+ return Some(ProcessUsingPort { pid, name, cmd });
+ }
+ }
+ }
+ }
+ }
+
+ None
+}
+
+#[cfg(target_os = "windows")]
+fn find_process_using_port_windows(port: u16) -> Option<ProcessUsingPort> {
+ use std::process::Command;
+
+ let output = Command::new("netstat")
+ .args(&["-ano"])
+ .output()
+ .ok()?;
+
+ let output_str = String::from_utf8_lossy(&output.stdout);
+
+ for line in output_str.lines() {
+ if line.contains(&format!(":{}", port)) && line.contains("LISTENING") {
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if let Some(pid_str) = parts.last() {
+ if let Ok(pid) = pid_str.parse::<u32>() {
+ let name_output = Command::new("tasklist")
+ .args(&["/FI", &format!("PID eq {}", pid), "/FO", "CSV", "/NH"])
+ .output()
+ .ok()?;
+
+ let name_str = String::from_utf8_lossy(&name_output.stdout);
+ let name = name_str
+ .split(',')
+ .next()
+ .unwrap_or("Unknown")
+ .trim_matches('"')
+ .to_string();
+
+ let cmd = get_process_command_line(pid).unwrap_or_else(|| vec![name.clone()]);
+
+ return Some(ProcessUsingPort { pid, name, cmd });
+ }
+ }
+ }
+ }
+
+ None
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn get_process_command_line(pid: u32) -> Option<Vec<String>> {
+ use std::process::Command;
+
+ let output = Command::new("ps")
+ .args(&["-p", &pid.to_string(), "-o", "command="])
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let cmd_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ if cmd_str.is_empty() {
+ return None;
+ }
+
+ Some(
+ cmd_str
+ .split_whitespace()
+ .map(|s| s.to_string())
+ .collect(),
+ )
+}
+
+#[cfg(target_os = "windows")]
+fn get_process_command_line(pid: u32) -> Option<Vec<String>> {
+ use std::process::Command;
+
+ let output = Command::new("wmic")
+ .args(&[
+ "process",
+ "where",
+ &format!("ProcessId={}", pid),
+ "get",
+ "CommandLine",
+ "/format:list",
+ ])
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let output_str = String::from_utf8_lossy(&output.stdout);
+ for line in output_str.lines() {
+ if line.starts_with("CommandLine=") {
+ let cmd_str = line.strip_prefix("CommandLine=")?.trim().to_string();
+ if !cmd_str.is_empty() {
+ return Some(
+ cmd_str
+ .split_whitespace()
+ .map(|s| s.to_string())
+ .collect(),
+ );
+ }
+ }
+ }
+
+ None
+}
+
+pub fn is_orphaned_mcp_process(process_info: &ProcessUsingPort) -> bool {
+ let name_lower = process_info.name.to_lowercase();
+ let cmd_str = process_info.cmd.join(" ").to_lowercase();
+
+ let is_node = name_lower.contains("node") || name_lower.contains("npx");
+ let is_mcp_server = cmd_str.contains("search-mcp-server");
+
+ is_node && is_mcp_server
+}