The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(engine): C81 log exit status, signal and last stderr lines of a dead llama-server
purpleabe073b94031
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 47c17893..50e82ae6 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -4539,7 +4539,10 @@ fn spawn_engine_attempt(cpu_fallback: flags.cpu_fallback,sanity_note: None,image_part_note: None,+ stderr: diagnostics.as_ref().map(|(buf, _)| std::sync::Arc::clone(buf)),});+ // A new engine: what the last one died of is history (C81).+ clear_last_engine_exit();}let outcome = wait_for_health_or_exit(state, port, health_timeout_for(model_path));@@ -4699,6 +4702,8 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,"port": DEFAULT_ENGINE_PORT,"model_path": null,"ctx": null,+ // C81: what the last engine died of, when it died on its own.+ "lastExit": last_engine_exit_note(),"cpuOnly": false,"gpuLayers": null,"sanityNote": null,@@ -5328,21 +5333,165 @@ pub async fn import_local_model(/// its process. Reaping here also leaves the state fit for the next start,/// which would otherwise find a stale child in the slot.pub(crate) fn reap_dead_engine(slot: &mut Option<BundledEngine>) -> bool {- let gone = match slot.as_mut() {+ reap_dead_engine_exit(slot).is_some()+}++/// How a sidecar ended, as far as the operating system and its own stderr say.+///+/// C81 (3.1.0): c1rrus, Linux/ROCm, the engine vanished mid-answer and the log+/// said only "the sidecar is gone". The status the reap had in its hand was+/// thrown away, and so was the stderr the drain thread kept collecting. Both+/// are now carried here, logged, and turned into one sentence for the UI.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct SidecarExit {+ pub code: Option<i32>,+ pub signal: Option<i32>,+ /// The last stderr lines, ANSI stripped. Empty when nothing was piped.+ pub stderr_tail: String,+ /// True for the `--embeddings` server, false for the chat engine.+ pub embed: bool,+}++/// How many stderr lines a death carries into the log and the event.+const EXIT_TAIL_LINES: usize = 20;++/// The reap, with what it found. `None` while the child lives, or when the+/// question could not be asked.+pub(crate) fn reap_dead_engine_exit(slot: &mut Option<BundledEngine>) -> Option<SidecarExit> {+ let status = match slot.as_mut() {// Ok(Some(status)) is an exited child; Ok(None) is a live one. An Err// means the question could not be asked, and a handle we cannot ask// about is not evidence of death, so it is left alone.- Some(e) => matches!(e.child.try_wait(), Ok(Some(_))),- None => false,+ Some(e) => match e.child.try_wait() {+ Ok(Some(status)) => status,+ _ => return None,+ },+ None => return None,};- if gone {- if let Some(mut e) = slot.take() {- let _ = e.child.wait();- // Said for both sidecars, so the wording names neither.- tracing::warn!(target: "engine", port = e.port, "the sidecar is gone, clearing the handle");+ let mut e = slot.take()?;+ let _ = e.child.wait();+ let exit = SidecarExit {+ code: status.code(),+ signal: unix_exit_signal(&status),+ stderr_tail: e+ .stderr+ .as_ref()+ .map(|buf| super::shell::captured_tail(buf, EXIT_TAIL_LINES))+ .unwrap_or_default(),+ embed: e.args.iter().any(|a| a == "--embeddings"),+ };+ // Said for both sidecars, so the wording names neither; the fields do.+ tracing::warn!(+ target: "engine",+ port = e.port,+ model = %e.model_path,+ sidecar = if exit.embed { SIDECAR_EMBED } else { SIDECAR_ENGINE },+ exit_code = exit.code.map(|c| c.to_string()).unwrap_or_else(|| "none".into()),+ signal = exit.signal.map(|s| s.to_string()).unwrap_or_else(|| "none".into()),+ cause = %exit_cause_words(exit.code, exit.signal),+ "the sidecar is gone, clearing the handle"+ );+ if !exit.stderr_tail.is_empty() {+ tracing::warn!(target: "engine", port = e.port, "last stderr lines of the sidecar:\n{}", exit.stderr_tail);+ }+ // The phone's in-process engine has no exit status of its own (its+ // `try_wait` reports a made-up success), so only a real process speaks.+ if !exit.embed && cfg!(desktop) {+ if let Ok(mut last) = LAST_ENGINE_EXIT.lock() {+ *last = Some(engine_exit_note(&exit));}}- gone+ Some(exit)+}++/// What the chat engine died of last, as the sentence the status shows while+/// no engine runs. Cleared by the next start.+static LAST_ENGINE_EXIT: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);++fn clear_last_engine_exit() {+ if let Ok(mut last) = LAST_ENGINE_EXIT.lock() {+ *last = None;+ }+}++pub(crate) fn last_engine_exit_note() -> Option<String> {+ LAST_ENGINE_EXIT.lock().ok().and_then(|g| g.clone())+}++/// The name and the usual cause of a POSIX signal, for the ones a model+/// server actually dies of.+fn signal_words(signal: i32) -> String {+ match signal {+ 9 => "SIGKILL, killed from outside; on Linux most often the system's out-of-memory killer".into(),+ 6 => "SIGABRT, the engine stopped itself on an internal error, often a graphics driver (ROCm/CUDA/Vulkan) error".into(),+ 11 => "SIGSEGV, a crash inside the engine or the graphics driver".into(),+ 4 => "SIGILL, the processor does not support an instruction the engine uses".into(),+ 7 => "SIGBUS, a memory access failed, e.g. the model file changed or the disk went away".into(),+ 15 => "SIGTERM, asked to stop from outside LU".into(),+ 2 => "SIGINT, interrupted".into(),+ n => format!("signal {n}"),+ }+}++/// Windows NTSTATUS crash codes, read back from `ExitStatus::code()`.+fn windows_code_words(code: i32) -> Option<&'static str> {+ match code as u32 {+ 0xC000_0005 => Some("access violation, a crash inside the engine or the graphics driver"),+ 0xC000_001D => Some("illegal instruction, the processor lacks AVX2"),+ 0xC000_0409 => Some("fail-fast abort, the engine stopped itself on an internal error"),+ 0xC000_00FD => Some("stack overflow"),+ 0xC000_0017 | 0xC000_012D => Some("out of memory"),+ 0xC000_0135 => Some("a DLL the engine needs was not found"),+ 0xC000_013A => Some("stopped with Ctrl+C or Ctrl+Break"),+ _ => None,+ }+}++/// "exit code 1", "signal 9 (SIGKILL, …)", "exit code -1073741819 (0xC0000005, access violation …)".+pub(crate) fn exit_cause_words(code: Option<i32>, signal: Option<i32>) -> String {+ match (code, signal) {+ (_, Some(sig)) => format!("signal {sig} ({})", signal_words(sig)),+ (Some(c), None) => match windows_code_words(c) {+ Some(w) => format!("exit code {c} (0x{:08X}, {w})", c as u32),+ None => format!("exit code {c}"),+ },+ (None, None) => "no exit code".into(),+ }+}++/// What the stderr tail says the trouble was, when it says something a user+/// can act on. Read from the end: the last words are the cause.+fn stderr_exit_hint(tail: &str) -> Option<&'static str> {+ let lower = tail.to_ascii_lowercase();+ if lower.contains("out of memory") || lower.contains("outofmemory") || lower.contains("failed to allocate") {+ return Some("The graphics card ran out of memory. A smaller model, a shorter context or fewer GPU layers usually fixes this.");+ }+ if lower.contains("rocm error") || lower.contains("hip error") || lower.contains("hiperror") {+ return Some("The ROCm driver reported an error. Updating the AMD driver or ROCm, or starting the engine on Vulkan, usually helps.");+ }+ if lower.contains("cuda error") {+ return Some("The NVIDIA driver reported an error. Updating the NVIDIA driver usually helps.");+ }+ if lower.contains("vk::") || lower.contains("vulkan error") || lower.contains("devicelost") || lower.contains("device lost") {+ return Some("The Vulkan driver lost the graphics card. Updating the graphics driver usually helps.");+ }+ None+}++/// The one sentence a user reads about an engine that stopped on its own.+pub(crate) fn engine_exit_note(exit: &SidecarExit) -> String {+ let head = format!(+ "The LU Engine stopped unexpectedly ({}).",+ exit_cause_words(exit.code, exit.signal)+ );+ let hint = stderr_exit_hint(&exit.stderr_tail).or(match (exit.code, exit.signal) {+ (_, Some(9)) => Some("This usually means the computer ran out of memory. A smaller model or a shorter context usually fixes this."),+ _ => None,+ });+ match hint {+ Some(h) => format!("{head} {h} It starts again with your next message; details are in the log."),+ None => format!("{head} It starts again with your next message; details are in the log."),+ }}/// What a status command should report for a sidecar slot: the port, the model@@ -5430,9 +5579,23 @@ pub(crate) const SIDECAR_WATCH_INTERVAL: Duration = Duration::from_millis(1500);/// Split out from the loop so the decision is testable without a Tauri app:/// the port has to be read BEFORE the reap, because the reap is what throws/// the handle away.-pub(crate) fn reaped_sidecar_port(slot: &mut Option<BundledEngine>) -> Option<u16> {- let port = slot.as_ref().map(|e| e.port);- if reap_dead_engine(slot) { port } else { None }+pub(crate) fn reaped_sidecar_port(slot: &mut Option<BundledEngine>) -> Option<(u16, SidecarExit)> {+ let port = slot.as_ref().map(|e| e.port)?;+ reap_dead_engine_exit(slot).map(|exit| (port, exit))+}++/// The payload of `SIDECAR_GONE_EVENT`. `message` is the sentence for the+/// chat engine; the embeddings server has no surface and gets none.+pub(crate) fn sidecar_gone_payload(sidecar: &str, port: u16, exit: &SidecarExit) -> serde_json::Value {+ serde_json::json!({+ "sidecar": sidecar,+ "port": port,+ "exitCode": exit.code,+ "signal": exit.signal,+ "cause": exit_cause_words(exit.code, exit.signal),+ "stderrTail": exit.stderr_tail,+ "message": if exit.embed || !cfg!(desktop) { None } else { Some(engine_exit_note(exit)) },+ })}/// Start the watch. One thread for both sidecars, for the life of the app.@@ -5445,22 +5608,19 @@ pub fn spawn_sidecar_watch(app: AppHandle) {loop {std::thread::sleep(SIDECAR_WATCH_INTERVAL);let state = app.state::<AppState>();- let mut gone: Vec<(&'static str, u16)> = Vec::new();+ let mut gone: Vec<(&'static str, u16, SidecarExit)> = Vec::new();if let Ok(mut guard) = state.bundled_engine.lock() {- if let Some(port) = reaped_sidecar_port(&mut guard) {- gone.push((SIDECAR_ENGINE, port));+ if let Some((port, exit)) = reaped_sidecar_port(&mut guard) {+ gone.push((SIDECAR_ENGINE, port, exit));}}if let Ok(mut guard) = state.bundled_embed.lock() {- if let Some(port) = reaped_sidecar_port(&mut guard) {- gone.push((SIDECAR_EMBED, port));+ if let Some((port, exit)) = reaped_sidecar_port(&mut guard) {+ gone.push((SIDECAR_EMBED, port, exit));}}- for (sidecar, port) in gone {- let _ = app.emit(SIDECAR_GONE_EVENT, serde_json::json!({- "sidecar": sidecar,- "port": port,- }));+ for (sidecar, port, exit) in gone {+ let _ = app.emit(SIDECAR_GONE_EVENT, sidecar_gone_payload(sidecar, port, &exit));}}});@@ -5632,6 +5792,7 @@ fn start_bundled_embed_blocking(cpu_fallback: false,sanity_note: None,image_part_note: None,+ stderr: diagnostics.as_ref().map(|(buf, _)| std::sync::Arc::clone(buf)),});if let Err(e) = wait_for_health(port, health_timeout_for(&model_path)) {@@ -6059,6 +6220,7 @@ fn load_into(// The engine inside the app loads no image part (the phone catalogue// names none), so there is nothing that could have stayed out.image_part_note: None,+ stderr: None,});tracing::info!(target: "engine", port, ctx = up.n_ctx, gpu_layers = up.gpu_layers, cpu_fallback = up.cpu_fallback, "the LU Engine is serving in-process");Ok(answer)@@ -6130,6 +6292,7 @@ fn start_bundled_embed_blocking(cpu_fallback: false,sanity_note: None,image_part_note: None,+ stderr: None,});// `low` and `critical` both take the embeddings model, so a kept warning// always means it is gone again.@@ -8930,6 +9093,7 @@ mod tests {cpu_fallback: false,sanity_note: None,image_part_note: None,+ stderr: None,});}@@ -9190,6 +9354,7 @@ mod tests {cpu_fallback: false,sanity_note: None,image_part_note: None,+ stderr: None,})}@@ -9382,8 +9547,8 @@ mod tests {let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);assert_eq!(- reaped_sidecar_port(&mut slot),- Some(DEFAULT_ENGINE_PORT),+ reaped_sidecar_port(&mut slot).map(|(port, exit)| (port, exit.code)),+ Some((DEFAULT_ENGINE_PORT, Some(0))),"the watch could not say which sidecar had gone",);assert!(slot.is_none(), "the handle survived its process");@@ -9392,6 +9557,107 @@ mod tests {assert_eq!(reaped_sidecar_port(&mut slot), None);}+ // ── C81: how the sidecar died, not only that it did ─────────────────────++ /// A real child that writes llama.cpp's last words to stderr and then+ /// dies of `how`, with its stderr drained the way the start drains it.+ #[cfg(unix)]+ fn dying_engine(script: &str, embed: bool) -> Option<BundledEngine> {+ let mut child = std::process::Command::new(crate::test_support::posix_shell())+ .args(["-c", script])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn a child that dies");+ let (buf, done) = super::super::shell::drain(child.stderr.take().unwrap());+ let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);+ if let Some(e) = slot.as_mut() {+ e.stderr = Some(buf);+ if embed {+ e.args = vec!["--embeddings".into()];+ }+ // The death has to have happened before the reap asks.+ let _ = e.child.wait();+ }+ let deadline = Instant::now() + Duration::from_secs(5);+ while !done.load(std::sync::atomic::Ordering::Acquire) && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(10));+ }+ slot+ }++ #[cfg(unix)]+ #[test]+ fn c1rrus_mid_answer_death_names_its_signal_and_its_last_lines() {+ // The c1rrus case: ROCm, the engine gone mid-answer. Before 3.1.0 the+ // log said "the sidecar is gone" and nothing else.+ let mut slot = dying_engine(+ "echo 'srv update_slots: decoding' >&2; \+ echo 'ggml_cuda_compute_forward: ROCm error: out of memory' >&2; \+ kill -ABRT $$",+ false,+ );+ let (port, exit) = reaped_sidecar_port(&mut slot).expect("reaped");+ assert_eq!(port, DEFAULT_ENGINE_PORT);+ assert_eq!(exit.signal, Some(6), "{exit:?}");+ assert_eq!(exit.code, None);+ assert!(exit.stderr_tail.ends_with("ROCm error: out of memory"), "{exit:?}");+ let note = engine_exit_note(&exit);+ assert!(note.contains("signal 6 (SIGABRT"), "{note}");+ assert!(note.contains("ran out of memory"), "{note}");+ let payload = sidecar_gone_payload(SIDECAR_ENGINE, port, &exit);+ assert_eq!(payload["signal"], 6);+ assert_eq!(payload["message"], serde_json::Value::String(note));+ }++ #[cfg(unix)]+ #[test]+ fn a_sigkill_without_words_points_at_memory() {+ let mut slot = dying_engine("kill -KILL $$", false);+ let (_, exit) = reaped_sidecar_port(&mut slot).expect("reaped");+ assert_eq!(exit.signal, Some(9));+ assert!(exit.stderr_tail.is_empty());+ let note = engine_exit_note(&exit);+ assert!(note.contains("SIGKILL") && note.contains("ran out of memory"), "{note}");+ }++ #[cfg(unix)]+ #[test]+ fn the_embeddings_server_is_logged_but_tells_the_chat_nothing() {+ let mut slot = dying_engine("echo 'bye' >&2; exit 3", true);+ let (port, exit) = reaped_sidecar_port(&mut slot).expect("reaped");+ assert!(exit.embed);+ assert_eq!(exit.code, Some(3));+ assert_eq!(exit.stderr_tail, "bye");+ let payload = sidecar_gone_payload(SIDECAR_EMBED, port, &exit);+ assert!(payload["message"].is_null(), "{payload}");+ assert_eq!(payload["cause"], "exit code 3");+ }++ #[test]+ fn exit_causes_read_like_words_on_every_platform() {+ assert_eq!(exit_cause_words(Some(1), None), "exit code 1");+ assert_eq!(exit_cause_words(None, None), "no exit code");+ assert!(exit_cause_words(None, Some(11)).starts_with("signal 11 (SIGSEGV"));+ assert!(exit_cause_words(None, Some(42)).starts_with("signal 42 (signal 42"));+ // Windows hands NTSTATUS back as a negative i32.+ assert_eq!(+ exit_cause_words(Some(0xC000_0005u32 as i32), None),+ "exit code -1073741819 (0xC0000005, access violation, a crash inside the engine or the graphics driver)",+ );+ assert!(exit_cause_words(Some(ILLEGAL_INSTRUCTION_EXIT_CODE), None).contains("AVX2"));+ // A driver error in the tail beats the generic signal guess.+ let exit = SidecarExit { code: None, signal: Some(9), stderr_tail: "CUDA error: an illegal memory access".into(), embed: false };+ assert!(engine_exit_note(&exit).contains("NVIDIA driver"));+ // Nothing to say beyond the cause: no invented advice.+ let exit = SidecarExit { code: Some(1), signal: None, stderr_tail: "something".into(), embed: false };+ assert_eq!(+ engine_exit_note(&exit),+ "The LU Engine stopped unexpectedly (exit code 1). It starts again with your next message; details are in the log.",+ );+ }+#[test]fn the_watch_stays_quiet_about_a_sidecar_that_is_still_running() {// Negative control. Without it the test above would pass on a watchdiff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex f523b589..33fc5634 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -49,10 +49,31 @@ pub(crate) fn cwd_in_workspace(cwd: Option<&str>, base: &Path) -> PathBuf {/// is still read off the pipe — it has to be, or the child blocks — but dropped.const MAX_CAPTURE: usize = 256 * 1024;+/// So viel vom ENDE einer Ausgabe bleibt immer erhalten (C81). `kept` haelt+/// den Anfang und hoert nach MAX_CAPTURE auf; ein llama-server, der nach+/// Stunden stirbt, hat seine letzten Worte aber weit dahinter geschrieben.+const TAIL_CAPTURE: usize = 16 * 1024;+#[derive(Default)]pub(crate) struct Captured {kept: Vec<u8>,total: usize,+ /// Die letzten TAIL_CAPTURE Bytes, laufend nachgeschoben.+ tail: std::collections::VecDeque<u8>,+}++impl Captured {+ fn push(&mut self, bytes: &[u8]) {+ self.total += bytes.len();+ let room = MAX_CAPTURE.saturating_sub(self.kept.len());+ if room > 0 {+ self.kept.extend_from_slice(&bytes[..bytes.len().min(room)]);+ }+ let bytes = &bytes[bytes.len().saturating_sub(TAIL_CAPTURE)..];+ let overflow = (self.tail.len() + bytes.len()).saturating_sub(TAIL_CAPTURE);+ self.tail.drain(..overflow);+ self.tail.extend(bytes.iter().copied());+ }}/// Drain a child pipe on its own thread. The pipe MUST be read while the process@@ -72,11 +93,7 @@ pub(crate) fn drain(mut pipe: impl Read + Send + 'static) -> (Arc<Mutex<CapturedOk(0) | Err(_) => break,Ok(n) => {if let Ok(mut c) = sink.lock() {- c.total += n;- let room = MAX_CAPTURE.saturating_sub(c.kept.len());- if room > 0 {- c.kept.extend_from_slice(&chunk[..n.min(room)]);- }+ c.push(&chunk[..n]);}}}@@ -166,6 +183,68 @@ pub(crate) fn captured_text(buf: &Arc<Mutex<Captured>>) -> String {text}+/// Die letzten `max_lines` nicht leeren Zeilen einer Ausgabe, aus dem+/// Ringpuffer statt aus dem Anfang (C81). Die erste Zeile im Puffer kann+/// abgeschnitten sein und faellt deshalb weg, sobald der Puffer voll war.+pub(crate) fn captured_tail(buf: &Arc<Mutex<Captured>>, max_lines: usize) -> String {+ let c = match buf.lock() {+ Ok(c) => c,+ Err(poisoned) => poisoned.into_inner(),+ };+ let bytes: Vec<u8> = c.tail.iter().copied().collect();+ let wrapped = c.total > c.tail.len();+ drop(c);+ let text = strip_ansi(&String::from_utf8_lossy(&bytes));+ let mut lines: Vec<&str> = text.lines().collect();+ if wrapped && !lines.is_empty() {+ lines.remove(0);+ }+ let lines: Vec<&str> = lines.into_iter().map(str::trim_end).filter(|l| !l.trim().is_empty()).collect();+ let start = lines.len().saturating_sub(max_lines);+ lines[start..].join("\n")+}++#[cfg(test)]+mod captured_tail_tests {+ use super::*;++ #[test]+ fn the_tail_keeps_the_last_words_long_after_the_head_stopped() {+ let buf = Arc::new(Mutex::new(Captured::default()));+ {+ let mut c = buf.lock().unwrap();+ // Mehr als MAX_CAPTURE an Geplapper, dann der Absturz.+ let line = b"slot update_slots: id 0 | task 7 | prompt processing progress\n";+ let mut written = 0;+ while written < MAX_CAPTURE + 64 * 1024 {+ c.push(line);+ written += line.len();+ }+ c.push(b"ggml_cuda_compute_forward: ROCm error: out of memory\n");+ c.push(b"\x1b[31mGGML_ABORT\x1b[0m failed\n");+ }+ let tail = captured_tail(&buf, 2);+ assert_eq!(tail, "ggml_cuda_compute_forward: ROCm error: out of memory\nGGML_ABORT failed");+ // Der Kopf bleibt, wie er war: abgeschnitten nach MAX_CAPTURE.+ assert!(captured_text(&buf).contains("[output truncated"));+ }++ #[test]+ fn a_short_output_is_all_tail_and_a_wrapped_first_line_is_dropped() {+ let buf = Arc::new(Mutex::new(Captured::default()));+ buf.lock().unwrap().push(b"one\n\ntwo\nthree\n");+ assert_eq!(captured_tail(&buf, 5), "one\ntwo\nthree");+ assert_eq!(captured_tail(&buf, 1), "three");+ let big = Arc::new(Mutex::new(Captured::default()));+ let mut chunk = vec![b'x'; TAIL_CAPTURE];+ chunk.extend_from_slice(b"\nlast\n");+ big.lock().unwrap().push(&chunk);+ // Die angeschnittene x-Zeile ist kein ganzer Satz und faellt weg.+ assert_eq!(captured_tail(&big, 5), "last");+ assert_eq!(captured_tail(&Arc::new(Mutex::new(Captured::default())), 5), "");+ }+}+/// Every process descending from `root`, deepest last.pub(crate) fn descendants(root: u32, sys: &sysinfo::System) -> Vec<u32> {let mut children: std::collections::HashMap<u32, Vec<u32>> = std::collections::HashMap::new();diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex dc0ceb96..44279efb 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -96,6 +96,10 @@ pub struct BundledEngine {/// part IS the answer to a request for this model, and must not be torn/// down because the part is still on disk.pub image_part_note: Option<&'static str>,+ /// The process's stderr as it is being drained, so a death long after the+ /// start can still name its last lines (C81). `None` where nothing was+ /// piped (the phone's in-process engine, tests).+ pub stderr: Option<std::sync::Arc<std::sync::Mutex<crate::commands::shell::Captured>>>,}#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]diff --git a/src/api/engine.ts b/src/api/engine.tsindex 3bd5097b..f1b86deb 100644--- a/src/api/engine.ts+++ b/src/api/engine.ts@@ -119,6 +119,9 @@ export interface EngineStatus {fitActions?: import('../lib/engine-fit').FitAction[] | null/** MoE layers whose experts stay on the processor (`--n-cpu-moe`). */cpuMoe?: number | null+ /** C81 (3.1.0): while no engine runs, what the last one died of when it+ * died on its own (exit code or signal, and the likely cause). */+ lastExit?: string | null/** The context the start asked for; `ctx` is what the VRAM plan gave a* context nobody chose (3.0.8, A25). */ctxRequested?: number | nulldiff --git a/src/components/settings/BuiltinEngineSettings.tsx b/src/components/settings/BuiltinEngineSettings.tsxindex 39345a69..bc7a0aaf 100644--- a/src/components/settings/BuiltinEngineSettings.tsx+++ b/src/components/settings/BuiltinEngineSettings.tsx@@ -127,6 +127,12 @@ export function BuiltinEngineSettings() {'Engine not running, settings apply automatically on the next start.')}</div>+ {/* C81 (3.1.0): the last engine died on its own; say how, until the next start. */}+ {!running && status?.lastExit ? (+ <div className="t-micro text-red-600 dark:text-red-400 leading-relaxed" data-testid="builtin-engine-last-exit">+ {status.lastExit}+ </div>+ ) : null}{/* A13: which port the engine really holds. It starts its walk at 8127and takes the next free one when that is held, and until now the onlyplace that said so was the log. */}diff --git a/src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.ts b/src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.tsindex cf53bf5b..b3efabf0 100644--- a/src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.ts+++ b/src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.ts@@ -108,6 +108,20 @@ describe('an engine killed from outside while the panel stands open', () => {expect(document.body.textContent).toContain('Engine not running')})+ // C81 (3.1.0): and it says what the engine died of, from Rust's own reading+ // of the exit status and the last stderr lines.+ it('names the cause of the death while no engine runs', async () => {+ await panelWithARunningEngine()+ const why = 'The LU Engine stopped unexpectedly (signal 9 (SIGKILL, killed from outside)).'+ bundledEngineStatus.mockResolvedValue({ ...DEAD, lastExit: why })+ await fireSidecarGone()+ expect(screen.getByTestId('builtin-engine-last-exit').textContent).toBe(why)+ // Gone again once an engine runs.+ bundledEngineStatus.mockResolvedValue({ ...RUNNING, lastExit: why })+ await act(async () => { await vi.advanceTimersByTimeAsync(ENGINE_STATUS_POLL_MS + 100) })+ expect(screen.queryByTestId('builtin-engine-last-exit')).toBeNull()+ })+// NEGATIVE CONTROL: the panel must not simply decay to "not running". An// engine that is still there stays on screen however long the section is// open, or the fix would have traded a stale display for a wrong one.diff --git a/src/hooks/useBuiltinEngineStatus.ts b/src/hooks/useBuiltinEngineStatus.tsindex 9e37125e..87b20fa0 100644--- a/src/hooks/useBuiltinEngineStatus.ts+++ b/src/hooks/useBuiltinEngineStatus.ts@@ -19,6 +19,7 @@ import { useEffect, useRef, useState } from 'react'import { bundledEngineStatus, type EngineStatus } from '../api/engine'import { isTauri } from '../api/backend'import { onAppForeground } from '../lib/app-lifecycle'+import { noteSidecarGone } from '../lib/engine-exit-notice'/** Rust meldet den eingesammelten toten Griff hierunter. */export const SIDECAR_GONE_EVENT = 'lu-sidecar-gone'@@ -64,7 +65,7 @@ export function useBuiltinEngineStatus(pausiert?: () => boolean): EngineStatusViconst timer = setInterval(read, ENGINE_STATUS_POLL_MS)let unlisten: (() => void) | null = nullvoid import('@tauri-apps/api/event')- .then(({ listen }) => listen(SIDECAR_GONE_EVENT, () => read()))+ .then(({ listen }) => listen(SIDECAR_GONE_EVENT, (event) => { noteSidecarGone(event.payload); read() })).then((off) => { if (alive) unlisten = off; else off() }).catch(() => {})// After a stay in the background the interval was frozen and the enginediff --git a/src/lib/__tests__/engine-exit-notice.test.ts b/src/lib/__tests__/engine-exit-notice.test.tsnew file mode 100644index 00000000..b4e1fb9c--- /dev/null+++ b/src/lib/__tests__/engine-exit-notice.test.ts@@ -0,0 +1,38 @@+/**+ * C81 (3.1.0): an engine that dies on its own is named, with its cause, above+ * the chat. Negative control: return null from engineStoppedMessage and the+ * first case turns red.+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { engineStoppedMessage, noteSidecarGone, ENGINE_STOPPED_NOTICE_MS } from '../engine-exit-notice'+import { useChatNoticeStore } from '../../stores/chatNoticeStore'++const SENTENCE = 'The LU Engine stopped unexpectedly (signal 6 (SIGABRT, …)). The graphics card ran out of memory.'++beforeEach(() => useChatNoticeStore.getState().clear())++describe('C81: the engine death reaches the chat', () => {+ it('shows the sentence Rust sent for the chat engine', () => {+ noteSidecarGone({ sidecar: 'engine', port: 8127, signal: 6, message: SENTENCE })+ const n = useChatNoticeStore.getState().notices+ expect(n).toHaveLength(1)+ expect(n[0]).toMatchObject({ id: 'engine-stopped', text: SENTENCE, ton: 'fehler' })+ expect(ENGINE_STOPPED_NOTICE_MS).toBeGreaterThanOrEqual(30_000)+ })++ it('says nothing for the embeddings server, an old payload or garbage', () => {+ noteSidecarGone({ sidecar: 'embed', port: 8128, message: null })+ noteSidecarGone({ sidecar: 'engine', port: 8127 })+ noteSidecarGone(null)+ noteSidecarGone('engine')+ expect(useChatNoticeStore.getState().notices).toHaveLength(0)+ expect(engineStoppedMessage({ sidecar: 'engine', message: ' ' })).toBeNull()+ })++ it('a second death replaces the line instead of stacking', () => {+ noteSidecarGone({ sidecar: 'engine', message: 'first' })+ noteSidecarGone({ sidecar: 'engine', message: 'second' })+ const n = useChatNoticeStore.getState().notices+ expect(n.map((x) => x.text)).toEqual(['second'])+ })+})diff --git a/src/lib/engine-exit-notice.ts b/src/lib/engine-exit-notice.tsnew file mode 100644index 00000000..e6cdd371--- /dev/null+++ b/src/lib/engine-exit-notice.ts@@ -0,0 +1,29 @@+/**+ * C81 (3.1.0): the LU Engine died on its own, and now the app says how.+ *+ * c1rrus (Linux, ROCm) had the engine vanish in the middle of an answer, and+ * neither the log nor the window said why. Rust now reads the exit code or+ * signal and the last stderr lines when it reaps the process, and sends one+ * sentence with the `lu-sidecar-gone` event (`message`, chat engine only).+ * This shows that sentence above the chat history, where the other chat+ * notices live (stores/chatNoticeStore.ts).+ */+import { useChatNoticeStore } from '../stores/chatNoticeStore'++/** Long enough to read a two-sentence cause, short enough not to linger. */+export const ENGINE_STOPPED_NOTICE_MS = 60_000++/** Pure: the sentence in a `lu-sidecar-gone` payload, or null. */+export function engineStoppedMessage(payload: unknown): string | null {+ if (!payload || typeof payload !== 'object') return null+ const p = payload as { sidecar?: unknown; message?: unknown }+ if (p.sidecar !== 'engine') return null+ return typeof p.message === 'string' && p.message.trim() ? p.message.trim() : null+}++/** Called for every `lu-sidecar-gone`; shows the sentence when there is one. */+export function noteSidecarGone(payload: unknown): void {+ const message = engineStoppedMessage(payload)+ if (!message) return+ useChatNoticeStore.getState().show('engine-stopped', message, 'fehler', ENGINE_STOPPED_NOTICE_MS)+}diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.tsindex a4793e5c..0b62df3c 100644--- a/src/stores/chatNoticeStore.ts+++ b/src/stores/chatNoticeStore.ts@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */-export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save'+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'engine-stopped'export interface ChatNotice {id: ChatNoticeId