Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): await model setting application and report failures
thinhlpg237a0d49c9bc
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex ed0681be0..e7c797aab 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -739,7 +739,10 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (nextValue !== prevValue) {changed.push({ key: s.key, value: nextValue })}- ;(s.controllerProps as { value?: unknown }).value = nextValue+ return {+ ...s,+ controllerProps: { ...s.controllerProps, value: nextValue },+ } as SettingComponentProps}return s})@@ -754,9 +757,30 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn arr})()await writeSettingsFile(updated)+ const previousConfig = { ...this.config }+ const previousTimeout = this.timeout+ const previousEnv = this.llamacpp_envfor (const { key, value } of changed) {this.onSettingUpdate(key, value)}+ if (this.presetRefreshTimer) {+ clearTimeout(this.presetRefreshTimer)+ this.presetRefreshTimer = null+ // Startup migrations are included in the initial preset. Once loaded,+ // an awaited settings save must include engine application, not merely+ // schedule it after the caller has already sent its next request.+ if (this.backgroundInit) {+ try {+ await this.refreshEnginePreset()+ } catch (error) {+ this.config = previousConfig+ this.timeout = previousTimeout+ this.llamacpp_env = previousEnv+ await writeSettingsFile(current)+ throw error+ }+ }+ }}override async registerSettings(@@ -2658,15 +2682,13 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}/**- * 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.+ * Persist a per-model setting into `model.yml` and apply the engine preset+ * before resolving. A failed application restores the saved configuration+ * and rejects so the caller can report the error.** 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).+ * Keys not in the mapping are silently ignored because they are Jan-side+ * concerns or are not emitted by `preset.ts`.*/async updateModelSettings(modelId: string,@@ -2684,6 +2706,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst cfg = (await invoke<ModelConfig>('read_yaml', {path: configPath,})) as ModelConfig & Record<string, unknown>+ const previousConfig = { ...cfg }let touched = falsefor (const [sidebarKey, value] of Object.entries(patch)) {@@ -2708,10 +2731,11 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngtry {await this.refreshEnginePreset()} catch (e) {- logger.warn(- `Failed to restart router after model settings update for ${modelId}`,- e- )+ await invoke<void>('write_yaml', {+ data: previousConfig,+ savePath: configPath,+ })+ throw e}}diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex ba399debe..49325cfb5 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -1,5 +1,14 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'+import { fs, getJanDataFolderPath, joinPath } from '@janhq/core'+import { invoke } from '@tauri-apps/api/core'+import {+ reloadEngineModels,+ startEngine,+} from '@janhq/tauri-plugin-llamacpp-api'+import type { ReloadReport } from '@janhq/tauri-plugin-llamacpp-api'+import { generatePreset } from '../preset'+import * as store from '../settings-store'import { getBackendSetting, setBackendSetting } from '../backend-settings'@@ -632,6 +641,102 @@ describe('llamacpp_extension', () => {})})+ describe('settings application', () => {+ const fitSetting = {+ key: 'fit',+ title: 'Fit',+ description: '',+ controllerType: 'checkbox' as const,+ controllerProps: { value: false },+ }+ let savedSettings = [structuredClone(fitSetting)]++ beforeEach(() => {+ vi.useFakeTimers()+ savedSettings = [structuredClone(fitSetting)]+ vi.spyOn(store, 'readSettingsFile').mockImplementation(async () =>+ structuredClone(savedSettings)+ )+ vi.spyOn(store, 'writeSettingsFile').mockImplementation(async (settings) => {+ savedSettings = settings.map((setting) => ({+ ...fitSetting,+ controllerProps: { value: setting.controllerProps.value === true },+ }))+ })+ vi.mocked(generatePreset).mockResolvedValue({+ path: '/jan/llamacpp/router.preset.ini',+ embeddingCount: 0,+ })+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')+ vi.mocked(joinPath).mockImplementation(async (parts) => parts.join('/'))+ extension['config'] = { ...extension['config'], fit: false }+ extension['backgroundInit'] = Promise.resolve()+ })++ afterEach(() => {+ vi.clearAllTimers()+ vi.useRealTimers()+ })++ it('keeps the save pending until the engine has applied fit', async () => {+ const reload = Promise.withResolvers<ReloadReport>()+ vi.mocked(reloadEngineModels).mockReturnValueOnce(reload.promise)+ let completed = false+ const save = extension.updateSettings([{+ ...fitSetting,+ controllerProps: { value: true },+ }]).then(() => { completed = true })++ await vi.waitFor(() => expect(reloadEngineModels).toHaveBeenCalled())+ expect(completed).toBe(false)+ reload.resolve({ added: [], changed: ['model'], removed: [], kept: [], models_max: 1 })+ await save+ expect((await extension.getSettings())[0].controllerProps.value).toBe(true)+ })++ it('rejects a failed fit application and restores the saved value', async () => {+ vi.mocked(reloadEngineModels).mockRejectedValueOnce(new Error('reload failed'))+ vi.mocked(startEngine).mockRejectedValueOnce(new Error('engine unavailable'))++ await expect(extension.updateSettings([{+ ...fitSetting,+ controllerProps: { value: true },+ }])).rejects.toThrow('engine unavailable')+ expect((await extension.getSettings())[0].controllerProps.value).toBe(false)+ expect(extension['config'].fit).toBe(false)+ })++ it('leaves startup migrations to the initial engine load', async () => {+ extension['backgroundInit'] = undefined+ await extension.updateSettings([{+ ...fitSetting,+ controllerProps: { value: true },+ }])+ await vi.advanceTimersByTimeAsync(600)++ expect(reloadEngineModels).not.toHaveBeenCalled()+ expect(startEngine).not.toHaveBeenCalled()+ expect((await extension.getSettings())[0].controllerProps.value).toBe(true)+ })++ it('rejects a failed context application and restores model.yml', async () => {+ let savedModel: Record<string, unknown> = { ctx_size: 4096 }+ vi.mocked(fs.existsSync).mockResolvedValue(true)+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === 'read_yaml') return structuredClone(savedModel)+ if (command === 'write_yaml' && args && 'data' in args) {+ savedModel = structuredClone(args.data as Record<string, unknown>)+ }+ })+ vi.mocked(reloadEngineModels).mockRejectedValueOnce(new Error('reload failed'))+ vi.mocked(startEngine).mockRejectedValueOnce(new Error('engine unavailable'))++ await expect(extension.updateModelSettings('model', { ctx_len: 8192 }))+ .rejects.toThrow('engine unavailable')+ expect(savedModel.ctx_size).toBe(4096)+ })+ })+})// The worker is a separate process precisely so a GGML_ASSERT or an OOM kill