Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

chore: update llamacpp settings (#8168)

Akarshan Biswas042bf6dc0c9a
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 8daa307e1..ad2c57cf3 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -274,19 +274,6 @@
]
}
},
- {
- "key": "defrag_thold",
- "title": "KV Cache Defragmentation Threshold",
- "description": "Threshold for KV cache defragmentation (< 0 to disable).",
- "controllerType": "input",
- "controllerProps": {
- "value": 0.1,
- "placeholder": "0.1",
- "type": "number",
- "textAlign": "right",
- "step": 0.01
- }
- },
{
"key": "rope_scaling",
"title": "RoPE Scaling Method",
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 76e88bd28..9079da393 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -71,6 +71,41 @@ import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
const EMBEDDING_CHECK_VERSION = 3
const MTP_CHECK_VERSION = 1
+// Provider settings that end up in `router.preset.ini` (`[*]` global section
+// in preset.ts). Mutating any of these requires a router restart so the new
+// preset is read; cosmetic / process-only keys (auto_update_engine, models_max,
+// timeout, llamacpp_env, version_backend) are handled separately or not at all.
+const PRESET_AFFECTING_KEYS = new Set<string>([
+ 'fit',
+ 'fit_target',
+ 'fit_ctx',
+ 'ctx_size',
+ 'n_gpu_layers',
+ 'flash_attn',
+ 'cache_type_k',
+ 'cache_type_v',
+ 'parallel',
+ 'cont_batching',
+ 'threads',
+ 'threads_batch',
+ 'n_predict',
+ 'ubatch_size',
+ 'device',
+ 'split_mode',
+ 'main_gpu',
+ 'no_mmap',
+ 'mlock',
+ 'rope_scaling',
+ 'rope_scale',
+ 'rope_freq_base',
+ 'rope_freq_scale',
+ 'ctx_shift',
+ 'cache_ram',
+ 'cache_reuse',
+ 'swa_full',
+ 'keep',
+])
+
/**
* Override the default app.log function to use Jan's logging system.
* @param args
@@ -105,6 +140,111 @@ function parseBuildNumber(version: string): number | null {
return match ? parseInt(match[1], 10) : null
}
+type YamlSettingValue = string | number | boolean | null
+
+type PersistedProviderSetting = {
+ controller_props?: {
+ value?: unknown
+ }
+}
+
+type PersistedModelState = {
+ id?: unknown
+ settings?: Record<string, PersistedProviderSetting>
+}
+
+const MODEL_PROVIDER_LOCAL_STORAGE_KEY = 'model-provider'
+const LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY =
+ 'llamacpp_model_yaml_backfill_v1'
+
+const MODEL_SETTINGS_YAML_MAPPING: Record<
+ string,
+ {
+ yamlKey: string
+ coerce: (v: unknown) => YamlSettingValue
+ }
+> = {
+ ctx_len: {
+ yamlKey: 'ctx_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
+ },
+ },
+ ngl: {
+ yamlKey: 'n_gpu_layers',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null
+ },
+ },
+ chat_template: {
+ yamlKey: 'chat_template',
+ coerce: (v) =>
+ typeof v === 'string' && v.trim().length > 0 ? v : null,
+ },
+ batch_size: {
+ yamlKey: 'batch_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
+ },
+ },
+ ubatch_size: {
+ yamlKey: 'ubatch_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
+ },
+ },
+ cpu_moe: {
+ yamlKey: 'cpu_moe',
+ coerce: (v) => (v === true ? true : null),
+ },
+ n_cpu_moe: {
+ yamlKey: 'n_cpu_moe',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
+ },
+ },
+ no_kv_offload: {
+ yamlKey: 'no_kv_offload',
+ coerce: (v) => (v === true ? true : null),
+ },
+ override_tensor_buffer_t: {
+ yamlKey: 'override_tensor',
+ coerce: (v) =>
+ typeof v === 'string' && v.trim().length > 0 ? v.trim() : null,
+ },
+ offload_mmproj: {
+ yamlKey: 'mmproj_offload',
+ coerce: (v) => (v === false ? false : null),
+ },
+}
+
+function readPersistedLlamacppModels(): PersistedModelState[] {
+ try {
+ const raw = localStorage.getItem(MODEL_PROVIDER_LOCAL_STORAGE_KEY)
+ if (!raw) return []
+ const parsed = JSON.parse(raw)
+ const providers = parsed?.state?.providers
+ if (!Array.isArray(providers)) return []
+ const llamacpp = providers.find(
+ (provider: { provider?: unknown }) => provider?.provider === 'llamacpp'
+ )
+ return Array.isArray(llamacpp?.models) ? llamacpp.models : []
+ } catch (error) {
+ logger.warn('Failed to read persisted llamacpp model settings:', error)
+ return []
+ }
+}
+
/**
* Breadth-first search of `rootDir` for the directory directly containing
* a file named `serverName`. Returns the absolute path of that directory,
@@ -219,6 +359,8 @@ export default class llamacpp_extension extends AIEngine {
// This sets the base directory where model files for this provider are stored.
await this.getProviderPath()
+ await this.migratePersistedModelSettingsToYaml()
+
// Set up validation event listeners to bridge Tauri events to frontend
this.unlistenValidationStarted = await listen<{
modelId: string
@@ -314,6 +456,13 @@ export default class llamacpp_extension extends AIEngine {
/* ignore probe failures */
}
+ // --no-webui was renamed to --no-ui in upstream b9222. Keep the legacy
+ // flag for older backends; the deprecated form still works on newer ones
+ // but emits a warning, so prefer the new spelling when available.
+ const NO_UI_RENAME_BUILD = 9222
+ const noUiFlag =
+ build !== null && build >= NO_UI_RENAME_BUILD ? '--no-ui' : '--no-webui'
+
const info = await invoke<{ port: number; api_key: string; pid: number }>(
'plugin:llamacpp|start_router',
{
@@ -322,7 +471,7 @@ export default class llamacpp_extension extends AIEngine {
port,
apiKey,
modelsMax,
- defaultArgs: [] as string[],
+ defaultArgs: [noUiFlag],
envs,
}
)
@@ -542,6 +691,58 @@ export default class llamacpp_extension extends AIEngine {
localStorage.setItem(MIGRATION_KEY, '1')
}
+ private async migratePersistedModelSettingsToYaml(): Promise<void> {
+ if (localStorage.getItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return
+
+ const persistedModels = readPersistedLlamacppModels()
+ if (persistedModels.length === 0) {
+ localStorage.setItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
+ return
+ }
+
+ const providerPath = await this.getProviderPath()
+
+ for (const persistedModel of persistedModels) {
+ const modelId =
+ typeof persistedModel.id === 'string' ? persistedModel.id : undefined
+ if (!modelId || !persistedModel.settings) continue
+
+ const configPath = await joinPath([
+ providerPath,
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(configPath))) continue
+
+ const cfg = (await invoke<ModelConfig>('read_yaml', {
+ path: configPath,
+ })) as ModelConfig & Record<string, unknown>
+
+ let touched = false
+ for (const [sidebarKey, persistedSetting] of Object.entries(
+ persistedModel.settings
+ )) {
+ const mapping = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
+ if (!mapping) continue
+
+ if (mapping.yamlKey in cfg) continue
+
+ const next = mapping.coerce(persistedSetting?.controller_props?.value)
+ if (next === null) continue
+
+ ;(cfg as Record<string, unknown>)[mapping.yamlKey] = next
+ touched = true
+ }
+
+ if (touched) {
+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
+ }
+ }
+
+ localStorage.setItem(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
+ }
+
async configureBackends(): Promise<void> {
if (this.isConfiguringBackends) {
logger.info(
@@ -1216,9 +1417,25 @@ export default class llamacpp_extension extends AIEngine {
this.llamacpp_env = value as string
} else if (key === 'timeout') {
this.timeout = value as number
+ } else if (PRESET_AFFECTING_KEYS.has(key)) {
+ // A live router was started with the previous preset; without a restart
+ // the new value is invisible to inference. Debounced so a flurry of
+ // slider/dropdown updates collapses into one bounce.
+ this.scheduleRouterRestart()
}
}
+ private routerRestartTimer: ReturnType<typeof setTimeout> | null = null
+ private scheduleRouterRestart(): void {
+ if (this.routerRestartTimer) clearTimeout(this.routerRestartTimer)
+ this.routerRestartTimer = setTimeout(() => {
+ this.routerRestartTimer = null
+ this.startRouter().catch((e) =>
+ logger.warn('Router restart after settings update failed:', e)
+ )
+ }, 600)
+ }
+
private async generateApiKey(modelId: string, port: string): Promise<string> {
const hash = await invoke<string>('plugin:llamacpp|generate_api_key', {
modelId: modelId + port,
@@ -1702,6 +1919,14 @@ export default class llamacpp_extension extends AIEngine {
savePath: newModelConfigPath,
})
)
+
+ // The router's preset still references the old model id until we
+ // regenerate; without this a `POST /models/load <new-id>` would 404.
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.warn(`Router restart after model rename (${modelId} → ${model.id}) failed`, e)
+ }
}
override async import(modelId: string, opts: ImportOptions): Promise<void> {
@@ -2003,9 +2228,8 @@ export default class llamacpp_extension extends AIEngine {
override async load(
modelId: string,
- _overrideSettings?: Partial<LlamacppConfig>,
- isEmbedding: boolean = false,
- _bypassAutoUnload: boolean = false
+ _settings?: unknown,
+ isEmbedding: boolean = false
): Promise<SessionInfo> {
const sInfo = await this.findSessionByModel(modelId)
if (sInfo) {
@@ -2494,6 +2718,64 @@ export default class llamacpp_extension extends AIEngine {
}
}
+ /**
+ * Persist a per-model setting from the sidebar into `model.yml`, regenerate
+ * the router preset, and restart the router so the next inference picks up
+ * the new args. In router mode the router reads args exclusively from
+ * `router.preset.ini`, so updating Zustand alone has no effect on inference.
+ *
+ * Sidebar keys are mapped to the canonical `model.yml` / preset keys here.
+ * Keys not in the mapping are silently ignored — they're either Jan-side
+ * concerns (`reasoning`, `auto_increase_ctx_len`) or not yet emitted by
+ * `preset.ts` (deferred to phase b).
+ */
+ async updateModelSettings(
+ modelId: string,
+ patch: Record<string, string | number | boolean | null | undefined>
+ ): Promise<void> {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(configPath))) {
+ throw new Error(`model.yml not found for ${modelId}`)
+ }
+ const cfg = (await invoke<ModelConfig>('read_yaml', {
+ path: configPath,
+ })) as ModelConfig & Record<string, unknown>
+
+ let touched = false
+ for (const [sidebarKey, value] of Object.entries(patch)) {
+ const m = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
+ if (!m) continue
+ const next = m.coerce(value)
+ if (next === null) {
+ if (m.yamlKey in cfg) {
+ delete (cfg as Record<string, unknown>)[m.yamlKey]
+ touched = true
+ }
+ } else {
+ ;(cfg as Record<string, unknown>)[m.yamlKey] = next
+ touched = true
+ }
+ }
+
+ if (!touched) return
+
+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
+
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.warn(
+ `Failed to restart router after model settings update for ${modelId}`,
+ e
+ )
+ }
+ }
+
async getDevices(): Promise<DeviceList[]> {
const cfg = this.config
const [version, backend] = cfg.version_backend.split('/')
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 3dcb2046b..37daf587f 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -31,6 +31,11 @@ type ModelYaml = ModelConfig & {
spec_draft_n_max?: number
spec_draft_n_min?: number
spec_draft_p_min?: number
+ cpu_moe?: boolean
+ n_cpu_moe?: number
+ no_kv_offload?: boolean
+ override_tensor?: string
+ mmproj_offload?: boolean
}
export const MTP_MIN_BUILD = 9193
@@ -99,45 +104,201 @@ export async function generatePreset(
const lines: string[] = []
+ // Emit only values that differ from llama.cpp's compiled defaults so the
+ // preset stays minimal and intent-revealing. Defaults sourced from
+ // tools/server/README.md.
lines.push('[*]')
- if (typeof config.fit === 'boolean') {
- lines.push(`fit = ${config.fit ? 'on' : 'off'}`)
+ // fit default = 'on'
+ if (config.fit === false) {
+ lines.push('fit = off')
}
- if (typeof config.fit_target === 'string' && config.fit_target.length > 0) {
+ // fit-target default = '1024' (MiB per device)
+ if (
+ typeof config.fit_target === 'string' &&
+ config.fit_target.length > 0 &&
+ config.fit_target !== '1024'
+ ) {
lines.push(`fit-target = ${escapeIniValue(config.fit_target)}`)
}
+ // fit-ctx default = 4096
const fitCtxNum =
typeof config.fit_ctx === 'number'
? config.fit_ctx
: typeof config.fit_ctx === 'string' && config.fit_ctx.length > 0
? Number(config.fit_ctx)
: NaN
- if (Number.isFinite(fitCtxNum) && fitCtxNum > 0) {
+ if (Number.isFinite(fitCtxNum) && fitCtxNum > 0 && fitCtxNum !== 4096) {
lines.push(`fit-ctx = ${fitCtxNum}`)
}
- if (typeof config.ctx_size === 'number' && config.ctx_size > 0) {
+ // ctx-size default = 0 (loaded from model); any positive user value is intent.
+ // Skip when auto-fit is enabled — fit owns context sizing and an explicit
+ // ctx-size would override it.
+ const fitEnabled = config.fit !== false
+ if (
+ !fitEnabled &&
+ typeof config.ctx_size === 'number' &&
+ config.ctx_size > 0
+ ) {
lines.push(`ctx-size = ${config.ctx_size}`)
}
+ // n-gpu-layers default = 0 / auto; emit any non-negative explicit value.
if (typeof config.n_gpu_layers === 'number' && config.n_gpu_layers >= 0) {
lines.push(`n-gpu-layers = ${config.n_gpu_layers}`)
}
+ // flash-attn default = 'auto'; explicit on/off only.
if (
typeof config.flash_attn === 'string' &&
(config.flash_attn === 'on' || config.flash_attn === 'off')
) {
lines.push(`flash-attn = ${config.flash_attn}`)
}
- if (typeof config.cache_type_k === 'string' && config.cache_type_k.length > 0) {
+ // cache-type-k/v default = 'f16'
+ if (
+ typeof config.cache_type_k === 'string' &&
+ config.cache_type_k.length > 0 &&
+ config.cache_type_k !== 'f16'
+ ) {
lines.push(`cache-type-k = ${escapeIniValue(config.cache_type_k)}`)
}
- if (typeof config.cache_type_v === 'string' && config.cache_type_v.length > 0) {
+ if (
+ typeof config.cache_type_v === 'string' &&
+ config.cache_type_v.length > 0 &&
+ config.cache_type_v !== 'f16'
+ ) {
lines.push(`cache-type-v = ${escapeIniValue(config.cache_type_v)}`)
}
+ // parallel default = -1 (auto); positive user value is intent.
if (typeof config.parallel === 'number' && config.parallel > 0) {
lines.push(`parallel = ${config.parallel}`)
}
- if (typeof config.cont_batching === 'boolean') {
- lines.push(`cont-batching = ${config.cont_batching}`)
+ // cont-batching default = true; emit only the explicit-off case.
+ if (config.cont_batching === false) {
+ lines.push('cont-batching = false')
+ }
+ // threads default = -1 (logical cores)
+ if (
+ typeof config.threads === 'number' &&
+ Number.isFinite(config.threads) &&
+ config.threads > 0
+ ) {
+ lines.push(`threads = ${Math.floor(config.threads)}`)
+ }
+ // threads-batch default = same as threads; emit only if positive and distinct.
+ if (
+ typeof config.threads_batch === 'number' &&
+ Number.isFinite(config.threads_batch) &&
+ config.threads_batch > 0 &&
+ config.threads_batch !== config.threads
+ ) {
+ lines.push(`threads-batch = ${Math.floor(config.threads_batch)}`)
+ }
+ // n-predict default = -1 (infinity)
+ if (
+ typeof config.n_predict === 'number' &&
+ Number.isFinite(config.n_predict) &&
+ config.n_predict !== -1
+ ) {
+ lines.push(`n-predict = ${Math.floor(config.n_predict)}`)
+ }
+ // ubatch-size default = 512
+ if (
+ typeof config.ubatch_size === 'number' &&
+ Number.isFinite(config.ubatch_size) &&
+ config.ubatch_size > 0 &&
+ config.ubatch_size !== 512
+ ) {
+ lines.push(`ubatch-size = ${Math.floor(config.ubatch_size)}`)
+ }
+ // device default = empty (auto-pick)
+ if (typeof config.device === 'string' && config.device.trim().length > 0) {
+ lines.push(`device = ${escapeIniValue(config.device)}`)
+ }
+ // split-mode default = 'layer'
+ if (
+ typeof config.split_mode === 'string' &&
+ config.split_mode.length > 0 &&
+ config.split_mode !== 'layer'
+ ) {
+ lines.push(`split-mode = ${escapeIniValue(config.split_mode)}`)
+ }
+ // main-gpu default = 0
+ if (
+ typeof config.main_gpu === 'number' &&
+ Number.isFinite(config.main_gpu) &&
+ config.main_gpu > 0
+ ) {
+ lines.push(`main-gpu = ${Math.floor(config.main_gpu)}`)
+ }
+ // no-mmap / mlock default = false
+ if (config.no_mmap === true) {
+ lines.push('no-mmap = true')
+ }
+ if (config.mlock === true) {
+ lines.push('mlock = true')
+ }
+ // rope-scaling default = 'none'
+ if (
+ typeof config.rope_scaling === 'string' &&
+ config.rope_scaling.length > 0 &&
+ config.rope_scaling !== 'none'
+ ) {
+ lines.push(`rope-scaling = ${escapeIniValue(config.rope_scaling)}`)
+ }
+ // rope-scale / rope-freq-scale default = 1.0 (identity / no scaling);
+ // rope-freq-base default = 0 (loaded from model).
+ if (
+ typeof config.rope_scale === 'number' &&
+ Number.isFinite(config.rope_scale) &&
+ config.rope_scale > 0 &&
+ config.rope_scale !== 1
+ ) {
+ lines.push(`rope-scale = ${config.rope_scale}`)
+ }
+ if (
+ typeof config.rope_freq_base === 'number' &&
+ Number.isFinite(config.rope_freq_base) &&
+ config.rope_freq_base > 0
+ ) {
+ lines.push(`rope-freq-base = ${config.rope_freq_base}`)
+ }
+ if (
+ typeof config.rope_freq_scale === 'number' &&
+ Number.isFinite(config.rope_freq_scale) &&
+ config.rope_freq_scale > 0 &&
+ config.rope_freq_scale !== 1
+ ) {
+ lines.push(`rope-freq-scale = ${config.rope_freq_scale}`)
+ }
+ // context-shift default = enabled
+ if (config.ctx_shift === false) {
+ lines.push('context-shift = false')
+ }
+ // cache-ram default = 8192 MiB
+ if (
+ typeof config.cache_ram === 'number' &&
+ Number.isFinite(config.cache_ram) &&
+ config.cache_ram !== 8192
+ ) {
+ lines.push(`cache-ram = ${Math.floor(config.cache_ram)}`)
+ }
+ // cache-reuse default = 0 (disabled)
+ if (
+ typeof config.cache_reuse === 'number' &&
+ Number.isFinite(config.cache_reuse) &&
+ config.cache_reuse > 0
+ ) {
+ lines.push(`cache-reuse = ${Math.floor(config.cache_reuse)}`)
+ }
+ if (config.swa_full === true) {
+ lines.push('swa-full = true')
+ }
+ // keep default = 0
+ if (
+ typeof config.keep === 'number' &&
+ Number.isFinite(config.keep) &&
+ config.keep !== 0
+ ) {
+ lines.push(`keep = ${Math.floor(config.keep)}`)
}
lines.push('')
@@ -168,7 +329,13 @@ export async function generatePreset(
lines.push(`chat-template = ${escapeIniValue(mc.chat_template)}`)
}
- if (typeof mc.ctx_size === 'number' && mc.ctx_size > 0) {
+ // Per-model overrides — same default-skipping rules as the [*] block.
+ // ctx-size is skipped when auto-fit is on so fit can size the context.
+ if (
+ !fitEnabled &&
+ typeof mc.ctx_size === 'number' &&
+ mc.ctx_size > 0
+ ) {
lines.push(`ctx-size = ${mc.ctx_size}`)
}
if (typeof mc.n_gpu_layers === 'number' && mc.n_gpu_layers >= 0) {
@@ -180,17 +347,57 @@ export async function generatePreset(
) {
lines.push(`flash-attn = ${mc.flash_attn}`)
}
- if (typeof mc.cache_type_k === 'string' && mc.cache_type_k.length > 0) {
+ if (
+ typeof mc.cache_type_k === 'string' &&
+ mc.cache_type_k.length > 0 &&
+ mc.cache_type_k !== 'f16'
+ ) {
lines.push(`cache-type-k = ${escapeIniValue(mc.cache_type_k)}`)
}
- if (typeof mc.cache_type_v === 'string' && mc.cache_type_v.length > 0) {
+ if (
+ typeof mc.cache_type_v === 'string' &&
+ mc.cache_type_v.length > 0 &&
+ mc.cache_type_v !== 'f16'
+ ) {
lines.push(`cache-type-v = ${escapeIniValue(mc.cache_type_v)}`)
}
if (typeof mc.parallel === 'number' && mc.parallel > 0) {
lines.push(`parallel = ${mc.parallel}`)
}
- if (typeof mc.cont_batching === 'boolean') {
- lines.push(`cont-batching = ${mc.cont_batching}`)
+ if (mc.cont_batching === false) {
+ lines.push('cont-batching = false')
+ }
+ if (
+ typeof mc.batch_size === 'number' &&
+ mc.batch_size > 0 &&
+ mc.batch_size !== 2048
+ ) {
+ lines.push(`batch-size = ${Math.floor(mc.batch_size)}`)
+ }
+ if (
+ typeof mc.ubatch_size === 'number' &&
+ mc.ubatch_size > 0 &&
+ mc.ubatch_size !== 512
+ ) {
+ lines.push(`ubatch-size = ${Math.floor(mc.ubatch_size)}`)
+ }
+ if (mc.cpu_moe === true) {
+ lines.push('cpu-moe = true')
+ }
+ if (typeof mc.n_cpu_moe === 'number' && mc.n_cpu_moe > 0) {
+ lines.push(`n-cpu-moe = ${Math.floor(mc.n_cpu_moe)}`)
+ }
+ if (mc.no_kv_offload === true) {
+ // INI key is the negated form; parse_bool_arg flips it server-side.
+ // Writing `no-kv-offload = true` => kv-offload disabled.
+ lines.push('no-kv-offload = true')
+ }
+ if (typeof mc.override_tensor === 'string' && mc.override_tensor.trim().length > 0) {
+ lines.push(`override-tensor = ${escapeIniValue(mc.override_tensor)}`)
+ }
+ // mmproj-offload defaults to on; only emit when explicitly disabled.
+ if (mc.mmproj_offload === false) {
+ lines.push('mmproj-offload = false')
}
if (
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index 4f4be00d7..610648c7a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -86,8 +86,6 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {
cache_type_k: asString(config.cache_type_k),
cache_type_v: asString(config.cache_type_v),
- defrag_thold: asNumber(config.defrag_thold, 0.0),
-
rope_scaling: asString(config.rope_scaling),
rope_scale: asNumber(config.rope_scale, 1.0),
rope_freq_base: asNumber(config.rope_freq_base, 0.0),
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index 56c9f4659..a23a33307 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -64,7 +64,6 @@ export type LlamacppConfig = {
no_kv_offload: boolean
cache_type_k: string
cache_type_v: string
- defrag_thold: number
rope_scaling: string
rope_scale: number
rope_freq_base: number
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
index de772af99..c6cf9d360 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
@@ -77,8 +77,10 @@ pub fn router_args(
port.to_string(),
"--api-key".to_string(),
api_key.to_string(),
- "--no-webui".to_string(),
];
+ // Web-UI disable flag (`--no-webui` pre-b9222, `--no-ui` from b9222) is
+ // appended by the TS caller via `default_args` because the spelling
+ // depends on the backend build number.
args.extend(default_args.iter().cloned());
args
}
@@ -588,7 +590,11 @@ mod tests {
assert!(joined.contains("--host 127.0.0.1"));
assert!(joined.contains("--port 1337"));
assert!(joined.contains("--api-key secret-key"));
- assert!(args.iter().any(|a| a == "--no-webui"));
+ // Web-UI disable flag is now appended by the caller (it's
+ // build-number-dependent: --no-webui vs --no-ui), so it must NOT be
+ // baked into the base argv.
+ assert!(!args.iter().any(|a| a == "--no-webui"));
+ assert!(!args.iter().any(|a| a == "--no-ui"));
}
#[test]
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index 7a02c5e5b..227f72e6d 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -1,6 +1,6 @@
import { IconSettings } from '@tabler/icons-react'
import debounce from 'lodash.debounce'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Sheet,
@@ -42,19 +42,95 @@ export function ModelSetting({
const serviceHub = useServiceHub()
const setActiveModels = useAppState((state) => state.setActiveModels)
- // Create a debounced version of stopModel that waits 500ms after the last call
- const debouncedStopModel = debounce((modelId: string) => {
- serviceHub
- .models()
- .stopModel(modelId)
- .then(() => {
- // Refresh active models after stopping
+ // Debounced stopModel — memoized so the timer survives across renders.
+ // Without useMemo a fresh debounce is created every keystroke and the
+ // cleanup effect below cancels the previous timer before it can fire.
+ const debouncedStopModel = useMemo(
+ () =>
+ debounce((modelId: string) => {
serviceHub
.models()
- .getActiveModels()
- .then((models) => setActiveModels(models || []))
- })
- }, 500)
+ .stopModel(modelId)
+ .then(() => {
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
+ })
+ }, 500),
+ [serviceHub, setActiveModels]
+ )
+
+ // Coalesce rapid sidebar edits into a single yaml-write + router-restart.
+ // Each call merges into a per-model accumulator; the debounced flush writes
+ // and clears it. Avoids a flurry of slider drags rewriting model.yml + bouncing
+ // the router on every keystroke.
+ const pendingPatchesRef = useRef<
+ Map<string, Record<string, string | number | boolean | null | undefined>>
+ >(new Map())
+ const rollbackSettingsRef = useRef<Map<string, Model['settings'] | undefined>>(
+ new Map()
+ )
+ const flushPendingPatches = useMemo(
+ () =>
+ debounce(() => {
+ const patches = pendingPatchesRef.current
+ pendingPatchesRef.current = new Map()
+ for (const [modelId, patch] of patches) {
+ serviceHub
+ .models()
+ .updateModelSettings(modelId, patch)
+ .then(() => {
+ rollbackSettingsRef.current.delete(modelId)
+ })
+ .catch((e) => {
+ const previousSettings = rollbackSettingsRef.current.get(modelId)
+ rollbackSettingsRef.current.delete(modelId)
+ const latestProvider = useModelProvider
+ .getState()
+ .getProviderByName(provider.provider)
+ if (latestProvider) {
+ const modelIndex = latestProvider.models.findIndex(
+ (m) => m.id === modelId
+ )
+ if (modelIndex !== -1) {
+ const revertedModels = [...latestProvider.models]
+ revertedModels[modelIndex] = {
+ ...revertedModels[modelIndex],
+ settings: previousSettings,
+ } as Model
+ useModelProvider.getState().updateProvider(provider.provider, {
+ models: revertedModels,
+ })
+ }
+ }
+ console.error('Failed to persist model settings', e)
+ })
+ }
+ }, 1500),
+ [provider.provider, serviceHub]
+ )
+ const debouncedPersistModelSettings = (
+ modelId: string,
+ patch: Record<string, string | number | boolean | null | undefined>,
+ previousSettings: Model['settings'] | undefined
+ ) => {
+ if (!rollbackSettingsRef.current.has(modelId)) {
+ rollbackSettingsRef.current.set(modelId, previousSettings)
+ }
+ const existing = pendingPatchesRef.current.get(modelId) ?? {}
+ pendingPatchesRef.current.set(modelId, { ...existing, ...patch })
+ flushPendingPatches()
+ }
+
+ useEffect(() => {
+ return () => {
+ // Flush — not cancel — so a pending ctx_len/ngl edit still gets
+ // written to model.yml and the router restarted after the sheet closes.
+ flushPendingPatches.flush()
+ debouncedStopModel.flush()
+ }
+ }, [debouncedStopModel, flushPendingPatches])
const handleSettingChange = (
key: string,
@@ -113,6 +189,14 @@ export function ModelSetting({
}
})
}
+
+ // In router mode the router reads args from `router.preset.ini` (built
+ // from `model.yml`) — Zustand alone has no effect on inference. Persist
+ // mappable keys to disk + restart the router so the next load uses the
+ // new args. Non-mappable keys are filtered inside the extension.
+ if (provider.provider === 'llamacpp') {
+ debouncedPersistModelSettings(model.id, { [key]: value }, model.settings)
+ }
}
}
@@ -188,15 +272,11 @@ export function ModelSetting({
{(() => {
return Object.entries(model.settings || {})
.reduce<[string, unknown][]>((acc, entry) => {
- if (entry[0] === 'auto_increase_ctx_len') return acc
if (entry[0] === 'reasoning') return acc
+ // Removed in v15 migration; defend against any pre-migration
+ // localStorage state that still carries the orphan entry.
+ if (entry[0] === 'auto_increase_ctx_len') return acc
if (fitEnabled && entry[0] === 'ctx_len') return acc
- if (entry[0] === 'ctx_len') {
- const autoIncrease = Object.entries(model.settings || {}).find(
- ([k]) => k === 'auto_increase_ctx_len'
- )
- if (autoIncrease) acc.push(autoIncrease)
- }
acc.push(entry)
return acc
}, [])
diff --git a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
index 70dc344e8..c94ce8d27 100644
--- a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
+++ b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
@@ -90,6 +90,46 @@ describe('useModelProvider - coverage', () => {
expect(result.current.getProviderByName('openai')?.api_key).toBe('sk-123')
expect(result.current.getProviderByName('anthropic')?.active).toBe(true)
})
+
+ it('keeps selectedModel in sync when replacing provider models', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [
+ makeProvider('llamacpp', [
+ {
+ id: 'model-1',
+ capabilities: [],
+ settings: { ctx_len: { controller_props: { value: 4096 } } },
+ },
+ ]),
+ ],
+ selectedProvider: 'llamacpp',
+ selectedModel: {
+ id: 'model-1',
+ capabilities: [],
+ settings: { ctx_len: { controller_props: { value: 4096 } } },
+ } as any,
+ })
+ })
+
+ act(() => {
+ result.current.updateProvider('llamacpp', {
+ models: [
+ {
+ id: 'model-1',
+ capabilities: [],
+ settings: { ctx_len: { controller_props: { value: 32768 } } },
+ },
+ ],
+ } as any)
+ })
+
+ expect(
+ result.current.selectedModel?.settings?.ctx_len?.controller_props?.value
+ ).toBe(32768)
+ })
})
describe('deleteModel', () => {
@@ -256,11 +296,41 @@ describe('useModelProvider - coverage', () => {
expect(migrated.providers.find((p: any) => p.provider === 'cohere')).toBeUndefined()
expect(migrated.providers.find((p: any) => p.provider === 'openai')).toBeDefined()
}],
- [10, 'adding auto_increase_ctx_len', {
+ [10, 'v10 is now a no-op (auto_increase_ctx_len removed in v15)', {
providers: [{ provider: 'llamacpp', models: [{ id: 'm1', settings: {}, capabilities: [] }], settings: [] }],
deletedModels: [],
}, (migrated: any) => {
- expect(migrated.providers[0].models[0].settings.auto_increase_ctx_len).toBeDefined()
+ expect(migrated.providers[0].models[0].settings.auto_increase_ctx_len).toBeUndefined()
+ }],
+ [12, 'v12 resets legacy string ctx_len=8192 back to auto', {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{
+ id: 'm1',
+ settings: { ctx_len: { controller_props: { value: '8192' } } },
+ capabilities: [],
+ }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }, (migrated: any) => {
+ expect(
+ migrated.providers[0].models[0].settings.ctx_len.controller_props.value
+ ).toBe('')
+ }],
+ [14, 'v14 → v15 strips orphan auto_increase_ctx_len', {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{
+ id: 'm1',
+ settings: { auto_increase_ctx_len: { controller_props: { value: true } } },
+ capabilities: [],
+ }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }, (migrated: any) => {
+ expect(migrated.providers[0].models[0].settings.auto_increase_ctx_len).toBeUndefined()
}],
[3, 'Anthropic provider migration', {
providers: [{
diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.ts
index 31b11fee7..32ac9941d 100644
--- a/web-app/src/hooks/useModelProvider.ts
+++ b/web-app/src/hooks/useModelProvider.ts
@@ -270,8 +270,8 @@ export const useModelProvider = create<ModelProviderState>()(
return { providers: nextProviders }
}),
updateProvider: (providerName, data) => {
- set((state) => ({
- providers: state.providers.map((provider) => {
+ set((state) => {
+ const providers = state.providers.map((provider) => {
if (provider.provider === providerName) {
return {
...provider,
@@ -279,8 +279,23 @@ export const useModelProvider = create<ModelProviderState>()(
}
}
return provider
- }),
- }))
+ })
+
+ let selectedModel = state.selectedModel
+ if (
+ selectedModel &&
+ state.selectedProvider === providerName &&
+ Array.isArray(data.models)
+ ) {
+ selectedModel =
+ data.models.find((model) => model.id === selectedModel?.id) ?? null
+ }
+
+ return {
+ providers,
+ selectedModel,
+ }
+ })
},
getProviderByName: (providerName: string) => {
const provider = get().providers.find(
@@ -638,24 +653,9 @@ export const useModelProvider = create<ModelProviderState>()(
)
}
- if (version <= 10 && state?.providers) {
- state.providers.forEach((provider) => {
- if (provider.models && provider.provider === 'llamacpp') {
- provider.models.forEach((model) => {
- if (!model.settings) model.settings = {}
-
- if (!model.settings.auto_increase_ctx_len) {
- model.settings.auto_increase_ctx_len = {
- ...modelSettings.auto_increase_ctx_len,
- controller_props: {
- ...modelSettings.auto_increase_ctx_len.controller_props,
- },
- }
- }
- })
- }
- })
- }
+ // Migration v10 historically inserted `auto_increase_ctx_len`. The
+ // setting was removed in v15, so v10 is now a no-op for any user
+ // still passing through this point.
if (version <= 11 && state?.providers) {
state.providers.forEach((provider) => {
@@ -715,15 +715,48 @@ export const useModelProvider = create<ModelProviderState>()(
const ctx = model.settings?.ctx_len as
| { controller_props?: { value?: unknown } }
| undefined
- if (ctx?.controller_props?.value === 8192) {
- ctx.controller_props.value = ''
+ const controllerProps = ctx?.controller_props
+ const ctxValue =
+ typeof controllerProps?.value === 'string'
+ ? Number(controllerProps.value)
+ : controllerProps?.value
+ if (ctxValue === 8192 && controllerProps) {
+ controllerProps.value = ''
+ }
+ })
+ })
+ }
+
+ if (version <= 13 && state?.providers) {
+ // `defrag-thold` was deprecated upstream and the control was deleted
+ // from settings.json. Strip the orphan entry from the persisted
+ // provider settings array so localStorage doesn't carry it forever.
+ state.providers.forEach((provider) => {
+ if (provider.provider !== 'llamacpp' || !provider.settings) return
+ provider.settings = provider.settings.filter(
+ (s) => s.key !== 'defrag_thold'
+ )
+ })
+ }
+
+ if (version <= 14 && state?.providers) {
+ // Auto-increase context was removed — the manual "Increase Context
+ // Size" button in the error banner now owns this. Strip the per-model
+ // setting entry from llamacpp models so the sidebar doesn't render a
+ // dead control.
+ state.providers.forEach((provider) => {
+ if (provider.provider !== 'llamacpp' || !provider.models) return
+ provider.models.forEach((model) => {
+ if (model.settings?.auto_increase_ctx_len) {
+ delete (model.settings as Record<string, unknown>)
+ .auto_increase_ctx_len
}
})
})
}
return state
},
- version: 14,
+ version: 15,
}
)
)
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index ac8e602d8..1939d1114 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -79,6 +79,42 @@ const SCHEMA_PRIMITIVE_TYPES = new Set([
const SCHEMA_NODE_MAP_KEYS = new Set(['properties', 'patternProperties', 'definitions', '$defs'])
const SCHEMA_NODE_LIST_KEYS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems'])
+// Per-model sidebar keys whose values should be forwarded into each chat-
+// completion request body as defaults. In router mode these can't be CLI args
+// — the router is one process serving every model — so they have to ride
+// along on each call. Assistant `parameters` override these in the merge.
+const MODEL_SAMPLING_SETTING_KEYS = [
+ 'temperature',
+ 'top_k',
+ 'top_p',
+ 'min_p',
+ 'repeat_last_n',
+ 'repeat_penalty',
+ 'presence_penalty',
+ 'frequency_penalty',
+] as const
+
+function extractModelSamplingDefaults(
+ model: Model | null | undefined
+): Record<string, unknown> {
+ if (!model?.settings) return {}
+ const out: Record<string, unknown> = {}
+ for (const key of MODEL_SAMPLING_SETTING_KEYS) {
+ const raw = model.settings[key]?.controller_props?.value
+ if (raw === undefined || raw === null || raw === '') continue
+ // Sidebar inputs are string-typed even when controller_props.type is
+ // 'number'; coerce so the request body matches the OpenAI schema.
+ if (typeof raw === 'string') {
+ const n = Number(raw)
+ if (!Number.isFinite(n)) continue
+ out[key] = n
+ } else {
+ out[key] = raw
+ }
+ }
+ return out
+}
+
/**
* Coerce a schema-node slot into a valid sub-schema. Some tool generators
* emit shorthand like `{ "properties": { "foo": "string" } }` instead of
@@ -821,12 +857,21 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
}
+ // Per-model sidebar sampling defaults flow through as request-body
+ // overrides (router mode can't bake them into CLI args). Assistant
+ // params still win — they're the explicit per-conversation override.
+ const modelSamplingDefaults = extractModelSamplingDefaults(selectedModel)
+
// Create the model before refreshing tools so the MCP orchestrator can run
// structured LLM routing when many servers are connected.
this.model = await ModelFactory.createModel(
modelId,
updatedProvider ?? provider,
- { ...(inferenceParams ?? {}), ...reasoningParams }
+ {
+ ...modelSamplingDefaults,
+ ...(inferenceParams ?? {}),
+ ...reasoningParams,
+ }
)
useAppState.getState().updateLoadingModel(false)
useAppState.getState().updateThreadLoadingModel(threadId, false)
diff --git a/web-app/src/lib/predefined.ts b/web-app/src/lib/predefined.ts
index 447768a38..697d767eb 100644
--- a/web-app/src/lib/predefined.ts
+++ b/web-app/src/lib/predefined.ts
@@ -1,14 +1,4 @@
export const modelSettings = {
- auto_increase_ctx_len: {
- key: 'auto_increase_ctx_len',
- title: 'Auto Increase Context Size',
- description:
- 'Automatically increase context size when the model runs out of context mid-conversation.',
- controller_type: 'checkbox',
- controller_props: {
- value: true,
- },
- },
ctx_len: {
key: 'ctx_len',
title: 'Context Size',
diff --git a/web-app/src/lib/predefinedParams.ts b/web-app/src/lib/predefinedParams.ts
index d355823cb..8d0245903 100644
--- a/web-app/src/lib/predefinedParams.ts
+++ b/web-app/src/lib/predefinedParams.ts
@@ -85,6 +85,72 @@ export const paramsSettings = {
title: 'JSON Schema',
description: `JSON schema string to constrain generations as valid JSON (llama.cpp only).`,
},
+ typical_p: {
+ key: 'typical_p',
+ value: 1.0,
+ title: 'Typical P',
+ description: `Locally-typical sampling (llama.cpp only). 1.0 = disabled. Lower values bias toward tokens whose probability is close to the conditional entropy.`,
+ },
+ top_n_sigma: {
+ key: 'top_n_sigma',
+ value: -1.0,
+ title: 'Top N Sigma',
+ description: `Top-n-sigma sampling (llama.cpp only). -1 = disabled. Filters tokens by standard deviations above the max logit.`,
+ },
+ dynatemp_range: {
+ key: 'dynatemp_range',
+ value: 0.0,
+ title: 'Dynamic Temperature Range',
+ description: `Dynamic temperature range (llama.cpp only). 0 = disabled. The effective temperature is sampled in [temperature - range, temperature + range].`,
+ },
+ dynatemp_exp: {
+ key: 'dynatemp_exp',
+ value: 1.0,
+ title: 'Dynamic Temperature Exponent',
+ description: `Dynamic temperature exponent (llama.cpp only). Shapes the temperature distribution within the dynamic range.`,
+ },
+ xtc_probability: {
+ key: 'xtc_probability',
+ value: 0.0,
+ title: 'XTC Probability',
+ description: `Probability of activating the XTC (Exclude Top Choices) sampler (llama.cpp only). 0 = disabled.`,
+ },
+ xtc_threshold: {
+ key: 'xtc_threshold',
+ value: 0.1,
+ title: 'XTC Threshold',
+ description: `Minimum probability of a token to be considered for XTC exclusion (llama.cpp only). Only used when XTC probability > 0.`,
+ },
+ dry_multiplier: {
+ key: 'dry_multiplier',
+ value: 0.0,
+ title: 'DRY Multiplier',
+ description: `DRY (Don't Repeat Yourself) penalty multiplier (llama.cpp only). 0 = disabled. Penalizes sequences that have appeared before in the context.`,
+ },
+ dry_base: {
+ key: 'dry_base',
+ value: 1.75,
+ title: 'DRY Base',
+ description: `DRY penalty base (llama.cpp only). Exponential base for penalty growth as repeated-sequence length increases.`,
+ },
+ dry_allowed_length: {
+ key: 'dry_allowed_length',
+ value: 2,
+ title: 'DRY Allowed Length',
+ description: `Minimum repeated-sequence length before DRY starts penalizing (llama.cpp only).`,
+ },
+ dry_penalty_last_n: {
+ key: 'dry_penalty_last_n',
+ value: -1,
+ title: 'DRY Penalty Window',
+ description: `Window of recent tokens DRY scans for repetitions (llama.cpp only). 0 = disabled, -1 = full context.`,
+ },
+ ignore_eos: {
+ key: 'ignore_eos',
+ value: false,
+ title: 'Ignore EOS',
+ description: `Continue generating past the end-of-sequence token (llama.cpp only). Useful for forcing the model to fill a token budget.`,
+ },
}
export const LLAMACPP_ONLY_PARAM_KEYS: ReadonlySet<string> = new Set([
@@ -93,4 +159,15 @@ export const LLAMACPP_ONLY_PARAM_KEYS: ReadonlySet<string> = new Set([
'mirostat_eta',
'grammar',
'json_schema',
+ 'typical_p',
+ 'top_n_sigma',
+ 'dynatemp_range',
+ 'dynatemp_exp',
+ 'xtc_probability',
+ 'xtc_threshold',
+ 'dry_multiplier',
+ 'dry_base',
+ 'dry_allowed_length',
+ 'dry_penalty_last_n',
+ 'ignore_eos',
])
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index e973fba0a..5836f1f1b 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -53,7 +53,6 @@ import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
import { ExtensionManager } from '@/lib/extension'
import { Shimmer } from '@/components/ai-elements/shimmer'
-import { useAgentMode } from '@/hooks/useAgentMode'
import { useMessageQueue } from '@/stores/message-queue-store'
import { generateThreadTitle } from '@/lib/thread-title-summarizer'
import { useAutoScroll } from '@/hooks/useAutoScroll'
@@ -153,11 +152,6 @@ function ThreadDetail() {
// context-limit hit, so the user sees it instead of a blank gap.
const [pendingContinueMessage, setPendingContinueMessage] =
useState<UIMessage | null>(null)
- const [autoIncreaseAttempts, setAutoIncreaseAttempts] = useState(0)
- const MAX_AUTO_INCREASE_ATTEMPTS = 3
- const isAutoIncreasingContext =
- autoIncreaseAttempts > 0 &&
- autoIncreaseAttempts < MAX_AUTO_INCREASE_ATTEMPTS
const [contextLimitError, setContextLimitError] = useState<Error | null>(null)
const [processingEmbeddings, setProcessingEmbeddings] = useState(false)
@@ -171,6 +165,14 @@ function ThreadDetail() {
const setContinueFromContentRef = useRef<((content: string) => void) | null>(
null
)
+ // Holds the partial assistant output captured when the model stops with
+ // `finishReason === 'length'`. Consumed by `handleContextSizeIncrease` so
+ // the manual "Increase Context Size" button resumes from where the stream
+ // stopped rather than regenerating from scratch.
+ const pendingContinuationRef = useRef<{
+ message: UIMessage
+ text: string
+ } | null>(null)
// Use the AI SDK chat hook
const {
@@ -209,23 +211,17 @@ function ThreadDetail() {
const isContextLimit = totalTokens >= ctxLen * 0.9
if (isContextLimit) {
- const autoIncrease =
- selectedModelState?.settings?.auto_increase_ctx_len
- ?.controller_props?.value ?? true
- if (autoIncrease) {
- const partialText = message.parts
- .filter((p) => p.type === 'text')
- .map((p) => (p as { type: 'text'; text: string }).text)
- .join('')
- if (partialText) {
- setContinueFromContentRef.current?.(partialText)
- // Keep the partial message visible while the model reloads
- setPendingContinueMessage(message)
- }
- handleContextSizeIncreaseRef.current?.()
- } else {
- setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))
+ // Stash the partial so the manual "Increase Context Size" button can
+ // resume from here. Surface the standard banner with the manual
+ // button — auto-increase was removed; the user explicitly opts in.
+ const partialText = message.parts
+ .filter((p) => p.type === 'text')
+ .map((p) => (p as { type: 'text'; text: string }).text)
+ .join('')
+ if (partialText) {
+ pendingContinuationRef.current = { message, text: partialText }
}
+ setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))
}
return
}
@@ -987,7 +983,36 @@ function ThreadDetail() {
models: updatedModels,
})
- await serviceHub.models().stopModel(selectedModel.id)
+ // For llamacpp the router reads ctx-size from the preset, not from any
+ // request param — so we must write model.yml and bounce the router before
+ // the regenerate, otherwise the next load picks up the OLD context size.
+ // Other providers consume the new Zustand value directly on next load.
+ if (provider.provider === 'llamacpp') {
+ try {
+ await serviceHub
+ .models()
+ .updateModelSettings(selectedModel.id, { ctx_len: newCtxLen })
+ } catch (e) {
+ updateProvider(provider.provider, {
+ models: provider.models,
+ })
+ console.error('Failed to persist increased ctx_len', e)
+ setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))
+ return
+ }
+ } else {
+ await serviceHub.models().stopModel(selectedModel.id)
+ }
+
+ // Consume any pending partial captured at the `finishReason === 'length'`
+ // event so the regenerate resumes from where the stream stopped, and the
+ // "Growing the Mind…" shimmer renders while the model reloads.
+ const pending = pendingContinuationRef.current
+ pendingContinuationRef.current = null
+ if (pending) {
+ setContinueFromContentRef.current?.(pending.text)
+ setPendingContinueMessage(pending.message)
+ }
setTimeout(() => {
handleRegenerate()
@@ -1004,27 +1029,6 @@ function ThreadDetail() {
handleContextSizeIncreaseRef.current = handleContextSizeIncrease
setContinueFromContentRef.current = setContinueFromContent
- // Skip auto-context-increase in agent mode
- const agentModeActive = useAgentMode((s) => s.agentThreads[threadId] === true)
- useEffect(() => {
- if (!error || agentModeActive) return
- if (autoIncreaseAttempts >= MAX_AUTO_INCREASE_ATTEMPTS) return
- const autoIncrease =
- selectedModel?.settings?.auto_increase_ctx_len?.controller_props?.value ??
- true
- if (!autoIncrease) return
- const isContextError =
- (error.message?.toLowerCase().includes('context') &&
- (error.message?.toLowerCase().includes('size') ||
- error.message?.toLowerCase().includes('length') ||
- error.message?.toLowerCase().includes('limit'))) ||
- error.message === OUT_OF_CONTEXT_SIZE
- if (isContextError) {
- setAutoIncreaseAttempts((prev) => prev + 1)
- handleContextSizeIncrease()
- }
- }, [error]) // eslint-disable-line react-hooks/exhaustive-deps
-
useEffect(() => {
if ((oomError || backendError) && (status === 'streaming' || status === 'submitted')) {
try {
@@ -1039,8 +1043,10 @@ function ThreadDetail() {
if (status === 'streaming' || status === 'submitted') {
setContextLimitError(null)
}
- if (status === 'streaming' && autoIncreaseAttempts > 0) {
- setAutoIncreaseAttempts(0)
+ if (status === 'streaming' && pendingContinuationRef.current) {
+ // The new turn is now flowing; drop the saved partial so it can't be
+ // consumed by a later, unrelated "Increase Context Size" click.
+ pendingContinuationRef.current = null
}
if (status === 'error' && pendingContinueMessage) {
setPendingContinueMessage(null)
@@ -1147,18 +1153,15 @@ function ThreadDetail() {
<Shimmer duration={1}>Processing embeddings...</Shimmer>
</div>
)}
- {!oomError && !backendError && (status === CHAT_STATUS.SUBMITTED ||
- isAutoIncreasingContext) && (
+ {!oomError && !backendError && status === CHAT_STATUS.SUBMITTED && (
<div className="flex flex-row items-center gap-2">
- {(pendingContinueMessage || isAutoIncreasingContext) && (
+ {pendingContinueMessage && (
<Shimmer duration={1}>Growing the Mind...</Shimmer>
)}
- {status === CHAT_STATUS.SUBMITTED && !lastIsAssistant && (
- <PromptProgress />
- )}
+ {!lastIsAssistant && <PromptProgress />}
</div>
)}
- {(error || contextLimitError || oomError || backendError) && !isAutoIncreasingContext && (
+ {(error || contextLimitError || oomError || backendError) && (
<div className="px-4 py-3 mx-4 my-2 rounded-lg border border-destructive/10 bg-destructive/10">
<div className="flex items-start gap-3">
<IconAlertCircle className="size-5 text-destructive shrink-0 mt-0.5" />
diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.ts
index 3285287e3..e81407111 100644
--- a/web-app/src/services/models/default.ts
+++ b/web-app/src/services/models/default.ts
@@ -593,6 +593,21 @@ export class DefaultModelsService implements ModelsService {
}
}
+ async updateModelSettings(
+ modelId: string,
+ patch: Record<string, string | number | boolean | null | undefined>
+ ): Promise<void> {
+ const engine = this.getEngine('llamacpp') as AIEngine & {
+ updateModelSettings?: (
+ id: string,
+ patch: Record<string, string | number | boolean | null | undefined>
+ ) => Promise<void>
+ }
+ if (engine && typeof engine.updateModelSettings === 'function') {
+ await engine.updateModelSettings(modelId, patch)
+ }
+ }
+
async isModelSupported(
modelPath: string,
ctxSize?: number
diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.ts
index 757fe682b..ee7f6f58b 100644
--- a/web-app/src/services/models/types.ts
+++ b/web-app/src/services/models/types.ts
@@ -165,6 +165,10 @@ export interface ModelsService {
spec_draft_p_min?: number | null
}
): Promise<void>
+ updateModelSettings(
+ modelId: string,
+ patch: Record<string, string | number | boolean | null | undefined>
+ ): Promise<void>
isModelSupported(
modelPath: string,
ctxSize?: number
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index 1df827540..b4d894334 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -105,15 +105,10 @@ export class TauriProvidersService extends DefaultProvidersService {
provider: providerName,
settings: Object.values(modelSettings).reduce(
(acc, setting) => {
- let value = setting.controller_props.value
- if (setting.key === 'ctx_len') {
- value = 8192 // Default context length for Llama.cpp models
- }
acc[setting.key] = {
...setting,
controller_props: {
...setting.controller_props,
- value: value,
},
}
return acc