Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
refactor: migrate llamacpp backend logic to rust plugin (#7171)
Akarshan Biswas81cd0dfae8b2
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex 343b091ff..a1a91ddf9 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -1,52 +1,18 @@import { getJanDataFolderPath, fs, joinPath, events } from '@janhq/core'import { invoke } from '@tauri-apps/api/core'import { getProxyConfig, basenameNoExt } from './util'-import { dirname, basename } from '@tauri-apps/api/path'+import { dirname } from '@tauri-apps/api/path'import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'--/*- * Helper function to map an old backend type string to its new, common equivalent.- * This is used for migrating stored user preferences.- */-export function mapOldBackendToNew(oldBackend: string): string {- const isWindows = oldBackend.startsWith('win-')- const isLinux = oldBackend.startsWith('linux-')- const osPrefix = isWindows ? 'win-' : isLinux ? 'linux-' : ''-- // Determine architecture suffix, defaulting to x64- const archSuffix = oldBackend.includes('-arm64') ? 'arm64' : 'x64'- const isX64 = archSuffix === 'x64'-- // Handle GPU backends- if (oldBackend.includes('cuda-cu12.0')) {- // Migration from e.g., 'linux-avx2-cuda-cu12.0-x64' to 'linux-cuda-12-common_cpus-x64'- return `${osPrefix}cuda-12-common_cpus-${isX64 ? 'x64' : archSuffix}`- } else if (oldBackend.includes('cuda-cu11.7')) {- // Migration from e.g., 'win-noavx-cuda-cu11.7-x64' to 'win-cuda-11-common_cpus-x64'- return `${osPrefix}cuda-11-common_cpus-${isX64 ? 'x64' : archSuffix}`- } else if (oldBackend.includes('vulkan')) {- // If it's already the new name, return it- if (oldBackend.includes('vulkan-common_cpus')) return oldBackend-- // Migration from e.g., 'linux-vulkan-x64' to 'linux-vulkan-common_cpus-x64'- return `${osPrefix}vulkan-common_cpus-${isX64 ? 'x64' : archSuffix}`- }-- // Handle CPU-only backends (avx, avx2, avx512, noavx)- const isOldCpuBackend =- oldBackend.includes('avx512') ||- oldBackend.includes('avx2') ||- oldBackend.includes('avx-x64') || // Check for 'avx' but not as part of 'avx2' or 'avx512'- oldBackend.includes('noavx-x64')-- if (isOldCpuBackend) {- // Migration from e.g., 'win-avx512-x64' to 'win-common_cpus-x64'- return `${osPrefix}common_cpus-${isX64 ? 'x64' : archSuffix}`- }-- // Return original if it doesn't match a pattern that needs migration (e.g., macos/arm64 which are already 'common')- return oldBackend-}+import {+ mapOldBackendToNew,+ getLocalInstalledBackendsInternal,+ normalizeFeatures,+ determineSupportedBackends,+ listSupportedBackendsFromRust,+ BackendVersion,+ getSupportedFeaturesFromRust,+ isCudaInstalledFromRust,+} from '@janhq/tauri-plugin-llamacpp-api'/** Reads currently installed backends in janDataFolderPath@@ -55,44 +21,14 @@ export function mapOldBackendToNew(oldBackend: string): string {export async function getLocalInstalledBackends(): Promise<{ version: string; backend: string }[]> {- const local: Array<{ version: string; backend: string }> = []const janDataFolderPath = await getJanDataFolderPath()- const backendsDir = await joinPath([+ const backendDir = await joinPath([janDataFolderPath,'llamacpp','backends',])- if (await fs.existsSync(backendsDir)) {- const versionDirs = await fs.readdirSync(backendsDir)-- // If the folder does not exist we are done.- if (!versionDirs) {- return local- }- for (const version of versionDirs) {- const versionPath = await joinPath([backendsDir, version])- const versionName = await basename(versionPath)-- // Check if versionPath is actually a directory before reading it- const versionStat = await fs.fileStat(versionPath)- if (!versionStat?.isDirectory) {- continue- }-- const backendTypes = await fs.readdirSync(versionPath)-- // Verify that the backend is really installed- for (const backendType of backendTypes) {- const backendName = await basename(backendType)- if (await isBackendInstalled(backendType, versionName)) {- local.push({ version: versionName, backend: backendName })- }- }- }- }- return local+ return await getLocalInstalledBackendsInternal(backendDir)}-/** currently reads available backends in remote*@@ -123,7 +59,7 @@ async function fetchRemoteSupportedBackends(remote.push({ version, backend })continue}- const mappedNew = mapOldBackendToNew(backend)+ const mappedNew = await mapOldBackendToNew(backend)if (mappedNew !== backend && supportedBackends.includes(mappedNew)) {// Push the ORIGINAL backend name here, as this is the name of the file on the server.remote.push({ version, backend })@@ -138,54 +74,23 @@ async function fetchRemoteSupportedBackends(// <Jan's data folder>/llamacpp/backends/<backend_version>/<backend_type>// what should be available to the user for selection?-export async function listSupportedBackends(): Promise<- { version: string; backend: string }[]-> {+export async function listSupportedBackends(): Promise<BackendVersion[]> {const sysInfo = await getSystemInfo()- const os_type = sysInfo.os_type+ const osType = sysInfo.os_typeconst arch = sysInfo.cpu.arch- const features = await _getSupportedFeatures()- const sysType = `${os_type}-${arch}`- let supportedBackends = []-- // NOTE: janhq's tags for llama.cpp builds are a bit different- // TODO: fetch versions from the server?- // TODO: select CUDA version based on driver version- if (sysType == 'windows-x86_64') {- supportedBackends.push('win-common_cpus-x64')- if (features.cuda11) {- supportedBackends.push('win-cuda-11-common_cpus-x64')- }- if (features.cuda12) {- supportedBackends.push('win-cuda-12-common_cpus-x64')- }- if (features.cuda13)- if (features.vulkan) supportedBackends.push('win-vulkan-common_cpus-x64')- }- // not available yet, placeholder for future- else if (sysType === 'windows-aarch64' || sysType === 'windows-arm64') {- supportedBackends.push('win-arm64')- } else if (sysType === 'linux-x86_64' || sysType === 'linux-x86') {- supportedBackends.push('linux-common_cpus-x64')- if (features.cuda11) {- supportedBackends.push('linux-cuda-11-common_cpus-x64')- }- if (features.cuda12) {- supportedBackends.push('linux-cuda-12-common_cpus-x64')- }- if (features.vulkan) supportedBackends.push('linux-vulkan-common_cpus-x64')- }- // not available yet, placeholder for future- else if (sysType === 'linux-aarch64' || sysType === 'linux-arm64') {- supportedBackends.push('linux-arm64')- } else if (sysType === 'macos-x86_64' || sysType === 'macos-x86') {- supportedBackends.push('macos-x64')- } else if (sysType === 'macos-aarch64' || sysType === 'macos-arm64') {- supportedBackends.push('macos-arm64')- }- // get latest backends from Github- let remoteBackendVersions = []+ const rawFeatures = await _getSupportedFeatures()+ const features = normalizeFeatures(rawFeatures)++ // Get supported backend names from Rust+ const supportedBackends = await determineSupportedBackends(+ osType,+ arch,+ features+ )++ // Get remote backends from Github+ let remoteBackendVersions: BackendVersion[] = []try {remoteBackendVersions =await fetchRemoteSupportedBackends(supportedBackends)@@ -197,23 +102,12 @@ export async function listSupportedBackends(): Promise<// Get locally installed versionsconst localBackendVersions = await getLocalInstalledBackends()- // Use a Map keyed by “${version}|${backend}” for O(1) deduplication.- const mergedMap = new Map<string, { version: string; backend: string }>()- for (const entry of remoteBackendVersions) {- mergedMap.set(`${entry.version}|${entry.backend}`, entry)- }- for (const entry of localBackendVersions) {- mergedMap.set(`${entry.version}|${entry.backend}`, entry)- }-- const merged = Array.from(mergedMap.values())- // Sort newest version first; if versions tie, sort by backend name- merged.sort((a, b) => {- const versionCmp = b.version.localeCompare(a.version)- return versionCmp !== 0 ? versionCmp : a.backend.localeCompare(b.backend)- })- return merged+ // Merge & sort via Rust+ return listSupportedBackendsFromRust(+ remoteBackendVersions,+ localBackendVersions+ )}export async function getBackendDir(@@ -384,49 +278,11 @@ export async function downloadBackend(async function _getSupportedFeatures() {const sysInfo = await getSystemInfo()- const features = {- avx: sysInfo.cpu.extensions.includes('avx'),- avx2: sysInfo.cpu.extensions.includes('avx2'),- avx512: sysInfo.cpu.extensions.includes('avx512'),- cuda11: false,- cuda12: false,- cuda13: false,- vulkan: false,- }-- // https://docs.nvidia.com/deploy/cuda-compatibility/#cuda-11-and-later-defaults-to-minor-version-compatibility- let minCuda11DriverVersion: string- let minCuda12DriverVersion: string- let minCuda13DriverVersion: string- if (sysInfo.os_type === 'linux') {- minCuda11DriverVersion = '450.80.02'- minCuda12DriverVersion = '525.60.13'- minCuda13DriverVersion = '580'- } else if (sysInfo.os_type === 'windows') {- minCuda11DriverVersion = '452.39'- minCuda12DriverVersion = '527.41'- minCuda13DriverVersion = '580'- }-- // TODO: HIP and SYCL- for (const gpuInfo of sysInfo.gpus) {- const driverVersion = gpuInfo.driver_version-- if (gpuInfo.nvidia_info?.compute_capability) {- if (compareVersions(driverVersion, minCuda11DriverVersion) >= 0)- features.cuda11 = true- if (compareVersions(driverVersion, minCuda12DriverVersion) >= 0)- features.cuda12 = true- if (compareVersions(driverVersion, minCuda13DriverVersion) >= 0) {- features.cuda13 = true- }- }- // Vulkan support check- if (gpuInfo.vulkan_info?.api_version) {- features.vulkan = true- }- }- return features+ return await getSupportedFeaturesFromRust(+ sysInfo.os_type,+ sysInfo.cpu.extensions,+ sysInfo.gpus+ )}/**@@ -463,67 +319,12 @@ async function _isCudaInstalled(version: string): Promise<boolean> {const sysInfo = await getSystemInfo()- const os_type = sysInfo.os_type-- const libnameLookup = {- 'windows-11.7': `cudart64_110.dll`,- 'windows-12.0': `cudart64_12.dll`,- 'windows-13.0': `cudart64_13.dll`,- 'linux-11.7': `libcudart.so.11.0`,- 'linux-12.0': `libcudart.so.12`,- 'linux-13.0': `libcudart.so.13`,- }-- const key = `${os_type}-${version}`- if (!(key in libnameLookup)) {- return false- }-- const libname = libnameLookup[key]-- // Expected new location- const newPath = await joinPath([backendDir, 'build', 'bin', libname])- if (await fs.existsSync(newPath)) return true-- // Old location (used by older builds)const janDataFolderPath = await getJanDataFolderPath()- const oldPath = await joinPath([- janDataFolderPath,- 'llamacpp',- 'lib',- libname,- ])-- if (await fs.existsSync(oldPath)) {- // Ensure target directory exists- const targetDir = await joinPath([backendDir, 'build', 'bin'])- if (!(await fs.existsSync(targetDir))) {- await fs.mkdir(targetDir)- }-- try {- // Move old lib to the correct new location- await fs.mv(oldPath, newPath)- console.log(`[CUDA] Migrated ${libname} from old path to new location.`)- return true- } catch (err) {- console.warn(`[CUDA] Failed to move old library:`, err)- }- }-- return false-}-function compareVersions(a: string, b: string): number {- const aParts = a.split('.').map(Number)- const bParts = b.split('.').map(Number)- const len = Math.max(aParts.length, bParts.length)-- for (let i = 0; i < len; i++) {- const x = aParts[i] || 0- const y = bParts[i] || 0- if (x > y) return 1- if (x < y) return -1- }- return 0+ return isCudaInstalledFromRust(+ backendDir,+ version,+ sysInfo.os_type,+ janDataFolderPath+ )}diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 794558bbb..1f7cf870d 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -32,7 +32,6 @@ import {isBackendInstalled,getBackendExePath,getBackendDir,- mapOldBackendToNew,} from './backend'import { invoke } from '@tauri-apps/api/core'import {@@ -56,6 +55,13 @@ import {EmbeddingResponse,DeviceList,SystemMemory,+ mapOldBackendToNew,+ findLatestVersionForBackend,+ prioritizeBackends,+ checkBackendForUpdates,+ removeOldBackendVersions,+ shouldMigrateBackend,+ handleSettingUpdate,} from '@janhq/tauri-plugin-llamacpp-api'import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'@@ -189,23 +195,6 @@ export default class llamacpp_extension extends AIEngine {}}- private findLatestVersionForBackend(- version_backends: { version: string; backend: string }[],- backendType: string- ): string | null {- const matchingBackends = version_backends.filter(- (vb) => mapOldBackendToNew(vb.backend) === backendType- )- if (matchingBackends.length === 0) {- return null- }-- // Sort by version (newest first) and get the latest- matchingBackends.sort((a, b) => b.version.localeCompare(a.version))- // Return the full string including the original asset name, as this is used for download/path- return `${matchingBackends[0].version}/${matchingBackends[0].backend}`- }-async configureBackends(): Promise<void> {if (this.isConfiguringBackends) {logger.info(@@ -239,46 +228,37 @@ export default class llamacpp_extension extends AIEngine {// Get stored backend preferenceconst storedBackendType = this.getStoredBackendType()let bestAvailableBackendString = ''- let effectiveStoredBackendType = storedBackendType++ // Calculate the "best" backend first, as it's used for fallback and defaults+ bestAvailableBackendString =+ await this.determineBestBackend(version_backends)if (storedBackendType) {- // migration part- const mappedNewBackendType = mapOldBackendToNew(storedBackendType)- const isMigrationNeeded = mappedNewBackendType !== storedBackendType-- if (isMigrationNeeded) {- // Check if the new, mapped backend is available in the current version list (by its effective type)- const isNewTypeAvailable = version_backends.some(- (vb) => mapOldBackendToNew(vb.backend) === mappedNewBackendType- )+ // Delegate migration check to Rust+ const migrationTarget = await shouldMigrateBackend(+ storedBackendType,+ version_backends+ )- if (isNewTypeAvailable) {- logger.info(- `Migrating stored backend type preference from old '${storedBackendType}' to new common type: '${mappedNewBackendType}'`- )- this.setStoredBackendType(mappedNewBackendType) // Update localStorage immediately- effectiveStoredBackendType = mappedNewBackendType- } else {- logger.warn(- `Migration from '${storedBackendType}' to '${mappedNewBackendType}' skipped: New type not available in supported backends. Using old preference for now.`- )- // Keep the original type if new type not available- effectiveStoredBackendType = storedBackendType- }+ if (migrationTarget) {+ logger.info(+ `Migrating stored backend type preference from old '${storedBackendType}' to new common type: '${migrationTarget}'`+ )+ this.setStoredBackendType(migrationTarget)}- // Use effectiveStoredBackendType (which is now the migrated type)- const preferredBackendString = this.findLatestVersionForBackend(+ const effectiveStoredBackendType = migrationTarget || storedBackendType++ // Use the effective (migrated) type to find the latest version+ const preferredBackendString = await findLatestVersionForBackend(version_backends,- effectiveStoredBackendType // Use the effective (migrated) type here+ effectiveStoredBackendType)if (preferredBackendString) {- // The returned string has the original asset name, we need to normalize it- const [version, backend] = preferredBackendString.split('/')- const normalizedBackend = mapOldBackendToNew(backend)- bestAvailableBackendString = `${version}/${normalizedBackend}`-+ // Override bestAvailableBackendString with the user preference+ // The returned string from Rust is "version/backend"+ bestAvailableBackendString = preferredBackendStringlogger.info(`Using stored backend preference: ${bestAvailableBackendString}`)@@ -288,12 +268,8 @@ export default class llamacpp_extension extends AIEngine {)// Clear the invalid stored preferencethis.clearStoredBackendType()- bestAvailableBackendString =- await this.determineBestBackend(version_backends)+ // bestAvailableBackendString remains as the priority one calculated earlier}- } else {- bestAvailableBackendString =- await this.determineBestBackend(version_backends)}let settings = structuredClone(SETTINGS)@@ -325,7 +301,7 @@ export default class llamacpp_extension extends AIEngine {// Determine initial UI default based on priority:// 1. Saved setting (if valid and not original default)- // 2. Best available for stored backend type+ // 2. Best available for stored backend type or automatic best// 3. Original defaultlet initialUiDefault = originalDefaultBackendValue@@ -335,7 +311,8 @@ export default class llamacpp_extension extends AIEngine {) {const [savedVersion, savedBackend] = savedBackendSetting.split('/')if (savedVersion && savedBackend) {- const normalizedBackend = mapOldBackendToNew(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@@ -462,7 +439,7 @@ export default class llamacpp_extension extends AIEngine {): Promise<string> {if (version_backends.length === 0) return ''- // Check GPU memory availability+ // Check GPU memory availability via system infolet hasEnoughGpuMemory = falsetry {const sysInfo = await getSystemInfo()@@ -478,90 +455,12 @@ export default class llamacpp_extension extends AIEngine {hasEnoughGpuMemory = false}- // Priority list for backend types (more specific/performant ones first)- // Vulkan will be conditionally prioritized based on GPU memory- const backendPriorities: string[] = hasEnoughGpuMemory- ? [- 'cuda-cu13.0',- 'cuda-cu12.0',- 'cuda-cu11.7',- 'vulkan',- 'common_cpus', // NEW: Unified CPU backend- 'avx512', // Old, for transition/local installed detection- 'avx2', // Old, for transition- 'avx', // Old, for transition- 'noavx', // Old, for transition- 'arm64',- 'x64',- ]- : [- 'cuda-cu13.0',- 'cuda-cu12.0',- 'cuda-cu11.7',- 'common_cpus', // NEW: Unified CPU backend- 'avx512', // Old, for transition- 'avx2', // Old, for transition- 'avx', // Old, for transition- 'noavx', // Old, for transition- 'arm64',- 'x64',- 'vulkan',- ]-- // Helper to map backend string to a priority category- const getBackendCategory = (backendString: string): string | undefined => {- if (backendString.includes('cuda-13-common_cpus')) return 'cuda-cu13.0'- if (- backendString.includes('cuda-12-common_cpus') ||- backendString.includes('cu12.0')- )- return 'cuda-cu12.0'- if (- backendString.includes('cuda-11-common_cpus') ||- backendString.includes('cu11.7')- )- return 'cuda-cu11.7'- if (backendString.includes('vulkan')) return 'vulkan'- if (backendString.includes('common_cpus')) return 'common_cpus'- if (backendString.includes('avx512')) return 'avx512'- if (backendString.includes('avx2')) return 'avx2'- if (- backendString.includes('avx') &&- !backendString.includes('avx2') &&- !backendString.includes('avx512')- )- return 'avx'- if (backendString.includes('noavx')) return 'noavx'- if (backendString.endsWith('arm64')) return 'arm64'- if (backendString.endsWith('x64')) return 'x64'- return undefined- }-- let foundBestBackend: { version: string; backend: string } | undefined- for (const priorityCategory of backendPriorities) {- const matchingBackends = version_backends.filter((vb) => {- const category = getBackendCategory(vb.backend)- return category === priorityCategory- })-- if (matchingBackends.length > 0) {- foundBestBackend = matchingBackends[0]- logger.info(- `Determined best available backend: ${foundBestBackend.version}/${foundBestBackend.backend} (Category: "${priorityCategory}")`- )- break- }- }-- if (foundBestBackend) {- return `${foundBestBackend.version}/${foundBestBackend.backend}`- } else {- // Fallback to newest version- logger.info(- `Fallback to: ${version_backends[0].version}/${version_backends[0].backend}`- )- return `${version_backends[0].version}/${version_backends[0].backend}`- }+ // Use Rust logic to prioritize backends+ const result = await prioritizeBackends(+ version_backends,+ hasEnoughGpuMemory+ )+ return result.backend_string}async updateBackend(@@ -587,9 +486,11 @@ export default class llamacpp_extension extends AIEngine {await new Promise((resolve) => setTimeout(resolve, 1000))}- const effectiveBackendType = mapOldBackendToNew(backend)+ // We ensure consistency by mapping the backend type, although targetBackendString should already be correct+ const effectiveBackendType = await mapOldBackendToNew(backend)const currentStoredBackend = this.getStoredBackendType()+ // Re-construct to be suretargetBackendString = `${version}/${effectiveBackendType}`// Update configuration@@ -627,11 +528,19 @@ export default class llamacpp_extension extends AIEngine {})}- // Clean up old versions of the same backend type+ // Clean up old versions of the same backend type using Rust command+ const janDataFolderPath = await getJanDataFolderPath()+ const backendsDir = await joinPath([+ janDataFolderPath,+ 'llamacpp',+ 'backends',+ ])+if (IS_WINDOWS) {await new Promise((resolve) => setTimeout(resolve, 500))}- await this.removeOldBackend(version, backend)++ await removeOldBackendVersions(backendsDir, version, backend)return { wasUpdated: true, newBackend: targetBackendString }} catch (error) {@@ -668,69 +577,40 @@ export default class llamacpp_extension extends AIEngine {return await this.updateBackend(bestAvailableBackendString)}- // Parse current backend configuration- const [currentVersion, currentBackend] = (- this.config.version_backend || ''- ).split('/')- // Get the effective/migrated backend type- const currentEffectiveBackendType = mapOldBackendToNew(currentBackend)-- if (!currentVersion || !currentBackend) {- logger.warn(- `Invalid current backend format: ${this.config.version_backend}`- )- return { wasUpdated: false, newBackend: this.config.version_backend }- }-- // Find the latest version for the currently selected backend type+ // Use Rust checkBackendForUpdates logic implicitly here by using the helpersconst version_backends = await listSupportedBackends()- const targetBackendString = this.findLatestVersionForBackend(- version_backends,- currentEffectiveBackendType+ const checkResult = await checkBackendForUpdates(+ this.config.version_backend,+ version_backends)- if (!targetBackendString) {- logger.warn(- `No available versions found for current backend type: ${currentEffectiveBackendType}`+ if (checkResult.update_needed && checkResult.target_backend) {+ logger.info(+ `Auto-updating to new version: ${checkResult.new_version} (${checkResult.target_backend})`)- // Attempt to fall back to the absolute best available if the preferred type is gone.- const bestEffectiveType = mapOldBackendToNew(+ return await this.updateBackend(checkResult.target_backend)+ }++ // If no update needed, check if we need to fall back (e.g. current backend not supported anymore)+ // The Rust check_backend_for_updates handles finding the latest version for current type.+ // If it returns no target_backend, it means current type is not found.+ if (!checkResult.target_backend) {+ const [currentVersion, currentBackend] =+ this.config.version_backend.split('/')+ const currentEffectiveType = await mapOldBackendToNew(currentBackend)+ const bestEffectiveType = await mapOldBackendToNew(bestAvailableBackendString.split('/')[1])- if (currentEffectiveBackendType !== bestEffectiveType) {++ if (currentEffectiveType !== bestEffectiveType) {logger.info(- `Falling back to best available backend: ${bestAvailableBackendString}`+ `Current backend type ${currentEffectiveType} not available, falling back to best available: ${bestAvailableBackendString}`)return await this.updateBackend(bestAvailableBackendString)}- return { wasUpdated: false, newBackend: this.config.version_backend }- }-- const [latestVersion, latestBackendName] = targetBackendString.split('/')-- // Check if update is needed (compare versions AND effective backend types)- if (- currentVersion === latestVersion &&- currentEffectiveBackendType === mapOldBackendToNew(latestBackendName)- ) {- logger.info(- 'Auto-update: Already using the latest version of the selected backend'- )- return { wasUpdated: false, newBackend: this.config.version_backend }}- // Perform version update or migration for the same effective backend type- logger.info(- `Auto-updating/Migrating from ${this.config.version_backend} to ${targetBackendString} (preserving effective backend type: ${currentEffectiveBackendType})`- )- return await this.updateBackend(targetBackendString)- }-- private parseBackendVersion(v: string): number {- // Remove any leading non‑digit characters (e.g. the "b")- const numeric = v.replace(/^[^\d]*/, '')- const n = Number(numeric)- return Number.isNaN(n) ? 0 : n+ return { wasUpdated: false, newBackend: this.config.version_backend }}async checkBackendForUpdates(): Promise<{@@ -738,110 +618,24 @@ export default class llamacpp_extension extends AIEngine {newVersion: stringtargetBackend?: string}> {- // Parse current backend configuration- const [currentVersion, currentBackend] = (- this.config.version_backend || ''- ).split('/')-- if (!currentVersion || !currentBackend) {- logger.warn(- `Invalid current backend format: ${this.config.version_backend}`+ try {+ const version_backends = await listSupportedBackends()+ const result = await checkBackendForUpdates(+ this.config.version_backend,+ version_backends)- return { updateNeeded: false, newVersion: '0' }- }- // Get the effective/migrated backend type for consistency with auto-update logic- const currentEffectiveBackendType = mapOldBackendToNew(currentBackend)-- // Find the latest version for the currently selected backend type (using effective type)- const version_backends = await listSupportedBackends()- const targetBackendString = this.findLatestVersionForBackend(- version_backends,- currentEffectiveBackendType // Use the effective type- )-- if (!targetBackendString) {- logger.warn(- `No available versions found for current backend type: ${currentEffectiveBackendType}`- )- return { updateNeeded: false, newVersion: '0' }- }-- const [latestVersion] = targetBackendString.split('/')-- // Check if update is needed (version comparison)- if (- this.parseBackendVersion(latestVersion) >- this.parseBackendVersion(currentVersion)- ) {- logger.info(- `New update available: ${latestVersion} -> ${targetBackendString}`- )return {- updateNeeded: true,- newVersion: latestVersion,- targetBackend: targetBackendString,+ updateNeeded: result.update_needed,+ newVersion: result.new_version,+ targetBackend: result.target_backend,}- } else {- logger.info(- `Already at latest version: ${currentVersion} = ${latestVersion}`- )+ } catch (e) {+ logger.warn('Failed to check for updates via Rust command:', e)return { updateNeeded: false, newVersion: '0' }}}- private async removeOldBackend(- latestVersion: string,- backendType: string- ): Promise<void> {- try {- const janDataFolderPath = await getJanDataFolderPath()- const backendsDir = await joinPath([- janDataFolderPath,- 'llamacpp',- 'backends',- ])-- if (!(await fs.existsSync(backendsDir))) {- return- }-- const versionDirs = await fs.readdirSync(backendsDir)-- for (const versionDir of versionDirs) {- const versionPath = await joinPath([backendsDir, versionDir])- const versionName = await basename(versionDir)-- // Skip the latest version- if (versionName === latestVersion) {- continue- }-- // Check if this version has the specific backend type we're interested in- const backendTypePath = await joinPath([versionPath, backendType])-- if (await fs.existsSync(backendTypePath)) {- const isInstalled = await isBackendInstalled(backendType, versionName)- if (isInstalled) {- try {- await fs.rm(backendTypePath)- logger.info(- `Removed old version of ${backendType}: ${backendTypePath}`- )- } catch (e) {- logger.warn(- `Failed to remove old backend version: ${backendTypePath}`,- e- )- }- }- }- }- } catch (error) {- logger.error('Error during old backend version cleanup:', error)- }- }-private async ensureFinalBackendInstallation(backendString: string): Promise<void> {@@ -906,30 +700,27 @@ export default class llamacpp_extension extends AIEngine {if (key === 'version_backend') {const valueStr = value as string- const [version, backend] = valueStr.split('/')+ // Async logic wrapped in IIFE since onSettingUpdate is void+ ;(async () => {+ try {+ const currentStored = this.getStoredBackendType() || undefined+ const result = await handleSettingUpdate(key, valueStr, currentStored)- // Store the backend type preference in localStorage only if it changed- if (backend) {- // Use the effective/migrated backend type for storage- const effectiveBackendType = mapOldBackendToNew(backend)- const currentStoredBackend = this.getStoredBackendType()+ if (result.backend_type_updated && result.effective_backend_type) {+ this.setStoredBackendType(result.effective_backend_type)+ logger.info(+ `Updated backend type preference to: ${result.effective_backend_type}`+ )+ }- // Compare with the effective type- if (currentStoredBackend !== effectiveBackendType) {- this.setStoredBackendType(effectiveBackendType)- logger.info(- `Updated backend type preference to: ${effectiveBackendType}`- )+ if (result.version && result.backend) {+ this.config.device = ''+ await this.ensureBackendReady(result.backend, result.version)+ }+ } catch (e) {+ logger.error('Error in onSettingUpdate async block:', e)}- }-- // Reset device setting when backend changes- this.config.device = ''-- const closure = async () => {- await this.ensureBackendReady(backend, version)- }- closure()+ })()} else if (key === 'auto_unload') {this.autoUnload = value as boolean} else if (key === 'llamacpp_env') {diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.tsindex 9dcf73ab6..a0d08c39b 100644--- a/extensions/llamacpp-extension/src/test/backend.test.ts+++ b/extensions/llamacpp-extension/src/test/backend.test.ts@@ -1,11 +1,9 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import {- listSupportedBackends,getBackendDir,getBackendExePath,isBackendInstalled,downloadBackend,- mapOldBackendToNew,} from '../backend'import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'import { fs, getJanDataFolderPath, events } from '@janhq/core'@@ -99,172 +97,6 @@ describe('Backend functions', () => {vi.restoreAllMocks()})- // ... (mapOldBackendToNew tests ...- describe('mapOldBackendToNew', () => {- it('should map old avx CPU backends to common_cpus (Windows)', () => {- expect(mapOldBackendToNew('win-avx2-x64')).toBe('win-common_cpus-x64')- expect(mapOldBackendToNew('win-avx512-x64')).toBe('win-common_cpus-x64')- expect(mapOldBackendToNew('win-avx-x64')).toBe('win-common_cpus-x64')- expect(mapOldBackendToNew('win-noavx-x64')).toBe('win-common_cpus-x64')- })-- it('should map old avx CPU backends to common_cpus (Linux)', () => {- expect(mapOldBackendToNew('linux-avx2-x64')).toBe('linux-common_cpus-x64')- expect(mapOldBackendToNew('linux-avx-x64')).toBe('linux-common_cpus-x64')- })-- it('should map old CUDA backends to new cuda-common_cpus (Windows)', () => {- expect(mapOldBackendToNew('win-avx512-cuda-cu12.0-x64')).toBe(- 'win-cuda-12-common_cpus-x64'- )- expect(mapOldBackendToNew('win-noavx-cuda-cu11.7-x64')).toBe(- 'win-cuda-11-common_cpus-x64'- )- })-- it('should map old CUDA backends to new cuda-common_cpus (Linux)', () => {- expect(mapOldBackendToNew('linux-avx2-cuda-cu12.0-x64')).toBe(- 'linux-cuda-12-common_cpus-x64'- )- expect(mapOldBackendToNew('linux-avx-cuda-cu11.7-x64')).toBe(- 'linux-cuda-11-common_cpus-x64'- )- })-- it('should map old Vulkan backend to new vulkan-common_cpus', () => {- expect(mapOldBackendToNew('linux-vulkan-x64')).toBe(- 'linux-vulkan-common_cpus-x64'- )- })-- it('should return already common backends as is', () => {- expect(mapOldBackendToNew('macos-arm64')).toBe('macos-arm64')- expect(mapOldBackendToNew('win-common_cpus-x64')).toBe(- 'win-common_cpus-x64'- )- expect(mapOldBackendToNew('linux-cuda-12-common_cpus-x64')).toBe(- 'linux-cuda-12-common_cpus-x64'- )- })- })-- describe('listSupportedBackends', () => {- it('should return new common_cpus backends when old avx assets exist for Windows x64', async () => {- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'windows',- cpu: {- arch: 'x86_64',- extensions: ['avx', 'avx2'],- },- gpus: [],- } as any)-- const mockReleases = [- {- tag_name: 'v1.0.0',- assets: [- { name: 'llama-v1.0.0-bin-win-avx2-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-avx-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-common_cpus-x64.tar.gz' },- ],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve({ releases: mockReleases }),- })-- vi.mocked(fs.readdirSync).mockResolvedValue([])-- const result = await listSupportedBackends()-- expect(result).toEqual([- { version: 'v1.0.0', backend: 'win-common_cpus-x64' },- { version: 'v1.0.0', backend: 'win-avx2-x64' },- { version: 'v1.0.0', backend: 'win-avx-x64' },- ])- })-- it('should return new cuda-12-common_cpus backends when old cuda assets exist for Windows', async () => {- // FIX: Force getSystemInfo to match the test scenario OS- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'windows',- cpu: {- arch: 'x86_64',- extensions: ['avx', 'avx2', 'avx512'],- },- gpus: [- {- driver_version: '530.41',- nvidia_info: { compute_capability: '8.6' },- },- ],- } as any)-- const mockReleases = [- {- tag_name: 'v1.0.0',- assets: [- { name: 'llama-v1.0.0-bin-win-avx512-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-cuda-12-common_cpus-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-avx2-cuda-cu12.0-x64.tar.gz' },- ],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve({ releases: mockReleases }),- })-- const result = await listSupportedBackends()-- expect(result).toContainEqual({- version: 'v1.0.0',- backend: 'win-cuda-12-common_cpus-x64',- })- expect(result).toContainEqual({- version: 'v1.0.0',- backend: 'win-avx512-cuda-cu12.0-x64',- })- expect(result).toContainEqual({- version: 'v1.0.0',- backend: 'win-avx2-cuda-cu12.0-x64',- })- expect(result.length).toBe(3)- })-- it('should return supported backends for macOS arm64 (no change expected)', async () => {- // FIX: Force getSystemInfo to match the test scenario OS- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'macos',- cpu: {- arch: 'aarch64',- extensions: [],- },- gpus: [],- } as any)-- const mockReleases = [- {- tag_name: 'v1.0.0',- assets: [{ name: 'llama-v1.0.0-bin-macos-arm64.tar.gz' }],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve({ releases: mockReleases }),- })-- vi.mocked(fs.readdirSync).mockResolvedValue([])-- const result = await listSupportedBackends()-- expect(result).toEqual([{ version: 'v1.0.0', backend: 'macos-arm64' }])- })- })describe('getBackendDir and getBackendExePath', () => {it('should use the specific backend name for directory path', async () => {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 93c0f405b..30433d7cb 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -17,7 +17,22 @@ const COMMANDS: &[&str] = &["estimate_kv_cache_size","get_model_size","is_model_supported",- "plan_model_load"+ "plan_model_load",+ // backend management+ "map_old_backend_to_new",+ "get_local_installed_backends",+ "list_supported_backends",+ "determine_supported_backends",+ "get_supported_features",+ "is_cuda_installed",+ "find_latest_version_for_backend",+ "prioritize_backends",+ "parse_backend_version",+ "check_backend_for_updates",+ "remove_old_backend_versions",+ "validate_backend_string",+ "should_migrate_backend",+ "handle_setting_update",];fn main() {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.tsindex b09b5cd66..5156f65b9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts@@ -5,6 +5,13 @@ import {UnloadResult,GgufMetadata,LlamacppConfig,+ BackendVersion,+ BackendFeatures,+ SupportedFeatures,+ GpuInfo,+ BestBackendResult,+ UpdateCheckResult,+ SettingUpdateResult,} from './types'// Helpers@@ -207,4 +214,158 @@ export async function cleanupLlamaProcesses(): Promise<void> {return await invoke('plugin:llamacpp|cleanup_llama_processes')}+// backend functions++/*+ * Helper function to map an old backend type string to its new, common equivalent.+ * This is used for migrating stored user preferences.+ */+export async function mapOldBackendToNew(oldBackend: string): Promise<string> {+ return await invoke<string>('plugin:llamacpp|map_old_backend_to_new', { oldBackend })+}++export async function getLocalInstalledBackendsInternal(+ backendsDir: string+): Promise<{ version: string; backend: string }[]> {+ return await invoke<{ version: string; backend: string }[]>(+ 'plugin:llamacpp|get_local_installed_backends',+ {+ backendsDir,+ }+ )+}++export function normalizeFeatures(features: any): BackendFeatures {+ return {+ cuda11: features.cuda11 || false,+ cuda12: features.cuda12 || false,+ cuda13: features.cuda13 || false,+ vulkan: features.vulkan || false,+ }+}++export async function determineSupportedBackends(+ osType: string,+ arch: string,+ features: BackendFeatures+): Promise<string[]> {+ return invoke<string[]>('plugin:llamacpp|determine_supported_backends', {+ osType,+ arch,+ features,+ })+}++export async function listSupportedBackendsFromRust(+ remoteBackendVersions: BackendVersion[],+ localBackendVersions: BackendVersion[]+): Promise<BackendVersion[]> {+ return invoke<BackendVersion[]>('plugin:llamacpp|list_supported_backends', {+ remoteBackendVersions,+ localBackendVersions,+ })+}++export async function getSupportedFeaturesFromRust(+ osType: string,+ cpuExtensions: string[],+ gpus: GpuInfo[]+): Promise<SupportedFeatures> {+ return invoke<SupportedFeatures>('plugin:llamacpp|get_supported_features', {+ osType,+ cpuExtensions,+ gpus,+ })+}++export async function isCudaInstalledFromRust(+ backendDir: string,+ version: string,+ osType: string,+ janDataFolderPath: string+): Promise<boolean> {+ return invoke<boolean>('plugin:llamacpp|is_cuda_installed', {+ backendDir,+ version,+ osType,+ janDataFolderPath,+ })+}++export async function findLatestVersionForBackend(+ versionBackends: BackendVersion[],+ backendType: string+): Promise<string | null> {+ return invoke('plugin:llamacpp|find_latest_version_for_backend', {+ versionBackends,+ backendType,+ })+}++export async function prioritizeBackends(+ versionBackends: BackendVersion[],+ hasEnoughGpuMemory: boolean+): Promise<BestBackendResult> {+ return invoke('plugin:llamacpp|prioritize_backends', {+ versionBackends,+ hasEnoughGpuMemory,+ })+}++export async function parseBackendVersion(+ versionString: string+): Promise<number> {+ return invoke('plugin:llamacpp|parse_backend_version', { versionString })+}++export async function checkBackendForUpdates(+ currentBackendString: string,+ versionBackends: BackendVersion[]+): Promise<UpdateCheckResult> {+ return invoke('plugin:llamacpp|check_backend_for_updates', {+ currentBackendString,+ versionBackends,+ })+}++export async function removeOldBackendVersions(+ backendsDir: string,+ latestVersion: string,+ backendType: string+): Promise<string[]> {+ return invoke('plugin:llamacpp|remove_old_backend_versions', {+ backendsDir,+ latestVersion,+ backendType,+ })+}++export async function validateBackendString(+ backendString: string+): Promise<[string, string]> {+ return invoke('plugin:llamacpp|validate_backend_string', { backendString })+}++export async function shouldMigrateBackend(+ storedBackendType: string,+ versionBackends: BackendVersion[]+): Promise<string | null> {+ return invoke('plugin:llamacpp|should_migrate_backend', {+ storedBackendType,+ versionBackends,+ })+}++export async function handleSettingUpdate(+ key: string,+ value: string,+ currentStoredBackend?: string+): Promise<SettingUpdateResult> {+ return invoke('plugin:llamacpp|handle_setting_update', {+ key,+ value,+ currentStoredBackend,+ })+}+export * from './types'diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex d79bcb87b..72e0676aa 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -121,3 +121,55 @@ export interface SystemMemory {totalMemory: number}+// backend types+export type BackendVersion = { version: string; backend: string }++export type BackendFeatures = {+ cuda11: boolean+ cuda12: boolean+ cuda13: boolean+ vulkan: boolean+}++export type SupportedFeatures = {+ avx: boolean+ avx2: boolean+ avx512: boolean+ cuda11: boolean+ cuda12: boolean+ cuda13: boolean+ vulkan: boolean+}+export type NvidiaInfo = {+ compute_capability: string+}++export type VulkanInfo = {+ api_version: string+}++export type GpuInfo = {+ driver_version: string+ nvidia_info?: NvidiaInfo | null+ vulkan_info?: VulkanInfo | null+}++export interface BestBackendResult {+ backend_string: string+ version: string+ backend_type: string+}++export interface UpdateCheckResult {+ update_needed: boolean+ new_version: string+ target_backend?: string+}++export interface SettingUpdateResult {+ backend_type_updated: boolean+ effective_backend_type?: string+ needs_backend_installation: boolean+ version?: string+ backend?: string+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.tomlnew file mode 100644index 000000000..3ba12c524--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-check-backend-for-updates"+description = "Enables the check_backend_for_updates command without any pre-configured scope."+commands.allow = ["check_backend_for_updates"]++[[permission]]+identifier = "deny-check-backend-for-updates"+description = "Denies the check_backend_for_updates command without any pre-configured scope."+commands.deny = ["check_backend_for_updates"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.tomlnew file mode 100644index 000000000..b01878f61--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-determine-supported-backends"+description = "Enables the determine_supported_backends command without any pre-configured scope."+commands.allow = ["determine_supported_backends"]++[[permission]]+identifier = "deny-determine-supported-backends"+description = "Denies the determine_supported_backends command without any pre-configured scope."+commands.deny = ["determine_supported_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.tomlnew file mode 100644index 000000000..22d0afbd9--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-find-latest-version-for-backend"+description = "Enables the find_latest_version_for_backend command without any pre-configured scope."+commands.allow = ["find_latest_version_for_backend"]++[[permission]]+identifier = "deny-find-latest-version-for-backend"+description = "Denies the find_latest_version_for_backend command without any pre-configured scope."+commands.deny = ["find_latest_version_for_backend"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.tomlnew file mode 100644index 000000000..ac1e5c94e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-local-installed-backends"+description = "Enables the get_local_installed_backends command without any pre-configured scope."+commands.allow = ["get_local_installed_backends"]++[[permission]]+identifier = "deny-get-local-installed-backends"+description = "Denies the get_local_installed_backends command without any pre-configured scope."+commands.deny = ["get_local_installed_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.tomlnew file mode 100644index 000000000..3d3e8dbd5--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-supported-features"+description = "Enables the get_supported_features command without any pre-configured scope."+commands.allow = ["get_supported_features"]++[[permission]]+identifier = "deny-get-supported-features"+description = "Denies the get_supported_features command without any pre-configured scope."+commands.deny = ["get_supported_features"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.tomlnew file mode 100644index 000000000..13ba58e8f--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-handle-setting-update"+description = "Enables the handle_setting_update command without any pre-configured scope."+commands.allow = ["handle_setting_update"]++[[permission]]+identifier = "deny-handle-setting-update"+description = "Denies the handle_setting_update command without any pre-configured scope."+commands.deny = ["handle_setting_update"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.tomlnew file mode 100644index 000000000..f5016fc33--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-is-cuda-installed"+description = "Enables the is_cuda_installed command without any pre-configured scope."+commands.allow = ["is_cuda_installed"]++[[permission]]+identifier = "deny-is-cuda-installed"+description = "Denies the is_cuda_installed command without any pre-configured scope."+commands.deny = ["is_cuda_installed"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.tomlnew file mode 100644index 000000000..efafa5d74--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-list-supported-backends"+description = "Enables the list_supported_backends command without any pre-configured scope."+commands.allow = ["list_supported_backends"]++[[permission]]+identifier = "deny-list-supported-backends"+description = "Denies the list_supported_backends command without any pre-configured scope."+commands.deny = ["list_supported_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.tomlnew file mode 100644index 000000000..0734db38c--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-map-old-backend-to-new"+description = "Enables the map_old_backend_to_new command without any pre-configured scope."+commands.allow = ["map_old_backend_to_new"]++[[permission]]+identifier = "deny-map-old-backend-to-new"+description = "Denies the map_old_backend_to_new command without any pre-configured scope."+commands.deny = ["map_old_backend_to_new"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.tomlnew file mode 100644index 000000000..20431da62--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-parse-backend-version"+description = "Enables the parse_backend_version command without any pre-configured scope."+commands.allow = ["parse_backend_version"]++[[permission]]+identifier = "deny-parse-backend-version"+description = "Denies the parse_backend_version command without any pre-configured scope."+commands.deny = ["parse_backend_version"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.tomlnew file mode 100644index 000000000..01ebe0883--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-prioritize-backends"+description = "Enables the prioritize_backends command without any pre-configured scope."+commands.allow = ["prioritize_backends"]++[[permission]]+identifier = "deny-prioritize-backends"+description = "Denies the prioritize_backends command without any pre-configured scope."+commands.deny = ["prioritize_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.tomlnew file mode 100644index 000000000..18ce48706--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-remove-old-backend-versions"+description = "Enables the remove_old_backend_versions command without any pre-configured scope."+commands.allow = ["remove_old_backend_versions"]++[[permission]]+identifier = "deny-remove-old-backend-versions"+description = "Denies the remove_old_backend_versions command without any pre-configured scope."+commands.deny = ["remove_old_backend_versions"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.tomlnew file mode 100644index 000000000..2b590c390--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-should-migrate-backend"+description = "Enables the should_migrate_backend command without any pre-configured scope."+commands.allow = ["should_migrate_backend"]++[[permission]]+identifier = "deny-should-migrate-backend"+description = "Denies the should_migrate_backend command without any pre-configured scope."+commands.deny = ["should_migrate_backend"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.tomlnew file mode 100644index 000000000..f2327ceb7--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-validate-backend-string"+description = "Enables the validate_backend_string command without any pre-configured scope."+commands.allow = ["validate_backend_string"]++[[permission]]+identifier = "deny-validate-backend-string"+description = "Denies the validate_backend_string command without any pre-configured scope."+commands.deny = ["validate_backend_string"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.mdindex faab24f25..15c371548 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md@@ -20,6 +20,20 @@ Default permissions for the llamacpp plugin- `allow-get-model-size`- `allow-is-model-supported`- `allow-plan-model-load`+- `allow-map-old-backend-to-new`+- `allow-get-local-installed-backends`+- `allow-list-supported-backends`+- `allow-determine-supported-backends`+- `allow-get-supported-features`+- `allow-is-cuda-installed`+- `allow-find-latest-version-for-backend`+- `allow-prioritize-backends`+- `allow-parse-backend-version`+- `allow-check-backend-for-updates`+- `allow-remove-old-backend-versions`+- `allow-validate-backend-string`+- `allow-should-migrate-backend`+- `allow-handle-setting-update`## Permission Table@@ -30,6 +44,32 @@ Default permissions for the llamacpp plugin</tr>+<tr>+<td>++`llamacpp:allow-check-backend-for-updates`++</td>+<td>++Enables the check_backend_for_updates command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-check-backend-for-updates`++</td>+<td>++Denies the check_backend_for_updates command without any pre-configured scope.++</td>+</tr>+<tr><td>@@ -59,6 +99,32 @@ Denies the cleanup_llama_processes command without any pre-configured scope.<tr><td>+`llamacpp:allow-determine-supported-backends`++</td>+<td>++Enables the determine_supported_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-determine-supported-backends`++</td>+<td>++Denies the determine_supported_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-estimate-kv-cache-size`</td>@@ -85,6 +151,32 @@ Denies the estimate_kv_cache_size command without any pre-configured scope.<tr><td>+`llamacpp:allow-find-latest-version-for-backend`++</td>+<td>++Enables the find_latest_version_for_backend command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-find-latest-version-for-backend`++</td>+<td>++Denies the find_latest_version_for_backend command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-find-session-by-model`</td>@@ -215,6 +307,32 @@ Denies the get_loaded_models command without any pre-configured scope.<tr><td>+`llamacpp:allow-get-local-installed-backends`++</td>+<td>++Enables the get_local_installed_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-get-local-installed-backends`++</td>+<td>++Denies the get_local_installed_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-get-model-size`</td>@@ -293,6 +411,84 @@ Denies the get_session_by_model command without any pre-configured scope.<tr><td>+`llamacpp:allow-get-supported-features`++</td>+<td>++Enables the get_supported_features command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-get-supported-features`++</td>+<td>++Denies the get_supported_features command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:allow-handle-setting-update`++</td>+<td>++Enables the handle_setting_update command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-handle-setting-update`++</td>+<td>++Denies the handle_setting_update command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:allow-is-cuda-installed`++</td>+<td>++Enables the is_cuda_installed command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-is-cuda-installed`++</td>+<td>++Denies the is_cuda_installed command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-is-model-supported`</td>@@ -345,6 +541,32 @@ Denies the is_process_running command without any pre-configured scope.<tr><td>+`llamacpp:allow-list-supported-backends`++</td>+<td>++Enables the list_supported_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-list-supported-backends`++</td>+<td>++Denies the list_supported_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-load-llama-model`</td>@@ -371,6 +593,58 @@ Denies the load_llama_model command without any pre-configured scope.<tr><td>+`llamacpp:allow-map-old-backend-to-new`++</td>+<td>++Enables the map_old_backend_to_new command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-map-old-backend-to-new`++</td>+<td>++Denies the map_old_backend_to_new command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:allow-parse-backend-version`++</td>+<td>++Enables the parse_backend_version command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-parse-backend-version`++</td>+<td>++Denies the parse_backend_version command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-plan-model-load`</td>@@ -397,6 +671,32 @@ Denies the plan_model_load command without any pre-configured scope.<tr><td>+`llamacpp:allow-prioritize-backends`++</td>+<td>++Enables the prioritize_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-prioritize-backends`++</td>+<td>++Denies the prioritize_backends command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-read-gguf-metadata`</td>@@ -423,6 +723,58 @@ Denies the read_gguf_metadata command without any pre-configured scope.<tr><td>+`llamacpp:allow-remove-old-backend-versions`++</td>+<td>++Enables the remove_old_backend_versions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-remove-old-backend-versions`++</td>+<td>++Denies the remove_old_backend_versions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:allow-should-migrate-backend`++</td>+<td>++Enables the should_migrate_backend command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-should-migrate-backend`++</td>+<td>++Denies the should_migrate_backend command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-unload-llama-model`</td>@@ -443,6 +795,32 @@ Enables the unload_llama_model command without any pre-configured scope.Denies the unload_llama_model command without any pre-configured scope.+</td>+</tr>++<tr>+<td>++`llamacpp:allow-validate-backend-string`++</td>+<td>++Enables the validate_backend_string command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-validate-backend-string`++</td>+<td>++Denies the validate_backend_string command without any pre-configured scope.+</td></tr></table>diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.tomlindex 91938e047..716f49f39 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml@@ -21,5 +21,21 @@ permissions = ["allow-estimate-kv-cache-size","allow-get-model-size","allow-is-model-supported",- "allow-plan-model-load"+ "allow-plan-model-load",++ # Backend management commands+ "allow-map-old-backend-to-new",+ "allow-get-local-installed-backends",+ "allow-list-supported-backends",+ "allow-determine-supported-backends",+ "allow-get-supported-features",+ "allow-is-cuda-installed",+ "allow-find-latest-version-for-backend",+ "allow-prioritize-backends",+ "allow-parse-backend-version",+ "allow-check-backend-for-updates",+ "allow-remove-old-backend-versions",+ "allow-validate-backend-string",+ "allow-should-migrate-backend",+ "allow-handle-setting-update"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.jsonindex 0dd243ff0..b30d75b04 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json@@ -294,6 +294,18 @@"PermissionKind": {"type": "string","oneOf": [+ {+ "description": "Enables the check_backend_for_updates command without any pre-configured scope.",+ "type": "string",+ "const": "allow-check-backend-for-updates",+ "markdownDescription": "Enables the check_backend_for_updates command without any pre-configured scope."+ },+ {+ "description": "Denies the check_backend_for_updates command without any pre-configured scope.",+ "type": "string",+ "const": "deny-check-backend-for-updates",+ "markdownDescription": "Denies the check_backend_for_updates command without any pre-configured scope."+ },{"description": "Enables the cleanup_llama_processes command without any pre-configured scope.","type": "string",@@ -306,6 +318,18 @@"const": "deny-cleanup-llama-processes","markdownDescription": "Denies the cleanup_llama_processes command without any pre-configured scope."},+ {+ "description": "Enables the determine_supported_backends command without any pre-configured scope.",+ "type": "string",+ "const": "allow-determine-supported-backends",+ "markdownDescription": "Enables the determine_supported_backends command without any pre-configured scope."+ },+ {+ "description": "Denies the determine_supported_backends command without any pre-configured scope.",+ "type": "string",+ "const": "deny-determine-supported-backends",+ "markdownDescription": "Denies the determine_supported_backends command without any pre-configured scope."+ },{"description": "Enables the estimate_kv_cache_size command without any pre-configured scope.","type": "string",@@ -318,6 +342,18 @@"const": "deny-estimate-kv-cache-size","markdownDescription": "Denies the estimate_kv_cache_size command without any pre-configured scope."},+ {+ "description": "Enables the find_latest_version_for_backend command without any pre-configured scope.",+ "type": "string",+ "const": "allow-find-latest-version-for-backend",+ "markdownDescription": "Enables the find_latest_version_for_backend command without any pre-configured scope."+ },+ {+ "description": "Denies the find_latest_version_for_backend command without any pre-configured scope.",+ "type": "string",+ "const": "deny-find-latest-version-for-backend",+ "markdownDescription": "Denies the find_latest_version_for_backend command without any pre-configured scope."+ },{"description": "Enables the find_session_by_model command without any pre-configured scope.","type": "string",@@ -378,6 +414,18 @@"const": "deny-get-loaded-models","markdownDescription": "Denies the get_loaded_models command without any pre-configured scope."},+ {+ "description": "Enables the get_local_installed_backends command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-local-installed-backends",+ "markdownDescription": "Enables the get_local_installed_backends command without any pre-configured scope."+ },+ {+ "description": "Denies the get_local_installed_backends command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-local-installed-backends",+ "markdownDescription": "Denies the get_local_installed_backends command without any pre-configured scope."+ },{"description": "Enables the get_model_size command without any pre-configured scope.","type": "string",@@ -414,6 +462,42 @@"const": "deny-get-session-by-model","markdownDescription": "Denies the get_session_by_model command without any pre-configured scope."},+ {+ "description": "Enables the get_supported_features command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-supported-features",+ "markdownDescription": "Enables the get_supported_features command without any pre-configured scope."+ },+ {+ "description": "Denies the get_supported_features command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-supported-features",+ "markdownDescription": "Denies the get_supported_features command without any pre-configured scope."+ },+ {+ "description": "Enables the handle_setting_update command without any pre-configured scope.",+ "type": "string",+ "const": "allow-handle-setting-update",+ "markdownDescription": "Enables the handle_setting_update command without any pre-configured scope."+ },+ {+ "description": "Denies the handle_setting_update command without any pre-configured scope.",+ "type": "string",+ "const": "deny-handle-setting-update",+ "markdownDescription": "Denies the handle_setting_update command without any pre-configured scope."+ },+ {+ "description": "Enables the is_cuda_installed command without any pre-configured scope.",+ "type": "string",+ "const": "allow-is-cuda-installed",+ "markdownDescription": "Enables the is_cuda_installed command without any pre-configured scope."+ },+ {+ "description": "Denies the is_cuda_installed command without any pre-configured scope.",+ "type": "string",+ "const": "deny-is-cuda-installed",+ "markdownDescription": "Denies the is_cuda_installed command without any pre-configured scope."+ },{"description": "Enables the is_model_supported command without any pre-configured scope.","type": "string",@@ -438,6 +522,18 @@"const": "deny-is-process-running","markdownDescription": "Denies the is_process_running command without any pre-configured scope."},+ {+ "description": "Enables the list_supported_backends command without any pre-configured scope.",+ "type": "string",+ "const": "allow-list-supported-backends",+ "markdownDescription": "Enables the list_supported_backends command without any pre-configured scope."+ },+ {+ "description": "Denies the list_supported_backends command without any pre-configured scope.",+ "type": "string",+ "const": "deny-list-supported-backends",+ "markdownDescription": "Denies the list_supported_backends command without any pre-configured scope."+ },{"description": "Enables the load_llama_model command without any pre-configured scope.","type": "string",@@ -450,6 +546,30 @@"const": "deny-load-llama-model","markdownDescription": "Denies the load_llama_model command without any pre-configured scope."},+ {+ "description": "Enables the map_old_backend_to_new command without any pre-configured scope.",+ "type": "string",+ "const": "allow-map-old-backend-to-new",+ "markdownDescription": "Enables the map_old_backend_to_new command without any pre-configured scope."+ },+ {+ "description": "Denies the map_old_backend_to_new command without any pre-configured scope.",+ "type": "string",+ "const": "deny-map-old-backend-to-new",+ "markdownDescription": "Denies the map_old_backend_to_new command without any pre-configured scope."+ },+ {+ "description": "Enables the parse_backend_version command without any pre-configured scope.",+ "type": "string",+ "const": "allow-parse-backend-version",+ "markdownDescription": "Enables the parse_backend_version command without any pre-configured scope."+ },+ {+ "description": "Denies the parse_backend_version command without any pre-configured scope.",+ "type": "string",+ "const": "deny-parse-backend-version",+ "markdownDescription": "Denies the parse_backend_version command without any pre-configured scope."+ },{"description": "Enables the plan_model_load command without any pre-configured scope.","type": "string",@@ -462,6 +582,18 @@"const": "deny-plan-model-load","markdownDescription": "Denies the plan_model_load command without any pre-configured scope."},+ {+ "description": "Enables the prioritize_backends command without any pre-configured scope.",+ "type": "string",+ "const": "allow-prioritize-backends",+ "markdownDescription": "Enables the prioritize_backends command without any pre-configured scope."+ },+ {+ "description": "Denies the prioritize_backends command without any pre-configured scope.",+ "type": "string",+ "const": "deny-prioritize-backends",+ "markdownDescription": "Denies the prioritize_backends command without any pre-configured scope."+ },{"description": "Enables the read_gguf_metadata command without any pre-configured scope.","type": "string",@@ -474,6 +606,30 @@"const": "deny-read-gguf-metadata","markdownDescription": "Denies the read_gguf_metadata command without any pre-configured scope."},+ {+ "description": "Enables the remove_old_backend_versions command without any pre-configured scope.",+ "type": "string",+ "const": "allow-remove-old-backend-versions",+ "markdownDescription": "Enables the remove_old_backend_versions command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_old_backend_versions command without any pre-configured scope.",+ "type": "string",+ "const": "deny-remove-old-backend-versions",+ "markdownDescription": "Denies the remove_old_backend_versions command without any pre-configured scope."+ },+ {+ "description": "Enables the should_migrate_backend command without any pre-configured scope.",+ "type": "string",+ "const": "allow-should-migrate-backend",+ "markdownDescription": "Enables the should_migrate_backend command without any pre-configured scope."+ },+ {+ "description": "Denies the should_migrate_backend command without any pre-configured scope.",+ "type": "string",+ "const": "deny-should-migrate-backend",+ "markdownDescription": "Denies the should_migrate_backend command without any pre-configured scope."+ },{"description": "Enables the unload_llama_model command without any pre-configured scope.","type": "string",@@ -487,10 +643,22 @@"markdownDescription": "Denies the unload_llama_model command without any pre-configured scope."},{- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`",+ "description": "Enables the validate_backend_string command without any pre-configured scope.",+ "type": "string",+ "const": "allow-validate-backend-string",+ "markdownDescription": "Enables the validate_backend_string command without any pre-configured scope."+ },+ {+ "description": "Denies the validate_backend_string command without any pre-configured scope.",+ "type": "string",+ "const": "deny-validate-backend-string",+ "markdownDescription": "Denies the validate_backend_string command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`","type": "string","const": "default",- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`"+ "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`"}]}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rsnew file mode 100644index 000000000..a1cc7707b--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs@@ -0,0 +1,1323 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::fs;+use std::path::PathBuf;++#[tauri::command]+pub fn map_old_backend_to_new(old_backend: String) -> String {+ let is_windows = old_backend.starts_with("win-");+ let is_linux = old_backend.starts_with("linux-");+ let os_prefix = if is_windows {+ "win-"+ } else if is_linux {+ "linux-"+ } else {+ ""+ };++ // Determine architecture suffix, defaulting to x64+ let arch_suffix = if old_backend.contains("-arm64") {+ "arm64"+ } else {+ "x64"+ };+ let is_x64 = arch_suffix == "x64";++ // Handle GPU backends+ if old_backend.contains("cuda-cu12.0") {+ // Migration from e.g., 'linux-avx2-cuda-cu12.0-x64' to 'linux-cuda-12-common_cpus-x64'+ return format!(+ "{}cuda-12-common_cpus-{}",+ os_prefix,+ if is_x64 { "x64" } else { arch_suffix }+ );+ } else if old_backend.contains("cuda-cu11.7") {+ // Migration from e.g., 'win-noavx-cuda-cu11.7-x64' to 'win-cuda-11-common_cpus-x64'+ return format!(+ "{}cuda-11-common_cpus-{}",+ os_prefix,+ if is_x64 { "x64" } else { arch_suffix }+ );+ } else if old_backend.contains("vulkan") {+ // If it's already the new name, return it+ if old_backend.contains("vulkan-common_cpus") {+ return old_backend;+ }++ // Migration from e.g., 'linux-vulkan-x64' to 'linux-vulkan-common_cpus-x64'+ return format!(+ "{}vulkan-common_cpus-{}",+ os_prefix,+ if is_x64 { "x64" } else { arch_suffix }+ );+ }++ // Handle CPU-only backends (avx, avx2, avx512, noavx)+ let is_old_cpu_backend = old_backend.contains("avx512")+ || old_backend.contains("avx2")+ || old_backend.contains("avx-x64") // Check for 'avx' but not as part of 'avx2' or 'avx512'+ || old_backend.contains("noavx-x64");++ if is_old_cpu_backend {+ // Migration from e.g., 'win-avx512-x64' to 'win-common_cpus-x64'+ return format!(+ "{}common_cpus-{}",+ os_prefix,+ if is_x64 { "x64" } else { arch_suffix }+ );+ }++ // Return original if it doesn't match a pattern that needs migration+ old_backend+}++#[derive(Serialize, Deserialize)]+pub struct InstalledBackend {+ version: String,+ backend: String,+}++#[tauri::command]+pub async fn get_local_installed_backends(+ backends_dir: String,+) -> Result<Vec<InstalledBackend>, String> {+ let mut local: Vec<InstalledBackend> = Vec::new();+ let backends_path = PathBuf::from(&backends_dir);++ // Check if backends directory exists+ if !backends_path.exists() {+ return Ok(local);+ }++ // Read version directories+ let version_dirs = fs::read_dir(&backends_path)+ .map_err(|e| format!("Failed to read backends directory: {}", e))?;++ for version_entry in version_dirs {+ let version_entry =+ version_entry.map_err(|e| format!("Failed to read version entry: {}", e))?;++ let version_path = version_entry.path();++ // Check if it's a directory+ let metadata =+ fs::metadata(&version_path).map_err(|e| format!("Failed to get metadata: {}", e))?;++ if !metadata.is_dir() {+ continue;+ }++ // Get version name from path+ let version_name = match version_path.file_name() {+ Some(name) => name.to_string_lossy().to_string(),+ None => continue,+ };++ // Read backend types in this version directory+ let backend_types = fs::read_dir(&version_path)+ .map_err(|e| format!("Failed to read version directory: {}", e))?;++ for backend_entry in backend_types {+ let backend_entry =+ backend_entry.map_err(|e| format!("Failed to read backend entry: {}", e))?;++ let backend_path = backend_entry.path();++ // Get backend name from path+ let backend_name = match backend_path.file_name() {+ Some(name) => name.to_string_lossy().to_string(),+ None => continue,+ };++ // Check if backend is actually installed+ if is_backend_installed(&backend_path) {+ local.push(InstalledBackend {+ version: version_name.clone(),+ backend: backend_name,+ });+ }+ }+ }++ Ok(local)+}++/// Helper function to check if a backend is properly installed+/// Checks for the existence of llama-server executable in the expected locations+fn is_backend_installed(backend_dir: &PathBuf) -> bool {+ if !backend_dir.exists() || !backend_dir.is_dir() {+ return false;+ }++ // Determine executable name based on platform+ let exe_name = if cfg!(target_os = "windows") {+ "llama-server.exe"+ } else {+ "llama-server"+ };++ // First check if build directory exists (build/bin/llama-server)+ let build_path = backend_dir.join("build").join("bin").join(exe_name);+ if build_path.exists() {+ return true;+ }++ // Otherwise check root directory (llama-server)+ let root_path = backend_dir.join(exe_name);+ root_path.exists()+}++#[derive(Serialize, Deserialize, Clone)]+pub struct BackendInfo {+ version: String,+ backend: String,+}++#[derive(Deserialize)]+pub struct SystemFeatures {+ cuda11: bool,+ cuda12: bool,+ cuda13: bool,+ vulkan: bool,+}++#[derive(Serialize)]+pub struct SupportedBackendsResult {+ supported_backend_names: Vec<String>,+ merged_backends: Vec<BackendInfo>,+}++#[tauri::command]+pub fn determine_supported_backends(+ os_type: String,+ arch: String,+ features: SystemFeatures,+) -> Result<Vec<String>, String> {+ let sys_type = format!("{}-{}", os_type, arch);+ let mut supported_backends: Vec<String> = Vec::new();++ // Determine supported backends based on system type and features+ match sys_type.as_str() {+ "windows-x86_64" => {+ supported_backends.push("win-common_cpus-x64".to_string());+ if features.cuda11 {+ supported_backends.push("win-cuda-11-common_cpus-x64".to_string());+ }+ if features.cuda12 {+ supported_backends.push("win-cuda-12-common_cpus-x64".to_string());+ }+ if features.cuda13 {+ supported_backends.push("win-cuda-13-common_cpus-x64".to_string());+ }+ if features.vulkan {+ supported_backends.push("win-vulkan-common_cpus-x64".to_string());+ }+ }+ "windows-aarch64" | "windows-arm64" => {+ supported_backends.push("win-arm64".to_string());+ }+ "linux-x86_64" | "linux-x86" => {+ supported_backends.push("linux-common_cpus-x64".to_string());+ if features.cuda11 {+ supported_backends.push("linux-cuda-11-common_cpus-x64".to_string());+ }+ if features.cuda12 {+ supported_backends.push("linux-cuda-12-common_cpus-x64".to_string());+ }+ if features.cuda13 {+ supported_backends.push("linux-cuda-13-common_cpus-x64".to_string());+ }+ if features.vulkan {+ supported_backends.push("linux-vulkan-common_cpus-x64".to_string());+ }+ }+ "linux-aarch64" | "linux-arm64" => {+ supported_backends.push("linux-arm64".to_string());+ }+ "macos-x86_64" | "macos-x86" => {+ supported_backends.push("macos-x64".to_string());+ }+ "macos-aarch64" | "macos-arm64" => {+ supported_backends.push("macos-arm64".to_string());+ }+ _ => {+ return Err(format!("Unsupported system type: {}", sys_type));+ }+ }++ Ok(supported_backends)+}++#[tauri::command]+pub async fn list_supported_backends(+ remote_backend_versions: Vec<BackendInfo>,+ local_backend_versions: Vec<BackendInfo>,+) -> Result<Vec<BackendInfo>, String> {+ // Merge remote and local backend versions with deduplication+ let mut merged_map: HashMap<String, BackendInfo> = HashMap::new();++ for entry in remote_backend_versions {+ let key = format!("{}|{}", entry.version, entry.backend);+ merged_map.insert(key, entry);+ }++ for entry in local_backend_versions {+ let key = format!("{}|{}", entry.version, entry.backend);+ merged_map.insert(key, entry);+ }++ // Convert to vector and sort+ let mut merged: Vec<BackendInfo> = merged_map.into_values().collect();++ // Sort newest version first; if versions tie, sort by backend name+ merged.sort_by(|a, b| {+ let version_cmp = b.version.cmp(&a.version);+ if version_cmp == std::cmp::Ordering::Equal {+ a.backend.cmp(&b.backend)+ } else {+ version_cmp+ }+ });++ Ok(merged)+}++#[derive(Serialize, Deserialize)]+pub struct SupportedFeatures {+ avx: bool,+ avx2: bool,+ avx512: bool,+ cuda11: bool,+ cuda12: bool,+ cuda13: bool,+ vulkan: bool,+}++#[derive(Deserialize)]+pub struct GpuInfo {+ driver_version: String,+ nvidia_info: Option<NvidiaInfo>,+ vulkan_info: Option<VulkanInfo>,+}++#[derive(Deserialize)]+pub struct NvidiaInfo {+ compute_capability: String,+}++#[derive(Deserialize)]+pub struct VulkanInfo {+ api_version: String,+}++#[tauri::command]+pub fn get_supported_features(+ os_type: String,+ cpu_extensions: Vec<String>,+ gpus: Vec<GpuInfo>,+) -> Result<SupportedFeatures, String> {+ let mut features = SupportedFeatures {+ avx: cpu_extensions.contains(&"avx".to_string()),+ avx2: cpu_extensions.contains(&"avx2".to_string()),+ avx512: cpu_extensions.contains(&"avx512".to_string()),+ cuda11: false,+ cuda12: false,+ cuda13: false,+ vulkan: false,+ };++ // https://docs.nvidia.com/deploy/cuda-compatibility/#cuda-11-and-later-defaults-to-minor-version-compatibility+ let (min_cuda11_driver, min_cuda12_driver, min_cuda13_driver) = match os_type.as_str() {+ "linux" => ("450.80.02", "525.60.13", "580"),+ "windows" => ("452.39", "527.41", "580"),+ _ => return Ok(features), // Other OS types don't support CUDA+ };++ // Check GPU features+ for gpu_info in gpus {+ let driver_version = &gpu_info.driver_version;++ // Check CUDA support+ if gpu_info.nvidia_info.is_some() {+ if compare_versions(driver_version, min_cuda11_driver) >= 0 {+ features.cuda11 = true;+ }+ if compare_versions(driver_version, min_cuda12_driver) >= 0 {+ features.cuda12 = true;+ }+ if compare_versions(driver_version, min_cuda13_driver) >= 0 {+ features.cuda13 = true;+ }+ }++ // Check Vulkan support+ if gpu_info.vulkan_info.is_some() {+ features.vulkan = true;+ }+ }++ Ok(features)+}++/// Compare version strings+/// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2+fn compare_versions(v1: &str, v2: &str) -> i32 {+ let parts1: Vec<&str> = v1.split('.').collect();+ let parts2: Vec<&str> = v2.split('.').collect();++ let max_len = parts1.len().max(parts2.len());++ for i in 0..max_len {+ let num1 = parts1+ .get(i)+ .and_then(|s| s.parse::<u32>().ok())+ .unwrap_or(0);+ let num2 = parts2+ .get(i)+ .and_then(|s| s.parse::<u32>().ok())+ .unwrap_or(0);++ match num1.cmp(&num2) {+ std::cmp::Ordering::Less => return -1,+ std::cmp::Ordering::Greater => return 1,+ std::cmp::Ordering::Equal => continue,+ }+ }++ 0+}++#[tauri::command]+pub async fn is_cuda_installed(+ backend_dir: String,+ version: String,+ os_type: String,+ jan_data_folder_path: String,+) -> Result<bool, String> {+ // Define library name lookup table+ let mut libname_lookup: HashMap<String, &str> = HashMap::new();+ libname_lookup.insert("windows-11.7".to_string(), "cudart64_110.dll");+ libname_lookup.insert("windows-12.0".to_string(), "cudart64_12.dll");+ libname_lookup.insert("windows-13.0".to_string(), "cudart64_13.dll");+ libname_lookup.insert("linux-11.7".to_string(), "libcudart.so.11.0");+ libname_lookup.insert("linux-12.0".to_string(), "libcudart.so.12");+ libname_lookup.insert("linux-13.0".to_string(), "libcudart.so.13");++ let key = format!("{}-{}", os_type, version);++ // Check if the OS-version combination is supported+ let libname = match libname_lookup.get(&key) {+ Some(name) => *name,+ None => return Ok(false),+ };++ // Expected new location: backend_dir/build/bin/libname+ let new_path = std::path::PathBuf::from(&backend_dir)+ .join("build")+ .join("bin")+ .join(libname);++ if new_path.exists() {+ return Ok(true);+ }++ // Old location (used by older builds): jan_data_folder_path/llamacpp/lib/libname+ let old_path = std::path::PathBuf::from(&jan_data_folder_path)+ .join("llamacpp")+ .join("lib")+ .join(libname);++ if old_path.exists() {+ // Ensure target directory exists+ let target_dir = PathBuf::from(&backend_dir).join("build").join("bin");++ if !target_dir.exists() {+ fs::create_dir_all(&target_dir)+ .map_err(|e| format!("Failed to create target directory: {}", e))?;+ }++ // Move old lib to the correct new location+ match fs::rename(&old_path, &new_path) {+ Ok(_) => {+ log::info!("[CUDA] Migrated {} from old path to new location.", libname);+ return Ok(true);+ }+ Err(err) => {+ log::warn!("[CUDA] Failed to move old library: {}", err);+ // Return false since the migration failed+ return Ok(false);+ }+ }+ }++ Ok(false)+}++#[derive(Serialize, Deserialize, Debug)]+pub struct BestBackendResult {+ pub backend_string: String,+ pub version: String,+ pub backend_type: String,+}++#[derive(Serialize, Deserialize, Debug)]+pub struct UpdateCheckResult {+ pub update_needed: bool,+ pub new_version: String,+ pub target_backend: Option<String>,+}++#[derive(Serialize, Deserialize, Debug)]+pub struct BackendConfigResult {+ pub best_available: String,+ pub effective_backend: String,+ pub backend_downloaded: bool,+ pub settings_updated: bool,+}++#[tauri::command]+pub fn find_latest_version_for_backend(+ version_backends: Vec<BackendInfo>,+ backend_type: String,+) -> Option<String> {+ let mut matching_backends: Vec<BackendInfo> = version_backends+ .into_iter()+ .filter(|vb| map_old_backend_to_new(vb.backend.clone()) == backend_type)+ .collect();++ if matching_backends.is_empty() {+ return None;+ }++ // Sort by version (newest first)+ matching_backends.sort_by(|a, b| b.version.cmp(&a.version));++ // Return the full string including the original asset name+ Some(format!(+ "{}/{}",+ matching_backends[0].version, matching_backends[0].backend+ ))+}++#[tauri::command]+pub async fn prioritize_backends(+ version_backends: Vec<BackendInfo>,+ has_enough_gpu_memory: bool,+) -> Result<BestBackendResult, String> {+ if version_backends.is_empty() {+ return Err("No backends available".to_string());+ }++ // Priority list based on GPU memory+ let backend_priorities: Vec<&str> = if has_enough_gpu_memory {+ vec![+ "cuda-cu13.0",+ "cuda-cu12.0",+ "cuda-cu11.7",+ "vulkan",+ "common_cpus",+ "avx512",+ "avx2",+ "avx",+ "noavx",+ "arm64",+ "x64",+ ]+ } else {+ vec![+ "cuda-cu13.0",+ "cuda-cu12.0",+ "cuda-cu11.7",+ "common_cpus",+ "avx512",+ "avx2",+ "avx",+ "noavx",+ "arm64",+ "x64",+ "vulkan",+ ]+ };++ // Find best matching backend+ for priority_category in backend_priorities {+ let matching_backends: Vec<&BackendInfo> = version_backends+ .iter()+ .filter(|vb| {+ let category = get_backend_category(&vb.backend);+ category.as_deref() == Some(priority_category)+ })+ .collect();++ if !matching_backends.is_empty() {+ let best = matching_backends[0];+ log::info!(+ "Determined best available backend: {}/{} (Category: \"{}\")",+ best.version,+ best.backend,+ priority_category+ );++ return Ok(BestBackendResult {+ backend_string: format!("{}/{}", best.version, best.backend),+ version: best.version.clone(),+ backend_type: best.backend.clone(),+ });+ }+ }++ // Fallback to newest version+ let fallback = &version_backends[0];+ log::info!("Fallback to: {}/{}", fallback.version, fallback.backend);++ Ok(BestBackendResult {+ backend_string: format!("{}/{}", fallback.version, fallback.backend),+ version: fallback.version.clone(),+ backend_type: fallback.backend.clone(),+ })+}++fn get_backend_category(backend_string: &str) -> Option<String> {+ if backend_string.contains("cuda-13-common_cpus") {+ return Some("cuda-cu13.0".to_string());+ }+ if backend_string.contains("cuda-12-common_cpus") || backend_string.contains("cu12.0") {+ return Some("cuda-cu12.0".to_string());+ }+ if backend_string.contains("cuda-11-common_cpus") || backend_string.contains("cu11.7") {+ return Some("cuda-cu11.7".to_string());+ }+ if backend_string.contains("vulkan") {+ return Some("vulkan".to_string());+ }+ if backend_string.contains("common_cpus") {+ return Some("common_cpus".to_string());+ }+ if backend_string.contains("avx512") {+ return Some("avx512".to_string());+ }+ if backend_string.contains("avx2") {+ return Some("avx2".to_string());+ }+ if backend_string.contains("avx")+ && !backend_string.contains("avx2")+ && !backend_string.contains("avx512")+ {+ return Some("avx".to_string());+ }+ if backend_string.contains("noavx") {+ return Some("noavx".to_string());+ }+ if backend_string.ends_with("arm64") {+ return Some("arm64".to_string());+ }+ if backend_string.ends_with("x64") {+ return Some("x64".to_string());+ }+ None+}++#[tauri::command]+pub fn parse_backend_version(version_string: String) -> u32 {+ // Remove any leading non-digit characters+ let numeric = version_string.trim_start_matches(|c: char| !c.is_ascii_digit());+ numeric.parse::<u32>().unwrap_or(0)+}++#[tauri::command]+pub async fn check_backend_for_updates(+ current_backend_string: String,+ version_backends: Vec<BackendInfo>,+) -> Result<UpdateCheckResult, String> {+ let parts: Vec<&str> = current_backend_string.split('/').collect();+ if parts.len() != 2 {+ return Err(format!(+ "Invalid current backend format: {}",+ current_backend_string+ ));+ }++ let current_version = parts[0];+ let current_backend = parts[1];++ // Get the effective/migrated backend type+ let current_effective_backend_type = map_old_backend_to_new(current_backend.to_string());++ // Find the latest version for the current backend type+ let target_backend_string =+ find_latest_version_for_backend(version_backends, current_effective_backend_type.clone());++ if target_backend_string.is_none() {+ log::warn!(+ "No available versions found for current backend type: {}",+ current_effective_backend_type+ );+ return Ok(UpdateCheckResult {+ update_needed: false,+ new_version: "0".to_string(),+ target_backend: None,+ });+ }++ let target_backend_string = target_backend_string.unwrap();+ let target_parts: Vec<&str> = target_backend_string.split('/').collect();+ let latest_version = target_parts[0];++ // Check if update is needed+ if parse_backend_version(latest_version.to_string())+ > parse_backend_version(current_version.to_string())+ {+ log::info!(+ "New update available: {} -> {}",+ latest_version,+ target_backend_string+ );+ Ok(UpdateCheckResult {+ update_needed: true,+ new_version: latest_version.to_string(),+ target_backend: Some(target_backend_string),+ })+ } else {+ log::info!(+ "Already at latest version: {} = {}",+ current_version,+ latest_version+ );+ Ok(UpdateCheckResult {+ update_needed: false,+ new_version: "0".to_string(),+ target_backend: None,+ })+ }+}++#[tauri::command]+pub async fn remove_old_backend_versions(+ backends_dir: String,+ latest_version: String,+ backend_type: String,+) -> Result<Vec<String>, String> {+ let mut removed_paths = Vec::new();+ let backends_path = PathBuf::from(&backends_dir);++ if !backends_path.exists() {+ return Ok(removed_paths);+ }++ let version_dirs = fs::read_dir(&backends_path)+ .map_err(|e| format!("Failed to read backends directory: {}", e))?;++ for version_entry in version_dirs {+ let version_entry =+ version_entry.map_err(|e| format!("Failed to read version entry: {}", e))?;++ let version_path = version_entry.path();+ let version_name = match version_path.file_name() {+ Some(name) => name.to_string_lossy().to_string(),+ None => continue,+ };++ // Skip the latest version+ if version_name == latest_version {+ continue;+ }++ // Check if this version has the specific backend type+ let backend_type_path = version_path.join(&backend_type);++ if backend_type_path.exists() {+ // Verify it's actually installed before removing+ if is_backend_installed(&backend_type_path) {+ match fs::remove_dir_all(&backend_type_path) {+ Ok(_) => {+ log::info!(+ "Removed old version of {}: {}",+ backend_type,+ backend_type_path.display()+ );+ removed_paths.push(backend_type_path.to_string_lossy().to_string());+ }+ Err(e) => {+ log::warn!(+ "Failed to remove old backend version: {} - {}",+ backend_type_path.display(),+ e+ );+ }+ }+ }+ }+ }++ Ok(removed_paths)+}++#[tauri::command]+pub fn validate_backend_string(backend_string: String) -> Result<(String, String), String> {+ let parts: Vec<&str> = backend_string.split('/').collect();+ if parts.len() != 2 {+ return Err(format!("Invalid backend format: {}", backend_string));+ }++ let version = parts[0].trim();+ let backend = parts[1].trim();++ if version.is_empty() || backend.is_empty() {+ return Err(format!("Invalid backend format: {}", backend_string));+ }++ Ok((version.to_string(), backend.to_string()))+}++#[tauri::command]+pub fn should_migrate_backend(+ stored_backend_type: String,+ version_backends: Vec<BackendInfo>,+) -> Result<Option<String>, String> {+ let mapped_new_backend_type = map_old_backend_to_new(stored_backend_type.clone());+ let is_migration_needed = mapped_new_backend_type != stored_backend_type;++ if !is_migration_needed {+ return Ok(None);+ }++ // Check if the new, mapped backend is available+ let is_new_type_available = version_backends+ .iter()+ .any(|vb| map_old_backend_to_new(vb.backend.clone()) == mapped_new_backend_type);++ if is_new_type_available {+ log::info!(+ "Migration needed from '{}' to '{}'",+ stored_backend_type,+ mapped_new_backend_type+ );+ Ok(Some(mapped_new_backend_type))+ } else {+ log::warn!(+ "Migration from '{}' to '{}' skipped: New type not available",+ stored_backend_type,+ mapped_new_backend_type+ );+ Ok(None)+ }+}++// ============================================================================+// Settings Update Handler+// ============================================================================++#[derive(Serialize, Deserialize, Debug)]+pub struct SettingUpdateResult {+ pub backend_type_updated: bool,+ pub effective_backend_type: Option<String>,+ pub needs_backend_installation: bool,+ pub version: Option<String>,+ pub backend: Option<String>,+}++#[tauri::command]+pub fn handle_setting_update(+ key: String,+ value: String,+ current_stored_backend: Option<String>,+) -> Result<SettingUpdateResult, String> {+ if key != "version_backend" {+ // For non-backend settings, return a simple result+ return Ok(SettingUpdateResult {+ backend_type_updated: false,+ effective_backend_type: None,+ needs_backend_installation: false,+ version: None,+ backend: None,+ });+ }++ // Handle version_backend update+ let parts: Vec<&str> = value.split('/').collect();+ if parts.len() != 2 {+ return Err(format!("Invalid backend format: {}", value));+ }++ let version = parts[0].to_string();+ let backend = parts[1].to_string();++ if version.is_empty() || backend.is_empty() {+ return Err(format!("Invalid backend format: {}", value));+ }++ // Get the effective/migrated backend type+ let effective_backend_type = map_old_backend_to_new(backend.clone());++ // Check if backend type changed+ let backend_type_updated = match current_stored_backend {+ Some(stored) => stored != effective_backend_type,+ None => true,+ };++ log::info!(+ "Setting update for version_backend: {}/{} (effective: {})",+ version,+ backend,+ effective_backend_type+ );++ Ok(SettingUpdateResult {+ backend_type_updated,+ effective_backend_type: Some(effective_backend_type),+ needs_backend_installation: true,+ version: Some(version),+ backend: Some(backend),+ })+}++// ---------------------------- Tests ------------------------------------------++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs::File;+ use std::io::Write;++ // --- Tests for map_old_backend_to_new ---++ #[test]+ fn test_map_old_backend_to_new_cuda() {+ // Linux CUDA 12+ assert_eq!(+ map_old_backend_to_new("linux-avx2-cuda-cu12.0-x64".to_string()),+ "linux-cuda-12-common_cpus-x64"+ );+ // Windows CUDA 11 (noavx)+ assert_eq!(+ map_old_backend_to_new("win-noavx-cuda-cu11.7-x64".to_string()),+ "win-cuda-11-common_cpus-x64"+ );+ }++ #[test]+ fn test_map_old_backend_to_new_vulkan() {+ // Linux Vulkan+ assert_eq!(+ map_old_backend_to_new("linux-vulkan-x64".to_string()),+ "linux-vulkan-common_cpus-x64"+ );+ // Already new format+ assert_eq!(+ map_old_backend_to_new("win-vulkan-common_cpus-x64".to_string()),+ "win-vulkan-common_cpus-x64"+ );+ }++ #[test]+ fn test_map_old_backend_to_new_cpu() {+ // AVX512 migration+ assert_eq!(+ map_old_backend_to_new("win-avx512-x64".to_string()),+ "win-common_cpus-x64"+ );+ // AVX2 migration+ assert_eq!(+ map_old_backend_to_new("linux-avx2-x64".to_string()),+ "linux-common_cpus-x64"+ );+ }++ #[test]+ fn test_map_old_backend_to_new_arch() {+ // ARM64 detection+ assert_eq!(+ map_old_backend_to_new("linux-arm64".to_string()),+ "linux-arm64" // Does not match specific migration patterns, returns original+ );+ }++ // --- Tests for compare_versions (Private helper) ---++ #[test]+ fn test_compare_versions() {+ assert_eq!(compare_versions("1.0", "2.0"), -1);+ assert_eq!(compare_versions("2.0", "1.0"), 1);+ assert_eq!(compare_versions("1.0", "1.0"), 0);+ assert_eq!(compare_versions("1.0.1", "1.0"), 1);+ assert_eq!(compare_versions("450.80.02", "450.80.02"), 0);+ assert_eq!(compare_versions("525.60.13", "450.80.02"), 1);+ assert_eq!(compare_versions("10", "2"), 1); // Numeric check, not string+ }++ // --- Tests for get_supported_features ---++ #[test]+ fn test_get_supported_features_cpu_only() {+ let gpus = vec![];+ let exts = vec!["avx".to_string(), "avx2".to_string()];++ let result = get_supported_features("linux".to_string(), exts, gpus).unwrap();++ assert!(result.avx);+ assert!(result.avx2);+ assert!(!result.avx512);+ assert!(!result.cuda11);+ assert!(!result.vulkan);+ }++ #[test]+ fn test_get_supported_features_cuda_linux() {+ // Driver 525.60.13 supports CUDA 12 on Linux+ let gpus = vec![GpuInfo {+ driver_version: "530.00".to_string(),+ nvidia_info: Some(NvidiaInfo {+ compute_capability: "8.0".to_string(),+ }),+ vulkan_info: None,+ }];++ let result = get_supported_features("linux".to_string(), vec![], gpus).unwrap();++ assert!(result.cuda11); // 530 > 450+ assert!(result.cuda12); // 530 > 525+ assert!(!result.cuda13); // 530 < 580+ }++ #[test]+ fn test_get_supported_features_vulkan() {+ let gpus = vec![GpuInfo {+ driver_version: "0.0".to_string(),+ nvidia_info: None,+ vulkan_info: Some(VulkanInfo {+ api_version: "1.3".to_string(),+ }),+ }];++ let result = get_supported_features("windows".to_string(), vec![], gpus).unwrap();++ assert!(result.vulkan);+ assert!(!result.cuda11);+ }++ // --- Tests for determine_supported_backends ---++ #[test]+ fn test_determine_supported_backends_windows_all() {+ let features = SystemFeatures {+ cuda11: true,+ cuda12: true,+ cuda13: false,+ vulkan: true,+ };++ let result =+ determine_supported_backends("windows".to_string(), "x86_64".to_string(), features)+ .unwrap();++ assert!(result.contains(&"win-common_cpus-x64".to_string()));+ assert!(result.contains(&"win-cuda-11-common_cpus-x64".to_string()));+ assert!(result.contains(&"win-cuda-12-common_cpus-x64".to_string()));+ assert!(result.contains(&"win-vulkan-common_cpus-x64".to_string()));+ assert!(!result.contains(&"win-cuda-13-common_cpus-x64".to_string()));+ }++ #[test]+ fn test_determine_supported_backends_mac_arm() {+ let features = SystemFeatures {+ cuda11: false,+ cuda12: false,+ cuda13: false,+ vulkan: false,+ };++ let result =+ determine_supported_backends("macos".to_string(), "arm64".to_string(), features)+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(result[0], "macos-arm64");+ }++ // --- Tests for list_supported_backends ---++ #[tokio::test]+ async fn test_list_supported_backends_sorting_and_dedup() {+ let remote = vec![+ BackendInfo {+ version: "b7523".into(),+ backend: "backend-a".into(),+ },+ BackendInfo {+ version: "b7523".into(),+ backend: "backend-b".into(),+ },+ ];++ let local = vec![+ // Should override remote+ BackendInfo {+ version: "b7523".into(),+ backend: "backend-a".into(),+ },+ // Newer version+ BackendInfo {+ version: "b7524".into(),+ backend: "backend-c".into(),+ },+ ];++ let result = list_supported_backends(remote, local).await.unwrap();++ // Expect 3 items: b7524(c), b7523(a), b7523(b)+ assert_eq!(result.len(), 3);++ // Check sorting: Version desc (b7524 > b7523)+ assert_eq!(result[0].version, "b7524");+ assert_eq!(result[1].version, "b7523");+ assert_eq!(result[2].version, "b7523");++ // Check sorting: Backend asc for same version+ // backend-a comes before backend-b+ assert_eq!(result[1].backend, "backend-a");+ assert_eq!(result[2].backend, "backend-b");+ }++ // --- Tests for parse_backend_version ---+ #[test]+ fn test_parse_backend_version() {+ assert_eq!(parse_backend_version("b7523".to_string()), 7523);+ assert_eq!(parse_backend_version("b7524".to_string()), 7524);+ assert_eq!(parse_backend_version("7525".to_string()), 7525);+ assert_eq!(parse_backend_version("v100".to_string()), 100);+ assert_eq!(parse_backend_version("invalid".to_string()), 0);+ // Note: "v1.0.0" would fail to parse as u32 due to dots, returning 0+ assert_eq!(parse_backend_version("v1.0.0".to_string()), 0);+ }+ // --- Filesystem Integration Tests ---++ #[tokio::test]+ async fn test_get_local_installed_backends() {+ let temp_dir = tempfile::tempdir().unwrap();+ let root = temp_dir.path();++ // Structure:+ // root/+ // b7523/+ // backend-a/+ // build/bin/llama-server (exe)+ // backend-empty/ (no exe)++ let v1_path = root.join("b7523");+ let backend_a = v1_path.join("backend-a");+ let backend_empty = v1_path.join("backend-empty");++ fs::create_dir_all(&backend_a.join("build").join("bin")).unwrap();+ fs::create_dir_all(&backend_empty).unwrap();++ // Create mock executable+ let exe_name = if cfg!(target_os = "windows") {+ "llama-server.exe"+ } else {+ "llama-server"+ };+ File::create(backend_a.join("build").join("bin").join(exe_name)).unwrap();++ let result = get_local_installed_backends(root.to_string_lossy().to_string())+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(result[0].version, "b7523");+ assert_eq!(result[0].backend, "backend-a");+ }++ #[tokio::test]+ async fn test_is_cuda_installed_migration() {+ let backend_dir = tempfile::tempdir().unwrap();+ let jan_data_dir = tempfile::tempdir().unwrap();++ let version = "12.0";+ let os_type = "linux"; // Maps to libcudart.so.12++ // Setup Old Path: jan_data/llamacpp/lib/libcudart.so.12+ let old_lib_dir = jan_data_dir.path().join("llamacpp").join("lib");+ fs::create_dir_all(&old_lib_dir).unwrap();+ let lib_name = "libcudart.so.12";+ let old_file_path = old_lib_dir.join(lib_name);+ {+ let mut f = File::create(&old_file_path).unwrap();+ f.write_all(b"dummy content").unwrap();+ }++ // Run Check (should trigger migration)+ let installed = is_cuda_installed(+ backend_dir.path().to_string_lossy().to_string(),+ version.to_string(),+ os_type.to_string(),+ jan_data_dir.path().to_string_lossy().to_string(),+ )+ .await+ .unwrap();++ assert!(installed, "Should return true after migration");++ // Verify Migration+ let new_path = backend_dir.path().join("build").join("bin").join(lib_name);+ assert!(new_path.exists(), "File should exist in new location");+ assert!(+ !old_file_path.exists(),+ "File should be removed from old location"+ );+ }++ #[tokio::test]+ async fn test_is_cuda_installed_already_exists() {+ let backend_dir = tempfile::tempdir().unwrap();+ let jan_data_dir = tempfile::tempdir().unwrap(); // Empty++ let version = "11.7";+ let os_type = "windows"; // Maps to cudart64_110.dll+ let lib_name = "cudart64_110.dll";++ // Setup New Path directly+ let target_dir = backend_dir.path().join("build").join("bin");+ fs::create_dir_all(&target_dir).unwrap();+ File::create(target_dir.join(lib_name)).unwrap();++ let installed = is_cuda_installed(+ backend_dir.path().to_string_lossy().to_string(),+ version.to_string(),+ os_type.to_string(),+ jan_data_dir.path().to_string_lossy().to_string(),+ )+ .await+ .unwrap();++ assert!(installed);+ }++ // --- Tests for find_latest_version_for_backend ---++ #[test]+ fn test_find_latest_version_for_backend() {+ let backends = vec![+ BackendInfo {+ version: "b7523".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ BackendInfo {+ version: "b7522".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ ];++ let result = find_latest_version_for_backend(backends, "linux-common_cpus-x64".to_string());+ assert_eq!(result, Some("b7524/linux-common_cpus-x64".to_string()));+ }++ #[test]+ fn test_find_latest_version_for_backend_with_migration() {+ let backends = vec![+ BackendInfo {+ version: "b7523".into(),+ backend: "linux-avx2-x64".into(), // Old format+ },+ BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(), // New format+ },+ ];++ // Both should map to linux-common_cpus-x64+ let result = find_latest_version_for_backend(backends, "linux-common_cpus-x64".to_string());+ assert_eq!(result, Some("b7524/linux-common_cpus-x64".to_string()));+ }++ // --- Tests for check_backend_for_updates ---++ #[tokio::test]+ async fn test_check_backend_for_updates_needs_update() {+ let current = "b7523/linux-common_cpus-x64".to_string();+ let available = vec![+ BackendInfo {+ version: "b7523".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ ];++ let result = check_backend_for_updates(current, available).await.unwrap();++ assert!(result.update_needed);+ assert_eq!(result.new_version, "b7524");+ assert_eq!(+ result.target_backend,+ Some("b7524/linux-common_cpus-x64".to_string())+ );+ }++ #[tokio::test]+ async fn test_check_backend_for_updates_already_latest() {+ let current = "b7524/linux-common_cpus-x64".to_string();+ let available = vec![+ BackendInfo {+ version: "b7523".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(),+ },+ ];++ let result = check_backend_for_updates(current, available).await.unwrap();++ assert!(!result.update_needed);+ assert_eq!(result.new_version, "0");+ assert_eq!(result.target_backend, None);+ }++ // --- Tests for validate_backend_string ---++ #[test]+ fn test_validate_backend_string_valid() {+ let result = validate_backend_string("b7524/linux-common_cpus-x64".to_string()).unwrap();+ assert_eq!(result.0, "b7524");+ assert_eq!(result.1, "linux-common_cpus-x64");+ }++ #[test]+ fn test_validate_backend_string_invalid() {+ let result = validate_backend_string("invalid-format".to_string());+ assert!(result.is_err());+ }++ // --- Tests for should_migrate_backend ---++ #[test]+ fn test_should_migrate_backend_needs_migration() {+ let old_backend = "linux-avx2-x64".to_string();+ let available = vec![BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(),+ }];++ let result = should_migrate_backend(old_backend, available).unwrap();+ assert_eq!(result, Some("linux-common_cpus-x64".to_string()));+ }++ #[test]+ fn test_should_migrate_backend_no_migration_needed() {+ let new_backend = "linux-common_cpus-x64".to_string();+ let available = vec![BackendInfo {+ version: "b7524".into(),+ backend: "linux-common_cpus-x64".into(),+ }];++ let result = should_migrate_backend(new_backend, available).unwrap();+ assert_eq!(result, None);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rsindex 57c2eca58..ce9866cf0 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs@@ -3,6 +3,8 @@ use tauri::{Manager, Runtime,};+mod args;+mod backend;pub mod cleanup;mod commands;mod device;@@ -10,7 +12,6 @@ mod error;mod gguf;mod path;mod process;-mod args;pub mod state;pub use cleanup::cleanup_llama_processes;pub use state::LLamaBackendSession;@@ -37,7 +38,22 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {gguf::commands::estimate_kv_cache_size,gguf::commands::get_model_size,gguf::commands::is_model_supported,- gguf::model_planner::plan_model_load+ gguf::model_planner::plan_model_load,+ // Backend management+ backend::map_old_backend_to_new,+ backend::get_local_installed_backends,+ backend::list_supported_backends,+ backend::determine_supported_backends,+ backend::get_supported_features,+ backend::is_cuda_installed,+ backend::find_latest_version_for_backend,+ backend::prioritize_backends,+ backend::parse_backend_version,+ backend::check_backend_for_updates,+ backend::remove_old_backend_versions,+ backend::validate_backend_string,+ backend::should_migrate_backend,+ backend::handle_setting_update]).setup(|app, _api| {// Initialize and manage the plugin state