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
feat(engine): the KV cache survives the VRAM handoff (#85)
David7f63f4f4a0f3
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex dec861c4..c2d2e5fd 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -122,7 +122,7 @@ pub(crate) fn effective_ctx(tuning: &EngineTuning) -> u32 {/// layer to the GPU (Metal on mac); llama-server clamps to the real layer/// count, so an over-large value is the idiomatic "all layers" request./// Default tuning yields exactly the legacy argv (pinned by regression test).-pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u16) -> Vec<String> {+pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u16, slot_save_dir: Option<&str>) -> Vec<String> {let mut args: Vec<String> = vec!["-m".into(),model_path.into(),@@ -161,6 +161,17 @@ pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: uif tuning.no_mmap {args.push("--no-mmap".into());}+ // GH #85 (I-Am-LongXi): enable llama-server's slot save/restore API so the+ // VRAM handoff can serialize the KV cache to disk before evicting the+ // engine for a render, and restore it after the reload instead of+ // re-processing the whole conversation. The flag only enables the+ // endpoint; nothing is written until a save is requested. (llama.cpp+ // cannot save slots with an mmproj loaded; the built-in engine never+ // loads one, so that limitation does not apply here.)+ if let Some(dir) = slot_save_dir {+ args.push("--slot-save-path".into());+ args.push(dir.into());+ }args}@@ -357,6 +368,34 @@ fn resolve_engine_binary(app: &AppHandle) -> Option<PathBuf> {// ── Health probe ─────────────────────────────────────────────────────────────+/// Save or restore llama-server's KV slot 0 (GH #85). The webview cannot fetch+/// the engine port directly (CSP; all engine traffic rides the Rust proxy), so+/// the handoff calls this instead. One fixed filename: the handoff carries at+/// most one conversation across one eviction at a time. `ok:false` is a normal+/// outcome (old binary, empty slot, ctx mismatch after a settings change) and+/// means the next turn re-processes the history, exactly the pre-#85 cost.+#[tauri::command]+pub async fn kv_slot_action(port: u16, action: String) -> Result<serde_json::Value, String> {+ if action != "save" && action != "restore" {+ return Err("action must be 'save' or 'restore'".to_string());+ }+ let url = format!("http://127.0.0.1:{port}/slots/0?action={action}");+ let client = reqwest::Client::builder()+ // Serializing a multi-GB KV cache to disk takes a while on slow disks.+ .timeout(Duration::from_secs(120))+ .build()+ .map_err(|e| e.to_string())?;+ let res = client+ .post(&url)+ .json(&serde_json::json!({ "filename": "lu-handoff.bin" }))+ .send()+ .await+ .map_err(|e| format!("slot {action} failed: {e}"))?;+ let ok = res.status().is_success();+ let body: serde_json::Value = res.json().await.unwrap_or_else(|_| serde_json::json!({}));+ Ok(serde_json::json!({ "ok": ok, "body": body }))+}+fn engine_healthy(port: u16) -> bool {reqwest::blocking::Client::builder().timeout(Duration::from_millis(400))@@ -448,7 +487,16 @@ fn start_bundled_engine_blocking(return Err(format!("Model file not found: {model_path}"));}- let desired_args = build_server_args(&model_path, &tuning, port);+ // KV-slot directory next to the built-in models (GH #85). Best effort: a+ // failure here only disables slot save/restore, never the engine itself.+ let slot_dir = builtin_models_dir()+ .ok()+ .and_then(|models| models.parent().map(|p| p.join("kv-slots")))+ .and_then(|dir| {+ std::fs::create_dir_all(&dir).ok()?;+ Some(dir.to_string_lossy().to_string())+ });+ let desired_args = build_server_args(&model_path, &tuning, port, slot_dir.as_deref());// Already serving this exact argv and healthy → no-op. The argv is the// idempotence key: a ctx/KV-quant/flash-attn change restarts the server,@@ -621,6 +669,10 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,"running": true,"healthy": engine_healthy(port),"port": port,+ // Model file size feeds the handoff's fits/doesn't-fit call+ // (GH #85): a GGUF's on-disk size is a close proxy for its+ // VRAM footprint at full offload.+ "modelBytes": std::fs::metadata(&model_path).map(|m| m.len()).unwrap_or(0),"model_path": model_path,"ctx": ctx,}),@@ -929,11 +981,21 @@ mod tests {assert_eq!(health_timeout_for_bytes(u64::MAX), Duration::from_secs(600));}+ #[test]+ fn slot_save_dir_appends_the_flag_and_none_stays_legacy() {+ // GH #85: the KV-slot flag rides at the end so every earlier pin holds.+ let with = build_server_args("/m.gguf", &EngineTuning::default(), 8127, Some("/data/kv-slots"));+ let tail: Vec<&str> = with.iter().rev().take(2).map(String::as_str).collect();+ assert_eq!(tail, vec!["/data/kv-slots", "--slot-save-path"]);+ let without = build_server_args("/m.gguf", &EngineTuning::default(), 8127, None);+ assert!(!without.iter().any(|a| a == "--slot-save-path"));+ }+#[test]fn default_tuning_args_match_legacy_shape() {// Pin: absent/default tuning must produce EXACTLY the argv the app has// shipped since 2.5.7 — expert settings are opt-in, never a drift.- let args = build_server_args("/models/qwen.gguf", &EngineTuning::default(), 8127);+ let args = build_server_args("/models/qwen.gguf", &EngineTuning::default(), 8127, None);assert_eq!(args,vec![@@ -958,7 +1020,7 @@ mod tests {mlock: true,no_mmap: true,};- let args = build_server_args("/m.gguf", &tuning, 8127);+ let args = build_server_args("/m.gguf", &tuning, 8127, None);assert_eq!(args,vec![@@ -991,7 +1053,7 @@ mod tests {mlock: false,no_mmap: false,};- let args = build_server_args("/m.gguf", &tuning, 8127);+ let args = build_server_args("/m.gguf", &tuning, 8127, None);assert_eq!(args,vec![@@ -1007,7 +1069,7 @@ mod tests {#[test]fn gpu_layers_zero_means_cpu_only_not_all() {let tuning = EngineTuning { gpu_layers: 0, ..Default::default() };- let args = build_server_args("/m.gguf", &tuning, 8127);+ let args = build_server_args("/m.gguf", &tuning, 8127, None);let ngl = args.iter().position(|a| a == "-ngl").unwrap();assert_eq!(args[ngl + 1], "0");}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 7b1be5de..bf9f3287 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -206,6 +206,7 @@ fn main() {commands::engine::start_bundled_engine,commands::engine::stop_bundled_engine,commands::engine::bundled_engine_status,+ commands::engine::kv_slot_action,commands::engine::swap_bundled_model,commands::engine::list_bundled_models,// Built-in embeddings server (bundled llama-server --embeddings, P5)diff --git a/src/api/__tests__/kv-slot-handoff.test.ts b/src/api/__tests__/kv-slot-handoff.test.tsnew file mode 100644index 00000000..b6526b5d--- /dev/null+++ b/src/api/__tests__/kv-slot-handoff.test.ts@@ -0,0 +1,49 @@+/**+ * GH #85 (I-Am-LongXi): der VRAM-Handoff wirft das Textmodell fuer einen+ * Render aus dem Speicher und laedt es danach neu. Fuer die Built-in-Engine+ * hiess Neuladen bisher: die komplette Gespraechshistorie wird beim naechsten+ * Turn neu verarbeitet. llama-server kann den KV-Cache als Slot auf Platte+ * sichern und wiederherstellen; der Handoff nutzt das jetzt.+ *+ * Quellgepinnt auf beiden Seiten des Drahts: die Rust-Bruecke (der Webview+ * kommt am Engine-Port nicht vorbei) und die Reihenfolge im Handoff (sichern+ * VOR dem Stopp, wiederherstellen NACH dem Start, nur wenn das Sichern+ * gelang). Kein anderer Test sieht eine dieser Weichen.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const hier = dirname(fileURLToPath(import.meta.url))+const handoff = () => readFileSync(resolve(hier, '..', 'vram-handoff.ts'), 'utf8')+const engineRs = () => readFileSync(resolve(hier, '..', '..', '..', 'src-tauri', 'src', 'commands', 'engine.rs'), 'utf8')++describe('#85: KV-Slot ueberlebt den VRAM-Handoff', () => {+ it('die Rust-Bruecke trifft llama-servers /slots-API und der Start traegt den Slot-Pfad', () => {+ const src = engineRs()+ expect(src).toMatch(/\/slots\/0\?action=/)+ expect(src).toMatch(/--slot-save-path/)+ expect(src).toMatch(/pub async fn kv_slot_action/)+ })++ it('die Built-in-Engine wird als dritter Teilnehmer erkannt und mitgerechnet', () => {+ const src = handoff()+ expect(src).toMatch(/bundled_engine_status/)+ expect(src).toMatch(/bundledTarget\?\.modelBytes/)+ expect(src).toMatch(/textModel \|\| lmsTarget \|\| bundledTarget/)+ })++ it('gesichert wird VOR dem Stopp, wiederhergestellt NACH dem Start, und nur nach gelungenem Sichern', () => {+ const src = handoff()+ const save = src.indexOf("action: 'save'")+ const stop = src.indexOf("backendCall('stop_bundled_engine')")+ const start = src.indexOf('startBundledEngine(evictedBundled.modelPath)')+ const restore = src.indexOf("action: 'restore'")+ expect(save).toBeGreaterThan(-1)+ expect(stop).toBeGreaterThan(save)+ expect(start).toBeGreaterThan(stop)+ expect(restore).toBeGreaterThan(start)+ expect(src).toMatch(/if \(evictedBundled\.slotSaved\)/)+ })+})diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 4409cbb0..d9c4059f 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -46,6 +46,7 @@import { backendCall, ollamaUrl, localFetch, isOllamaLocal } from './backend'import { listRunningModels, loadModel, unloadModel } from './ollama'+import { startBundledEngine } from './engine'import { useSettingsStore } from '../stores/settingsStore'import {getImageModels,@@ -458,6 +459,31 @@ export function estimateLmsTextVramBytes(id: string): number | undefined {return Math.round(params * 0.75 * 1e9)}+// ── Built-in engine (llama-server) juggling + KV-slot carry (GH #85) ──+// I-Am-LongXi: llama.cpp can serialize a slot's KV cache to disk and restore+// it after a reload. The handoff uses that, so evicting the built-in engine+// for a render no longer costs a full history re-process on the next turn.+// The HTTP rides the Rust side (kv_slot_action): the webview cannot reach the+// engine port, all engine traffic goes through the proxy anyway.++export interface BundledTarget {+ port: number+ modelPath: string+ /** GGUF size on disk, a close proxy for its VRAM at full offload. */+ modelBytes: number+}++/** The built-in llama-server, when it is running and holding VRAM. */+export async function detectBundledEngine(): Promise<BundledTarget | null> {+ try {+ const s = await backendCall<{ running?: boolean; port?: number; model_path?: string | null; modelBytes?: number }>('bundled_engine_status')+ if (s?.running && typeof s.port === 'number' && typeof s.model_path === 'string' && s.model_path) {+ return { port: s.port, modelPath: s.model_path, modelBytes: typeof s.modelBytes === 'number' ? s.modelBytes : 0 }+ }+ } catch { /* command absent (web build) or engine idle */ }+ return null+}+export async function pollGone(modelName: string, timeoutMs = 15_000): Promise<boolean> {const deadline = Date.now() + timeoutMs// Check immediately first (cheap) before sleeping.@@ -755,20 +781,24 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: nif (!lmsTarget) lmsTarget = await detectAnyLoadedLmsModel()const lmsVramBytes = lmsTarget ? estimateLmsTextVramBytes(lmsTarget.id) : undefined+ // ── Built-in engine side (live): llama-server holding a GGUF (GH #85) ──+ const bundledTarget = await detectBundledEngine()+// ── Decide: one shared fits/doesn't-fit call over EVERYTHING resident.// If the sum doesn't co-exist with the generation footprint, free BOTH// sides — over-evicting is lossless (both reload in the finally), while// under-evicting risks the exact 11.9/12 GB thrash this exists to avoid.let willUnload = falselet willUnloadLms = false- if (textModel || lmsTarget) {+ let willUnloadBundled = false+ if (textModel || lmsTarget || bundledTarget) {try {const [footprint, systemVram, mode] = await Promise.all([Promise.resolve(estimateModelFootprintGB(targetModel)),getSystemVRAM(),Promise.resolve(getExclusiveVramMode()),])- const residentBytes = (textVramBytes ?? 0) + (lmsVramBytes ?? 0)+ const residentBytes = (textVramBytes ?? 0) + (lmsVramBytes ?? 0) + (bundledTarget?.modelBytes ?? 0)const decision = decideUnload({textVramBytes: residentBytes > 0 ? residentBytes : undefined,modelFootprintGB: footprint,@@ -777,13 +807,16 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: n})willUnload = decision.unload && !!textModelwillUnloadLms = decision.unload && !!lmsTarget+ willUnloadBundled = decision.unload && !!bundledTargetlog.info('vram_handoff.decision', {kind,targetModel,textModel,lmsModel: lmsTarget?.id ?? null,+ bundledModel: bundledTarget?.modelPath ?? null,textVramBytes,lmsVramBytes,+ bundledBytes: bundledTarget?.modelBytes,...decision,})} catch (e) {@@ -791,6 +824,7 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: nlog.warn('vram_handoff.decision_failed', { err: String(e) })willUnload = falsewillUnloadLms = false+ willUnloadBundled = false}}@@ -798,6 +832,7 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: n// even if `active` was somehow stale.let evictedModel: string | null = nulllet evictedLms: LmsTextModel | null = null+ let evictedBundled: (BundledTarget & { slotSaved: boolean }) | null = nulltry {// A chat-initiated ComfyUI gen is now ACTUALLY in flight — we are past every@@ -861,6 +896,23 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: n}}+ // ── (b3) HANDOFF-OUT for the built-in engine (GH #85) ──────────+ if (willUnloadBundled && bundledTarget) {+ emitHandoff('freeing_vram', { kind, detail: 'built-in engine' })+ // Carry the conversation across the eviction: serialize the KV cache to+ // disk, then stop the engine. Restore happens in the finally. When+ // either half fails, the next chat turn just re-processes the history,+ // which is exactly the pre-#85 cost — never block the render on it.+ const saved = await backendCall<{ ok?: boolean }>('kv_slot_action', { port: bundledTarget.port, action: 'save' }).catch(() => null)+ if (saved?.ok !== true) log.warn('vram_handoff.kv_save_failed', { port: bundledTarget.port })+ try {+ await backendCall('stop_bundled_engine')+ evictedBundled = { ...bundledTarget, slotSaved: saved?.ok === true }+ } catch (e) {+ log.warn('vram_handoff.bundled_stop_failed', { err: String(e) })+ }+ }+// Cancelled while freeing VRAM / waiting for eviction — bail before we even// touch ComfyUI. The finally still restores the text model.if (_genCancelRequested) return `${label(kind)} generation cancelled.`@@ -961,6 +1013,24 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: nlog.warn('vram_handoff.lms_reload_failed', { lmsModel: evictedLms.id, err: String(e) })}}+ if (evictedBundled) {+ try {+ // Same model, same settings-derived tuning as every engine start;+ // start_bundled_engine blocks until /health is green, so the slot+ // restore below never races the model load.+ await startBundledEngine(evictedBundled.modelPath)+ if (evictedBundled.slotSaved) {+ const restored = await backendCall<{ ok?: boolean }>('kv_slot_action', { port: evictedBundled.port, action: 'restore' }).catch(() => null)+ if (restored?.ok !== true) {+ // Non-fatal by design: the next turn re-processes the history,+ // exactly the pre-#85 cost.+ log.warn('vram_handoff.kv_restore_failed', { port: evictedBundled.port })+ }+ }+ } catch (e) {+ log.warn('vram_handoff.bundled_reload_failed', { err: String(e) })+ }+ }emitHandoff('done', { kind })}}