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.

feat(engine): expert tuning for the built-in engine (ctx, flash-attn, KV-quant, threads, GPU layers, mlock/mmap)

purple48a3b4d4354c
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 7f56032f..90fdca3a 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -65,11 +65,65 @@ pub(crate) fn host_target_triple() -> String {
}
}
+/// Expert tuning for the chat engine, settable from the app's Built-in Engine
+/// settings. `Default` reproduces the exact argv the app has always used, so
+/// an absent/partial tuning is never a behavior change. Values are whitelisted
+/// in `build_server_args` — an unknown string falls back to the default flag
+/// (settings files are user-editable; never pass them through verbatim).
+#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct EngineTuning {
+ /// Context window (`--ctx-size`). 0 is NOT forwarded as llama-server's
+ /// "use model default" — a 128k-trained model would allocate a huge KV
+ /// cache unprompted; 0/absent means our 8192 default.
+ pub ctx: u32,
+ /// Flash Attention: "auto" (binary default, omitted), "on", "off".
+ pub flash_attn: String,
+ /// KV cache quantization for K / V: "f16" (default, omitted), "bf16",
+ /// "q8_0", "q4_0". Quantized V requires Flash Attention in llama.cpp.
+ pub cache_type_k: String,
+ pub cache_type_v: String,
+ /// CPU threads for generation. <=0 = auto (omitted).
+ pub threads: i32,
+ /// GPU layers to offload. <0 = all (999, today's behavior); >=0 explicit
+ /// (0 = CPU-only is a valid expert choice on RAM-starved boxes).
+ pub gpu_layers: i32,
+ /// Pin model in RAM (`--mlock`).
+ pub mlock: bool,
+ /// Disable mmap (`--no-mmap`): slower load, fewer pageouts.
+ pub no_mmap: bool,
+}
+
+impl Default for EngineTuning {
+ fn default() -> Self {
+ Self {
+ ctx: 8192,
+ flash_attn: "auto".into(),
+ cache_type_k: "f16".into(),
+ cache_type_v: "f16".into(),
+ threads: -1,
+ gpu_layers: -1,
+ mlock: false,
+ no_mmap: false,
+ }
+ }
+}
+
+/// KV cache types this build of llama-server accepts and we consider sane.
+const KV_CACHE_TYPES: &[&str] = &["f16", "bf16", "q8_0", "q4_0"];
+
+/// The context size actually passed to the server (`tuning.ctx`, with 0
+/// falling back to the 8192 default — see `EngineTuning::ctx`).
+pub(crate) fn effective_ctx(tuning: &EngineTuning) -> u32 {
+ if tuning.ctx == 0 { 8192 } else { tuning.ctx }
+}
+
/// Build the `llama-server` argv for a chat engine. `-ngl 999` offloads every
/// 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.
-pub(crate) fn build_server_args(model_path: &str, ctx: u32, port: u16) -> Vec<String> {
- vec![
+/// 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> {
+ let mut args: Vec<String> = vec![
"-m".into(),
model_path.into(),
"--host".into(),
@@ -77,10 +131,37 @@ pub(crate) fn build_server_args(model_path: &str, ctx: u32, port: u16) -> Vec<St
"--port".into(),
port.to_string(),
"--ctx-size".into(),
- ctx.to_string(),
+ effective_ctx(tuning).to_string(),
"-ngl".into(),
- "999".into(),
- ]
+ if tuning.gpu_layers < 0 {
+ "999".into()
+ } else {
+ tuning.gpu_layers.to_string()
+ },
+ ];
+ if matches!(tuning.flash_attn.as_str(), "on" | "off") {
+ args.push("-fa".into());
+ args.push(tuning.flash_attn.clone());
+ }
+ if tuning.cache_type_k != "f16" && KV_CACHE_TYPES.contains(&tuning.cache_type_k.as_str()) {
+ args.push("-ctk".into());
+ args.push(tuning.cache_type_k.clone());
+ }
+ if tuning.cache_type_v != "f16" && KV_CACHE_TYPES.contains(&tuning.cache_type_v.as_str()) {
+ args.push("-ctv".into());
+ args.push(tuning.cache_type_v.clone());
+ }
+ if tuning.threads > 0 {
+ args.push("-t".into());
+ args.push(tuning.threads.to_string());
+ }
+ if tuning.mlock {
+ args.push("--mlock".into());
+ }
+ if tuning.no_mmap {
+ args.push("--no-mmap".into());
+ }
+ args
}
/// Build the `llama-server` argv for the EMBEDDINGS server (P5). `--embeddings`
@@ -260,12 +341,12 @@ fn wait_for_health(port: u16) -> Result<(), String> {
pub async fn start_bundled_engine(
app: AppHandle,
model_path: String,
- ctx: Option<u32>,
+ tuning: Option<EngineTuning>,
port: Option<u16>,
) -> Result<serde_json::Value, String> {
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
- start_bundled_engine_blocking(&app, &state, model_path, ctx, port)
+ start_bundled_engine_blocking(&app, &state, model_path, tuning, port)
})
.await
.map_err(|e| format!("Engine start task failed to run: {e}"))?
@@ -275,26 +356,31 @@ fn start_bundled_engine_blocking(
app: &AppHandle,
state: &State<'_, AppState>,
model_path: String,
- ctx: Option<u32>,
+ tuning: Option<EngineTuning>,
port: Option<u16>,
) -> Result<serde_json::Value, String> {
let _gate = crate::commands::process::start_gate(&crate::commands::process::ENGINE_START);
- let ctx = ctx.unwrap_or(8192);
+ let tuning = tuning.unwrap_or_default();
let port = port.unwrap_or(DEFAULT_ENGINE_PORT);
if !Path::new(&model_path).exists() {
return Err(format!("Model file not found: {model_path}"));
}
- // Already serving this exact model and healthy → no-op.
+ let desired_args = build_server_args(&model_path, &tuning, port);
+
+ // 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,
+ // an identical request reuses the running process.
{
let guard = state.bundled_engine.lock().unwrap();
if let Some(engine) = guard.as_ref() {
- if engine.model_path == model_path && engine_healthy(engine.port) {
+ if engine.args == desired_args && engine_healthy(engine.port) {
return Ok(serde_json::json!({
"status": "already_running",
"port": engine.port,
"model_path": engine.model_path,
+ "ctx": engine.ctx,
}));
}
}
@@ -322,7 +408,7 @@ fn start_bundled_engine_blocking(
println!("[Engine] Starting built-in llama-server on port {port} — {model_path}");
let mut cmd = Command::new(&binary);
- cmd.args(build_server_args(&model_path, ctx, port))
+ cmd.args(&desired_args)
.stdin(Stdio::null())
.stdout(Stdio::null())
// llama-server writes the REASON a start fails here: a GGUF it refuses,
@@ -348,6 +434,8 @@ fn start_bundled_engine_blocking(
child,
model_path: model_path.clone(),
port,
+ ctx: Some(effective_ctx(&tuning)),
+ args: desired_args,
});
// Wait for the model to load. On failure, reap the child so we don't leave
@@ -365,6 +453,7 @@ fn start_bundled_engine_blocking(
"status": "started",
"port": port,
"model_path": model_path,
+ "ctx": effective_ctx(&tuning),
}))
}
@@ -393,20 +482,22 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,
let state = app.state::<AppState>();
let probe = {
let guard = state.bundled_engine.lock().unwrap();
- guard.as_ref().map(|e| (e.port, e.model_path.clone()))
+ guard.as_ref().map(|e| (e.port, e.model_path.clone(), e.ctx))
};
match probe {
- Some((port, model_path)) => serde_json::json!({
+ Some((port, model_path, ctx)) => serde_json::json!({
"running": true,
"healthy": engine_healthy(port),
"port": port,
"model_path": model_path,
+ "ctx": ctx,
}),
None => serde_json::json!({
"running": false,
"healthy": false,
"port": DEFAULT_ENGINE_PORT,
"model_path": null,
+ "ctx": null,
}),
}
})
@@ -422,7 +513,7 @@ pub async fn bundled_engine_status(app: AppHandle) -> Result<serde_json::Value,
pub async fn swap_bundled_model(
app: AppHandle,
model_path: String,
- ctx: Option<u32>,
+ tuning: Option<EngineTuning>,
) -> Result<serde_json::Value, String> {
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
@@ -433,7 +524,7 @@ pub async fn swap_bundled_model(
.as_ref()
.map(|e| e.port)
.unwrap_or(DEFAULT_ENGINE_PORT);
- start_bundled_engine_blocking(&app, &state, model_path, ctx, Some(port))
+ start_bundled_engine_blocking(&app, &state, model_path, tuning, Some(port))
})
.await
.map_err(|e| format!("Engine swap task failed to run: {e}"))?
@@ -577,6 +668,10 @@ fn start_bundled_embed_blocking(
child,
model_path: model_path.clone(),
port,
+ // No --ctx-size on the embed server; args recorded for symmetry (its
+ // idempotence check stays model_path-based, embeds have no tuning).
+ ctx: None,
+ args: build_embed_args(&model_path, port),
});
if let Err(e) = wait_for_health(port) {
@@ -656,8 +751,10 @@ mod tests {
use super::*;
#[test]
- fn args_include_model_ctx_port_and_full_gpu_offload() {
- let args = build_server_args("/models/qwen.gguf", 8192, 8127);
+ 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);
assert_eq!(
args,
vec![
@@ -670,6 +767,83 @@ mod tests {
);
}
+ #[test]
+ fn expert_tuning_adds_all_flags_in_stable_order() {
+ let tuning = EngineTuning {
+ ctx: 16384,
+ flash_attn: "on".into(),
+ cache_type_k: "q8_0".into(),
+ cache_type_v: "q8_0".into(),
+ threads: 8,
+ gpu_layers: 20,
+ mlock: true,
+ no_mmap: true,
+ };
+ let args = build_server_args("/m.gguf", &tuning, 8127);
+ assert_eq!(
+ args,
+ vec![
+ "-m", "/m.gguf",
+ "--host", "127.0.0.1",
+ "--port", "8127",
+ "--ctx-size", "16384",
+ "-ngl", "20",
+ "-fa", "on",
+ "-ctk", "q8_0",
+ "-ctv", "q8_0",
+ "-t", "8",
+ "--mlock",
+ "--no-mmap",
+ ]
+ );
+ }
+
+ #[test]
+ fn junk_tuning_values_fall_back_to_legacy_argv() {
+ // Settings files are user-editable JSON — junk enum strings must be
+ // dropped (binary defaults), never passed through to the argv.
+ let tuning = EngineTuning {
+ ctx: 0,
+ flash_attn: "banana".into(),
+ cache_type_k: "'; rm -rf /".into(),
+ cache_type_v: "zzz".into(),
+ threads: -4,
+ gpu_layers: -1,
+ mlock: false,
+ no_mmap: false,
+ };
+ let args = build_server_args("/m.gguf", &tuning, 8127);
+ assert_eq!(
+ args,
+ vec![
+ "-m", "/m.gguf",
+ "--host", "127.0.0.1",
+ "--port", "8127",
+ "--ctx-size", "8192",
+ "-ngl", "999",
+ ]
+ );
+ }
+
+ #[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 ngl = args.iter().position(|a| a == "-ngl").unwrap();
+ assert_eq!(args[ngl + 1], "0");
+ }
+
+ #[test]
+ fn partial_tuning_json_deserializes_with_defaults() {
+ // The frontend sends partial objects ({ctx: 16384}); serde(default)
+ // must fill the rest so a partial settings write never breaks starts.
+ let t: EngineTuning = serde_json::from_str(r#"{"ctx":16384,"cacheTypeK":"q8_0"}"#).unwrap();
+ assert_eq!(t.ctx, 16384);
+ assert_eq!(t.cache_type_k, "q8_0");
+ assert_eq!(t.flash_attn, "auto");
+ assert_eq!(t.gpu_layers, -1);
+ }
+
#[test]
fn embed_args_enable_embeddings_and_mean_pooling() {
let args = build_embed_args("/models/nomic-embed.gguf", 8128);
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 2b2d3db3..85f10f80 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -40,6 +40,14 @@ pub struct BundledEngine {
pub child: Child,
pub model_path: String,
pub port: u16,
+ /// Context size the CHAT engine was started with (`None` for the embed
+ /// server, which never sets `--ctx-size`). Surfaced by the status command
+ /// so the UI shows the true token-counter denominator.
+ pub ctx: Option<u32>,
+ /// Full argv the process was spawned with — the idempotence key: a start
+ /// request resolving to the same argv reuses the running process, any
+ /// difference (model, ctx, tuning, port) triggers a stop→start.
+ pub args: Vec<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
diff --git a/src/api/__tests__/builtin-ensure.test.ts b/src/api/__tests__/builtin-ensure.test.ts
index ffa77cc8..40abe3a6 100644
--- a/src/api/__tests__/builtin-ensure.test.ts
+++ b/src/api/__tests__/builtin-ensure.test.ts
@@ -17,6 +17,13 @@ vi.mock('../../stores/providerStore', () => ({
},
}))
+const TUNING = { ctx: 16384, flashAttn: 'on', cacheTypeK: 'q8_0', cacheTypeV: 'q8_0', threads: -1, gpuLayers: -1, mlock: false, noMmap: false }
+vi.mock('../../stores/settingsStore', () => ({
+ useSettingsStore: {
+ getState: () => ({ settings: { builtinEngine: TUNING } }),
+ },
+}))
+
const backendCall = vi.fn()
vi.mock('../backend', () => ({
backendCall: (...args: any[]) => backendCall(...args),
@@ -57,12 +64,14 @@ describe('ensureBuiltinEngineAlive', () => {
expect(callsTo('start_bundled_engine')).toHaveLength(0)
})
- it('restarts a dead engine with the bundled GGUF path (prefixed name too)', async () => {
+ it('restarts a dead engine with the bundled GGUF path AND the user tuning (prefixed name too)', async () => {
mockEngine({ healthy: false })
await ensureBuiltinEngineAlive('openai::qwen2.5-0.5b')
const starts = callsTo('start_bundled_engine')
expect(starts).toHaveLength(1)
- expect(starts[0][1]).toEqual({ modelPath: '/models/qwen2.5-0.5b.gguf' })
+ // Tuning rides along so a self-heal never silently drops configured
+ // ctx/KV-quant back to defaults.
+ expect(starts[0][1]).toEqual({ modelPath: '/models/qwen2.5-0.5b.gguf', tuning: TUNING })
})
it('leaves foreign models alone (openai-compat server that is not ours)', async () => {
diff --git a/src/api/__tests__/engine.test.ts b/src/api/__tests__/engine.test.ts
index fcdda227..ef6b3ddb 100644
--- a/src/api/__tests__/engine.test.ts
+++ b/src/api/__tests__/engine.test.ts
@@ -25,27 +25,44 @@ import {
type BundledModel,
} from '../engine'
import { backendCall } from '../backend'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+import type { BuiltinEngineTuning } from '../../types/settings'
+
+// v18: the wrappers inject the settings-backed expert tuning on every
+// start/swap; the real settings store is loaded here, so "no explicit tuning"
+// must resolve to DEFAULT_SETTINGS.builtinEngine — that IS the chokepoint.
+const DEFAULT_TUNING = DEFAULT_SETTINGS.builtinEngine
beforeEach(() => {
vi.mocked(backendCall).mockReset()
})
describe('engine command wrappers', () => {
- it('starts the engine with camelCase args (Tauri maps → snake_case)', async () => {
+ it('starts the engine with camelCase args and an explicit tuning', async () => {
+ vi.mocked(backendCall).mockResolvedValue({ port: 8127 } as never)
+ const tuning: BuiltinEngineTuning = { ...DEFAULT_TUNING, ctx: 4096, cacheTypeK: 'q8_0' }
+ await startBundledEngine('/models/qwen.gguf', tuning)
+ expect(backendCall).toHaveBeenCalledWith('start_bundled_engine', {
+ modelPath: '/models/qwen.gguf',
+ tuning,
+ })
+ })
+
+ it('injects the settings-backed tuning when none is passed (chokepoint)', async () => {
vi.mocked(backendCall).mockResolvedValue({ port: 8127 } as never)
- await startBundledEngine('/models/qwen.gguf', 4096)
+ await startBundledEngine('/models/qwen.gguf')
expect(backendCall).toHaveBeenCalledWith('start_bundled_engine', {
modelPath: '/models/qwen.gguf',
- ctx: 4096,
+ tuning: DEFAULT_TUNING,
})
})
- it('swaps the loaded model by path', async () => {
+ it('swaps the loaded model by path with the settings tuning', async () => {
vi.mocked(backendCall).mockResolvedValue({ port: 8127 } as never)
await swapBundledModel('/models/other.gguf')
expect(backendCall).toHaveBeenCalledWith('swap_bundled_model', {
modelPath: '/models/other.gguf',
- ctx: undefined,
+ tuning: DEFAULT_TUNING,
})
})
@@ -111,7 +128,7 @@ describe('activateBuiltinModel', () => {
expect(ok).toBe(true)
expect(backendCall).toHaveBeenCalledWith('swap_bundled_model', {
modelPath: '/m/qwen.gguf',
- ctx: undefined,
+ tuning: DEFAULT_TUNING,
})
})
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index d96f1372..e66f3ec7 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -16,6 +16,7 @@
import { backendCall } from './backend'
import { useProviderStore } from '../stores/providerStore'
+import { useSettingsStore } from '../stores/settingsStore'
interface EngineStatusLite {
running: boolean
@@ -68,7 +69,11 @@ export async function ensureBuiltinEngineAlive(modelName: string): Promise<void>
const hit = models.find((m) => m.name === bare)
if (!hit) return // not a bundled GGUF — some other openai-compat server
- await backendCall('start_bundled_engine', { modelPath: hit.path })
+ // 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
}
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 5926792c..90f82665 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -14,7 +14,17 @@
import { backendCall } from './backend'
import { prefixModelName } from './providers'
import { useProviderStore } from '../stores/providerStore'
+import { useSettingsStore } from '../stores/settingsStore'
import type { CloudModel } from '../types/models'
+import type { BuiltinEngineTuning } from '../types/settings'
+
+/** The user's Built-in Engine expert tuning (settings-backed). Injected into
+ * every start/swap below, so Onboarding, Discover, the model picker and the
+ * post-offload self-heal all honor it without threading it through callsites.
+ * Undefined (pre-migration blob) is fine — Rust falls back to its defaults. */
+function tuningFromSettings(): BuiltinEngineTuning | undefined {
+ return useSettingsStore.getState().settings.builtinEngine
+}
export interface BundledModel {
/** File name without the `.gguf` extension. The id shown in the picker. */
@@ -32,6 +42,9 @@ export interface EngineStatus {
healthy: boolean
port: number
model_path: string | null
+ /** 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
}
/** Loopback base URL of the managed embeddings server (P5). Mirrors the Rust
@@ -57,9 +70,10 @@ export function isManagedBuiltinActive(): boolean {
return cfg.enabled && cfg.managed === true
}
-/** Start the built-in engine with a specific GGUF. Idempotent for the same model. */
-export function startBundledEngine(modelPath: string, ctx?: number) {
- return backendCall('start_bundled_engine', { modelPath, ctx })
+/** Start the built-in engine with a specific GGUF. Idempotent for the same
+ * model + tuning (the Rust side compares the resulting argv). */
+export function startBundledEngine(modelPath: string, tuning?: BuiltinEngineTuning) {
+ return backendCall('start_bundled_engine', { modelPath, tuning: tuning ?? tuningFromSettings() })
}
/** Stop the managed engine child if one is running. */
@@ -73,8 +87,8 @@ export function bundledEngineStatus() {
}
/** Swap the loaded model (stop → start on the same port). */
-export function swapBundledModel(modelPath: string, ctx?: number) {
- return backendCall('swap_bundled_model', { modelPath, ctx })
+export function swapBundledModel(modelPath: string, tuning?: BuiltinEngineTuning) {
+ return backendCall('swap_bundled_model', { modelPath, tuning: tuning ?? tuningFromSettings() })
}
/** Start the built-in embeddings server (P5) with a specific embedding GGUF.
@@ -160,10 +174,10 @@ export function bundledToAIModels(models: BundledModel[]): CloudModel[] {
* Resolves the GGUF path from the last listBundledModels() and swaps the engine.
* No-op if the path is unknown (list not yet fetched).
*/
-export async function activateBuiltinModel(nameOrPrefixed: string, ctx?: number): Promise<boolean> {
+export async function activateBuiltinModel(nameOrPrefixed: string, tuning?: BuiltinEngineTuning): Promise<boolean> {
const name = nameOrPrefixed.includes('::') ? nameOrPrefixed.split('::')[1] : nameOrPrefixed
const path = pathByName.get(name)
if (!path) return false
- await swapBundledModel(path, ctx)
+ await swapBundledModel(path, tuning)
return true
}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index dc12393f..11d062e1 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -49,6 +49,16 @@ export const DEFAULT_SETTINGS: Settings = {
// Bug AA v2.5.0 — Ollama num_ctx override. 0 = use Ollama default (2048
// on most builds). Users with RAG / long chats can bump this up.
contextWindowOverride: 0,
+ builtinEngine: {
+ ctx: 8192,
+ flashAttn: 'auto',
+ cacheTypeK: 'f16',
+ cacheTypeV: 'f16',
+ threads: -1,
+ gpuLayers: -1,
+ mlock: false,
+ noMmap: false,
+ },
// Bug BB v2.5.0 — GPU picker. "auto" + empty indices = no env-var,
// runtime picks default. User sets these via Settings → Hardware.
gpuVendor: 'auto',
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 6bb2fcd2..e6a77918 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -49,7 +49,11 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'
// v17 (2.5.10): added settings.codexAutoApply (default false) — auto-apply
// staged changes when the run finishes. Additive merge backfills the default;
// stage-mode behaviour is unchanged until the user turns the new switch on.
-const STORE_VERSION = 17
+// v18 (2.6.0): added settings.builtinEngine (expert tuning for the bundled
+// llama-server: ctx, flash attention, KV-cache quant, threads, GPU layers,
+// mlock/mmap; defaults = the exact pre-2.6.0 argv). Additive merge backfills
+// the default object; engine behaviour is unchanged until the user edits it.
+const STORE_VERSION = 18
interface SettingsState {
settings: Settings
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 883c98a1..c6baf5c2 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -6,6 +6,26 @@ export type CavemanMode = 'off' | 'lite' | 'full' | 'ultra'
export type AppMode = 'local' | 'cloud'
+/** Expert tuning for the bundled llama-server. Mirrors Rust `EngineTuning`
+ * (camelCase over IPC); values are whitelisted on the Rust side. */
+export interface BuiltinEngineTuning {
+ /** `--ctx-size`. 0 = app default (8192). */
+ ctx: number
+ /** Flash Attention: 'auto' (binary default), 'on', 'off'. */
+ flashAttn: 'auto' | 'on' | 'off'
+ /** KV-cache quantization for K/V. 'f16' = off. Quantized V needs flash attention. */
+ cacheTypeK: 'f16' | 'bf16' | 'q8_0' | 'q4_0'
+ cacheTypeV: 'f16' | 'bf16' | 'q8_0' | 'q4_0'
+ /** CPU threads for generation. <=0 = auto. */
+ threads: number
+ /** GPU layers to offload. -1 = all layers, 0 = CPU-only. */
+ gpuLayers: number
+ /** Pin the model in RAM (`--mlock`). */
+ mlock: boolean
+ /** Disable mmap (`--no-mmap`): slower load, fewer pageouts. */
+ noMmap: boolean
+}
+
export interface Settings {
apiEndpoint: string
temperature: number
@@ -91,6 +111,12 @@ export interface Settings {
// providers ignore this field — they manage context themselves.
/** User-side context-window override (forwarded as Ollama's num_ctx). 0 = auto. */
contextWindowOverride: number
+ // Built-in engine expert tuning (2.6.0 Engine-Sweep). Forwarded to the Rust
+ // EngineTuning (whitelisted there) on every engine start/swap — Onboarding,
+ // Discover, model picker and the post-offload self-heal all inherit it via
+ // the api/engine chokepoint. Defaults reproduce the pre-2.6.0 argv exactly.
+ /** Expert settings for the bundled llama-server (chat engine only). */
+ builtinEngine: BuiltinEngineTuning
// Bug BB v2.5.0 — BobbyT Discord 2026-05-26. GPU vendor + indices to
// forward as CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES /
// ONEAPI_DEVICE_SELECTOR on next Ollama / ComfyUI spawn. "auto" + empty