Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: prompt user on llama-server shutdown when models are busy (#8139)
Akarshan Biswas33b6ff33672c
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 3a653e893..5d5f4ea62 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -7,6 +7,9 @@ const COMMANDS: &[&str] = &[// Router-mode commands (Phase 1)"start_router","stop_router",+ "try_graceful_stop_router",+ "force_kill_router_tree",+ "force_stop_model","get_router_info","get_devices","generate_api_key",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.tomlindex 883ec5d09..881c5a57b 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml@@ -9,6 +9,9 @@ permissions = ["allow-unload-llama-model","allow-start-router","allow-stop-router",+ "allow-try-graceful-stop-router",+ "allow-force-kill-router-tree",+ "allow-force-stop-model","allow-get-router-info","allow-get-devices","allow-generate-api-key",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rsindex 0d63ed17c..af71ae938 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs@@ -15,6 +15,9 @@ pub async fn cleanup_processes<R: Runtime>(app_handle: &tauri::AppHandle<R>) {guard.take()};if let Some(handle) = maybe_handle {+ app_state+ .router_pid+ .store(0, std::sync::atomic::Ordering::SeqCst);if let Err(e) = crate::router::stop_router(handle).await {log::warn!("Failed to stop router during cleanup: {}", e);}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex c9f863b43..54b60a9f5 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -430,6 +430,9 @@ pub async fn start_router<R: Runtime>(api_key: handle.api_key.clone(),pid: handle.pid,};+ state+ .router_pid+ .store(handle.pid, std::sync::atomic::Ordering::SeqCst);*guard = Some(handle);Ok(info)}@@ -439,6 +442,9 @@ pub async fn stop_router<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<let state: State<Arc<LlamacppState>> = app_handle.state();let mut guard = state.router.lock().await;if let Some(handle) = guard.take() {+ state+ .router_pid+ .store(0, std::sync::atomic::Ordering::SeqCst);crate::router::stop_router(handle).await.map_err(|e| e.to_string())?;@@ -458,3 +464,104 @@ pub async fn get_router_info<R: Runtime>(pid: h.pid,}))}++/// `Ok(Some(busy))` on deadline; handle is restored to state.+#[tauri::command]+pub async fn try_graceful_stop_router<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ deadline_secs: u64,+) -> Result<Option<Vec<String>>, String> {+ let state: State<Arc<LlamacppState>> = app_handle.state();+ let maybe_handle = {+ let mut guard = state.router.lock().await;+ guard.take()+ };+ let Some(handle) = maybe_handle else {+ return Ok(None);+ };+ match crate::router::try_graceful_stop_router(handle, Duration::from_secs(deadline_secs)).await {+ Ok(()) => {+ state+ .router_pid+ .store(0, std::sync::atomic::Ordering::SeqCst);+ Ok(None)+ }+ Err((h, busy)) => {+ let mut guard = state.router.lock().await;+ *guard = Some(h);+ Ok(Some(busy))+ }+ }+}++/// Issues `POST /models/unload` for `model_id` only if `/slots?model=<id>`+/// reports `is_processing: true`. Returns whether an unload was triggered.+#[tauri::command]+pub async fn force_stop_model<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ model_id: String,+) -> Result<bool, String> {+ let (port, api_key, _pid) = router_endpoint(&app_handle).await?;+ let client = http_client().await;++ let slots_url = format!("http://127.0.0.1:{}/slots", port);+ let resp = client+ .get(&slots_url)+ .query(&[("model", model_id.as_str())])+ .bearer_auth(&api_key)+ .send()+ .await+ .map_err(|e| e.to_string())?;+ if !resp.status().is_success() {+ return Ok(false);+ }+ let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;+ let busy = json+ .as_array()+ .map(|arr| {+ arr.iter().any(|s| {+ s.get("is_processing")+ .and_then(|v| v.as_bool())+ .unwrap_or(false)+ })+ })+ .unwrap_or(false);+ if !busy {+ return Ok(false);+ }++ let url = format!("http://127.0.0.1:{}/models/unload", port);+ let resp = client+ .post(&url)+ .bearer_auth(&api_key)+ .json(&ModelRequestBody { model: &model_id })+ .send()+ .await+ .map_err(|e| e.to_string())?;+ log::info!(+ "force_stop_model: unload {} returned {}",+ model_id,+ resp.status()+ );+ Ok(true)+}++#[tauri::command]+pub async fn force_kill_router_tree<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+) -> Result<(), String> {+ let state: State<Arc<LlamacppState>> = app_handle.state();+ let pid = state+ .router_pid+ .swap(0, std::sync::atomic::Ordering::SeqCst);+ let maybe_handle = {+ let mut guard = state.router.lock().await;+ guard.take()+ };+ match (maybe_handle, pid) {+ (Some(handle), _) => crate::router::force_kill_router_tree(handle).await,+ (None, p) if p != 0 => crate::router::force_kill_router_tree_by_pid(p),+ _ => {}+ }+ Ok(())+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rsindex 1ffdc6727..b55f0ae85 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs@@ -17,7 +17,7 @@ mod process;pub mod router;pub mod state;pub use cleanup::cleanup_llama_processes;-pub use commands::stop_router;+pub use commands::{force_kill_router_tree, stop_router, try_graceful_stop_router};pub use state::LlamacppState;pub fn init<R: Runtime>() -> TauriPlugin<R> {@@ -28,6 +28,9 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {commands::unload_llama_model,commands::start_router,commands::stop_router,+ commands::try_graceful_stop_router,+ commands::force_kill_router_tree,+ commands::force_stop_model,commands::get_router_info,commands::get_devices,commands::generate_api_key,diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rsindex e670ee825..010999b52 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs@@ -10,6 +10,7 @@ use std::path::{Path, PathBuf};use std::process::Stdio;use std::time::Duration;+use sysinfo::{Pid, ProcessesToUpdate, System};use tokio::io::{AsyncBufReadExt, BufReader};use tokio::process::{Child, Command};use tokio::sync::mpsc;@@ -229,100 +230,274 @@ pub async fn start_router(})}-/// Gracefully shut down a router process.-///-/// Unloads loaded models over HTTP first so children flush GPU / KV cache-/// state, then terminates the router itself (SIGTERM→SIGKILL on Unix, forced-/// kill on Windows).-pub async fn stop_router(mut handle: RouterHandle) -> ServerResult<()> {- unload_all_models_best_effort(handle.port, &handle.api_key).await;+/// Always terminates; force-kills on busy-deadline. For user-prompt flows+/// use [`try_graceful_stop_router`] directly.+pub async fn stop_router(handle: RouterHandle) -> ServerResult<()> {+ match try_graceful_stop_router(handle, Duration::from_secs(10)).await {+ Ok(()) => Ok(()),+ Err((h, busy)) => {+ log::warn!(+ "stop_router: deadline hit with {} busy model(s) {:?}; force-killing tree",+ busy.len(),+ busy+ );+ force_kill_router_tree(h).await;+ Ok(())+ }+ }+}- #[cfg(unix)]- {- crate::process::graceful_terminate_process(&mut handle.child).await;+/// `Err((handle, busy))` on deadline — caller decides next step.+pub async fn try_graceful_stop_router(+ mut handle: RouterHandle,+ deadline: Duration,+) -> Result<(), (RouterHandle, Vec<String>)> {+ let start = Instant::now();++ let client = match reqwest::Client::builder().build() {+ Ok(c) => c,+ Err(e) => {+ log::warn!("try_graceful_stop_router: failed to build http client: {}; terminating directly", e);+ terminate_router_process(&mut handle.child).await;+ return Ok(());+ }+ };++ let initial = match list_busy_models(&client, handle.port, &handle.api_key).await {+ Ok(v) => v,+ Err(e) => {+ log::warn!(+ "try_graceful_stop_router: GET /models failed ({}); router likely already down, terminating",+ e+ );+ terminate_router_process(&mut handle.child).await;+ return Ok(());+ }+ };++ let loaded_only: Vec<String> = match list_models_filtered(&client, handle.port, &handle.api_key, &["loaded"]).await {+ Ok(v) => v,+ Err(_) => initial.clone(),+ };+ let processing =+ list_processing_models(&client, handle.port, &handle.api_key, &loaded_only).await;+ if !processing.is_empty() {+ log::warn!(+ "try_graceful_stop_router: {} model(s) actively processing: {:?}",+ processing.len(),+ processing+ );+ return Err((handle, processing));}- #[cfg(all(windows, target_arch = "x86_64"))]- {- crate::process::force_terminate_process(&mut handle.child).await;++ if !initial.is_empty() {+ log::info!(+ "try_graceful_stop_router: requesting unload for {} model(s)",+ initial.len()+ );+ let unload_url = format!("http://127.0.0.1:{}/models/unload", handle.port);+ for id in &initial {+ let body = serde_json::json!({ "model": id });+ match client+ .post(&unload_url)+ .bearer_auth(&handle.api_key)+ .json(&body)+ .send()+ .await+ {+ Ok(r) if r.status().is_success() => {}+ Ok(r) => log::warn!("try_graceful_stop_router: unload {} returned {}", id, r.status()),+ Err(e) => log::warn!("try_graceful_stop_router: unload {} failed: {}", id, e),+ }+ }}- #[cfg(not(any(unix, all(windows, target_arch = "x86_64"))))]- {- let _ = handle.child.kill().await;- let _ = handle.child.wait().await;++ loop {+ let still = list_busy_models(&client, handle.port, &handle.api_key)+ .await+ .unwrap_or_default();+ if still.is_empty() {+ break;+ }+ let elapsed = start.elapsed();+ if elapsed >= deadline {+ log::warn!(+ "try_graceful_stop_router: deadline ({:?}) hit with {} busy model(s)",+ deadline,+ still.len()+ );+ return Err((handle, still));+ }+ let remaining = deadline - elapsed;+ tokio::time::sleep(Duration::from_millis(150).min(remaining)).await;}++ terminate_router_process(&mut handle.child).await;Ok(())}-async fn unload_all_models_best_effort(port: u16, api_key: &str) {- let overall = Duration::from_secs(10);- let _ = tokio::time::timeout(overall, async {- let client = match reqwest::Client::builder()- .timeout(Duration::from_secs(5))- .build()- {- Ok(c) => c,- Err(e) => {- log::warn!("stop_router: failed to build http client: {}", e);- return;- }- };+async fn list_busy_models(+ client: &reqwest::Client,+ port: u16,+ api_key: &str,+) -> Result<Vec<String>, String> {+ list_models_filtered(client, port, api_key, &["loaded", "loading"]).await+}- let list_url = format!("http://127.0.0.1:{}/models", port);- let resp = match client.get(&list_url).bearer_auth(api_key).send().await {+async fn list_models_filtered(+ client: &reqwest::Client,+ port: u16,+ api_key: &str,+ allowed_status: &[&str],+) -> Result<Vec<String>, String> {+ let url = format!("http://127.0.0.1:{}/models", port);+ let resp = client+ .get(&url)+ .bearer_auth(api_key)+ .send()+ .await+ .map_err(|e| e.to_string())?;+ let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;+ Ok(json+ .get("data")+ .and_then(|d| d.as_array())+ .map(|arr| {+ arr.iter()+ .filter(|m| {+ m.get("status")+ .and_then(|s| s.get("value"))+ .and_then(|v| v.as_str())+ .map(|s| allowed_status.contains(&s))+ .unwrap_or(false)+ })+ .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(String::from))+ .collect()+ })+ .unwrap_or_default())+}++async fn list_processing_models(+ client: &reqwest::Client,+ port: u16,+ api_key: &str,+ candidates: &[String],+) -> Vec<String> {+ let url = format!("http://127.0.0.1:{}/slots", port);+ let mut busy = Vec::new();+ for id in candidates {+ let resp = match client+ .get(&url)+ .query(&[("model", id.as_str())])+ .bearer_auth(api_key)+ .send()+ .await+ {Ok(r) => r,Err(e) => {- log::warn!("stop_router: GET /models failed (router likely already down): {}", e);- return;+ log::warn!("list_processing_models: GET /slots?model={} failed: {}", id, e);+ continue;}};- let json: serde_json::Value = match resp.json().await {- Ok(v) => v,- Err(e) => {- log::warn!("stop_router: invalid JSON from /models: {}", e);- return;- }+ if !resp.status().is_success() {+ continue;+ }+ let Ok(json) = resp.json::<serde_json::Value>().await else {+ continue;};- let ids: Vec<String> = json- .get("data")- .and_then(|d| d.as_array())+ let is_busy = json+ .as_array().map(|arr| {- arr.iter()- .filter(|m| {- m.get("status")- .and_then(|s| s.get("value"))- .and_then(|v| v.as_str())- .map(|s| matches!(s, "loaded" | "loading"))- .unwrap_or(false)- })- .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(String::from))- .collect()+ arr.iter().any(|s| {+ s.get("is_processing")+ .and_then(|v| v.as_bool())+ .unwrap_or(false)+ })})- .unwrap_or_default();+ .unwrap_or(false);+ if is_busy {+ busy.push(id.clone());+ }+ }+ busy+}- if ids.is_empty() {- return;+async fn terminate_router_process(child: &mut Child) {+ #[cfg(unix)]+ {+ crate::process::graceful_terminate_process(child).await;+ }+ #[cfg(all(windows, target_arch = "x86_64"))]+ {+ crate::process::force_terminate_process(child).await;+ }+ #[cfg(not(any(unix, all(windows, target_arch = "x86_64"))))]+ {+ let _ = child.kill().await;+ let _ = child.wait().await;+ }+}++/// Force-kill by PID only; used when the handle is owned elsewhere+/// (e.g. the watcher loop). Does not reap — the holder of the `Child`+/// will reap on its next operation or on drop.+pub fn force_kill_router_tree_by_pid(router_pid: u32) {+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ let rpid = Pid::from_u32(router_pid);+ let children: Vec<Pid> = sys+ .processes()+ .values()+ .filter(|p| p.parent() == Some(rpid))+ .map(|p| p.pid())+ .collect();+ log::info!(+ "force_kill_router_tree_by_pid: router pid {} + {} direct child(ren)",+ router_pid,+ children.len()+ );+ if let Some(p) = sys.process(rpid) {+ let _ = p.kill();+ }+ for cpid in &children {+ if let Some(p) = sys.process(*cpid) {+ let _ = p.kill();}- log::info!("stop_router: unloading {} model(s) before shutdown", ids.len());-- let unload_url = format!("http://127.0.0.1:{}/models/unload", port);- let tasks = ids.into_iter().map(|id| {- let client = client.clone();- let url = unload_url.clone();- let key = api_key.to_string();- tokio::spawn(async move {- let body = serde_json::json!({ "model": id });- match client.post(&url).bearer_auth(&key).json(&body).send().await {- Ok(r) if r.status().is_success() => {}- Ok(r) => log::warn!("stop_router: unload {} returned {}", id, r.status()),- Err(e) => log::warn!("stop_router: unload {} failed: {}", id, e),- }- })- });- for t in tasks {- let _ = t.await;+ }+}++/// Router is killed before children so it can't spawn new ones mid-sweep.+pub async fn force_kill_router_tree(mut handle: RouterHandle) {+ let router_pid = handle.pid;+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);++ let rpid = Pid::from_u32(router_pid);+ let children: Vec<Pid> = sys+ .processes()+ .values()+ .filter(|p| p.parent() == Some(rpid))+ .map(|p| p.pid())+ .collect();++ log::info!(+ "force_kill_router_tree: router pid {} + {} direct child(ren)",+ router_pid,+ children.len()+ );++ if let Some(p) = sys.process(rpid) {+ if !p.kill() {+ log::debug!("force_kill_router_tree: router pid {} kill() false (likely already dying)", router_pid);}- })- .await;+ }+ // Failures are expected: router's own exit handler reaps these in parallel.+ for cpid in &children {+ if let Some(p) = sys.process(*cpid) {+ let _ = p.kill();+ }+ }++ let _ = handle.child.wait().await;}#[cfg(test)]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rsindex 28b96a76e..ddaf992c9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs@@ -1,4 +1,5 @@use serde::{Deserialize, Serialize};+use std::sync::atomic::AtomicU32;use tokio::sync::Mutex;#[derive(Debug, Clone, Serialize, Deserialize)]@@ -12,12 +13,16 @@ pub struct SessionInfo {pub struct LlamacppState {pub router: Mutex<Option<crate::router::RouterHandle>>,+ /// Mirror of the router PID for emergency lookup (e.g. force-kill while+ /// the handle is temporarily owned by the watcher loop). 0 = no router.+ pub router_pid: AtomicU32,}impl Default for LlamacppState {fn default() -> Self {Self {router: Mutex::new(None),+ router_pid: AtomicU32::new(0),}}}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 74ebe8c2b..f3085be5e 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -101,6 +101,8 @@ macro_rules! invoke_commands_with_extras {// Downloadcore::downloads::commands::download_files,core::downloads::commands::cancel_download_task,+ // App lifecycle+ confirm_exit,$($extra,)*@@ -108,6 +110,87 @@ macro_rules! invoke_commands_with_extras {};}+#[cfg(not(feature = "cli"))]+static SHUTTING_DOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+#[cfg(not(feature = "cli"))]+static GRACEFUL_IN_PROGRESS: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);+#[cfg(not(feature = "cli"))]+static BUSY_MODELS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());++#[cfg(not(feature = "cli"))]+#[tauri::command]+async fn confirm_exit<R: tauri::Runtime>(_app_handle: tauri::AppHandle<R>) {+ SHUTTING_DOWN.store(true, std::sync::atomic::Ordering::SeqCst);+ tokio::spawn(async {+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ std::process::exit(0);+ });+}++#[cfg(not(feature = "cli"))]+fn is_llamacpp_router_running<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool {+ use tauri::Manager;+ app.try_state::<std::sync::Arc<tauri_plugin_llamacpp::LlamacppState>>()+ .map(|s| s.router_pid.load(std::sync::atomic::Ordering::SeqCst) != 0)+ .unwrap_or(false)+}++#[cfg(not(feature = "cli"))]+fn reemit_busy_if_any<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>) {+ let busy = BUSY_MODELS.lock().map(|g| g.clone()).unwrap_or_default();+ if !busy.is_empty() {+ let _ = app_handle.emit("llamacpp-busy-on-exit", &busy);+ }+}++#[cfg(not(feature = "cli"))]+async fn handle_graceful_exit<R: tauri::Runtime>(+ app_handle: tauri::AppHandle<R>,+ source: &'static str,+ exit_code: i32,+) {+ use std::sync::atomic::Ordering;+ let mut emitted = false;+ loop {+ if SHUTTING_DOWN.load(Ordering::SeqCst) {+ return;+ }+ match tauri_plugin_llamacpp::try_graceful_stop_router(app_handle.clone(), 1).await {+ Ok(None) => {+ if let Ok(mut g) = BUSY_MODELS.lock() {+ g.clear();+ }+ SHUTTING_DOWN.store(true, Ordering::SeqCst);+ app_handle.exit(exit_code);+ return;+ }+ Ok(Some(busy)) => {+ if let Ok(mut g) = BUSY_MODELS.lock() {+ *g = busy.clone();+ }+ if !emitted {+ log::warn!("{}: {} model(s) busy: {:?}", source, busy.len(), busy);+ if let Err(e) = app_handle.emit("llamacpp-busy-on-exit", &busy) {+ log::warn!("emit llamacpp-busy-on-exit failed: {}", e);+ SHUTTING_DOWN.store(true, Ordering::SeqCst);+ app_handle.exit(exit_code);+ return;+ }+ emitted = true;+ }+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;+ }+ Err(e) => {+ log::warn!("{}: try_graceful_stop_router failed: {}", source, e);+ SHUTTING_DOWN.store(true, Ordering::SeqCst);+ app_handle.exit(exit_code);+ return;+ }+ }+ }+}+#[cfg(not(feature = "cli"))]#[cfg_attr(all(mobile, any(target_os = "android", target_os = "ios")),@@ -259,14 +342,46 @@ pub fn run() {.expect("error while running tauri application");// Handle app lifecycle eventsapp.run(|app, event| {- if let RunEvent::ExitRequested { .. } = event {+ use std::sync::atomic::Ordering;+ if let RunEvent::WindowEvent {+ event: tauri::WindowEvent::CloseRequested { api, .. },+ label,+ ..+ } = &event+ {+ if label == "main"+ && !SHUTTING_DOWN.load(Ordering::SeqCst)+ && is_llamacpp_router_running(app)+ {+ api.prevent_close();+ let _ = app.emit("llamacpp-close-attempt", ());+ if GRACEFUL_IN_PROGRESS.swap(true, Ordering::SeqCst) {+ reemit_busy_if_any(app);+ return;+ }+ let app_handle = app.clone();+ tauri::async_runtime::spawn(async move {+ handle_graceful_exit(app_handle, "CloseRequested", 0).await;+ GRACEFUL_IN_PROGRESS.store(false, Ordering::SeqCst);+ });+ return;+ }+ }+ if let RunEvent::ExitRequested { api, code, .. } = &event {+ if SHUTTING_DOWN.load(Ordering::SeqCst) || !is_llamacpp_router_running(app) {+ return;+ }+ api.prevent_exit();+ let _ = app.emit("llamacpp-close-attempt", ());+ if GRACEFUL_IN_PROGRESS.swap(true, Ordering::SeqCst) {+ reemit_busy_if_any(app);+ return;+ }let app_handle = app.clone();- tokio::task::block_in_place(|| {- tauri::async_runtime::block_on(async {- if let Err(e) = tauri_plugin_llamacpp::stop_router(app_handle).await {- log::warn!("stop_router on ExitRequested failed: {}", e);- }- })+ let exit_code = code.unwrap_or(0);+ tauri::async_runtime::spawn(async move {+ handle_graceful_exit(app_handle, "ExitRequested", exit_code).await;+ GRACEFUL_IN_PROGRESS.store(false, Ordering::SeqCst);});return;}diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex b63cc1a77..e43c6b844 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -1,4 +1,5 @@import TextareaAutosize from 'react-textarea-autosize'+import { invoke } from '@tauri-apps/api/core'import { cn, formatBytes } from '@/lib/utils'import { usePrompt } from '@/hooks/usePrompt'import { useThreads } from '@/hooks/useThreads'@@ -549,8 +550,18 @@ const ChatInput = memo(function ChatInput({abortControllers[threadId]?.abort()}cancelToolCall?.()+ // Escalate: if the llama.cpp model is still processing after the HTTP+ // abort, force-unload it so generation actually stops. KV cache is lost.+ const modelId = selectedModel?.id+ if (selectedProvider === 'llamacpp' && modelId) {+ setTimeout(() => {+ invoke('plugin:llamacpp|force_stop_model', { modelId }).catch((e) => {+ console.warn('force_stop_model failed:', e)+ })+ }, 500)+ }},- [abortControllers, cancelToolCall, onStop]+ [abortControllers, cancelToolCall, onStop, selectedModel?.id, selectedProvider])const fileInputRef = useRef<HTMLInputElement>(null)diff --git a/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsx b/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsxnew file mode 100644index 000000000..a42c62795--- /dev/null+++ b/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsx@@ -0,0 +1,133 @@+import { useEffect, useState } from 'react'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { AlertTriangle } from 'lucide-react'+import { toast } from 'sonner'++import { useAppState } from '@/hooks/useAppState'+import { isPlatformTauri } from '@/lib/platform/utils'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'++export default function LlamacppBusyOnExitDialog() {+ const { t } = useTranslation()+ const [busyModels, setBusyModels] = useState<string[] | null>(null)+ const [forcing, setForcing] = useState(false)++ useEffect(() => {+ if (!isPlatformTauri()) return+ const CLOSING_TOAST_ID = 'llamacpp-closing'+ const unlistenAttempt = listen('llamacpp-close-attempt', () => {+ toast.loading(t('common:llamacppBusyOnExit.shuttingDown'), {+ id: CLOSING_TOAST_ID,+ duration: Infinity,+ })+ }).catch((e) => {+ console.warn('listen llamacpp-close-attempt failed:', e)+ return () => {}+ })+ const unlistenBusy = listen<string[]>('llamacpp-busy-on-exit', (event) => {+ toast.dismiss(CLOSING_TOAST_ID)+ setBusyModels(event.payload ?? [])+ }).catch((e) => {+ console.warn('listen llamacpp-busy-on-exit failed:', e)+ return () => {}+ })+ return () => {+ void unlistenAttempt.then((fn) => fn?.())+ void unlistenBusy.then((fn) => fn?.())+ toast.dismiss(CLOSING_TOAST_ID)+ }+ }, [t])++ const handleForceQuit = async () => {+ setForcing(true)+ try {+ const state = useAppState.getState()+ Object.values(state.abortControllers).forEach((ctrl) => {+ try {+ ctrl.abort()+ } catch (e) {+ console.warn('abort controller threw on force-quit:', e)+ }+ })+ const threadIds = new Set<string>([+ ...Object.keys(state.busyThreads),+ ...Object.keys(state.streamingContents),+ ...Object.keys(state.loadingModels),+ ...Object.keys(state.abortControllers),+ ])+ threadIds.forEach((tid) => state.clearThreadState(tid))+ await invoke('plugin:llamacpp|force_kill_router_tree')+ await invoke('confirm_exit')+ } catch (e) {+ console.error('force-quit failed:', e)+ setForcing(false)+ }+ }++ const handleCancel = () => {+ setBusyModels(null)+ toast.dismiss('llamacpp-closing')+ }++ return (+ <Dialog open={busyModels !== null} onOpenChange={(o) => !o && handleCancel()}>+ <DialogContent showCloseButton={false}>+ <DialogHeader>+ <div className="flex items-start gap-3">+ <div className="shrink-0">+ <AlertTriangle className="size-4 text-destructive" />+ </div>+ <div>+ <DialogTitle>{t('common:llamacppBusyOnExit.title')}</DialogTitle>+ <DialogDescription className="mt-1 text-main-view-fg/70">+ {t('common:llamacppBusyOnExit.description')}+ </DialogDescription>+ </div>+ </div>+ </DialogHeader>++ {busyModels && busyModels.length > 0 && (+ <div className="bg-main-view-fg/2 p-2 border border-main-view-fg/5 rounded-lg text-sm text-main-view-fg/70 max-h-[150px] overflow-y-auto">+ <ul className="list-disc pl-5 space-y-1 break-all">+ {busyModels.map((id) => (+ <li key={id}>{id}</li>+ ))}+ </ul>+ </div>+ )}++ <DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end">+ <Button+ variant="link"+ onClick={handleCancel}+ disabled={forcing}+ className="flex-1 text-right sm:flex-none"+ >+ {t('common:cancel')}+ </Button>+ <Button+ variant="link"+ onClick={() => void handleForceQuit()}+ disabled={forcing}+ autoFocus+ className="flex-1 text-right sm:flex-none border border-destructive/30 text-destructive !px-2"+ >+ {forcing+ ? t('common:llamacppBusyOnExit.forcing')+ : t('common:llamacppBusyOnExit.forceQuit')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/locales/ca/common.json b/web-app/src/locales/ca/common.jsonindex 2e8a02087..907e29ca8 100644--- a/web-app/src/locales/ca/common.json+++ b/web-app/src/locales/ca/common.json@@ -399,5 +399,12 @@"title": "Fil eliminat del projecte","description": "El fil s’ha eliminat de \"{{projectName}}\" correctament"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/cs/common.json b/web-app/src/locales/cs/common.jsonindex afc83f0e1..ec1e685e1 100644--- a/web-app/src/locales/cs/common.json+++ b/web-app/src/locales/cs/common.json@@ -398,5 +398,12 @@"title": "Vlákno odebráno","description": "Vlákno bylo úspěšně odebráno z \"{{projectName}}\""}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.jsonindex d7812044b..2121f0083 100644--- a/web-app/src/locales/de-DE/common.json+++ b/web-app/src/locales/de-DE/common.json@@ -398,5 +398,12 @@"title": "Download abgeschlossen","description": "Modell \"{{item}}\" erfolgreich heruntergeladen und verifiziert"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 8b1c42d52..18b5757e3 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -480,5 +480,12 @@},"files": {"chunksCount": "{{count}} chunks"+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/es/common.json b/web-app/src/locales/es/common.jsonindex 8b0dd0a47..ceb6f40e7 100644--- a/web-app/src/locales/es/common.json+++ b/web-app/src/locales/es/common.json@@ -468,5 +468,12 @@},"files": {"chunksCount": "{{count}} fragmentos"+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.jsonindex ef532e72f..b45dc72dc 100644--- a/web-app/src/locales/fr/common.json+++ b/web-app/src/locales/fr/common.json@@ -401,5 +401,12 @@"attachmentInjectedIndicator": "Injecté dans la discussion","attachmentEmbeddedIndicator": "Intégré pour RAG","viewInjectedContent": "Voir le contenu injecté",- "injectedContentTitle": "Contenu du fichier injecté"+ "injectedContentTitle": "Contenu du fichier injecté",+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"+ }}diff --git a/web-app/src/locales/hi/common.json b/web-app/src/locales/hi/common.jsonindex 684145dcc..6a14f785f 100644--- a/web-app/src/locales/hi/common.json+++ b/web-app/src/locales/hi/common.json@@ -468,5 +468,12 @@},"files": {"chunksCount": "{{count}} खंड"+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/id/common.json b/web-app/src/locales/id/common.jsonindex 4fe125970..73eeddd53 100644--- a/web-app/src/locales/id/common.json+++ b/web-app/src/locales/id/common.json@@ -398,5 +398,12 @@"noProjectsFound": "Tidak ada proyek ditemukan","tryDifferentSearch": "Coba kata kunci pencarian lain","uploadingFiles": "Mengunggah file…"+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex 87fe5dd3d..e5ec37e75 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -389,5 +389,12 @@"title": "スレッドが削除されました","description": "スレッドは「{{projectName}}」から正常に削除されました"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/ko/common.json b/web-app/src/locales/ko/common.jsonindex 6550e6f3b..ca06c168a 100644--- a/web-app/src/locales/ko/common.json+++ b/web-app/src/locales/ko/common.json@@ -466,5 +466,12 @@},"files": {"chunksCount": "청크 {{count}}개"+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/pl/common.json b/web-app/src/locales/pl/common.jsonindex 0d6b42d01..e15e37d93 100644--- a/web-app/src/locales/pl/common.json+++ b/web-app/src/locales/pl/common.json@@ -398,5 +398,12 @@"conversationNotAvailable": "Rozmowa niedostępna","conversationNotAvailableDescription": "Rozmowa, do której próbujesz uzyskać dostęp, nie jest dostępna lub została usunięta.","temporaryChat": "Tymczasowy Czat",- "temporaryChatTooltip": "Tymczasowy czat nie pojawi się w Twojej historii"+ "temporaryChatTooltip": "Tymczasowy czat nie pojawi się w Twojej historii",+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"+ }}diff --git a/web-app/src/locales/pt-BR/common.json b/web-app/src/locales/pt-BR/common.jsonindex d9e2fe791..f4b8f45d7 100644--- a/web-app/src/locales/pt-BR/common.json+++ b/web-app/src/locales/pt-BR/common.json@@ -399,5 +399,12 @@"attachmentInjectedIndicator": "Injetado no chat","attachmentEmbeddedIndicator": "Incorporado para RAG","viewInjectedContent": "Ver conteúdo injetado",- "injectedContentTitle": "Conteúdo de arquivo injetado"+ "injectedContentTitle": "Conteúdo de arquivo injetado",+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"+ }}diff --git a/web-app/src/locales/ru/common.json b/web-app/src/locales/ru/common.jsonindex ebca6e019..5e2a5b9df 100644--- a/web-app/src/locales/ru/common.json+++ b/web-app/src/locales/ru/common.json@@ -408,5 +408,12 @@"title": "Обсуждение удалено","description": "Обсуждение успешно удалено из проекта \"{{projectName}}\""}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/vn/common.json b/web-app/src/locales/vn/common.jsonindex 57aa16e13..52108697d 100644--- a/web-app/src/locales/vn/common.json+++ b/web-app/src/locales/vn/common.json@@ -398,5 +398,12 @@"title": "Chủ đề đã được xóa","description": "Chủ đề đã được xóa khỏi \"{{projectName}}\" thành công"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.jsonindex 2e4550c05..5bf4f68f3 100644--- a/web-app/src/locales/zh-CN/common.json+++ b/web-app/src/locales/zh-CN/common.json@@ -398,5 +398,12 @@"title": "线程已移除","description": "线程已成功从\"{{projectName}}\"中移除"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/locales/zh-TW/common.json b/web-app/src/locales/zh-TW/common.jsonindex 634c45891..c8ddcae64 100644--- a/web-app/src/locales/zh-TW/common.json+++ b/web-app/src/locales/zh-TW/common.json@@ -398,5 +398,12 @@"title": "執行緒已移除","description": "執行緒已成功從「{{projectName}}」中移除"}+ },+ "llamacppBusyOnExit": {+ "title": "llama.cpp is still busy",+ "description": "One or more models did not unload in time. Force-quitting will terminate llama.cpp and may interrupt active responses.",+ "forceQuit": "Force quit",+ "forcing": "Force quitting…",+ "shuttingDown": "Shutting down…"}}diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex 5a4c83b6f..490280674 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -30,6 +30,7 @@ import { LeftSidebar } from '@/components/left-sidebar'import { WindowControls } from '@/components/WindowControls'import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'import ErrorDialog from '@/containers/dialogs/ErrorDialog'+import LlamacppBusyOnExitDialog from '@/containers/dialogs/LlamacppBusyOnExitDialog'import MissingDependenciesDialog from '@/containers/dialogs/MissingDependenciesDialog'export const Route = createRootRoute({@@ -158,6 +159,7 @@ function RootLayout() {<ToolApproval /><AttachmentIngestionDialog /><ErrorDialog />+ <LlamacppBusyOnExitDialog /><MissingDependenciesDialog /><OutOfContextPromiseModal /></TranslationProvider>