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: remove hardcoded port

Vanalite56f3fa6d471c
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 0ff126de4..7837da0f2 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -48,6 +48,20 @@ pub async fn deactivate_mcp_server<R: Runtime>(
) -> Result<(), String> {
log::info!("Deactivating MCP server: {name}");
+ // Get port from config before removing (for lock file cleanup later)
+ let bridge_port = if name == "Jan Browser MCP" {
+ let active_servers = state.mcp_active_servers.lock().await;
+ active_servers.get(&name).and_then(|config| {
+ config
+ .get("envs")
+ .and_then(|envs| envs.get("BRIDGE_PORT"))
+ .and_then(|port| port.as_str())
+ .and_then(|port_str| port_str.parse::<u16>().ok())
+ })
+ } else {
+ None
+ };
+
// First, mark server as manually deactivated to prevent restart
// Remove from active servers list to prevent restart
{
@@ -92,11 +106,14 @@ pub async fn deactivate_mcp_server<R: Runtime>(
}
}
- // Delete lock file if this is Jan Browser MCP
+ // Delete lock file if this is Jan Browser MCP and we have a port
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);
+ if let Some(port) = bridge_port {
+ use crate::core::mcp::lockfile::delete_lock_file;
+
+ if let Err(e) = delete_lock_file(&app, port) {
+ log::warn!("Failed to delete lock file for port {}: {}", port, e);
+ }
}
}
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 8520de939..abd8d666c 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -877,6 +877,7 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
) -> Result<bool, String> {
use crate::core::mcp::lockfile::{check_and_cleanup_stale_lock, is_process_alive, read_lock_file};
+ // Check lock file first (fast path)
if let Some(lock) = read_lock_file(app, port) {
log::debug!("Found lock file for port {}: PID={}", port, lock.pid);
@@ -886,23 +887,44 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
return Ok(true);
}
- log::info!(
- "Process {} from lock file is alive, attempting kill",
- lock.pid
- );
- kill_process_by_pid(lock.pid).await?;
+ // Process from lock file is alive - verify it's still the MCP process
+ if let Some(process_info) = jan_utils::network::get_process_info_by_pid(lock.pid) {
+ if jan_utils::network::is_orphaned_mcp_process(&process_info) {
+ log::info!(
+ "Lock file PID {} verified as MCP process, attempting kill",
+ lock.pid
+ );
+ kill_process_by_pid(lock.pid).await?;
- use crate::core::mcp::lockfile::delete_lock_file;
- delete_lock_file(app, port)?;
+ use crate::core::mcp::lockfile::delete_lock_file;
+ delete_lock_file(app, port)?;
- tokio::time::sleep(tokio::time::Duration::from_millis(500)).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 via lock file");
- return Ok(true);
+ if jan_utils::network::is_port_available(port) {
+ log::info!("Cleaned up orphaned process via lock file");
+ return Ok(true);
+ }
+ } else {
+ log::warn!(
+ "Lock file PID {} is alive but NOT an MCP process (name: {}, cmd: {:?}). Lock file is stale.",
+ lock.pid,
+ process_info.name,
+ process_info.cmd
+ );
+ // PID reused by another process, clean up stale lock file
+ check_and_cleanup_stale_lock(app, port).await?;
+ }
+ } else {
+ log::debug!(
+ "Could not get process info for PID {}, cleaning up lock file",
+ lock.pid
+ );
+ check_and_cleanup_stale_lock(app, port).await?;
}
}
+ // Fallback: Use lsof/netstat to find process on port
let process_info = match jan_utils::network::find_process_using_port(port) {
Some(info) => info,
None => return Ok(false),
@@ -918,13 +940,13 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
if !jan_utils::network::is_orphaned_mcp_process(&process_info) {
log::warn!(
- "Port {} occupied by non-MCP process '{}' (PID {})",
+ "Port {} occupied by non-Jan 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 {} is in use by another application '{}' (PID {}). Please close that application or use a different port.",
port, process_info.name, process_info.pid
));
}
diff --git a/src-tauri/utils/src/network.rs b/src-tauri/utils/src/network.rs
index 280e94033..68395aaa1 100644
--- a/src-tauri/utils/src/network.rs
+++ b/src-tauri/utils/src/network.rs
@@ -319,6 +319,89 @@ fn get_process_command_line(pid: u32) -> Option<Vec<String>> {
None
}
+/// Get process information by PID
+/// Returns None if process doesn't exist or cannot be determined
+pub fn get_process_info_by_pid(pid: u32) -> Option<ProcessUsingPort> {
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ {
+ get_process_info_by_pid_unix(pid)
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ get_process_info_by_pid_windows(pid)
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
+ {
+ None
+ }
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn get_process_info_by_pid_unix(pid: u32) -> Option<ProcessUsingPort> {
+ use std::process::Command;
+
+ // Use ps to get process info by PID
+ let output = Command::new("ps")
+ .args(&["-p", &pid.to_string(), "-o", "comm="])
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ if name.is_empty() {
+ return None;
+ }
+
+ let cmd = get_process_command_line(pid).unwrap_or_else(|| vec![name.clone()]);
+
+ Some(ProcessUsingPort { pid, name, cmd })
+}
+
+#[cfg(target_os = "windows")]
+fn get_process_info_by_pid_windows(pid: u32) -> Option<ProcessUsingPort> {
+ use std::process::Command;
+
+ // Use wmic to get process info by PID
+ let output = Command::new("wmic")
+ .args(&[
+ "process",
+ "where",
+ &format!("ProcessId={}", pid),
+ "get",
+ "Name",
+ "/format:list",
+ ])
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let output_str = String::from_utf8_lossy(&output.stdout);
+ let mut name = String::new();
+
+ for line in output_str.lines() {
+ if line.starts_with("Name=") {
+ name = line.strip_prefix("Name=")?.trim().to_string();
+ break;
+ }
+ }
+
+ if name.is_empty() {
+ return None;
+ }
+
+ let cmd = get_process_command_line(pid).unwrap_or_else(|| vec![name.clone()]);
+
+ Some(ProcessUsingPort { pid, name, cmd })
+}
+
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();