Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp): browser port leak and auto-disable ux (#8317)
Arun Babu Neelicattu432fc88b7fc5
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex 88fa9a3a9..2ef9cdb03 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -6,7 +6,7 @@ use tokio::time::timeout;use super::{constants::DEFAULT_MCP_CONFIG,- helpers::{restart_active_mcp_servers, start_mcp_server},+ helpers::{kill_process_by_pid, restart_active_mcp_servers, start_mcp_server},};use crate::core::{app::commands::get_jan_data_folder_path,@@ -19,6 +19,9 @@ use crate::core::{};use std::{collections::HashSet, fs, time::Duration};+const BRIDGE_KILL_SETTLE_MS: u64 = 100; // settle after graceful cancel before port check+const PORT_FREE_SETTLE_MS: u64 = 500; // settle after force-kill before returning+async fn tool_call_timeout(state: &AppState) -> Duration {state.mcp_settings.lock().await.tool_call_timeout_duration()}@@ -156,7 +159,7 @@ pub async fn deactivate_mcp_server<R: Runtime>(let active_servers = state.mcp_active_servers.lock().await;active_servers.get(&name).and_then(|config| {config- .get("envs")+ .get("env").and_then(|envs| envs.get("BRIDGE_PORT")).and_then(|port| port.as_str()).and_then(|port_str| port_str.parse::<u16>().ok())@@ -199,11 +202,25 @@ pub async fn deactivate_mcp_server<R: Runtime>(let mut pids = state.mcp_server_pids.lock().await;pids.remove(&name);}- // Delete lock file if this is Jan Browser MCP and we have a port+if name == "Jan Browser MCP" {if let Some(port) = bridge_port {- use crate::core::mcp::lockfile::delete_lock_file;+ tokio::time::sleep(Duration::from_millis(BRIDGE_KILL_SETTLE_MS)).await;++ // Port 17389 is application-specific; the ~100 ms race window before another+ // process could grab it is negligible in practice.+ if !jan_utils::network::is_port_available(port) {+ if let Some(info) = jan_utils::network::find_process_using_port(port) {+ log::info!("Killing process on port {} after deactivation: PID={}", port, info.pid);+ if let Err(e) = kill_process_by_pid(info.pid).await {+ log::warn!("Failed to kill PID {}: {}", info.pid, e);+ } else {+ tokio::time::sleep(Duration::from_millis(PORT_FREE_SETTLE_MS)).await;+ }+ }+ }+ 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.rsindex 558619176..61c826ea8 100644--- a/src-tauri/src/core/mcp/helpers.rs+++ b/src-tauri/src/core/mcp/helpers.rs@@ -24,6 +24,8 @@ use crate::core::{};use jan_utils::{can_override_npx, can_override_uvx};+const BRIDGE_KILL_SETTLE_MS: u64 = 100; // settle after graceful cancel before port check+#[derive(Debug, Clone, Copy)]pub enum ShutdownContext {AppExit, // User closing app - be fast@@ -772,14 +774,22 @@ async fn schedule_mcp_start_task<R: Runtime>(// If all attempts failed, we still proceed to emit the event.// The health monitor will handle ongoing reconnection.- // Create lock file for Jan Browser MCPif 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);+ let child_pid = app+ .state::<AppState>()+ .mcp_server_pids+ .lock()+ .await+ .get(&name)+ .copied();+ if let Some(pid) = child_pid {+ if let Err(e) = create_lock_file(&app, port, &name, pid) {+ log::warn!("Failed to create lock file for port {}: {}", port, e);+ }}}}@@ -903,8 +913,8 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(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);- }+ // Fall through — port may still be held by a grandchild that outlived this PID.+ } else {// Process from lock file is alive - verify it's still the MCP processif let Some(process_info) = jan_utils::network::get_process_info_by_pid(lock.pid) {@@ -941,6 +951,7 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>();check_and_cleanup_stale_lock(app, port).await?;}+ }}// Fallback: Use lsof/netstat to find process on port@@ -984,7 +995,7 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(}#[cfg(unix)]-async fn kill_process_by_pid(pid: u32) -> Result<(), String> {+pub async fn kill_process_by_pid(pid: u32) -> Result<(), String> {use nix::sys::signal::{kill, Signal};use nix::unistd::Pid;@@ -1008,7 +1019,7 @@ async fn kill_process_by_pid(pid: u32) -> Result<(), String> {}#[cfg(windows)]-async fn kill_process_by_pid(pid: u32) -> Result<(), String> {+pub async fn kill_process_by_pid(pid: u32) -> Result<(), String> {use std::process::Command;#[cfg(windows)]@@ -1152,10 +1163,17 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(if name == "Jan Browser MCP" {if let Some(port) = port {- use crate::core::mcp::lockfile::delete_lock_file;if success {- tokio::time::sleep(Duration::from_millis(100)).await;+ sleep(Duration::from_millis(BRIDGE_KILL_SETTLE_MS)).await;}+ if !jan_utils::network::is_port_available(port) {+ if let Some(info) = jan_utils::network::find_process_using_port(port) {+ if let Err(e) = kill_process_by_pid(info.pid).await {+ log::warn!("Failed to kill port {} holder PID {}: {}", port, info.pid, e);+ }+ }+ }+ use crate::core::mcp::lockfile::delete_lock_file;let _ = delete_lock_file(&app_clone, port);}}diff --git a/src-tauri/src/core/mcp/lockfile.rs b/src-tauri/src/core/mcp/lockfile.rsindex 541716e5c..6291970d8 100644--- a/src-tauri/src/core/mcp/lockfile.rs+++ b/src-tauri/src/core/mcp/lockfile.rs@@ -6,6 +6,8 @@ use tauri::{AppHandle, Manager, Runtime};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct McpLockFile {pub pid: u32,+ #[serde(default)]+ pub jan_pid: u32,pub port: u16,pub server_name: String,pub created_at: String,@@ -24,6 +26,7 @@ pub fn create_lock_file<R: Runtime>(app: &AppHandle<R>,port: u16,server_name: &str,+ pid: u32,) -> Result<(), String> {let lock_path = get_lock_file_path(app, port);@@ -34,7 +37,8 @@ pub fn create_lock_file<R: Runtime>(}let lock = McpLockFile {- pid: std::process::id(),+ pid,+ jan_pid: std::process::id(),port,server_name: server_name.to_string(),created_at: chrono::Utc::now().to_rfc3339(),@@ -192,7 +196,7 @@ pub fn cleanup_own_locks<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {{if let Ok(content) = fs::read_to_string(&path) {if let Ok(lock) = serde_json::from_str::<McpLockFile>(&content) {- if lock.pid == current_pid {+ if lock.jan_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 7364bf205..52477d0da 100644--- a/src-tauri/src/core/mcp/tests.rs+++ b/src-tauri/src/core/mcp/tests.rs@@ -790,6 +790,7 @@ fn test_mcp_lock_file_serde_round_trip() {use super::lockfile::McpLockFile;let lock = McpLockFile {pid: 4242,+ jan_pid: std::process::id(),port: 17389,server_name: "Jan Browser MCP".to_string(),created_at: "2026-01-01T00:00:00+00:00".to_string(),@@ -838,11 +839,13 @@ fn test_create_read_delete_lock_file_round_trip() {// Ensure clean slatelet _ = delete_lock_file(app.handle(), port);- create_lock_file(app.handle(), port, "test-server").expect("create_lock_file");+ let fake_child_pid = std::process::id().wrapping_add(1);+ create_lock_file(app.handle(), port, "test-server", fake_child_pid).expect("create_lock_file");let lock = read_lock_file(app.handle(), port).expect("read_lock_file");assert_eq!(lock.port, port);assert_eq!(lock.server_name, "test-server");- assert_eq!(lock.pid, std::process::id());+ assert_eq!(lock.pid, fake_child_pid);+ assert_eq!(lock.jan_pid, std::process::id());assert!(!lock.created_at.is_empty());assert!(!lock.hostname.is_empty());@@ -886,8 +889,8 @@ async fn test_check_and_cleanup_stale_lock_keeps_live_lock() {let app = mock_app();let port: u16 = 53_115;let _ = delete_lock_file(app.handle(), port);- create_lock_file(app.handle(), port, "live").unwrap();- // Lock points at the current PID, which is alive → must NOT be removed+ create_lock_file(app.handle(), port, "live", std::process::id()).unwrap();+ // Lock pid is the current process (alive) → must NOT be removedlet cleaned = check_and_cleanup_stale_lock(app.handle(), port).await.unwrap();assert!(!cleaned);assert!(read_lock_file(app.handle(), port).is_some());@@ -910,6 +913,7 @@ async fn test_check_and_cleanup_stale_lock_removes_dead_pid_lock() {let dead_pid: u32 = i32::MAX as u32;let lock = McpLockFile {pid: dead_pid,+ jan_pid: std::process::id(),port,server_name: "ghost".to_string(),created_at: "2020-01-01T00:00:00+00:00".to_string(),@@ -937,17 +941,18 @@ fn test_cleanup_own_locks_removes_only_current_pid_locks() {let _ = delete_lock_file(app.handle(), own_port);let _ = delete_lock_file(app.handle(), other_port);- // Lock owned by us- create_lock_file(app.handle(), own_port, "ours").unwrap();+ // Lock owned by us (jan_pid matches current process)+ let fake_child_pid = std::process::id().wrapping_add(1);+ create_lock_file(app.handle(), own_port, "ours", fake_child_pid).unwrap();- // Lock owned by some other PID — write directly into the SAME dir lockfile uses+ // Lock owned by a different Jan instance — write directly into the SAME dir lockfile useslet app_data_dir = app.handle().path().app_data_dir().expect("app data dir");std::fs::create_dir_all(&app_data_dir).ok();let other_path = app_data_dir.join(format!("mcp_lock_{}.json", other_port));- // Pick a PID that is definitely not us (and survives wrap)- let foreign_pid = if std::process::id() == 1 { 2 } else { 1 };+ let foreign_jan_pid = if std::process::id() == 1 { 2 } else { 1 };let foreign = McpLockFile {- pid: foreign_pid,+ pid: foreign_jan_pid,+ jan_pid: foreign_jan_pid,port: other_port,server_name: "theirs".into(),created_at: "2020-01-01T00:00:00+00:00".into(),diff --git a/src-tauri/utils/src/network.rs b/src-tauri/utils/src/network.rsindex 255b23146..e82407a79 100644--- a/src-tauri/utils/src/network.rs+++ b/src-tauri/utils/src/network.rs@@ -418,11 +418,14 @@ 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();+ // lsof may return a truncated thread name rather than "node"; cmd is more reliable.+ if cmd_str.contains("search-mcp-server") {+ return true;+ }+let is_js_runtime =name_lower.contains("node") || name_lower.contains("npx") || name_lower.contains("bun");- let is_jan_mcp_server = cmd_str.contains("search-mcp-server")- || (cmd_str.contains("jan") && cmd_str.contains("mcp"))- || cmd_str.contains("node")+ let is_jan_mcp_server = (cmd_str.contains("jan") && cmd_str.contains("mcp"))|| cmd_str.contains("bun");is_js_runtime && is_jan_mcp_serverdiff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex bd5d98494..2b41431ff 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -221,6 +221,7 @@ const ChatInput = memo(function ChatInput({dialogOpen: extensionDialogOpen,dialogState: extensionDialogState,toggleBrowser: handleBrowseClick,+ disableDueToIncompatibleModel,handleCancel: handleExtensionDialogCancel,setDialogOpen: setExtensionDialogOpen,} = useJanBrowserExtension()@@ -234,9 +235,11 @@ const ChatInput = memo(function ChatInput({// Auto-disable browser feature when model doesn't support ituseEffect(() => {if (janBrowserMCPActive && !modelSupportsBrowser) {- handleBrowseClick()+ disableDueToIncompatibleModel()}- }, [janBrowserMCPActive, modelSupportsBrowser, handleBrowseClick])+ // disableDueToIncompatibleModel omitted: its !isActive guard makes stale closures safe.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [janBrowserMCPActive, modelSupportsBrowser])const attachmentsEnabled = useAttachments((s) => s.enabled)const parsePreference = useAttachments((s) => s.parseMode)diff --git a/web-app/src/hooks/useJanBrowserExtension.ts b/web-app/src/hooks/useJanBrowserExtension.tsindex 6c9e666cc..99a005963 100644--- a/web-app/src/hooks/useJanBrowserExtension.ts+++ b/web-app/src/hooks/useJanBrowserExtension.ts@@ -104,6 +104,40 @@ export function useJanBrowserExtension() {}}, [janBrowserConfig, serviceHub, editServer, syncServers])+ /**+ * Deactivate the Jan Browser MCP because the selected model lacks required capabilities.+ * Shows a descriptive toast instead of the generic "disabled" message.+ */+ const disableDueToIncompatibleModel = useCallback(async () => {+ if (operationInProgressRef.current) return+ operationInProgressRef.current = true++ try {+ if (!janBrowserConfig || !isActive) return++ if (cancelDeactivationPromiseRef.current) {+ await cancelDeactivationPromiseRef.current+ }++ cancelledRef.current = false+ setIsLoading(true)++ await serviceHub.mcp().deactivateMCPServer(JAN_BROWSER_MCP_NAME)+ toast.warning('Jan Browser MCP disabled — model doesn\'t support vision.')++ editServer(JAN_BROWSER_MCP_NAME, {+ ...janBrowserConfig,+ active: false,+ })+ await syncServers()+ } catch (error) {+ console.error('Error auto-disabling Jan Browser MCP:', error)+ } finally {+ setIsLoading(false)+ operationInProgressRef.current = false+ }+ }, [janBrowserConfig, isActive, serviceHub, editServer, syncServers])+/*** Toggle the Jan Browser MCP (called when clicking the browser icon)*/@@ -206,6 +240,7 @@ export function useJanBrowserExtension() {// ActionstoggleBrowser,+ disableDueToIncompatibleModel,handleCancel,setDialogOpen,}