Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: add backend migration mapping and update backend handling (#6917) (#6920)
Louis384eed56e6b4
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex 3e69c9f76..69062f755 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -3,6 +3,53 @@ import { invoke } from '@tauri-apps/api/core'import { getProxyConfig, basenameNoExt } from './util'import { dirname, basename } 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+}+++/** Reads currently installed backends in janDataFolderPath*@@ -76,6 +123,12 @@ async function fetchRemoteSupportedBackends(if (supportedBackends.includes(backend)) {remote.push({ version, backend })+ continue+ }+ const mappedNew = 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 })}}}diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 60c24d2f1..614eeaa02 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -33,6 +33,7 @@ import {isBackendInstalled,getBackendExePath,getBackendDir,+ mapOldBackendToNew,} from './backend'import { invoke } from '@tauri-apps/api/core'import { getProxyConfig } from './util'@@ -276,7 +277,7 @@ export default class llamacpp_extension extends AIEngine {backendType: string): string | null {const matchingBackends = version_backends.filter(- (vb) => vb.backend === backendType+ (vb) => mapOldBackendToNew(vb.backend) === backendType)if (matchingBackends.length === 0) {return null@@ -284,6 +285,7 @@ export default class llamacpp_extension extends AIEngine {// Sort by version (newest first) and get the latestmatchingBackends.sort((a, b) => b.version.localeCompare(a.version))+ // Return the full string including the original asset name, as this is used for download/pathreturn `${matchingBackends[0].version}/${matchingBackends[0].backend}`}@@ -320,12 +322,35 @@ export default class llamacpp_extension extends AIEngine {// Get stored backend preferenceconst storedBackendType = this.getStoredBackendType()let bestAvailableBackendString = ''+ let effectiveStoredBackendType = storedBackendTypeif (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+ )++ 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.`+ )+ }+ }// Find the latest version of the stored backend typeconst preferredBackendString = this.findLatestVersionForBackend(version_backends,- storedBackendType+ effectiveStoredBackendType)if (preferredBackendString) {bestAvailableBackendString = preferredBackendString@@ -388,10 +413,11 @@ export default class llamacpp_extension extends AIEngine {const [, backendType] = savedBackendSetting.split('/')if (backendType) {const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== backendType) {- this.setStoredBackendType(backendType)+ const effectiveBackendType = mapOldBackendToNew(backendType)+ if (currentStoredBackend !== effectiveBackendType) {+ this.setStoredBackendType(effectiveBackendType)logger.info(- `Stored backend type preference from saved setting: ${backendType}`+ `Stored backend type preference from saved setting: ${effectiveBackendType}`)}}@@ -401,10 +427,11 @@ export default class llamacpp_extension extends AIEngine {const [, backendType] = bestAvailableBackendString.split('/')if (backendType) {const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== backendType) {- this.setStoredBackendType(backendType)+ const effectiveBackendType = mapOldBackendToNew(backendType)+ if (currentStoredBackend !== effectiveBackendType) {+ this.setStoredBackendType(effectiveBackendType)logger.info(- `Stored backend type preference from best available: ${backendType}`+ `Stored backend type preference from best available: ${effectiveBackendType}`)}}@@ -532,31 +559,42 @@ export default class llamacpp_extension extends AIEngine {? ['cuda-cu12.0','cuda-cu11.7',- 'vulkan', // Include vulkan if we have enough GPU memory- 'avx512',- 'avx2',- 'avx',- 'noavx',+ '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-cu12.0','cuda-cu11.7',- 'avx512',- 'avx2',- 'avx',- 'noavx',+ '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', // demote to last if we don't have enough memory+ 'vulkan',]// Helper to map backend string to a priority categoryconst getBackendCategory = (backendString: string): string | undefined => {- if (backendString.includes('cuda-12-common_cpus')) return 'cuda-cu12.0'- if (backendString.includes('cuda-11-common_cpus')) return 'cuda-cu11.7'- if (backendString.includes('vulkan-common_cpus')) return 'vulkan'+ 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 (@@ -625,10 +663,13 @@ export default class llamacpp_extension extends AIEngine {this.config.version_backend = targetBackendString// Store the backend type preference only if it changed+ const effectiveBackendType = mapOldBackendToNew(backend)const currentStoredBackend = this.getStoredBackendType()- if (currentStoredBackend !== backend) {- this.setStoredBackendType(backend)- logger.info(`Updated stored backend type preference: ${backend}`)+ if (currentStoredBackend !== effectiveBackendType) {+ this.setStoredBackendType(effectiveBackendType)+ logger.info(+ `Updated stored backend type preference: ${effectiveBackendType}`+ )}// Update settings@@ -700,6 +741,8 @@ export default class llamacpp_extension extends AIEngine {const [currentVersion, currentBackend] = (this.config.version_backend || '').split('/')+ // Get the effective/migrated backend type+ const currentEffectiveBackendType = mapOldBackendToNew(currentBackend)if (!currentVersion || !currentBackend) {logger.warn(@@ -712,31 +755,42 @@ export default class llamacpp_extension extends AIEngine {const version_backends = await listSupportedBackends()const targetBackendString = this.findLatestVersionForBackend(version_backends,- currentBackend+ currentEffectiveBackendType)if (!targetBackendString) {logger.warn(`No available versions found for current backend type: ${currentBackend}`)+ // Attempt to fall back to the absolute best available if the preferred type is gone.+ if (+ currentBackend !==+ mapOldBackendToNew(bestAvailableBackendString.split('/')[1])+ ) {+ logger.info(+ `Falling back to best available backend: ${bestAvailableBackendString}`+ )+ return await this.updateBackend(bestAvailableBackendString)+ }return { wasUpdated: false, newBackend: this.config.version_backend }}- const [latestVersion] = targetBackendString.split('/')+ const [latestVersion, latestBackendName] = targetBackendString.split('/')// Check if update is needed (only version comparison for same backend type)- if (currentVersion === latestVersion) {+ if (+ currentVersion === latestVersion &&+ currentBackend === 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 for the same backend typelogger.info(- `Auto-updating from ${this.config.version_backend} to ${targetBackendString} (preserving backend type)`+ `Auto-updating/Migrating from ${this.config.version_backend} to ${targetBackendString} (preserving effective backend type: ${currentEffectiveBackendType})`)-return await this.updateBackend(targetBackendString)}@@ -1120,7 +1174,13 @@ export default class llamacpp_extension extends AIEngine {*/async installBackend(path: string): Promise<void> {const platformName = IS_WINDOWS ? 'win' : 'linux'- const re = /^llama-(b\d+)-bin-(.+?)\.(?:tar\.gz|zip)$/++ // Match any prefix before 'llama', then version and backend+ // Examples:+ // - llama-b6929-bin-<os>-<backend>-x64.tar.gz or zip+ // - custom-prefix-llama-b6929-bin-<os>-<backend>-x64.tar.gz or zip+ const re = /^(.+?-)?llama-(b\d+)-bin-(.+?)\.(?:tar\.gz|zip)$/+const archiveName = await basename(path)logger.info(`Installing backend from path: ${path}`)@@ -1131,18 +1191,37 @@ export default class llamacpp_extension extends AIEngine {logger.error(`Invalid path or file ${path}`)throw new Error(`Invalid path or file ${path}`)}+const match = re.exec(archiveName)- if (!match) throw new Error('Failed to parse archive name')- const [, version, backend] = match- if (!version && !backend) {++ if (!match) {+ throw new Error(+ `Failed to parse archive name: ${archiveName}. Expected format: [Optional prefix-]llama-<version>-bin-<backend>.(tar.gz|zip)`+ )+ }++ const [, prefix, version, backend] = match++ if (!version || !backend) {throw new Error(`Invalid backend archive name: ${archiveName}`)}- const backendDir = await getBackendDir(backend, version)++ // Include prefix in the backend identifier if present+ const backendIdentifier = prefix ? `${prefix}${backend}` : backend++ logger.info(+ `Detected prefix: ${prefix || 'none'}, version: ${version}, backend: ${backendIdentifier}`+ )++ const backendDir = await getBackendDir(backendIdentifier, version)+try {await invoke('decompress', { path: path, outputDir: backendDir })} catch (e) {logger.error(`Failed to install: ${String(e)}`)+ throw new Error(`Failed to decompress archive: ${String(e)}`)}+const binPath =platformName === 'win'? await joinPath([backendDir, 'build', 'bin', 'llama-server.exe'])@@ -1150,11 +1229,16 @@ export default class llamacpp_extension extends AIEngine {if (!fs.existsSync(binPath)) {await fs.rm(backendDir)- throw new Error('Not a supported backend archive!')+ throw new Error(+ 'Not a supported backend archive! Missing llama-server binary.'+ )}+try {await this.configureBackends()- logger.info(`Backend ${backend}/${version} installed and UI refreshed`)+ logger.info(+ `Backend ${backendIdentifier}/${version} installed and UI refreshed`+ )} catch (e) {logger.error('Backend installed but failed to refresh UI', e)throw new Error(@@ -1596,7 +1680,11 @@ export default class llamacpp_extension extends AIEngine {const port = await this.getRandomPort()// disable llama-server webui- args.push('--no-webui')+ // TODO: Determine what's the best course of action here.+ // Hopefully, we would want all the fork to have same set of arguments+ // Otherwise it would become impossible to maintain+ // Keeping this for now+ if (!backend.startsWith('ik')) args.push('--no-webui')const api_key = await this.generateApiKey(modelId, String(port))envs['LLAMA_API_KEY'] = api_keyenvs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)@@ -1655,10 +1743,13 @@ export default class llamacpp_extension extends AIEngine {// Note: Older llama.cpp versions are no longer supportedif (cfg.flash_attn !== undefined ||- !cfg.flash_attn ||- cfg.flash_attn !== ''- )+ (cfg.flash_attn !== 'auto' && // set argument only when the setting value is not auto+ !backend.startsWith('ik')) // ik fork of llama.cpp doesn't support --flash-attn+ ) {args.push('--flash-attn', String(cfg.flash_attn)) //default: auto = ON when supported+ } else if (backend.startsWith('ik') && cfg.flash_attn == 'on') {+ args.push('-fa') // hoping the ik fork is still using the old fa arguments+ }// Boolean flagsif (cfg.ctx_shift) args.push('--context-shift')@@ -1698,7 +1789,13 @@ export default class llamacpp_extension extends AIEngine {const backendPath = await getBackendExePath(backend, version)try {- const sInfo = await loadLlamaModel(backendPath, args, envs, isEmbedding, Number(this.timeout))+ const sInfo = await loadLlamaModel(+ backendPath,+ args,+ envs,+ isEmbedding,+ Number(this.timeout)+ )return sInfo} catch (error) {logger.error('Error in load command:\n', error)diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.tsindex a3395d907..9dcf73ab6 100644--- a/extensions/llamacpp-extension/src/test/backend.test.ts+++ b/extensions/llamacpp-extension/src/test/backend.test.ts@@ -1,59 +1,194 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+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'+import { invoke } from '@tauri-apps/api/core'+import { dirname } from '@tauri-apps/api/path'++// Mock constants: Hardcode path string directly inside the mock to avoid hoisting issues+const MOCK_JAN_PATH_STRING = '/path/to/jan'++// Mock the core dependencies+vi.mock('@janhq/core', () => ({+ getJanDataFolderPath: vi.fn().mockResolvedValue('/path/to/jan'),+ fs: {+ existsSync: vi.fn(),+ readdirSync: vi.fn().mockResolvedValue([]),+ rm: vi.fn().mockResolvedValue(undefined),+ },+ joinPath: vi.fn(async (paths: string[]) => paths.join('/')),+ events: {+ emit: vi.fn(),+ },+}))+vi.mock('@tauri-apps/api/core', () => ({+ invoke: vi.fn(),+}))+vi.mock('@janhq/tauri-plugin-hardware-api', () => ({+ getSystemInfo: vi.fn(),+}))+vi.mock('../util', () => ({+ getProxyConfig: vi.fn().mockReturnValue({}),+ basenameNoExt: vi.fn((name) => name.replace(/\.tar\.gz$/, '')),+}))+vi.mock('@tauri-apps/api/path', () => ({+ // Mock dirname to return the direct parent directory (used for decompress outputDir)+ dirname: vi.fn(async (path) => path.split('/').slice(0, -1).join('/')),+ basename: vi.fn(async (path) => path.split('/').pop()),+}))// Mock the global fetch functionglobal.fetch = vi.fn()+// Mock IS_WINDOWS and window.core global for environment setup+vi.stubGlobal('IS_WINDOWS', false)+vi.stubGlobal('window', {+ core: {+ extensionManager: {+ getByName: vi.fn(),+ },+ },+})++// Setup global mock for `window.core.extensionManager.getByName` and the download manager+const mockDownloadManager = {+ downloadFiles: vi.fn().mockImplementation((items, taskId, onProgress) => {+ // Simulate successful download+ if (onProgress) onProgress(100, 100)+ return Promise.resolve()+ }),+}+vi.mocked(window.core.extensionManager.getByName).mockReturnValue(+ mockDownloadManager+)+describe('Backend functions', () => {beforeEach(() => {vi.clearAllMocks()+ // Mock getJanDataFolderPath explicitly to a simple path+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')++ vi.mocked(getSystemInfo).mockResolvedValue({+ os_type: 'linux',+ cpu: {+ arch: 'x86_64',+ extensions: [],+ },+ gpus: [],+ } as any)++ // Default mock for isBackendInstalled dependencies+ vi.mocked(fs.existsSync).mockImplementation(async (path: string) => {+ if (path.includes('build')) return true // Assume build dir check passes+ return false+ })+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue(+ mockDownloadManager+ )+ vi.mocked(mockDownloadManager.downloadFiles).mockClear()+ })++ afterEach(() => {+ 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 supported backends for Windows x64', async () => {- // Mock system info- const getSystemInfo = vi.fn().mockResolvedValue({+ 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)- // Mock GitHub releasesconst 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(mockReleases),+ 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 CUDA backends with proper CPU instruction detection for Windows', async () => {- // Mock system info with CUDA support and AVX512- const getSystemInfo = vi.fn().mockResolvedValue({+ 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',@@ -65,159 +200,51 @@ describe('Backend functions', () => {nvidia_info: { compute_capability: '8.6' },},],- })-- // Mock GitHub releases with CUDA backends- 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-avx2-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-avx-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-noavx-cuda-cu12.0-x64.tar.gz' },- ],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve(mockReleases),- })-- const result = await listSupportedBackends()-- expect(result).toContain({ version: 'v1.0.0', backend: 'win-avx512-cuda-cu12.0-x64' })- })-- it('should select appropriate CUDA backend based on CPU features - AVX2 only', async () => {- // Mock system info with CUDA support but only AVX2- const getSystemInfo = vi.fn().mockResolvedValue({- os_type: 'windows',- cpu: {- arch: 'x86_64',- extensions: ['avx', 'avx2'], // No 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' },- { name: 'llama-v1.0.0-bin-win-avx-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-noavx-cuda-cu12.0-x64.tar.gz' },],},]global.fetch = vi.fn().mockResolvedValue({ok: true,- json: () => Promise.resolve(mockReleases),+ json: () => Promise.resolve({ releases: mockReleases }),})const result = await listSupportedBackends()- expect(result).toContain({ version: 'v1.0.0', backend: 'win-avx2-cuda-cu12.0-x64' })- expect(result).not.toContain({ version: 'v1.0.0', backend: 'win-avx512-cuda-cu12.0-x64' })- })-- it('should select appropriate CUDA backend based on CPU features - no AVX', async () => {- // Mock system info with CUDA support but no AVX- const getSystemInfo = vi.fn().mockResolvedValue({- os_type: 'windows',- cpu: {- arch: 'x86_64',- extensions: [], // No AVX extensions- },- gpus: [- {- driver_version: '530.41',- nvidia_info: { compute_capability: '8.6' },- },- ],- })-- 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-avx2-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-avx-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-win-noavx-cuda-cu12.0-x64.tar.gz' },- ],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve(mockReleases),+ expect(result).toContainEqual({+ version: 'v1.0.0',+ backend: 'win-cuda-12-common_cpus-x64',})-- const result = await listSupportedBackends()-- expect(result).toContain({ version: 'v1.0.0', backend: 'win-noavx-cuda-cu12.0-x64' })- expect(result).not.toContain({ version: 'v1.0.0', backend: 'win-avx2-cuda-cu12.0-x64' })- expect(result).not.toContain({ version: 'v1.0.0', backend: 'win-avx512-cuda-cu12.0-x64' })- })-- it('should return CUDA backends with proper CPU instruction detection for Linux', async () => {- // Mock system info with CUDA support and AVX support- const getSystemInfo = vi.fn().mockResolvedValue({- os_type: 'linux',- cpu: {- arch: 'x86_64',- extensions: ['avx'], // Only AVX, no AVX2- },- gpus: [- {- driver_version: '530.60.13',- nvidia_info: { compute_capability: '8.6' },- },- ],+ expect(result).toContainEqual({+ version: 'v1.0.0',+ backend: 'win-avx512-cuda-cu12.0-x64',})-- const mockReleases = [- {- tag_name: 'v1.0.0',- assets: [- { name: 'llama-v1.0.0-bin-linux-avx512-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-linux-avx2-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-linux-avx-cuda-cu12.0-x64.tar.gz' },- { name: 'llama-v1.0.0-bin-linux-noavx-cuda-cu12.0-x64.tar.gz' },- ],- },- ]-- global.fetch = vi.fn().mockResolvedValue({- ok: true,- json: () => Promise.resolve(mockReleases),+ expect(result).toContainEqual({+ version: 'v1.0.0',+ backend: 'win-avx2-cuda-cu12.0-x64',})-- const result = await listSupportedBackends()-- expect(result).toContain({ version: 'v1.0.0', backend: 'linux-avx-cuda-cu12.0-x64' })- expect(result).not.toContain({ version: 'v1.0.0', backend: 'linux-avx2-cuda-cu12.0-x64' })- expect(result).not.toContain({ version: 'v1.0.0', backend: 'linux-avx512-cuda-cu12.0-x64' })+ expect(result.length).toBe(3)})- it('should return supported backends for macOS arm64', async () => {- const getSystemInfo = vi.fn().mockResolvedValue({+ 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 = [{@@ -228,262 +255,178 @@ describe('Backend functions', () => {global.fetch = vi.fn().mockResolvedValue({ok: true,- json: () => Promise.resolve(mockReleases),+ 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', () => {- it('should return correct backend directory path', async () => {- const { getJanDataFolderPath, joinPath } = await import('@janhq/core')+ describe('getBackendDir and getBackendExePath', () => {+ it('should use the specific backend name for directory path', async () => {+ vi.mocked(fs.existsSync).mockImplementation(async (path: string) =>+ path.includes('build')+ ) // Mock build dir check- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockResolvedValue(- '/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64'- )-- const result = await getBackendDir('win-avx2-x64', 'v1.0.0')+ const dir = await getBackendDir('linux-avx2-x64', 'v1.2.3')+ expect(dir).toBe(`/path/to/jan/llamacpp/backends/v1.2.3/linux-avx2-x64`)- expect(result).toBe('/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64')- expect(joinPath).toHaveBeenCalledWith([- '/path/to/jan',- 'llamacpp',- 'backends',- 'v1.0.0',- 'win-avx2-x64',- ])+ const exePath = await getBackendExePath('linux-avx2-x64', 'v1.2.3')+ expect(exePath).toBe(+ `/path/to/jan/llamacpp/backends/v1.2.3/linux-avx2-x64/build/bin/llama-server`+ )})- })- describe('getBackendExePath', () => {- it('should return correct exe path for Windows', async () => {- const getSystemInfo = vi.fn().mockResolvedValue({- os_type: 'windows',- })+ it('should use the new common backend name for directory path if it was the asset name', async () => {+ vi.mocked(fs.existsSync).mockImplementation(async (path: string) =>+ path.includes('build')+ ) // Mock build dir check- const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')-- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath)- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64'- )- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64/build'- )- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server.exe'- )-- vi.mocked(fs.existsSync).mockResolvedValue(true)-- const result = await getBackendExePath('win-avx2-x64', 'v1.0.0')-- expect(result).toBe(- '/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server.exe'+ const dir = await getBackendDir('win-common_cpus-x64', 'v2.0.0')+ expect(dir).toBe(+ `/path/to/jan/llamacpp/backends/v2.0.0/win-common_cpus-x64`)- })-- it('should return correct exe path for Linux/macOS', async () => {- const getSystemInfo = vi.fn().mockResolvedValue({- os_type: 'linux',- })- const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')-- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath)- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64'- )- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64/build'- )- .mockResolvedValueOnce(- '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64/build/bin/llama-server'- )-- vi.mocked(fs.existsSync).mockResolvedValue(true)-- const result = await getBackendExePath('linux-avx2-x64', 'v1.0.0')-- expect(result).toBe(- '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64/build/bin/llama-server'+ const exePath = await getBackendExePath('win-common_cpus-x64', 'v2.0.0')+ expect(exePath).toBe(+ `/path/to/jan/llamacpp/backends/v2.0.0/win-common_cpus-x64/build/bin/llama-server`)})})describe('isBackendInstalled', () => {- it('should return true when backend is installed', async () => {- const { fs } = await import('@janhq/core')-- vi.mocked(fs.existsSync).mockResolvedValue(true)+ it('should return true when backend is installed using its specific name', async () => {+ vi.stubGlobal('IS_WINDOWS', false) // Linux/macOS for llama-server+ // Mock both the check for the 'build' directory and the final executable path+ vi.mocked(fs.existsSync).mockImplementation(async (path: string) => {+ const expectedExePath = `/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server`+ if (path === expectedExePath) return true+ if (path.endsWith('/build')) return true+ return false+ })const result = await isBackendInstalled('win-avx2-x64', 'v1.0.0')-expect(result).toBe(true)+ // Check that it was called with the final exe path+ expect(fs.existsSync).toHaveBeenCalledWith(+ `/path/to/jan/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server`+ )})-- it('should return false when backend is not installed', async () => {- const { fs } = await import('@janhq/core')-- vi.mocked(fs.existsSync).mockResolvedValue(false)+ })+ describe('isBackendInstalled', () => {+ it('should return true when backend is installed using its specific name', async () => {+ vi.stubGlobal('IS_WINDOWS', false) // Linux/macOS for llama-server+ // Mock both the check for the 'build' directory and the final executable path+ vi.mocked(fs.existsSync).mockImplementation(async (path: string) => {+ const expectedExePath = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server`+ if (path === expectedExePath) return true+ if (path.endsWith('/build')) return true+ return false+ })const result = await isBackendInstalled('win-avx2-x64', 'v1.0.0')-- expect(result).toBe(false)+ expect(result).toBe(true)+ // Check that it was called with the final exe path+ expect(fs.existsSync).toHaveBeenCalledWith(+ `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server`+ )})})describe('downloadBackend', () => {- it('should download backend successfully', async () => {- const mockDownloadManager = {- downloadFiles: vi- .fn()- .mockImplementation((items, taskId, onProgress) => {- // Simulate successful download- onProgress(100, 100)- return Promise.resolve()- }),- }-- window.core.extensionManager.getByName = vi- .fn()- .mockReturnValue(mockDownloadManager)-- const { getJanDataFolderPath, joinPath, fs, events } = await import(- '@janhq/core'+ beforeEach(() => {+ vi.mocked(mockDownloadManager.downloadFiles).mockClear()+ vi.mocked(mockDownloadManager.downloadFiles).mockImplementation(+ (items, taskId, onProgress) => {+ if (onProgress) onProgress(100, 100)+ return Promise.resolve()+ })- const { invoke } = await import('@tauri-apps/api/core')-- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockImplementation((paths) =>- Promise.resolve(paths.join('/'))- )- vi.mocked(fs.rm).mockResolvedValue(undefined)- vi.mocked(invoke).mockResolvedValue(undefined)-- await downloadBackend('win-avx2-x64', 'v1.0.0')-- expect(mockDownloadManager.downloadFiles).toHaveBeenCalled()- expect(events.emit).toHaveBeenCalledWith('onFileDownloadSuccess', {- modelId: 'llamacpp-v1-0-0-win-avx2-x64',- downloadType: 'Engine',+ vi.mocked(invoke).mockImplementation(async (command: string) => {+ if (command === 'is_library_available') return false+ if (command === 'decompress') return undefined+ return undefined})+ vi.mocked(fs.rm).mockResolvedValue(undefined)})+ it('should include cudart for cuda-12-common_cpus if not installed', async () => {+ vi.stubGlobal('IS_WINDOWS', true)+ vi.mocked(getSystemInfo).mockResolvedValue({+ os_type: 'windows',+ cpu: { arch: 'x86_64', extensions: [] },+ gpus: [+ {+ driver_version: '530.41',+ nvidia_info: { compute_capability: '8.6' },+ },+ ],+ } as any)- it('should handle download errors', async () => {- const mockDownloadManager = {- downloadFiles: vi.fn().mockRejectedValue(new Error('Download failed')),- }-- window.core.extensionManager.getByName = vi- .fn()- .mockReturnValue(mockDownloadManager)-- const { events } = await import('@janhq/core')+ await downloadBackend('win-cuda-12-common_cpus-x64', 'v1.0.0')- await expect(downloadBackend('win-avx2-x64', 'v1.0.0')).rejects.toThrow(- 'Download failed'+ const downloadItems = vi.mocked(mockDownloadManager.downloadFiles).mock+ .calls[0][0]+ expect(downloadItems.length).toBe(2)+ expect(downloadItems[0].url).toContain(+ 'win-cuda-12-common_cpus-x64.tar.gz')-- expect(events.emit).toHaveBeenCalledWith('onFileDownloadError', {- modelId: 'llamacpp-v1-0-0-win-avx2-x64',- downloadType: 'Engine',- })- })-- it('should correctly extract parent directory from Windows paths', async () => {- const { dirname } = await import('@tauri-apps/api/path')-- // Mock dirname to simulate Windows path handling- vi.mocked(dirname).mockResolvedValue('C:\\path\\to\\backend')-- const mockDownloadManager = {- downloadFiles: vi- .fn()- .mockImplementation((items, taskId, onProgress) => {- onProgress(100, 100)- return Promise.resolve()- }),- }-- window.core.extensionManager.getByName = vi- .fn()- .mockReturnValue(mockDownloadManager)-- const { getJanDataFolderPath, joinPath, fs, events } = await import(- '@janhq/core'+ expect(downloadItems[1].url).toContain(+ 'cudart-llama-bin-win-cu12.0-x64.tar.gz')- const { invoke } = await import('@tauri-apps/api/core')+ })- vi.mocked(getJanDataFolderPath).mockResolvedValue('C:\\path\\to\\jan')- vi.mocked(joinPath).mockImplementation((paths) =>- Promise.resolve(paths.join('\\'))- )- vi.mocked(fs.rm).mockResolvedValue(undefined)- vi.mocked(invoke).mockResolvedValue(undefined)+ it('should include cudart for old cuda-cu11.7 if not installed', async () => {+ vi.stubGlobal('IS_WINDOWS', false)+ vi.mocked(getSystemInfo).mockResolvedValue({+ os_type: 'linux',+ cpu: { arch: 'x86_64', extensions: [] },+ gpus: [+ {+ driver_version: '452.39',+ nvidia_info: { compute_capability: '7.0' },+ },+ ],+ } as any)- await downloadBackend('win-avx2-x64', 'v1.0.0')+ // Downloading old name asset+ await downloadBackend('linux-avx2-cuda-cu11.7-x64', 'v1.0.0')- // Verify that dirname was called for path extraction- expect(dirname).toHaveBeenCalledWith(- 'C:\\path\\to\\jan\\llamacpp\\backends\\v1.0.0\\win-avx2-x64\\backend.tar.gz'+ const downloadItems = vi.mocked(mockDownloadManager.downloadFiles).mock+ .calls[0][0]+ expect(downloadItems.length).toBe(2)+ expect(downloadItems[0].url).toContain(+ 'linux-avx2-cuda-cu11.7-x64.tar.gz'+ )+ expect(downloadItems[1].url).toContain(+ 'cudart-llama-bin-linux-cu11.7-x64.tar.gz')-- // Verify decompress was called with correct parent directory- expect(invoke).toHaveBeenCalledWith('decompress', {- path: 'C:\\path\\to\\jan\\llamacpp\\backends\\v1.0.0\\win-avx2-x64\\backend.tar.gz',- outputDir: 'C:\\path\\to\\backend',- })})- it('should correctly extract parent directory from Unix paths', async () => {- const { dirname } = await import('@tauri-apps/api/path')-- // Mock dirname to simulate Unix path handling- vi.mocked(dirname).mockResolvedValue('/path/to/backend')-- const mockDownloadManager = {- downloadFiles: vi- .fn()- .mockImplementation((items, taskId, onProgress) => {- onProgress(100, 100)- return Promise.resolve()- }),- }-- window.core.extensionManager.getByName = vi- .fn()- .mockReturnValue(mockDownloadManager)+ it('should correctly extract parent directory from Windows paths', async () => {+ vi.stubGlobal('IS_WINDOWS', true)- const { getJanDataFolderPath, joinPath, fs, events } = await import(- '@janhq/core'- )- const { invoke } = await import('@tauri-apps/api/core')+ // Mock getSystemInfo for Windows/x64+ vi.mocked(getSystemInfo).mockResolvedValue({+ os_type: 'windows',+ cpu: { arch: 'x86_64', extensions: [] },+ gpus: [],+ } as any)- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockImplementation((paths) =>- Promise.resolve(paths.join('/'))+ // Mock dirname to return Windows-style path components (for dirname mock)+ vi.mocked(dirname).mockResolvedValue(+ `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`)- vi.mocked(fs.rm).mockResolvedValue(undefined)- vi.mocked(invoke).mockResolvedValue(undefined)-- await downloadBackend('linux-avx2-x64', 'v1.0.0')- // Verify that dirname was called for path extraction- expect(dirname).toHaveBeenCalledWith(- '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz'- )+ await downloadBackend('win-avx2-x64', 'v1.0.0')// Verify decompress was called with correct parent directoryexpect(invoke).toHaveBeenCalledWith('decompress', {- path: '/path/to/jan/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz',- outputDir: '/path/to/backend',+ path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/backend.tar.gz`,+ outputDir: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`,})})})diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex 49f13eeae..a53661f23 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -44,7 +44,7 @@ pub async fn load_llama_model<R: Runtime>(mut args: Vec<String>,envs: HashMap<String, String>,is_embedding: bool,- timeout: u64+ timeout: u64,) -> ServerResult<SessionInfo> {let state: State<LlamacppState> = app_handle.state();let mut process_map = state.llama_server_process.lock().await;@@ -69,7 +69,10 @@ pub async fn load_llama_model<R: Runtime>(None};- log::info!("MMPROJ Path string: {}", &mmproj_path_string.as_ref().unwrap_or(&"None".to_string()));+ log::info!(+ "MMPROJ Path string: {}",+ &mmproj_path_string.as_ref().unwrap_or(&"None".to_string())+ );let api_key: String;@@ -102,6 +105,7 @@ pub async fn load_llama_model<R: Runtime>(let (ready_tx, mut ready_rx) = mpsc::channel::<bool>(1);// Spawn task to monitor stdout for readiness+ let stdout_ready_tx = ready_tx.clone();let _stdout_task = tokio::spawn(async move {let mut reader = BufReader::new(stdout);let mut byte_buffer = Vec::new();@@ -116,6 +120,16 @@ pub async fn load_llama_model<R: Runtime>(if !line.is_empty() {log::info!("[llamacpp stdout] {}", line);}++ // Check for readiness indicators+ let line_lower = line.to_lowercase();+ if line_lower.contains("http server listening")+ || line_lower.contains("all slots are idle")+ || line_lower.contains("starting the main loop")+ {+ log::info!("Server appears to be ready based on stdout: '{}'", line);+ let _ = stdout_ready_tx.send(true).await;+ }}Err(e) => {log::error!("Error reading stdout: {}", e);