Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: move backend download/management logic to Rust plugin and add deps verification (#8026)

Akarshan Biswasc168f887f36d
diff --git a/core/src/types/api/index.ts b/core/src/types/api/index.ts
index 3cdd9c0fb..aa2075ca8 100644
--- a/core/src/types/api/index.ts
+++ b/core/src/types/api/index.ts
@@ -65,6 +65,8 @@ export enum AppEvent {
onDeepLink = 'onDeepLink',
onMainViewStateChange = 'onMainViewStateChange',
+
+ onBackendVerificationFailed = 'onBackendVerificationFailed',
}
export enum DownloadEvent {
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.ts
index a1a91ddf9..d77240188 100644
--- a/extensions/llamacpp-extension/src/backend.ts
+++ b/extensions/llamacpp-extension/src/backend.ts
@@ -1,17 +1,15 @@
import { getJanDataFolderPath, fs, joinPath, events } from '@janhq/core'
import { invoke } from '@tauri-apps/api/core'
-import { getProxyConfig, basenameNoExt } from './util'
+import { getProxyConfig } from './util'
import { dirname } from '@tauri-apps/api/path'
import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
import {
- mapOldBackendToNew,
getLocalInstalledBackendsInternal,
normalizeFeatures,
determineSupportedBackends,
listSupportedBackendsFromRust,
BackendVersion,
getSupportedFeaturesFromRust,
- isCudaInstalledFromRust,
} from '@janhq/tauri-plugin-llamacpp-api'
/*
@@ -29,46 +27,6 @@ export async function getLocalInstalledBackends(): Promise<
])
return await getLocalInstalledBackendsInternal(backendDir)
}
-/*
- * currently reads available backends in remote
- *
- */
-async function fetchRemoteSupportedBackends(
- supportedBackends: string[]
-): Promise<{ version: string; backend: string }[]> {
- // Pull the latest releases from the repo
- const { releases } = await _fetchGithubReleases('janhq', 'llama.cpp')
- releases.sort((a, b) => b.tag_name.localeCompare(a.tag_name))
- releases.splice(10) // keep only the latest 10 releases
-
- // Walk the assets and keep only those that match a supported backend
- const remote: { version: string; backend: string }[] = []
-
- for (const release of releases) {
- const version = release.tag_name
- const prefix = `llama-${version}-bin-`
-
- for (const asset of release.assets) {
- const name = asset.name
-
- if (!name.startsWith(prefix)) continue
-
- const backend = basenameNoExt(name).slice(prefix.length)
-
- if (supportedBackends.includes(backend)) {
- remote.push({ version, backend })
- continue
- }
- 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 })
- }
- }
- }
-
- return remote
-}
// folder structure
// <Jan's data folder>/llamacpp/backends/<backend_version>/<backend_type>
@@ -76,24 +34,27 @@ async function fetchRemoteSupportedBackends(
// what should be available to the user for selection?
export async function listSupportedBackends(): Promise<BackendVersion[]> {
const sysInfo = await getSystemInfo()
- const osType = sysInfo.os_type
- const arch = sysInfo.cpu.arch
-
- const rawFeatures = await _getSupportedFeatures()
+ const rawFeatures = await getSupportedFeaturesFromRust(
+ sysInfo.os_type,
+ sysInfo.cpu.extensions,
+ sysInfo.gpus
+ )
const features = normalizeFeatures(rawFeatures)
// Get supported backend names from Rust
const supportedBackends = await determineSupportedBackends(
- osType,
- arch,
+ sysInfo.os_type,
+ sysInfo.cpu.arch,
features
)
- // Get remote backends from Github
+ // Get remote backends via Rust (handles GitHub + CDN fallback)
let remoteBackendVersions: BackendVersion[] = []
try {
- remoteBackendVersions =
- await fetchRemoteSupportedBackends(supportedBackends)
+ remoteBackendVersions = await invoke(
+ 'plugin:llamacpp|fetch_remote_supported_backends',
+ { supportedBackends, proxy: getProxyConfig() }
+ )
} catch (e) {
console.debug(
`Not able to get remote backends, Jan might be offline or network problem: ${String(e)}`
@@ -104,50 +65,67 @@ export async function listSupportedBackends(): Promise<BackendVersion[]> {
const localBackendVersions = await getLocalInstalledBackends()
// Merge & sort via Rust
- return listSupportedBackendsFromRust(
- remoteBackendVersions,
- localBackendVersions
- )
+ return listSupportedBackendsFromRust(remoteBackendVersions, localBackendVersions)
}
export async function getBackendDir(
backend: string,
version: string
): Promise<string> {
- const janDataFolderPath = await getJanDataFolderPath()
- const backendDir = await joinPath([
- janDataFolderPath,
- 'llamacpp',
- 'backends',
- version,
+ const janDataFolder = await getJanDataFolderPath()
+ return invoke<string>('plugin:llamacpp|get_backend_dir', {
backend,
- ])
- return backendDir
+ version,
+ janDataFolder,
+ })
}
export async function getBackendExePath(
backend: string,
version: string
): Promise<string> {
- const exe_name = IS_WINDOWS ? 'llama-server.exe' : 'llama-server'
- const backendDir = await getBackendDir(backend, version)
- let exePath: string
- const buildDir = await joinPath([backendDir, 'build'])
- if (await fs.existsSync(buildDir)) {
- exePath = await joinPath([backendDir, 'build', 'bin', exe_name])
- } else {
- exePath = await joinPath([backendDir, exe_name])
- }
- return exePath
+ const janDataFolder = await getJanDataFolderPath()
+ return invoke<string>('plugin:llamacpp|get_backend_exe_path', {
+ backend,
+ version,
+ janDataFolder,
+ isWindows: IS_WINDOWS,
+ })
}
export async function isBackendInstalled(
backend: string,
version: string
): Promise<boolean> {
- const exePath = await getBackendExePath(backend, version)
- const result = await fs.existsSync(exePath)
- return result
+ const janDataFolder = await getJanDataFolderPath()
+ return invoke<boolean>('plugin:llamacpp|check_backend_installed', {
+ backend,
+ version,
+ janDataFolder,
+ isWindows: IS_WINDOWS,
+ })
+}
+
+export type BackendVerificationResult = {
+ verified: boolean
+ missing_libraries: string[]
+ resolved_libraries: string[]
+}
+
+export async function verifyBackendInstallation(
+ backend: string,
+ version: string
+): Promise<BackendVerificationResult> {
+ const janDataFolder = await getJanDataFolderPath()
+ return invoke<BackendVerificationResult>(
+ 'plugin:llamacpp|verify_backend_installation',
+ {
+ backend,
+ version,
+ janDataFolder,
+ isWindows: IS_WINDOWS,
+ }
+ )
}
export async function downloadBackend(
@@ -155,82 +133,39 @@ export async function downloadBackend(
version: string,
source: 'github' | 'cdn' = 'github'
): Promise<void> {
- const backendDir = await getBackendDir(backend, version)
-
- const downloadManager = window.core.extensionManager.getByName(
- '@janhq/download-extension'
- )
-
- // Get proxy configuration from localStorage
+ const janDataFolderPath = await getJanDataFolderPath()
+ const sysInfo = await getSystemInfo()
const proxyConfig = getProxyConfig()
- const platformName = IS_WINDOWS ? 'win' : 'linux'
+ const downloadItems: Array<{
+ url: string
+ save_path: string
+ model_id: string
+ proxy?: object
+ }> = await invoke('plugin:llamacpp|build_backend_download_items', {
+ backend,
+ version,
+ source,
+ janDataFolder: janDataFolderPath,
+ osType: sysInfo.os_type,
+ })
- // Build URLs per source
- const backendUrl =
- source === 'github'
- ? `https://github.com/janhq/llama.cpp/releases/download/${version}/llama-${version}-bin-${backend}.tar.gz`
- : `https://catalog.jan.ai/llama.cpp/releases/${version}/llama-${version}-bin-${backend}.tar.gz`
+ // Attach proxy config to each item
+ const itemsWithProxy = downloadItems.map((item) => ({
+ ...item,
+ proxy: proxyConfig,
+ }))
+ const downloadManager = window.core.extensionManager.getByName(
+ '@janhq/download-extension'
+ )
const taskId = `llamacpp-${version}-${backend}`.replace(/\./g, '-')
-
- const downloadItems = [
- {
- url: backendUrl,
- save_path: await joinPath([backendDir, 'backend.tar.gz']),
- proxy: proxyConfig,
- model_id: taskId,
- },
- ]
-
- // also download CUDA runtime + cuBLAS + cuBLASLt if needed
- if (
- (backend.includes('cu11.7') || backend.includes('cuda-11')) &&
- !(await _isCudaInstalled(backendDir, '11.7'))
- ) {
- downloadItems.push({
- url:
- source === 'github'
- ? `https://github.com/janhq/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu11.7-x64.tar.gz`
- : `https://catalog.jan.ai/llama.cpp/releases/${version}/cudart-llama-bin-${platformName}-cu11.7-x64.tar.gz`,
- save_path: await joinPath([backendDir, 'build', 'bin', 'cuda11.tar.gz']),
- proxy: proxyConfig,
- model_id: taskId,
- })
- } else if (
- (backend.includes('cu12.0') || backend.includes('cuda-12')) &&
- !(await _isCudaInstalled(backendDir, '12.0'))
- ) {
- downloadItems.push({
- url:
- source === 'github'
- ? `https://github.com/janhq/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu12.0-x64.tar.gz`
- : `https://catalog.jan.ai/llama.cpp/releases/${version}/cudart-llama-bin-${platformName}-cu12.0-x64.tar.gz`,
- save_path: await joinPath([backendDir, 'build', 'bin', 'cuda12.tar.gz']),
- proxy: proxyConfig,
- model_id: taskId,
- })
- } else if (
- backend.includes('cuda-13') &&
- !(await _isCudaInstalled(backendDir, '13.0'))
- ) {
- downloadItems.push({
- url:
- source === 'github'
- ? `https://github.com/janhq/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu13.0-x64.tar.gz`
- : `https://catalog.jan.ai/llama.cpp/releases/${version}/cudart-llama-bin-${platformName}-cu13.0-x64.tar.gz`,
- save_path: await joinPath([backendDir, 'build', 'bin', 'cuda13.tar.gz']),
- proxy: proxyConfig,
- model_id: taskId,
- })
- }
const downloadType = 'Engine'
console.log(
- `Downloading backend ${backend} version ${version} from ${source}: ${JSON.stringify(
- downloadItems
- )}`
+ `Downloading backend ${backend} version ${version} from ${source}: ${JSON.stringify(itemsWithProxy)}`
)
+
let downloadCompleted = false
try {
const onProgress = (transferred: number, total: number) => {
@@ -242,17 +177,14 @@ export async function downloadBackend(
})
downloadCompleted = transferred === total
}
- await downloadManager.downloadFiles(downloadItems, taskId, onProgress)
+ await downloadManager.downloadFiles(itemsWithProxy, taskId, onProgress)
- // once we reach this point, it either means download finishes or it was cancelled.
- // if there was an error, it would have been caught above
if (!downloadCompleted) {
events.emit('onFileDownloadStopped', { modelId: taskId, downloadType })
return
}
- // decompress the downloaded tar.gz files
- for (const { save_path } of downloadItems) {
+ for (const { save_path } of itemsWithProxy) {
if (save_path.endsWith('.tar.gz')) {
const parentDir = await dirname(save_path)
await invoke('decompress', { path: save_path, outputDir: parentDir })
@@ -262,7 +194,6 @@ export async function downloadBackend(
events.emit('onFileDownloadSuccess', { modelId: taskId, downloadType })
} catch (error) {
- // Fallback: if GitHub fails, retry once with CDN
if (
source === 'github' &&
error?.toString() !== 'Error: Download cancelled'
@@ -275,56 +206,3 @@ export async function downloadBackend(
throw error
}
}
-
-async function _getSupportedFeatures() {
- const sysInfo = await getSystemInfo()
- return await getSupportedFeaturesFromRust(
- sysInfo.os_type,
- sysInfo.cpu.extensions,
- sysInfo.gpus
- )
-}
-
-/**
- * Fetch releases with GitHub-first strategy and fallback to CDN on any error.
- * CDN endpoint is expected to mirror GitHub releases JSON shape.
- */
-async function _fetchGithubReleases(
- owner: string,
- repo: string
-): Promise<{ releases: any[]; source: 'github' | 'cdn' }> {
- const githubUrl = `https://api.github.com/repos/${owner}/${repo}/releases`
- try {
- const response = await fetch(githubUrl)
- if (!response.ok)
- throw new Error(`GitHub error: ${response.status} ${response.statusText}`)
- const releases = await response.json()
- return { releases, source: 'github' }
- } catch (_err) {
- const cdnUrl = 'https://catalog.jan.ai/llama.cpp/releases/releases.json'
- const response = await fetch(cdnUrl)
- if (!response.ok) {
- throw new Error(
- `Failed to fetch releases from both sources. CDN error: ${response.status} ${response.statusText}`
- )
- }
- const releases = await response.json()
- return { releases, source: 'cdn' }
- }
-}
-
-// accept backendDir (full path) and cuda version (e.g. '11.7' or '12.0' or '13.0')
-async function _isCudaInstalled(
- backendDir: string,
- version: string
-): Promise<boolean> {
- const sysInfo = await getSystemInfo()
- const janDataFolderPath = await getJanDataFolderPath()
-
- return isCudaInstalledFromRust(
- backendDir,
- version,
- sysInfo.os_type,
- janDataFolderPath
- )
-}
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 87ba05f8b..a6629d839 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -30,6 +30,7 @@ import {
listSupportedBackends,
downloadBackend,
isBackendInstalled,
+ verifyBackendInstallation,
getBackendExePath,
getBackendDir,
} from './backend'
@@ -489,6 +490,18 @@ export default class llamacpp_extension extends AIEngine {
if (!backendWasDownloaded && effectiveBackendString) {
await this.ensureFinalBackendInstallation(effectiveBackendString)
}
+
+ // Run dependency verification once after the backend is confirmed
+ // installed. This covers both fresh downloads and pre-existing installs,
+ // and runs only once per app startup via the isConfiguringBackends guard.
+ if (effectiveBackendString) {
+ // effectiveBackendString is expected to be "<version>/<backend>" (e.g.
+ // "b4589/linux-cuda-12"). Any other shape silently skips verification.
+ const [version, backend] = effectiveBackendString.split('/')
+ if (version && backend) {
+ await this.verifyBackendDeps(backend, version)
+ }
+ }
} finally {
this.isConfiguringBackends = false
}
@@ -1715,6 +1728,32 @@ export default class llamacpp_extension extends AIEngine {
return `${this.provider}/${cleanModelId}`
}
+ private async verifyBackendDeps(backend: string, version: string): Promise<void> {
+ const backendKey = `${version}/${backend}`
+ try {
+ const verification = await verifyBackendInstallation(backend, version)
+ if (verification.verified) {
+ logger.info(
+ `Backend ${backendKey} dependency verification passed (${verification.resolved_libraries.length} libraries resolved)`
+ )
+ } else {
+ logger.warn(
+ `Backend ${backendKey} is missing libraries: ${verification.missing_libraries.join(', ')}`
+ )
+ events.emit(AppEvent.onBackendVerificationFailed, {
+ backend,
+ version,
+ missingLibraries: verification.missing_libraries,
+ })
+ }
+ } catch (verifyErr) {
+ // Intentionally non-fatal: verification is advisory only. A BinaryNotFound
+ // error here means the exe disappeared between install and startup — the
+ // backend will fail naturally when first used, which is surfaced elsewhere.
+ logger.warn(`Backend ${backendKey} dependency verification failed: ${verifyErr}`)
+ }
+ }
+
private async ensureBackendReady(
backend: string,
version: string
diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.ts
index c88b6e12c..7ba0a3e34 100644
--- a/extensions/llamacpp-extension/src/test/backend.test.ts
+++ b/extensions/llamacpp-extension/src/test/backend.test.ts
@@ -4,14 +4,14 @@ import {
getBackendExePath,
isBackendInstalled,
downloadBackend,
+ verifyBackendInstallation,
} 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'
-import { isCudaInstalledFromRust } from '@janhq/tauri-plugin-llamacpp-api'
-// Mock constants: Hardcode path string directly inside the mock to avoid hoisting issues
+// Mock constants
const MOCK_JAN_PATH_STRING = '/path/to/jan'
// Mock the core dependencies
@@ -34,13 +34,12 @@ 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$/, '')),
+ getProxyConfig: vi.fn().mockReturnValue({ enabled: false }),
+ basenameNoExt: vi.fn((name: string) => 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()),
+ dirname: vi.fn(async (path: string) => path.split('/').slice(0, -1).join('/')),
+ basename: vi.fn(async (path: string) => path.split('/').pop()),
}))
vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {
const actual = await vi.importActual<
@@ -49,13 +48,9 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {
return {
...actual,
- isCudaInstalledFromRust: vi.fn().mockResolvedValue(false),
}
})
-// Mock the global fetch function
-global.fetch = vi.fn()
-
// Mock IS_WINDOWS and window.core global for environment setup
vi.stubGlobal('IS_WINDOWS', false)
vi.stubGlobal('window', {
@@ -79,10 +74,9 @@ vi.mocked(window.core.extensionManager.getByName).mockReturnValue(
)
describe('Backend functions', () => {
- beforeEach(() => {
+ beforeEach(async () => {
vi.clearAllMocks()
- // Mock getJanDataFolderPath explicitly to a simple path
- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
+ vi.mocked(getJanDataFolderPath).mockResolvedValue(MOCK_JAN_PATH_STRING)
vi.mocked(getSystemInfo).mockResolvedValue({
os_type: 'linux',
@@ -93,91 +87,191 @@ describe('Backend functions', () => {
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()
- vi.mocked(isCudaInstalledFromRust).mockResolvedValue(false)
+ // Re-apply after clearAllMocks wipes return values
+ const { getProxyConfig } = await import('../util')
+ vi.mocked(getProxyConfig).mockReturnValue({ enabled: false } as any)
})
afterEach(() => {
vi.restoreAllMocks()
})
-
- 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
+ describe('getBackendDir', () => {
+ it('should call invoke with correct params and return the path', async () => {
+ const expectedDir = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/linux-avx2-x64`
+ vi.mocked(invoke).mockResolvedValueOnce(expectedDir)
const dir = await getBackendDir('linux-avx2-x64', 'v1.2.3')
- expect(dir).toBe(`/path/to/jan/llamacpp/backends/v1.2.3/linux-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`
- )
+ expect(invoke).toHaveBeenCalledWith('plugin:llamacpp|get_backend_dir', {
+ backend: 'linux-avx2-x64',
+ version: 'v1.2.3',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ })
+ expect(dir).toBe(expectedDir)
})
- 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
+ it('should call invoke with correct params for new common backend name', async () => {
+ const expectedDir = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v2.0.0/win-common_cpus-x64`
+ vi.mocked(invoke).mockResolvedValueOnce(expectedDir)
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`
+
+ expect(invoke).toHaveBeenCalledWith('plugin:llamacpp|get_backend_dir', {
+ backend: 'win-common_cpus-x64',
+ version: 'v2.0.0',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ })
+ expect(dir).toBe(expectedDir)
+ })
+ })
+
+ describe('getBackendExePath', () => {
+ it('should call invoke with correct params including isWindows', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ const expectedExe = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/linux-avx2-x64/llama-server`
+ vi.mocked(invoke).mockResolvedValueOnce(expectedExe)
+
+ const exePath = await getBackendExePath('linux-avx2-x64', 'v1.2.3')
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|get_backend_exe_path',
+ {
+ backend: 'linux-avx2-x64',
+ version: 'v1.2.3',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ isWindows: false,
+ }
)
+ expect(exePath).toBe(expectedExe)
+ })
- 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`
+ it('should pass isWindows=true on Windows', async () => {
+ vi.stubGlobal('IS_WINDOWS', true)
+ const expectedExe = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/win-avx2-x64/llama-server.exe`
+ vi.mocked(invoke).mockResolvedValueOnce(expectedExe)
+
+ const exePath = await getBackendExePath('win-avx2-x64', 'v1.2.3')
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|get_backend_exe_path',
+ {
+ backend: 'win-avx2-x64',
+ version: 'v1.2.3',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ isWindows: true,
+ }
)
+ expect(exePath).toBe(expectedExe)
})
})
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 = `/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
- })
+ it('should call invoke with correct params and return true when installed', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ vi.mocked(invoke).mockResolvedValueOnce(true)
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`
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|check_backend_installed',
+ {
+ backend: 'win-avx2-x64',
+ version: 'v1.0.0',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ isWindows: false,
+ }
)
+ expect(result).toBe(true)
})
- })
- 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
- })
+
+ it('should return false when backend is not installed', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ vi.mocked(invoke).mockResolvedValueOnce(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(
- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/build/bin/llama-server`
+
+ expect(result).toBe(false)
+ })
+ })
+
+ describe('verifyBackendInstallation', () => {
+ it('should invoke verify_backend_installation with correct params on Linux', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ const mockResult = {
+ verified: true,
+ missing_libraries: [],
+ resolved_libraries: ['libvulkan.so.1', 'libstdc++.so.6'],
+ }
+ vi.mocked(invoke).mockResolvedValueOnce(mockResult)
+
+ const result = await verifyBackendInstallation(
+ 'linux-vulkan-common_cpus-x64',
+ 'b8795'
+ )
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|verify_backend_installation',
+ {
+ backend: 'linux-vulkan-common_cpus-x64',
+ version: 'b8795',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ isWindows: false,
+ }
+ )
+ expect(result.verified).toBe(true)
+ expect(result.missing_libraries).toHaveLength(0)
+ expect(result.resolved_libraries).toHaveLength(2)
+ })
+
+ it('should return verified=false with missing library list when deps are absent', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ const mockResult = {
+ verified: false,
+ missing_libraries: ['libvulkan.so.1', 'libcuda.so.1'],
+ resolved_libraries: ['libstdc++.so.6'],
+ }
+ vi.mocked(invoke).mockResolvedValueOnce(mockResult)
+
+ const result = await verifyBackendInstallation(
+ 'linux-vulkan-common_cpus-x64',
+ 'b8795'
+ )
+
+ expect(result.verified).toBe(false)
+ expect(result.missing_libraries).toEqual(['libvulkan.so.1', 'libcuda.so.1'])
+ })
+
+ it('should pass isWindows=true on Windows', async () => {
+ vi.stubGlobal('IS_WINDOWS', true)
+ const mockResult = {
+ verified: true,
+ missing_libraries: [],
+ resolved_libraries: ['KERNEL32.dll'],
+ }
+ vi.mocked(invoke).mockResolvedValueOnce(mockResult)
+
+ await verifyBackendInstallation('win-common_cpus-x64', 'b8795')
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|verify_backend_installation',
+ expect.objectContaining({ isWindows: true })
+ )
+ })
+
+ it('should propagate invoke errors', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ vi.mocked(invoke).mockRejectedValueOnce(
+ new Error('BINARY_NOT_FOUND')
)
+
+ await expect(
+ verifyBackendInstallation('linux-common_cpus-x64', 'b8795')
+ ).rejects.toThrow('BINARY_NOT_FOUND')
})
})
@@ -190,14 +284,47 @@ describe('Backend functions', () => {
return Promise.resolve()
}
)
+ })
+
+ it('should call build_backend_download_items and pass items with proxy to downloadFiles', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ const taskId = 'llamacpp-v1-0-0-linux-avx2-x64'
+ const mockItems = [
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz`,
+ model_id: taskId,
+ },
+ ]
+
vi.mocked(invoke).mockImplementation(async (command: string) => {
- if (command === 'is_library_available') return false
+ if (command === 'plugin:llamacpp|build_backend_download_items')
+ return mockItems
if (command === 'decompress') return undefined
return undefined
})
- vi.mocked(fs.rm).mockResolvedValue(undefined)
+
+ await downloadBackend('linux-avx2-x64', 'v1.0.0')
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|build_backend_download_items',
+ {
+ backend: 'linux-avx2-x64',
+ version: 'v1.0.0',
+ source: 'github',
+ janDataFolder: MOCK_JAN_PATH_STRING,
+ osType: 'linux',
+ }
+ )
+
+ const downloadItems =
+ vi.mocked(mockDownloadManager.downloadFiles).mock.calls[0][0]
+ expect(downloadItems.length).toBe(1)
+ expect(downloadItems[0].url).toContain('linux-avx2-x64.tar.gz')
+ expect(downloadItems[0].proxy).toBeDefined()
})
- it('should include cudart for cuda-12-common_cpus if not installed', async () => {
+
+ it('should include cudart for cuda-12-common_cpus if Rust returns two items', async () => {
vi.stubGlobal('IS_WINDOWS', true)
vi.mocked(getSystemInfo).mockResolvedValue({
os_type: 'windows',
@@ -210,26 +337,45 @@ describe('Backend functions', () => {
],
} as any)
+ const taskId = 'llamacpp-v1-0-0-win-cuda-12-common_cpus-x64'
+ const mockItems = [
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-win-cuda-12-common_cpus-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/backend.tar.gz`,
+ model_id: taskId,
+ },
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/cudart-llama-bin-win-cu12.0-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/build/bin/cuda12.tar.gz`,
+ model_id: taskId,
+ },
+ ]
+
+ vi.mocked(invoke).mockImplementation(async (command: string) => {
+ if (command === 'plugin:llamacpp|build_backend_download_items')
+ return mockItems
+ if (command === 'decompress') return undefined
+ return undefined
+ })
+
await downloadBackend('win-cuda-12-common_cpus-x64', 'v1.0.0')
- const downloadItems = vi.mocked(mockDownloadManager.downloadFiles).mock
- .calls[0][0]
+ 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(downloadItems[0].url).toContain('win-cuda-12-common_cpus-x64.tar.gz')
expect(downloadItems[0].save_path).toBe(
`${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/backend.tar.gz`
)
- expect(downloadItems[1].url).toContain(
- 'cudart-llama-bin-win-cu12.0-x64.tar.gz'
- )
+ expect(downloadItems[1].url).toContain('cudart-llama-bin-win-cu12.0-x64.tar.gz')
expect(downloadItems[1].save_path).toBe(
`${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/build/bin/cuda12.tar.gz`
)
+ expect(downloadItems[0].proxy).toBeDefined()
+ expect(downloadItems[1].proxy).toBeDefined()
})
- it('should include cudart for old cuda-cu11.7 if not installed', async () => {
+ it('should include cudart for old cuda-cu11.7 if Rust returns two items', async () => {
vi.stubGlobal('IS_WINDOWS', false)
vi.mocked(getSystemInfo).mockResolvedValue({
os_type: 'linux',
@@ -242,48 +388,121 @@ describe('Backend functions', () => {
],
} as any)
- // Downloading old name asset
+ const taskId = 'llamacpp-v1-0-0-linux-avx2-cuda-cu11-7-x64'
+ const mockItems = [
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-cuda-cu11.7-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/backend.tar.gz`,
+ model_id: taskId,
+ },
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/cudart-llama-bin-linux-cu11.7-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/build/bin/cuda11.tar.gz`,
+ model_id: taskId,
+ },
+ ]
+
+ vi.mocked(invoke).mockImplementation(async (command: string) => {
+ if (command === 'plugin:llamacpp|build_backend_download_items')
+ return mockItems
+ if (command === 'decompress') return undefined
+ return undefined
+ })
+
await downloadBackend('linux-avx2-cuda-cu11.7-x64', 'v1.0.0')
- const downloadItems = vi.mocked(mockDownloadManager.downloadFiles).mock
- .calls[0][0]
+ 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[0].url).toContain('linux-avx2-cuda-cu11.7-x64.tar.gz')
expect(downloadItems[0].save_path).toBe(
`${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/backend.tar.gz`
)
- expect(downloadItems[1].url).toContain(
- 'cudart-llama-bin-linux-cu11.7-x64.tar.gz'
- )
+ expect(downloadItems[1].url).toContain('cudart-llama-bin-linux-cu11.7-x64.tar.gz')
expect(downloadItems[1].save_path).toBe(
`${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/build/bin/cuda11.tar.gz`
)
})
- it('should correctly extract parent directory from Windows paths', async () => {
+ it('should correctly call decompress for .tar.gz files and use dirname for outputDir', async () => {
vi.stubGlobal('IS_WINDOWS', true)
-
- // Mock getSystemInfo for Windows/x64
vi.mocked(getSystemInfo).mockResolvedValue({
os_type: 'windows',
cpu: { arch: 'x86_64', extensions: [] },
gpus: [],
} as any)
- // Mock dirname to return Windows-style path components (for dirname mock)
+ const taskId = 'llamacpp-v1-0-0-win-avx2-x64'
+ const backendTarPath = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/backend.tar.gz`
+ const mockItems = [
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-win-avx2-x64.tar.gz',
+ save_path: backendTarPath,
+ model_id: taskId,
+ },
+ ]
+
+ vi.mocked(invoke).mockImplementation(async (command: string) => {
+ if (command === 'plugin:llamacpp|build_backend_download_items')
+ return mockItems
+ if (command === 'decompress') return undefined
+ return undefined
+ })
+
vi.mocked(dirname).mockResolvedValue(
`${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`
)
await downloadBackend('win-avx2-x64', 'v1.0.0')
- // Verify decompress was called with correct parent directory
expect(invoke).toHaveBeenCalledWith('decompress', {
- path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/backend.tar.gz`,
+ path: backendTarPath,
outputDir: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`,
})
})
+
+ it('should fall back to CDN when GitHub download fails', async () => {
+ vi.stubGlobal('IS_WINDOWS', false)
+ vi.mocked(getSystemInfo).mockResolvedValue({
+ os_type: 'linux',
+ cpu: { arch: 'x86_64', extensions: [] },
+ gpus: [],
+ } as any)
+
+ const taskId = 'llamacpp-v1-0-0-linux-avx2-x64'
+ const mockItems = [
+ {
+ url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-x64.tar.gz',
+ save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz`,
+ model_id: taskId,
+ },
+ ]
+
+ // invoke always returns items (both github and cdn calls)
+ vi.mocked(invoke).mockImplementation(async (command: string) => {
+ if (command === 'plugin:llamacpp|build_backend_download_items')
+ return mockItems
+ if (command === 'decompress') return undefined
+ return undefined
+ })
+
+ // First downloadFiles call (github) throws; second (cdn) succeeds
+ vi.mocked(mockDownloadManager.downloadFiles)
+ .mockRejectedValueOnce(new Error('Network error'))
+ .mockImplementation((items, _taskId, onProgress) => {
+ if (onProgress) onProgress(100, 100)
+ return Promise.resolve()
+ })
+
+ await downloadBackend('linux-avx2-x64', 'v1.0.0')
+
+ // Should have been called twice (github + cdn fallback)
+ expect(mockDownloadManager.downloadFiles).toHaveBeenCalledTimes(2)
+ // Second call should use cdn source
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|build_backend_download_items',
+ expect.objectContaining({ source: 'cdn' })
+ )
+ })
})
})
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
index 04e0d927d..0adc825ea 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
@@ -15,6 +15,8 @@ base64 = "0.22.1"
byteorder = "1.5.0"
hmac = "0.12.1"
jan-utils = { path = "../../utils" }
+lddtree = "0.5"
+walkdir = "2"
log = "0.4"
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
@@ -24,6 +26,7 @@ tauri = { version = "2.5.0", default-features = false, features = [] }
thiserror = "2.0.12"
tokio = { version = "1", features = ["full"] }
tauri-plugin-hardware = { path = "../tauri-plugin-hardware" }
+serde_json = "1.0.149"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
reqwest = { version = "0.11", features = ["json", "blocking", "stream", "native-tls"] }
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index d8f21dfd7..23d7b2908 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -33,6 +33,13 @@ const COMMANDS: &[&str] = &[
"validate_backend_string",
"should_migrate_backend",
"handle_setting_update",
+ // Backend path & download commands
+ "get_backend_dir",
+ "get_backend_exe_path",
+ "check_backend_installed",
+ "verify_backend_installation",
+ "fetch_remote_supported_backends",
+ "build_backend_download_items",
];
fn main() {
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
index 4e71b2931..09ee44ede 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -35,6 +35,12 @@ Default permissions for the llamacpp plugin
- `allow-validate-backend-string`
- `allow-should-migrate-backend`
- `allow-handle-setting-update`
+- `allow-get-backend-dir`
+- `allow-get-backend-exe-path`
+- `allow-check-backend-installed`
+- `allow-verify-backend-installation`
+- `allow-fetch-remote-supported-backends`
+- `allow-build-backend-download-items`
## Permission Table
@@ -45,6 +51,32 @@ Default permissions for the llamacpp plugin
</tr>
+<tr>
+<td>
+
+`llamacpp:allow-build-backend-download-items`
+
+</td>
+<td>
+
+Enables the build_backend_download_items command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-build-backend-download-items`
+
+</td>
+<td>
+
+Denies the build_backend_download_items command without any pre-configured scope.
+
+</td>
+</tr>
+
<tr>
<td>
@@ -74,6 +106,32 @@ Denies the check_backend_for_updates command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-check-backend-installed`
+
+</td>
+<td>
+
+Enables the check_backend_installed command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-check-backend-installed`
+
+</td>
+<td>
+
+Denies the check_backend_installed command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-cleanup-llama-processes`
</td>
@@ -178,6 +236,32 @@ Denies the estimate_kv_cache_size command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-fetch-remote-supported-backends`
+
+</td>
+<td>
+
+Enables the fetch_remote_supported_backends command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-fetch-remote-supported-backends`
+
+</td>
+<td>
+
+Denies the fetch_remote_supported_backends command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-find-latest-version-for-backend`
</td>
@@ -282,6 +366,58 @@ Denies the get_all_sessions command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-get-backend-dir`
+
+</td>
+<td>
+
+Enables the get_backend_dir command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-get-backend-dir`
+
+</td>
+<td>
+
+Denies the get_backend_dir command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:allow-get-backend-exe-path`
+
+</td>
+<td>
+
+Enables the get_backend_exe_path command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-get-backend-exe-path`
+
+</td>
+<td>
+
+Denies the get_backend_exe_path command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-get-devices`
</td>
@@ -1056,6 +1192,32 @@ Enables the validate_backend_string command without any pre-configured scope.
Denies the validate_backend_string command without any pre-configured scope.
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:allow-verify-backend-installation`
+
+</td>
+<td>
+
+Enables the verify_backend_installation command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-verify-backend-installation`
+
+</td>
+<td>
+
+Denies the verify_backend_installation 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.toml
index 43e264157..3be448c8a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -38,5 +38,13 @@ permissions = [
"allow-remove-old-backend-versions",
"allow-validate-backend-string",
"allow-should-migrate-backend",
- "allow-handle-setting-update"
+ "allow-handle-setting-update",
+
+ # Backend path & download commands
+ "allow-get-backend-dir",
+ "allow-get-backend-exe-path",
+ "allow-check-backend-installed",
+ "allow-verify-backend-installation",
+ "allow-fetch-remote-supported-backends",
+ "allow-build-backend-download-items"
]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
index a62af9dbc..e3f7c6c01 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 build_backend_download_items command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-build-backend-download-items",
+ "markdownDescription": "Enables the build_backend_download_items command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the build_backend_download_items command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-build-backend-download-items",
+ "markdownDescription": "Denies the build_backend_download_items command without any pre-configured scope."
+ },
{
"description": "Enables the check_backend_for_updates command without any pre-configured scope.",
"type": "string",
@@ -306,6 +318,18 @@
"const": "deny-check-backend-for-updates",
"markdownDescription": "Denies the check_backend_for_updates command without any pre-configured scope."
},
+ {
+ "description": "Enables the check_backend_installed command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-check-backend-installed",
+ "markdownDescription": "Enables the check_backend_installed command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the check_backend_installed command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-check-backend-installed",
+ "markdownDescription": "Denies the check_backend_installed command without any pre-configured scope."
+ },
{
"description": "Enables the cleanup_llama_processes command without any pre-configured scope.",
"type": "string",
@@ -354,6 +378,18 @@
"const": "deny-estimate-kv-cache-size",
"markdownDescription": "Denies the estimate_kv_cache_size command without any pre-configured scope."
},
+ {
+ "description": "Enables the fetch_remote_supported_backends command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-fetch-remote-supported-backends",
+ "markdownDescription": "Enables the fetch_remote_supported_backends command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the fetch_remote_supported_backends command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-fetch-remote-supported-backends",
+ "markdownDescription": "Denies the fetch_remote_supported_backends command without any pre-configured scope."
+ },
{
"description": "Enables the find_latest_version_for_backend command without any pre-configured scope.",
"type": "string",
@@ -402,6 +438,30 @@
"const": "deny-get-all-sessions",
"markdownDescription": "Denies the get_all_sessions command without any pre-configured scope."
},
+ {
+ "description": "Enables the get_backend_dir command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-backend-dir",
+ "markdownDescription": "Enables the get_backend_dir command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_backend_dir command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-backend-dir",
+ "markdownDescription": "Denies the get_backend_dir command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the get_backend_exe_path command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-backend-exe-path",
+ "markdownDescription": "Enables the get_backend_exe_path command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_backend_exe_path command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-backend-exe-path",
+ "markdownDescription": "Denies the get_backend_exe_path command without any pre-configured scope."
+ },
{
"description": "Enables the get_devices command without any pre-configured scope.",
"type": "string",
@@ -763,10 +823,22 @@
"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-ensure-session-ready`\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`",
+ "description": "Enables the verify_backend_installation command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-verify-backend-installation",
+ "markdownDescription": "Enables the verify_backend_installation command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the verify_backend_installation command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-verify-backend-installation",
+ "markdownDescription": "Denies the verify_backend_installation 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-ensure-session-ready`\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`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`",
"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-ensure-session-ready`\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`"
+ "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-ensure-session-ready`\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`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
index 93d83823b..6a2d4b784 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
@@ -804,6 +804,415 @@ pub fn should_migrate_backend(
}
}
+// ============================================================================
+// Backend Path & Installation Commands
+// ============================================================================
+
+#[tauri::command]
+pub fn get_backend_dir(backend: String, version: String, jan_data_folder: String) -> String {
+ PathBuf::from(&jan_data_folder)
+ .join("llamacpp")
+ .join("backends")
+ .join(&version)
+ .join(&backend)
+ .to_string_lossy()
+ .to_string()
+}
+
+#[tauri::command]
+pub fn get_backend_exe_path(
+ backend: String,
+ version: String,
+ jan_data_folder: String,
+ is_windows: bool,
+) -> String {
+ let backend_dir = PathBuf::from(get_backend_dir(backend, version, jan_data_folder));
+ let exe_name = if is_windows {
+ "llama-server.exe"
+ } else {
+ "llama-server"
+ };
+
+ let build_path = backend_dir.join("build").join("bin").join(exe_name);
+ if build_path.exists() {
+ return build_path.to_string_lossy().to_string();
+ }
+
+ backend_dir.join(exe_name).to_string_lossy().to_string()
+}
+
+#[tauri::command]
+pub fn check_backend_installed(
+ backend: String,
+ version: String,
+ jan_data_folder: String,
+ is_windows: bool,
+) -> bool {
+ let exe_path =
+ PathBuf::from(get_backend_exe_path(backend, version, jan_data_folder, is_windows));
+ exe_path.exists()
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BackendVerificationResult {
+ pub verified: bool,
+ pub missing_libraries: Vec<String>,
+ pub resolved_libraries: Vec<String>,
+}
+
+fn expected_gpu_lib_name(backend: &str) -> Option<&'static str> {
+ let b = backend.to_lowercase();
+ let is_windows = cfg!(target_os = "windows");
+ if b.contains("cuda") {
+ Some(if is_windows { "ggml-cuda.dll" } else { "libggml-cuda.so" })
+ } else if b.contains("vulkan") {
+ Some(if is_windows { "ggml-vulkan.dll" } else { "libggml-vulkan.so" })
+ } else {
+ None
+ }
+}
+
+fn verify_backend_dependencies(
+ bin_dir: &PathBuf,
+ exe_path: &PathBuf,
+ backend: &str,
+) -> Result<BackendVerificationResult, crate::error::LlamacppError> {
+ if !bin_dir.exists() {
+ return Err(crate::error::LlamacppError::new(
+ crate::error::ErrorCode::BinaryNotFound,
+ "Backend directory not found".into(),
+ Some(bin_dir.to_string_lossy().to_string()),
+ ));
+ }
+
+ let start = std::time::Instant::now();
+ let mut missing: std::collections::HashSet<String> = std::collections::HashSet::new();
+
+ // Existence check runs before parsing so a deleted lib is caught without
+ // handing a bad path to goblin.
+ let gpu_lib_path: Option<PathBuf> = if cfg!(target_os = "macos") {
+ None
+ } else {
+ expected_gpu_lib_name(backend).and_then(|name| {
+ let path = bin_dir.join(name);
+ if path.exists() {
+ Some(path)
+ } else {
+ missing.insert(name.to_string());
+ None
+ }
+ })
+ };
+
+ // Skip CPU variants (ggml-cpu-haswell, etc.) — they're loaded only when
+ // the host's detected features match, so parsing them false-flags deps.
+ let mut paths: Vec<PathBuf> = vec![exe_path.clone()];
+ if let Some(p) = gpu_lib_path {
+ paths.push(p);
+ }
+
+ let analysis = crate::deps_analyzer::analyze_out_of_process(bin_dir, &paths);
+
+ let resolved: std::collections::HashSet<String> = analysis.resolved.into_iter().collect();
+ for name in analysis.missing {
+ missing.insert(name);
+ }
+
+ // A lib may be resolved by one binary but missing for another — keep only
+ // libs that no binary resolved.
+ let mut truly_missing: Vec<String> =
+ missing.difference(&resolved).cloned().collect();
+ let mut resolved_vec: Vec<String> = resolved.into_iter().collect();
+ truly_missing.sort();
+ resolved_vec.sort();
+
+ let elapsed = start.elapsed();
+ log::info!(
+ "verify_backend_dependencies: scanned {} in {:.2}s ({} resolved, {} missing)",
+ bin_dir.display(),
+ elapsed.as_secs_f64(),
+ resolved_vec.len(),
+ truly_missing.len(),
+ );
+
+ Ok(BackendVerificationResult {
+ verified: truly_missing.is_empty(),
+ missing_libraries: truly_missing,
+ resolved_libraries: resolved_vec,
+ })
+}
+
+#[tauri::command]
+pub async fn verify_backend_installation(
+ backend: String,
+ version: String,
+ jan_data_folder: String,
+ is_windows: bool,
+) -> Result<BackendVerificationResult, crate::error::LlamacppError> {
+ let exe_path =
+ PathBuf::from(get_backend_exe_path(backend.clone(), version.clone(), jan_data_folder.clone(), is_windows));
+ if !exe_path.exists() {
+ return Err(crate::error::LlamacppError::new(
+ crate::error::ErrorCode::BinaryNotFound,
+ "Backend executable not found".into(),
+ Some(exe_path.to_string_lossy().to_string()),
+ ));
+ }
+ // Libs sit next to the exe (build/bin/ when present); backend_dir is too high.
+ let bin_dir = exe_path
+ .parent()
+ .map(PathBuf::from)
+ .unwrap_or_else(|| PathBuf::from(get_backend_dir(backend.clone(), version, jan_data_folder)));
+ tokio::task::spawn_blocking(move || verify_backend_dependencies(&bin_dir, &exe_path, &backend))
+ .await
+ .map_err(|e| crate::error::LlamacppError::new(
+ crate::error::ErrorCode::InternalError,
+ "Dependency verification task panicked".into(),
+ Some(e.to_string()),
+ ))?
+}
+
+// ============================================================================
+// Remote Backend Fetching
+// ============================================================================
+
+#[derive(Deserialize)]
+struct GithubRelease {
+ tag_name: String,
+ assets: Vec<GithubAsset>,
+}
+
+#[derive(Deserialize)]
+struct GithubAsset {
+ name: String,
+}
+
+/// Subset of the app's ProxyConfig needed to build a reqwest proxy. Kept local
+/// to avoid a cross-crate dependency on the app crate. Shape must stay in sync
+/// with the TS `getProxyConfig()` payload and the app's `ProxyConfig` struct.
+#[derive(Deserialize, Clone, Debug)]
+pub struct ProxyConfig {
+ pub url: String,
+ pub username: Option<String>,
+ pub password: Option<String>,
+ pub ignore_ssl: Option<bool>,
+}
+
+fn build_http_client(proxy: Option<&ProxyConfig>) -> Result<reqwest::Client, String> {
+ let mut builder = reqwest::Client::builder().user_agent("jan-app");
+
+ if let Some(cfg) = proxy {
+ if !cfg.url.trim().is_empty() {
+ let mut p = reqwest::Proxy::all(&cfg.url)
+ .map_err(|e| format!("Invalid proxy URL: {}", e))?;
+ if let (Some(u), Some(pw)) = (&cfg.username, &cfg.password) {
+ if !u.is_empty() {
+ p = p.basic_auth(u, pw);
+ }
+ }
+ builder = builder.proxy(p);
+ if cfg.ignore_ssl.unwrap_or(false) {
+ builder = builder.danger_accept_invalid_certs(true);
+ }
+ }
+ }
+
+ builder
+ .build()
+ .map_err(|e| format!("Failed to build HTTP client: {}", e))
+}
+
+#[tauri::command]
+pub async fn fetch_remote_supported_backends(
+ supported_backends: Vec<String>,
+ proxy: Option<ProxyConfig>,
+) -> Result<Vec<BackendInfo>, String> {
+ let client = build_http_client(proxy.as_ref())?;
+
+ let releases: Vec<GithubRelease> = {
+ let primary = client
+ .get("https://api.github.com/repos/janhq/llama.cpp/releases")
+ .send()
+ .await;
+
+ match primary {
+ Ok(resp) if resp.status().is_success() => resp
+ .json::<Vec<GithubRelease>>()
+ .await
+ .map_err(|e| format!("Failed to parse GitHub releases JSON: {}", e))?,
+ _ => {
+ // Fallback to catalog mirror
+ let fallback = client
+ .get("https://catalog.jan.ai/llama.cpp/releases/releases.json")
+ .send()
+ .await
+ .map_err(|e| format!("Both GitHub and fallback requests failed: {}", e))?;
+
+ fallback
+ .json::<Vec<GithubRelease>>()
+ .await
+ .map_err(|e| format!("Failed to parse fallback releases JSON: {}", e))?
+ }
+ }
+ };
+
+ // Take the first 10 (already sorted descending by tag_name from GitHub)
+ let mut result: Vec<BackendInfo> = Vec::new();
+ let mut sorted_releases = releases;
+ sorted_releases.sort_by(|a, b| b.tag_name.cmp(&a.tag_name));
+
+ for release in sorted_releases.into_iter().take(10) {
+ let version = &release.tag_name;
+ for asset in &release.assets {
+ // Expected format: llama-{version}-bin-{backend}.tar.gz
+ let prefix = format!("llama-{}-bin-", version);
+ let suffix = ".tar.gz";
+ if asset.name.starts_with(&prefix) && asset.name.ends_with(suffix) {
+ let backend = asset.name[prefix.len()..asset.name.len() - suffix.len()].to_string();
+ let mapped = map_old_backend_to_new(backend.clone());
+ if supported_backends.contains(&backend) || supported_backends.contains(&mapped) {
+ result.push(BackendInfo {
+ version: version.clone(),
+ backend,
+ });
+ }
+ }
+ }
+ }
+
+ Ok(result)
+}
+
+// ============================================================================
+// Backend Download Item Builder
+// ============================================================================
+
+#[derive(Serialize, Deserialize)]
+pub struct BackendDownloadItem {
+ pub url: String,
+ pub save_path: String,
+ pub model_id: String,
+}
+
+/// Internal helper: check if a CUDA runtime library is present at the new
+/// location (`backend_dir/build/bin/{libname}`) without performing any
+/// migration side-effects.
+fn check_cuda_installed_internal(backend_dir: &str, cuda_version: &str, os_type: &str) -> bool {
+ let libname: &str = match (os_type, cuda_version) {
+ ("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",
+ _ => return false,
+ };
+
+ PathBuf::from(backend_dir)
+ .join("build")
+ .join("bin")
+ .join(libname)
+ .exists()
+}
+
+#[tauri::command]
+pub fn build_backend_download_items(
+ backend: String,
+ version: String,
+ source: String,
+ jan_data_folder: String,
+ os_type: String,
+) -> Result<Vec<BackendDownloadItem>, String> {
+ let backend_dir = get_backend_dir(backend.clone(), version.clone(), jan_data_folder.clone());
+ let task_id = format!("llamacpp-{}-{}", version, backend).replace('.', "-");
+ let platform_name = if os_type == "windows" { "win" } else { "linux" };
+
+ // Base URL for the main backend archive
+ let backend_url = match source.as_str() {
+ "github" => format!(
+ "https://github.com/janhq/llama.cpp/releases/download/{}/llama-{}-bin-{}.tar.gz",
+ version, version, backend
+ ),
+ _ => format!(
+ "https://catalog.jan.ai/llama.cpp/releases/{}/llama-{}-bin-{}.tar.gz",
+ version, version, backend
+ ),
+ };
+
+ let save_path = format!("{}/backend.tar.gz", backend_dir);
+
+ let mut items = vec![BackendDownloadItem {
+ url: backend_url,
+ save_path,
+ model_id: task_id.clone(),
+ }];
+
+ // CUDA runtime items
+ if backend.contains("cu11.7") || backend.contains("cuda-11") {
+ let already_installed =
+ check_cuda_installed_internal(&backend_dir, "11.7", &os_type);
+ if !already_installed {
+ let cuda_url = match source.as_str() {
+ "github" => format!(
+ "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu11.7-x64.tar.gz",
+ version, platform_name
+ ),
+ _ => format!(
+ "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu11.7-x64.tar.gz",
+ version, platform_name
+ ),
+ };
+ items.push(BackendDownloadItem {
+ url: cuda_url,
+ save_path: format!("{}/build/bin/cuda11.tar.gz", backend_dir),
+ model_id: task_id.clone(),
+ });
+ }
+ } else if backend.contains("cu12.0") || backend.contains("cuda-12") {
+ let already_installed =
+ check_cuda_installed_internal(&backend_dir, "12.0", &os_type);
+ if !already_installed {
+ let cuda_url = match source.as_str() {
+ "github" => format!(
+ "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu12.0-x64.tar.gz",
+ version, platform_name
+ ),
+ _ => format!(
+ "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu12.0-x64.tar.gz",
+ version, platform_name
+ ),
+ };
+ items.push(BackendDownloadItem {
+ url: cuda_url,
+ save_path: format!("{}/build/bin/cuda12.tar.gz", backend_dir),
+ model_id: task_id.clone(),
+ });
+ }
+ } else if backend.contains("cuda-13") {
+ let already_installed =
+ check_cuda_installed_internal(&backend_dir, "13.0", &os_type);
+ if !already_installed {
+ let cuda_url = match source.as_str() {
+ "github" => format!(
+ "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu13.0-x64.tar.gz",
+ version, platform_name
+ ),
+ _ => format!(
+ "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu13.0-x64.tar.gz",
+ version, platform_name
+ ),
+ };
+ items.push(BackendDownloadItem {
+ url: cuda_url,
+ save_path: format!("{}/build/bin/cuda13.tar.gz", backend_dir),
+ model_id: task_id.clone(),
+ });
+ }
+ }
+
+ Ok(items)
+}
+
// ============================================================================
// Settings Update Handler
// ============================================================================
@@ -1321,4 +1730,321 @@ mod tests {
let result = should_migrate_backend(new_backend, available).unwrap();
assert_eq!(result, None);
}
+
+ // -------------------------------------------------------------------------
+ // Tests for get_backend_dir
+ // -------------------------------------------------------------------------
+
+ #[test]
+ fn test_get_backend_dir_path_format() {
+ let result = get_backend_dir(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "/home/user/.jan".to_string(),
+ );
+ assert!(result.contains("llamacpp"));
+ assert!(result.contains("backends"));
+ assert!(result.contains("b7523"));
+ assert!(result.contains("linux-common_cpus-x64"));
+ // Ensure the segments are in the right order
+ let path = PathBuf::from(&result);
+ let components: Vec<_> = path.components().collect();
+ let names: Vec<String> = components
+ .iter()
+ .map(|c| c.as_os_str().to_string_lossy().to_string())
+ .collect();
+ let llamacpp_idx = names.iter().position(|n| n == "llamacpp").unwrap();
+ let backends_idx = names.iter().position(|n| n == "backends").unwrap();
+ let version_idx = names.iter().position(|n| n == "b7523").unwrap();
+ let backend_idx = names.iter().position(|n| n == "linux-common_cpus-x64").unwrap();
+ assert!(llamacpp_idx < backends_idx);
+ assert!(backends_idx < version_idx);
+ assert!(version_idx < backend_idx);
+ }
+
+ // -------------------------------------------------------------------------
+ // Tests for get_backend_exe_path
+ // -------------------------------------------------------------------------
+
+ #[test]
+ fn test_get_backend_exe_path_no_build_dir_linux() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let result = get_backend_exe_path(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data.clone(),
+ false,
+ );
+ // Should fall back to root dir (build dir doesn't exist)
+ assert!(result.ends_with("llama-server"));
+ assert!(!result.ends_with("llama-server.exe"));
+ }
+
+ #[test]
+ fn test_get_backend_exe_path_no_build_dir_windows() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let result = get_backend_exe_path(
+ "win-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ true,
+ );
+ assert!(result.ends_with("llama-server.exe"));
+ }
+
+ #[test]
+ fn test_get_backend_exe_path_with_build_dir() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ // Create the build/bin directory and place the exe there
+ let backend_dir = PathBuf::from(&jan_data)
+ .join("llamacpp")
+ .join("backends")
+ .join("b7523")
+ .join("linux-common_cpus-x64");
+ let build_bin = backend_dir.join("build").join("bin");
+ fs::create_dir_all(&build_bin).unwrap();
+ File::create(build_bin.join("llama-server")).unwrap();
+
+ let result = get_backend_exe_path(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ false,
+ );
+ assert!(result.contains("build"));
+ assert!(result.contains("bin"));
+ assert!(result.ends_with("llama-server"));
+ }
+
+ // -------------------------------------------------------------------------
+ // Tests for check_backend_installed
+ // -------------------------------------------------------------------------
+
+ #[test]
+ fn test_check_backend_installed_true() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let backend_dir = PathBuf::from(&jan_data)
+ .join("llamacpp")
+ .join("backends")
+ .join("b7523")
+ .join("linux-common_cpus-x64");
+ fs::create_dir_all(&backend_dir).unwrap();
+ File::create(backend_dir.join("llama-server")).unwrap();
+
+ let result = check_backend_installed(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ false,
+ );
+ assert!(result);
+ }
+
+ #[test]
+ fn test_check_backend_installed_false_when_missing() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let result = check_backend_installed(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ false,
+ );
+ assert!(!result);
+ }
+
+ // -------------------------------------------------------------------------
+ // Tests for verify_backend_installation
+ // -------------------------------------------------------------------------
+
+ #[tokio::test]
+ async fn test_verify_backend_installation_returns_err_when_exe_missing() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let result = verify_backend_installation(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ false,
+ )
+ .await;
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(matches!(err.code, crate::error::ErrorCode::BinaryNotFound));
+ }
+
+ #[test]
+ fn test_verify_backend_dependencies_returns_err_on_missing_dir() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let nonexistent = temp_dir.path().join("does-not-exist");
+
+ let exe = nonexistent.join("llama-server");
+ let result = verify_backend_dependencies(&nonexistent, &exe, "linux-common_cpus-x64");
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(matches!(err.code, crate::error::ErrorCode::BinaryNotFound));
+ }
+
+ #[test]
+ fn test_verify_backend_dependencies_skips_unparseable_files() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ // An unparseable file in the dir should be silently skipped, not error.
+ fs::write(temp_dir.path().join("llama-server"), b"not a real binary").unwrap();
+ fs::write(temp_dir.path().join("libggml.so"), b"not a real binary").unwrap();
+
+ let dir = temp_dir.path().to_path_buf();
+ let exe = dir.join("llama-server");
+ let result = verify_backend_dependencies(&dir, &exe, "linux-common_cpus-x64");
+
+ // Succeeds with an empty result — nothing parseable, nothing missing.
+ assert!(result.is_ok());
+ let r = result.unwrap();
+ assert!(r.verified);
+ assert!(r.missing_libraries.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_verify_backend_installation_scans_whole_backend_dir() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ // Create the backend dir with a stub exe and a stub DLL beside it.
+ let backend_dir = PathBuf::from(&jan_data)
+ .join("llamacpp")
+ .join("backends")
+ .join("b7523")
+ .join("linux-common_cpus-x64");
+ fs::create_dir_all(&backend_dir).unwrap();
+ fs::write(backend_dir.join("llama-server"), b"not a real binary").unwrap();
+ fs::write(backend_dir.join("libggml.so"), b"not a real binary").unwrap();
+
+ // Both files are unparseable stubs — verify_backend_installation must
+ // return Ok (nothing missing) rather than Err, confirming it walks the
+ // whole directory and skips non-binaries rather than hard-failing.
+ let result = verify_backend_installation(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ jan_data,
+ false,
+ )
+ .await;
+ assert!(result.is_ok());
+ let r = result.unwrap();
+ assert!(r.verified);
+ }
+
+ #[test]
+ fn test_is_virtual_windows_dll() {
+ assert!(crate::deps_analyzer::is_virtual_windows_dll("api-ms-win-core-memory-l1-1-0.dll"));
+ assert!(crate::deps_analyzer::is_virtual_windows_dll("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.DLL"));
+ assert!(crate::deps_analyzer::is_virtual_windows_dll("ext-ms-win-ntuser-draw-l1-1-0.dll"));
+ assert!(!crate::deps_analyzer::is_virtual_windows_dll("KERNEL32.dll"));
+ assert!(!crate::deps_analyzer::is_virtual_windows_dll("libcuda.so.1"));
+ assert!(!crate::deps_analyzer::is_virtual_windows_dll("libvulkan.so.1"));
+ }
+
+ // -------------------------------------------------------------------------
+ // Tests for build_backend_download_items
+ // -------------------------------------------------------------------------
+
+ #[test]
+ fn test_build_backend_download_items_non_cuda_returns_one_item() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let items = build_backend_download_items(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "github".to_string(),
+ jan_data,
+ "linux".to_string(),
+ )
+ .unwrap();
+
+ assert_eq!(items.len(), 1);
+ assert!(items[0].url.contains("linux-common_cpus-x64"));
+ assert!(items[0].url.contains("github.com"));
+ }
+
+ #[test]
+ fn test_build_backend_download_items_cuda12_returns_two_items() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let items = build_backend_download_items(
+ "linux-cuda-12-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "github".to_string(),
+ jan_data,
+ "linux".to_string(),
+ )
+ .unwrap();
+
+ assert_eq!(items.len(), 2);
+ assert!(items[1].url.contains("cu12.0"));
+ assert!(items[1].save_path.ends_with("cuda12.tar.gz"));
+ // All items must share the same model_id for unified progress tracking
+ assert_eq!(items[0].model_id, items[1].model_id);
+ }
+
+ #[test]
+ fn test_build_backend_download_items_cu11_returns_two_items() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let items = build_backend_download_items(
+ "linux-cu11.7-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "cdn".to_string(),
+ jan_data,
+ "linux".to_string(),
+ )
+ .unwrap();
+
+ assert_eq!(items.len(), 2);
+ assert!(items[1].url.contains("cu11.7"));
+ assert!(items[1].save_path.ends_with("cuda11.tar.gz"));
+ // All items must share the same model_id for unified progress tracking
+ assert_eq!(items[0].model_id, items[1].model_id);
+ }
+
+ #[test]
+ fn test_build_backend_download_items_github_vs_cdn_urls() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let jan_data = temp_dir.path().to_string_lossy().to_string();
+
+ let github_items = build_backend_download_items(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "github".to_string(),
+ jan_data.clone(),
+ "linux".to_string(),
+ )
+ .unwrap();
+
+ let cdn_items = build_backend_download_items(
+ "linux-common_cpus-x64".to_string(),
+ "b7523".to_string(),
+ "cdn".to_string(),
+ jan_data,
+ "linux".to_string(),
+ )
+ .unwrap();
+
+ assert!(github_items[0].url.contains("github.com"));
+ assert!(cdn_items[0].url.contains("catalog.jan.ai"));
+ assert_ne!(github_items[0].url, cdn_items[0].url);
+ }
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs
new file mode 100644
index 000000000..d87fb8276
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs
@@ -0,0 +1,141 @@
+//! Out-of-process shared-library dependency analyzer. `lddtree`/`goblin` can
+//! panic or segfault on malformed binaries; running it in a subprocess keeps
+//! a crash from taking down the app.
+
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+
+pub const ANALYZE_FLAG: &str = "--internal-analyze-deps";
+
+#[derive(Debug, Serialize, Deserialize, Default)]
+pub struct AnalyzeOutput {
+ pub missing: Vec<String>,
+ pub resolved: Vec<String>,
+}
+
+pub fn run_deps_analyzer_if_requested() {
+ let mut args = std::env::args().skip(1);
+ if args.next().as_deref() != Some(ANALYZE_FLAG) {
+ return;
+ }
+
+ let lib_dir = match args.next() {
+ Some(d) => PathBuf::from(d),
+ None => {
+ eprintln!("{}: missing <lib_dir> argument", ANALYZE_FLAG);
+ std::process::exit(2);
+ }
+ };
+ let targets: Vec<PathBuf> = args.map(PathBuf::from).collect();
+
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ analyze(&lib_dir, &targets)
+ }));
+
+ match result {
+ Ok(out) => match serde_json::to_string(&out) {
+ Ok(s) => {
+ println!("{}", s);
+ std::process::exit(0);
+ }
+ Err(e) => {
+ eprintln!("serialize failed: {}", e);
+ std::process::exit(3);
+ }
+ },
+ Err(e) => {
+ let msg = e
+ .downcast_ref::<&str>()
+ .copied()
+ .or_else(|| e.downcast_ref::<String>().map(|s| s.as_str()))
+ .unwrap_or("unknown panic");
+ eprintln!("lddtree panic: {}", msg);
+ std::process::exit(4);
+ }
+ }
+}
+
+fn analyze(lib_dir: &Path, targets: &[PathBuf]) -> AnalyzeOutput {
+ let analyzer =
+ lddtree::DependencyAnalyzer::default().add_library_path(lib_dir.to_path_buf());
+
+ let mut missing: HashSet<String> = HashSet::new();
+ let mut resolved: HashSet<String> = HashSet::new();
+
+ for path in targets {
+ let tree = match analyzer.clone().analyze(path) {
+ Ok(t) => t,
+ Err(_) => continue,
+ };
+ for (name, lib) in &tree.libraries {
+ if lib.found() {
+ resolved.insert(name.clone());
+ } else if !is_virtual_windows_dll(name) {
+ missing.insert(name.clone());
+ }
+ }
+ }
+
+ let mut missing: Vec<String> = missing.into_iter().collect();
+ let mut resolved: Vec<String> = resolved.into_iter().collect();
+ missing.sort();
+ resolved.sort();
+ AnalyzeOutput { missing, resolved }
+}
+
+// api-ms-win-*/ext-ms-win-* are virtual DLLs resolved by the Windows kernel
+// and never exist on disk — lddtree flags them as missing but they aren't.
+pub(crate) fn is_virtual_windows_dll(name: &str) -> bool {
+ let lower = name.to_lowercase();
+ lower.starts_with("api-ms-win-") || lower.starts_with("ext-ms-win-")
+}
+
+pub fn analyze_out_of_process(lib_dir: &Path, targets: &[PathBuf]) -> AnalyzeOutput {
+ let exe = match std::env::current_exe() {
+ Ok(p) => p,
+ Err(e) => {
+ log::warn!("deps_analyzer: current_exe failed: {}", e);
+ return AnalyzeOutput::default();
+ }
+ };
+
+ let mut cmd = Command::new(&exe);
+ cmd.arg(ANALYZE_FLAG).arg(lib_dir);
+ for t in targets {
+ cmd.arg(t);
+ }
+ cmd.stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ let output = match cmd.output() {
+ Ok(o) => o,
+ Err(e) => {
+ log::warn!("deps_analyzer: failed to spawn subprocess: {}", e);
+ return AnalyzeOutput::default();
+ }
+ };
+
+ if !output.status.success() {
+ log::warn!(
+ "deps_analyzer: subprocess exited with {:?}; stderr: {}",
+ output.status.code(),
+ String::from_utf8_lossy(&output.stderr).trim(),
+ );
+ return AnalyzeOutput::default();
+ }
+
+ match serde_json::from_slice::<AnalyzeOutput>(&output.stdout) {
+ Ok(o) => o,
+ Err(e) => {
+ log::warn!(
+ "deps_analyzer: malformed subprocess output: {} (stdout: {})",
+ e,
+ String::from_utf8_lossy(&output.stdout).trim(),
+ );
+ AnalyzeOutput::default()
+ }
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 4207069e9..410e8e3f0 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -6,6 +6,7 @@ use tauri::{
mod args;
mod backend;
pub mod cleanup;
+pub mod deps_analyzer;
mod commands;
mod device;
mod error;
@@ -55,7 +56,14 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
backend::remove_old_backend_versions,
backend::validate_backend_string,
backend::should_migrate_backend,
- backend::handle_setting_update
+ backend::handle_setting_update,
+ // Backend path & download commands
+ backend::get_backend_dir,
+ backend::get_backend_exe_path,
+ backend::check_backend_installed,
+ backend::verify_backend_installation,
+ backend::fetch_remote_supported_backends,
+ backend::build_backend_download_items
])
.setup(|app, _api| {
// Initialize and manage the plugin state
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 5193402df..3de5058cb 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,8 +2,12 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
+ // Fix PATH before anything that may spawn subprocesses, so the lddtree
+ // helper (and any other child) inherits directories added by fix_path_env.
let _ = fix_path_env::fix();
- // Normal Tauri app startup
+ // Exits early if invoked as the out-of-process lddtree helper.
+ tauri_plugin_llamacpp::deps_analyzer::run_deps_analyzer_if_requested();
+
app_lib::run();
}
diff --git a/web-app/src/containers/dialogs/BackendUpdater.tsx b/web-app/src/containers/dialogs/BackendUpdater.tsx
index 761e2f73d..60c437d21 100644
--- a/web-app/src/containers/dialogs/BackendUpdater.tsx
+++ b/web-app/src/containers/dialogs/BackendUpdater.tsx
@@ -50,6 +50,11 @@ const BackendUpdater = () => {
return null
}
+ // Don't show if auto-update is enabled — the engine updates silently
+ if (updateState.autoUpdateEnabled) {
+ return null
+ }
+
// Don't show if user clicked remind me later
if (backendUpdateState.remindMeLater) {
console.log('BackendUpdater: Not showing notification due to:', {
diff --git a/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx
new file mode 100644
index 000000000..facfb80cd
--- /dev/null
+++ b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx
@@ -0,0 +1,335 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { AlertTriangle, ChevronDown, ChevronUp, ExternalLink } from 'lucide-react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { events, AppEvent } from '@janhq/core'
+import { useEffect, useState } from 'react'
+
+type VerificationFailedPayload = {
+ backend: string
+ version: string
+ missingLibraries: string[]
+}
+
+/** Maps a raw backend identifier to a human-readable display name. */
+function getBackendDisplayName(backend: string): string {
+ const b = backend.toLowerCase()
+ if (b.includes('cuda-13') || b.includes('cuda13')) return 'NVIDIA CUDA 13 Backend'
+ if (b.includes('cuda-12') || b.includes('cuda12')) return 'NVIDIA CUDA 12 Backend'
+ if (b.includes('cuda-11') || b.includes('cuda11')) return 'NVIDIA CUDA 11 Backend'
+ if (b.includes('cuda')) return 'NVIDIA CUDA Backend'
+ if (b.includes('vulkan')) return 'Vulkan Backend'
+ if (b.includes('metal')) return 'Apple Metal Backend'
+ if (b.includes('cpu') || b.includes('common_cpu') || b.includes('common-cpu')) return 'CPU Backend'
+ return backend
+}
+
+type InstallRecommendation = {
+ label: string
+ description: string
+ url?: string
+ /** Raw lib names that triggered this recommendation */
+ libs: string[]
+}
+
+/**
+ * Groups raw missing library names into actionable install recommendations.
+ * Returns recommendations and any libs not covered by a known group.
+ */
+function getInstallRecommendations(
+ missingLibs: string[],
+ backend: string
+): { recommendations: InstallRecommendation[]; uncovered: string[] } {
+ const b = backend.toLowerCase()
+ const isWindows = IS_WINDOWS
+ const isLinux = IS_LINUX
+
+ const cudaVersion = b.includes('cuda-13') || b.includes('cuda13')
+ ? '13'
+ : b.includes('cuda-12') || b.includes('cuda12')
+ ? '12'
+ : b.includes('cuda-11') || b.includes('cuda11')
+ ? '11'
+ : null
+
+ const recommendations: InstallRecommendation[] = []
+ const coveredLibs = new Set<string>()
+
+ // Bundled backend libs must be checked FIRST so that names like
+ // libggml-cuda.so are claimed here rather than by the CUDA filter below.
+ // These are shipped inside the backend archive — missing means corrupted download.
+ const bundledLibs = missingLibs.filter((lib) => {
+ const l = lib.toLowerCase()
+ return l.includes('ggml') || l.includes('llama')
+ })
+ if (bundledLibs.length > 0) {
+ bundledLibs.forEach((l) => coveredLibs.add(l))
+ recommendations.push({
+ label: 'Re-download the backend',
+ description:
+ 'Some core backend files are missing or corrupted — this usually means the download was interrupted or the archive was only partially extracted. Delete the backend and re-download it from Jan settings.',
+ libs: bundledLibs,
+ })
+ }
+
+ // CUDA runtime/compute libs. Filters against coveredLibs so that bundled
+ // libs like libggml-cuda.so are not double-counted here.
+ const cudaLibs = missingLibs.filter((lib) => {
+ if (coveredLibs.has(lib)) return false
+ const l = lib.toLowerCase()
+ return (
+ l.startsWith('libcuda') ||
+ l.startsWith('cuda') ||
+ l.includes('cublas') ||
+ l.includes('curand') ||
+ l.includes('cufft') ||
+ l.includes('cusolver') ||
+ l.includes('cusparse') ||
+ l.includes('cudart') ||
+ l.startsWith('nvcuda') ||
+ l === 'cuda.dll'
+ )
+ })
+ if (cudaLibs.length > 0) {
+ cudaLibs.forEach((l) => coveredLibs.add(l))
+ const versionSuffix = cudaVersion ? ` ${cudaVersion}` : ''
+ recommendations.push({
+ label: `NVIDIA CUDA Toolkit${versionSuffix}`,
+ description: isWindows
+ ? `Install the CUDA Toolkit${versionSuffix} from NVIDIA. During installation, select "CUDA" components.`
+ : `Install the CUDA Toolkit${versionSuffix} from NVIDIA. On Debian/Ubuntu: sudo apt install cuda-toolkit-${cudaVersion ?? '12'}. On RHEL/Fedora: use the NVIDIA repo.`,
+ url: 'https://developer.nvidia.com/cuda-downloads',
+ libs: cudaLibs,
+ })
+ }
+
+ // NCCL — only relevant on CUDA backends; guard on cudaVersion to avoid
+ // false positives on CPU/Vulkan backends.
+ const ncclLibs = cudaVersion !== null
+ ? missingLibs.filter((lib) => !coveredLibs.has(lib) && lib.toLowerCase().includes('nccl'))
+ : []
+ if (ncclLibs.length > 0) {
+ ncclLibs.forEach((l) => coveredLibs.add(l))
+ recommendations.push({
+ label: 'NVIDIA NCCL',
+ description: isWindows
+ ? 'Install NCCL from the NVIDIA Developer site. NCCL is used for multi-GPU collective communications.'
+ : 'Install NCCL via the NVIDIA package repository. On Debian/Ubuntu: sudo apt install libnccl2 libnccl-dev. See the NVIDIA NCCL install guide for your distro.',
+ url: 'https://developer.nvidia.com/nccl/nccl-download',
+ libs: ncclLibs,
+ })
+ }
+
+ // cuDNN libs
+ const cudnnLibs = missingLibs.filter((lib) => !coveredLibs.has(lib) && lib.toLowerCase().includes('cudnn'))
+ if (cudnnLibs.length > 0) {
+ cudnnLibs.forEach((l) => coveredLibs.add(l))
+ recommendations.push({
+ label: 'NVIDIA cuDNN',
+ description: isWindows
+ ? 'Install cuDNN from the NVIDIA Developer site and place the DLLs alongside the application or in System32.'
+ : 'Install cuDNN via the NVIDIA package repository or download the tarball and copy libs to /usr/local/cuda/lib64.',
+ url: 'https://developer.nvidia.com/cudnn-downloads',
+ libs: cudnnLibs,
+ })
+ }
+
+ // Vulkan libs
+ const vulkanLibs = missingLibs.filter((lib) => {
+ if (coveredLibs.has(lib)) return false
+ const l = lib.toLowerCase()
+ return l.includes('vulkan') || l === 'libvulkan.so' || l === 'libvulkan.so.1' || l === 'vulkan-1.dll'
+ })
+ if (vulkanLibs.length > 0) {
+ vulkanLibs.forEach((l) => coveredLibs.add(l))
+ const vulkanUrl = isWindows
+ ? 'https://vulkan.lunarg.com/sdk/home#windows'
+ : isLinux
+ ? 'https://vulkan.lunarg.com/sdk/home#linux'
+ : 'https://vulkan.lunarg.com/sdk/home'
+ recommendations.push({
+ label: 'Vulkan Runtime',
+ description: isWindows
+ ? 'Install the Vulkan Runtime from LunarG. Your GPU driver may already include it — update your GPU driver first.'
+ : 'Install the Vulkan loader: on Ubuntu/Debian: sudo apt install libvulkan1. On Arch: sudo pacman -S vulkan-icd-loader. On RHEL/Fedora: sudo dnf install vulkan-loader.',
+ url: vulkanUrl,
+ libs: vulkanLibs,
+ })
+ }
+
+ const uncovered = missingLibs.filter((lib) => !coveredLibs.has(lib))
+ return { recommendations, uncovered }
+}
+
+export default function MissingDependenciesDialog() {
+ const { t } = useTranslation()
+ const [payload, setPayload] = useState<VerificationFailedPayload | undefined>()
+ const [showRawLibs, setShowRawLibs] = useState(false)
+
+ useEffect(() => {
+ const handler = (data: VerificationFailedPayload) => {
+ setPayload(data)
+ setShowRawLibs(false)
+ }
+ events.on(AppEvent.onBackendVerificationFailed, handler)
+ return () => {
+ events.off(AppEvent.onBackendVerificationFailed, handler)
+ }
+ }, [])
+
+ const displayName = payload ? getBackendDisplayName(payload.backend) : ''
+ const { recommendations, uncovered } = payload
+ ? getInstallRecommendations(payload.missingLibraries, payload.backend)
+ : { recommendations: [], uncovered: [] }
+ const allRawLibs = payload?.missingLibraries ?? []
+
+ return (
+ <Dialog
+ open={!!payload}
+ onOpenChange={(open) => !open && setPayload(undefined)}
+ >
+ <DialogContent showCloseButton={false}>
+ <DialogHeader>
+ <div className="flex items-start gap-3">
+ <div className="shrink-0 mt-0.5">
+ <AlertTriangle className="size-4 text-destructive" />
+ </div>
+ <div>
+ <DialogTitle>
+ {t('common:missingDependenciesDialog.title')}
+ </DialogTitle>
+ <DialogDescription className="mt-1 text-main-view-fg/70">
+ {t('common:missingDependenciesDialog.description', {
+ backend: displayName,
+ })}
+ </DialogDescription>
+ </div>
+ </div>
+ </DialogHeader>
+
+ <div className="space-y-3">
+ {recommendations.length > 0 ? (
+ <>
+ <p className="text-sm text-main-view-fg/60">
+ {t('common:missingDependenciesDialog.installLabel')}
+ </p>
+ <ul className="space-y-2">
+ {recommendations.map((rec) => (
+ <li
+ key={rec.label}
+ className="rounded-lg border border-main-view-fg/10 bg-main-view-fg/2 p-3 space-y-1"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm font-medium text-main-view-fg">
+ {rec.label}
+ </span>
+ {rec.url && (
+ <a
+ href={rec.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-xs text-blue-400 hover:text-blue-300 shrink-0"
+ >
+ {t('common:missingDependenciesDialog.download')}
+ <ExternalLink className="size-3" />
+ </a>
+ )}
+ </div>
+ <p className="text-xs text-main-view-fg/60 leading-relaxed">
+ {rec.description}
+ </p>
+ </li>
+ ))}
+ </ul>
+
+ {uncovered.length > 0 && (
+ <div className="space-y-1">
+ <p className="text-xs text-main-view-fg/50">
+ {t('common:missingDependenciesDialog.additionalLibraries')}
+ </p>
+ <ul className="space-y-1">
+ {uncovered.map((lib) => (
+ <li
+ key={lib}
+ className="text-xs font-mono text-main-view-fg/70 bg-main-view-fg/5 px-2 py-1 rounded border border-main-view-fg/5 break-all"
+ >
+ {lib}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </>
+ ) : (
+ // No known group — fall back to raw list
+ <div className="space-y-1">
+ <p className="text-sm text-main-view-fg/60">
+ {t('common:missingDependenciesDialog.missingLibraries')}
+ </p>
+ <ul className="max-h-[180px] overflow-y-auto space-y-1">
+ {allRawLibs.map((lib) => (
+ <li
+ key={lib}
+ className="text-sm font-mono text-main-view-fg/80 bg-main-view-fg/10 px-2 py-1 rounded border border-main-view-fg/5 break-all"
+ >
+ {lib}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* Collapsible raw lib names when recommendations are shown */}
+ {recommendations.length > 0 && allRawLibs.length > 0 && (
+ <div>
+ <button
+ type="button"
+ onClick={() => setShowRawLibs((v) => !v)}
+ className="flex items-center gap-1 text-xs text-main-view-fg/40 hover:text-main-view-fg/60 transition-colors"
+ >
+ {showRawLibs ? (
+ <ChevronUp className="size-3" />
+ ) : (
+ <ChevronDown className="size-3" />
+ )}
+ {t('common:missingDependenciesDialog.showRawLibraries', {
+ count: allRawLibs.length,
+ })}
+ </button>
+ {showRawLibs && (
+ <ul className="mt-2 max-h-[120px] overflow-y-auto space-y-1">
+ {allRawLibs.map((lib) => (
+ <li
+ key={lib}
+ className="text-xs font-mono text-main-view-fg/50 bg-main-view-fg/5 px-2 py-0.5 rounded break-all"
+ >
+ {lib}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </div>
+
+ <DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end">
+ <Button
+ variant="link"
+ onClick={() => setPayload(undefined)}
+ autoFocus
+ className="flex-1 text-right sm:flex-none border border-main-view-fg/20 !px-2"
+ >
+ {t('common:dismiss')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-app/src/containers/dialogs/__tests__/SecurityConfigDialog.test.tsx b/web-app/src/containers/dialogs/__tests__/SecurityConfigDialog.test.tsx
index a4d7b9fb7..662a1eb46 100644
--- a/web-app/src/containers/dialogs/__tests__/SecurityConfigDialog.test.tsx
+++ b/web-app/src/containers/dialogs/__tests__/SecurityConfigDialog.test.tsx
@@ -96,7 +96,7 @@ describe('SecurityConfigDialog', () => {
})
render(<SecurityConfigDialog isOpen={true} onClose={vi.fn()} />)
await screen.findByText('Security Settings')
- fireEvent.click(screen.getByText('Devices'))
+ fireEvent.click(screen.getByRole('button', { name: /devices/i }))
await waitFor(() =>
expect(hoisted.invoke).toHaveBeenCalledWith('security_get_devices')
)
@@ -110,7 +110,7 @@ describe('SecurityConfigDialog', () => {
})
render(<SecurityConfigDialog isOpen={true} onClose={vi.fn()} />)
await screen.findByText('Security Settings')
- fireEvent.click(screen.getByText('Logs'))
+ fireEvent.click(await screen.findByRole('button', { name: /logs/i }))
await waitFor(() =>
expect(hoisted.invoke).toHaveBeenCalledWith('security_get_logs', {
limit: 100,
@@ -187,7 +187,7 @@ describe('SecurityConfigDialog', () => {
})
render(<SecurityConfigDialog isOpen={true} onClose={vi.fn()} />)
await screen.findByText('Security Settings')
- fireEvent.click(screen.getByText('Devices'))
+ fireEvent.click(screen.getByRole('button', { name: /devices/i }))
await screen.findByText('Require Device Pairing')
// Radix Switch exposes role="switch"
const sw = screen.getByRole('switch')
diff --git a/web-app/src/hooks/useAgentMode.ts b/web-app/src/hooks/useAgentMode.ts
index 4b1dd71b3..de677ce05 100644
--- a/web-app/src/hooks/useAgentMode.ts
+++ b/web-app/src/hooks/useAgentMode.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
type AgentModeState = {
/** Map of threadId → agent mode enabled */
@@ -56,7 +55,7 @@ export const useAgentMode = create<AgentModeState>()(
}),
{
name: localStorageKey.agentMode,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useAnalytic.ts b/web-app/src/hooks/useAnalytic.ts
index a01b81f43..0205ff1a5 100644
--- a/web-app/src/hooks/useAnalytic.ts
+++ b/web-app/src/hooks/useAnalytic.ts
@@ -1,5 +1,4 @@
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
@@ -47,7 +46,7 @@ export const useProductAnalyticPrompt = create<ProductAnalyticPromptState>()(
},
{
name: localStorageKey.productAnalyticPrompt,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
@@ -71,7 +70,7 @@ export const useProductAnalytic = create<ProductAnalyticState>()(
},
{
name: localStorageKey.productAnalytic,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useFavoriteModel.ts b/web-app/src/hooks/useFavoriteModel.ts
index 9d0ff0a1e..778c9f9d0 100644
--- a/web-app/src/hooks/useFavoriteModel.ts
+++ b/web-app/src/hooks/useFavoriteModel.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
interface FavoriteModelState {
favoriteModels: Model[]
@@ -48,7 +47,7 @@ export const useFavoriteModel = create<FavoriteModelState>()(
}),
{
name: localStorageKey.favoriteModels,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useGeneralSetting.ts b/web-app/src/hooks/useGeneralSetting.ts
index 501809c68..f78499cbd 100644
--- a/web-app/src/hooks/useGeneralSetting.ts
+++ b/web-app/src/hooks/useGeneralSetting.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { ExtensionManager } from '@/lib/extension'
type GeneralSettingState = {
currentLanguage: Language
@@ -49,7 +48,7 @@ export const useGeneralSetting = create<GeneralSettingState>()(
}),
{
name: localStorageKey.settingGeneral,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useHardware.ts b/web-app/src/hooks/useHardware.ts
index 703435cd4..183fa2490 100644
--- a/web-app/src/hooks/useHardware.ts
+++ b/web-app/src/hooks/useHardware.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
// Hardware data types
export interface CPU {
@@ -210,7 +209,7 @@ export const useHardware = create<HardwareStore>()(
}),
{
name: localStorageKey.settingHardware,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.ts
index 4f1ad5f9e..ffd642925 100644
--- a/web-app/src/hooks/useInterfaceSettings.ts
+++ b/web-app/src/hooks/useInterfaceSettings.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { useTheme } from './useTheme'
import {
getDefaultNotificationPosition,
@@ -142,7 +141,7 @@ const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {
}
const interfaceStorage = createJSONStorage<InterfaceSettingsPersistedSlice>(() =>
- fileStorage
+ localStorage
)
export const useInterfaceSettings = create<InterfaceSettingsState>()(
diff --git a/web-app/src/hooks/useJanModelPrompt.ts b/web-app/src/hooks/useJanModelPrompt.ts
index 5b03e984c..91dc0a400 100644
--- a/web-app/src/hooks/useJanModelPrompt.ts
+++ b/web-app/src/hooks/useJanModelPrompt.ts
@@ -1,5 +1,4 @@
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import { useModelProvider } from './useModelProvider'
@@ -23,7 +22,7 @@ export const useJanModelPromptDismissed =
}),
{
name: localStorageKey.janModelPromptDismissed,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
version: 1,
migrate: (persistedState: unknown) => {
const state = persistedState as Record<string, unknown>
diff --git a/web-app/src/hooks/useLatestJanModel.ts b/web-app/src/hooks/useLatestJanModel.ts
index 6c635692f..f139a85fa 100644
--- a/web-app/src/hooks/useLatestJanModel.ts
+++ b/web-app/src/hooks/useLatestJanModel.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey, CACHE_EXPIRY_MS } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { getServiceHub } from '@/hooks/useServiceHub'
import type { CatalogModel } from '@/services/models/types'
@@ -56,7 +55,7 @@ export const useLatestJanModel = create<LatestJanModelState>()(
}),
{
name: localStorageKey.latestJanModel,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
model: state.model,
lastFetchedAt: state.lastFetchedAt,
diff --git a/web-app/src/hooks/useLeftPanel.ts b/web-app/src/hooks/useLeftPanel.ts
index 108ac38d8..d1909f1ff 100644
--- a/web-app/src/hooks/useLeftPanel.ts
+++ b/web-app/src/hooks/useLeftPanel.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
type LeftPanelStoreState = {
open: boolean
@@ -24,7 +23,7 @@ export const useLeftPanel = create<LeftPanelStoreState>()(
}),
{
name: localStorageKey.LeftPanel,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useLocalApiServer.ts b/web-app/src/hooks/useLocalApiServer.ts
index cbddfa34c..109189bf3 100644
--- a/web-app/src/hooks/useLocalApiServer.ts
+++ b/web-app/src/hooks/useLocalApiServer.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
type LocalApiServerState = {
// Run local API server once app opens
@@ -86,7 +85,7 @@ export const useLocalApiServer = create<LocalApiServerState>()(
}),
{
name: localStorageKey.settingLocalApiServer,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
version: 3,
migrate: (persistedState: unknown, version: number) => {
const state = persistedState as Partial<LocalApiServerState>
diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.ts
index 738e69a47..1dca9640f 100644
--- a/web-app/src/hooks/useModelProvider.ts
+++ b/web-app/src/hooks/useModelProvider.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { getServiceHub } from '@/hooks/useServiceHub'
import { modelSettings } from '@/lib/predefined'
@@ -240,7 +239,7 @@ export const useModelProvider = create<ModelProviderState>()(
}),
{
name: localStorageKey.modelProvider,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
migrate: (persistedState: unknown, version: number) => {
const state = persistedState as ModelProviderState & {
providers: Array<
diff --git a/web-app/src/hooks/useModelSources.ts b/web-app/src/hooks/useModelSources.ts
index 4f6f4c180..5bf6b3e78 100644
--- a/web-app/src/hooks/useModelSources.ts
+++ b/web-app/src/hooks/useModelSources.ts
@@ -1,6 +1,5 @@
import { create } from 'zustand'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { createJSONStorage, persist } from 'zustand/middleware'
import { getServiceHub } from '@/hooks/useServiceHub'
import type { CatalogModel } from '@/services/models/types'
@@ -48,7 +47,7 @@ export const useModelSources = create<ModelSourcesState>()(
}),
{
name: localStorageKey.modelSources,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useProxyConfig.ts b/web-app/src/hooks/useProxyConfig.ts
index a7fe582e2..39754dfa0 100644
--- a/web-app/src/hooks/useProxyConfig.ts
+++ b/web-app/src/hooks/useProxyConfig.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
type ProxyConfigState = {
proxyEnabled: boolean
@@ -54,7 +53,7 @@ export const useProxyConfig = create<ProxyConfigState>()(
}),
{
name: localStorageKey.settingProxyConfig,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useTheme.ts b/web-app/src/hooks/useTheme.ts
index 92c9ab77e..35556a4e7 100644
--- a/web-app/src/hooks/useTheme.ts
+++ b/web-app/src/hooks/useTheme.ts
@@ -3,7 +3,6 @@ import { createJSONStorage, persist } from 'zustand/middleware'
import { getServiceHub } from '@/hooks/useServiceHub'
import type { ThemeMode } from '@/services/theme/types'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
// Function to check if OS prefers dark mode
export const checkOSDarkMode = (): boolean => {
@@ -53,7 +52,7 @@ export const useTheme = create<ThemeState>()(
},
{
name: localStorageKey.theme,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.ts
index fbf360bfe..0e49cb462 100644
--- a/web-app/src/hooks/useToolApproval.ts
+++ b/web-app/src/hooks/useToolApproval.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
export type ToolApprovalModalProps = {
toolName: string
@@ -113,7 +112,7 @@ export const useToolApproval = create<ToolApprovalState>()(
}),
{
name: localStorageKey.toolApproval,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
// Only persist approved tools and global permission setting, not modal state
partialize: (state) => ({
approvedTools: state.approvedTools,
diff --git a/web-app/src/hooks/useToolAvailable.ts b/web-app/src/hooks/useToolAvailable.ts
index 4a25fbcf8..0822c49cb 100644
--- a/web-app/src/hooks/useToolAvailable.ts
+++ b/web-app/src/hooks/useToolAvailable.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
import { MCPTool } from '@/types/completion'
// Helper function to create composite key for server+tool
@@ -151,7 +150,7 @@ export const useToolAvailable = create<ToolDisabledState>()(
}),
{
name: localStorageKey.toolAvailability,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
// Persist all state
partialize: (state) => ({
disabledTools: state.disabledTools,
diff --git a/web-app/src/hooks/useVulkan.ts b/web-app/src/hooks/useVulkan.ts
index 8621703ff..d71e04603 100644
--- a/web-app/src/hooks/useVulkan.ts
+++ b/web-app/src/hooks/useVulkan.ts
@@ -1,7 +1,6 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
-import { fileStorage } from '@/lib/fileStorage'
interface VulkanStore {
// Vulkan state
@@ -29,7 +28,7 @@ export const useVulkan = create<VulkanStore>()(
}),
{
name: localStorageKey.settingVulkan,
- storage: createJSONStorage(() => fileStorage),
+ storage: createJSONStorage(() => localStorage),
}
)
)
diff --git a/web-app/src/i18n/setup.ts b/web-app/src/i18n/setup.ts
index c3da52e65..9b4f4621e 100644
--- a/web-app/src/i18n/setup.ts
+++ b/web-app/src/i18n/setup.ts
@@ -1,4 +1,4 @@
-import { useGeneralSetting } from '@/hooks/useGeneralSetting'
+import { localStorageKey } from '@/constants/localStorage'
// Types for our i18n implementation
export interface TranslationResources {
@@ -51,13 +51,12 @@ Object.entries(localeFiles).forEach(([path, module]) => {
}
})
-// Get stored language preference from the zustand store.
-// During initial load the store may not have hydrated yet from file storage,
-// so we fall back to 'en'. The language updates once hydration completes
-// (see useGeneralSetting subscription at the bottom of this file).
+// Get stored language preference
const getStoredLanguage = (): string => {
try {
- return useGeneralSetting.getState().currentLanguage || 'en'
+ const stored = localStorage.getItem(localStorageKey.settingGeneral)
+ const parsed = stored ? JSON.parse(stored) : {}
+ return parsed?.state?.currentLanguage || 'en'
} catch {
return 'en'
}
@@ -114,8 +113,16 @@ const translate = (key: string, options: Record<string, unknown> = {}): string =
const changeLanguage = (lng: string): void => {
if (i18nInstance && resources[lng]) {
i18nInstance.language = lng
- // Persist via the zustand store — this writes through to file storage
- useGeneralSetting.getState().setCurrentLanguage(lng as Language)
+
+ // Update localStorage
+ try {
+ const stored = localStorage.getItem(localStorageKey.settingGeneral)
+ const parsed = stored ? JSON.parse(stored) : { state: {} }
+ parsed.state.currentLanguage = lng
+ localStorage.setItem(localStorageKey.settingGeneral, JSON.stringify(parsed))
+ } catch (error) {
+ console.error('Failed to save language preference:', error)
+ }
}
}
@@ -146,14 +153,4 @@ export const loadTranslations = (): void => {
// Initialize and export the i18n instance
const i18n = initI18n()
-// When the general settings store finishes hydrating from file storage,
-// update the i18n language in case it differs from the initial default.
-useGeneralSetting.subscribe((state) => {
- if (state.currentLanguage && state.currentLanguage !== i18nInstance.language) {
- if (resources[state.currentLanguage]) {
- i18nInstance.language = state.currentLanguage
- }
- }
-})
-
export default i18n
diff --git a/web-app/src/lib/__tests__/fileStorage.test.ts b/web-app/src/lib/__tests__/fileStorage.test.ts
deleted file mode 100644
index d877caa6a..000000000
--- a/web-app/src/lib/__tests__/fileStorage.test.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
-
-// In-memory backing store used by the mock Tauri plugin
-const mockStoreData = new Map<string, unknown>()
-const mockSave = vi.fn().mockResolvedValue(undefined)
-const mockStore = {
- get: vi.fn(async <T>(key: string): Promise<T | undefined> => {
- return mockStoreData.get(key) as T | undefined
- }),
- set: vi.fn(async (key: string, value: unknown) => {
- mockStoreData.set(key, value)
- }),
- delete: vi.fn(async (key: string) => {
- return mockStoreData.delete(key)
- }),
- save: mockSave,
-}
-
-vi.mock('@tauri-apps/api/core', () => ({
- invoke: vi.fn().mockResolvedValue('/mock/jan/data'),
-}))
-
-vi.mock('@tauri-apps/plugin-store', () => ({
- load: vi.fn().mockResolvedValue(mockStore),
-}))
-
-describe('fileStorage', () => {
- // Each describe block re-imports the module after setting/clearing
- // __TAURI_INTERNALS__ so IS_TAURI is evaluated fresh.
- let fileStorage: typeof import('../fileStorage').fileStorage
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockStoreData.clear()
- localStorage.clear()
- })
-
- afterEach(() => {
- delete (window as Record<string, unknown>).__TAURI_INTERNALS__
- })
-
- describe('when NOT in Tauri (browser fallback)', () => {
- beforeEach(async () => {
- delete (window as Record<string, unknown>).__TAURI_INTERNALS__
- vi.resetModules()
- const mod = await import('../fileStorage')
- fileStorage = mod.fileStorage
- })
-
- it('getItem reads from localStorage', async () => {
- localStorage.setItem('test-key', 'test-value')
- expect(await fileStorage.getItem('test-key')).toBe('test-value')
- })
-
- it('setItem writes to localStorage', async () => {
- await fileStorage.setItem('test-key', 'test-value')
- expect(localStorage.getItem('test-key')).toBe('test-value')
- })
-
- it('removeItem removes from localStorage', async () => {
- localStorage.setItem('test-key', 'to-be-removed')
- await fileStorage.removeItem('test-key')
- expect(localStorage.getItem('test-key')).toBeNull()
- })
-
- it('returns null for missing keys', async () => {
- expect(await fileStorage.getItem('nonexistent')).toBeNull()
- })
-
- it('never touches the Tauri store', async () => {
- await fileStorage.setItem('k', 'v')
- await fileStorage.getItem('k')
- expect(mockStore.get).not.toHaveBeenCalled()
- expect(mockStore.set).not.toHaveBeenCalled()
- })
- })
-
- describe('when in Tauri (file-backed storage)', () => {
- beforeEach(async () => {
- ;(window as Record<string, unknown>).__TAURI_INTERNALS__ = {}
- vi.resetModules()
- mockStoreData.clear()
- mockStore.get.mockClear()
- mockStore.set.mockClear()
- mockStore.delete.mockClear()
- mockSave.mockClear()
- const mod = await import('../fileStorage')
- fileStorage = mod.fileStorage
- })
-
- it('loads the store from the Jan data folder', async () => {
- // Trigger store init by calling any method
- await fileStorage.getItem('any-key')
- const { load } = await import('@tauri-apps/plugin-store')
- expect(load).toHaveBeenCalledWith(
- '/mock/jan/data/settings.json',
- { autoSave: false, defaults: {} }
- )
- })
-
- it('setItem writes to the file store', async () => {
- await fileStorage.setItem('my-setting', '{"theme":"dark"}')
- expect(mockStore.set).toHaveBeenCalledWith(
- 'my-setting',
- '{"theme":"dark"}'
- )
- })
-
- it('setItem triggers a disk save', async () => {
- await fileStorage.setItem('k', 'v')
- // save is fire-and-forget, give it a tick to resolve
- await new Promise((r) => setTimeout(r, 0))
- expect(mockSave).toHaveBeenCalled()
- })
-
- it('getItem reads from the file store', async () => {
- mockStoreData.set('my-setting', '{"theme":"dark"}')
- expect(await fileStorage.getItem('my-setting')).toBe('{"theme":"dark"}')
- })
-
- it('getItem returns null for missing keys', async () => {
- expect(await fileStorage.getItem('nonexistent')).toBeNull()
- })
-
- it('removeItem deletes from the file store', async () => {
- mockStoreData.set('key', 'value')
- await fileStorage.removeItem('key')
- expect(mockStore.delete).toHaveBeenCalledWith('key')
- })
-
- it('does not touch localStorage when Tauri store is available', async () => {
- await fileStorage.setItem('key', 'value')
- expect(localStorage.getItem('key')).toBeNull()
- })
-
- describe('migration from localStorage', () => {
- it('copies localStorage data to file store on first read', async () => {
- localStorage.setItem('setting-general', '{"state":{"lang":"vi"}}')
-
- const result = await fileStorage.getItem('setting-general')
-
- expect(mockStore.set).toHaveBeenCalledWith(
- 'setting-general',
- '{"state":{"lang":"vi"}}'
- )
- // Immediate save for migration data safety
- expect(mockSave).toHaveBeenCalled()
- // localStorage cleaned up after confirmed write
- expect(localStorage.getItem('setting-general')).toBeNull()
- expect(result).toBe('{"state":{"lang":"vi"}}')
- })
-
- it('does not overwrite existing file store data', async () => {
- localStorage.setItem('theme', '{"old":"data"}')
- mockStoreData.set('theme', '{"new":"data"}')
-
- const result = await fileStorage.getItem('theme')
-
- expect(result).toBe('{"new":"data"}')
- expect(mockStore.set).not.toHaveBeenCalledWith(
- 'theme',
- '{"old":"data"}'
- )
- // localStorage still cleaned up
- expect(localStorage.getItem('theme')).toBeNull()
- })
-
- it('runs migration only once per key', async () => {
- localStorage.setItem('key', 'value')
-
- await fileStorage.getItem('key')
- localStorage.setItem('key', 'new-value')
- await fileStorage.getItem('key')
-
- // store.set called once (migration), not twice
- expect(mockStore.set).toHaveBeenCalledTimes(1)
- })
-
- it('preserves localStorage if the file write fails', async () => {
- localStorage.setItem('key', 'important-data')
- mockStore.set.mockRejectedValueOnce(new Error('disk full'))
-
- const result = await fileStorage.getItem('key')
-
- expect(localStorage.getItem('key')).toBe('important-data')
- // File store has no data, so null
- expect(result).toBeNull()
- })
-
- it('concurrent reads share the same migration', async () => {
- localStorage.setItem('shared', 'data')
-
- // Fire two reads without awaiting
- const [r1, r2] = await Promise.all([
- fileStorage.getItem('shared'),
- fileStorage.getItem('shared'),
- ])
-
- // Both should get the migrated value
- expect(r1).toBe('data')
- expect(r2).toBe('data')
- // Migration should only write once
- expect(mockStore.set).toHaveBeenCalledTimes(1)
- })
- })
- })
-
- describe('migrateAllLocalStorageKeys', () => {
- let migrateAllLocalStorageKeys: typeof import('../fileStorage').migrateAllLocalStorageKeys
-
- beforeEach(async () => {
- ;(window as Record<string, unknown>).__TAURI_INTERNALS__ = {}
- vi.resetModules()
- mockStoreData.clear()
- mockStore.get.mockClear()
- mockStore.set.mockClear()
- mockStore.delete.mockClear()
- mockSave.mockClear()
- const mod = await import('../fileStorage')
- fileStorage = mod.fileStorage
- migrateAllLocalStorageKeys = mod.migrateAllLocalStorageKeys
- })
-
- it('migrates all localStorage keys to the file store', async () => {
- localStorage.setItem('key-a', 'value-a')
- localStorage.setItem('key-b', 'value-b')
- localStorage.setItem('key-c', 'value-c')
-
- await migrateAllLocalStorageKeys()
-
- expect(mockStore.set).toHaveBeenCalledWith('key-a', 'value-a')
- expect(mockStore.set).toHaveBeenCalledWith('key-b', 'value-b')
- expect(mockStore.set).toHaveBeenCalledWith('key-c', 'value-c')
- // Single flush to disk, not one per key
- expect(mockSave).toHaveBeenCalledTimes(1)
- // All localStorage entries cleaned up
- expect(localStorage.length).toBe(0)
- })
-
- it('does not overwrite keys already in the file store', async () => {
- localStorage.setItem('existing', 'old-value')
- mockStoreData.set('existing', 'new-value')
-
- await migrateAllLocalStorageKeys()
-
- // Should not overwrite
- expect(mockStore.set).not.toHaveBeenCalledWith('existing', 'old-value')
- expect(mockStoreData.get('existing')).toBe('new-value')
- // localStorage still cleaned up
- expect(localStorage.getItem('existing')).toBeNull()
- })
-
- it('is a no-op when localStorage is empty', async () => {
- await migrateAllLocalStorageKeys()
- expect(mockStore.set).not.toHaveBeenCalled()
- })
-
- it('is a no-op in non-Tauri environment', async () => {
- delete (window as Record<string, unknown>).__TAURI_INTERNALS__
- vi.resetModules()
- const mod = await import('../fileStorage')
-
- localStorage.setItem('key', 'value')
- await mod.migrateAllLocalStorageKeys()
-
- // localStorage untouched
- expect(localStorage.getItem('key')).toBe('value')
- expect(mockStore.set).not.toHaveBeenCalled()
- })
- })
-
- describe('graceful fallback when Tauri store fails to load', () => {
- beforeEach(async () => {
- ;(window as Record<string, unknown>).__TAURI_INTERNALS__ = {}
- vi.resetModules()
-
- // Make plugin-store load throw
- const pluginStore = await import('@tauri-apps/plugin-store')
- vi.mocked(pluginStore.load).mockRejectedValueOnce(
- new Error('plugin unavailable')
- )
-
- const mod = await import('../fileStorage')
- fileStorage = mod.fileStorage
- })
-
- it('falls back to localStorage on store init failure', async () => {
- localStorage.setItem('fallback-key', 'fallback-value')
- expect(await fileStorage.getItem('fallback-key')).toBe('fallback-value')
-
- await fileStorage.setItem('new-key', 'new-value')
- expect(localStorage.getItem('new-key')).toBe('new-value')
- })
- })
-})
diff --git a/web-app/src/lib/fileStorage.ts b/web-app/src/lib/fileStorage.ts
deleted file mode 100644
index a4c279e92..000000000
--- a/web-app/src/lib/fileStorage.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * File-based storage adapter for zustand persist middleware.
- *
- * Desktop (Tauri): persists settings to a local JSON file via @tauri-apps/plugin-store.
- * Browser (dev/web): falls back to localStorage for compatibility.
- *
- * On first access of each key, existing localStorage data is automatically migrated
- * to the file store. localStorage is only cleared after a confirmed write to disk.
- */
-import type { StateStorage } from 'zustand/middleware'
-
-const IS_TAURI =
- typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window
-
-const STORE_FILENAME = 'settings.json'
-
-// Minimal interface matching the subset of @tauri-apps/plugin-store we use.
-// Keeps this module decoupled from Tauri types for testability.
-interface TauriStore {
- get: <T>(key: string) => Promise<T | undefined>
- set: (key: string, value: unknown) => Promise<void>
- delete: (key: string) => Promise<boolean>
- save: () => Promise<void>
-}
-
-let store: TauriStore | null = null
-let initPromise: Promise<void> | null = null
-
-// Track per-key migration promises so concurrent getItem calls for the
-// same key correctly wait for a single migration to finish.
-const migrationPromises = new Map<string, Promise<void>>()
-
-async function ensureStore(): Promise<void> {
- if (store) return
- if (initPromise) {
- await initPromise
- return
- }
- initPromise = (async () => {
- try {
- const { invoke } = await import('@tauri-apps/api/core')
- const dataFolder = await invoke<string>('get_jan_data_folder_path')
- const { load } = await import('@tauri-apps/plugin-store')
- const storePath = `${dataFolder}/${STORE_FILENAME}`
- store = await load(storePath, { autoSave: false, defaults: {} })
- } catch (e) {
- console.warn(
- 'File storage unavailable, falling back to localStorage:',
- e
- )
- }
- })()
- await initPromise
-}
-
-/**
- * Persist in-memory state to disk. Called after every write so behaviour
- * matches localStorage (which persists synchronously). The save itself
- * is fire-and-forget — the in-memory state is already up-to-date, and
- * a failed flush will be overwritten by the next successful one.
- */
-function persistToDisk(): void {
- store?.save().catch((e) => {
- console.warn('Failed to persist settings to disk:', e)
- })
-}
-
-/**
- * Migrate a single key from localStorage to the file store.
- * Runs once per key per session. Concurrent calls for the same key share
- * one promise so the migration isn't duplicated or raced against.
- * Data is only removed from localStorage after a confirmed disk write.
- */
-function migrateFromLocalStorage(name: string): Promise<void> {
- const pending = migrationPromises.get(name)
- if (pending) return pending
-
- const promise = doMigrate(name)
- migrationPromises.set(name, promise)
- return promise
-}
-
-async function doMigrate(name: string): Promise<void> {
- try {
- const localValue = localStorage.getItem(name)
- if (localValue === null) return
-
- // Already in the file store — just clean up localStorage
- const existing = await store!.get(name)
- if (existing !== undefined && existing !== null) {
- localStorage.removeItem(name)
- return
- }
-
- // Copy to file store with an immediate flush for data safety
- await store!.set(name, localValue)
- await store!.save()
- localStorage.removeItem(name)
- } catch (e) {
- // Keep localStorage intact so we can retry next session
- migrationPromises.delete(name)
- console.warn(
- `Migration of "${name}" from localStorage to file storage failed:`,
- e
- )
- }
-}
-
-/**
- * Proactively migrate ALL localStorage keys to the file store.
- *
- * Should be called once at app startup so that users who update
- * the app will not lose any data — including keys that are read
- * directly via localStorage rather than through zustand stores.
- *
- * Safe to call multiple times; each key is migrated at most once
- * per session via the shared `migrationPromises` map.
- */
-export async function migrateAllLocalStorageKeys(): Promise<void> {
- if (!IS_TAURI) return
-
- try {
- await ensureStore()
- if (!store) return
-
- // Snapshot all current localStorage keys
- const keys: string[] = []
- for (let i = 0; i < localStorage.length; i++) {
- const key = localStorage.key(i)
- if (key) keys.push(key)
- }
-
- if (keys.length === 0) return
-
- // Copy each key into the file store (in-memory only, no disk I/O yet)
- const migratedKeys: string[] = []
- for (const key of keys) {
- // Skip keys already being migrated by a concurrent getItem call
- if (migrationPromises.has(key)) continue
-
- const localValue = localStorage.getItem(key)
- if (localValue === null) continue
-
- const existing = await store.get(key)
- if (existing !== undefined && existing !== null) {
- // Already in file store — just clean up localStorage
- localStorage.removeItem(key)
- continue
- }
-
- await store.set(key, localValue)
- migratedKeys.push(key)
- }
-
- if (migratedKeys.length === 0) return
-
- // Single flush to disk for all keys at once
- await store.save()
-
- // Only clean up localStorage after confirmed disk write
- for (const key of migratedKeys) {
- localStorage.removeItem(key)
- // Mark as migrated so lazy per-key migration skips these
- migrationPromises.set(key, Promise.resolve())
- }
- } catch (e) {
- // Keep localStorage intact so we can retry next session
- console.warn('Bulk migration from localStorage failed:', e)
- }
-}
-
-/**
- * Storage adapter compatible with zustand's createJSONStorage().
- *
- * Usage:
- * import { fileStorage } from '@/lib/fileStorage'
- * storage: createJSONStorage(() => fileStorage)
- */
-export const fileStorage: StateStorage = {
- getItem: async (name: string): Promise<string | null> => {
- if (!IS_TAURI) return localStorage.getItem(name)
-
- await ensureStore()
- if (!store) return localStorage.getItem(name)
-
- await migrateFromLocalStorage(name)
- const value = await store.get<string>(name)
- return value ?? null
- },
-
- setItem: async (name: string, value: string): Promise<void> => {
- if (!IS_TAURI) {
- localStorage.setItem(name, value)
- return
- }
-
- await ensureStore()
- if (!store) {
- localStorage.setItem(name, value)
- return
- }
-
- await store.set(name, value)
- persistToDisk()
- },
-
- removeItem: async (name: string): Promise<void> => {
- if (!IS_TAURI) {
- localStorage.removeItem(name)
- return
- }
-
- await ensureStore()
- if (!store) {
- localStorage.removeItem(name)
- return
- }
-
- await store.delete(name)
- persistToDisk()
- },
-}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 041975042..5323e40b6 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -57,6 +57,7 @@
"clearRecent": "Clear",
"name": "Name",
"cancel": "Cancel",
+ "dismiss": "Dismiss",
"create": "Create",
"save": "Save",
"edit": "Edit",
@@ -266,6 +267,15 @@
"titleFallback": "Something went wrong",
"details": "Details"
},
+ "missingDependenciesDialog": {
+ "title": "Missing System Libraries",
+ "description": "The {{backend}} was installed but some required system libraries could not be found. It may fall back to CPU or not run correctly.",
+ "installLabel": "To fix this, install the following:",
+ "download": "Download",
+ "additionalLibraries": "Additional missing libraries:",
+ "missingLibraries": "Missing libraries:",
+ "showRawLibraries": "Show {{count}} missing library names"
+ },
"projects": {
"title": "Projects",
"new": "New Projects",
diff --git a/web-app/src/main.tsx b/web-app/src/main.tsx
index 1cc0d7227..8bef9bef7 100644
--- a/web-app/src/main.tsx
+++ b/web-app/src/main.tsx
@@ -7,11 +7,6 @@ import { routeTree } from './routeTree.gen'
import './index.css'
import './i18n'
-import { migrateAllLocalStorageKeys } from './lib/fileStorage'
-
-// Migrate all localStorage data to file-based storage on startup
-// so users updating the app don't lose their settings.
-migrateAllLocalStorageKeys()
// Mobile-specific viewport and styling setup
const setupMobileViewport = () => {
diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsx
index 620dc531c..5a4c83b6f 100644
--- a/web-app/src/routes/__root.tsx
+++ b/web-app/src/routes/__root.tsx
@@ -30,6 +30,7 @@ import { LeftSidebar } from '@/components/left-sidebar'
import { WindowControls } from '@/components/WindowControls'
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'
import ErrorDialog from '@/containers/dialogs/ErrorDialog'
+import MissingDependenciesDialog from '@/containers/dialogs/MissingDependenciesDialog'
export const Route = createRootRoute({
component: RootLayout,
@@ -157,6 +158,7 @@ function RootLayout() {
<ToolApproval />
<AttachmentIngestionDialog />
<ErrorDialog />
+ <MissingDependenciesDialog />
<OutOfContextPromiseModal />
</TranslationProvider>
</ServiceHubProvider>