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: close app in background

Vanalite10acacbf1d52
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 7837da0f2..38f7ee046 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_with_restart, stop_mcp_servers},
+ helpers::{restart_active_mcp_servers, start_mcp_server_with_restart},
};
use crate::core::{
app::commands::get_jan_data_folder_path,
@@ -123,9 +123,11 @@ pub async fn deactivate_mcp_server<R: Runtime>(
#[tauri::command]
pub async fn restart_mcp_servers<R: Runtime>(app: AppHandle<R>, state: State<'_, AppState>) -> Result<(), String> {
+ use super::helpers::{stop_mcp_servers_with_context, ShutdownContext};
+
let servers = state.mcp_servers.clone();
- // Stop the servers
- stop_mcp_servers(state.mcp_servers.clone()).await?;
+
+ stop_mcp_servers_with_context(&app, &state, ShutdownContext::ManualRestart).await?;
// Restart only previously active servers (like cortex)
restart_active_mcp_servers(&app, servers).await?;
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 30a62ec93..a3875af85 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -24,6 +24,31 @@ use crate::core::{
};
use jan_utils::{can_override_npx, can_override_uvx};
+#[derive(Debug, Clone, Copy)]
+pub enum ShutdownContext {
+ AppExit, // User closing app - be fast
+ ManualRestart, // User restarting servers - be thorough
+ FactoryReset, // Deleting data - be very thorough
+}
+
+impl ShutdownContext {
+ fn per_server_timeout(&self) -> Duration {
+ match self {
+ Self::AppExit => Duration::from_millis(500),
+ Self::ManualRestart => Duration::from_secs(2),
+ Self::FactoryReset => Duration::from_secs(5),
+ }
+ }
+
+ fn overall_timeout(&self) -> Duration {
+ match self {
+ Self::AppExit => Duration::from_millis(1500),
+ Self::ManualRestart => Duration::from_secs(5),
+ Self::FactoryReset => Duration::from_secs(10),
+ }
+ }
+}
+
/// Calculate exponential backoff delay with jitter
///
/// # Arguments
@@ -132,7 +157,7 @@ pub async fn run_mcp_commands<R: Runtime>(
let config_clone = config.clone();
// Spawn task for initial startup attempt
- let handle = tokio::spawn(async move {
+ let handle = tauri::async_runtime::spawn(async move {
// Only wait for the initial startup attempt, not the monitoring
let result = start_mcp_server_with_restart(
app_clone.clone(),
@@ -190,6 +215,7 @@ pub async fn run_mcp_commands<R: Runtime>(
pub async fn monitor_mcp_server_handle(
servers_state: SharedMcpServers,
name: String,
+ shutdown_flag: Arc<Mutex<bool>>,
) -> Option<rmcp::service::QuitReason> {
log::info!("Monitoring MCP server {name} health");
@@ -198,7 +224,13 @@ pub async fn monitor_mcp_server_handle(
// Small delay between health checks
sleep(Duration::from_secs(5)).await;
- // Check if server is still healthy by trying to list tools
+ {
+ let shutdown = shutdown_flag.lock().await;
+ if *shutdown {
+ return Some(rmcp::service::QuitReason::Closed);
+ }
+ }
+
let health_check_result = {
let servers = servers_state.lock().await;
if let Some(service) = servers.get(&name) {
@@ -331,6 +363,7 @@ pub async fn start_restart_loop<R: Runtime>(
restart_counts: Arc<Mutex<HashMap<String, u32>>>,
successfully_connected: Arc<Mutex<HashMap<String, bool>>>,
mcp_settings: Arc<Mutex<McpSettings>>,
+ shutdown_flag: Arc<Mutex<bool>>,
) {
loop {
let current_restart_count = {
@@ -413,7 +446,7 @@ pub async fn start_restart_loop<R: Runtime>(
// Monitor the server again
let quit_reason =
- monitor_mcp_server_handle(servers_state.clone(), name.clone()).await;
+ monitor_mcp_server_handle(servers_state.clone(), name.clone(), shutdown_flag.clone()).await;
log::info!("MCP server {name} quit with reason: {quit_reason:?}");
@@ -1016,11 +1049,11 @@ async fn kill_process_by_pid(pid: u32) -> Result<(), String> {
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
- let _ = stop_mcp_servers(state.mcp_servers.clone()).await;
+pub async fn background_cleanup_mcp_servers<R: Runtime>(
+ app: &AppHandle<R>,
+ state: &State<'_, AppState>,
+) {
+ let _ = stop_mcp_servers_with_context(app, state, ShutdownContext::AppExit).await;
// Clear active servers and restart counts
{
@@ -1031,34 +1064,131 @@ pub async fn clean_up_mcp_servers<R: Runtime>(app: &AppHandle<R>, state: State<'
let mut restart_counts = state.mcp_restart_counts.lock().await;
restart_counts.clear();
}
+ {
+ let mut connected = state.mcp_successfully_connected.lock().await;
+ connected.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);
- }
+ let _ = cleanup_own_locks(app);
+}
- log::info!("MCP servers cleaned up successfully");
+struct ShutdownGuard {
+ flag: Arc<Mutex<bool>>,
}
-pub async fn stop_mcp_servers(servers_state: SharedMcpServers) -> Result<(), String> {
- let mut servers_map = servers_state.lock().await;
- let keys: Vec<String> = servers_map.keys().cloned().collect();
- for key in keys {
- if let Some(service) = servers_map.remove(&key) {
- match service {
- RunningServiceEnum::NoInit(service) => {
- log::info!("Stopping server {key}...");
- service.cancel().await.map_err(|e| e.to_string())?;
- }
- RunningServiceEnum::WithInit(service) => {
- log::info!("Stopping server {key} with initialization...");
- service.cancel().await.map_err(|e| e.to_string())?;
- }
+impl Drop for ShutdownGuard {
+ fn drop(&mut self) {
+ if let Ok(mut guard) = self.flag.try_lock() {
+ *guard = false;
+ } else {
+ let flag = self.flag.clone();
+ tauri::async_runtime::spawn(async move {
+ let mut guard = flag.lock().await;
+ *guard = false;
+ });
+ }
+ }
+}
+
+pub async fn stop_mcp_servers_with_context<R: Runtime>(
+ app: &AppHandle<R>,
+ state: &State<'_, AppState>,
+ context: ShutdownContext,
+) -> Result<(), String> {
+ {
+ let mut shutdown_in_progress = state.mcp_shutdown_in_progress.lock().await;
+ if *shutdown_in_progress {
+ return Ok(());
+ }
+ *shutdown_in_progress = true;
+ }
+
+ let _guard = ShutdownGuard {
+ flag: state.mcp_shutdown_in_progress.clone(),
+ };
+
+ {
+ let mut monitoring_tasks = state.mcp_monitoring_tasks.lock().await;
+ for (_name, handle) in monitoring_tasks.drain() {
+ handle.abort();
+ }
+ }
+
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ let servers_to_stop: Vec<(String, RunningServiceEnum, Option<u16>)> = {
+ let mut servers_map = state.mcp_servers.lock().await;
+ let keys: Vec<String> = servers_map.keys().cloned().collect();
+
+ let mut result = Vec::new();
+ for key in keys {
+ if let Some(service) = servers_map.remove(&key) {
+ let port = if key == "Jan Browser MCP" {
+ let active_servers = state.mcp_active_servers.lock().await;
+ active_servers.get(&key).and_then(|config| {
+ config.get("env")
+ .and_then(|e| e.get("BRIDGE_PORT"))
+ .and_then(|p| p.as_str())
+ .and_then(|s| s.parse::<u16>().ok())
+ })
+ } else {
+ None
+ };
+
+ result.push((key, service, port));
}
}
+ result
+ };
+
+ if servers_to_stop.is_empty() {
+ return Ok(());
}
- drop(servers_map); // Release the lock after stopping
+
+ let per_server_timeout = context.per_server_timeout();
+ let stop_handles: Vec<_> = servers_to_stop
+ .into_iter()
+ .map(|(name, service, port)| {
+ let app_clone = app.clone();
+
+ tauri::async_runtime::spawn(async move {
+ let cancel_future = async {
+ match service {
+ RunningServiceEnum::NoInit(service) => service.cancel().await,
+ RunningServiceEnum::WithInit(service) => service.cancel().await,
+ }
+ };
+
+ let success = tokio::time::timeout(per_server_timeout, cancel_future)
+ .await
+ .map(|r| r.is_ok())
+ .unwrap_or(false);
+
+ 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;
+ }
+ let _ = delete_lock_file(&app_clone, port);
+ }
+ }
+
+ (name, success)
+ })
+ })
+ .collect();
+
+ let overall_timeout = context.overall_timeout();
+ let _ = tokio::time::timeout(
+ overall_timeout,
+ futures_util::future::join_all(stop_handles)
+ ).await;
+
+ tokio::time::sleep(Duration::from_millis(200)).await;
+
Ok(())
}
@@ -1089,16 +1219,19 @@ pub async fn spawn_server_monitoring_task<R: Runtime>(
successfully_connected: Arc<Mutex<HashMap<String, bool>>>,
mcp_settings: Arc<Mutex<McpSettings>>,
) {
+ let app_state = app.state::<AppState>();
+ let shutdown_flag = app_state.mcp_shutdown_in_progress.clone();
+
let app_clone = app.clone();
let servers_clone = servers_state.clone();
let name_clone = name.clone();
let config_clone = config.clone();
let mcp_settings_clone = mcp_settings.clone();
- tauri::async_runtime::spawn(async move {
+ let task_handle = tauri::async_runtime::spawn(async move {
// Monitor the server using RunningService's JoinHandle<QuitReason>
let quit_reason =
- monitor_mcp_server_handle(servers_clone.clone(), name_clone.clone()).await;
+ monitor_mcp_server_handle(servers_clone.clone(), name_clone.clone(), shutdown_flag.clone()).await;
log::info!(
"MCP server {name_clone} quit with reason: {quit_reason:?}"
@@ -1116,10 +1249,17 @@ pub async fn spawn_server_monitoring_task<R: Runtime>(
restart_counts,
successfully_connected,
mcp_settings_clone.clone(),
+ shutdown_flag,
)
.await;
}
});
+
+ // Store task handle for later cancellation
+ {
+ let mut tasks = app_state.mcp_monitoring_tasks.lock().await;
+ tasks.insert(name.clone(), task_handle);
+ }
}
/// Determine if a server should be restarted based on its connection status and quit reason
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index b832b03a2..45c7535b0 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -742,7 +742,7 @@ pub async fn start_server(
};
log::info!("Jan API server started on http://{addr}");
- let server_task = tokio::spawn(async move {
+ let server_task = tauri::async_runtime::spawn(async move {
if let Err(e) = server.await {
log::error!("Server error: {e}");
return Err(Box::new(e) as Box<dyn std::error::Error + Send + Sync>);
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index bb8c4ef0a..3d7052f31 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -7,10 +7,9 @@ use rmcp::{
RoleClient, ServiceError,
};
use tokio::sync::{Mutex, oneshot};
-use tokio::task::JoinHandle;
/// Server handle type for managing the proxy server lifecycle
-pub type ServerHandle = JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
+pub type ServerHandle = tauri::async_runtime::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
pub enum RunningServiceEnum {
NoInit(RunningService<RoleClient, ()>),
@@ -29,6 +28,9 @@ pub struct AppState {
pub server_handle: Arc<Mutex<Option<ServerHandle>>>,
pub tool_call_cancellations: Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>,
pub mcp_settings: Arc<Mutex<McpSettings>>,
+ pub mcp_shutdown_in_progress: Arc<Mutex<bool>>,
+ pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tauri::async_runtime::JoinHandle<()>>>>,
+ pub background_cleanup_handle: Arc<Mutex<Option<tauri::async_runtime::JoinHandle<()>>>>,
}
impl RunningServiceEnum {
diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rs
index 01aea8d68..86e45663d 100644
--- a/src-tauri/src/core/system/commands.rs
+++ b/src-tauri/src/core/system/commands.rs
@@ -7,7 +7,7 @@ use crate::core::app::commands::{
default_data_folder_path, get_jan_data_folder_path, update_app_configuration,
};
use crate::core::app::models::AppConfiguration;
-use crate::core::mcp::helpers::clean_up_mcp_servers;
+use crate::core::mcp::helpers::{stop_mcp_servers_with_context, ShutdownContext};
use crate::core::state::AppState;
#[tauri::command]
@@ -26,7 +26,21 @@ 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(&app_handle, state.clone()).await;
+ let _ = stop_mcp_servers_with_context(&app_handle, &state, ShutdownContext::FactoryReset).await;
+
+ {
+ let mut active_servers = state.mcp_active_servers.lock().await;
+ active_servers.clear();
+ }
+ {
+ let mut restart_counts = state.mcp_restart_counts.lock().await;
+ restart_counts.clear();
+ }
+
+ use crate::core::mcp::lockfile::cleanup_own_locks;
+ if let Err(e) = cleanup_own_locks(&app_handle) {
+ log::warn!("Failed to cleanup lock files: {}", e);
+ }
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 784b4448c..44c2afeba 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2,7 +2,7 @@ mod core;
use core::{
app::commands::get_jan_data_folder_path,
downloads::models::DownloadManagerState,
- mcp::{helpers::clean_up_mcp_servers, models::McpSettings},
+ mcp::models::McpSettings,
setup::{self, setup_mcp},
state::AppState,
};
@@ -125,6 +125,9 @@ pub fn run() {
server_handle: Arc::new(Mutex::new(None)),
tool_call_cancellations: Arc::new(Mutex::new(HashMap::new())),
mcp_settings: Arc::new(Mutex::new(McpSettings::default())),
+ mcp_shutdown_in_progress: Arc::new(Mutex::new(false)),
+ mcp_monitoring_tasks: Arc::new(Mutex::new(HashMap::new())),
+ background_cleanup_handle: Arc::new(Mutex::new(None)),
})
.setup(|app| {
app.handle().plugin(
@@ -206,24 +209,50 @@ pub fn run() {
// Handle app lifecycle events
app.run(|app, event| {
if let RunEvent::Exit = event {
- // This is called when the app is actually exiting (e.g., macOS dock quit)
- // We can't prevent this, so run cleanup quickly
let app_handle = app.clone();
- tokio::task::block_in_place(|| {
+
+ #[cfg(not(any(target_os = "ios", target_os = "android")))]
+ {
+ if let Some(window) = app_handle.get_webview_window("main") {
+ let _ = window.hide();
+ let _ = window.emit("app-shutting-down", ());
+ }
+ }
+
+ let state = app_handle.state::<AppState>();
+
+ let cleanup_already_running = tokio::task::block_in_place(|| {
tauri::async_runtime::block_on(async {
- // Hide window immediately (not available on mobile platforms)
- if let Some(window) = app_handle.get_webview_window("main") {
- #[cfg(not(any(target_os = "ios", target_os = "android")))]
- {
- let _ = window.hide();
- }
- let _ = window.emit("kill-mcp-servers", ());
- }
+ let handle = state.background_cleanup_handle.lock().await;
+ handle.is_some()
+ })
+ });
+
+ if cleanup_already_running {
+ return;
+ }
+
+ let app_handle_for_cleanup = app_handle.clone();
+
+ let cleanup_handle = tauri::async_runtime::spawn(async move {
+ use crate::core::mcp::helpers::background_cleanup_mcp_servers;
+
+ let state = app_handle_for_cleanup.state::<AppState>();
+
+ let cleanup_future = background_cleanup_mcp_servers(&app_handle_for_cleanup, &state);
+ let _ = tokio::time::timeout(tokio::time::Duration::from_secs(3), cleanup_future).await;
- // Quick cleanup with shorter timeout
- let state = app_handle.state::<AppState>();
- let _ = clean_up_mcp_servers(&app_handle, state).await;
- let _ = cleanup_llama_processes(app.clone()).await;
+ if let Err(e) = cleanup_llama_processes(app_handle_for_cleanup.clone()).await {
+ log::warn!("Failed to cleanup llama processes: {}", e);
+ }
+
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ });
+
+ tokio::task::block_in_place(|| {
+ tauri::async_runtime::block_on(async {
+ let mut handle_guard = state.background_cleanup_handle.lock().await;
+ *handle_guard = Some(cleanup_handle);
});
});
}