Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): say the engine stopped instead of a raw connection error (#9181)
James Dam945c2ddd6843
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex a3134f4fd..1bba6adaa 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -47,7 +47,169 @@ async fn http_client() -> reqwest::Client {crate::engine::worker::loopback_client_builder().timeout(Duration::from_secs(600)).build()- .unwrap_or_else(|_| crate::engine::worker::loopback_client())+ .expect("a reqwest client without proxies builds")+}++/// True when a request to the worker never got a response: refused, reset, or+/// timed out before it answered. Only these say anything about the worker+/// itself -- an HTTP error status means it is alive and talking.+fn never_reached_worker(e: &reqwest::Error) -> bool {+ e.status().is_none() && (e.is_connect() || e.is_timeout() || e.is_request())+}++/// The error with its causes. reqwest's own text stops at "error sending+/// request for url (...)", and whether that was a refusal, a reset or a proxy+/// is only in the source chain.+fn error_chain(e: &dyn std::error::Error) -> String {+ let mut out = e.to_string();+ let mut source = e.source();+ while let Some(cause) = source {+ let text = cause.to_string();+ if !out.contains(&text) {+ out.push_str(": ");+ out.push_str(&text);+ }+ source = cause.source();+ }+ out+}++/// What became of the worker a failed request was aimed at.+#[derive(Debug)]+enum WorkerFate {+ /// Its process has exited, and this is how.+ Exited(crate::engine::worker::ExitReport),+ /// No longer the registered worker -- already reaped, or replaced -- so+ /// there is no exit status left to report.+ Gone,+ /// Still running, yet its port did not answer.+ Running,+}++/// How long a worker that looks alive is watched before it is called+/// unreachable. A worker that crashes mid-request has its sockets closed by the+/// kernel a moment before its exit can be collected, so the client can see the+/// reset first; without this grace that crash would be blamed on a VPN or a+/// proxy instead of being reported with its exit code and stderr.+const EXIT_GRACE: Duration = Duration::from_millis(500);+const EXIT_POLL: Duration = Duration::from_millis(50);++/// Checks the process, which is the one thing that tells the two causes of an+/// unreachable worker apart: a crash, or something between Jan and 127.0.0.1.+///+/// A worker found dead is reaped here, as `get_engine_info` does, so the next+/// load starts a fresh one instead of failing against the same closed port.+/// One still running is re-checked for up to [`EXIT_GRACE`] before it counts+/// as running; the engine lock is released between checks.+async fn worker_fate(state: &LlamacppState, port: u16) -> WorkerFate {+ let deadline = tokio::time::Instant::now() + EXIT_GRACE;+ loop {+ {+ let mut guard = state.engine.lock().await;+ let Some(handle) = guard.as_mut().filter(|h| h.port == port) else {+ return WorkerFate::Gone;+ };+ if handle.exited().is_some() {+ // Reaped under the lock, reported outside it: the report waits+ // briefly for the rest of the worker's stderr.+ let mut dead = guard.take().expect("checked above");+ drop(guard);+ let report = dead.exit_report().await.expect("it has exited");+ log::error!(+ "jan-llama-worker exited unexpectedly ({}); last output: {:?}",+ report.status,+ report.last_lines+ );+ return WorkerFate::Exited(report);+ }+ }+ if tokio::time::Instant::now() >= deadline {+ return WorkerFate::Running;+ }+ tokio::time::sleep(EXIT_POLL).await;+ }+}++/// The error for a worker that did not answer. `message` is the full English+/// account; `details` is the evidence the UI shows beside its localized text+/// for the code, so it leads with what a support thread would ask for.+fn unreachable_worker_error(port: u16, fate: WorkerFate, cause: &str) -> LlamacppError {+ match fate {+ WorkerFate::Exited(report) => {+ let mut details = report.status.clone();+ if !report.last_lines.is_empty() {+ details.push_str(". Last output: ");+ details.push_str(&report.last_lines.join(" / "));+ }+ LlamacppError::new(+ ErrorCode::EngineStopped,+ format!(+ "The llama.cpp engine stopped unexpectedly ({}).",+ report.status+ ),+ Some(details),+ )+ }+ WorkerFate::Gone => LlamacppError::new(+ ErrorCode::EngineStopped,+ "The llama.cpp engine stopped unexpectedly.".into(),+ Some(cause.to_string()),+ ),+ WorkerFate::Running => LlamacppError::new(+ ErrorCode::EngineUnreachable,+ format!(+ "The llama.cpp engine is running, but Jan cannot connect to it on \+ 127.0.0.1:{port}. A VPN, proxy or security software may be blocking \+ local connections."+ ),+ Some(format!("127.0.0.1:{port}: {cause}")),+ ),+ }+}++/// Turns a failed request to the worker into the error the user sees. A+/// request that never reached it is explained from the worker's own state;+/// anything else keeps `context` and reqwest's text as before.+async fn worker_request_error(+ state: &LlamacppState,+ port: u16,+ context: &str,+ e: reqwest::Error,+) -> LlamacppError {+ let generic = |e: &reqwest::Error| {+ LlamacppError::new(+ ErrorCode::InternalError,+ context.to_string(),+ Some(error_chain(e)),+ )+ };+ if !never_reached_worker(&e) {+ return generic(&e);+ }+ let fate = worker_fate(state, port).await;+ // A live worker that merely took too long -- a slow load, a busy machine+ // -- was reached; blaming a VPN or a proxy for that would send the user+ // looking in the wrong place. A connect timeout still counts as unreached.+ if matches!(fate, WorkerFate::Running) && e.is_timeout() && !e.is_connect() {+ return generic(&e);+ }+ unreachable_worker_error(port, fate, &error_chain(&e))+}++/// For the commands that return `String` errors: the structured error as JSON,+/// which `parseEngineError` on the web side recovers from a message string, so+/// it is shown from its code like any other engine error.+fn into_string_error(err: LlamacppError) -> String {+ serde_json::to_string(&err).unwrap_or(err.message)+}++/// [`into_string_error`] for a [`ServerError`]: an engine error keeps its code+/// as JSON, anything else is its plain text as before.+fn server_error_string(err: ServerError) -> String {+ match err {+ ServerError::Llamacpp(err) => into_string_error(err),+ other => other.to_string(),+ }}/// Payload for the `llamacpp-model-load-progress` event, mirrored from the@@ -301,6 +463,7 @@ async fn post_load<R: Runtime>(log::debug!("/models/sse did not answer within {SUBSCRIBE_TIMEOUT:?}; loading anyway");}+ let state: State<Arc<LlamacppState>> = app_handle.state();let client = http_client().await;let url = format!("http://127.0.0.1:{}/models/load", port);let resp = client@@ -308,19 +471,19 @@ async fn post_load<R: Runtime>(.bearer_auth(api_key).json(&ModelRequestBody { model: model_id }).send()- .await- .map_err(|e| {- ServerError::Llamacpp(LlamacppError::new(- ErrorCode::InternalError,- "Failed to call the engine's /models/load".into(),- Some(e.to_string()),- ))- });+ .await;let resp = match resp {Ok(r) => r,Err(e) => {progress_task.abort();- return Err(e);+ let err = worker_request_error(+ &state,+ port,+ "Failed to call the engine's /models/load",+ e,+ )+ .await;+ return Err(ServerError::Llamacpp(err));}};let status = resp.status();@@ -349,7 +512,7 @@ async fn post_load<R: Runtime>(// resolves on the first poll. It stays as the fallback for the case where// the answer said "already loading" and someone else owns the attempt.let result = tokio::select! {- r = wait_until_loaded(port, api_key, model_id, Duration::from_secs(600)) => r,+ r = wait_until_loaded(&state, port, api_key, model_id, Duration::from_secs(600)) => r,exit_code = sse_failure => Err(ServerError::Llamacpp(LlamacppError::new(ErrorCode::ModelLoadFailed,format!("Model {} failed to load", model_id),@@ -419,6 +582,7 @@ fn evaluate_load_poll(const STALE_FAILURE_GRACE: Duration = Duration::from_secs(20);async fn wait_until_loaded(+ state: &LlamacppState,port: u16,api_key: &str,model_id: &str,@@ -431,18 +595,16 @@ async fn wait_until_loaded(let mut saw_loading = false;loop {- let resp = client- .get(&url)- .bearer_auth(api_key)- .send()- .await- .map_err(|e| {- ServerError::Llamacpp(LlamacppError::new(- ErrorCode::InternalError,- "Failed to poll router /models".into(),- Some(e.to_string()),- ))- })?;+ // A worker that dies mid-load (a GPU init crash, antivirus) surfaces+ // here, as the next poll failing to connect.+ let resp = match client.get(&url).bearer_auth(api_key).send().await {+ Ok(r) => r,+ Err(e) => {+ let err =+ worker_request_error(state, port, "Failed to poll router /models", e).await;+ return Err(ServerError::Llamacpp(err));+ }+ };let json: serde_json::Value = resp.json().await.map_err(|e| {ServerError::Llamacpp(LlamacppError::new(@@ -573,18 +735,27 @@ async fn wait_until_unloaded(}}-async fn engine_loaded_model_ids(port: u16, api_key: &str) -> Result<Vec<String>, String> {+async fn engine_loaded_model_ids(+ state: &LlamacppState,+ port: u16,+ api_key: &str,+) -> Result<Vec<String>, String> {// Router-aware listing: `/models` (not `/v1/models`, which is OAI-compat// and returns a single element). Each entry has a `status` object whose// `value` is one of "loaded" / "loading" / "unloaded" / "sleeping".+ //+ // This is the first request of every model start (the frontend asks what+ // is loaded before loading), so a dead or unreachable worker is reported+ // from here more often than from anywhere else.let client = http_client().await;let url = format!("http://127.0.0.1:{}/models", port);- let resp = client- .get(&url)- .bearer_auth(api_key)- .send()- .await- .map_err(|e| format!("Failed to query /models: {}", e))?;+ let resp = match client.get(&url).bearer_auth(api_key).send().await {+ Ok(r) => r,+ Err(e) => {+ let err = worker_request_error(state, port, "Failed to query /models", e).await;+ return Err(into_string_error(err));+ }+ };if !resp.status().is_success() {return Err(format!("/models returned {}", resp.status()));}@@ -668,7 +839,7 @@ pub async fn ensure_session_ready<R: Runtime>(let (port, api_key, pid, _lease) = engine_endpoint(&app_handle).await?;post_load(&app_handle, port, &api_key, &model_id).await- .map_err(|e| e.to_string())?;+ .map_err(server_error_string)?;Ok(SessionInfo {pid: pid as i32,port: port as i32,@@ -687,7 +858,8 @@ pub async fn find_session_by_model<R: Runtime>(Ok(v) => v,Err(_) => return Ok(None),};- let ids = engine_loaded_model_ids(port, &api_key).await?;+ let state: State<Arc<LlamacppState>> = app_handle.state();+ let ids = engine_loaded_model_ids(&state, port, &api_key).await?;if ids.iter().any(|id| id == &model_id) {Ok(Some(SessionInfo {pid: pid as i32,@@ -709,7 +881,299 @@ pub async fn get_loaded_models<R: Runtime>(Ok(v) => v,Err(_) => return Ok(Vec::new()),};- engine_loaded_model_ids(port, &api_key).await+ let state: State<Arc<LlamacppState>> = app_handle.state();+ engine_loaded_model_ids(&state, port, &api_key).await+}++#[cfg(test)]+mod unreachable_worker_tests {+ use super::*;+ use crate::engine::worker::{self, ExitReport};+ use std::path::Path;++ fn json(err: &LlamacppError) -> serde_json::Value {+ serde_json::to_value(err).unwrap()+ }++ #[test]+ fn a_worker_that_exited_is_reported_as_stopped_with_its_exit_and_last_words() {+ let fate = WorkerFate::Exited(ExitReport {+ status: "exit code 0xC0000005".into(),+ last_lines: vec![+ "ggml_cuda_init: found 1 CUDA devices".into(),+ "CUDA error: unspecified launch failure".into(),+ ],+ });+ let err = unreachable_worker_error(51825, fate, "error sending request");+ let v = json(&err);+ assert_eq!(v["code"], "ENGINE_STOPPED");+ assert_eq!(+ err.message,+ "The llama.cpp engine stopped unexpectedly (exit code 0xC0000005)."+ );+ let details = err.details.unwrap();+ assert!(details.starts_with("exit code 0xC0000005"), "{details}");+ assert!(details.contains("unspecified launch failure"), "{details}");+ }++ #[test]+ fn a_silent_exit_reports_just_the_status() {+ let fate = WorkerFate::Exited(ExitReport {+ status: "killed by SIGKILL".into(),+ last_lines: vec![],+ });+ let err = unreachable_worker_error(1, fate, "refused");+ assert_eq!(err.details.as_deref(), Some("killed by SIGKILL"));+ }++ #[test]+ fn a_worker_already_reaped_is_still_reported_as_stopped() {+ let err = unreachable_worker_error(1, WorkerFate::Gone, "connection refused");+ assert_eq!(json(&err)["code"], "ENGINE_STOPPED");+ assert_eq!(err.details.as_deref(), Some("connection refused"));+ }++ // The case a VPN or proxy produces: nothing wrong with the engine, so the+ // message has to point away from it, at what sits in between.+ #[test]+ fn a_live_worker_that_cannot_be_reached_points_at_what_is_in_between() {+ let err = unreachable_worker_error(51825, WorkerFate::Running, "connection refused");+ assert_eq!(json(&err)["code"], "ENGINE_UNREACHABLE");+ assert!(err.message.contains("127.0.0.1:51825"), "{}", err.message);+ for hint in ["VPN", "proxy", "security software"] {+ assert!(err.message.contains(hint), "{}", err.message);+ }+ assert_eq!(+ err.details.as_deref(),+ Some("127.0.0.1:51825: connection refused")+ );+ }++ // `engineError.ts` recovers this from a message string, so it has to be+ // the same JSON a structured Tauri error would have been.+ #[test]+ fn a_string_error_carries_the_structured_error_as_json() {+ let err = unreachable_worker_error(1, WorkerFate::Gone, "x");+ let v: serde_json::Value = serde_json::from_str(&into_string_error(err)).unwrap();+ assert_eq!(v["code"], "ENGINE_STOPPED");+ assert!(v["message"].is_string());+ }++ // `ensure_session_ready` returns a String, and its load can fail with an+ // engine error; the code has to survive as JSON, not thiserror's Display.+ #[test]+ fn a_string_command_keeps_an_engine_errors_code() {+ let err = ServerError::Llamacpp(unreachable_worker_error(1, WorkerFate::Gone, "x"));+ let text = server_error_string(err);+ let v: serde_json::Value = serde_json::from_str(&text).expect(&text);+ assert_eq!(v["code"], "ENGINE_STOPPED");++ let other = server_error_string(ServerError::InvalidArgument("bad".into()));+ assert_eq!(other, "Invalid argument: bad");+ }++ /// A loopback port nothing listens on.+ fn closed_port() -> u16 {+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ l.local_addr().unwrap().port()+ }++ #[tokio::test]+ async fn a_refused_connection_counts_as_never_reaching_the_worker() {+ let port = closed_port();+ let e = worker::loopback_client()+ .get(format!("http://127.0.0.1:{port}/models"))+ .send()+ .await+ .expect_err("nothing listens there");+ assert!(never_reached_worker(&e), "{e:?}");+ let chain = error_chain(&e);+ assert!(chain.len() > e.to_string().len(), "the cause is appended: {chain}");+ }++ #[cfg(unix)]+ async fn spawn_fake(dir: &Path, body: &str) -> worker::WorkerHandle {+ let exe = worker::tests::fake_worker(dir, body);+ worker::tests::spawn_script(&exe)+ .await+ .expect("the fake worker prints a handshake")+ }++ // End to end through the command path: a worker that handshakes, then+ // crashes, is reported from its exit status and stderr rather than as+ // "error sending request for url", and is reaped so the next load can+ // start a fresh one.+ #[cfg(unix)]+ #[tokio::test]+ async fn listing_models_on_a_crashed_worker_says_the_engine_stopped() {+ let dir = tempfile::tempdir().unwrap();+ let port = closed_port();+ let handle = spawn_fake(+ dir.path(),+ &format!(+ "echo '{{\"port\":{port},\"pid\":'$$'}}'\n\+ echo 'CUDA error: unspecified launch failure' >&2\n\+ exit 3"+ ),+ )+ .await;+ let state = LlamacppState::new();+ *state.engine.lock().await = Some(handle);++ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ while state.engine.lock().await.as_mut().unwrap().exited().is_none() {+ assert!(std::time::Instant::now() < deadline, "fake worker did not exit");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ let err = engine_loaded_model_ids(&state, port, "k").await.unwrap_err();+ let v: serde_json::Value = serde_json::from_str(&err).expect(&err);+ assert_eq!(v["code"], "ENGINE_STOPPED", "{v}");+ assert!(v["message"].as_str().unwrap().contains("exit code 3"), "{v}");+ assert!(+ v["details"].as_str().unwrap().contains("unspecified launch failure"),+ "{v}"+ );+ assert!(state.engine.lock().await.is_none(), "a dead worker is reaped");++ let again = engine_loaded_model_ids(&state, port, "k").await.unwrap_err();+ assert!(again.contains("ENGINE_STOPPED"), "{again}");+ }++ // The crash reason is the last thing a dying worker writes, and its exit+ // can be collected before the stderr drain has read it. A request made the+ // moment the worker is seen dead must still carry that line. The line is+ // written by a child that outlives the worker by a moment, which makes+ // "exited, but stderr not yet read" certain instead of a race.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_request_right_after_a_crash_still_carries_its_last_words() {+ let dir = tempfile::tempdir().unwrap();+ let port = closed_port();+ let handle = spawn_fake(+ dir.path(),+ &format!(+ "echo '{{\"port\":{port},\"pid\":'$$'}}'\n\+ (sleep 0.1; echo 'CUDA error: unspecified launch failure' >&2) &\n\+ exit 3"+ ),+ )+ .await;+ let state = LlamacppState::new();+ *state.engine.lock().await = Some(handle);++ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ while state.engine.lock().await.as_mut().unwrap().exited().is_none() {+ assert!(std::time::Instant::now() < deadline, "fake worker did not exit");+ tokio::time::sleep(Duration::from_millis(1)).await;+ }++ let err = engine_loaded_model_ids(&state, port, "k").await.unwrap_err();+ let v: serde_json::Value = serde_json::from_str(&err).expect(&err);+ assert_eq!(v["code"], "ENGINE_STOPPED", "{v}");+ assert!(v["message"].as_str().unwrap().contains("exit code 3"), "{v}");+ assert!(+ v["details"].as_str().unwrap().contains("unspecified launch failure"),+ "{v}"+ );+ assert!(state.engine.lock().await.is_none(), "a dead worker is reaped");+ }++ // A worker that dies mid-request can drop its connection a moment before+ // its exit is collectable. Seen alive at first, it must still be reported+ // as stopped once it exits within the grace window, not as unreachable.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_worker_that_exits_just_after_the_failed_request_is_reported_as_stopped() {+ let dir = tempfile::tempdir().unwrap();+ let port = closed_port();+ let handle = spawn_fake(+ dir.path(),+ &format!(+ "echo '{{\"port\":{port},\"pid\":'$$'}}'\n\+ sleep 0.15\n\+ exit 3"+ ),+ )+ .await;+ let state = LlamacppState::new();+ *state.engine.lock().await = Some(handle);+ assert!(+ state.engine.lock().await.as_mut().unwrap().exited().is_none(),+ "still running when the request fails"+ );++ match worker_fate(&state, port).await {+ WorkerFate::Exited(report) => assert!(report.status.contains('3'), "{report:?}"),+ other => panic!("expected Exited, got {other:?}"),+ }+ assert!(state.engine.lock().await.is_none(), "a dead worker is reaped");+ }++ // A worker that accepts the connection but has not answered yet -- a long+ // model load -- is reachable, so the message must not blame a proxy.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_slow_answer_from_a_live_worker_is_not_blamed_on_the_connection() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ // Accepts and then says nothing, like a worker busy loading.+ let server = tokio::spawn(async move {+ let (_socket, _) = listener.accept().await.unwrap();+ tokio::time::sleep(Duration::from_secs(30)).await;+ });+ let dir = tempfile::tempdir().unwrap();+ let handle = spawn_fake(+ dir.path(),+ &format!("echo '{{\"port\":{port},\"pid\":'$$'}}'\nexec sleep 30"),+ )+ .await;+ let state = LlamacppState::new();+ *state.engine.lock().await = Some(handle);++ let e = worker::loopback_client_builder()+ .timeout(Duration::from_millis(300))+ .build()+ .unwrap()+ .get(format!("http://127.0.0.1:{port}/models"))+ .send()+ .await+ .expect_err("the server never answers");+ assert!(e.is_timeout(), "{e:?}");+ let err = worker_request_error(&state, port, "Failed to query /models", e).await;+ assert_eq!(json(&err)["code"], "INTERNAL_ERROR", "{err:?}");+ assert_eq!(err.message, "Failed to query /models");++ server.abort();+ state.engine.lock().await.take().unwrap().kill().await;+ }++ // A worker that is alive but whose port refuses: what a firewall, a VPN or+ // a proxy capturing loopback looks like from here.+ #[cfg(unix)]+ #[tokio::test]+ async fn listing_models_on_a_live_but_unreachable_worker_blames_the_connection() {+ let dir = tempfile::tempdir().unwrap();+ let port = closed_port();+ let handle = spawn_fake(+ dir.path(),+ &format!("echo '{{\"port\":{port},\"pid\":'$$'}}'\nexec sleep 30"),+ )+ .await;+ let state = LlamacppState::new();+ *state.engine.lock().await = Some(handle);++ let err = engine_loaded_model_ids(&state, port, "k").await.unwrap_err();+ let v: serde_json::Value = serde_json::from_str(&err).expect(&err);+ assert_eq!(v["code"], "ENGINE_UNREACHABLE", "{v}");+ assert!(+ v["message"].as_str().unwrap().contains(&format!("127.0.0.1:{port}")),+ "{v}"+ );++ let handle = state.engine.lock().await.take();+ assert!(handle.is_some(), "a live worker is left in place");+ handle.unwrap().kill().await;+ }}#[cfg(test)]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rsindex 0f9c5127e..6a08cf97f 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs@@ -9,9 +9,10 @@//! management, so a build that did not compile llama.cpp can still drive a//! worker shipped alongside it as a sidecar.-use std::collections::HashMap;+use std::collections::{HashMap, VecDeque};use std::path::{Path, PathBuf};-use std::process::Stdio;+use std::process::{ExitStatus, Stdio};+use std::sync::{Arc, Mutex};use std::time::Duration;use serde::{Deserialize, Serialize};@@ -210,6 +211,88 @@ pub type FaultCallback = std::sync::Arc<dyn Fn(RuntimeFault, String) + Send + Sy/// first one, not all of them.const FAULT_DEBOUNCE: Duration = Duration::from_secs(3);+/// How much of the worker's stderr is kept for an error message. A worker that+/// dies on GPU init or under antivirus prints its reason last, and the user+/// otherwise sees only a refused connection; a few lines are enough to name+/// the cause, and the full stream is already in the app log.+const STDERR_TAIL_LINES: usize = 4;++/// Per line, so one runaway line cannot crowd out the rest of the tail.+const STDERR_TAIL_LINE_CHARS: usize = 300;++/// How long a dead worker's stderr drain is given to finish before its tail is+/// read. A worker's last words are often its last write before it exits, so+/// its exit can be collected while they still sit unread in the pipe. The pipe+/// closes when the worker does, so this is normally a few milliseconds; the+/// bound is for a grandchild that still holds the pipe open.+const STDERR_DRAIN_WAIT: Duration = Duration::from_millis(300);++/// The last few stderr lines, shared between the drain task and the handle.+type StderrTail = Arc<Mutex<VecDeque<String>>>;++/// Lines that are kept out of the tail, though still logged. ggml prints one+/// `load_backend: loaded ... from <path>` per backend at start, which says+/// nothing about a crash and would fill the error with local paths.+fn is_tail_noise(line: &str) -> bool {+ line.starts_with("load_backend:")+}++fn remember_stderr_line(tail: &StderrTail, line: &str) {+ let line = line.trim();+ if line.is_empty() || is_tail_noise(line) {+ return;+ }+ let line: String = line.chars().take(STDERR_TAIL_LINE_CHARS).collect();+ let Ok(mut tail) = tail.lock() else { return };+ if tail.len() == STDERR_TAIL_LINES {+ tail.pop_front();+ }+ tail.push_back(line);+}++fn stderr_lines(tail: &StderrTail) -> Vec<String> {+ tail.lock().map(|t| t.iter().cloned().collect()).unwrap_or_default()+}++/// How a worker that is no longer running ended, for the error the user sees.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExitReport {+ /// From [`describe_exit`], e.g. `exit code 0xC0000005`.+ pub status: String,+ /// The worker's last stderr lines, oldest first. Empty if it said nothing.+ pub last_lines: Vec<String>,+}++/// An exit status in the form a user, or a search engine, will recognise.+///+/// Windows reports a crash as an NTSTATUS such as `0xC0000005` (access+/// violation) or `0xC0000409` (stack buffer overrun), which as the decimal+/// `i32` `code()` returns is a meaningless negative number. Unix reports a+/// crash as a signal and no code at all.+pub fn describe_exit(status: &ExitStatus) -> String {+ if let Some(code) = status.code() {+ let raw = code as u32;+ return if raw >= 0xC000_0000 {+ format!("exit code 0x{raw:08X}")+ } else {+ format!("exit code {code}")+ };+ }+ #[cfg(unix)]+ {+ use std::os::unix::process::ExitStatusExt;+ if let Some(sig) = status.signal() {+ // Signal numbers differ by platform (SIGBUS is 7 on Linux, 10 on+ // macOS), so the name comes from the platform's own table.+ return match nix::sys::signal::Signal::try_from(sig) {+ Ok(signal) => format!("killed by {}", signal.as_str()),+ Err(_) => format!("killed by signal {sig}"),+ };+ }+ }+ "no exit code".to_string()+}+/// Env var the worker reads its bearer token from. Never an argv flag: argv is/// world-readable via `ps` / `/proc/<pid>/cmdline`, and the supervisor logs it.pub const API_KEY_ENV: &str = "JAN_LLAMA_API_KEY";@@ -238,8 +321,14 @@ pub fn loopback_client_builder() -> reqwest::ClientBuilder {}/// [`loopback_client_builder`] with reqwest's defaults otherwise.+///+/// No fallback to `reqwest::Client::default()`: that would turn proxy lookup+/// back on, and it fails (by panicking) on the same TLS-backend error that+/// would make this build fail, which is all that can -- proxies are off.pub fn loopback_client() -> reqwest::Client {- loopback_client_builder().build().unwrap_or_default()+ loopback_client_builder()+ .build()+ .expect("a reqwest client without proxies builds")}/// How long to wait for the handshake. Generous because a cold page-cache read@@ -409,6 +498,9 @@ pub struct WorkerHandle {/// the worker that is actually running.pub devices: Option<Vec<DeviceIdentity>>,child: Child,+ stderr_tail: StderrTail,+ /// The task filling `stderr_tail`; it ends when the worker's stderr closes.+ stderr_drain: Option<tokio::task::JoinHandle<()>>,/// Declared after `child` so it is dropped after it: the graceful stop must/// get its turn before closing the job would kill the worker outright.#[cfg(windows)]@@ -482,6 +574,27 @@ impl WorkerHandle {pub fn exited(&mut self) -> Option<std::process::ExitStatus> {self.child.try_wait().ok().flatten()}++ /// None while still running, otherwise how it ended and what it last said.+ ///+ /// Waits up to [`STDERR_DRAIN_WAIT`] for the rest of its stderr first, so+ /// a crash reason written just before the exit is not missed.+ pub async fn exit_report(&mut self) -> Option<ExitReport> {+ let status = self.exited()?;+ wait_for_drain(self.stderr_drain.take()).await;+ Some(ExitReport {+ status: describe_exit(&status),+ last_lines: stderr_lines(&self.stderr_tail),+ })+ }+}++/// Gives a dead worker's stderr drain a bounded moment to read what is left.+/// On timeout the task is detached, not cancelled, and keeps logging.+async fn wait_for_drain(drain: Option<tokio::task::JoinHandle<()>>) {+ if let Some(drain) = drain {+ let _ = tokio::time::timeout(STDERR_DRAIN_WAIT, drain).await;+ }}/// Spawns the worker and waits for its handshake line.@@ -545,8 +658,11 @@ pub async fn spawn(.ok_or_else(|| WorkerError::Spawn("no stdout pipe".into()))?;// Drained on its own task: a full stderr pipe would otherwise block the// worker mid-generation, which is a hang with no error message.+ let stderr_tail = StderrTail::default();+ let mut stderr_drain = None;if let Some(stderr) = child.stderr.take() {- tokio::spawn(async move {+ let tail = stderr_tail.clone();+ stderr_drain = Some(tokio::spawn(async move {let mut lines = BufReader::new(stderr).lines();let mut reader = FaultReader::default();let mut last_fault_at: Option<tokio::time::Instant> = None;@@ -575,6 +691,7 @@ pub async fn spawn(};let Ok(Some(line)) = next else { break };log::debug!("jan-llama-worker: {line}");+ remember_stderr_line(&tail, &line);for (fault, text) in reader.feed(&line) {report(fault, text);}@@ -582,7 +699,7 @@ pub async fn spawn(if let Some((fault, line)) = reader.flush() {report(fault, line);}- });+ }));}let mut lines = BufReader::new(stdout).lines();@@ -598,11 +715,22 @@ pub async fn spawn(return Err(WorkerError::Handshake(e.to_string()));}Ok(Ok(None)) => {- // Closed stdout without a line: it died. The exit status is the- // most useful thing we can report.- let status = child.wait().await.ok();+ // Closed stdout without a line: it died. The exit status and its+ // last words are the most useful things we can report.+ let status = child+ .wait()+ .await+ .map(|s| describe_exit(&s))+ .unwrap_or_else(|e| format!("exit status unknown: {e}"));+ wait_for_drain(stderr_drain).await;+ let lines = stderr_lines(&stderr_tail);+ let output = if lines.is_empty() {+ String::new()+ } else {+ format!("; last output: {}", lines.join(" / "))+ };return Err(WorkerError::Handshake(format!(- "exited before serving (status {status:?})"+ "exited before serving ({status}){output}")));}Ok(Ok(Some(line))) => line,@@ -631,6 +759,8 @@ pub async fn spawn(cuda_toolkit: hs.cuda_toolkit,devices: hs.devices,child,+ stderr_tail,+ stderr_drain,#[cfg(windows)]_job: job,})@@ -665,7 +795,7 @@ pub fn sidecar_path() -> Option<PathBuf> {}#[cfg(test)]-mod tests {+pub(crate) mod tests {use super::*;// Restored with the marker lists intact: each entry came from a real crash@@ -972,6 +1102,124 @@ mod tests {assert!(matches!(err, WorkerError::Spawn(_)), "got {err:?}");}+ // The tail is what turns "connection refused" into a cause, so it must+ // keep the newest lines, and only a few of them.+ #[test]+ fn the_stderr_tail_keeps_the_last_few_nonblank_lines() {+ let tail = StderrTail::default();+ for i in 0..10 {+ remember_stderr_line(&tail, &format!("line {i}"));+ remember_stderr_line(&tail, " ");+ }+ let kept = stderr_lines(&tail);+ assert_eq!(kept.len(), STDERR_TAIL_LINES);+ assert_eq!(kept.last().map(String::as_str), Some("line 9"));++ remember_stderr_line(&tail, &"x".repeat(5000));+ assert_eq!(+ stderr_lines(&tail).last().map(|l| l.chars().count()),+ Some(STDERR_TAIL_LINE_CHARS)+ );+ }++ // Backend-load lines name no cause and carry local paths, so a crash+ // right after start must show what came before them, not them.+ #[test]+ fn backend_load_lines_stay_out_of_the_tail() {+ let tail = StderrTail::default();+ remember_stderr_line(&tail, "ggml_metal_init: error: failed to allocate");+ for b in ["MTL", "BLAS", "CPU"] {+ remember_stderr_line(+ &tail,+ &format!("load_backend: loaded {b} backend from /opt/jan/libggml-{b}.so"),+ );+ }+ assert_eq!(+ stderr_lines(&tail),+ vec!["ggml_metal_init: error: failed to allocate".to_string()]+ );+ }++ #[cfg(unix)]+ #[test]+ fn exit_statuses_read_the_way_users_search_for_them() {+ use std::os::unix::process::ExitStatusExt;+ // Unix wait status: the code in the high byte, a signal in the low bits.+ assert_eq!(describe_exit(&ExitStatus::from_raw(3 << 8)), "exit code 3");+ // From the platform's constants: SIGBUS is 7 on Linux but 10 on macOS,+ // where 7 is SIGEMT.+ use nix::sys::signal::Signal;+ for (sig, name) in [+ (Signal::SIGABRT, "SIGABRT"),+ (Signal::SIGBUS, "SIGBUS"),+ (Signal::SIGKILL, "SIGKILL"),+ (Signal::SIGSEGV, "SIGSEGV"),+ (Signal::SIGTERM, "SIGTERM"),+ ] {+ assert_eq!(+ describe_exit(&ExitStatus::from_raw(sig as i32)),+ format!("killed by {name}")+ );+ }+ assert_eq!(describe_exit(&ExitStatus::from_raw(100)), "killed by signal 100");+ }++ #[cfg(windows)]+ #[test]+ fn a_windows_crash_code_is_shown_as_its_ntstatus() {+ use std::os::windows::process::ExitStatusExt;+ assert_eq!(+ describe_exit(&ExitStatus::from_raw(0xC000_0005)),+ "exit code 0xC0000005"+ );+ assert_eq!(describe_exit(&ExitStatus::from_raw(1)), "exit code 1");+ }++ /// A stand-in worker: a shell script that ignores the worker flags.+ #[cfg(unix)]+ pub(crate) fn fake_worker(dir: &Path, body: &str) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let path = dir.join("fake-worker.sh");+ std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ path+ }++ /// `spawn`, retried while the script is "Text file busy". Another test+ /// forking at the moment the script was written inherits the write fd until+ /// its child execs, and executing a file open for writing is ETXTBSY.+ #[cfg(unix)]+ pub(crate) async fn spawn_script(exe: &Path) -> Result<WorkerHandle, WorkerError> {+ for _ in 0..50 {+ match spawn(exe, Path::new("/tmp/x.ini"), 0, "k", 1, 0, HashMap::new(), None).await {+ Err(WorkerError::Spawn(m)) if m.contains("os error 26") => {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ other => return other,+ }+ }+ panic!("{} stayed busy", exe.display());+ }++ // A GPU init crash happens before the handshake, so this message is all+ // the user gets; it has to carry the exit code and the reason, not a+ // Debug-printed `Option<ExitStatus>`.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_worker_that_dies_before_serving_reports_its_exit_and_last_words() {+ let dir = tempfile::tempdir().unwrap();+ let exe = fake_worker(+ dir.path(),+ "echo 'ggml_cuda_init: failed to initialize CUDA: unknown error' >&2\nexit 3",+ );+ let err = spawn_script(&exe)+ .await+ .expect_err("a worker that exits must fail the start");+ let msg = err.to_string();+ assert!(msg.contains("exit code 3"), "{msg}");+ assert!(msg.contains("failed to initialize CUDA"), "{msg}");+ }+#[tokio::test]async fn a_process_that_says_nothing_is_reported_not_awaited_forever() {// `true` exits immediately with no output, standing in for a workerdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rsindex e84e2f813..4e6bc6143 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs@@ -13,6 +13,12 @@ pub enum ErrorCode {// --- Memory Errors ---OutOfMemory,+ // --- Engine Process Errors ---+ /// The worker process exited on its own: a crash, or something killed it.+ EngineStopped,+ /// The worker is alive, but its loopback port cannot be reached.+ EngineUnreachable,+// --- Configuration Errors ---InvalidArgument,@@ -263,6 +269,8 @@ mod tests {(ErrorCode::MissingSharedLibrary, "MISSING_SHARED_LIBRARY"),(ErrorCode::GpuDriverTooOld, "GPU_DRIVER_TOO_OLD"),(ErrorCode::OutOfMemory, "OUT_OF_MEMORY"),+ (ErrorCode::EngineStopped, "ENGINE_STOPPED"),+ (ErrorCode::EngineUnreachable, "ENGINE_UNREACHABLE"),(ErrorCode::InvalidArgument, "INVALID_ARGUMENT"),(ErrorCode::IoError, "IO_ERROR"),(ErrorCode::InternalError, "INTERNAL_ERROR"),diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.tsindex d1184f42c..c47029330 100644--- a/web-app/src/lib/__tests__/engineError.test.ts+++ b/web-app/src/lib/__tests__/engineError.test.ts@@ -128,6 +128,36 @@ describe('describeEngineError', () => {expect(detail.endsWith('...')).toBe(true)})+ // `find_session_by_model` and `get_loaded_models` return String errors, so+ // the plugin sends the structured error as JSON inside the string, and the+ // extension rethrows it as `new Error(String(e))`. It has to come out as the+ // localized sentence plus the evidence, not as the raw JSON.+ it('describes an engine-stopped error that arrived inside an Error message', () => {+ const fromRust = JSON.stringify({+ code: 'ENGINE_STOPPED',+ message: 'The llama.cpp engine stopped unexpectedly (exit code 0xC0000005).',+ details: 'exit code 0xC0000005. Last output: CUDA error: unspecified launch failure',+ })++ const text = describeEngineError(new Error(fromRust))++ expect(mockT).toHaveBeenCalledWith('model-errors:engine.ENGINE_STOPPED')+ expect(text).toContain('0xC0000005')+ expect(text).not.toContain('"code"')+ })++ it('describes a live but unreachable engine from its code', () => {+ const text = describeEngineError(+ JSON.stringify({+ code: 'ENGINE_UNREACHABLE',+ details: '127.0.0.1:51825: error sending request: connection refused',+ })+ )++ expect(mockT).toHaveBeenCalledWith('model-errors:engine.ENGINE_UNREACHABLE')+ expect(text).toContain('127.0.0.1:51825')+ })+it('omits the detail wrapper when there is no detail', () => {describeEngineError({ code: 'IO_ERROR' })diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.tsindex f6f01166e..78dbdad2e 100644--- a/web-app/src/lib/engineError.ts+++ b/web-app/src/lib/engineError.ts@@ -12,6 +12,8 @@ export const ENGINE_ERROR_CODES = ['MISSING_SHARED_LIBRARY','GPU_DRIVER_TOO_OLD','OUT_OF_MEMORY',+ 'ENGINE_STOPPED',+ 'ENGINE_UNREACHABLE','INVALID_ARGUMENT','IO_ERROR','INTERNAL_ERROR',diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex b35adf5b5..a682a8ab3 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -66,6 +66,8 @@ const DYNAMIC_KEYS: Record<string, string[]> = {'engine.MISSING_SHARED_LIBRARY','engine.GPU_DRIVER_TOO_OLD','engine.OUT_OF_MEMORY',+ 'engine.ENGINE_STOPPED',+ 'engine.ENGINE_UNREACHABLE','engine.INVALID_ARGUMENT','engine.IO_ERROR','engine.INTERNAL_ERROR',diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.jsonindex 63520f5d8..5109e2bbc 100644--- a/web-app/src/locales/en/model-errors.json+++ b/web-app/src/locales/en/model-errors.json@@ -16,6 +16,8 @@"MISSING_SHARED_LIBRARY": "A library the engine needs is missing, so it cannot start.","GPU_DRIVER_TOO_OLD": "Your GPU driver is too old for this engine. Updating the driver, or switching to the CPU engine in Settings, will fix this.","OUT_OF_MEMORY": "There is not enough memory to run this model. A smaller model or a smaller context size usually helps.",+ "ENGINE_STOPPED": "The llama.cpp engine stopped unexpectedly. Sending the message again starts it again; if it keeps stopping, security software or the GPU driver may be the cause.",+ "ENGINE_UNREACHABLE": "The llama.cpp engine is running, but Jan cannot connect to it on this computer (127.0.0.1). A VPN, proxy or security software may be blocking local connections.","INVALID_ARGUMENT": "One of the model's settings is not valid.","IO_ERROR": "A file could not be read or written while starting the model.","INTERNAL_ERROR": "Something went wrong inside Jan while starting the model."