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.

feat(llamacpp): re-enable auto-fit by default and report models that do not fit (#9493)

Akarshan Biswas2377b91896e2
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 72d5fe4d0..66b3f61fd 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -41,7 +41,7 @@
"description": "Whether to adjust unset arguments to fit in device memory ('on' or 'off'). (env: LLAMA_ARG_FIT)",
"controllerType": "checkbox",
"controllerProps": {
- "value": false
+ "value": true
}
},
{
diff --git a/extensions/llamacpp-extension/src/fit-default.test.ts b/extensions/llamacpp-extension/src/fit-default.test.ts
new file mode 100644
index 000000000..706ed8414
--- /dev/null
+++ b/extensions/llamacpp-extension/src/fit-default.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect } from 'vitest'
+import type { SettingComponentProps } from '@janhq/core'
+import settingsJson from '../settings.json'
+import { applyPlatformFitDefault } from './fit-default'
+
+const shipped = (): SettingComponentProps[] =>
+ structuredClone(settingsJson) as unknown as SettingComponentProps[]
+
+const fitOf = (settings: SettingComponentProps[]) =>
+ settings.find((s) => s.key === 'fit')?.controllerProps.value
+
+describe('fit default', () => {
+ it('ships on', () => {
+ expect(fitOf(shipped())).toBe(true)
+ })
+
+ it('stays on off macOS', () => {
+ const settings = shipped()
+ applyPlatformFitDefault(settings, false)
+ expect(fitOf(settings)).toBe(true)
+ })
+
+ // janhq/jan#9198: with mmap on, Metal counts the mapped file against the
+ // working set, which fit does not model.
+ it('is off on macOS', () => {
+ const settings = shipped()
+ applyPlatformFitDefault(settings, true)
+ expect(fitOf(settings)).toBe(false)
+ })
+})
diff --git a/extensions/llamacpp-extension/src/fit-default.ts b/extensions/llamacpp-extension/src/fit-default.ts
new file mode 100644
index 000000000..9dee372ae
--- /dev/null
+++ b/extensions/llamacpp-extension/src/fit-default.ts
@@ -0,0 +1,19 @@
+import type { SettingComponentProps } from '@janhq/core'
+
+/**
+ * Turns the shipped `fit: true` default off on macOS, in place, before the
+ * settings are registered.
+ *
+ * With mmap on (the default) Metal counts the whole mapped file against
+ * `recommendedMaxWorkingSetSize`, which fit does not model, so it plans a load
+ * that still fails (janhq/jan#9198). Only the default changes: a value the
+ * user already stored wins in `registerSettings`.
+ */
+export function applyPlatformFitDefault(
+ settings: SettingComponentProps[],
+ isMac: boolean
+): void {
+ if (!isMac) return
+ const fit = settings.find((s) => s.key === 'fit')
+ if (fit) fit.controllerProps.value = false
+}
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 891dcd9ff..e87d9eb9c 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -33,6 +33,8 @@ import {
writeSettingsFile,
settingsFileExists,
} from './settings-store'
+import { applyPlatformFitDefault } from './fit-default'
+import { findModelEntries } from './model-tree'
import { listen } from '@tauri-apps/api/event'
import { invoke } from '@tauri-apps/api/core'
@@ -196,6 +198,14 @@ const LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY =
/// again. A user who deliberately chose exactly 100 loses that choice, which is
/// the right trade: 100 was never a considered value, it was the default.
const LEGACY_NGL_DEFAULT = 100
+/// Separate from the backfill key: the sweep now reaches nested Hub folders,
+/// and every existing install already has the backfill key set.
+const LEGACY_NGL_SWEPT_KEY = 'llamacpp_legacy_ngl_swept_v1'
+
+/// The context size the web-app seeded into every llamacpp model while fit was
+/// off by default; see migrateSeededCtxSize.
+const SEEDED_CTX_SIZE = 8192
+const SEEDED_CTX_CLEARED_KEY = 'llamacpp_seeded_ctx_cleared_v1'
/// Matches the `timeout` default in settings.json.
const DEFAULT_TIMEOUT = 600
@@ -486,6 +496,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
// check_for_updates, auto_update_engine, verify_backend_deps) from the
// persisted set on its own.
const settings = structuredClone(SETTINGS)
+ applyPlatformFitDefault(settings, IS_MAC)
await this.registerSettings(settings)
let loadedConfig: any = {}
@@ -499,10 +510,9 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
}
this.config = loadedConfig as LlamacppConfig
- // Auto-fit is disabled by default on all platforms; ctx-size owns context
- // sizing. Force off for users a prior build left with fit enabled.
- await this.migrateFitOff()
-
+ // No fit migration: the settings file stores every value with no record of
+ // who set it, so a stored `fit: false` cannot be told apart from an explicit
+ // off. Existing installs keep what they have; the default reaches new ones.
await this.migrateAutoUnloadToModelsMax()
await this.migrateParallelToDefault()
@@ -513,8 +523,13 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
// This sets the base directory where model files for this provider are stored.
await this.getProviderPath()
+ await this.migrateLegacyNgl()
+
await this.migratePersistedModelSettingsToYaml()
+ // After the backfill, which is what copied the seed into model.yml.
+ await this.migrateSeededCtxSize()
+
// Set up validation event listeners to bridge Tauri events to frontend
this.unlistenValidationStarted = await listen<{
modelId: string
@@ -1199,37 +1214,12 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
await setBackendSetting(MIGRATION_KEY, '1')
}
- private async migrateFitOff(): Promise<void> {
- const MIGRATION_KEY = 'llamacpp_fit_off_v1'
- if (await getBackendSetting(MIGRATION_KEY)) return
-
- if (this.config.fit === true) {
- const settings = await this.getSettings()
- await this.updateSettings(
- settings.map((item) => {
- if (item.key === 'fit') {
- item.controllerProps.value = false
- }
- return item
- })
- )
- this.config.fit = false
- logger.info('Migrated fit setting: disabled')
- }
-
- await setBackendSetting(MIGRATION_KEY, '1')
- }
-
private async migratePersistedModelSettingsToYaml(): Promise<void> {
if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return
const persistedModels = await readPersistedLlamacppModels()
const providerPath = await this.getProviderPath()
- // v1's n_gpu_layers stamp lives in model.yml, not in the persisted
- // settings, so it has to be swept even when nothing is persisted.
- await this.stripLegacyNglFromModelYaml(providerPath)
-
if (persistedModels.length === 0) {
await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
return
@@ -1293,40 +1283,64 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
}
/**
- * Removes v1's `n_gpu_layers: 100` stamp from every model.yml.
+ * One-shot: removes v1's `n_gpu_layers: 100` stamp from every model.yml. It
+ * lives in the yaml, not in the persisted settings, so it is swept even when
+ * nothing is persisted.
+ */
+ private async migrateLegacyNgl(): Promise<void> {
+ if (await getBackendSetting(LEGACY_NGL_SWEPT_KEY)) return
+ await this.stripModelYamlValue(
+ await this.getProviderPath(),
+ 'n_gpu_layers',
+ LEGACY_NGL_DEFAULT
+ )
+ await setBackendSetting(LEGACY_NGL_SWEPT_KEY, '1')
+ }
+
+ /**
+ * One-shot: drops the `ctx_size: 8192` the web-app seeded into every model
+ * (and the settings backfill then copied into model.yml), so auto-fit may
+ * shrink the context down to `fit_ctx`; upstream's fit leaves a set context
+ * alone. The seed has no provenance, so 8192 is taken to be it. Nothing
+ * changes with fit off: preset.ts's `[*] ctx-size` is 8192 too.
+ */
+ private async migrateSeededCtxSize(): Promise<void> {
+ if (await getBackendSetting(SEEDED_CTX_CLEARED_KEY)) return
+ await this.stripModelYamlValue(
+ await this.getProviderPath(),
+ 'ctx_size',
+ SEEDED_CTX_SIZE
+ )
+ await setBackendSetting(SEEDED_CTX_CLEARED_KEY, '1')
+ }
+
+ /**
+ * Removes `key` from every model.yml where it equals `value`.
*
- * Separate from the settings backfill because the stamp is in the yaml even
- * for models that no longer appear in the persisted provider settings, so
- * iterating the persisted list would miss them.
+ * Walks the models directory rather than the persisted settings because a
+ * stamped value is in the yaml even for models that no longer appear in the
+ * persisted provider settings, so iterating the persisted list would miss them.
*/
- private async stripLegacyNglFromModelYaml(providerPath: string): Promise<void> {
+ private async stripModelYamlValue(
+ providerPath: string,
+ key: string,
+ value: number
+ ): Promise<void> {
const modelsDir = await joinPath([providerPath, 'models'])
if (!(await fs.existsSync(modelsDir))) return
- let entries: string[] = []
- try {
- entries = await fs.readdirSync(modelsDir)
- } catch (e) {
- logger.warn('Could not list models while sweeping legacy ngl:', e)
- return
- }
-
- for (const entry of entries) {
- const configPath = await joinPath([entry, 'model.yml'])
+ for (const { configPath } of await findModelEntries(modelsDir)) {
try {
- if (!(await fs.existsSync(configPath))) continue
// Read as a bag rather than ModelConfig: that type covers the
// plugin's own fields, not every per-model key the sidebar writes.
const cfg = await fs.readYaml<Record<string, unknown>>(configPath)
- if (cfg?.n_gpu_layers !== LEGACY_NGL_DEFAULT) continue
- delete cfg.n_gpu_layers
+ if (cfg?.[key] !== value) continue
+ delete cfg[key]
await fs.writeYaml(configPath, cfg)
- logger.info(
- `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${configPath}`
- )
+ logger.info(`Removed ${key}=${value} from ${configPath}`)
} catch (e) {
// Per-model isolation: one unreadable yaml must not block the sweep.
- logger.warn(`Legacy ngl sweep skipped ${configPath}:`, e)
+ logger.warn(`${key} sweep skipped ${configPath}:`, e)
}
}
}
@@ -1693,41 +1707,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
logger.warn(`list: migrateLegacyModels failed, continuing: ${String(err)}`)
}
- let modelIds: string[] = []
-
- // DFS. Mirror the defensive pattern in preset.ts: an unreadable entry
- // (Windows AV quarantine, junction, locked file) must not kill the whole
- // scan — log and continue past it.
- let stack = [modelsDir]
- while (stack.length > 0) {
- const currentDir = stack.pop()
-
- // check if model.yml exists
- const modelConfigPath = await joinPath([currentDir, 'model.yml'])
- if (await fs.existsSync(modelConfigPath)) {
- // +1 to remove the leading slash
- // NOTE: this does not handle Windows path \\
- modelIds.push(currentDir.slice(modelsDir.length + 1))
- continue
- }
-
- let children: string[] = []
- try {
- children = await fs.readdirSync(currentDir)
- } catch (err) {
- logger.warn(`list: readdir failed for ${currentDir}: ${String(err)}`)
- continue
- }
- for (const child of children) {
- try {
- const dirInfo = await fs.fileStat(child)
- if (!dirInfo?.isDirectory) continue
- stack.push(child)
- } catch (err) {
- logger.warn(`list: stat failed for ${child}: ${String(err)}`)
- }
- }
- }
+ const modelIds = (await findModelEntries(modelsDir)).map((e) => e.modelId)
// Per-model isolation: one malformed model.yml (or a write_yaml failure
// inside resolveEmbeddingConfig) must not discard the other entries.
diff --git a/extensions/llamacpp-extension/src/model-tree.ts b/extensions/llamacpp-extension/src/model-tree.ts
new file mode 100644
index 000000000..0c4d600b3
--- /dev/null
+++ b/extensions/llamacpp-extension/src/model-tree.ts
@@ -0,0 +1,49 @@
+import { fs, joinPath, logger } from '@janhq/core'
+
+/** A directory under `models/` that holds a `model.yml`. */
+export type ModelEntry = {
+ /** The path below `models/`, e.g. `author/model` for a Hub download. */
+ modelId: string
+ configPath: string
+}
+
+/**
+ * Every model under `modelsDir`, however deeply nested.
+ *
+ * Model IDs are paths: an import is `models/<id>/model.yml`, but a Hub quant is
+ * saved as `models/<author>/<model>/model.yml`, so a one-level scan misses most
+ * downloads. A directory with a `model.yml` is a model and is not descended
+ * into. An unreadable entry (Windows AV quarantine, a junction, a locked file)
+ * is logged and skipped so it cannot hide every other model.
+ */
+export async function findModelEntries(modelsDir: string): Promise<ModelEntry[]> {
+ const entries: ModelEntry[] = []
+ const stack: string[] = [modelsDir]
+ while (stack.length > 0) {
+ const currentDir = stack.pop() as string
+ const configPath = await joinPath([currentDir, 'model.yml'])
+ if (await fs.existsSync(configPath)) {
+ // +1 drops the leading separator. NOTE: not Windows-`\\`-aware, the same
+ // trade-off list() and the preset always made.
+ entries.push({ modelId: currentDir.slice(modelsDir.length + 1), configPath })
+ continue
+ }
+
+ let children: string[] = []
+ try {
+ children = await fs.readdirSync(currentDir)
+ } catch (err) {
+ logger.warn(`models scan: readdir failed for ${currentDir}: ${String(err)}`)
+ continue
+ }
+ for (const child of children) {
+ try {
+ const stat = await fs.fileStat(child)
+ if (stat?.isDirectory) stack.push(child)
+ } catch (err) {
+ logger.warn(`models scan: stat failed for ${child}: ${String(err)}`)
+ }
+ }
+ }
+ return entries
+}
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.ts
index 659c05a06..017bd708e 100644
--- a/extensions/llamacpp-extension/src/preset.test.ts
+++ b/extensions/llamacpp-extension/src/preset.test.ts
@@ -719,6 +719,15 @@ describe('generatePreset upstream-default skipping', () => {
expect(modelSection('m')).toContain('ctx-size = 16384')
})
+ // No ctx_size in model.yml (the seeded 8192 is gone) means nothing pins n_ctx,
+ // so fit is free to shrink the context down to fit_ctx.
+ it('emits no ctx-size anywhere when fit is on and the model sets none', async () => {
+ setupModel('m', {})
+ await generatePreset('/p', '/jan', { fit: true } as any)
+ expect(modelSection('m')).not.toContain('ctx-size')
+ expect(globalSection()).not.toContain('ctx-size')
+ })
+
it('emits n-gpu-layers for auto (-1) and all (-2) but not below', async () => {
setupModel('a', { n_gpu_layers: -1 })
await generatePreset('/p', '/jan', { fit: false } as any)
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 69949f8ed..385e2a862 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -15,6 +15,7 @@
import { fs, joinPath } from '@janhq/core'
import { invoke } from '@tauri-apps/api/core'
+import { findModelEntries } from './model-tree'
import type { LlamacppConfig, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'
// ModelConfig is intentionally widened — model.yml may carry extra fields like
@@ -186,37 +187,10 @@ export async function generatePreset(
await fs.mkdir(modelsDir)
}
- // DFS for any directory containing model.yml — mirrors the logic in
- // index.ts:list() so nested model IDs (e.g. "huggingface/foo") work.
- const modelEntries: { modelId: string; configPath: string }[] = []
- const stack: string[] = [modelsDir]
- while (stack.length > 0) {
- const currentDir = stack.pop() as string
- const modelConfigPath = await joinPath([currentDir, 'model.yml'])
- if (await fs.existsSync(modelConfigPath)) {
- // +1 to drop leading separator. NOTE: matches index.ts behavior; not
- // Windows-`\\`-aware, same trade-off as the existing list() impl.
- const modelId = currentDir.slice(modelsDir.length + 1)
- if (modelId.length > 0) {
- modelEntries.push({ modelId, configPath: modelConfigPath })
- }
- continue
- }
- let children: string[] = []
- try {
- children = await fs.readdirSync(currentDir)
- } catch {
- continue
- }
- for (const child of children) {
- try {
- const stat = await fs.fileStat(child)
- if (stat?.isDirectory) stack.push(child)
- } catch {
- /* ignore unreadable entries */
- }
- }
- }
+ // A model.yml at the models root itself has no ID to key a section on.
+ const modelEntries = (await findModelEntries(modelsDir)).filter(
+ (e) => e.modelId.length > 0
+ )
modelEntries.sort((a, b) => a.modelId.localeCompare(b.modelId))
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index eae31ad5c..b589af6c2 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -511,64 +511,79 @@ describe('llamacpp_extension', () => {
})
})
- describe('migrateFitOff', () => {
- beforeEach(() => {
- vi.mocked(getBackendSetting).mockResolvedValue(null)
+ // Existing installs keep their stored fit value: the settings file has no
+ // record of who set it, so an untouched off and an explicit off look alike.
+ describe('fit migration', () => {
+ it('no longer forces fit off at load', () => {
+ expect((extension as any).migrateFitOff).toBeUndefined()
})
+ })
- it('should skip migration if already migrated', async () => {
- vi.mocked(getBackendSetting).mockResolvedValue('1')
- extension['config'] = { fit: true } as any
- extension['getSettings'] = vi.fn()
-
- await extension['migrateFitOff']()
+ describe('migrateSeededCtxSize', () => {
+ const yamls: Record<string, Record<string, unknown>> = {}
- expect(extension['getSettings']).not.toHaveBeenCalled()
+ beforeEach(async () => {
+ const { fs, joinPath, getJanDataFolderPath } = await import('@janhq/core')
+ vi.mocked(getBackendSetting).mockResolvedValue(null)
+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')
+ vi.mocked(joinPath).mockImplementation((p) => Promise.resolve(p.join('/')))
+ // A Hub download is nested one level deeper, under its author.
+ yamls['/jan/llamacpp/models/seeded/model.yml'] = { name: 's', ctx_size: 8192 }
+ yamls['/jan/llamacpp/models/custom/model.yml'] = { name: 'c', ctx_size: 32768 }
+ yamls['/jan/llamacpp/models/author/hub/model.yml'] = { name: 'h', ctx_size: 8192 }
+ const tree: Record<string, string[]> = {
+ '/jan/llamacpp/models': [
+ '/jan/llamacpp/models/seeded',
+ '/jan/llamacpp/models/custom',
+ '/jan/llamacpp/models/author',
+ ],
+ '/jan/llamacpp/models/author': ['/jan/llamacpp/models/author/hub'],
+ }
+ vi.mocked(fs.existsSync).mockImplementation(
+ async (p: string) => p === '/jan/llamacpp/models' || p in yamls
+ )
+ vi.mocked(fs.readdirSync).mockImplementation(async (p: string) => tree[p] ?? [])
+ vi.mocked(fs.fileStat).mockResolvedValue({ isDirectory: true, size: 0 })
+ ;(fs as any).readYaml = vi.fn((path: string) =>
+ Promise.resolve(structuredClone(yamls[path]))
+ )
+ ;(fs as any).writeYaml = vi.fn((path: string, data: Record<string, unknown>) => {
+ yamls[path] = data
+ return Promise.resolve()
+ })
})
- it('should set migration key without calling updateSettings when fit is already false', async () => {
- extension['config'] = { fit: false } as any
- extension['getSettings'] = vi.fn()
- extension['updateSettings'] = vi.fn()
-
- await extension['migrateFitOff']()
+ it('drops the seeded 8192 so fit can size the context, and keeps a chosen one', async () => {
+ await (extension as any).migrateSeededCtxSize()
- expect(extension['getSettings']).not.toHaveBeenCalled()
- expect(extension['updateSettings']).not.toHaveBeenCalled()
- expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')
+ expect(yamls['/jan/llamacpp/models/seeded/model.yml']).toEqual({ name: 's' })
+ expect(yamls['/jan/llamacpp/models/author/hub/model.yml']).toEqual({ name: 'h' })
+ expect(yamls['/jan/llamacpp/models/custom/model.yml'].ctx_size).toBe(32768)
+ expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_seeded_ctx_cleared_v1', '1')
})
- it('should disable fit when it is true', async () => {
- extension['config'] = { fit: true } as any
- extension['getSettings'] = vi.fn().mockResolvedValue([
- { key: 'fit', controllerProps: { value: true } },
- { key: 'ctx_size', controllerProps: { value: 2048 } },
- ])
- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+ it('runs once', async () => {
+ vi.mocked(getBackendSetting).mockResolvedValue('1')
- await extension['migrateFitOff']()
+ await (extension as any).migrateSeededCtxSize()
- const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]
- expect(updatedSettings.find((s: any) => s.key === 'fit').controllerProps.value).toBe(false)
- expect(updatedSettings.find((s: any) => s.key === 'ctx_size').controllerProps.value).toBe(2048)
- expect(extension['config'].fit).toBe(false)
- expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_fit_off_v1', '1')
+ expect(yamls['/jan/llamacpp/models/seeded/model.yml'].ctx_size).toBe(8192)
})
- it('should not modify other settings during fit migration', async () => {
- extension['config'] = { fit: true } as any
- extension['getSettings'] = vi.fn().mockResolvedValue([
- { key: 'fit', controllerProps: { value: true } },
- { key: 'fit_target', controllerProps: { value: '1024' } },
- { key: 'fit_ctx', controllerProps: { value: '' } },
- ])
- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+ // Installs that already ran the settings backfill still need the nested
+ // folders swept, so the ngl sweep has its own key.
+ it('sweeps the legacy n_gpu_layers stamp under its own key', async () => {
+ yamls['/jan/llamacpp/models/author/hub/model.yml'] = { name: 'h', n_gpu_layers: 100 }
+ yamls['/jan/llamacpp/models/custom/model.yml'] = { name: 'c', n_gpu_layers: 20 }
+ vi.mocked(getBackendSetting).mockImplementation(async (key: string) =>
+ key === 'llamacpp_model_yaml_backfill_v2' ? '1' : null
+ )
- await extension['migrateFitOff']()
+ await (extension as any).migrateLegacyNgl()
- const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]
- expect(updatedSettings.find((s: any) => s.key === 'fit_target').controllerProps.value).toBe('1024')
- expect(updatedSettings.find((s: any) => s.key === 'fit_ctx').controllerProps.value).toBe('')
+ expect(yamls['/jan/llamacpp/models/author/hub/model.yml']).toEqual({ name: 'h' })
+ expect(yamls['/jan/llamacpp/models/custom/model.yml'].n_gpu_layers).toBe(20)
+ expect(setBackendSetting).toHaveBeenCalledWith('llamacpp_legacy_ngl_swept_v1', '1')
})
})
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index 1bba6adaa..76cab90d9 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -5,6 +5,8 @@ use std::sync::Arc;
use std::time::Duration;
use tauri::{Emitter, Manager, Runtime, State};
+use crate::engine::preset;
+use crate::engine::worker::FitMark;
use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};
use crate::state::{EngineLease, LlamacppState, SessionInfo};
@@ -94,6 +96,79 @@ enum WorkerFate {
const EXIT_GRACE: Duration = Duration::from_millis(500);
const EXIT_POLL: Duration = Duration::from_millis(50);
+/// How long a failed load waits for the worker's fit-failure line. fit prints
+/// it before the load starts, but stderr is drained on its own task, so it can
+/// still be in the pipe when the HTTP answer arrives.
+const FIT_NOTE_WAIT: Duration = Duration::from_millis(100);
+
+/// Where the worker on `port` is in its fit-failure lines, taken before a load
+/// so that only a line printed during it counts.
+async fn fit_mark(state: &LlamacppState, port: u16) -> Option<FitMark> {
+ let guard = state.engine.lock().await;
+ guard.as_ref().filter(|h| h.port == port).map(|h| h.fit_mark())
+}
+
+/// The fit-failure line the worker on `port` printed after `mark`, plus the
+/// preset it runs from.
+async fn fit_failure_since(
+ state: &LlamacppState,
+ port: u16,
+ mark: FitMark,
+) -> (Option<String>, Option<std::path::PathBuf>) {
+ let guard = state.engine.lock().await;
+ match guard.as_ref().filter(|h| h.port == port) {
+ Some(h) => (h.fit_failure_since(mark), Some(h.preset_path.clone())),
+ None => (None, None),
+ }
+}
+
+/// Rewords a failed load that auto-fit could not place. Without this the user
+/// sees an out-of-memory error whose advice is a smaller context, when fit has
+/// already shrunk the context as far as `fit-ctx` allows.
+///
+/// Two signals, because fit.cpp only gives up loudly without a GPU: there it
+/// prints a "unable to fit model into system memory" line. With a GPU it never
+/// fails; it shrinks the context, moves layers to the CPU and loads, so a model
+/// too big for the device fails as a plain out-of-memory load. That is read as
+/// not fitting only when fit owned the context for this model; a pinned
+/// `ctx-size` is left alone by fit, and lowering it is real advice.
+async fn explain_load_failure(
+ state: &LlamacppState,
+ port: u16,
+ model_id: &str,
+ mark: Option<FitMark>,
+ err: LlamacppError,
+) -> LlamacppError {
+ let Some(mark) = mark else { return err };
+ let (mut line, mut preset) = fit_failure_since(state, port, mark).await;
+ if line.is_none() {
+ tokio::time::sleep(FIT_NOTE_WAIT).await;
+ (line, preset) = fit_failure_since(state, port, mark).await;
+ }
+ let output = err.details.clone().unwrap_or_default();
+ if let Some(line) = line {
+ let details = if output.trim().is_empty() {
+ line
+ } else {
+ format!("{line}; {output}")
+ };
+ return LlamacppError::model_does_not_fit(details);
+ }
+ if !matches!(err.code, ErrorCode::OutOfMemory) {
+ return err;
+ }
+ let ini = match preset {
+ Some(path) => tokio::fs::read_to_string(&path).await.ok(),
+ None => None,
+ };
+ match ini {
+ Some(ini) if preset::fit_owns_context(&ini, model_id) => {
+ LlamacppError::model_does_not_fit(output)
+ }
+ _ => err,
+ }
+}
+
/// Checks the process, which is the one thing that tells the two causes of an
/// unreachable worker apart: a crash, or something between Jan and 127.0.0.1.
///
@@ -464,6 +539,7 @@ async fn post_load<R: Runtime>(
}
let state: State<Arc<LlamacppState>> = app_handle.state();
+ let mark = fit_mark(&state, port).await;
let client = http_client().await;
let url = format!("http://127.0.0.1:{}/models/load", port);
let resp = client
@@ -491,10 +567,9 @@ async fn post_load<R: Runtime>(
let body = resp.text().await.unwrap_or_default();
if !body.to_lowercase().contains("already") {
progress_task.abort();
- return Err(ServerError::Llamacpp(load_rejection_error(
- status.as_u16(),
- &body,
- )));
+ let err = load_rejection_error(status.as_u16(), &body);
+ let err = explain_load_failure(&state, port, model_id, mark, err).await;
+ return Err(ServerError::Llamacpp(err));
}
}
@@ -520,7 +595,12 @@ async fn post_load<R: Runtime>(
))),
};
progress_task.abort();
- result
+ match result {
+ Err(ServerError::Llamacpp(err)) => Err(ServerError::Llamacpp(
+ explain_load_failure(&state, port, model_id, mark, err).await,
+ )),
+ other => other,
+ }
}
#[derive(Debug, PartialEq)]
@@ -1174,6 +1254,137 @@ mod unreachable_worker_tests {
assert!(handle.is_some(), "a live worker is left in place");
handle.unwrap().kill().await;
}
+
+ /// The worker's answer to a load llama.cpp could not allocate, as
+ /// `http.rs` sends it: the shim's message plus the ERROR lines it caught.
+ const OOM_BODY: &str = r#"{"error":{"message":"failed to load model; ggml_backend_cuda_buffer_type_alloc_buffer: allocating 9000.00 MiB on device 0: cudaMalloc failed: out of memory","code":400}}"#;
+
+ const FIT_LINE: &str = "common_fit_params: failed to fit params to free device memory: was unable to fit model into system memory by reducing context, abort";
+
+ /// A live fake worker whose stderr runs `stderr` after the handshake,
+ /// installed as the engine and pointed at a preset holding `ini`.
+ #[cfg(unix)]
+ async fn fit_worker(dir: &Path, stderr: &str, ini: &str) -> (LlamacppState, u16) {
+ let port = closed_port();
+ let mut handle = spawn_fake(
+ dir,
+ &format!("echo '{{\"port\":{port},\"pid\":'$$'}}'\n{stderr}\nexec sleep 30"),
+ )
+ .await;
+ let preset = dir.join("router.preset.ini");
+ std::fs::write(&preset, ini).unwrap();
+ handle.preset_path = preset;
+ let state = LlamacppState::new();
+ *state.engine.lock().await = Some(handle);
+ (state, port)
+ }
+
+ /// Waits until the worker's stderr drain has seen a fit-failure line
+ /// printed after `mark`, so the assertion is not a race with the pipe.
+ #[cfg(unix)]
+ async fn wait_for_fit_line(state: &LlamacppState, port: u16, mark: FitMark) {
+ let deadline = std::time::Instant::now() + Duration::from_secs(10);
+ while fit_failure_since(state, port, mark).await.0.is_none() {
+ assert!(std::time::Instant::now() < deadline, "fit line never arrived");
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ }
+
+ #[cfg(unix)]
+ async fn stop(state: LlamacppState) {
+ state.engine.lock().await.take().unwrap().kill().await;
+ }
+
+ // No GPU: fit gives up out loud, and the load that follows fails with
+ // whatever llama.cpp hit next. The fit line is the cause.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_load_after_fit_gave_up_on_system_memory_does_not_fit() {
+ let dir = tempfile::tempdir().unwrap();
+ // Printed once the mark is taken, as during a real load.
+ let (state, port) = fit_worker(
+ dir.path(),
+ &format!("sleep 0.2; echo '{FIT_LINE}' >&2"),
+ "[*]\nfit = off\nctx-size = 8192\n[m]\n",
+ )
+ .await;
+ let mark = fit_mark(&state, port).await;
+ wait_for_fit_line(&state, port, mark.unwrap()).await;
+
+ let failed = LlamacppError::from_load_failure("failed to load model");
+ let err = explain_load_failure(&state, port, "m", mark, failed).await;
+ let v = json(&err);
+ assert_eq!(v["code"], "MODEL_DOES_NOT_FIT", "{v}");
+ let details = v["details"].as_str().unwrap();
+ assert!(details.starts_with(FIT_LINE), "{details}");
+ assert!(details.ends_with("failed to load model"), "{details}");
+ stop(state).await;
+ }
+
+ // With a GPU fit never fails: it shrinks the context and offloads, and a
+ // model still too big runs out of memory. With fit owning the context that
+ // is the model not fitting, not a context the user could lower.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn an_out_of_memory_load_with_fit_owning_the_context_does_not_fit() {
+ let dir = tempfile::tempdir().unwrap();
+ let (state, port) =
+ fit_worker(dir.path(), "", "[*]\nfit-ctx = 4096\n\n[m]\nmodel = /m.gguf\n").await;
+ let mark = fit_mark(&state, port).await;
+
+ let err = load_rejection_error(400, OOM_BODY);
+ assert_eq!(json(&err)["code"], "OUT_OF_MEMORY", "the plain classification");
+ let err = explain_load_failure(&state, port, "m", mark, err).await;
+ let v = json(&err);
+ assert_eq!(v["code"], "MODEL_DOES_NOT_FIT", "{v}");
+ assert!(
+ v["details"].as_str().unwrap().contains("cudaMalloc failed: out of memory"),
+ "{v}"
+ );
+ stop(state).await;
+ }
+
+ // Fit off, or a context the user pinned (fit leaves it alone): a smaller
+ // context is real advice, so the out-of-memory error stands.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn an_out_of_memory_load_fit_did_not_size_stays_out_of_memory() {
+ for ini in [
+ "[*]\nfit = off\nctx-size = 8192\n\n[m]\nmodel = /m.gguf\n",
+ "[*]\n\n[m]\nmodel = /m.gguf\nctx-size = 32768\n",
+ ] {
+ let dir = tempfile::tempdir().unwrap();
+ let (state, port) = fit_worker(dir.path(), "", ini).await;
+ let mark = fit_mark(&state, port).await;
+
+ let err = load_rejection_error(400, OOM_BODY);
+ let err = explain_load_failure(&state, port, "m", mark, err).await;
+ assert_eq!(json(&err)["code"], "OUT_OF_MEMORY", "{ini}");
+ stop(state).await;
+ }
+ }
+
+ // A fit line from an earlier load must not be blamed for this one, and a
+ // failure that is not about memory keeps its own code.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn an_earlier_loads_fit_line_does_not_explain_this_failure() {
+ let dir = tempfile::tempdir().unwrap();
+ let (state, port) = fit_worker(
+ dir.path(),
+ &format!("echo '{FIT_LINE}' >&2"),
+ "[*]\n[m]\n",
+ )
+ .await;
+ let before = fit_mark(&state, port).await.unwrap();
+ wait_for_fit_line(&state, port, before).await;
+ let mark = fit_mark(&state, port).await;
+
+ let failed = LlamacppError::from_load_failure("error loading model architecture: unknown");
+ let err = explain_load_failure(&state, port, "m", mark, failed).await;
+ assert_eq!(json(&err)["code"], "MODEL_ARCH_NOT_SUPPORTED", "{err:?}");
+ stop(state).await;
+ }
}
#[cfg(test)]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
index 98c4e6e84..34886723b 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs
@@ -67,6 +67,39 @@ pub fn shared_value(ini: &str, key: &str) -> Option<String> {
None
}
+/// Whether auto-fit is free to size `section`'s context: fit is on (llama.cpp's
+/// default when the preset says nothing), no `ctx-size` pins it, and the split
+/// mode is not `tensor`.
+///
+/// Only then has fit already shrunk the context as far as `fit-ctx` allows by
+/// the time a load runs out of memory, so "use a smaller context" would be
+/// wrong advice. Any `ctx-size`, 0 included, stops fit from touching it
+/// (`common/arg.cpp`: 0 asks for the full trained context). Tensor split mode
+/// makes fit.cpp abort before it reduces the context. An explicit n-gpu-layers,
+/// tensor-split or row split mode does not: fit shrinks the context first and
+/// only then declines to place layers. A model's own line
+/// wins over `[*]`, the order the C++ loader applies them in. Only the spellings
+/// Jan's preset generator writes are read.
+pub fn fit_owns_context(ini: &str, section: &str) -> bool {
+ let bodies = section_bodies(ini);
+ let value = |key: &str| {
+ [section, "*"].iter().find_map(|name| {
+ bodies.get(*name)?.iter().find_map(|line| {
+ let (k, v) = line.split_once('=')?;
+ (k.trim() == key).then(|| v.trim().to_string())
+ })
+ })
+ };
+ // `common_arg_utils::is_falsey`; anything else leaves fit at its default.
+ let fit_on = !matches!(
+ value("fit").as_deref(),
+ Some("off" | "disabled" | "false" | "0")
+ );
+ fit_on
+ && value("ctx-size").is_none()
+ && value("split-mode").as_deref() != Some("tensor")
+}
+
/// Load specs for every model in a preset.
///
/// The spec carries the section body so `Registry::reload` can diff it. Two
@@ -181,6 +214,34 @@ embeddings = true
);
}
+ #[test]
+ fn fit_owns_the_context_only_when_on_and_no_ctx_size_pins_it() {
+ let auto = "[*]\nparallel = 1\n\n[m]\nmodel = /m.gguf\n";
+ assert!(fit_owns_context(auto, "m"), "fit is on by default");
+ assert!(fit_owns_context("[*]\nfit = on\n[m]\n", "m"));
+
+ // Jan's preset with fit off pins the shared context as well.
+ let off = "[*]\nfit = off\nctx-size = 8192\n\n[m]\nmodel = /m.gguf\n";
+ assert!(!fit_owns_context(off, "m"));
+ assert!(!fit_owns_context("[*]\nfit = false\n[m]\n", "m"));
+
+ // A user's own context, or 0 (the full trained one), is left alone by
+ // fit, so a smaller context is still advice that helps.
+ assert!(!fit_owns_context("[*]\n[m]\nctx-size = 32768\n", "m"));
+ assert!(!fit_owns_context("[*]\n[m]\nctx-size = 0\n", "m"));
+ assert!(fit_owns_context("[*]\n[m]\n[other]\nctx-size = 4096\n", "m"));
+
+ // A model's own line overrides [*].
+ assert!(fit_owns_context("[*]\nfit = off\n[m]\nfit = on\n", "m"));
+
+ // Tensor split aborts fit before it touches the context; row split
+ // and pinned layers only stop it after it has shrunk the context.
+ assert!(!fit_owns_context("[*]\nsplit-mode = tensor\n[m]\n", "m"));
+ assert!(fit_owns_context("[*]\nsplit-mode = row\n[m]\n", "m"));
+ assert!(fit_owns_context("[*]\ntensor-split = 3,1\n[m]\n", "m"));
+ assert!(fit_owns_context("[*]\n[m]\nn-gpu-layers = 20\n", "m"));
+ }
+
// Comments and blank lines are not settings; a reload triggered by one
// would cold-load the user's chat model for nothing.
#[test]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
index ac49e31b9..70af0df5a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
@@ -174,6 +174,20 @@ fn is_backend_error_line(line_lower: &str) -> bool {
.any(|m| line_lower.contains(m))
}
+/// Whether a worker log line says auto-fit could not fit the model even into
+/// system memory. llama.cpp then loads with the unfitted parameters anyway, so
+/// the load that follows fails with an error that does not name the cause.
+///
+/// fit.cpp throws this only when there is no GPU at all (`nd == 0`); with a GPU
+/// it shrinks the context and offloads instead, and a model still too big shows
+/// up as an ordinary out-of-memory load failure (see `commands::explain_load_failure`).
+/// The other reasons fit gives (an explicit n_gpu_layers or tensor split, a
+/// split mode it does not handle) are fit declining to run, not a model that is
+/// too big. None of them is a runtime fault, so `classify_fault` ignores them.
+pub fn is_fit_failure_line(line_lower: &str) -> bool {
+ line_lower.contains("failed to fit params") && line_lower.contains("unable to fit model")
+}
+
/// Turns worker stderr lines into faults, one call per line.
///
/// Metal reports a failed command buffer as two lines: a status line that
@@ -252,6 +266,22 @@ const STDERR_DRAIN_WAIT: Duration = Duration::from_millis(300);
/// The last few stderr lines, shared between the drain task and the handle.
type StderrTail = Arc<Mutex<VecDeque<String>>>;
+/// Fit-failure lines the worker printed. Counted rather than taken, so a load
+/// can ask for the lines printed since it started without clearing a line that
+/// a concurrent load on the same worker is still waiting for.
+#[derive(Default)]
+struct FitNotes {
+ count: u64,
+ last: Option<String>,
+}
+
+type FitFailure = Arc<Mutex<FitNotes>>;
+
+/// How many fit-failure lines a worker had printed at some moment; see
+/// [`WorkerHandle::fit_failure_since`].
+#[derive(Debug, Clone, Copy)]
+pub struct FitMark(u64);
+
/// Lines that are kept out of the tail, though still logged. ggml prints one
/// `load_backend: loaded ... from <path>` per backend at start, which says
/// nothing about a crash and would fill the error with local paths.
@@ -519,8 +549,12 @@ pub struct WorkerHandle {
/// not in the webview, so it survives a page reload and always describes
/// the worker that is actually running.
pub devices: Option<Vec<DeviceIdentity>>,
+ /// The preset the worker was started from. Jan regenerates it in place and
+ /// the worker reloads the same path, so it also describes later loads.
+ pub preset_path: PathBuf,
child: Child,
stderr_tail: StderrTail,
+ fit_failure: FitFailure,
/// The task filling `stderr_tail`; it ends when the worker's stderr closes.
stderr_drain: Option<tokio::task::JoinHandle<()>>,
/// Declared after `child` so it is dropped after it: the graceful stop must
@@ -597,6 +631,30 @@ impl WorkerHandle {
self.child.try_wait().ok().flatten()
}
+ /// Taken before a load, so only a fit failure printed during that load is
+ /// blamed for it: a stale one would pin the next, unrelated failure on fit.
+ pub fn fit_mark(&self) -> FitMark {
+ FitMark(self.fit_failure.lock().map(|f| f.count).unwrap_or(0))
+ }
+
+ /// The latest fit-failure line, if one was printed after `mark`.
+ ///
+ /// The line names no model: llama.cpp logs it from inside the load. The
+ /// worker loads one model at a time, but two loads sent at once can each
+ /// see a line printed after both marks, so a model that failed for another
+ /// reason can be reported as not fitting when the other one did not fit.
+ /// Tagging the line would take a marker that llama.cpp's own (asynchronous)
+ /// logger orders against, which it does not offer. Rare in practice: the
+ /// frontend loads one chat model at a time.
+ pub fn fit_failure_since(&self, mark: FitMark) -> Option<String> {
+ let notes = self.fit_failure.lock().ok()?;
+ if notes.count > mark.0 {
+ notes.last.clone()
+ } else {
+ None
+ }
+ }
+
/// None while still running, otherwise how it ended and what it last said.
///
/// Waits up to [`STDERR_DRAIN_WAIT`] for the rest of its stderr first, so
@@ -689,9 +747,11 @@ pub async fn spawn(
// Drained on its own task: a full stderr pipe would otherwise block the
// worker mid-generation, which is a hang with no error message.
let stderr_tail = StderrTail::default();
+ let fit_failure = FitFailure::default();
let mut stderr_drain = None;
if let Some(stderr) = child.stderr.take() {
let tail = stderr_tail.clone();
+ let fit_note = fit_failure.clone();
stderr_drain = Some(tokio::spawn(async move {
let mut lines = BufReader::new(stderr).lines();
let mut reader = FaultReader::default();
@@ -722,6 +782,12 @@ pub async fn spawn(
let Ok(Some(line)) = next else { break };
log::debug!("jan-llama-worker: {line}");
remember_stderr_line(&tail, &line);
+ if is_fit_failure_line(&line.to_lowercase()) {
+ if let Ok(mut notes) = fit_note.lock() {
+ notes.count += 1;
+ notes.last = Some(line.trim().to_string());
+ }
+ }
for (fault, text) in reader.feed(&line) {
report(fault, text);
}
@@ -788,8 +854,10 @@ pub async fn spawn(
models: hs.models,
cuda_toolkit: hs.cuda_toolkit,
devices: hs.devices,
+ preset_path: preset_path.to_path_buf(),
child,
stderr_tail,
+ fit_failure,
stderr_drain,
#[cfg(windows)]
_job: job,
@@ -893,6 +961,19 @@ pub(crate) mod tests {
);
}
+ // fit declining to run (the user pinned the layers) is not a model that is
+ // too big, and must not be reported as one.
+ #[test]
+ fn fit_declining_to_run_is_not_a_fit_failure() {
+ for line in [
+ "common_fit_params: failed to fit params to free device memory: n_gpu_layers already set by user to 99, abort",
+ "common_fit_params: successfully fit params to free device memory",
+ "alloc_tensor_range: failed to allocate cuda0 buffer of size 2491323904",
+ ] {
+ assert!(!is_fit_failure_line(&line.to_lowercase()), "{line:?}");
+ }
+ }
+
#[test]
fn classifies_metal_and_host_out_of_memory_as_oom() {
for line in [
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
index b71c9a82b..249058bb3 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs
@@ -12,6 +12,10 @@ pub enum ErrorCode {
// --- Memory Errors ---
OutOfMemory,
+ /// The load failed although auto-fit owned the layers and the context, so
+ /// no split fits this device's memory. Distinct from `OutOfMemory`:
+ /// lowering the context will not help, because fit already tried that.
+ ModelDoesNotFit,
// --- Engine Process Errors ---
/// The worker process exited on its own: a crash, or something killed it.
@@ -53,6 +57,17 @@ impl LlamacppError {
}
}
+ /// A load that failed with auto-fit already doing all it could: the model
+ /// does not fit this device at any context fit may choose. `details` keeps
+ /// what llama.cpp said, which is the evidence.
+ pub fn model_does_not_fit(details: String) -> Self {
+ Self::new(
+ ErrorCode::ModelDoesNotFit,
+ "The model does not fit on this device.".into(),
+ Some(details),
+ )
+ }
+
/// Classifies engine output from a failed model load. An unrecognized
/// reason is a failed load rather than a crashed process, and `details`
/// keeps llama.cpp's own words so the UI can show them next to the
@@ -273,6 +288,7 @@ mod tests {
(ErrorCode::UnsupportedCpu, "UNSUPPORTED_CPU"),
(ErrorCode::GpuDriverTooOld, "GPU_DRIVER_TOO_OLD"),
(ErrorCode::OutOfMemory, "OUT_OF_MEMORY"),
+ (ErrorCode::ModelDoesNotFit, "MODEL_DOES_NOT_FIT"),
(ErrorCode::EngineStopped, "ENGINE_STOPPED"),
(ErrorCode::EngineUnreachable, "ENGINE_UNREACHABLE"),
(ErrorCode::InvalidArgument, "INVALID_ARGUMENT"),
diff --git a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
index 1dde851b4..3a7b2ab52 100644
--- a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
+++ b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
@@ -302,7 +302,7 @@ describe('useModelProvider - coverage', () => {
}, (migrated: any) => {
expect(migrated.providers[0].models[0].settings.auto_increase_ctx_len).toBeUndefined()
}],
- [12, 'v12 resets legacy 8192 to auto, v16 re-seeds 8192 default', {
+ [12, 'v12 resets legacy 8192 to auto, v16 re-seeds it, v21 clears it again', {
providers: [{
provider: 'llamacpp',
models: [{
@@ -316,9 +316,9 @@ describe('useModelProvider - coverage', () => {
}, (migrated: any) => {
expect(
migrated.providers[0].models[0].settings.ctx_len.controller_props.value
- ).toBe(8192)
+ ).toBe('')
}],
- [16, 'v16 seeds empty ctx_len with 8192 default', {
+ [16, 'v16 seeds empty ctx_len, v21 clears the seed so fit can size it', {
providers: [{
provider: 'llamacpp',
models: [{
@@ -332,7 +332,22 @@ describe('useModelProvider - coverage', () => {
}, (migrated: any) => {
expect(
migrated.providers[0].models[0].settings.ctx_len.controller_props.value
- ).toBe(8192)
+ ).toBe('')
+ }],
+ [20, 'v21 clears the seeded 8192 and keeps a chosen context', {
+ providers: [{
+ provider: 'llamacpp',
+ models: [
+ { id: 'seeded', settings: { ctx_len: { controller_props: { value: 8192 } } }, capabilities: [] },
+ { id: 'chosen', settings: { ctx_len: { controller_props: { value: 32768 } } }, capabilities: [] },
+ ],
+ settings: [],
+ }],
+ deletedModels: [],
+ }, (migrated: any) => {
+ const [seeded, chosen] = migrated.providers[0].models
+ expect(seeded.settings.ctx_len.controller_props.value).toBe('')
+ expect(chosen.settings.ctx_len.controller_props.value).toBe(32768)
}],
[14, 'v14 → v15 strips orphan auto_increase_ctx_len', {
providers: [{
diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.ts
index 6ceb92490..cd78424ad 100644
--- a/web-app/src/hooks/useModelProvider.ts
+++ b/web-app/src/hooks/useModelProvider.ts
@@ -815,9 +815,32 @@ export const useModelProvider = create<ModelProviderState>()(
})
}
+ if (version <= 20 && state?.providers) {
+ // Auto-fit is on by default again (jan-internal#487), and fit leaves
+ // a set context alone, so the 8192 the v16 migration seeded would
+ // keep it from shrinking the context and would shadow the launched
+ // n_ctx in every readout that prefers ctx_len. The seed carries no provenance, so
+ // 8192 is taken to be it, as v12 did; a user who typed exactly 8192
+ // loses it here and in model.yml (the extension's
+ // migrateSeededCtxSize), which with fit off changes nothing.
+ state.providers.forEach((provider) => {
+ if (provider.provider !== 'llamacpp' || !provider.models) return
+ provider.models.forEach((model) => {
+ const controllerProps = (
+ model.settings?.ctx_len as
+ | { controller_props?: { value?: unknown } }
+ | undefined
+ )?.controller_props
+ if (controllerProps && Number(controllerProps.value) === 8192) {
+ controllerProps.value = ''
+ }
+ })
+ })
+ }
+
return state
},
- version: 20,
+ version: 21,
}
)
)
diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.ts
index c7cb538cb..a9e14d6ec 100644
--- a/web-app/src/lib/__tests__/engineError.test.ts
+++ b/web-app/src/lib/__tests__/engineError.test.ts
@@ -125,6 +125,17 @@ describe('describeEngineError', () => {
expect(text).toContain('cudaMalloc failed: out of memory')
})
+ // jan-internal#487: fit finding no plan is its own advice, not the generic
+ // OOM one that suggests lowering a context fit already lowered.
+ it('describes a model fit could not place as not fitting this device', () => {
+ describeEngineError({
+ code: 'MODEL_DOES_NOT_FIT',
+ details: 'common_fit_params: failed to allocate a plan',
+ })
+
+ expect(mockT).toHaveBeenCalledWith('model-errors:engine.MODEL_DOES_NOT_FIT')
+ })
+
it('collapses whitespace and clips a log-sized detail', () => {
const text = describeEngineError({
code: 'MODEL_LOAD_FAILED',
diff --git a/web-app/src/lib/coworkModelControls.ts b/web-app/src/lib/coworkModelControls.ts
index 06a1ca6e4..eb9a0823c 100644
--- a/web-app/src/lib/coworkModelControls.ts
+++ b/web-app/src/lib/coworkModelControls.ts
@@ -2,6 +2,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useCoworkRun } from '@/hooks/useCoworkRun'
import type { ModelsService } from '@/services/models/types'
+import { getLocalPropsExtension, readCtxLen } from '@/lib/llamacppRouterProps'
export function coworkLocalModel(
provider: ModelProvider | undefined,
@@ -60,8 +61,15 @@ export async function increaseCoworkContext(
let context = coworkModelContext(provider, modelId)
if (!context) {
const setting = coworkLocalModel(provider, modelId)?.settings?.ctx_len
- const value = Number(setting?.controller_props?.value)
- if (setting && Number.isInteger(value) && value > 0) {
+ // An empty ctx_len is left to fit; grow from the window it launched with.
+ const value =
+ readCtxLen(setting?.controller_props?.value) ??
+ readCtxLen(
+ (await getLocalPropsExtension(providerName)
+ ?.getModelProps?.(modelId)
+ .catch(() => undefined))?.nCtx
+ )
+ if (setting && value !== undefined) {
const max = await models.getModelContextLimit(modelId, providerName)
if (max !== undefined && Number.isInteger(max) && max > 0)
context = { value, max, next: nextCoworkContextSize(value, max) }
diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.ts
index 7188b7d15..fb3255e76 100644
--- a/web-app/src/lib/engineError.ts
+++ b/web-app/src/lib/engineError.ts
@@ -12,6 +12,7 @@ export const ENGINE_ERROR_CODES = [
'MISSING_SHARED_LIBRARY',
'GPU_DRIVER_TOO_OLD',
'OUT_OF_MEMORY',
+ 'MODEL_DOES_NOT_FIT',
'ENGINE_STOPPED',
'ENGINE_UNREACHABLE',
'UNSUPPORTED_CPU',
diff --git a/web-app/src/lib/predefined.ts b/web-app/src/lib/predefined.ts
index 274b56896..1926989b6 100644
--- a/web-app/src/lib/predefined.ts
+++ b/web-app/src/lib/predefined.ts
@@ -1,3 +1,7 @@
+/// The fixed context MLX models are seeded with. MLX has no auto-fit, so the
+/// empty llamacpp default below would leave the window to the mlx server.
+export const MLX_DEFAULT_CTX_LEN = 8192
+
export const modelSettings = {
ctx_len: {
key: 'ctx_len',
@@ -6,8 +10,12 @@ export const modelSettings = {
'Size of the prompt context. Leave empty to auto-fit when --fit is on.',
controller_type: 'input',
controller_props: {
- value: 8192,
- placeholder: '8192',
+ // Empty, not 8192: an explicit value pins n_ctx and upstream's fit then
+ // leaves the context alone. With fit off, preset.ts's [*] ctx-size =
+ // 8192 still applies, so the effective default is unchanged there.
+ // MLX overrides this with MLX_DEFAULT_CTX_LEN.
+ value: '',
+ placeholder: 'auto',
type: 'number',
},
},
diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.ts
index 938de237e..7a8a2b2a9 100644
--- a/web-app/src/locales/__tests__/localeKeys.test.ts
+++ b/web-app/src/locales/__tests__/localeKeys.test.ts
@@ -66,6 +66,7 @@ const DYNAMIC_KEYS: Record<string, string[]> = {
'engine.MISSING_SHARED_LIBRARY',
'engine.GPU_DRIVER_TOO_OLD',
'engine.OUT_OF_MEMORY',
+ 'engine.MODEL_DOES_NOT_FIT',
'engine.ENGINE_STOPPED',
'engine.ENGINE_UNREACHABLE',
'engine.UNSUPPORTED_CPU',
diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.json
index 176481152..b4ded7893 100644
--- a/web-app/src/locales/en/model-errors.json
+++ b/web-app/src/locales/en/model-errors.json
@@ -16,6 +16,7 @@
"MISSING_SHARED_LIBRARY": "A library the engine needs is missing, so it cannot start.",
"GPU_DRIVER_TOO_OLD": "Your GPU driver is too old for this engine. Updating the driver, or switching to the CPU engine in Settings, will fix this.",
"OUT_OF_MEMORY": "There is not enough memory to run this model. A smaller model or a smaller context size usually helps.",
+ "MODEL_DOES_NOT_FIT": "This model does not fit on this device, even with the smallest context Fit is allowed to use. A smaller model or a smaller quantization will load.",
"ENGINE_STOPPED": "The llama.cpp engine stopped unexpectedly. Sending the message again starts it again; if it keeps stopping, security software or the GPU driver may be the cause.",
"ENGINE_UNREACHABLE": "The llama.cpp engine is running, but Jan cannot connect to it on this computer (127.0.0.1). A VPN, proxy or security software may be blocking local connections.",
"UNSUPPORTED_CPU": "Local models are not supported on this computer's processor. Jan's local engine is built for Apple Silicon Macs (M1 or newer), so it cannot start on an Intel Mac. Cloud and custom providers still work.",
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index bf18a4d40..59b0ddde1 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -2044,8 +2044,12 @@ function ThreadDetail() {
const model = provider.models[modelIndex]
// Increase context length in steps: <8192 -> 8192 -> 32768 -> x1.5
+ // An empty ctx_len is left to fit, so the window to grow from is the one
+ // the model launched with, not a guess that could be below it.
const currentCtxLen =
- (model.settings?.ctx_len?.controller_props?.value as number) ?? 8192
+ readCtxLen(model.settings?.ctx_len?.controller_props?.value) ??
+ launchedCtxLens.get(threadId) ??
+ 8192
const maxCtxLen =
(model.settings?.ctx_len?.controller_props?.max as number) || 131072
diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.ts
index 9ee0b32f2..e09eadfe6 100644
--- a/web-app/src/services/providers/__tests__/tauri.test.ts
+++ b/web-app/src/services/providers/__tests__/tauri.test.ts
@@ -43,6 +43,7 @@ vi.mock('@/types/models', () => ({
}))
vi.mock('@/lib/predefined', () => ({
+ MLX_DEFAULT_CTX_LEN: 8192,
modelSettings: {
temperature: {
key: 'temperature',
@@ -121,6 +122,29 @@ describe('TauriProvidersService', () => {
expect(llama!.models).toHaveLength(1)
})
+ // MLX has no auto-fit, so an empty context would drop --ctx-size and leave
+ // the window to the mlx server; it keeps the old fixed default.
+ it('seeds an empty ctx_len for llamacpp only, MLX keeps 8192', async () => {
+ const engine = () => ({
+ list: vi.fn().mockResolvedValue([{ id: 'm', name: 'M' }]),
+ getSettings: vi.fn().mockResolvedValue([]),
+ isToolSupported: vi.fn().mockResolvedValue(false),
+ })
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([
+ ['llamacpp', engine()],
+ ['mlx', engine()],
+ ]),
+ } as any)
+
+ const result = await svc.getProviders()
+ const ctx = (name: string) =>
+ result.find((p: any) => p.provider === name)!.models[0].settings!
+ .ctx_len.controller_props.value
+ expect(ctx('llamacpp')).toBe(4096)
+ expect(ctx('mlx')).toBe(8192)
+ })
+
it('adds TOOLS capability when isToolSupported returns true', async () => {
const mockEngine = {
list: vi.fn().mockResolvedValue([{ id: 'm1', name: 'M1', description: '' }]),
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index ae8d2d798..d6ecd9f02 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -6,7 +6,7 @@ import { predefinedProviders } from '@/constants/providers'
import { providerModels } from '@/constants/models'
import { EngineManager, SettingComponentProps } from '@janhq/core'
import { ModelCapabilities } from '@/types/models'
-import { modelSettings } from '@/lib/predefined'
+import { MLX_DEFAULT_CTX_LEN, modelSettings } from '@/lib/predefined'
import { ExtensionManager } from '@/lib/extension'
import { fetch as fetchTauri } from '@tauri-apps/plugin-http'
import { invoke } from '@tauri-apps/api/core'
@@ -117,6 +117,9 @@ export class TauriProvidersService extends DefaultProvidersService {
...setting,
controller_props: {
...setting.controller_props,
+ ...(setting.key === 'ctx_len' && providerName === 'mlx'
+ ? { value: MLX_DEFAULT_CTX_LEN }
+ : {}),
},
}
return acc