Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(llamacpp): split version/backend selectors and overhaul settings UX
Akarshan5b99a92f2669
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.jsonindex eb5aa7349..418ee17ad 100644--- a/extensions/llamacpp-extension/settings.json+++ b/extensions/llamacpp-extension/settings.json@@ -1,8 +1,19 @@[{- "key": "version_backend",- "title": "Version & Backend",- "description": "Version and Backend for llama.cpp",+ "key": "llamacpp_version",+ "title": "Version",+ "description": "llama.cpp release version",+ "controllerType": "dropdown",+ "controllerProps": {+ "value": "none",+ "options": [],+ "recommended": ""+ }+ },+ {+ "key": "llamacpp_backend",+ "title": "Backend",+ "description": "Hardware backend for llama.cpp (CUDA, Vulkan, CPU, etc.)","controllerType": "dropdown","controllerProps": {"value": "none",@@ -22,10 +33,17 @@"textAlign": "right"}},+ {+ "key": "check_for_updates",+ "title": "Check for updates",+ "description": "Fetch the remote llama.cpp release list. Required for the version dropdown to show releases beyond what's installed locally, and for update notifications.",+ "controllerType": "checkbox",+ "controllerProps": { "value": true }+ },{"key": "auto_update_engine","title": "Auto update engine",- "description": "Automatically update llamacpp engine to latest version",+ "description": "Automatically download and switch to the latest llamacpp engine when available. Requires \"Check for updates\" to be on.","controllerType": "checkbox","controllerProps": { "value": true }},diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex d77240188..c741ebc7e 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -32,7 +32,12 @@ export async function getLocalInstalledBackends(): Promise<// <Jan's data folder>/llamacpp/backends/<backend_version>/<backend_type>// what should be available to the user for selection?-export async function listSupportedBackends(): Promise<BackendVersion[]> {+/**+ * Hardware-supported backends published by upstream. Excludes+ * locally-installed-only entries, so the "recommended backend" calculation+ * isn't biased by user side-loads.+ */+export async function fetchRemoteBackends(): Promise<BackendVersion[]> {const sysInfo = await getSystemInfo()const rawFeatures = await getSupportedFeaturesFromRust(sysInfo.os_type,@@ -40,18 +45,14 @@ export async function listSupportedBackends(): Promise<BackendVersion[]> {sysInfo.gpus)const features = normalizeFeatures(rawFeatures)-- // Get supported backend names from Rustconst supportedBackends = await determineSupportedBackends(sysInfo.os_type,sysInfo.cpu.arch,features)- // Get remote backends via Rust (handles GitHub + CDN fallback)- let remoteBackendVersions: BackendVersion[] = []try {- remoteBackendVersions = await invoke(+ return await invoke<BackendVersion[]>('plugin:llamacpp|fetch_remote_supported_backends',{ supportedBackends, proxy: getProxyConfig() })@@ -59,12 +60,15 @@ export async function listSupportedBackends(): Promise<BackendVersion[]> {console.debug(`Not able to get remote backends, Jan might be offline or network problem: ${String(e)}`)+ return []}+}- // Get locally installed versions+export async function listSupportedBackends(+ checkRemote: boolean = true+): Promise<BackendVersion[]> {+ const remoteBackendVersions = checkRemote ? await fetchRemoteBackends() : []const localBackendVersions = await getLocalInstalledBackends()-- // Merge & sort via Rustreturn listSupportedBackendsFromRust(remoteBackendVersions, localBackendVersions)}diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 17c9fd8ef..b8fc29e9b 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -22,12 +22,19 @@ import {AppEvent,DownloadEvent,chatCompletionRequestMessage,+ SettingComponentProps,} from '@janhq/core'+import {+ readSettingsFile,+ writeSettingsFile,+ settingsFileExists,+} from './settings-store'import { error, info, warn } from '@tauri-apps/plugin-log'import { listen } from '@tauri-apps/api/event'import {listSupportedBackends,+ fetchRemoteBackends,downloadBackend,isBackendInstalled,verifyBackendInstallation,@@ -324,6 +331,8 @@ export default class llamacpp_extension extends AIEngine {override async onLoad(): Promise<void> {super.onLoad() // Calls registerEngine() from AIEngine+ await this.migrateLocalStorageToFile()+let settings = structuredClone(SETTINGS) // Clone to modify settings definition before registrationif (!IS_MAC) {@@ -331,8 +340,34 @@ export default class llamacpp_extension extends AIEngine {if (fitItem) fitItem.controllerProps.value = true}- // This makes the settings (including the backend options and initial value) available to the Jan UI.- this.registerSettings(settings)+ // Migration: legacy `version_backend` (single composite string) → split+ // into `llamacpp_version` + `llamacpp_backend`. Read from localStorage+ // before registerSettings overwrites the persisted set.+ try {+ const prior = await this.getSettings()+ const legacy = prior.find((s) => s.key === 'version_backend')+ const legacyValue = legacy?.controllerProps?.value+ if (+ typeof legacyValue === 'string' &&+ legacyValue.includes('/') &&+ legacyValue !== 'none'+ ) {+ const [v, b] = legacyValue.split('/')+ if (v && b) {+ const vSetting = settings.find((s) => s.key === 'llamacpp_version')+ const bSetting = settings.find((s) => s.key === 'llamacpp_backend')+ if (vSetting) vSetting.controllerProps.value = v+ if (bSetting) bSetting.controllerProps.value = b+ logger.info(+ `Migrated legacy version_backend '${legacyValue}' → version='${v}', backend='${b}'`+ )+ }+ }+ } catch (e) {+ logger.warn('version_backend migration check failed (ignored):', e)+ }++ await this.registerSettings(settings)let loadedConfig: any = {}for (const item of settings) {@@ -344,6 +379,7 @@ export default class llamacpp_extension extends AIEngine {)}this.config = loadedConfig as LlamacppConfig+ this.recomposeVersionBackend()// Migration v2: disable fit by defaultawait this.migrateFitDefault()@@ -385,6 +421,109 @@ export default class llamacpp_extension extends AIEngine {}}+ override async getSettings(): Promise<SettingComponentProps[]> {+ return readSettingsFile()+ }++ override async updateSettings(+ componentProps: Partial<SettingComponentProps>[]+ ): Promise<void> {+ const current = await readSettingsFile()+ const updated = current.length+ ? current.map((s) => {+ const patch = componentProps.find((p) => p.key === s.key)+ if (patch?.controllerProps) {+ ;(s.controllerProps as { value?: unknown }).value = (+ patch.controllerProps as { value?: unknown }+ ).value+ }+ return s+ })+ : (componentProps as SettingComponentProps[])+ await writeSettingsFile(updated)+ }++ override async registerSettings(+ settings: SettingComponentProps[]+ ): Promise<void> {+ settings.forEach((s) => {+ s.extensionName = this.name+ })+ const old = await readSettingsFile()+ if (old.length) {+ settings.forEach((s) => {+ const prev = old.find((o) => o.key === s.key)+ if (!prev) return+ const cp = s.controllerProps as Record<string, unknown>+ const pcp = prev.controllerProps as Record<string, unknown>+ if (pcp.value !== undefined) cp.value = pcp.value+ if ('options' in cp) {+ const newOptions = (cp.options as unknown[]) ?? []+ if (newOptions.length === 0 && Array.isArray(pcp.options)) {+ cp.options = pcp.options+ }+ const opts = (cp.options as { value: unknown }[]) ?? []+ if (opts.length && !opts.some((o) => o.value === cp.value)) {+ cp.value = opts[0]?.value+ }+ }+ })+ }+ await writeSettingsFile(settings)+ }++ private async migrateLocalStorageToFile(): Promise<void> {+ if (await settingsFileExists()) return+ if (!this.name) return+ let raw: string | null = null+ try {+ raw = localStorage.getItem(this.name)+ } catch {+ raw = null+ }+ if (!raw) return+ try {+ const parsed = JSON.parse(raw)+ if (Array.isArray(parsed)) {+ await writeSettingsFile(parsed as SettingComponentProps[])+ logger.info(+ `Migrated llamacpp settings from localStorage → file (${parsed.length} entries)`+ )+ }+ } catch (e) {+ logger.warn('Failed to migrate localStorage settings to file:', e)+ return+ }+ try {+ localStorage.removeItem(this.name)+ } catch (e) {+ logger.warn('Failed to clear migrated localStorage entry:', e)+ }+ }++ private async persistRecommended(+ key: string,+ value: string+ ): Promise<void> {+ const settings = await readSettingsFile()+ const entry = settings.find((s) => s.key === key)+ if (!entry) return+ const cp = entry.controllerProps as { recommended?: string }+ if (cp.recommended === value) return+ cp.recommended = value+ await writeSettingsFile(settings)+ }++ private recomposeVersionBackend(): void {+ const v = this.config?.llamacpp_version+ const b = this.config?.llamacpp_backend+ if (v && b && v !== 'none' && b !== 'none') {+ this.config.version_backend = `${v}/${b}`+ } else if (!this.config.version_backend) {+ this.config.version_backend = ''+ }+ }+private async startRouter(): Promise<void> {const versionBackend = this.config?.version_backendif (@@ -757,7 +896,9 @@ export default class llamacpp_extension extends AIEngine {let version_backends: { version: string; backend: string }[] = []try {- version_backends = await listSupportedBackends()+ version_backends = await listSupportedBackends(+ this.config.check_for_updates !== false+ )if (version_backends.length === 0) {throw new Error('No supported backend binaries found for this system. Backend selection and auto-update will be unavailable.'@@ -777,9 +918,18 @@ export default class llamacpp_extension extends AIEngine {const storedBackendType = this.getStoredBackendType()let bestAvailableBackendString = ''- // Calculate the "best" backend first, as it's used for fallback and defaults+ // "Recommended" is computed against upstream releases only — a+ // user-side-loaded backend (Install from File) must not bias the+ // suggestion. If we have no remote data (check_for_updates off or+ // offline), there is no honest recommendation to surface.+ const remoteOnly =+ this.config.check_for_updates !== false+ ? await fetchRemoteBackends()+ : []bestAvailableBackendString =- await this.determineBestBackend(version_backends)+ remoteOnly.length > 0+ ? await this.determineBestBackend(remoteOnly)+ : ''if (storedBackendType) {// Delegate migration check to Rust@@ -821,84 +971,99 @@ export default class llamacpp_extension extends AIEngine {}let settings = structuredClone(SETTINGS)- const backendSettingIndex = settings.findIndex(- (item) => item.key === 'version_backend'- )-- let originalDefaultBackendValue = ''- if (backendSettingIndex !== -1) {- const backendSetting = settings[backendSettingIndex]- originalDefaultBackendValue = backendSetting.controllerProps- .value as string-- backendSetting.controllerProps.options = version_backends.map((b) => {- const key = `${b.version}/${b.backend}`- return { value: key, name: key }- })-- // Set the recommended backend based on bestAvailableBackendString- if (bestAvailableBackendString) {- backendSetting.controllerProps.recommended =- bestAvailableBackendString- }-- const savedBackendSetting = await this.getSetting<string>(- 'version_backend',- originalDefaultBackendValue+ const versionSetting = settings.find((s) => s.key === 'llamacpp_version')+ const backendSetting = settings.find((s) => s.key === 'llamacpp_backend')+ if (!versionSetting || !backendSetting) {+ throw new Error(+ 'Critical settings "llamacpp_version" / "llamacpp_backend" not found.')+ }++ // Read prior persisted values (may have been pre-populated by the+ // legacy-migration pass in onLoad, or carry user-edited values from a+ // prior session).+ const priorPersisted = await this.getSettings()+ const priorVersion = String(+ priorPersisted.find((s) => s.key === 'llamacpp_version')?.controllerProps+ .value ?? ''+ )+ const priorBackend = String(+ priorPersisted.find((s) => s.key === 'llamacpp_backend')?.controllerProps+ .value ?? ''+ )- // Determine initial UI default based on priority:- // 1. Saved setting (if valid and not original default)- // 2. Best available for stored backend type or automatic best- // 3. Original default- let initialUiDefault = originalDefaultBackendValue+ const allVersions = Array.from(+ new Set(version_backends.map((b) => b.version))+ )+ versionSetting.controllerProps.options = allVersions.map((v) => ({+ value: v,+ name: v,+ }))+ const allBackends = Array.from(+ new Set(version_backends.map((b) => b.backend))+ )+ backendSetting.controllerProps.options = allBackends.map((b) => ({+ value: b,+ name: b,+ }))++ const [bestVersion, bestBackend] =+ bestAvailableBackendString.split('/')+ if (bestVersion) versionSetting.controllerProps.recommended = bestVersion+ if (bestBackend) backendSetting.controllerProps.recommended = bestBackend++ // Decide initial UI values. Priority: valid prior selection → best-available.+ let initialVersion = bestVersion || ''+ let initialBackend = bestBackend || ''+ if (+ priorVersion &&+ priorBackend &&+ priorVersion !== 'none' &&+ priorBackend !== 'none'+ ) {+ const normalizedBackend = await mapOldBackendToNew(priorBackend)+ const composed = `${priorVersion}/${normalizedBackend}`if (- savedBackendSetting &&- savedBackendSetting !== originalDefaultBackendValue+ version_backends.some(+ (e) => `${e.version}/${e.backend}` === composed+ )) {- const [savedVersion, savedBackend] = savedBackendSetting.split('/')- if (savedVersion && savedBackend) {- // Map saved backend to new format if needed- const normalizedBackend = await mapOldBackendToNew(savedBackend)- initialUiDefault = `${savedVersion}/${normalizedBackend}`-- // Store the backend type from the saved setting only if different- const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== normalizedBackend) {- this.setStoredBackendType(normalizedBackend)- logger.info(- `Stored backend type preference from saved setting: ${normalizedBackend}`- )- }- }- } else if (bestAvailableBackendString) {- initialUiDefault = bestAvailableBackendString- // Store the backend type from the best available only if different- const [, backendType] = bestAvailableBackendString.split('/')- if (backendType) {- const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== backendType) {- this.setStoredBackendType(backendType)- logger.info(- `Stored backend type preference from best available: ${backendType}`- )- }+ initialVersion = priorVersion+ initialBackend = normalizedBackend+ const currentStoredBackend = this.getStoredBackendType()+ if (currentStoredBackend !== normalizedBackend) {+ this.setStoredBackendType(normalizedBackend)+ logger.info(+ `Stored backend type preference from saved setting: ${normalizedBackend}`+ )}}-- backendSetting.controllerProps.value = initialUiDefault- logger.info(- `Initial UI default for version_backend set to: ${initialUiDefault}`- )- } else {- logger.error(- 'Critical setting "version_backend" definition not found in SETTINGS.'- )- throw new Error('Critical setting "version_backend" not found.')+ } else if (bestBackend) {+ const currentStoredBackend = this.getStoredBackendType()+ if (currentStoredBackend !== bestBackend) {+ this.setStoredBackendType(bestBackend)+ logger.info(+ `Stored backend type preference from best available: ${bestBackend}`+ )+ }}- this.registerSettings(settings)+ versionSetting.controllerProps.value = initialVersion+ backendSetting.controllerProps.value = initialBackend+ logger.info(+ `Initial UI defaults: llamacpp_version='${initialVersion}', llamacpp_backend='${initialBackend}'`+ )++ // Must await — registerSettings is async; without await, the+ // persistRecommended writes below race with its merge+write and lose.+ await this.registerSettings(settings)++ // core's registerSettings preserves the previous `recommended` over the+ // new one (see extension.ts:142-148). Force-write afterward so a stale+ // recommendation from a prior session can't outlive a fresh compute.+ await this.persistRecommended('llamacpp_version', bestVersion || '')+ await this.persistRecommended('llamacpp_backend', bestBackend || '')let effectiveBackendString = this.config.version_backendlet backendWasDownloaded = false@@ -921,29 +1086,32 @@ export default class llamacpp_extension extends AIEngine {`Fresh installation or invalid backend detected, using: ${effectiveBackendString}`)- // Update the config immediately- this.config.version_backend = effectiveBackendString+ const [newV, newB] = effectiveBackendString.split('/')+ this.config.llamacpp_version = newV+ this.config.llamacpp_backend = newB+ this.recomposeVersionBackend()- // Update the settings to reflect the change in UIconst updatedSettings = await this.getSettings()await this.updateSettings(updatedSettings.map((item) => {- if (item.key === 'version_backend') {- item.controllerProps.value = effectiveBackendString+ if (item.key === 'llamacpp_version') {+ item.controllerProps.value = newV+ } else if (item.key === 'llamacpp_backend') {+ item.controllerProps.value = newB}return item}))logger.info(`Updated UI settings to show: ${effectiveBackendString}`)- // Emit for updating feif (events && typeof events.emit === 'function') {- logger.info(- `Emitting settingsChanged event for version_backend with value: ${effectiveBackendString}`- )events.emit('settingsChanged', {- key: 'version_backend',- value: effectiveBackendString,+ key: 'llamacpp_version',+ value: newV,+ })+ events.emit('settingsChanged', {+ key: 'llamacpp_backend',+ value: newB,})}}@@ -964,7 +1132,7 @@ export default class llamacpp_extension extends AIEngine {}}- if (this.config.auto_update_engine) {+ if (this.config.auto_update_engine && this.config.check_for_updates) {const updateResult = await this.handleAutoUpdate(bestAvailableBackendString)@@ -1009,7 +1177,9 @@ export default class llamacpp_extension extends AIEngine {async refreshBackendOptions(): Promise<void> {let version_backends: { version: string; backend: string }[] = []try {- version_backends = await listSupportedBackends()+ version_backends = await listSupportedBackends(+ this.config.check_for_updates !== false+ )} catch (e) {logger.error(`refreshBackendOptions: failed to list supported backends: ${String(e)}`@@ -1023,49 +1193,59 @@ export default class llamacpp_extension extends AIEngine {version_backends.sort((a, b) => b.version.localeCompare(a.version))const settings = await this.getSettings()- const backendSetting = settings.find(- (item) => item.key === 'version_backend'- )- if (!backendSetting) {+ const versionSetting = settings.find((s) => s.key === 'llamacpp_version')+ const backendSetting = settings.find((s) => s.key === 'llamacpp_backend')+ if (!versionSetting || !backendSetting) {logger.error(- 'refreshBackendOptions: version_backend setting not found in persisted settings'+ 'refreshBackendOptions: llamacpp_version/llamacpp_backend not found in persisted settings')return}- const newOptions = version_backends.map((b) => {- const key = `${b.version}/${b.backend}`- return { value: key, name: key }- })-- backendSetting.controllerProps.options = newOptions-- // Preserve current selection if still present; otherwise fall back to- // the best available so the UI stays consistent.- const currentValue = backendSetting.controllerProps.value as- | string- | undefined- const stillPresent =- typeof currentValue === 'string' &&- newOptions.some((o) => o.value === currentValue)- if (!stillPresent) {+ const allVersions = Array.from(+ new Set(version_backends.map((b) => b.version))+ )+ const allBackends = Array.from(+ new Set(version_backends.map((b) => b.backend))+ )+ versionSetting.controllerProps.options = allVersions.map((v) => ({+ value: v,+ name: v,+ }))+ backendSetting.controllerProps.options = allBackends.map((b) => ({+ value: b,+ name: b,+ }))++ const currentV = String(versionSetting.controllerProps.value ?? '')+ const currentB = String(backendSetting.controllerProps.value ?? '')+ const composedStillPresent =+ currentV &&+ currentB &&+ version_backends.some(+ (e) => e.version === currentV && e.backend === currentB+ )+ if (!composedStillPresent) {const best = await this.determineBestBackend(version_backends)- if (best) {- backendSetting.controllerProps.value = best- this.config.version_backend = best+ const [bv, bb] = best.split('/')+ if (bv && bb) {+ versionSetting.controllerProps.value = bv+ backendSetting.controllerProps.value = bb+ this.config.llamacpp_version = bv+ this.config.llamacpp_backend = bb+ this.recomposeVersionBackend()}}- // registerSettings overwrites the persisted settings (including the- // new options array). updateSettings only copies `value`, which would- // silently drop our options change.await this.registerSettings(settings)- // Tell the rest of the app (GlobalEventHandler) to refetch providers- // so the dropdown re-renders with the new options.if (events && typeof events.emit === 'function') {events.emit('settingsChanged', {- key: 'version_backend',+ key: 'llamacpp_version',+ value: versionSetting.controllerProps.value,+ })+ events.emit('settingsChanged', {+ key: 'llamacpp_backend',value: backendSetting.controllerProps.value,})}@@ -1156,18 +1336,18 @@ export default class llamacpp_extension extends AIEngine {// Persist settings and stored preference before mutating in-memory config,// so that if any of these steps fail, config remains consistent.- // Update settings first — if this fails, we haven't mutated any state yetconst settings = await this.getSettings()await this.updateSettings(settings.map((item) => {- if (item.key === 'version_backend') {- item.controllerProps.value = targetBackendString+ if (item.key === 'llamacpp_version') {+ item.controllerProps.value = version+ } else if (item.key === 'llamacpp_backend') {+ item.controllerProps.value = backend}return item}))- // Store the backend type preference only if it changedif (currentStoredBackend !== effectiveBackendType) {this.setStoredBackendType(effectiveBackendType)logger.info(@@ -1175,20 +1355,21 @@ export default class llamacpp_extension extends AIEngine {)}- // All critical side effects succeeded — now commit to in-memory config- this.config.version_backend = targetBackendString+ this.config.llamacpp_version = version+ this.config.llamacpp_backend = backend+ this.recomposeVersionBackend()this.config.device = ''logger.info(`Successfully updated to backend: ${targetBackendString}`)- // Emit for updating frontendif (events && typeof events.emit === 'function') {- logger.info(- `Emitting settingsChanged event for version_backend with value: ${targetBackendString}`- )events.emit('settingsChanged', {- key: 'version_backend',- value: targetBackendString,+ key: 'llamacpp_version',+ value: version,+ })+ events.emit('settingsChanged', {+ key: 'llamacpp_backend',+ value: backend,})}@@ -1248,7 +1429,7 @@ export default class llamacpp_extension extends AIEngine {}// Use Rust checkBackendForUpdates logic implicitly here by using the helpers- const version_backends = await listSupportedBackends()+ const version_backends = await listSupportedBackends(true)const checkResult = await checkBackendForUpdates(this.config.version_backend,version_backends@@ -1289,7 +1470,7 @@ export default class llamacpp_extension extends AIEngine {targetBackend?: string}> {try {- const version_backends = await listSupportedBackends()+ const version_backends = await listSupportedBackends(true)const result = await checkBackendForUpdates(this.config.version_backend,version_backends@@ -1374,10 +1555,7 @@ export default class llamacpp_extension extends AIEngine {}onSettingUpdate<T>(key: string, value: T): void {- if (key === 'version_backend') {- // Skip entirely if updateBackend() is already handling it —- // updateBackend() will commit to in-memory config itself after all- // side effects succeed.+ if (key === 'llamacpp_version' || key === 'llamacpp_backend') {if (this.isUpdatingBackend) {return}@@ -1385,13 +1563,59 @@ export default class llamacpp_extension extends AIEngine {this.config[key] = value- if (key === 'version_backend') {- const valueStr = value as string- // Async logic wrapped in IIFE since onSettingUpdate is void+ if (key === 'llamacpp_version' || key === 'llamacpp_backend') {;(async () => {try {+ let v = this.config.llamacpp_version+ let b = this.config.llamacpp_backend+ if (!v || !b || v === 'none' || b === 'none') return++ // Validate (v, b) combination exists; if not, auto-resolve the+ // backend to the best one available for the chosen version.+ const supported = await listSupportedBackends(+ this.config.check_for_updates !== false+ )+ const combos = new Set(+ supported.map((e) => `${e.version}/${e.backend}`)+ )+ if (!combos.has(`${v}/${b}`)) {+ const candidates = supported.filter((e) => e.version === v)+ if (candidates.length === 0) {+ logger.warn(+ `No backends available for version '${v}'; ignoring update.`+ )+ return+ }+ const best = await this.determineBestBackend(candidates)+ const [, bb] = best.split('/')+ if (!bb) return+ b = bb+ this.config.llamacpp_backend = bb+ const settings = await this.getSettings()+ await this.updateSettings(+ settings.map((item) => {+ if (item.key === 'llamacpp_backend') {+ item.controllerProps.value = bb+ }+ return item+ })+ )+ if (events && typeof events.emit === 'function') {+ events.emit('settingsChanged', {+ key: 'llamacpp_backend',+ value: bb,+ })+ }+ }++ this.recomposeVersionBackend()+ const composite = this.config.version_backendconst currentStored = this.getStoredBackendType() || undefined- const result = await handleSettingUpdate(key, valueStr, currentStored)+ const result = await handleSettingUpdate(+ 'version_backend',+ composite,+ currentStored+ )if (result.backend_type_updated && result.effective_backend_type) {this.setStoredBackendType(result.effective_backend_type)diff --git a/extensions/llamacpp-extension/src/settings-store.ts b/extensions/llamacpp-extension/src/settings-store.tsnew file mode 100644index 000000000..21ab3f81b--- /dev/null+++ b/extensions/llamacpp-extension/src/settings-store.ts@@ -0,0 +1,56 @@+import { fs, joinPath, getJanDataFolderPath } from '@janhq/core'+import type { SettingComponentProps } from '@janhq/core'++const DIR_NAME = 'llamacpp'+const FILE_NAME = 'settings.json'+const TMP_NAME = 'settings.json.tmp'++let writeChain: Promise<unknown> = Promise.resolve()++async function paths(): Promise<{ dir: string; file: string; tmp: string }> {+ const root = await getJanDataFolderPath()+ const dir = await joinPath([root, DIR_NAME])+ const file = await joinPath([dir, FILE_NAME])+ const tmp = await joinPath([dir, TMP_NAME])+ return { dir, file, tmp }+}++export async function readSettingsFile(): Promise<SettingComponentProps[]> {+ const { file } = await paths()+ if (!(await fs.existsSync(file))) return []+ try {+ const raw = await fs.readFileSync(file, 'utf8')+ const parsed = JSON.parse(raw)+ return Array.isArray(parsed) ? (parsed as SettingComponentProps[]) : []+ } catch {+ return []+ }+}++export async function writeSettingsFile(+ settings: SettingComponentProps[]+): Promise<void> {+ const task = async () => {+ const { dir, file, tmp } = await paths()+ if (!(await fs.existsSync(dir))) await fs.mkdir(dir)+ const json = JSON.stringify(settings, null, 2)+ await fs.writeFileSync(tmp, json)+ try {+ await fs.mv(tmp, file)+ } catch {+ await fs.writeFileSync(file, json)+ try {+ if (await fs.existsSync(tmp)) await fs.rm(tmp)+ } catch {+ /* best-effort */+ }+ }+ }+ writeChain = writeChain.then(task, task)+ await writeChain+}++export async function settingsFileExists(): Promise<boolean> {+ const { file } = await paths()+ return await fs.existsSync(file)+}diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.tsindex 01fa4c309..ce2188999 100644--- a/extensions/llamacpp-extension/src/test/backend.test.ts+++ b/extensions/llamacpp-extension/src/test/backend.test.ts@@ -5,6 +5,7 @@ import {isBackendInstalled,downloadBackend,verifyBackendInstallation,+ fetchRemoteBackends,} from '../backend'import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'import { fs, getJanDataFolderPath, events } from '@janhq/core'@@ -48,6 +49,11 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {return {...actual,+ getSupportedFeaturesFromRust: vi.fn().mockResolvedValue({}),+ normalizeFeatures: vi.fn().mockReturnValue({}),+ determineSupportedBackends: vi+ .fn()+ .mockResolvedValue(['linux-vulkan-x64']),}})@@ -552,4 +558,31 @@ describe('Backend functions', () => {)})})++ describe('fetchRemoteBackends', () => {+ it('returns the upstream-released backends from the plugin invoke', async () => {+ const remote = [+ { version: 'b9300', backend: 'linux-vulkan-common_cpus-x64' },+ { version: 'b9222', backend: 'linux-vulkan-common_cpus-x64' },+ ]+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {+ if (cmd === 'plugin:llamacpp|fetch_remote_supported_backends')+ return remote as any+ return undefined as any+ })++ const result = await fetchRemoteBackends()+ expect(result).toEqual(remote)+ })++ it('returns [] when the remote fetch fails (offline)', async () => {+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {+ if (cmd === 'plugin:llamacpp|fetch_remote_supported_backends')+ throw new Error('offline')+ return undefined as any+ })+ const result = await fetchRemoteBackends()+ expect(result).toEqual([])+ })+ })})diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex ce0824ebe..7feafcd12 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -616,7 +616,7 @@ describe('llamacpp_extension', () => {extension['isUpdatingBackend'] = true// Call onSettingUpdate while updateBackend is "running"- extension.onSettingUpdate('version_backend', 'v2.0.0/linux-avx2-x64')+ extension.onSettingUpdate('llamacpp_backend', 'linux-avx2-x64')// ensureBackendReady should NOT have been called from onSettingUpdateexpect(extension['ensureBackendReady']).not.toHaveBeenCalled()diff --git a/extensions/llamacpp-extension/src/test/settings-store.test.ts b/extensions/llamacpp-extension/src/test/settings-store.test.tsnew file mode 100644index 000000000..6e2b1b987--- /dev/null+++ b/extensions/llamacpp-extension/src/test/settings-store.test.ts@@ -0,0 +1,104 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { fsMock } = vi.hoisted(() => ({+ fsMock: {+ existsSync: vi.fn(),+ readFileSync: vi.fn(),+ writeFileSync: vi.fn(),+ mkdir: vi.fn(),+ mv: vi.fn(),+ rm: vi.fn(),+ },+}))++vi.mock('@janhq/core', () => ({+ getJanDataFolderPath: vi.fn().mockResolvedValue('/jan'),+ joinPath: vi.fn(async (parts: string[]) => parts.join('/')),+ fs: fsMock,+}))++import {+ readSettingsFile,+ writeSettingsFile,+ settingsFileExists,+} from '../settings-store'++beforeEach(() => {+ vi.clearAllMocks()+ fsMock.mv.mockResolvedValue(undefined)+ fsMock.mkdir.mockResolvedValue(undefined)+ fsMock.writeFileSync.mockResolvedValue(undefined)+ fsMock.rm.mockResolvedValue(undefined)+})++describe('settings-store', () => {+ it('returns [] when the file does not exist', async () => {+ fsMock.existsSync.mockResolvedValue(false)+ const result = await readSettingsFile()+ expect(result).toEqual([])+ })++ it('parses an existing settings file', async () => {+ fsMock.existsSync.mockResolvedValue(true)+ const data = [{ key: 'a', controllerProps: { value: 1 } }]+ fsMock.readFileSync.mockResolvedValue(JSON.stringify(data))+ const result = await readSettingsFile()+ expect(result).toEqual(data)+ })++ it('returns [] on malformed JSON instead of throwing', async () => {+ fsMock.existsSync.mockResolvedValue(true)+ fsMock.readFileSync.mockResolvedValue('{not json')+ const result = await readSettingsFile()+ expect(result).toEqual([])+ })++ it('settingsFileExists reflects fs.existsSync', async () => {+ fsMock.existsSync.mockResolvedValueOnce(true)+ expect(await settingsFileExists()).toBe(true)+ fsMock.existsSync.mockResolvedValueOnce(false)+ expect(await settingsFileExists()).toBe(false)+ })++ it('writes via tmp + mv (atomic-ish) and creates the dir if missing', async () => {+ fsMock.existsSync.mockResolvedValue(false)+ await writeSettingsFile([{ key: 'k', controllerProps: { value: 1 } }] as any)+ expect(fsMock.mkdir).toHaveBeenCalledWith('/jan/llamacpp')+ expect(fsMock.writeFileSync).toHaveBeenCalledWith(+ '/jan/llamacpp/settings.json.tmp',+ expect.any(String)+ )+ expect(fsMock.mv).toHaveBeenCalledWith(+ '/jan/llamacpp/settings.json.tmp',+ '/jan/llamacpp/settings.json'+ )+ })++ it('falls back to direct write when mv fails', async () => {+ fsMock.existsSync.mockResolvedValue(true)+ fsMock.mv.mockRejectedValueOnce(new Error('cross-device'))+ await writeSettingsFile([{ key: 'k', controllerProps: { value: 1 } }] as any)+ expect(fsMock.writeFileSync).toHaveBeenCalledWith(+ '/jan/llamacpp/settings.json',+ expect.any(String)+ )+ })++ it('serializes concurrent writes', async () => {+ fsMock.existsSync.mockResolvedValue(true)+ let inflight = 0+ let maxInflight = 0+ fsMock.writeFileSync.mockImplementation(async () => {+ inflight += 1+ maxInflight = Math.max(maxInflight, inflight)+ await new Promise((r) => setTimeout(r, 5))+ inflight -= 1+ })+ await Promise.all([+ writeSettingsFile([{ key: 'a' }] as any),+ writeSettingsFile([{ key: 'b' }] as any),+ writeSettingsFile([{ key: 'c' }] as any),+ ])+ expect(maxInflight).toBe(1)+ })+})diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.tsindex 83b62b872..bceb2a0ef 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts@@ -42,9 +42,22 @@ function asString(v: any, defaultValue = ''): string {}export function normalizeLlamacppConfig(config: any): LlamacppConfig {+ const llamacpp_version = asString(config.llamacpp_version)+ const llamacpp_backend = asString(config.llamacpp_backend)+ const composedVersionBackend =+ llamacpp_version && llamacpp_backend+ ? `${llamacpp_version}/${llamacpp_backend}`+ : asString(config.version_backend)return {- version_backend: asString(config.version_backend),+ llamacpp_version,+ llamacpp_backend,+ version_backend: composedVersionBackend,auto_update_engine: asBool(config.auto_update_engine),+ check_for_updates:+ config.check_for_updates === undefined ||+ config.check_for_updates === null+ ? true+ : asBool(config.check_for_updates),verify_backend_deps:config.verify_backend_deps === undefined || config.verify_backend_deps === null? truediff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex 9fd0778cb..519b18fe8 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -33,8 +33,12 @@ export interface GgufMetadata {// llama.cpp settingsexport type LlamacppConfig = {+ llamacpp_version: string+ llamacpp_backend: string+ /** Composed from llamacpp_version + llamacpp_backend as `${version}/${backend}`. Not user-settable. */version_backend: stringauto_update_engine: boolean+ check_for_updates: booleanverify_backend_deps: booleanauto_unload: booleanmodels_max: string | numberdiff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsxindex 276fc284f..3a7d3cfdc 100644--- a/web-app/src/containers/ModelSetting.tsx+++ b/web-app/src/containers/ModelSetting.tsx@@ -366,10 +366,10 @@ function MtpPanel({}}, [modelId, serviceHub])- const versionBackend = provider.settings?.find(- (s) => s.key === 'version_backend'+ const llamacppVersion = provider.settings?.find(+ (s) => s.key === 'llamacpp_version')?.controller_props?.value as string | undefined- const buildNo = parseBuildNumber(versionBackend?.split('/')[0])+ const buildNo = parseBuildNumber(llamacppVersion)const backendSupports = buildNo !== null && buildNo >= MTP_MIN_BUILDconst persist = useCallback(diff --git a/web-app/src/hooks/useBackendUpdater.ts b/web-app/src/hooks/useBackendUpdater.tsindex efb08853a..c19c82e41 100644--- a/web-app/src/hooks/useBackendUpdater.ts+++ b/web-app/src/hooks/useBackendUpdater.ts@@ -36,25 +36,15 @@ async function getCurrentBackendTypeFromSettings(extension: ExtensionWithSettings): Promise<string> {const settings = await extension.getSettings?.()- const currentBackendSetting = settings?.find(- (s) => s.key === 'version_backend'- )- const currentBackend = currentBackendSetting?.controllerProps?.value as string+ const backendSetting = settings?.find((s) => s.key === 'llamacpp_backend')+ const currentBackendType = (+ backendSetting?.controllerProps?.value as string | undefined+ )?.trim()- if (!currentBackend) {+ if (!currentBackendType) {throw new Error('Current backend not found')}- const parts = currentBackend.split('/')- const currentVersionPart = parts[0]?.trim()- const currentBackendType = parts[1]?.trim()-- if (parts.length !== 2 || !currentVersionPart || !currentBackendType) {- throw new Error(- `Invalid current backend format: "${currentBackend}". Expected "version/backendType".`- )- }-return currentBackendType}diff --git a/web-app/src/providers/GlobalEventHandler.tsx b/web-app/src/providers/GlobalEventHandler.tsxindex 0b53e0b02..f20a83015 100644--- a/web-app/src/providers/GlobalEventHandler.tsx+++ b/web-app/src/providers/GlobalEventHandler.tsx@@ -53,13 +53,13 @@ export function GlobalEventHandler() {}) => {console.log('Global settingsChanged event:', event)- // Handle version_backend changes specifically- if (event.key === 'version_backend') {+ if (+ event.key === 'llamacpp_version' ||+ event.key === 'llamacpp_backend'+ ) {try {- // Refresh providers to get updated settings from the extensionconst updatedProviders = await serviceHub.providers().getProviders()setProviders(updatedProviders)- console.log('Providers refreshed after version_backend change')} catch (error) {console.error('Failed to refresh providers after settingsChanged:',diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex 82d9f13f8..bbc56ade6 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -150,11 +150,13 @@ function ProviderDetail() {])// Check if llamacpp/mlx provider needs backend configuration+ const isBackendKey = (k: string) =>+ k === 'llamacpp_version' || k === 'llamacpp_backend'const needsBackendConfig =(provider?.provider === 'llamacpp' || provider?.provider === 'mlx') &&provider.settings?.some((setting) =>- setting.key === 'version_backend' &&+ isBackendKey(setting.key) &&(setting.controller_props.value === 'none' ||setting.controller_props.value === '' ||!setting.controller_props.value)@@ -795,8 +797,7 @@ function ProviderDetail() {// Use the DynamicController componentconst actionComponent = (<div className="mt-2">- {needsBackendConfig &&- setting.key === 'version_backend' ? (+ {needsBackendConfig && isBackendKey(setting.key) ? (<div className="flex items-center gap-1 text-sm"><IconLoader size={16} className="animate-spin" /><span>loading</span>@@ -836,8 +837,8 @@ function ProviderDetail() {updateObj.base_url = newValue}- // Reset device setting to empty when backend version changes- if (settingKey === 'version_backend') {+ // Reset device setting to empty when backend or version changes+ if (isBackendKey(settingKey)) {const deviceSettingIndex =newSettings.findIndex((s) => s.key === 'device'@@ -918,19 +919,16 @@ function ProviderDetail() {),}}/>- {setting.key === 'version_backend' &&+ {setting.key === 'llamacpp_backend' &&setting.controller_props?.recommended && (<div className="mt-1 text-sm text-muted-foreground"><span className="font-medium">- {setting.controller_props.recommended- ?.split('/')- .pop() ||- setting.controller_props.recommended}+ {setting.controller_props.recommended}</span><span> is the recommended backend.</span></div>)}- {setting.key === 'version_backend' &&+ {setting.key === 'llamacpp_backend' &&(provider?.provider === 'llamacpp' ||provider?.provider === 'mlx') && (<div className="mt-2 flex flex-wrap gap-2">diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsxindex ce5573b7a..a422f3a74 100644--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx@@ -47,11 +47,18 @@ const h = vi.hoisted(() => {],settings: [{- key: 'version_backend',+ key: 'llamacpp_version',+ title: 'Version',+ description: 'llama.cpp release version',+ controller_type: 'input',+ controller_props: { value: 'v1', recommended: 'v1' },+ },+ {+ key: 'llamacpp_backend',title: 'Backend',- description: 'Backend version',+ description: 'Hardware backend',controller_type: 'input',- controller_props: { value: 'v1', recommended: 'cuda/v1' },+ controller_props: { value: 'cuda', recommended: 'cuda' },},{key: 'device',@@ -792,12 +799,12 @@ describe('ProviderDetail route', () => {)})- it('for llamacpp, the version_backend control also stops all running models on change', async () => {+ it('for llamacpp, the llamacpp_version control also stops all running models on change', async () => {h.params.providerName = 'llamacpp'renderComponent()const dyns = screen.getAllByTestId('dynamic-ctrl')await act(async () => {- fireEvent.click(dyns[0]) // version_backend+ fireEvent.click(dyns[0]) // llamacpp_version})expect(h.modelsSvc.stopAllModels).toHaveBeenCalled()})