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): ein Klick startet die Engine einmal, und eine kaputte Datei heisst nicht Grafikkarte

purple29f22a1a9558
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index d2703f63..83f4d76d 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -1031,6 +1031,36 @@ fn stderr_blames_the_model(stderr: &str) -> bool {
MARKERS.iter().any(|m| lower.contains(m))
}
+/// The subset of those markers that can ONLY come from the bytes in the file:
+/// a header llama.cpp cannot parse, an architecture it does not know, a tensor
+/// count that does not match the metadata.
+///
+/// Measured 2026-09-03 on the Windows release build with a deliberately
+/// truncated GGUF (valid magic, 2 MB of zeroes). llama-server said
+/// `error loading model: unknown model architecture: ''` and exited, and the
+/// app answered "This looks like a graphics-card problem. Set GPU Layers to 0",
+/// which cannot repair a file. It answered that because the routine
+/// backend-init lines of every start on an NVIDIA box carry the word `cuda`,
+/// `stderr_blames_the_gpu` matches on that bare word, and the graphics-card
+/// branch is asked first.
+///
+/// So this question is asked BEFORE the card. `failed to load model` is
+/// deliberately NOT in here: a CUDA out-of-memory prints that line too, and on
+/// that failure GPU Layers 0 is exactly the right advice. Only markers that a
+/// working card can never produce belong here.
+fn stderr_blames_the_model_file(stderr: &str) -> bool {
+ const MARKERS: &[&str] = &[
+ "unknown model architecture",
+ "invalid magic",
+ "unsupported model",
+ "wrong number of tensors",
+ "gguf_init_from_file",
+ "failed to open gguf",
+ ];
+ let lower = stderr.to_ascii_lowercase();
+ MARKERS.iter().any(|m| lower.contains(m))
+}
+
/// One English sentence a user can act on, plus llama-server's own last words
/// so a bug report still carries them.
///
@@ -1049,6 +1079,7 @@ pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: D
&& stderr_names_a_missing_system_library(&failure.stderr).is_none()
&& stderr_blames_the_gpu(&failure.stderr)
&& !stderr_blames_the_port(&failure.stderr)
+ && !stderr_blames_the_model_file(&failure.stderr)
{
// A missing system library is asked before the card: the loader line
// "error while loading shared libraries: libvulkan.so.1" carries the
@@ -1060,6 +1091,11 @@ pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: D
// where the log carries a real bind sentence, because "cuda" appears in
// the routine backend-init lines of every start on an NVIDIA box and
// "set GPU Layers to 0" does not free a busy port.
+ // And the FILE is asked before the card, for the same kind of reason
+ // one step further: llama.cpp answers any load error through its
+ // auto-fit path, whose line carries the words "device memory", so a
+ // GGUF with a header it cannot parse used to arrive here and be sent
+ // away as a graphics-card problem. No setting repairs a broken file.
format!("The LU Engine started and exited again before it could serve on port {port}. It was tried twice. This looks like a graphics-card problem. Open Settings, LU Engine and set GPU Layers to 0 to run on the CPU, then try again.")
} else if failure.died && stderr_blames_the_port(&failure.stderr) {
format!(
@@ -3476,6 +3512,54 @@ mod tests {
assert!(!msg.contains("GPU Layers"), "{msg}");
}
+ /// The real tail of a real failure, captured 2026-09-03 on the Windows
+ /// release build after starting a deliberately truncated GGUF (valid
+ /// magic, 2 MB of zeroes) through the Use button.
+ ///
+ /// It carries no `cuda` line at all. What put it on the graphics-card
+ /// branch is llama.cpp's own auto-fit line, "trying to fit params to free
+ /// DEVICE MEMORY", which it prints on any load error, and which matches
+ /// the `device memory` marker in `stderr_blames_the_gpu`. So the user was
+ /// told to set GPU Layers to 0 on a file that no setting can repair.
+ const KAPUTTE_GGUF_STDERR: &str = "\
+srv load_model: loading model 'C:\\Users\\x\\models\\diag-kaputt.gguf'
+llama_model_load: error loading model: unknown model architecture: ''
+llama_model_load_from_file_impl: failed to load model
+common_fit_params: encountered an error while trying to fit params to free device memory: failed to load model
+cmn common_init_: failed to load model 'C:\\Users\\x\\models\\diag-kaputt.gguf'
+srv llama_server: exiting due to model loading error";
+
+ #[test]
+ fn a_broken_file_is_not_reported_as_a_graphics_card_problem() {
+ let f = StartFailure {
+ died: true,
+ port_taken: false,
+ stderr: KAPUTTE_GGUF_STDERR.into(),
+ };
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ assert!(msg.contains("refused the model file"), "{msg}");
+ assert!(!msg.contains("GPU Layers"), "{msg}");
+ assert!(!msg.contains("graphics-card"), "{msg}");
+ // The engine's own last words still travel, for a bug report.
+ assert!(msg.contains("unknown model architecture"), "{msg}");
+ }
+
+ #[test]
+ fn a_card_that_runs_out_of_memory_keeps_the_gpu_layers_way_out() {
+ // The negative control for the test above, and the reason
+ // `failed to load model` is NOT one of the file-structure markers: a
+ // CUDA out-of-memory prints that same line, and there GPU Layers 0 is
+ // exactly the advice that gets the user chatting.
+ let f = StartFailure {
+ died: true,
+ port_taken: false,
+ stderr: "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 9216.00 MiB on device 0: cudaMalloc failed: out of memory\nllama_model_load: error loading model: unable to allocate CUDA0 buffer\nllama_model_load_from_file_impl: failed to load model".into(),
+ };
+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60));
+ assert!(msg.contains("GPU Layers"), "{msg}");
+ assert!(!msg.contains("refused the model file"), "{msg}");
+ }
+
#[test]
fn a_stranger_on_the_port_keeps_its_own_message() {
let f = StartFailure { died: true, port_taken: true, stderr: String::new() };
diff --git a/src/api/__tests__/ein-klick-startet-die-engine-einmal.test.ts b/src/api/__tests__/ein-klick-startet-die-engine-einmal.test.ts
new file mode 100644
index 00000000..b7a14e34
--- /dev/null
+++ b/src/api/__tests__/ein-klick-startet-die-engine-einmal.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Ein Klick auf Use startet die Engine EINMAL, auch wenn sie nicht hochkommt.
+ *
+ * Gemessen am 03.09.2026 auf dem Windows-Release-Build. Eine absichtlich
+ * abgeschnittene GGUF (gueltiger Magic, 2 MB Nullen) ueber den Use-Knopf
+ * gestartet, ein Prozesswaechter zaehlte mit: VIER lu-llama-server, in zwei
+ * Paaren 5,7 s auseinander, alle vier mit identischem argv. Auf dem Schirm
+ * stand "It was tried twice".
+ *
+ * Ursache sind zwei Aufrufer an einer Engine. `useModels.activateModel` ruft
+ * `setActiveModel(name)`, und der Speicher (`stores/modelStore.ts`) startet in
+ * derselben Aktualisierung selbst eine Aktivierung; danach ruft der Hook im
+ * selben Tick noch einmal. Der Kommentar im Speicher sagt, Rusts argv-
+ * Idempotenz mache den zweiten Aufruf zum Nichtstun. Fuer ein Modell, das
+ * LAEDT, stimmt das. Fuer eines, das nicht laedt, gibt es keine laufende
+ * Engine, mit deren argv man vergleichen koennte, also laeuft die ganze
+ * Routine ein zweites Mal, Wiederholungsversuch inklusive.
+ *
+ * Run: npx vitest run src/api/__tests__/ein-klick-startet-die-engine-einmal.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../backend', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../backend')>()
+ return { ...actual, backendCall: vi.fn() }
+})
+
+import { activateBuiltinModel, listBundledModels, __resetActivationsForTests } from '../engine'
+import { backendCall } from '../backend'
+import type { BuiltinEngineTuning } from '../../types/settings'
+
+/** Die volle Struktur, damit der Test denselben Vertrag benutzt wie die App. */
+const einstellung = (ctx: number): BuiltinEngineTuning => ({
+ ctx,
+ flashAttn: 'auto',
+ cacheTypeK: 'f16',
+ cacheTypeV: 'f16',
+ threads: 0,
+ gpuLayers: -1,
+ mlock: false,
+ noMmap: false,
+})
+
+const PFAD = 'C:\\models\\diag-kaputt.gguf'
+const aufruf = backendCall as unknown as ReturnType<typeof vi.fn>
+
+/** Wie viele Male ein echter Engine-Start bestellt wurde. */
+const starts = () =>
+ aufruf.mock.calls.filter(([cmd]) => cmd === 'swap_bundled_model' || cmd === 'start_bundled_engine').length
+
+beforeEach(async () => {
+ __resetActivationsForTests()
+ aufruf.mockReset()
+ // Die Liste einmal echt beantworten, damit der Pfad im Modul bekannt ist.
+ aufruf.mockResolvedValueOnce({ models: [{ name: 'diag-kaputt', path: PFAD }] })
+ await listBundledModels()
+ aufruf.mockReset()
+})
+
+describe('zwei Aufrufer, eine Engine', () => {
+ it('bestellt bei zwei gleichzeitigen Aktivierungen genau einen Start', async () => {
+ aufruf.mockResolvedValue({ port: 8127 })
+ const [a, b] = await Promise.all([
+ activateBuiltinModel('openai::diag-kaputt'),
+ activateBuiltinModel('diag-kaputt'),
+ ])
+ expect(a).toBe(true)
+ expect(b).toBe(true)
+ expect(starts()).toBe(1)
+ })
+
+ it('bestellt auch dann einen Start, wenn die Engine gar nicht hochkommt', async () => {
+ // Der teure Fall: ohne laufende Engine greift Rusts argv-Idempotenz nicht,
+ // und der zweite Aufruf haette die ganze Routine ein zweites Mal gefahren.
+ const tot = new Error('The LU Engine started and exited again before it could serve on port 8127.')
+ aufruf.mockRejectedValue(tot)
+ const ergebnisse = await Promise.allSettled([
+ activateBuiltinModel('openai::diag-kaputt'),
+ activateBuiltinModel('diag-kaputt'),
+ ])
+ expect(ergebnisse.map((e) => e.status)).toEqual(['rejected', 'rejected'])
+ // Beide Aufrufer erfahren denselben Grund, keiner bekommt ein stilles OK.
+ for (const e of ergebnisse) {
+ expect((e as PromiseRejectedResult).reason).toBe(tot)
+ }
+ expect(starts()).toBe(1)
+ })
+
+ it('laesst einen spaeteren Klick wieder wirklich starten (Negativkontrolle)', async () => {
+ // Zusammenfassen darf nur gleichzeitige Aufrufer betreffen. Wer nach einem
+ // gescheiterten Start noch einmal klickt, will einen echten neuen Versuch.
+ aufruf.mockRejectedValue(new Error('tot'))
+ await activateBuiltinModel('diag-kaputt').catch(() => undefined)
+ await activateBuiltinModel('diag-kaputt').catch(() => undefined)
+ expect(starts()).toBe(2)
+ })
+
+ it('trennt zwei Aktivierungen mit unterschiedlicher Einstellung', async () => {
+ aufruf.mockResolvedValue({ port: 8127 })
+ await Promise.all([
+ activateBuiltinModel('diag-kaputt', einstellung(8192)),
+ activateBuiltinModel('diag-kaputt', einstellung(32768)),
+ ])
+ expect(starts()).toBe(2)
+ })
+})
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 7084f2b8..ab5c2edb 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -380,10 +380,35 @@ export function bundledToAIModels(models: BundledModel[]): CloudModel[] {
}))
}
+/** Activations already on their way, keyed by GGUF path plus tuning, so two
+ * callers asking for the SAME model share one engine start. */
+const activationsInFlight = new Map<string, Promise<boolean>>()
+
/**
* Activate a built-in model by its picker id (`openai::<name>` or bare `<name>`).
* Resolves the GGUF path from the last listBundledModels() and swaps the engine.
* No-op if the path is unknown (list not yet fetched).
+ *
+ * TWO CALLERS, ONE ENGINE (measured 2026-09-03, Windows release build).
+ * Every activation happens twice. `useModels.activateModel` calls
+ * `setActiveModel(name)`, and the store chokepoint (`stores/modelStore.ts`)
+ * fires an activation of its own inside that update; the hook then calls this
+ * function again in the same tick. The picker (`ModelSelector`) does the same
+ * in the other order. The store's comment says Rust's argv idempotence turns
+ * the second call into a no-op, and for a model that LOADS that is true.
+ *
+ * For a model that does not load it is false, and expensively so. There is no
+ * running engine to compare argv against, so the second command runs the whole
+ * routine again: Rust tries once, retries once, and does it all a second time.
+ * One click on a broken GGUF spawned FOUR llama-server processes (measured:
+ * 4 spawns, in two pairs 5.7 s apart, all with identical argv), while the
+ * message on screen said "It was tried twice". Twice the wait, twice the VRAM
+ * churn, and a sentence that is off by a factor of two.
+ *
+ * So the coalescing lives here, at the one door both callers come through,
+ * rather than in either of them. Concurrent callers share the promise, failure
+ * included. A LATER click is a fresh call, because the entry is dropped as soon
+ * as the run settles, and a user retrying a failed start must really retry.
*/
export async function activateBuiltinModel(nameOrPrefixed: string, tuning?: BuiltinEngineTuning): Promise<boolean> {
const name = nameOrPrefixed.includes('::') ? nameOrPrefixed.split('::')[1] : nameOrPrefixed
@@ -395,6 +420,25 @@ export async function activateBuiltinModel(nameOrPrefixed: string, tuning?: Buil
path = pathByName.get(name)
}
if (!path) return false
- await swapBundledModel(path, tuning)
- return true
+ // The tuning is part of the key: two callers wanting the same file with
+ // different settings want two different engines, and the second must not be
+ // handed the first one's promise.
+ const key = `${path}\u0000${JSON.stringify(tuning ?? null)}`
+ const laufend = activationsInFlight.get(key)
+ if (laufend) return laufend
+ const lauf = (async () => {
+ await swapBundledModel(path as string, tuning)
+ return true
+ })()
+ activationsInFlight.set(key, lauf)
+ try {
+ return await lauf
+ } finally {
+ if (activationsInFlight.get(key) === lauf) activationsInFlight.delete(key)
+ }
+}
+
+/** Test-only: forget every in-flight activation. */
+export function __resetActivationsForTests(): void {
+ activationsInFlight.clear()
}