Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: prevent duplicate backend downloads during llamacpp update (#7721)
atoz96ba6403a8ef30
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex e8616e533..4267b5e02 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -126,6 +126,7 @@ export default class llamacpp_extension extends AIEngine {private apiSecret: string = 'JustAskNow'private pendingDownloads: Map<string, Promise<void>> = new Map()private isConfiguringBackends: boolean = false+ private isUpdatingBackend: boolean = falseprivate loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promisesprivate unlistenValidationStarted?: () => void@@ -468,19 +469,45 @@ export default class llamacpp_extension extends AIEngine {async updateBackend(targetBackendString: string): Promise<{ wasUpdated: boolean; newBackend: string }> {+ if (this.isUpdatingBackend) {+ logger.warn('Backend update already in progress, skipping new update request')+ // Treat concurrent update requests as a benign no-op and report that no new update+ // was performed, while still returning the current backend value.+ return { wasUpdated: false, newBackend: this.config.version_backend }+ }++ this.isUpdatingBackend = true+try {if (!targetBackendString)throw new Error(`Invalid backend string: ${targetBackendString} supplied to update function`)- const [version, backend] = targetBackendString.split('/')+ const backendParts = targetBackendString.split('/')++ if (+ backendParts.length !== 2 ||+ !backendParts[0]?.trim() ||+ !backendParts[1]?.trim()+ ) {+ throw new Error(+ `Invalid backend string format: "${targetBackendString}". Expected "version/backend".`+ )+ }++ const [rawVersion, rawBackend] = backendParts+ const version = rawVersion.trim()+ const backend = rawBackend.trim()++ // Normalize the target backend string to use trimmed values+ targetBackendString = `${version}/${backend}`logger.info(`Updating backend to ${targetBackendString} (backend type: ${backend})`)- // Download new backend+ // Download new backend using the original asset/backend nameawait this.ensureBackendReady(backend, version)// Add delay on Windows@@ -488,25 +515,14 @@ export default class llamacpp_extension extends AIEngine {await new Promise((resolve) => setTimeout(resolve, 1000))}- // We ensure consistency by mapping the backend type, although targetBackendString should already be correct+ // Map backend type for stored preference only (not for download/config)const effectiveBackendType = await mapOldBackendToNew(backend)const currentStoredBackend = this.getStoredBackendType()- // Re-construct to be sure- targetBackendString = `${version}/${effectiveBackendType}`-- // Update configuration- this.config.version_backend = targetBackendString-- // Store the backend type preference only if it changed- if (currentStoredBackend !== targetBackendString) {- this.setStoredBackendType(targetBackendString)- logger.info(- `Updated stored backend type preference: ${targetBackendString}`- )- }+ // Persist settings and stored preference before mutating in-memory config,+ // so that if any of these steps fail, config remains consistent.- // Update settings+ // Update settings first — if this fails, we haven't mutated any state yetconst settings = await this.getSettings()await this.updateSettings(settings.map((item) => {@@ -517,6 +533,18 @@ export default class llamacpp_extension extends AIEngine {}))+ // Store the backend type preference only if it changed+ if (currentStoredBackend !== effectiveBackendType) {+ this.setStoredBackendType(effectiveBackendType)+ logger.info(+ `Updated stored backend type preference: ${effectiveBackendType}`+ )+ }++ // All critical side effects succeeded — now commit to in-memory config+ this.config.version_backend = targetBackendString+ this.config.device = ''+logger.info(`Successfully updated to backend: ${targetBackendString}`)// Emit for updating frontend@@ -530,24 +558,30 @@ export default class llamacpp_extension extends AIEngine {})}- // Clean up old versions of the same backend type using Rust command- const janDataFolderPath = await getJanDataFolderPath()- const backendsDir = await joinPath([- janDataFolderPath,- 'llamacpp',- 'backends',- ])+ // Clean up old versions — best-effort, don't fail the update if this errors+ try {+ const janDataFolderPath = await getJanDataFolderPath()+ const backendsDir = await joinPath([+ janDataFolderPath,+ 'llamacpp',+ 'backends',+ ])++ if (IS_WINDOWS) {+ await new Promise((resolve) => setTimeout(resolve, 500))+ }- if (IS_WINDOWS) {- await new Promise((resolve) => setTimeout(resolve, 500))+ await removeOldBackendVersions(backendsDir, version, backend)+ } catch (cleanupError) {+ logger.warn('Failed to remove old backend versions:', cleanupError)}- await removeOldBackendVersions(backendsDir, version, backend)-return { wasUpdated: true, newBackend: targetBackendString }} catch (error) {logger.error('Backend update failed:', error)return { wasUpdated: false, newBackend: this.config.version_backend }+ } finally {+ this.isUpdatingBackend = false}}@@ -698,6 +732,15 @@ export default class llamacpp_extension extends AIEngine {}onSettingUpdate<T>(key: string, value: T): void {+ if (key === 'version_backend') {+ // Skip entirely if updateBackend() is already handling it —+ // updateBackend() will commit to in-memory config itself after all+ // side effects succeed.+ if (this.isUpdatingBackend) {+ return+ }+ }+this.config[key] = valueif (key === 'version_backend') {diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex 59090c7bf..e90235f7a 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -13,6 +13,18 @@ vi.mock('../backend', () => ({getBackendDir: vi.fn(),}))+// Mock tauri-plugin-llamacpp-api (partial mock)+vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {+ const actual = await vi.importActual<+ typeof import('@janhq/tauri-plugin-llamacpp-api')+ >('@janhq/tauri-plugin-llamacpp-api')++ return {+ ...actual,+ mapOldBackendToNew: vi.fn(),+ removeOldBackendVersions: vi.fn(),+ }+})describe('llamacpp_extension', () => {let extension: llamacpp_extension@@ -403,4 +415,176 @@ describe('llamacpp_extension', () => {expect(result).toEqual(['model1', 'model2'])})})++ describe('updateBackend', () => {+ beforeEach(() => {+ vi.stubGlobal('IS_WINDOWS', false)+ extension['config'] = {+ version_backend: 'v1.0.0/linux-avx2-x64',+ device: '',+ } as any+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ describe('validation', () => {+ it('should reject empty targetBackendString', async () => {+ const result = await extension.updateBackend('')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })++ it('should reject targetBackendString with no slash', async () => {+ const result = await extension.updateBackend('v1.2.3')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })++ it('should reject targetBackendString with trailing slash', async () => {+ const result = await extension.updateBackend('v1.2.3/')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })++ it('should reject targetBackendString with leading slash', async () => {+ const result = await extension.updateBackend('/linux-avx2-x64')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })++ it('should reject targetBackendString with extra segments', async () => {+ const result = await extension.updateBackend('v1/backend/extra')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })++ it('should reject targetBackendString with whitespace-only parts', async () => {+ const result = await extension.updateBackend(' / ')+ expect(result).toEqual({+ wasUpdated: false,+ newBackend: 'v1.0.0/linux-avx2-x64',+ })+ })+ })++ describe('isUpdatingBackend flag', () => {+ it('should reset isUpdatingBackend to false after successful update', async () => {+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)+ extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')+ extension['setStoredBackendType'] = vi.fn()+ extension['getSettings'] = vi.fn().mockResolvedValue([])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ const { getJanDataFolderPath, joinPath } = await import('@janhq/core')+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')+ vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')++ const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')+ vi.mocked(removeOldBackendVersions).mockResolvedValue([])++ expect(extension['isUpdatingBackend']).toBe(false)++ await extension.updateBackend('v2.0.0/linux-avx2-x64')++ expect(extension['isUpdatingBackend']).toBe(false)+ })++ it('should reset isUpdatingBackend to false after failed update', async () => {+ extension['ensureBackendReady'] = vi.fn().mockRejectedValue(new Error('download failed'))++ expect(extension['isUpdatingBackend']).toBe(false)++ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')++ expect(extension['isUpdatingBackend']).toBe(false)+ expect(result.wasUpdated).toBe(false)+ })++ it('should return no-op when an update is already in progress', async () => {+ // Simulate an update already in progress+ extension['isUpdatingBackend'] = true++ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')+ expect(result.wasUpdated).toBe(false)+ })+ })++ describe('onSettingUpdate guard', () => {+ it('should skip ensureBackendReady in onSettingUpdate when updateBackend is in progress', async () => {+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)++ // Simulate updateBackend in progress+ extension['isUpdatingBackend'] = true++ // Call onSettingUpdate while updateBackend is "running"+ extension.onSettingUpdate('version_backend', 'v2.0.0/linux-avx2-x64')++ // ensureBackendReady should NOT have been called from onSettingUpdate+ expect(extension['ensureBackendReady']).not.toHaveBeenCalled()+ })+ })++ describe('stored backend type', () => {+ it('should store effectiveBackendType, not the full version/backend string', async () => {+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)+ extension['getStoredBackendType'] = vi.fn().mockReturnValue('old-backend-type')+ extension['setStoredBackendType'] = vi.fn()+ extension['getSettings'] = vi.fn().mockResolvedValue([])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ const { getJanDataFolderPath, joinPath } = await import('@janhq/core')+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')+ vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')++ const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')+ vi.mocked(removeOldBackendVersions).mockResolvedValue([])++ await extension.updateBackend('v2.0.0/linux-avx2-x64')++ // setStoredBackendType should be called with the backend type only, not "version/backend"+ const storedValue = vi.mocked(extension['setStoredBackendType']).mock.calls[0]?.[0]+ expect(storedValue).not.toContain('/')+ })+ })++ describe('trimming', () => {+ it('should trim whitespace from version and backend before use', async () => {+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)+ extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')+ extension['setStoredBackendType'] = vi.fn()+ extension['getSettings'] = vi.fn().mockResolvedValue([])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ const { getJanDataFolderPath, joinPath } = await import('@janhq/core')+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')+ vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')++ const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')+ vi.mocked(removeOldBackendVersions).mockResolvedValue([])++ await extension.updateBackend(' v2.0.0 / linux-avx2-x64 ')++ // ensureBackendReady should receive trimmed values+ expect(extension['ensureBackendReady']).toHaveBeenCalledWith(+ 'linux-avx2-x64',+ 'v2.0.0'+ )+ })+ })+ })})\ No newline at end of filediff --git a/web-app/src/hooks/useBackendUpdater.ts b/web-app/src/hooks/useBackendUpdater.tsindex 7a0e7601a..887a86366 100644--- a/web-app/src/hooks/useBackendUpdater.ts+++ b/web-app/src/hooks/useBackendUpdater.ts@@ -6,6 +6,7 @@ export interface BackendUpdateInfo {updateNeeded: booleannewVersion: stringcurrentVersion?: string+ targetBackend?: string}interface ExtensionSetting {@@ -15,6 +16,41 @@ interface ExtensionSetting {}}+interface BackendUpdateResult {+ wasUpdated: boolean+ reason?: 'in_progress' | 'error' | string+}++interface ExtensionWithSettings {+ getSettings?: () => Promise<ExtensionSetting[] | undefined>+}++async function getCurrentBackendTypeFromSettings(+ extension: ExtensionWithSettings+): Promise<string> {+ const settings = await extension.getSettings?.()+ const currentBackendSetting = settings?.find(+ (s) => s.key === 'version_backend'+ )+ const currentBackend = currentBackendSetting?.controllerProps?.value as string++ if (!currentBackend) {+ throw new Error('Current backend not found')+ }++ const parts = currentBackend.split('/')+ const currentVersionPart = parts[0]?.trim()+ const currentBackendType = parts[1]?.trim()++ if (parts.length !== 2 || !currentVersionPart || !currentBackendType) {+ throw new Error(+ `Invalid current backend format: "${currentBackend}". Expected "version/backendType".`+ )+ }++ return currentBackendType+}+interface LlamacppExtension {getSettings?(): Promise<ExtensionSetting[]>checkBackendForUpdates?(): Promise<BackendUpdateInfo>@@ -220,6 +256,11 @@ export const useBackendUpdater = () => {if (!updateState.updateInfo) returntry {+ // If an update is already in progress, avoid triggering a duplicate update.+ if (updateState.isUpdating) {+ return+ }+setUpdateState((prev) => ({...prev,isUpdating: true,@@ -256,28 +297,42 @@ export const useBackendUpdater = () => {throw new Error('Extension does not support backend updates')}- // Get current backend version to construct target backend stringconst extension = extensionToUse as LlamacppExtension- const settings = await extension.getSettings?.()- const currentBackendSetting = settings?.find(- (s) => s.key === 'version_backend'- )- const currentBackend = currentBackendSetting?.controllerProps- ?.value as string-- if (!currentBackend) {- throw new Error('Current backend not found')- }- // Extract backend type from current backend string (e.g., "b3224/cuda12" -> "cuda12")- const [, backendType] = currentBackend.split('/')- const targetBackendString = `${updateState.updateInfo.newVersion}/${backendType}`+ // Use the exact target backend from checkBackendForUpdates if available,+ // to avoid mismatches between old/new backend name formats+ let targetBackendString = updateState.updateInfo.targetBackend++ if (targetBackendString) {+ // Validate and normalize the provided target backend string+ const rawParts = targetBackendString.split('/')+ const versionPart = rawParts[0]?.trim()+ const backendTypePart = rawParts[1]?.trim()++ if (rawParts.length !== 2 || !versionPart || !backendTypePart) {+ // Malformed targetBackend; fall back to constructing from current settings+ const currentBackendType = await getCurrentBackendTypeFromSettings(+ extension+ )+ targetBackendString = `${updateState.updateInfo.newVersion}/${currentBackendType}`+ } else {+ // Normalize to "version/backendType" with trimmed parts+ targetBackendString = `${versionPart}/${backendTypePart}`+ }+ } else {+ // Fallback: construct from current settings if targetBackend wasn't provided+ const currentBackendType = await getCurrentBackendTypeFromSettings(+ extension+ )+ targetBackendString = `${updateState.updateInfo.newVersion}/${currentBackendType}`+ }// Call the extension's updateBackend method- const result = await extension.updateBackend?.(targetBackendString)+ const rawResult = await extension.updateBackend?.(targetBackendString)+ const result = rawResult as BackendUpdateResult | undefined- if (result?.wasUpdated) {- // Reset update state+ if (result?.wasUpdated === true) {+ // Reset update state on successful updateconst newState = {isUpdateAvailable: false,updateInfo: null,@@ -288,6 +343,24 @@ export const useBackendUpdater = () => {...newState,}))syncStateToOtherInstances(newState)+ } else if (+ result?.wasUpdated === false &&+ (result.reason === 'in_progress' || typeof result.reason === 'undefined')+ ) {+ // Benign no-op (e.g., another update is already in progress or the+ // extension returned a no-op response without a reason). Do not treat+ // this as a failure; just clear the local isUpdating flag.+ setUpdateState((prev) => ({+ ...prev,+ isUpdating: false,+ }))+ } else if (+ result?.wasUpdated === false &&+ result.reason &&+ result.reason !== 'in_progress'+ ) {+ // Explicit failure reason from extension: surface as an error.+ throw new Error(`Backend update failed: ${result.reason}`)} else {throw new Error('Backend update failed')}@@ -299,7 +372,7 @@ export const useBackendUpdater = () => {}))throw error}- }, [updateState.updateInfo, syncStateToOtherInstances])+ }, [updateState.updateInfo, updateState.isUpdating, syncStateToOtherInstances])const installBackend = useCallback(async (filePath: string) => {try {