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): der Rueckfall auf den Prozessor steht endlich auf dem Schirm

purple406ed50e6dea
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index d9f3aa2f..99456ebb 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -238,7 +238,12 @@ const KV_BYTES_PER_LAYER_PER_1K_CTX: u64 = 4 * MIB;
const ASSUMED_BLOCK_COUNT: u32 = 16;
/// What `-ngl` carries when every layer is wanted.
-const ALL_LAYERS: &str = "999";
+///
+/// A number rather than a string, because two questions are asked of it: what
+/// to write into argv, and whether a layer count read back OUT of argv is this
+/// sentinel or a real measurement. A surface that printed "999" at a user
+/// would be printing the sentinel.
+const ALL_LAYERS: u32 = 999;
/// The numbers an offload decision is made from. Plain values, so the
/// arithmetic can be checked without a graphics card in the machine.
@@ -345,6 +350,17 @@ pub(crate) fn gpu_layers_in(args: &[String]) -> Option<u32> {
args.windows(2).find(|w| w[0] == "-ngl").and_then(|w| w[1].parse().ok())
}
+/// The layer count a surface may show the user, `None` when the start asked
+/// for every layer.
+///
+/// `None` is what nearly every machine gets: a card with room, and a card
+/// nothing could measure, both send the sentinel. A number here means the app
+/// decided against the card (or the user typed one), which is the only case
+/// worth a line on screen.
+pub(crate) fn gpu_layers_reported(args: &[String]) -> Option<u32> {
+ gpu_layers_in(args).filter(|n| *n != ALL_LAYERS)
+}
+
/// The argv with the `-ngl <n>` pair removed, for the idempotence check.
pub(crate) fn argv_without_gpu_layers(args: &[String]) -> Vec<String> {
let mut out = Vec::with_capacity(args.len());
@@ -388,7 +404,7 @@ pub(crate) fn build_server_args(model_path: &str, tuning: &EngineTuning, port: u
effective_ctx(tuning).to_string(),
"-ngl".into(),
if tuning.gpu_layers < 0 {
- auto_ngl.map(|n| n.to_string()).unwrap_or_else(|| ALL_LAYERS.to_string())
+ auto_ngl.unwrap_or(ALL_LAYERS).to_string()
} else {
tuning.gpu_layers.to_string()
},
@@ -1674,6 +1690,7 @@ fn start_bundled_engine_blocking(
model_path: e.model_path.clone(),
args: e.args.clone(),
auto_layers: e.auto_layers,
+ cpu_fallback: e.cpu_fallback,
port: e.port,
ctx: e.ctx,
})
@@ -1704,6 +1721,10 @@ struct PreviousEngine {
/// process is the same kind of start it was, and the idempotence check
/// keeps answering the same way about it afterwards.
auto_layers: bool,
+ /// Whether that engine was already the CPU retry. Carried for the same
+ /// reason: a restore brings the process back as it was, and a status read
+ /// afterwards must not claim the card back for it.
+ cpu_fallback: bool,
}
/// Der Satz, der an die Fehlermeldung geht, wenn das alte Modell wieder laeuft.
@@ -1728,6 +1749,7 @@ fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine) -> b
vorher.port,
vorher.ctx,
vorher.auto_layers,
+ vorher.cpu_fallback,
)
.is_ok();
if !ok {
@@ -1875,7 +1897,7 @@ fn start_after_stop(
vram_source = card.as_ref().map(|c| c.source).unwrap_or("none"),
block_count = header.block_count.map(|b| b.to_string()).unwrap_or_else(|| "unknown".into()),
ctx = ctx_size,
- ngl = plan.layers.map(|l| l.to_string()).unwrap_or_else(|| ALL_LAYERS.to_string()),
+ ngl = plan.layers.unwrap_or(ALL_LAYERS).to_string(),
"{}",
plan.why
);
@@ -1888,7 +1910,7 @@ fn start_after_stop(
let deadline = health_timeout_for(model_path);
let ctx = Some(ctx_size);
- let first = spawn_engine_attempt(state, &binary, &desired_args, model_path, port, ctx, auto_layers);
+ let first = spawn_engine_attempt(state, &binary, &desired_args, model_path, port, ctx, auto_layers, false);
let failure = match first {
Ok(()) => {
tracing::info!(target: "engine", port, attempt = 1, "the LU Engine is serving");
@@ -1959,7 +1981,7 @@ fn start_after_stop(
// next start with the same settings has to be allowed to try the card
// again.
let retry_auto = auto_layers && !offload_was_tried;
- match spawn_engine_attempt(state, &binary, &retry_args, model_path, retry_port, ctx, retry_auto) {
+ match spawn_engine_attempt(state, &binary, &retry_args, model_path, retry_port, ctx, retry_auto, offload_was_tried) {
Ok(()) => {
if offload_was_tried {
tracing::warn!(
@@ -2007,6 +2029,7 @@ fn spawn_engine_attempt(
port: u16,
ctx: Option<u32>,
auto_layers: bool,
+ cpu_fallback: bool,
) -> Result<(), StartFailure> {
// The one line a support log has to carry. Everything the start depends on
// is in the argv: model path, context size, layer count, cache types,
@@ -2067,6 +2090,7 @@ fn spawn_engine_attempt(
ctx,
args: args.to_vec(),
auto_layers,
+ cpu_fallback,
});
let outcome = wait_for_health_or_exit(state, port, health_timeout_for(model_path));
@@ -2155,16 +2179,26 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,
live_sidecar(&mut guard)
};
match probe {
- Some((port, model_path, ctx)) => serde_json::json!({
+ Some(live) => serde_json::json!({
"running": true,
- "healthy": engine_healthy(port),
- "port": port,
+ "healthy": engine_healthy(live.port),
+ "port": live.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,
+ "modelBytes": std::fs::metadata(&live.model_path).map(|m| m.len()).unwrap_or(0),
+ "model_path": live.model_path,
+ "ctx": live.ctx,
+ // Where this engine computes, and how much of the model the
+ // card really took (3.0.0 leftover). `start_bundled_engine`
+ // answered `cpuOnly` once, in the return value of the call
+ // that started it, and nothing kept it: the fallback was a
+ // fact about the running process that no surface could ask
+ // about afterwards, and a user who came back to the window
+ // five minutes later found an engine that looked ordinary and
+ // ran at a tenth of the speed.
+ "cpuOnly": live.cpu_fallback,
+ "gpuLayers": live.gpu_layers,
}),
None => serde_json::json!({
"running": false,
@@ -2172,6 +2206,8 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,
"port": DEFAULT_ENGINE_PORT,
"model_path": null,
"ctx": null,
+ "cpuOnly": false,
+ "gpuLayers": null,
}),
}
})
@@ -2710,9 +2746,32 @@ pub(crate) fn reap_dead_engine(slot: &mut Option<BundledEngine>) -> bool {
/// not, so an embed sidecar killed from outside kept answering "running" on
/// 8128 exactly the way the chat engine used to on 8127. Both status commands
/// go through this one function now, so the two cannot drift apart again.
-pub(crate) fn live_sidecar(slot: &mut Option<BundledEngine>) -> Option<(u16, String, Option<u32>)> {
+/// What a live sidecar is, in the words its status answers need.
+///
+/// A tuple until the CPU fallback had to be reported. Five values read as
+/// `(p, _, _, _, _)` at a call site, which is a shape nobody can check against
+/// the thing it describes, so they have names.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct LiveSidecar {
+ pub port: u16,
+ pub model_path: String,
+ pub ctx: Option<u32>,
+ /// The app took the graphics card away by itself after a start died.
+ pub cpu_fallback: bool,
+ /// The `-ngl` the process really carries, `None` when it asked for all of
+ /// them (`gpu_layers_reported`).
+ pub gpu_layers: Option<u32>,
+}
+
+pub(crate) fn live_sidecar(slot: &mut Option<BundledEngine>) -> Option<LiveSidecar> {
reap_dead_engine(slot);
- slot.as_ref().map(|e| (e.port, e.model_path.clone(), e.ctx))
+ slot.as_ref().map(|e| LiveSidecar {
+ port: e.port,
+ model_path: e.model_path.clone(),
+ ctx: e.ctx,
+ cpu_fallback: e.cpu_fallback,
+ gpu_layers: gpu_layers_reported(&e.args),
+ })
}
// ── The watch that tells the UI a sidecar died ───────────────────────────────
@@ -2903,8 +2962,9 @@ fn start_bundled_embed_blocking(
args: embed_args,
// The embeddings server sends a fixed `-ngl 999` and nothing measures
// anything for it: these models are a few hundred MiB and fit on
- // whatever is there.
+ // whatever is there, so there is also no GPU start for it to lose.
auto_layers: false,
+ cpu_fallback: false,
});
if let Err(e) = wait_for_health(port, health_timeout_for(&model_path)) {
@@ -2973,11 +3033,11 @@ pub async fn bundled_embed_status(app: AppHandle) -> Result<serde_json::Value, S
live_sidecar(&mut guard)
};
match probe {
- Some((port, model_path, _ctx)) => serde_json::json!({
+ Some(live) => serde_json::json!({
"running": true,
- "healthy": engine_healthy(port),
- "port": port,
- "model_path": model_path,
+ "healthy": engine_healthy(live.port),
+ "port": live.port,
+ "model_path": live.model_path,
}),
None => serde_json::json!({
"running": false,
@@ -3457,6 +3517,25 @@ mod tests {
);
}
+ #[test]
+ fn the_status_shows_a_layer_count_but_never_the_sentinel() {
+ // What a surface may print. 999 is llama.cpp's way of saying "all of
+ // them", so printing it would put a magic number in front of a user
+ // who owns a card with 32 layers.
+ let auto = EngineTuning::default();
+ let all = build_server_args("/m.gguf", &auto, 8127, None, None, None);
+ assert_eq!(gpu_layers_reported(&all), None, "the sentinel reached a surface");
+ let some = build_server_args("/m.gguf", &auto, 8127, None, None, Some(18));
+ assert_eq!(gpu_layers_reported(&some), Some(18));
+ // A start that ended on the processor names the zero rather than
+ // hiding it: nought layers on the card is the whole story.
+ let cpu = EngineTuning { gpu_layers: 0, ..Default::default() };
+ assert_eq!(
+ gpu_layers_reported(&build_server_args("/m.gguf", &cpu, 8127, None, None, None)),
+ Some(0)
+ );
+ }
+
#[test]
fn the_idempotence_key_ignores_a_measurement_but_not_a_setting() {
// Two auto starts a minute apart measure different free memory. That
@@ -4144,6 +4223,7 @@ mod tests {
ctx: Some(8192),
args: Vec::new(),
auto_layers: false,
+ cpu_fallback: false,
});
}
@@ -4226,6 +4306,7 @@ mod tests {
model_path: "/tmp/hermes.gguf".into(),
args: vec!["-c".into(), "sleep 30".into()],
auto_layers: false,
+ cpu_fallback: false,
port,
ctx: Some(8192),
};
@@ -4268,6 +4349,7 @@ mod tests {
model_path: "/tmp/hermes.gguf".into(),
args: vec!["-c".into(), "exit 1".into()],
auto_layers: false,
+ cpu_fallback: false,
port: DEAD_PORT,
ctx: Some(8192),
};
@@ -4372,9 +4454,78 @@ mod tests {
ctx: Some(8192),
args: Vec::new(),
auto_layers: false,
+ cpu_fallback: false,
})
}
+ #[test]
+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]
+ fn a_status_read_says_that_the_engine_ended_up_on_the_processor() {
+ // The fallback was answered ONCE, in the return value of the start
+ // call, and then forgotten. A status read a minute later described an
+ // engine that ran at a tenth of its speed as an ordinary one.
+ 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_ENGINE_PORT);
+ {
+ let e = slot.as_mut().unwrap();
+ e.cpu_fallback = true;
+ e.args = build_server_args(
+ "/m.gguf",
+ &EngineTuning { gpu_layers: 0, ..Default::default() },
+ DEFAULT_ENGINE_PORT,
+ None,
+ None,
+ None,
+ );
+ }
+
+ let seen = live_sidecar(&mut slot).expect("the engine is running");
+ assert!(seen.cpu_fallback, "the fallback did not survive the status read");
+ assert_eq!(seen.gpu_layers, Some(0));
+
+ let mut engine = slot.take().unwrap();
+ let _ = engine.child.kill();
+ let _ = engine.child.wait();
+ }
+
+ #[test]
+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]
+ fn a_typed_cpu_setting_is_not_reported_as_a_failed_start() {
+ // The counter-check to the test above. Someone who wrote 0 into GPU
+ // Layers got what he asked for, and telling him the graphics card
+ // failed would be an invention.
+ 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_ENGINE_PORT);
+ slot.as_mut().unwrap().args = build_server_args(
+ "/m.gguf",
+ &EngineTuning { gpu_layers: 0, ..Default::default() },
+ DEFAULT_ENGINE_PORT,
+ None,
+ None,
+ None,
+ );
+
+ let seen = live_sidecar(&mut slot).expect("the engine is running");
+ assert!(!seen.cpu_fallback, "a typed setting was reported as a fallback");
+ assert_eq!(seen.gpu_layers, Some(0));
+
+ let mut engine = slot.take().unwrap();
+ let _ = engine.child.kill();
+ let _ = engine.child.wait();
+ }
+
#[test]
#[cfg_attr(target_os = "windows", ignore = "uses sh")]
fn an_engine_killed_from_outside_stops_counting_as_running() {
@@ -4456,7 +4607,7 @@ mod tests {
let mut slot = engine_around(child, DEFAULT_EMBED_PORT);
let seen = live_sidecar(&mut slot);
- assert_eq!(seen.as_ref().map(|(p, _, _)| *p), Some(DEFAULT_EMBED_PORT));
+ assert_eq!(seen.as_ref().map(|s| s.port), Some(DEFAULT_EMBED_PORT));
assert!(slot.is_some());
let mut engine = slot.take().unwrap();
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index dd6a54b8..b58f9985 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -57,6 +57,15 @@ pub struct BundledEngine {
/// between auto and a typed number is a different request even on the days
/// the two numbers happen to agree.
pub auto_layers: bool,
+ /// True when THIS process is the retry that dropped GPU offload after a
+ /// first attempt died (`engine.rs`, SecondAttempt::CpuOnly).
+ ///
+ /// NOT the same question as "does argv say `-ngl 0`". A user who typed 0
+ /// into Settings got exactly what he asked for and has nothing to be told
+ /// about; this flag marks the case where the app took the card away by
+ /// itself, which is the one the user never chose and until now could only
+ /// find in the log file.
+ pub cpu_fallback: bool,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index e1e0ab6c..4b65c366 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -30,6 +30,7 @@ import {
builtinModelNameFromPath,
} from '../lib/builtin-model-identity'
import { hostOf, isLocalTransportFailure } from '../lib/local-backend-transport'
+import { announceEngineCpuFallback } from '../lib/engine-offload'
interface EngineStatusLite {
running: boolean
@@ -40,6 +41,11 @@ interface EngineStatusLite {
* not running. The ONLY honest answer to "which model is loaded": the
* `model` field of a request is a label llama-server ignores. */
model_path?: string | null
+ /** Which port it really holds, and whether the app had to drop GPU offload
+ * to get it serving. Both only so the fallback note below can be said from
+ * the send path, which is the only status read the chat ever makes. */
+ port?: number | null
+ cpuOnly?: boolean
}
interface BundledList {
@@ -236,6 +242,10 @@ async function loadBuiltinModel(modelName: string): Promise<void> {
} catch {
return // non-Tauri context (tests/browser) — nothing to manage
}
+ // The chat draws the standing line and never polls the engine, so this is
+ // the one read on that side of the app. Says nothing when there is nothing
+ // to say, and nothing twice about the same engine (lib/engine-offload).
+ announceEngineCpuFallback(status)
// Healthy AND holding what the caller wants: the only case that may skip
// out. An engine whose status carries no model_path cannot be judged, so it
// counts as a match and the send proceeds exactly as it did before.
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 95e56e95..071700ab 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -20,6 +20,7 @@ import { useSettingsStore } from '../stores/settingsStore'
import type { CloudModel } from '../types/models'
import type { BuiltinEngineTuning } from '../types/settings'
import { LU_ENGINE_NAME } from '../lib/engine-name'
+import { announceEngineCpuFallback } from '../lib/engine-offload'
/** The user's Built-in Engine expert tuning (settings-backed). Injected into
* every start/swap below, so Onboarding, Discover, the model picker and the
@@ -69,6 +70,13 @@ export interface EngineStatus {
/** Context size the chat engine was started with (null when not running or
* for the embed server). The TRUE token-counter denominator. */
ctx?: number | null
+ /** The engine is on the processor because a start WITH the graphics card
+ * died first (3.0.0, ccdc2d14). Not the same as a GPU Layers of 0 typed
+ * into Settings, which is an answer rather than an accident. */
+ cpuOnly?: boolean
+ /** The `-ngl` the running process carries, null when it asked for every
+ * layer. See lib/engine-offload. */
+ gpuLayers?: number | null
}
/** Loopback base URL of the managed embeddings server (P5). Mirrors the Rust
@@ -154,6 +162,11 @@ export async function bundledEngineStatus() {
// without the reset a one-off collision would keep the app on 8129 for good
// and the Settings test would read "failed" on a free 8127 (review S5).
syncBuiltinEnginePort(status?.running ? status.port : ENGINE_PORT)
+ // An engine the app pushed onto the processor by itself says so, once per
+ // engine. This is the poll behind Settings and the models view; the chat's
+ // own pre-send probe says it from builtin-ensure, because the chat does not
+ // poll and this note would otherwise never reach the screen it hangs over.
+ announceEngineCpuFallback(status)
return status
}
diff --git a/src/api/lu-engine-switch.ts b/src/api/lu-engine-switch.ts
index cf7b2944..934e07ed 100644
--- a/src/api/lu-engine-switch.ts
+++ b/src/api/lu-engine-switch.ts
@@ -32,6 +32,9 @@ import type { ProviderModel } from './providers/types'
import { PROVIDER_PRESETS } from './providers/types'
import { slotTakeoverUpdate } from '../lib/openai-slot-handover'
import { LU_ENGINE_NAME } from '../lib/engine-name'
+// Dieselbe Liste beantwortet die Frage auf dem Statusweg, der diese Datei
+// nicht importieren kann, ohne einen Kreis zu schliessen (lib/engine-offload).
+import { VIEWS_WITH_THE_ENGINE_NOTE } from '../lib/engine-offload'
import { displayModelName } from './providers'
/** What the user is told when the pick moved his chat backend. */
@@ -314,9 +317,6 @@ function haltenBis(pruefung: () => boolean, frist = CHAT_PROVIDER_SWITCH_HOLD_MS
return () => Date.now() < ende && pruefung()
}
-/** Die Seiten, auf denen `LuEngineSwitchBar` wirklich haengt. */
-const SEITEN_MIT_ZEILE: ReadonlySet<string> = new Set(['chat', 'models'])
-
/**
* Wie lange eine Zeile auf ihren Leser wartet.
*
@@ -339,7 +339,7 @@ export const UNSEEN_NOTE_HOLD_MS = 5 * 60_000
*/
function bisJemandHinsehenKann(): () => boolean {
return haltenBis(
- () => !SEITEN_MIT_ZEILE.has(useUIStore.getState().currentView),
+ () => !VIEWS_WITH_THE_ENGINE_NOTE.has(useUIStore.getState().currentView),
UNSEEN_NOTE_HOLD_MS,
)
}
diff --git a/src/components/settings/BuiltinEngineSettings.tsx b/src/components/settings/BuiltinEngineSettings.tsx
index 2f2559ae..b88af2f4 100644
--- a/src/components/settings/BuiltinEngineSettings.tsx
+++ b/src/components/settings/BuiltinEngineSettings.tsx
@@ -12,6 +12,7 @@ import { Hinweis } from '../ui/Hinweis'
import { bundledEngineStatus, swapBundledModel, ENGINE_PORT } from '../../api/engine'
import { useBuiltinEngineStatus } from '../../hooks/useBuiltinEngineStatus'
import { enginePortLine } from '../../lib/engine-port'
+import { engineOffloadLine } from '../../lib/engine-offload'
import type { BuiltinEngineTuning } from '../../types/settings'
type KvType = BuiltinEngineTuning['cacheTypeK']
@@ -126,6 +127,16 @@ export function BuiltinEngineSettings() {
<div className="t-micro text-gray-500" data-testid="builtin-engine-port">
{enginePortLine(status, ENGINE_PORT)}
</div>
+ {/* 3.0.0: how much of the model the card really took. Empty on the
+ ordinary machine, where every layer was asked for and got. A start
+ that ended on the processor by itself says so HERE as well as in the
+ standing line above the composer, because that line is an event and
+ walks away, while this stays true for as long as the process runs. */}
+ {engineOffloadLine(status) ? (
+ <div className="t-micro text-gray-500" data-testid="builtin-engine-offload">
+ {engineOffloadLine(status)}
+ </div>
+ ) : null}
{/* Context length */}
<div className="flex items-center justify-between">
diff --git a/src/components/settings/__tests__/engine-offload-is-visible.test.ts b/src/components/settings/__tests__/engine-offload-is-visible.test.ts
new file mode 100644
index 00000000..e3a4500f
--- /dev/null
+++ b/src/components/settings/__tests__/engine-offload-is-visible.test.ts
@@ -0,0 +1,174 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * 3.0.0 leftover, found 2026-09-11: the CPU fallback had no surface.
+ *
+ * Commit ccdc2d14 gave the engine a second start attempt that drops GPU
+ * offload when the first one dies with layers on the card, and a layer count
+ * measured against free graphics memory instead of a flat `-ngl 999`. Both
+ * worked. Neither could be seen: `start_bundled_engine` answered
+ * `cpuOnly: true` in the return value of one call, every caller read `.port`
+ * out of that object and threw the rest away, and the layer count lived in the
+ * argv and the log file. A user whose card could not hold the model got an
+ * engine that looked ordinary, said nothing, and answered at a tenth of the
+ * speed.
+ *
+ * Two surfaces, because the two facts have different lifetimes: the fallback
+ * is an event and goes to the standing line above the composer, the layer
+ * count is a condition and goes where Settings already names model, context
+ * and port.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/engine-offload-is-visible.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 backendCall = vi.fn()
+vi.mock('../../../api/backend', () => ({
+ backendCall: (cmd: string, args?: unknown) => backendCall(cmd, args),
+ isTauri: () => true,
+ isMacOS: () => false,
+ isLinux: () => false,
+ isWindows: () => false,
+ openExternal: vi.fn(),
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+
+const { engineOffloadLine, announceEngineCpuFallback, ENGINE_CPU_ONLY_NOTE, __resetEngineCpuFallbackNote } =
+ await import('../../../lib/engine-offload')
+const { bundledEngineStatus } = await import('../../../api/engine')
+const { useLuEngineSwitchStore } = await import('../../../stores/luEngineSwitchStore')
+const { BuiltinEngineSettings } = await import('../BuiltinEngineSettings')
+const { LuEngineSwitchBar } = await import('../../chat/LuEngineSwitchBar')
+
+/** A running engine that took the whole model onto the card. The ordinary one. */
+const AUF_DER_KARTE = {
+ running: true, healthy: true, port: 8127,
+ model_path: '/m/phi.gguf', ctx: 8192, cpuOnly: false, gpuLayers: null,
+}
+
+/** The same engine after the GPU attempt died and the retry took the card out. */
+const AUF_DEM_PROZESSOR = { ...AUF_DER_KARTE, cpuOnly: true, gpuLayers: 0 }
+
+beforeEach(() => {
+ backendCall.mockReset()
+ backendCall.mockResolvedValue({})
+ __resetEngineCpuFallbackNote()
+ useLuEngineSwitchStore.getState().dismiss()
+})
+afterEach(() => { cleanup(); vi.useRealTimers() })
+
+/** Mount the expert panel over one status answer and read its offload line. */
+async function panel(status: unknown): Promise<string | null> {
+ backendCall.mockImplementation(async (cmd: string) =>
+ cmd === 'bundled_engine_status' ? status : {})
+ render(createElement(BuiltinEngineSettings))
+ await act(async () => { await Promise.resolve(); await Promise.resolve() })
+ return screen.queryByTestId('builtin-engine-offload')?.textContent ?? null
+}
+
+/** Read one status through the app's own wrapper, then draw the standing line. */
+async function standingLine(status: unknown): Promise<HTMLElement | null> {
+ backendCall.mockImplementation(async (cmd: string) =>
+ cmd === 'bundled_engine_status' ? status : {})
+ await act(async () => { await bundledEngineStatus() })
+ render(createElement(LuEngineSwitchBar))
+ return screen.queryByTestId('lu-engine-switch-note')
+}
+
+describe('the line itself', () => {
+ it('says the card was taken out, not just that nought layers went on it', () => {
+ expect(engineOffloadLine(AUF_DEM_PROZESSOR)).toBe('GPU layers: 0, the GPU start failed')
+ })
+
+ it('names a measured layer count', () => {
+ expect(engineOffloadLine({ running: true, gpuLayers: 18 })).toBe('GPU layers: 18')
+ })
+
+ it('stays silent when every layer was asked for', () => {
+ // 999 is llama.cpp's sentinel for "all of them" and Rust withholds it, so
+ // this is what an ordinary machine produces and it deserves no line.
+ expect(engineOffloadLine(AUF_DER_KARTE)).toBeNull()
+ expect(engineOffloadLine({ running: true })).toBeNull()
+ })
+
+ it('promises nothing about an engine that is not up', () => {
+ expect(engineOffloadLine({ running: false, cpuOnly: true, gpuLayers: 0 })).toBeNull()
+ expect(engineOffloadLine(null)).toBeNull()
+ })
+
+ // A user who wrote 0 into GPU Layers got what he asked for. Telling him the
+ // graphics card failed would be an invention.
+ it('does not call a typed zero a failed start', () => {
+ expect(engineOffloadLine({ running: true, cpuOnly: false, gpuLayers: 0 })).toBe('GPU layers: 0')
+ })
+})
+
+describe('Built-in Engine (expert) shows the layer count', () => {
+ it('says the engine ended up on the processor', async () => {
+ expect(await panel(AUF_DEM_PROZESSOR)).toBe('GPU layers: 0, the GPU start failed')
+ })
+
+ it('names the layers a measured start bought', async () => {
+ expect(await panel({ ...AUF_DER_KARTE, gpuLayers: 24 })).toBe('GPU layers: 24')
+ })
+
+ it('adds no line at all on the ordinary machine', async () => {
+ expect(await panel(AUF_DER_KARTE)).toBeNull()
+ })
+})
+
+describe('the standing line above the composer', () => {
+ it('tells the user his engine is on the CPU and where to read why', async () => {
+ const line = await standingLine(AUF_DEM_PROZESSOR)
+ expect(line?.textContent).toContain(ENGINE_CPU_ONLY_NOTE)
+ // Quiet, not red. lib/hinweis.ts: a slower engine that serves is not an
+ // error, and this app has exactly two tones.
+ expect(line?.getAttribute('data-tone')).toBe('info')
+ })
+
+ it('says nothing about an engine that got the card it wanted', async () => {
+ expect(await standingLine(AUF_DER_KARTE)).toBeNull()
+ })
+
+ it('says it once per engine, not once per poll', async () => {
+ await standingLine(AUF_DEM_PROZESSOR)
+ useLuEngineSwitchStore.getState().dismiss()
+ // Three more polls of the SAME process. A note the user has just closed
+ // must not come back three seconds later.
+ await act(async () => { await bundledEngineStatus() })
+ await act(async () => { await bundledEngineStatus() })
+ await act(async () => { await bundledEngineStatus() })
+ expect(useLuEngineSwitchStore.getState().note).toBeNull()
+ })
+
+ it('speaks again when a new engine falls back', async () => {
+ await standingLine(AUF_DEM_PROZESSOR)
+ useLuEngineSwitchStore.getState().dismiss()
+ backendCall.mockImplementation(async (cmd: string) =>
+ cmd === 'bundled_engine_status' ? { ...AUF_DEM_PROZESSOR, model_path: '/m/qwen.gguf' } : {})
+ await act(async () => { await bundledEngineStatus() })
+ expect(useLuEngineSwitchStore.getState().note).toBe(ENGINE_CPU_ONLY_NOTE)
+ })
+
+ it('holds the note back while no view can draw it', async () => {
+ // The poll behind Settings is one of the two that reach this code, and
+ // Settings does not draw the line. Announcing there on the ordinary clock
+ // would spend the whole twelve seconds on a page that cannot show it.
+ const { useUIStore } = await import('../../../stores/uiStore')
+ useUIStore.setState({ currentView: 'settings' })
+ try {
+ announceEngineCpuFallback(AUF_DEM_PROZESSOR)
+ expect(useLuEngineSwitchStore.getState().note).toBe(ENGINE_CPU_ONLY_NOTE)
+ // Still standing after the ordinary clock would have cleared it.
+ vi.useFakeTimers()
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000) })
+ expect(useLuEngineSwitchStore.getState().note).toBe(ENGINE_CPU_ONLY_NOTE)
+ } finally {
+ useUIStore.setState({ currentView: 'chat' })
+ }
+ })
+})
diff --git a/src/lib/engine-offload.ts b/src/lib/engine-offload.ts
new file mode 100644
index 00000000..8e075af0
--- /dev/null
+++ b/src/lib/engine-offload.ts
@@ -0,0 +1,133 @@
+/**
+ * Where the LU Engine actually computes, said out loud.
+ *
+ * Commit ccdc2d14 (3.0.0, bugs u and a) taught the engine two things: to
+ * measure free graphics memory and buy a layer count with it instead of
+ * demanding all of them, and to run the SECOND start attempt on the processor
+ * when the first one died with layers on the card. Both are real repairs and
+ * neither had a surface. `start_bundled_engine` answered `cpuOnly: true` once,
+ * in the return value of the call that started it, and every caller read
+ * `.port` out of that object and dropped the rest on the floor. The layer
+ * count existed only inside the argv and the log file.
+ *
+ * So a user whose card could not hold the model got exactly what the reports
+ * described before the fix, minus the crash: an engine that looks ordinary,
+ * says nothing, and answers at a tenth of the speed. "Why is it suddenly slow"
+ * had no answer anywhere in the window.
+ *
+ * Two statements, because the two facts have different lifetimes:
+ *
+ * - the fallback is an EVENT. It happened at a moment, to this engine, and
+ * the user has something to do about it (read the log, close whatever is
+ * holding the card, pick a smaller model). It goes to the standing line
+ * above the composer, once per engine.
+ * - the layer count is a CONDITION. It stays true for as long as the process
+ * runs, so it belongs where the app already says which model, which
+ * context and which port: the Built-in Engine panel in Settings.
+ *
+ * Quiet tone for both. lib/hinweis.ts allows exactly two, and this is not an
+ * error: the engine is serving, the chat works, it is slower than it could be.
+ */
+
+import { useUIStore } from '../stores/uiStore'
+import { useLuEngineSwitchStore } from '../stores/luEngineSwitchStore'
+
+/** What a `bundled_engine_status` answer says about offload. */
+export interface EngineOffloadStatus {
+ running?: boolean
+ port?: number | null
+ model_path?: string | null
+ /** The app took the graphics card away by itself after a start died. NOT a
+ * GPU Layers of 0 that the user typed into Settings. */
+ cpuOnly?: boolean
+ /** The `-ngl` the process really carries, null when it asked for all of
+ * them. Rust withholds the 999 sentinel rather than making every surface
+ * know what it means (`gpu_layers_reported`). */
+ gpuLayers?: number | null
+}
+
+/** The sentence the standing line carries after a fallback. */
+export const ENGINE_CPU_ONLY_NOTE =
+ 'Running on the CPU. The GPU start failed; see the log file in Settings > Troubleshoot.'
+
+/**
+ * The clause the engine-details line adds, or null when there is nothing to
+ * add.
+ *
+ * Null is the ordinary answer: a card with room, and a machine nothing could
+ * measure, both ask for every layer, and a line reading "GPU layers: 999"
+ * would be printing llama.cpp's sentinel at a person.
+ */
+export function engineOffloadLine(status: EngineOffloadStatus | null | undefined): string | null {
+ if (!status?.running) return null
+ // A zero the app chose is not the same sentence as a zero the user typed, so
+ // the fallback is named before the number is.
+ if (status.cpuOnly) return 'GPU layers: 0, the GPU start failed'
+ const layers = status.gpuLayers
+ if (typeof layers !== 'number' || !Number.isInteger(layers) || layers < 0) return null
+ return `GPU layers: ${layers}`
+}
+
+/**
+ * Which engine a fallback note would be about, or null when there is none.
+ *
+ * Port and model together: a restart onto another port, or a swap to another
+ * model, is a new engine and deserves to be told about again. The same process
+ * polled every three seconds is not.
+ */
+export function engineCpuFallbackKey(status: EngineOffloadStatus | null | undefined): string | null {
+ if (!status?.running || !status.cpuOnly) return null
+ return `${status.port ?? '?'}|${status.model_path ?? '?'}`
+}
+
+/**
+ * The views that actually draw the standing line (`LuEngineSwitchBar`).
+ *
+ * Lives here, in the leaf, because two callers need it and one of them
+ * (api/lu-engine-switch) cannot be imported from the status path without a
+ * cycle. It is the same list either way and must not become two.
+ */
+export const VIEWS_WITH_THE_ENGINE_NOTE: ReadonlySet<string> = new Set(['chat', 'models'])
+
+/**
+ * How long a note waits for a reader before it gives up.
+ *
+ * The engine status is polled from Settings, which does NOT draw the standing
+ * line, so a note announced from there would spend its twelve seconds on a
+ * page that cannot show it. Generous enough for a round through Settings,
+ * short enough that the sentence still describes something the user just did.
+ */
+export const ENGINE_NOTE_UNSEEN_HOLD_MS = 5 * 60_000
+
+/** The last engine a fallback was announced for, so a poll cannot repeat it. */
+let angesagt: string | null = null
+
+/** Test-only: forget what was said. */
+export function __resetEngineCpuFallbackNote(): void {
+ angesagt = null
+}
+
+/**
+ * Say that this engine ended up on the processor, once.
+ *
+ * Called wherever a status answer arrives: the poll behind Settings and the
+ * models view, and the pre-send probe that runs in the chat. Cheap and quiet
+ * when there is nothing to say, which is almost always.
+ */
+export function announceEngineCpuFallback(status: EngineOffloadStatus | null | undefined): void {
+ const key = engineCpuFallbackKey(status)
+ if (key === null) {
+ // The engine came back on the card, or stopped. The next fallback is a new
+ // fact and has to be allowed to speak.
+ angesagt = null
+ return
+ }
+ if (angesagt === key) return
+ angesagt = key
+ const ende = Date.now() + ENGINE_NOTE_UNSEEN_HOLD_MS
+ useLuEngineSwitchStore.getState().announce(
+ ENGINE_CPU_ONLY_NOTE,
+ 'info',
+ () => Date.now() < ende && !VIEWS_WITH_THE_ENGINE_NOTE.has(useUIStore.getState().currentView),
+ )
+}