Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(chat): detect router-side model unloads via /models/sse
Akarshan Biswasd1c69a014ad2
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex b8d3ed534..f6dc4457f 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -137,6 +137,118 @@ fn spawn_load_progress_listener<R: Runtime>(})}+/// Payload for the `llamacpp-model-unloaded` event: any model transition to+/// `status: "unloaded"` seen on `/models/sse`, regardless of cause (explicit+/// unload, LRU eviction under `models_max`, or a crash - `exit_code` is 0 for+/// the first two, nonzero for a crash). Forwarded unconditionally; the+/// frontend already knows about unloads it requested itself, so reconciling+/// already-correct state is a harmless no-op.+#[derive(serde::Serialize, Clone)]+pub struct UnloadEventPayload {+ pub model: String,+ pub exit_code: Option<i64>,+}++/// Parses one SSE event block, returning an unload payload only for a+/// `status_change` event whose `data.status` is `"unloaded"`. `None` for any+/// other event/status or malformed input.+fn parse_unload_event(block: &str) -> Option<UnloadEventPayload> {+ for line in block.lines() {+ let data = line+ .strip_prefix("data: ")+ .or_else(|| line.strip_prefix("data:"))?;+ let json: serde_json::Value = serde_json::from_str(data).ok()?;+ if json.get("event").and_then(|v| v.as_str()) != Some("status_change") {+ continue;+ }+ let model = json.get("model").and_then(|v| v.as_str())?;+ let status = json+ .get("data")+ .and_then(|d| d.get("status"))+ .and_then(|v| v.as_str())?;+ if status != "unloaded" {+ continue;+ }+ let exit_code = json+ .get("data")+ .and_then(|d| d.get("exit_code"))+ .and_then(|v| v.as_i64());+ return Some(UnloadEventPayload {+ model: model.to_string(),+ exit_code,+ });+ }+ None+}++/// Subscribes to the router's `/models/sse` feed for the router's entire+/// lifetime, re-emitting every model-unload transition (explicit unload, LRU+/// eviction, crash) as `llamacpp-model-unloaded`. Unlike+/// `spawn_load_progress_listener` (per-model, aborted once loading finishes)+/// this runs continuously and reconnects with backoff on a dropped+/// connection, since the router process can outlive many individual loads.+///+/// `/models/sse` itself was introduced upstream in build b9688 (#23976); on+/// an older backend the initial connection succeeds at the TCP/HTTP layer+/// but the route 404s, so we give up permanently after the first failed+/// connection instead of retrying forever against a route that will never+/// exist. A transient connection error (router mid-restart) is retried with+/// exponential backoff instead, since that's recoverable.+fn spawn_unload_watcher<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ port: u16,+ api_key: String,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ use futures_util::StreamExt;++ let client = http_client().await;+ let url = format!("http://127.0.0.1:{}/models/sse", port);+ let mut backoff = Duration::from_millis(500);+ const MAX_BACKOFF: Duration = Duration::from_secs(30);++ loop {+ let resp = match client.get(&url).bearer_auth(&api_key).send().await {+ Ok(r) => r,+ Err(e) => {+ log::debug!(+ "model unload watcher: failed to connect to /models/sse: {}; retrying in {:?}",+ e,+ backoff+ );+ tokio::time::sleep(backoff).await;+ backoff = (backoff * 2).min(MAX_BACKOFF);+ continue;+ }+ };+ if !resp.status().is_success() {+ log::debug!(+ "model unload watcher: /models/sse returned {} (backend predates b9688?); giving up",+ resp.status()+ );+ return;+ }+ backoff = Duration::from_millis(500);++ let mut stream = resp.bytes_stream();+ let mut buf = String::new();+ while let Some(chunk) = stream.next().await {+ let Ok(bytes) = chunk else { break };+ buf.push_str(&String::from_utf8_lossy(&bytes));+ while let Some(pos) = buf.find("\n\n") {+ let event_block: String = buf.drain(..pos + 2).collect();+ if let Some(payload) = parse_unload_event(&event_block) {+ let _ = app_handle.emit("llamacpp-model-unloaded", payload);+ }+ }+ }+ // Stream ended (router restarted or connection dropped); briefly+ // pause then reconnect.+ tokio::time::sleep(Duration::from_millis(500)).await;+ }+ })+}+async fn post_load<R: Runtime>(app_handle: &tauri::AppHandle<R>,port: u16,@@ -611,12 +723,23 @@ pub async fn start_router<R: Runtime>(.router_pid.store(handle.pid, std::sync::atomic::Ordering::SeqCst);*guard = Some(handle);++ let watcher = spawn_unload_watcher(app_handle.clone(), info.port, info.api_key.clone());+ *state.unload_watcher.lock().await = Some(watcher);+Ok(info)}+async fn stop_unload_watcher(state: &LlamacppState) {+ if let Some(handle) = state.unload_watcher.lock().await.take() {+ handle.abort();+ }+}+#[tauri::command]pub async fn stop_router<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {let state: State<Arc<LlamacppState>> = app_handle.state();+ stop_unload_watcher(&state).await;let mut guard = state.router.lock().await;if let Some(handle) = guard.take() {state@@ -725,6 +848,7 @@ pub async fn try_graceful_stop_router<R: Runtime>(state.router_pid.store(0, std::sync::atomic::Ordering::SeqCst);+ stop_unload_watcher(&state).await;Ok(None)}Err((h, busy)) => {@@ -799,6 +923,7 @@ pub async fn force_kill_router_tree<R: Runtime>(let mut guard = state.router.lock().await;guard.take()};+ stop_unload_watcher(&state).await;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),@@ -903,3 +1028,86 @@ mod load_progress_tests {assert!(payload.stage.is_none());}}++#[cfg(test)]+mod unload_watcher_tests {+ use super::parse_unload_event;++ fn sse_block(model: &str, event: &str, data: serde_json::Value) -> String {+ let payload = serde_json::json!({ "model": model, "event": event, "data": data });+ format!("data: {}\n\n", payload)+ }++ #[test]+ fn parses_an_unload_event_with_exit_code() {+ let block = sse_block(+ "model-1",+ "status_change",+ serde_json::json!({ "status": "unloaded", "exit_code": 137 }),+ );+ let payload = parse_unload_event(&block).expect("should parse");+ assert_eq!(payload.model, "model-1");+ assert_eq!(payload.exit_code, Some(137));+ }++ #[test]+ fn parses_a_clean_unload_with_zero_exit_code() {+ // LRU eviction / explicit unload: clean stop, exit_code 0.+ let block = sse_block(+ "model-1",+ "status_change",+ serde_json::json!({ "status": "unloaded", "exit_code": 0 }),+ );+ let payload = parse_unload_event(&block).expect("should parse");+ assert_eq!(payload.exit_code, Some(0));+ }++ #[test]+ fn ignores_non_unloaded_status() {+ let block = sse_block(+ "model-1",+ "status_change",+ serde_json::json!({ "status": "loading" }),+ );+ assert!(parse_unload_event(&block).is_none());+ }++ #[test]+ fn ignores_non_status_change_events() {+ let block = sse_block(+ "model-1",+ "model_remove",+ serde_json::json!({}),+ );+ assert!(parse_unload_event(&block).is_none());+ }++ #[test]+ fn defaults_missing_exit_code_to_none() {+ let block = sse_block(+ "model-1",+ "status_change",+ serde_json::json!({ "status": "unloaded" }),+ );+ let payload = parse_unload_event(&block).expect("should parse");+ assert_eq!(payload.exit_code, None);+ }++ #[test]+ fn ignores_malformed_json() {+ let block = "data: not json\n\n".to_string();+ assert!(parse_unload_event(&block).is_none());+ }++ #[test]+ fn ignores_missing_status_field() {+ let block = sse_block("model-1", "status_change", serde_json::json!({}));+ assert!(parse_unload_event(&block).is_none());+ }++ #[test]+ fn ignores_blocks_with_no_data_line() {+ let block = "event: ping\n\n".to_string();+ assert!(parse_unload_event(&block).is_none());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rsindex ddaf992c9..2a79e40e7 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs@@ -16,6 +16,9 @@ pub struct LlamacppState {/// 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,+ /// Persistent `/models/sse` subscriber (router-side unload notifications),+ /// alive for the router's lifetime. Aborted whenever the router stops.+ pub unload_watcher: Mutex<Option<tokio::task::JoinHandle<()>>>,}impl Default for LlamacppState {@@ -23,6 +26,7 @@ impl Default for LlamacppState {Self {router: Mutex::new(None),router_pid: AtomicU32::new(0),+ unload_watcher: Mutex::new(None),}}}diff --git a/web-app/src/containers/dialogs/LlamacppOomListener.tsx b/web-app/src/containers/dialogs/LlamacppOomListener.tsxindex b9ddcc232..d1f73d606 100644--- a/web-app/src/containers/dialogs/LlamacppOomListener.tsx+++ b/web-app/src/containers/dialogs/LlamacppOomListener.tsx@@ -15,6 +15,11 @@ type LoadProgressPayload = {value: number}+type UnloadEventPayload = {+ model: string+ exit_code?: number | null+}+export default function LlamacppOomListener() {useEffect(() => {if (!isPlatformTauri()) return@@ -56,10 +61,25 @@ export default function LlamacppOomListener() {console.warn('listen llamacpp-model-load-progress failed:', e)return () => {}})+ // Fired for every model unload the router observes (explicit unload, LRU+ // eviction under models_max, or a crash) - forwarded unconditionally.+ // Jan already flips activeModels off for unloads it requested itself, so+ // reconciling an already-correct state here is a harmless no-op; the+ // real value is catching router-side evictions Jan didn't initiate.+ const unlistenUnloaded = listen<UnloadEventPayload>(+ 'llamacpp-model-unloaded',+ (event) => {+ useAppState.getState().removeActiveModel(event.payload.model)+ }+ ).catch((e) => {+ console.warn('listen llamacpp-model-unloaded failed:', e)+ return () => {}+ })return () => {void unlistenOom.then((fn) => fn?.())void unlistenBackend.then((fn) => fn?.())void unlistenLoadProgress.then((fn) => fn?.())+ void unlistenUnloaded.then((fn) => fn?.())}}, [])diff --git a/web-app/src/containers/dialogs/__tests__/LlamacppOomListener.test.tsx b/web-app/src/containers/dialogs/__tests__/LlamacppOomListener.test.tsxindex c77bc64f9..69600588e 100644--- a/web-app/src/containers/dialogs/__tests__/LlamacppOomListener.test.tsx+++ b/web-app/src/containers/dialogs/__tests__/LlamacppOomListener.test.tsx@@ -5,12 +5,16 @@ import LlamacppOomListener from '../LlamacppOomListener'import { useAppState } from '@/hooks/useAppState'let loadProgressHandler: ((event: { payload: unknown }) => void) | undefined+let unloadHandler: ((event: { payload: unknown }) => void) | undefinedvi.mock('@tauri-apps/api/event', () => ({listen: vi.fn((eventName: string, handler: (event: { payload: unknown }) => void) => {if (eventName === 'llamacpp-model-load-progress') {loadProgressHandler = handler}+ if (eventName === 'llamacpp-model-unloaded') {+ unloadHandler = handler+ }return Promise.resolve(() => {})}),}))@@ -73,3 +77,42 @@ describe('LlamacppOomListener - model load progress', () => {})})})++describe('LlamacppOomListener - model unloaded', () => {+ beforeEach(() => {+ unloadHandler = undefined+ act(() => {+ useAppState.setState({ activeModels: ['model-1', 'model-2'] })+ })+ })++ it('removes the unloaded model from activeModels', async () => {+ render(<LlamacppOomListener />)+ await act(async () => {+ await Promise.resolve()+ })++ expect(unloadHandler).toBeDefined()+ act(() => {+ unloadHandler?.({ payload: { model: 'model-1', exit_code: 0 } })+ })++ expect(useAppState.getState().activeModels).toEqual(['model-2'])+ })++ it('is a no-op when the unloaded model was already reconciled', async () => {+ act(() => {+ useAppState.setState({ activeModels: ['model-2'] })+ })+ render(<LlamacppOomListener />)+ await act(async () => {+ await Promise.resolve()+ })++ act(() => {+ unloadHandler?.({ payload: { model: 'model-1', exit_code: 137 } })+ })++ expect(useAppState.getState().activeModels).toEqual(['model-2'])+ })+})diff --git a/web-app/src/hooks/__tests__/useAppState.coverage.test.ts b/web-app/src/hooks/__tests__/useAppState.coverage.test.tsindex c706b740f..e0a654333 100644--- a/web-app/src/hooks/__tests__/useAppState.coverage.test.ts+++ b/web-app/src/hooks/__tests__/useAppState.coverage.test.ts@@ -212,4 +212,24 @@ describe('useAppState - coverage', () => {expect(result.current.activeModels).toEqual(['model-a', 'model-b'])})+ it('should remove a single active model', () => {+ const { result } = renderHook(() => useAppState())++ act(() => {+ result.current.setActiveModels(['model-a', 'model-b'])+ result.current.removeActiveModel('model-a')+ })+ expect(result.current.activeModels).toEqual(['model-b'])+ })++ it('should no-op removing a model that is not active', () => {+ const { result } = renderHook(() => useAppState())++ act(() => {+ result.current.setActiveModels(['model-a'])+ result.current.removeActiveModel('model-does-not-exist')+ })+ expect(result.current.activeModels).toEqual(['model-a'])+ })+})diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.tsindex 13c5272ca..86b722efc 100644--- a/web-app/src/hooks/useAppState.ts+++ b/web-app/src/hooks/useAppState.ts@@ -75,6 +75,7 @@ type AppState = {updateLiveTokenStats: (stats: LiveTokenStats | undefined) => voidupdateModelLoadProgress: (progress: ModelLoadProgress | undefined) => voidsetActiveModels: (models: string[]) => void+ removeActiveModel: (modelId: string) => voidupdateThreadStreamingContent: (threadId: string,@@ -219,6 +220,11 @@ export const useAppState = create<AppState>()((set) => ({activeModels: models,}))},+ removeActiveModel: (modelId: string) => {+ set((state) => ({+ activeModels: state.activeModels.filter((id) => id !== modelId),+ }))+ },updateThreadStreamingContent: (threadId, content) =>set((state) => {