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): the app checks which model is loaded before it sends

purplea39a6f765219
diff --git a/src/api/__tests__/builtin-model-guard.test.ts b/src/api/__tests__/builtin-model-guard.test.ts
new file mode 100644
index 00000000..aa839708
--- /dev/null
+++ b/src/api/__tests__/builtin-model-guard.test.ts
@@ -0,0 +1,172 @@
+/**
+ * 2.6.7 counter-check, nebenbefund 1: the built-in engine ignores the `model`
+ * field. With Gemma loaded, requests naming Hermes and even naming a model
+ * that does not exist were answered by Gemma, with no error. The app never
+ * asked whether the loaded model IS the requested one, so a group chat with
+ * two local speakers showed two names and ran one model.
+ *
+ * These tests pin the app side of the cure: the send-time gate now compares
+ * and reloads, and `builtinReloadNeeded` answers the same question without
+ * acting so the group round can say what it is waiting for.
+ *
+ * Run: npx vitest run src/api/__tests__/builtin-model-guard.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+let managed = true
+vi.mock('../../stores/providerStore', () => ({
+ useProviderStore: {
+ getState: () => ({ providers: { openai: { enabled: true, managed } } }),
+ },
+}))
+
+const TUNING = { ctx: 16384 }
+vi.mock('../../stores/settingsStore', () => ({
+ useSettingsStore: {
+ getState: () => ({ settings: { builtinEngine: TUNING } }),
+ },
+}))
+
+const backendCall = vi.fn()
+vi.mock('../backend', () => ({
+ backendCall: (...args: any[]) => backendCall(...args),
+}))
+
+import { ensureBuiltinEngineAlive, builtinReloadNeeded } from '../builtin-ensure'
+
+const GEMMA = { name: 'gemma-3-4b-it-abliterated-Q4_K_M', path: 'C:\\m\\gemma-3-4b-it-abliterated-Q4_K_M.gguf' }
+const HERMES = { name: 'Hermes-3-Llama-3.2-3B.Q4_K_M', path: 'C:\\m\\Hermes-3-Llama-3.2-3B.Q4_K_M.gguf' }
+
+/** The box as it stood: engine up, Gemma loaded, both GGUFs on disk. */
+function gemmaLoaded(list: Array<{ name: string; path: string }> = [GEMMA, HERMES]) {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') {
+ return { running: true, healthy: true, ctx: 8192, model_path: GEMMA.path }
+ }
+ if (cmd === 'list_bundled_models') return { models: list }
+ if (cmd === 'swap_bundled_model') return { status: 'started' }
+ if (cmd === 'start_bundled_engine') return { status: 'started' }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+}
+
+const callsTo = (cmd: string) => backendCall.mock.calls.filter((c) => c[0] === cmd)
+
+describe('the send-time gate enforces which model is loaded', () => {
+ beforeEach(() => {
+ backendCall.mockReset()
+ managed = true
+ })
+
+ it('swaps the engine when the request names a different model than the loaded one', async () => {
+ gemmaLoaded()
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ const swaps = callsTo('swap_bundled_model')
+ expect(swaps).toHaveLength(1)
+ expect(swaps[0][1]).toEqual({ modelPath: HERMES.path, tuning: TUNING })
+ // A swap is a restart, never a silent second engine.
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ })
+
+ // Negative control 1: the model that IS loaded must not cause a reload. A
+ // gate that swaps on every send would restart llama-server for every message.
+ it('does nothing when the loaded model is the requested one', async () => {
+ gemmaLoaded()
+ await ensureBuiltinEngineAlive('openai::gemma-3-4b-it-abliterated-Q4_K_M')
+ expect(callsTo('swap_bundled_model')).toHaveLength(0)
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ expect(callsTo('list_bundled_models')).toHaveLength(0)
+ })
+
+ // Negative control 2: an engine whose status carries no model_path cannot be
+ // judged, and guessing there would break every send on an older status shape.
+ it('does not reload when the loaded model is unknown', async () => {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') return { running: true, healthy: true }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+ await ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ expect(callsTo('swap_bundled_model')).toHaveLength(0)
+ })
+
+ it('refuses with an English sentence naming both models when the wanted one is gone', async () => {
+ // The invented name from the counter-check. Nothing to load, so the only
+ // honest answer is to say what is loaded and what was asked for.
+ gemmaLoaded([GEMMA])
+ await expect(ensureBuiltinEngineAlive('openai::gibt-es-nicht-42')).rejects.toThrow(
+ /has "gemma-3-4b-it-abliterated-Q4_K_M" loaded, but this request asked for "gibt-es-nicht-42"/,
+ )
+ expect(callsTo('swap_bundled_model')).toHaveLength(0)
+ })
+
+ it('serialises two different models instead of handing the second the first promise', async () => {
+ // The old coalescing was a single global promise: a concurrent send for
+ // another model got "ready" back without its model ever being loaded.
+ let releaseFirst!: () => void
+ const firstSwap = new Promise<void>((r) => (releaseFirst = r))
+ backendCall.mockImplementation(async (cmd: string, args?: any) => {
+ if (cmd === 'bundled_engine_status') {
+ return { running: true, healthy: true, model_path: GEMMA.path }
+ }
+ if (cmd === 'list_bundled_models') return { models: [GEMMA, HERMES] }
+ if (cmd === 'swap_bundled_model') {
+ if (args.modelPath === HERMES.path) await firstSwap
+ return { status: 'started' }
+ }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+ const a = ensureBuiltinEngineAlive('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ const b = ensureBuiltinEngineAlive('openai::gemma-3-4b-it-abliterated-Q4_K_M')
+ releaseFirst()
+ await Promise.all([a, b])
+ // The second caller ran its own check after the first finished. It asked
+ // for the model the status still reports as loaded, so it needed no swap,
+ // but it did look, which is the whole point.
+ expect(callsTo('swap_bundled_model')).toHaveLength(1)
+ expect(callsTo('bundled_engine_status')).toHaveLength(2)
+ })
+})
+
+describe('builtinReloadNeeded', () => {
+ beforeEach(() => {
+ backendCall.mockReset()
+ managed = true
+ })
+
+ it('names the model that has to be loaded first', async () => {
+ gemmaLoaded()
+ expect(await builtinReloadNeeded('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')).toBe('Hermes-3-Llama-3.2-3B.Q4_K_M')
+ })
+
+ it('answers null for the model that is already loaded', async () => {
+ gemmaLoaded()
+ expect(await builtinReloadNeeded('openai::gemma-3-4b-it-abliterated-Q4_K_M')).toBeNull()
+ })
+
+ it('answers the model when the engine is down, because a start is a load too', async () => {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') return { running: false, healthy: false, model_path: null }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+ expect(await builtinReloadNeeded('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')).toBe('Hermes-3-Llama-3.2-3B.Q4_K_M')
+ })
+
+ // Negative controls: it must stay quiet for everything that is not ours.
+ it('answers null for a cloud model, an unmanaged slot and a dead backend', async () => {
+ gemmaLoaded()
+ expect(await builtinReloadNeeded('lucloud::kimi-k2')).toBeNull()
+ expect(await builtinReloadNeeded('ollama-model-with-no-prefix')).not.toBeNull()
+ managed = false
+ expect(await builtinReloadNeeded('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')).toBeNull()
+ managed = true
+ backendCall.mockRejectedValue(new Error('not in tauri'))
+ expect(await builtinReloadNeeded('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')).toBeNull()
+ })
+
+ it('changes nothing it looked at', async () => {
+ gemmaLoaded()
+ await builtinReloadNeeded('openai::Hermes-3-Llama-3.2-3B.Q4_K_M')
+ expect(callsTo('swap_bundled_model')).toHaveLength(0)
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ })
+})
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index 6d23195e..653e3c8c 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -19,12 +19,22 @@ import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
import { builtinSlotStatus, type SlotStatus } from '../lib/builtin-slot-status'
import { AGENT_CONTEXT_CAP } from '../lib/context-window'
+import {
+ bareBuiltinModelName,
+ builtinModelMatches,
+ builtinModelMismatchMessage,
+ builtinModelNameFromPath,
+} from '../lib/builtin-model-identity'
interface EngineStatusLite {
running: boolean
healthy: boolean
/** The `--ctx-size` the chat engine was started with (ENG-3). */
ctx?: number | null
+ /** Absolute path of the GGUF the engine was started with, null when it is
+ * 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
}
interface BundledList {
@@ -34,7 +44,12 @@ interface BundledList {
// Coalesce concurrent sends (chat + title generation) into ONE health-check /
// restart. start_bundled_engine blocks until /health is green, so awaiting the
// same promise is exactly "wait for the restart the other call kicked off".
-let inflight: Promise<void> | null = null
+//
+// Keyed by model since 2.6.7: the call can now SWAP the loaded model, and a
+// second caller asking for a different model must not be handed the first
+// caller's promise and told the engine is ready. Same model rides along, a
+// different model waits its turn and then runs its own check.
+let inflight: { key: string; promise: Promise<void> } | null = null
/**
* Rewrite a transport failure against our own engine into something a user can
@@ -62,58 +77,118 @@ export function isManagedBuiltinSlot(): boolean {
}
/**
- * Make sure the built-in engine is up before a send. No-op when the slot is
- * not managed, the engine is already healthy, or `modelName` is not a bundled
- * GGUF (nothing we own to heal). Throws only when an actual restart attempt
- * fails — that error carries llama-server's stderr tail and IS the honest
- * thing to show in the chat instead of a bare "fetch failed".
+ * Is the engine about to answer with the wrong model.
+ *
+ * Answers the question `ensureBuiltinEngineAlive` acts on, without acting:
+ * null when nothing has to happen, otherwise the bare id that has to be loaded
+ * first. The group round asks this so it can put a loading line in the bubble
+ * BEFORE it waits, because a swap stops and restarts llama-server and a large
+ * GGUF takes long enough that a silent wait reads as a hang.
+ *
+ * Never throws and never changes anything.
+ */
+export async function builtinReloadNeeded(modelName: string): Promise<string | null> {
+ if (!isManagedBuiltinSlot()) return null
+ // A model from another provider slot travels through its own provider and
+ // has nothing to do with our engine.
+ const parts = modelName.split('::')
+ if (parts.length === 2 && parts[0] !== 'openai') return null
+ const bare = bareBuiltinModelName(modelName)
+ if (!bare) return null
+ try {
+ const status = await backendCall<EngineStatusLite>('bundled_engine_status')
+ if (!status?.healthy) return bare
+ return builtinModelMatches(status.model_path, bare) ? null : bare
+ } catch {
+ return null // non-Tauri context (tests/browser), nothing to manage
+ }
+}
+
+/**
+ * Make sure the built-in engine is up AND holding `modelName` before a send.
+ * No-op when the slot is not managed or the engine already has that exact
+ * model. Throws only when an actual start/swap attempt fails, and that error
+ * carries llama-server's stderr tail and IS the honest thing to show in the
+ * chat instead of a bare "fetch failed".
+ *
+ * The model half is new in 2.6.7 and is the app-side cure for the counter-check
+ * finding: llama-server answers whatever it holds, whatever the `model` field
+ * says, so "the engine is healthy" was never enough to send.
*/
export async function ensureBuiltinEngineAlive(modelName: string): Promise<void> {
if (!isManagedBuiltinSlot()) return
- if (inflight) return inflight
- inflight = (async () => {
- try {
- let status: EngineStatusLite | null
- try {
- status = await backendCall<EngineStatusLite>('bundled_engine_status')
- } catch {
- return // non-Tauri context (tests/browser) — nothing to manage
- }
- if (status?.healthy) return
-
- let models: Array<{ name: string; path: string }>
- try {
- const res = await backendCall<BundledList>('list_bundled_models')
- models = res?.models ?? []
- } catch {
- return
- }
- const bare = modelName.includes('::') ? modelName.split('::')[1] : modelName
- const hit = models.find((m) => m.name === bare)
- if (!hit) {
- // The slot IS our engine (managed), the engine is NOT healthy, and the
- // model the picker is holding is not on disk where the engine looks.
- // Returning quietly here sent the send straight into a dead port, and
- // the user got "proxy_localhost_stream_chunked: error sending request
- // for url (http://127.0.0.1:8127/v1/chat/completions)" as their first
- // impression of the app (applejames, Discord 2026-08-01, fresh install
- // on Windows 10 — they gave up on the built-in engine and moved to
- // Ollama). Say what is actually wrong instead.
- throw new Error(
- `The built-in engine has no model file named "${bare}". It may have been deleted, moved, or the download did not finish. Open Models, install it again, then pick it in the chat.`,
- )
- }
-
- // Restart with the user's expert tuning, not bare defaults — otherwise a
- // self-heal would silently drop a configured ctx/KV-quant until the next
- // manual model pick.
- const tuning = useSettingsStore.getState().settings.builtinEngine
- await backendCall('start_bundled_engine', { modelPath: hit.path, tuning })
- } finally {
- inflight = null
- }
+ const key = bareBuiltinModelName(modelName)
+ if (inflight && inflight.key === key) return inflight.promise
+ const earlier = inflight?.promise
+ const run = (async () => {
+ // A swap for another model is already running: let it finish rather than
+ // fight it for the one engine process. Its failure is its own caller's to
+ // report, so it is swallowed here.
+ if (earlier) await earlier.catch(() => undefined)
+ await loadBuiltinModel(modelName)
})()
- return inflight
+ inflight = { key, promise: run }
+ try {
+ await run
+ } finally {
+ if (inflight?.promise === run) inflight = null
+ }
+}
+
+/** The body of `ensureBuiltinEngineAlive`, minus the coalescing. */
+async function loadBuiltinModel(modelName: string): Promise<void> {
+ let status: EngineStatusLite | null
+ try {
+ status = await backendCall<EngineStatusLite>('bundled_engine_status')
+ } catch {
+ return // non-Tauri context (tests/browser) — nothing to manage
+ }
+ // 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.
+ const rightModel = builtinModelMatches(status?.model_path, modelName)
+ if (status?.healthy && rightModel) return
+
+ let models: Array<{ name: string; path: string }>
+ try {
+ const res = await backendCall<BundledList>('list_bundled_models')
+ models = res?.models ?? []
+ } catch {
+ return
+ }
+ const bare = bareBuiltinModelName(modelName)
+ const hit = models.find((m) => m.name === bare)
+ if (!hit && status?.healthy) {
+ // The engine runs, it holds something else, and the model the caller named
+ // is not on disk. Loading it is impossible, and letting the send through
+ // would hand the user another model's answer under this model's name.
+ // Say which is which instead.
+ throw new Error(builtinModelMismatchMessage(builtinModelNameFromPath(status.model_path), bare))
+ }
+ if (!hit) {
+ // The slot IS our engine (managed), the engine is NOT healthy, and the
+ // model the picker is holding is not on disk where the engine looks.
+ // Returning quietly here sent the send straight into a dead port, and
+ // the user got "proxy_localhost_stream_chunked: error sending request
+ // for url (http://127.0.0.1:8127/v1/chat/completions)" as their first
+ // impression of the app (applejames, Discord 2026-08-01, fresh install
+ // on Windows 10 — they gave up on the built-in engine and moved to
+ // Ollama). Say what is actually wrong instead.
+ throw new Error(
+ `The built-in engine has no model file named "${bare}". It may have been deleted, moved, or the download did not finish. Open Models, install it again, then pick it in the chat.`,
+ )
+ }
+
+ // Restart with the user's expert tuning, not bare defaults — otherwise a
+ // self-heal would silently drop a configured ctx/KV-quant until the next
+ // manual model pick.
+ const tuning = useSettingsStore.getState().settings.builtinEngine
+ // A running engine holding the WRONG model is a swap (stop, then start on
+ // the same port). Everything else is a plain start, which is idempotent for
+ // the same model and tuning, so an engine that is merely still warming up is
+ // never torn down and restarted for nothing.
+ const cmd = status?.running && !rightModel ? 'swap_bundled_model' : 'start_bundled_engine'
+ await backendCall(cmd, { modelPath: hit.path, tuning })
}
// The default the engine ships with. A settings ctx equal to it is treated as
diff --git a/src/lib/__tests__/builtin-model-identity.test.ts b/src/lib/__tests__/builtin-model-identity.test.ts
new file mode 100644
index 00000000..8be3c89c
--- /dev/null
+++ b/src/lib/__tests__/builtin-model-identity.test.ts
@@ -0,0 +1,102 @@
+/**
+ * The rules behind "is the built-in engine holding the model this request
+ * names". Pure, so the Rust twin in `commands/proxy.rs` can be read against
+ * the same table.
+ *
+ * Run: npx vitest run src/lib/__tests__/builtin-model-identity.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ bareBuiltinModelName,
+ builtinModelMatches,
+ builtinModelMismatchMessage,
+ builtinModelNameFromPath,
+} from '../builtin-model-identity'
+
+describe('builtinModelNameFromPath', () => {
+ it('reads the picker id off a posix path', () => {
+ expect(builtinModelNameFromPath('/Users/x/models/qwen2.5-0.5b.gguf')).toBe('qwen2.5-0.5b')
+ })
+
+ it('reads the picker id off a windows path, which is what Rust hands us there', () => {
+ expect(
+ builtinModelNameFromPath('C:\\Users\\ddrob\\AppData\\Roaming\\lu\\models\\mlabonne_gemma-3-4b-it-abliterated-Q4_K_M.gguf'),
+ ).toBe('mlabonne_gemma-3-4b-it-abliterated-Q4_K_M')
+ })
+
+ it('collapses a gguf-split part back to the name the picker shows', () => {
+ // scan_gguf_models lists a split set under the base name and points at
+ // part 1, so a raw stem compare would call every split model a mismatch.
+ expect(builtinModelNameFromPath('/m/DeepSeek-V4-Flash-Q4_K_M-00001-of-00003.gguf')).toBe('DeepSeek-V4-Flash-Q4_K_M')
+ })
+
+ it('tolerates an upper case extension from a hand copied file', () => {
+ expect(builtinModelNameFromPath('/m/Model.GGUF')).toBe('Model')
+ })
+
+ it('answers empty for nothing loaded', () => {
+ expect(builtinModelNameFromPath(null)).toBe('')
+ expect(builtinModelNameFromPath(undefined)).toBe('')
+ expect(builtinModelNameFromPath(' ')).toBe('')
+ })
+
+ // Negative control: a name that merely LOOKS like a shard keeps its suffix,
+ // so a real model called "...-of-..." is not renamed out from under itself.
+ it('does not strip a suffix that is not a shard marker', () => {
+ expect(builtinModelNameFromPath('/m/best-of-both-worlds.gguf')).toBe('best-of-both-worlds')
+ expect(builtinModelNameFromPath('/m/model-1-of-3.gguf')).toBe('model-1-of-3')
+ })
+})
+
+describe('bareBuiltinModelName', () => {
+ it('strips the provider prefix and a trailing extension', () => {
+ expect(bareBuiltinModelName('openai::qwen2.5-0.5b')).toBe('qwen2.5-0.5b')
+ expect(bareBuiltinModelName('qwen2.5-0.5b')).toBe('qwen2.5-0.5b')
+ expect(bareBuiltinModelName('openai::qwen2.5-0.5b.gguf')).toBe('qwen2.5-0.5b')
+ })
+
+ it('leaves a name with more than one separator alone, as the registry does', () => {
+ // getProviderIdFromModel only treats an exactly-two-part split as prefixed.
+ expect(bareBuiltinModelName('a::b::c')).toBe('a::b::c')
+ })
+
+ it('answers empty for nothing', () => {
+ expect(bareBuiltinModelName(undefined)).toBe('')
+ })
+})
+
+describe('builtinModelMatches', () => {
+ it('is true for the same model, prefixed or not', () => {
+ expect(builtinModelMatches('/m/qwen2.5-0.5b.gguf', 'qwen2.5-0.5b')).toBe(true)
+ expect(builtinModelMatches('/m/qwen2.5-0.5b.gguf', 'openai::qwen2.5-0.5b')).toBe(true)
+ })
+
+ it('is FALSE for the case the counter-check measured on the box', () => {
+ // Gemma loaded, request says Hermes. The engine answered it with Gemma.
+ expect(
+ builtinModelMatches('C:\\m\\mlabonne_gemma-3-4b-it-abliterated-Q4_K_M.gguf', 'Hermes-3-Llama-3.2-3B.Q4_K_M'),
+ ).toBe(false)
+ // And the invented name, which was answered just as happily.
+ expect(builtinModelMatches('C:\\m\\mlabonne_gemma-3-4b-it-abliterated-Q4_K_M.gguf', 'gibt-es-nicht-42')).toBe(false)
+ })
+
+ // Negative control: not knowing must never be reported as a mismatch, or
+ // every send against an engine whose status carries no path would die.
+ it('is true when either side is unknown', () => {
+ expect(builtinModelMatches(null, 'qwen2.5-0.5b')).toBe(true)
+ expect(builtinModelMatches('/m/qwen2.5-0.5b.gguf', '')).toBe(true)
+ expect(builtinModelMatches(undefined, undefined)).toBe(true)
+ })
+})
+
+describe('builtinModelMismatchMessage', () => {
+ it('names both models, in English, without a dash', () => {
+ const msg = builtinModelMismatchMessage('gemma-3-4b', 'Hermes-3')
+ expect(msg).toContain('"gemma-3-4b"')
+ expect(msg).toContain('"Hermes-3"')
+ expect(msg).not.toMatch(/[—–]/)
+ // English only: no localised operating system wording ever reaches here,
+ // and no German word is allowed in a user facing string.
+ expect(msg).toMatch(/^[\x20-\x7E]+$/)
+ })
+})
diff --git a/src/lib/builtin-model-identity.ts b/src/lib/builtin-model-identity.ts
new file mode 100644
index 00000000..7c4bcba7
--- /dev/null
+++ b/src/lib/builtin-model-identity.ts
@@ -0,0 +1,88 @@
+/**
+ * Which model the built-in engine is really holding.
+ *
+ * Counter-check finding, Windows box 2026-08-28: with Gemma loaded, a request
+ * carrying `"model": "Hermes-3-Llama-3.2-3B.Q4_K_M"` and even one carrying
+ * `"model": "gibt-es-nicht-42"` were both answered by Gemma, with no error and
+ * no model change. That is llama-server behaving as documented: it serves the
+ * one model it was started with and treats the `model` field as a label. The
+ * app never checked, so the user could be shown one name and be answered by
+ * another. In a group chat with two local speakers that is not an edge case,
+ * it is every single round.
+ *
+ * These are the pure halves of the check: the picker id of a loaded GGUF path,
+ * the bare id behind a picker id, and the comparison between them. Kept apart
+ * from `api/builtin-ensure` so the rules can be tested without a store or a
+ * Tauri backend, and so the Rust guard in `commands/proxy.rs` has a readable
+ * twin to mirror (`builtin_model_name_from_path` there).
+ */
+
+/**
+ * llama.cpp gguf-split suffix on a file STEM (the extension is already gone).
+ * `scan_gguf_models` in Rust collapses a split set into one entry named after
+ * the base and pointing at part 1, so the loaded path of a split model is
+ * `<base>-00001-of-00003.gguf` while its picker id is plain `<base>`.
+ */
+const SHARD_SUFFIX = /-\d{4,5}-of-\d{4,5}$/
+
+/**
+ * The picker id of a bundled GGUF, derived from the path the engine was
+ * started with. Handles both path separators because the loaded path comes
+ * from Rust and may be a Windows one.
+ *
+ * Empty string when nothing is loaded, which callers must read as "unknown",
+ * never as "mismatch".
+ */
+export function builtinModelNameFromPath(modelPath: string | null | undefined): string {
+ const raw = (modelPath ?? '').trim()
+ if (!raw) return ''
+ const leaf = raw.split(/[\\/]/).pop() ?? ''
+ const stem = leaf.replace(/\.gguf$/i, '')
+ return stem.replace(SHARD_SUFFIX, '')
+}
+
+/**
+ * The bare model id behind a picker id: `openai::qwen2.5-0.5b` and
+ * `qwen2.5-0.5b` both answer `qwen2.5-0.5b`. A trailing `.gguf` is dropped so
+ * a caller that passes the file name still lines up with the listing.
+ */
+export function bareBuiltinModelName(nameOrPrefixed: string | null | undefined): string {
+ const raw = (nameOrPrefixed ?? '').trim()
+ const parts = raw.split('::')
+ const bare = parts.length === 2 ? parts[1] : raw
+ return bare.replace(/\.gguf$/i, '')
+}
+
+/**
+ * Does the engine hold what the request asks for.
+ *
+ * True whenever the answer is not a proven mismatch: an unknown loaded path
+ * (engine not running, or a status shape without one) and an empty request
+ * both mean there is nothing to contradict, and inventing a mismatch there
+ * would break sends that were always fine. Only two known, different names
+ * count as a mismatch.
+ */
+export function builtinModelMatches(
+ loadedPath: string | null | undefined,
+ requested: string | null | undefined,
+): boolean {
+ const loaded = builtinModelNameFromPath(loadedPath)
+ const want = bareBuiltinModelName(requested)
+ if (!loaded || !want) return true
+ return loaded === want
+}
+
+/**
+ * The English sentence a user gets when a request names a model the engine is
+ * not holding and the app cannot load it (the file is gone). The wording says
+ * what was asked for, what is loaded, and what to do, because "model not
+ * found" on a server that answers everything is the least helpful thing we
+ * could say.
+ */
+export function builtinModelMismatchMessage(loadedName: string, requestedName: string): string {
+ return (
+ `The built-in engine has "${loadedName}" loaded, but this request asked for "${requestedName}". ` +
+ 'The engine serves only the model it was started with, so answering would have used the wrong model. ' +
+ `Install or pick "${requestedName}" in Models and send again.`
+ )
+}