Skip to content

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.

fix(engine): eine abgeschossene Engine faellt der Anzeige auf, ohne dass jemand fragt

purple7d2c72854857
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index d6ed1c7e..53247d27 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -19,7 +19,7 @@ use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde::Serialize;
-use tauri::{AppHandle, Manager, State};
+use tauri::{AppHandle, Emitter, Manager, State};
use crate::state::{AppState, BundledEngine};
@@ -1953,6 +1953,77 @@ pub(crate) fn live_sidecar(slot: &mut Option<BundledEngine>) -> Option<(u16, Str
slot.as_ref().map(|e| (e.port, e.model_path.clone(), e.ctx))
}
+// ── The watch that tells the UI a sidecar died ───────────────────────────────
+//
+// A16, Windows counter-check 02.09.: `reap_dead_engine` was only ever reached
+// by someone ASKING, and Settings asks once, when the section is mounted. So
+// killing lu-llama-server with the panel open left "Engine running / Port:
+// 8127" on screen for 30 seconds and counting; folding the section and
+// unfolding it was the only thing that corrected it, because that asked again.
+// Reaping on a timer turns the same knowledge into something the app says by
+// itself, and the event it emits is what lets the panel be right without
+// polling the backend into the ground.
+
+/// The event a sidecar's death raises. Payload: `{ sidecar, port }`.
+pub const SIDECAR_GONE_EVENT: &str = "lu-sidecar-gone";
+
+/// Which sidecar the event is about. The chat engine has a display in
+/// Settings; the embeddings server has none, and is reported anyway so a
+/// future display, or a log reader, gets the same answer for both.
+pub(crate) const SIDECAR_ENGINE: &str = "engine";
+pub(crate) const SIDECAR_EMBED: &str = "embed";
+
+/// How often the watch looks.
+///
+/// The requirement is that the display is right within five seconds of a kill,
+/// and the UI has its own poll behind this event, so the budget is shared. A
+/// second and a half costs two `try_wait` calls and a mutex each, which is
+/// nothing next to the health probe the status command already makes on every
+/// poll, and leaves the worst case (the event lost, the poll doing the work)
+/// comfortably inside the five.
+pub(crate) const SIDECAR_WATCH_INTERVAL: Duration = Duration::from_millis(1500);
+
+/// Reap one slot and, when something really was reaped, say which port it held.
+///
+/// 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 }
+}
+
+/// Start the watch. One thread for both sidecars, for the life of the app.
+///
+/// The two slots are locked one after the other and never together: everything
+/// else in this file takes exactly one of them at a time, and a watch that took
+/// both would be the only place in the process able to build a lock cycle.
+pub fn spawn_sidecar_watch(app: AppHandle) {
+ std::thread::spawn(move || {
+ loop {
+ std::thread::sleep(SIDECAR_WATCH_INTERVAL);
+ let state = app.state::<AppState>();
+ let mut gone: Vec<(&'static str, u16)> = 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 Ok(mut guard) = state.bundled_embed.lock() {
+ if let Some(port) = reaped_sidecar_port(&mut guard) {
+ gone.push((SIDECAR_EMBED, port));
+ }
+ }
+ for (sidecar, port) in gone {
+ let _ = app.emit(SIDECAR_GONE_EVENT, serde_json::json!({
+ "sidecar": sidecar,
+ "port": port,
+ }));
+ }
+ }
+ });
+}
+
pub(crate) fn stop_engine_locked(state: &AppState) -> bool {
let mut guard = state.bundled_engine.lock().unwrap();
if let Some(mut engine) = guard.take() {
@@ -3051,6 +3122,69 @@ mod tests {
let _ = engine.child.wait();
}
+ // ── A16: the watch that says a sidecar died without being asked ─────────
+
+ #[test]
+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]
+ fn the_watch_names_the_port_of_a_sidecar_that_died() {
+ // What the loop does once per tick. The port has to come out of the
+ // slot before the reap clears it, which is the whole reason this is a
+ // function and not two lines inside the thread.
+ let mut child = std::process::Command::new("sh")
+ .args(["-c", "exit 0"])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn a child that exits immediately");
+ let _ = child.wait();
+ let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);
+
+ assert_eq!(
+ reaped_sidecar_port(&mut slot),
+ Some(DEFAULT_ENGINE_PORT),
+ "the watch could not say which sidecar had gone",
+ );
+ assert!(slot.is_none(), "the handle survived its process");
+ // A second tick has nothing to report: the event fires once, not on
+ // every tick for the rest of the session.
+ assert_eq!(reaped_sidecar_port(&mut slot), None);
+ }
+
+ #[test]
+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]
+ fn the_watch_stays_quiet_about_a_sidecar_that_is_still_running() {
+ // Negative control. Without it the test above would pass on a watch
+ // that announced a death on every tick and cleared the slot with it,
+ // which would take the running engine off the screen.
+ let child = std::process::Command::new("sh")
+ .args(["-c", "sleep 30"])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn a long lived child");
+ let mut slot = engine_around(child, DEFAULT_EMBED_PORT);
+
+ assert_eq!(reaped_sidecar_port(&mut slot), None, "a live sidecar was declared dead");
+ assert!(slot.is_some());
+
+ let mut engine = slot.take().unwrap();
+ let _ = engine.child.kill();
+ let _ = engine.child.wait();
+ }
+
+ #[test]
+ fn the_watch_looks_often_enough_to_beat_the_five_second_promise() {
+ // The display has to be right within five seconds of a kill. The tick
+ // is the coarse half of that budget (the UI's own poll is the other),
+ // so a tick slower than the promise would break it silently.
+ assert!(
+ SIDECAR_WATCH_INTERVAL <= Duration::from_secs(2),
+ "the sidecar watch ticks too slowly to keep the five second promise",
+ );
+ }
+
#[test]
fn an_empty_slot_has_nothing_to_reap() {
let mut slot: Option<BundledEngine> = None;
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index abfd5085..e396258f 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -406,6 +406,14 @@ fn main() {
});
}
+ // ─── The watch on the two llama-server sidecars ───
+ // A16: a sidecar killed from outside (Task Manager, a crash, a
+ // driver reset) was only noticed when something asked for its
+ // status, and Settings asks once per mount. The watch asks on a
+ // timer and emits `lu-sidecar-gone`, so the panel can be right
+ // while it is standing open.
+ commands::engine::spawn_sidecar_watch(app.handle().clone());
+
// ─── System Tray ───
let show = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
diff --git a/src/components/settings/BuiltinEngineSettings.tsx b/src/components/settings/BuiltinEngineSettings.tsx
index ddb8c0e9..59734ee0 100644
--- a/src/components/settings/BuiltinEngineSettings.tsx
+++ b/src/components/settings/BuiltinEngineSettings.tsx
@@ -5,7 +5,7 @@
// (same path the model picker uses); when stopped, the next start picks the
// values up automatically.
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { Loader2, AlertTriangle, Check, Zap } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
import { bundledEngineStatus, swapBundledModel, ENGINE_PORT, type EngineStatus } from '../../api/engine'
@@ -32,6 +32,30 @@ function modelNameFromPath(path: string | null): string | null {
return path.split(/[\\/]/).pop()?.replace(/\.gguf$/i, '') ?? null
}
+/**
+ * The Rust event a sidecar's death raises (commands/engine.rs).
+ *
+ * A16, Windows counter-check 02.09.: the panel read the engine status exactly
+ * once, on mount. Kill lu-llama-server with the section standing open and the
+ * line said "Engine running · Port: 8127" for the full thirty seconds the
+ * counter-check watched, and only folding the section and unfolding it put it
+ * right, because that mounted the panel again and asked again. A display that
+ * is wrong about a process that is gone is worse than no display: it is the
+ * answer to "why does chat not work" and it is the wrong answer.
+ */
+export const SIDECAR_GONE_EVENT = 'lu-sidecar-gone'
+
+/**
+ * The fallback poll, for the case where the event never lands.
+ *
+ * The event is the fast path and normally does the whole job. This is the belt:
+ * an event lost in a reload, a listener that failed to register, a sidecar the
+ * watch has not reached yet. Three seconds keeps the worst case inside the five
+ * the requirement names, and the call behind it is the same status read the
+ * panel already makes on mount.
+ */
+export const ENGINE_STATUS_POLL_MS = 3_000
+
export function BuiltinEngineSettings() {
const tuning = useSettingsStore((s) => s.settings.builtinEngine)
const updateSettings = useSettingsStore((s) => s.updateSettings)
@@ -42,9 +66,34 @@ export function BuiltinEngineSettings() {
const [applied, setApplied] = useState(false)
const [error, setError] = useState<string | null>(null)
+ // A restart this panel started reads the status itself when it is done, and
+ // a poll landing in the middle of it would show the gap as "not running".
+ const busyRef = useRef(false)
+ busyRef.current = busy
+
useEffect(() => {
if (!isTauri()) return
- bundledEngineStatus().then(setStatus).catch(() => setStatus(null))
+ let alive = true
+ const read = () => {
+ if (busyRef.current) return
+ bundledEngineStatus()
+ .then((s) => { if (alive) setStatus(s) })
+ .catch(() => { if (alive) setStatus(null) })
+ }
+ read()
+ const timer = setInterval(read, ENGINE_STATUS_POLL_MS)
+ // The fast path: Rust's watch reaps the dead handle and says so, and this
+ // asks again the moment it hears it, instead of waiting out the poll.
+ let unlisten: (() => void) | null = null
+ void import('@tauri-apps/api/event')
+ .then(({ listen }) => listen(SIDECAR_GONE_EVENT, () => read()))
+ .then((off) => { if (alive) unlisten = off; else off() })
+ .catch(() => {})
+ return () => {
+ alive = false
+ clearInterval(timer)
+ unlisten?.()
+ }
}, [])
const patch = (p: Partial<BuiltinEngineTuning>) => {
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.ts
new file mode 100644
index 00000000..94daf996
--- /dev/null
+++ b/src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.ts
@@ -0,0 +1,143 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * A16, Windows counter-check 02.09. (A15-4a): the LU Engine panel read the
+ * engine status once, on mount. Kill lu-llama-server with the section standing
+ * open and the line kept saying "Engine running · Port: 8127" through all
+ * sixteen samples the counter-check took over thirty seconds. Folding the
+ * section and unfolding it corrected it, because that mounted the panel again
+ * and asked again, which is exactly the wrong thing to have to know.
+ *
+ * The panel follows the engine now: Rust's watch reaps the dead handle and
+ * emits `lu-sidecar-gone`, and this is the belt behind it, a three second poll
+ * for the case where the event never lands.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/engine-status-follows-a-dead-sidecar.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, cleanup, act } from '@testing-library/react'
+
+const bundledEngineStatus = vi.fn()
+/** The Rust-side listeners this panel registered, so the test can fire one. */
+const listeners: Record<string, ((e: unknown) => void)[]> = {}
+const unlisten = vi.fn()
+
+vi.mock('../../../api/backend', () => ({
+ isTauri: () => true,
+ isMacOS: () => false,
+ backendCall: vi.fn(async () => null),
+}))
+vi.mock('../../../api/engine', async () => {
+ const actual = await vi.importActual<typeof import('../../../api/engine')>('../../../api/engine')
+ return {
+ ...actual,
+ bundledEngineStatus: (...a: unknown[]) => bundledEngineStatus(...(a as [])),
+ swapBundledModel: vi.fn(async () => ({ port: 8127 })),
+ }
+})
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: async (name: string, cb: (e: unknown) => void) => {
+ ;(listeners[name] ??= []).push(cb)
+ return unlisten
+ },
+}))
+
+const { BuiltinEngineSettings, ENGINE_STATUS_POLL_MS, SIDECAR_GONE_EVENT } =
+ await import('../BuiltinEngineSettings')
+
+const RUNNING = { running: true, healthy: true, port: 8127, model_path: 'C:\\m\\Phi-4-mini-instruct-Q4_K_M.gguf', ctx: 8192 }
+const DEAD = { running: false, healthy: false, port: 8127, model_path: null, ctx: null }
+
+/** Mount the panel with the engine up, and let the mount read settle. */
+async function panelWithARunningEngine() {
+ bundledEngineStatus.mockResolvedValue(RUNNING)
+ render(createElement(BuiltinEngineSettings))
+ await act(async () => { await Promise.resolve(); await Promise.resolve() })
+ expect(document.body.textContent).toContain('Engine running')
+ expect(screen.getByTestId('builtin-engine-port').textContent).toContain('8127')
+}
+
+/** What `taskkill /F /IM lu-llama-server.exe` leaves behind. */
+function theEngineIsKilledFromOutside() {
+ bundledEngineStatus.mockResolvedValue(DEAD)
+}
+
+async function fireSidecarGone() {
+ await act(async () => {
+ for (const cb of listeners[SIDECAR_GONE_EVENT] ?? []) cb({ payload: { sidecar: 'engine', port: 8127 } })
+ await Promise.resolve(); await Promise.resolve()
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ bundledEngineStatus.mockReset()
+ unlisten.mockClear()
+ for (const k of Object.keys(listeners)) delete listeners[k]
+})
+afterEach(() => { cleanup(); vi.useRealTimers() })
+
+describe('an engine killed from outside while the panel stands open', () => {
+ it('says so within five seconds without anyone touching the section', async () => {
+ await panelWithARunningEngine()
+ theEngineIsKilledFromOutside()
+
+ // The whole promise, in one number: the counter-check watched for thirty
+ // seconds and saw nothing change.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000)
+ })
+
+ expect(document.body.textContent).toContain('Engine not running')
+ expect(document.body.textContent).not.toContain('Engine running ·')
+ })
+
+ it('and does not wait for the poll when Rust says the sidecar is gone', async () => {
+ await panelWithARunningEngine()
+ theEngineIsKilledFromOutside()
+
+ // No timer advanced at all: this is the event path on its own.
+ await fireSidecarGone()
+
+ expect(document.body.textContent).toContain('Engine not running')
+ })
+
+ // 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.
+ it('leaves a living engine alone however long the section stands open', async () => {
+ await panelWithARunningEngine()
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000) })
+
+ expect(document.body.textContent).toContain('Engine running')
+ expect(screen.getByTestId('builtin-engine-port').textContent).toContain('8127')
+ })
+
+ // NEGATIVE CONTROL: it is a poll, not a one-off retry. The engine coming
+ // back has to reach the panel too.
+ it('picks an engine back up when it is started again', async () => {
+ await panelWithARunningEngine()
+ theEngineIsKilledFromOutside()
+ await act(async () => { await vi.advanceTimersByTimeAsync(ENGINE_STATUS_POLL_MS + 100) })
+ expect(document.body.textContent).toContain('Engine not running')
+
+ bundledEngineStatus.mockResolvedValue(RUNNING)
+ await act(async () => { await vi.advanceTimersByTimeAsync(ENGINE_STATUS_POLL_MS + 100) })
+ expect(document.body.textContent).toContain('Engine running')
+ })
+
+ it('stops asking once the section is folded away', async () => {
+ await panelWithARunningEngine()
+ const asked = bundledEngineStatus.mock.calls.length
+ cleanup()
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000) })
+ expect(bundledEngineStatus.mock.calls.length, 'the poll outlived the panel').toBe(asked)
+ expect(unlisten, 'the Rust listener outlived the panel').toHaveBeenCalled()
+ })
+
+ it('polls often enough to keep the five second promise', () => {
+ expect(ENGINE_STATUS_POLL_MS).toBeLessThanOrEqual(3_000)
+ })
+})