Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(onboarding): guided first-run setup wizard (#8594)
Akarshan Biswasfad3f12a147d
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsindex 939411b56..0bc9086a3 100644--- a/extensions/llamacpp-extension/src/backend.ts+++ b/extensions/llamacpp-extension/src/backend.ts@@ -12,6 +12,8 @@ import {getSupportedFeaturesFromRust,fetchBackendChecksums,verifyFileSha512,+ probeBackendLoad,+ type LoadProbeResult,} from '@janhq/tauri-plugin-llamacpp-api'/*@@ -118,6 +120,19 @@ export type BackendVerificationResult = {resolved_libraries: string[]}+/**+ * Loads the backend's GPU library the way llama-server would, to recover the+ * reason it cannot. A release build of ggml discards that error and silently+ * falls back to CPU, so this is the only way to name the missing dependency.+ */+export async function probeBackendGpuLibraries(+ backend: string,+ version: string+): Promise<LoadProbeResult> {+ const janDataFolder = await getJanDataFolderPath()+ return probeBackendLoad(backend, version, janDataFolder, IS_WINDOWS)+}+export async function verifyBackendInstallation(backend: string,version: stringdiff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 7fe6dee24..8b68107c5 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -42,6 +42,7 @@ import {getBackendExePath,getBackendDir,getLocalInstalledBackends,+ probeBackendGpuLibraries,} from './backend'import { invoke } from '@tauri-apps/api/core'import {@@ -56,6 +57,15 @@ import {type EmbedBatchResult,} from './util'import { generatePreset, MTP_MIN_BUILD } from './preset'+import {+ backendImpliesGpu,+ evaluateEmbeddingVector,+ evaluateGpuOffload,+ isBackendConfigured,+ type EmbeddingVectorProblem,+ type GpuOffloadCheck,+ type ReadinessStatus,+} from './readiness'import {getBackendSetting,setBackendSetting,@@ -189,12 +199,36 @@ type PersistedModelState = {const MODEL_PROVIDER_STORE_KEY = 'model-provider'const INTERFACE_SETTINGS_STORE_KEY = 'setting-appearance'const EMBEDDER_BOOTSTRAP_KEY = 'llamacpp-embedder-bootstrapped'+/** Set once the user has agreed to the first-run download. */+const SETUP_CONSENT_KEY = 'llamacpp-first-run-setup-started'const FALLBACK_EMBEDDING_MODEL_ID = 'sentence-transformer-mini'const FALLBACK_EMBEDDING_MODEL_URL ='https://huggingface.co/second-state/All-MiniLM-L6-v2-Embedding-GGUF/resolve/main/all-MiniLM-L6-v2-ggml-model-f16.gguf?download=true'const LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY ='llamacpp_model_yaml_backfill_v1'+// Short and non-empty: enough to exercise tokenize plus pooling without making+// setup wait on a long prompt.+const EMBEDDING_PROBE_TEXT = 'jan setup embedding probe'++export interface EmbeddingModelReport {+ status: ReadinessStatus+ modelId?: string+ dimension?: number+ problem?: EmbeddingVectorProblem+ error?: string+ /** The engine has not finished setting up, so nothing was concluded. */+ pending?: boolean+}++export interface GpuOffloadReport extends GpuOffloadCheck {+ backend: string+ /** Set when the device probe itself failed, leaving `reason` undetermined. */+ error?: string+ /** The engine has not finished setting up, so nothing was concluded. */+ pending?: boolean+}+// Sampling defaults are floats/ints where 0 is a meaningful value (e.g.// temperature=0), so unlike ctx_len these coercions keep 0 and only reject// blank/non-finite input.@@ -394,6 +428,9 @@ export default class llamacpp_extension extends AIEngine {private providerPath!: stringprivate apiSecret: string = 'JustAskNow'private pendingDownloads: Map<string, Promise<void>> = new Map()+ /** Keyed by modelId; two imports of one model would cancel each other. */+ private pendingImports: Map<string, Promise<void>> = new Map()+ private embedderBootstrapError?: stringprivate isConfiguringBackends: boolean = falseprivate isUpdatingBackend: boolean = falseprivate currentUpdate: Promise<{@@ -418,6 +455,8 @@ export default class llamacpp_extension extends AIEngine {// Backend discovery + router spawn run off the onLoad critical path; awaited// via ensureRouterReady() before any model load so inference never races it.private backgroundInit?: Promise<void>+ /** Single-flight provisioning run; see ensureProvisioned(). */+ private provisioning?: Promise<void>override async onLoad(): Promise<void> {super.onLoad() // Calls registerEngine() from AIEngine@@ -497,32 +536,87 @@ export default class llamacpp_extension extends AIEngine {// A restart on the new binary is owned by updateBackend, which needs it to// health-check the switch. On a fresh install (no backend yet)// configureBackends must run first to download one before the router can start.- this.backgroundInit = (async () => {+ // A first run downloads a backend and an embedding model -- hundreds of+ // megabytes. That is not started behind the user's back: the setup screen+ // asks first and then calls startFirstRunSetup(). An install that already+ // has a backend has nothing to ask about, so it provisions as before, and+ // any later attempt to use a local model provisions on demand through+ // ensureRouterReady().+ if ((await this.hasInstalledBackend()) || (await this.hasSetupConsent())) {+ this.backgroundInit = this.ensureProvisioned()+ } else {+ logger.info(+ 'Deferring first-run provisioning until the setup screen asks for it.'+ )+ }+ }++ private async hasSetupConsent(): Promise<boolean> {+ try {+ return Boolean(await getBackendSetting(SETUP_CONSENT_KEY))+ } catch (e) {+ // A readable answer is not worth blocking startup over; erring towards+ // "not consented" only defers work the user can still trigger.+ logger.warn('Could not read the first-run setup flag:', e)+ return false+ }+ }++ /**+ * Runs the first-run provisioning the setup screen asked for, and remembers+ * that it was asked so a later launch does not wait again.+ */+ async startFirstRunSetup(): Promise<void> {+ try {+ await setBackendSetting(SETUP_CONSENT_KEY, 'true')+ } catch (e) {+ logger.warn('Could not persist the first-run setup flag:', e)+ }+ await this.ensureProvisioned()+ }++ /**+ * Downloads/selects a backend, starts the router, then installs the fallback+ * embedder. Single-flight: startup, the setup screen and the first model load+ * can all ask for it, and only one run happens.+ *+ * When a usable backend is already installed the router starts first so+ * inference is available without waiting on the network-bound update check.+ * A restart on the new binary is owned by updateBackend, which needs it to+ * health-check the switch. On a fresh install configureBackends must run first+ * to download one before the router can start.+ */+ private ensureProvisioned(): Promise<void> {+ this.provisioning ??= (async () => {if (await this.hasInstalledBackend()) {try {await this.startRouter()} catch (e) {- logger.error('Router failed to start during onLoad:', e)+ logger.error('Router failed to start during provisioning:', e)+ this.reportMissingLibrariesFromError(e)}try {await this.configureBackends()} catch (e) {- logger.error('configureBackends failed during onLoad:', e)+ logger.error('configureBackends failed during provisioning:', e)}} else {try {await this.configureBackends()} catch (e) {- logger.error('configureBackends failed during onLoad:', e)+ logger.error('configureBackends failed during provisioning:', e)}try {await this.startRouter()} catch (e) {- logger.error('Router failed to start during onLoad:', e)+ logger.error('Router failed to start during provisioning:', e)+ this.reportMissingLibrariesFromError(e)}}await this.bootstrapDefaultEmbedder()})()+ this.backgroundInit = this.provisioning+ return this.provisioning}/**@@ -537,20 +631,26 @@ export default class llamacpp_extension extends AIEngine {private async bootstrapDefaultEmbedder(): Promise<void> {try {if (await getBackendSetting(EMBEDDER_BOOTSTRAP_KEY)) return- const models = await this.list()- const hasEmbedder = models.some(- (m) => (m as { embedding?: boolean }).embedding === true- )- if (!hasEmbedder) {+ if (!(await this.hasEmbedderInstalled())) {await this.import(FALLBACK_EMBEDDING_MODEL_ID, {modelPath: FALLBACK_EMBEDDING_MODEL_URL,})+ // A stopped or cancelled download resolves without throwing, so the+ // install has to be confirmed before the one-shot flag is recorded --+ // otherwise bootstrap marks itself done and never retries.+ if (!(await this.hasEmbedderInstalled())) {+ throw new Error(+ `Import of "${FALLBACK_EMBEDDING_MODEL_ID}" did not complete`+ )+ }logger.info(`Pre-installed fallback embedding model "${FALLBACK_EMBEDDING_MODEL_ID}" at startup`)}await setBackendSetting(EMBEDDER_BOOTSTRAP_KEY, 'true')+ this.embedderBootstrapError = undefined} catch (e) {+ this.embedderBootstrapError = e instanceof Error ? e.message : String(e)logger.warn('Fallback embedder bootstrap failed (will import on demand):',e@@ -558,6 +658,197 @@ export default class llamacpp_extension extends AIEngine {}}+ private async hasEmbedderInstalled(): Promise<boolean> {+ const models = await this.list()+ return models.some((m) => (m as { embedding?: boolean }).embedding === true)+ }++ /**+ * A launch failure that names unresolvable libraries carries the same+ * actionable information as a failed static verification, so it raises the+ * same dependency dialog instead of surfacing a generic process error.+ */+ private reportMissingLibrariesFromError(error: unknown): void {+ const err = error as { code?: string; missing_libraries?: unknown }+ if (err?.code !== 'MISSING_SHARED_LIBRARY') return++ const libs = Array.isArray(err.missing_libraries)+ ? err.missing_libraries.filter(+ (lib): lib is string => typeof lib === 'string'+ )+ : []+ if (libs.length === 0) return++ const [version, backend] = (this.config?.version_backend ?? '').split('/')+ events.emit(AppEvent.onBackendVerificationFailed, {+ backend: backend ?? '',+ version: version ?? '',+ missingLibraries: libs,+ })+ }++ /**+ * Why the startup embedder install failed, for setup to report. Undefined+ * when it succeeded or has not run; the import is retried on demand, so this+ * is advisory rather than terminal.+ */+ getEmbedderBootstrapError(): string | undefined {+ return this.embedderBootstrapError+ }++ /**+ * Proves the embedding model can actually produce a usable vector, rather+ * than inferring health from a completed download. Never throws: setup+ * reports the problem and lets the user continue.+ */+ async verifyEmbeddingModel(): Promise<EmbeddingModelReport> {+ // The router cannot start before a backend is selected, and the embedder is+ // installed after that. Probing during that window would block on the whole+ // backend download and then report a failure that is really an absence.+ if (!isBackendConfigured(this.config?.version_backend)) {+ return { status: 'ok', pending: true }+ }++ let modelId: string | undefined+ try {+ const sInfo = await this.ensureEmbeddingModelLoaded()+ modelId = sInfo.model_id+ const response = await this.embed([EMBEDDING_PROBE_TEXT])+ const check = evaluateEmbeddingVector(response?.data?.[0]?.embedding)+ return {+ status: check.ok ? 'ok' : 'warning',+ modelId,+ dimension: check.dimension,+ problem: check.problem,+ }+ } catch (e) {+ // A failed startup install is the more specific cause, and it is the one+ // the user can act on.+ return {+ status: 'warning',+ modelId,+ error:+ this.getEmbedderBootstrapError() ??+ (e instanceof Error ? e.message : String(e)),+ }+ }+ }++ /**+ * Names the GPU libraries the loader cannot resolve, and raises the same+ * dependency dialog a failed static verification does. Empty when the probe+ * found nothing or could not run, so callers fall back to the symptom-level+ * verdict rather than reporting a cause that was never established.+ */+ private async probeMissingGpuLibraries(backend: string): Promise<string[]> {+ const [version] = (this.config?.version_backend ?? '').split('/')+ if (!version || !backend) return []++ try {+ const result = await probeBackendGpuLibraries(backend, version)+ if (result.inconclusive) return []++ // Built by reduce rather than flatMap: this extension declares an ES2018+ // lib, where flatMap is not available.+ const seen = new Set<string>()+ for (const failure of result.failures) {+ for (const lib of failure.missing_libraries ?? []) seen.add(lib)+ }+ const missing = Array.from(seen)+ if (missing.length > 0) {+ logger.warn(+ `Backend ${backend} cannot load its GPU library; missing: ${missing.join(', ')}`+ )+ events.emit(AppEvent.onBackendVerificationFailed, {+ backend,+ version,+ missingLibraries: missing,+ })+ }+ return missing+ } catch (e) {+ logger.warn('Backend load probe failed:', e)+ return []+ }+ }++ /**+ * Detects a GPU backend that runs entirely on the CPU. Such a router starts+ * cleanly and reports healthy, so this comparison against the engine's own+ * device list is the only signal that offload never happened.+ */+ async verifyGpuOffload(): Promise<GpuOffloadReport> {+ // No backend chosen yet means the engine is still setting itself up. An+ // empty name would otherwise read as "a CPU-only build", which is how a+ // CUDA install came to be reported as leaving the GPU idle.+ if (!isBackendConfigured(this.config?.version_backend)) {+ return {+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ }+ }++ const backend = (this.config?.version_backend ?? '').split('/')[1] ?? ''++ // A CPU build cannot offload, so skip the --list-devices subprocess rather+ // than spend a 30s-timeout spawn confirming a known answer.+ if (!backendImpliesGpu(backend)) {+ return {+ status: 'ok',+ backend,+ gpuExpected: false,+ engineDeviceCount: 0,+ }+ }++ let engineDeviceCount: number+ try {+ engineDeviceCount = (await this.getDevices()).length+ } catch (e) {+ // Without a device list there is no basis for a reason code, and guessing+ // one would point the user at the wrong fix.+ return {+ status: 'warning',+ backend,+ gpuExpected: backendImpliesGpu(backend),+ engineDeviceCount: 0,+ error: e instanceof Error ? e.message : String(e),+ }+ }++ let hardwareGpuCount = 0+ try {+ hardwareGpuCount = (await getSystemInfo())?.gpus?.length ?? 0+ } catch (e) {+ logger.warn('Hardware GPU probe failed during setup verification:', e)+ }++ // Zero devices on a GPU build means the library never loaded. ggml discards+ // that loader error in a release build, so ask the loader directly to name+ // the dependency instead of reporting only the symptom.+ if (engineDeviceCount === 0) {+ const missing = await this.probeMissingGpuLibraries(backend)+ if (missing.length > 0) {+ return {+ status: 'warning',+ backend,+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'missingLibrary',+ missingLibraries: missing,+ }+ }+ }++ return {+ backend,+ ...evaluateGpuOffload({ backend, engineDeviceCount, hardwareGpuCount }),+ }+ }+// True when config.version_backend names a backend that's already downloaded,// so the router can spawn without waiting on configureBackends.private async hasInstalledBackend(): Promise<boolean> {@@ -717,24 +1008,16 @@ export default class llamacpp_extension extends AIEngine {private async runStartRouter(): Promise<void> {const versionBackend = this.config?.version_backend- if (- !versionBackend ||- versionBackend === 'none' ||- !versionBackend.includes('/')- ) {+ if (!isBackendConfigured(versionBackend)) {logger.info(- 'Router will start once backend is configured (no version_backend yet).'+ `Router will start once backend is configured (version_backend: ${+ versionBackend || 'unset'+ }).`)return}- const [version, backend] = versionBackend.split('/')- if (!version || !backend) {- logger.warn(- `Skipping router start; malformed version_backend: ${versionBackend}`- )- return- }+ const [version, backend] = (versionBackend as string).split('/')const providerPath = await this.getProviderPath()const janDataFolderPath = await getJanDataFolderPath()@@ -2767,7 +3050,29 @@ export default class llamacpp_extension extends AIEngine {}}+ /**+ * Joins concurrent imports of the same model instead of starting a second one.+ * Two callers racing (startup embedder bootstrap and an on-demand embed) both+ * passed the `model.yml` existence guard, then registered the same download+ * task id -- which Rust resolves by cancelling the first and deleting its+ * partial file. The loser then returned without writing `model.yml`, so its+ * caller went on to load a model that was never installed.+ */override async import(modelId: string, opts: ImportOptions): Promise<void> {+ const inFlight = this.pendingImports.get(modelId)+ if (inFlight) {+ logger.info(`Joining in-flight import of "${modelId}"`)+ return inFlight+ }++ const task = this.runImport(modelId, opts).finally(() => {+ this.pendingImports.delete(modelId)+ })+ this.pendingImports.set(modelId, task)+ return task+ }++ private async runImport(modelId: string, opts: ImportOptions): Promise<void> {const isValidModelId = (id: string) => {// only allow alphanumeric, underscore, hyphen, and dot characters in modelIdif (!/^[a-zA-Z0-9/_\-\.]+$/.test(id)) return false@@ -3145,9 +3450,9 @@ export default class llamacpp_extension extends AIEngine {// still isn't up. Safe to call redundantly: startRouter reuses a router that// already matches this config rather than respawning it.private async ensureRouterReady(): Promise<void> {- if (this.backgroundInit) {- await this.backgroundInit.catch(() => undefined)- }+ // Provisions if the setup screen never got the chance to ask, so skipping+ // setup and later loading a local model still works.+ await this.ensureProvisioned().catch(() => undefined)if (!(await this.getRouterInfo())) {await this.startRouter()}@@ -3246,12 +3551,16 @@ export default class llamacpp_extension extends AIEngine {}}+ /**+ * The id becomes a Tauri event name (`download-<taskId>`), which cannot contain+ * a dot. Dots are replaced rather than truncated at: truncating collapsed every+ * `Jan-v3.*` quant onto one id, and Rust cancels an in-flight task whose id+ * repeats -- deleting its partial file -- so downloading one quant destroyed+ * another's, and pause/cancel hit whichever quant happened to be registered.+ */private createDownloadTaskId(modelId: string) {- // prepend provider to make taksId unique across providers- const cleanModelId = modelId.includes('.')- ? modelId.slice(0, modelId.indexOf('.'))- : modelId- return `${this.provider}/${cleanModelId}`+ // prepend provider to make taskId unique across providers+ return `${this.provider}/${modelId.replace(/\./g, '-')}`}private async verifyBackendDeps(backend: string, version: string): Promise<void> {diff --git a/extensions/llamacpp-extension/src/readiness.test.ts b/extensions/llamacpp-extension/src/readiness.test.tsnew file mode 100644index 000000000..13e59a60d--- /dev/null+++ b/extensions/llamacpp-extension/src/readiness.test.ts@@ -0,0 +1,167 @@+import { describe, it, expect } from 'vitest'+import {+ backendImpliesGpu,+ isBackendConfigured,+ evaluateGpuOffload,+ evaluateEmbeddingVector,+} from './readiness'++describe('backendImpliesGpu', () => {+ it('recognizes every GPU variant Jan ships', () => {+ for (const backend of [+ 'linux-cuda-12-common_cpus-x64',+ 'linux-cuda-11-common_cpus-x64',+ 'win-cuda-13-common_cpus-x64',+ 'linux-vulkan-common_cpus-x64',+ 'linux-hip-common_cpus-x64',+ ]) {+ expect(backendImpliesGpu(backend), backend).toBe(true)+ }+ })++ it('does not flag CPU variants', () => {+ for (const backend of [+ 'linux-common_cpus-x64',+ 'win-common_cpus-x64',+ 'win-arm64',+ 'linux-noavx-x64',+ 'linux-avx2-x64',+ ]) {+ expect(backendImpliesGpu(backend), backend).toBe(false)+ }+ })++ // Metal is implicit on Apple Silicon and always available, so a macOS build+ // must not be reported as a GPU variant that failed to find a device.+ it('does not flag macOS builds', () => {+ expect(backendImpliesGpu('macos-arm64')).toBe(false)+ expect(backendImpliesGpu('macos-x64')).toBe(false)+ })++ it('tolerates an empty or missing backend id', () => {+ expect(backendImpliesGpu('')).toBe(false)+ expect(backendImpliesGpu(undefined as unknown as string)).toBe(false)+ })+})++describe('evaluateGpuOffload', () => {+ it('passes a CPU backend without looking at devices', () => {+ const result = evaluateGpuOffload({+ backend: 'linux-common_cpus-x64',+ engineDeviceCount: 0,+ hardwareGpuCount: 0,+ })+ expect(result.status).toBe('ok')+ expect(result.gpuExpected).toBe(false)+ expect(result.reason).toBeUndefined()+ })++ it('passes a GPU backend that the engine can actually use', () => {+ const result = evaluateGpuOffload({+ backend: 'linux-cuda-12-common_cpus-x64',+ engineDeviceCount: 1,+ hardwareGpuCount: 1,+ })+ expect(result.status).toBe('ok')+ expect(result.gpuExpected).toBe(true)+ })++ // The machine has no GPU at all: the wrong variant was installed.+ it('warns when a GPU backend finds no devices and no GPU hardware exists', () => {+ const result = evaluateGpuOffload({+ backend: 'linux-cuda-12-common_cpus-x64',+ engineDeviceCount: 0,+ hardwareGpuCount: 0,+ })+ expect(result.status).toBe('warning')+ expect(result.reason).toBe('noGpuHardware')+ })++ // A GPU exists but the engine cannot reach it, which is a driver/runtime+ // problem and needs different advice than "you have no GPU".+ it('distinguishes a present GPU the engine cannot reach', () => {+ const result = evaluateGpuOffload({+ backend: 'linux-cuda-12-common_cpus-x64',+ engineDeviceCount: 0,+ hardwareGpuCount: 1,+ })+ expect(result.status).toBe('warning')+ expect(result.reason).toBe('runtimeUnreachable')+ })++ it('reports the engine device count it based the verdict on', () => {+ expect(+ evaluateGpuOffload({+ backend: 'linux-cuda-12-common_cpus-x64',+ engineDeviceCount: 2,+ hardwareGpuCount: 2,+ }).engineDeviceCount+ ).toBe(2)+ })+})++describe('evaluateEmbeddingVector', () => {+ it('accepts a healthy vector and reports its dimension', () => {+ const result = evaluateEmbeddingVector([0.1, -0.2, 0.3])+ expect(result.ok).toBe(true)+ expect(result.dimension).toBe(3)+ expect(result.problem).toBeUndefined()+ })++ it('rejects a missing vector', () => {+ expect(evaluateEmbeddingVector(undefined).problem).toBe('missing')+ expect(evaluateEmbeddingVector(null).problem).toBe('missing')+ expect(evaluateEmbeddingVector('nope').problem).toBe('missing')+ })++ // vector-db rejects this later with "embedding is empty"; catching it during+ // setup turns a first-attachment failure into an onboarding warning.+ it('rejects an empty vector', () => {+ const result = evaluateEmbeddingVector([])+ expect(result.ok).toBe(false)+ expect(result.problem).toBe('empty')+ expect(result.dimension).toBe(0)+ })++ it('rejects non-finite values that sqlite-vec would refuse', () => {+ for (const bad of [NaN, Infinity, -Infinity]) {+ const result = evaluateEmbeddingVector([0.1, bad, 0.3])+ expect(result.ok, String(bad)).toBe(false)+ expect(result.problem).toBe('nonFinite')+ }+ })++ it('rejects non-numeric entries', () => {+ expect(evaluateEmbeddingVector([0.1, '0.2', 0.3]).problem).toBe('nonFinite')+ })++ // An all-zero vector makes cosine similarity divide by zero, so retrieval+ // silently returns nothing useful. It signals a misconfigured pooling type.+ it('rejects a degenerate all-zero vector', () => {+ const result = evaluateEmbeddingVector([0, 0, 0])+ expect(result.ok).toBe(false)+ expect(result.problem).toBe('degenerate')+ expect(result.dimension).toBe(3)+ })+})++describe('isBackendConfigured', () => {+ it('accepts a well-formed version/backend pair', () => {+ expect(isBackendConfigured('b6099/linux-cuda-12-common_cpus-x64')).toBe(true)+ })++ // A fresh install sits in these states through a catalog fetch and a backend+ // download; treating them as "configured" is what made a probe report a+ // defect instead of an absence.+ it('rejects the fresh-install placeholders', () => {+ for (const value of ['', ' ', 'none', undefined, null]) {+ expect(isBackendConfigured(value), String(value)).toBe(false)+ }+ })++ it('rejects a malformed pair', () => {+ for (const value of ['b6099', 'b6099/', '/linux-cuda', '/']) {+ expect(isBackendConfigured(value), value).toBe(false)+ }+ })+})diff --git a/extensions/llamacpp-extension/src/readiness.ts b/extensions/llamacpp-extension/src/readiness.tsnew file mode 100644index 000000000..f0967b132--- /dev/null+++ b/extensions/llamacpp-extension/src/readiness.ts@@ -0,0 +1,122 @@+/**+ * Setup readiness checks. Pure decision logic, kept out of the extension class+ * so it is testable without a router, a backend install, or Tauri.+ */++export type ReadinessStatus = 'ok' | 'warning'++/**+ * `noGpuHardware` means a GPU build is installed on a machine with no GPU.+ * `runtimeUnreachable` means a GPU exists but the engine cannot see it, which+ * points at the driver or runtime rather than the variant choice.+ * `missingLibrary` is the same symptom with the cause established: the loader+ * named a dependency it could not resolve.+ */+export type GpuOffloadReason =+ | 'noGpuHardware'+ | 'runtimeUnreachable'+ | 'missingLibrary'++export interface GpuOffloadCheck {+ status: ReadinessStatus+ gpuExpected: boolean+ engineDeviceCount: number+ reason?: GpuOffloadReason+ /** Set only for `missingLibrary`, to drive install advice. */+ missingLibraries?: string[]+}++/**+ * Whether a backend has been selected. Nothing downstream of the router can be+ * probed until it has: on a fresh install this stays false through a catalog+ * fetch and a backend download, so a probe answered during that window reports+ * an absence of setup rather than a defect.+ */+export function isBackendConfigured(+ versionBackend: string | undefined | null+): boolean {+ const value = (versionBackend ?? '').trim()+ if (value === '' || value === 'none' || !value.includes('/')) return false+ const [version, backend] = value.split('/')+ return Boolean(version && backend)+}++export type EmbeddingVectorProblem =+ | 'missing'+ | 'empty'+ | 'nonFinite'+ | 'degenerate'++export interface EmbeddingVectorCheck {+ ok: boolean+ dimension: number+ problem?: EmbeddingVectorProblem+}++// Substrings of a backend variant id that mean layers are meant to run on a+// GPU. Metal is excluded: it is implicit on Apple Silicon and always present,+// so a macOS build can never be "a GPU build that found no GPU".+const GPU_BACKEND_MARKERS = ['cuda', 'vulkan', 'hip']++export function backendImpliesGpu(backend: string): boolean {+ const lower = (backend ?? '').toLowerCase()+ return GPU_BACKEND_MARKERS.some((marker) => lower.includes(marker))+}++/**+ * A GPU backend that starts cleanly but sees no devices falls back to CPU+ * silently: llama.cpp's layer fit puts everything on the host and the router+ * still reports healthy. Comparing the engine's own device list against the+ * variant is the only way to catch it.+ */+export function evaluateGpuOffload(input: {+ backend: string+ engineDeviceCount: number+ hardwareGpuCount: number+}): GpuOffloadCheck {+ const { backend, engineDeviceCount, hardwareGpuCount } = input+ const gpuExpected = backendImpliesGpu(backend)++ if (!gpuExpected || engineDeviceCount > 0) {+ return { status: 'ok', gpuExpected, engineDeviceCount }+ }++ return {+ status: 'warning',+ gpuExpected,+ engineDeviceCount,+ reason: hardwareGpuCount > 0 ? 'runtimeUnreachable' : 'noGpuHardware',+ }+}++/**+ * Validates a probe embedding before anything is persisted. Mirrors the checks+ * the vector-db plugin applies at insert time, so a broken embedder surfaces+ * during setup instead of on the user's first attachment.+ */+export function evaluateEmbeddingVector(+ vector: unknown+): EmbeddingVectorCheck {+ if (!Array.isArray(vector)) {+ return { ok: false, dimension: 0, problem: 'missing' }+ }+ if (vector.length === 0) {+ return { ok: false, dimension: 0, problem: 'empty' }+ }++ const dimension = vector.length+ const hasInvalid = vector.some(+ (value) => typeof value !== 'number' || !Number.isFinite(value)+ )+ if (hasInvalid) {+ return { ok: false, dimension, problem: 'nonFinite' }+ }++ // Cosine similarity divides by the vector norm, so an all-zero embedding+ // makes every score NaN rather than merely inaccurate.+ if (vector.every((value) => value === 0)) {+ return { ok: false, dimension, problem: 'degenerate' }+ }++ return { ok: true, dimension }+}diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex e3ecf2ef6..1de04aeb0 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -23,6 +23,7 @@ vi.mock('../backend', () => ({missing_libraries: [],resolved_libraries: [],}),+ probeBackendGpuLibraries: vi.fn(),}))// Mock tauri-plugin-llamacpp-api (partial mock)@@ -1245,9 +1246,15 @@ describe('bootstrapDefaultEmbedder', () => {it('imports the fallback embedder when none is installed, then marks the bootstrap done', async () => {vi.mocked(getBackendSetting).mockResolvedValue(null)+ // The install is confirmed by re-listing, so the second call has to reflect+ // the import having landed.const list = vi.spyOn(extension, 'list')- .mockResolvedValue([{ id: 'chat-model', embedding: false }] as never)+ .mockResolvedValueOnce([{ id: 'chat-model', embedding: false }] as never)+ .mockResolvedValue([+ { id: 'chat-model', embedding: false },+ { id: 'sentence-transformer-mini', embedding: true },+ ] as never)const importSpy = vi.spyOn(extension, 'import').mockResolvedValue(undefined as never)@@ -1513,3 +1520,669 @@ describe('router adoption after a UI crash', () => {expect(extension['routerStartLock']).toBeNull()})})++describe('verifyEmbeddingModel', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ // The probe is gated on a configured backend, since the router it needs+ // cannot exist before one is selected.+ extension.config = {+ ...(extension.config ?? {}),+ version_backend: 'b6099/linux-cuda-12-common_cpus-x64',+ } as never+ vi.spyOn(extension as never, 'ensureEmbeddingModelLoaded').mockResolvedValue(+ { model_id: 'sentence-transformer-mini', port: 1234 } as never+ )+ })++ const armEmbed = (embedding: unknown) =>+ vi+ .spyOn(extension, 'embed')+ .mockResolvedValue({ data: [{ embedding, index: 0 }] } as never)++ it('reports pending instead of probing before a backend is configured', async () => {+ extension['config'] = { version_backend: '' } as never+ const embed = armEmbed([0.1])++ const result = await extension.verifyEmbeddingModel()++ expect(result.pending).toBe(true)+ expect(result.status).toBe('ok')+ expect(embed).not.toHaveBeenCalled()+ })++ // The startup install failing is the specific, actionable cause; the load+ // error it produces downstream is not.+ it('prefers the bootstrap error over the downstream load error', async () => {+ vi.spyOn(extension as never, 'getEmbedderBootstrapError').mockReturnValue(+ 'download failed: HTTP 403' as never+ )+ vi.spyOn(extension as never, 'ensureEmbeddingModelLoaded').mockRejectedValue(+ new Error('model not found in router preset') as never+ )++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('warning')+ expect(result.error).toBe('download failed: HTTP 403')+ })++ it('reports the model id and dimension of a healthy embedder', async () => {+ armEmbed([0.1, 0.2, 0.3])++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('ok')+ expect(result.modelId).toBe('sentence-transformer-mini')+ expect(result.dimension).toBe(3)+ })++ it('actually sends a probe request rather than trusting the install', async () => {+ const embed = armEmbed([0.1])++ await extension.verifyEmbeddingModel()++ expect(embed).toHaveBeenCalledTimes(1)+ expect(embed.mock.calls[0][0]).toHaveLength(1)+ })++ it('warns on a degenerate vector that would break cosine similarity', async () => {+ armEmbed([0, 0, 0])++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('warning')+ expect(result.problem).toBe('degenerate')+ })++ it('warns when the embedder returns no vector at all', async () => {+ armEmbed(undefined)++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('warning')+ expect(result.problem).toBe('missing')+ })++ // Warn-never-block: a failed probe must not reject and strand onboarding.+ it('reports a load failure as a warning instead of throwing', async () => {+ vi.spyOn(extension as never, 'ensureEmbeddingModelLoaded').mockRejectedValue(+ new Error('router is not running')+ )++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('warning')+ expect(result.error).toContain('router is not running')+ })++ it('reports a failed embed request as a warning', async () => {+ vi.spyOn(extension, 'embed').mockRejectedValue(new Error('HTTP 400'))++ const result = await extension.verifyEmbeddingModel()++ expect(result.status).toBe('warning')+ expect(result.error).toContain('HTTP 400')+ })+})++describe('verifyGpuOffload', () => {+ let extension: llamacpp_extension++ const arm = async (+ backend: string,+ devices: unknown[],+ gpus: unknown[] | undefined+ ) => {+ extension = new llamacpp_extension()+ extension['config'] = { version_backend: `b9145/${backend}` } as never+ vi.spyOn(extension, 'getDevices').mockResolvedValue(devices as never)+ const { getSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')+ vi.mocked(getSystemInfo).mockResolvedValue(+ (gpus === undefined ? undefined : { gpus }) as never+ )+ }++ beforeEach(() => {+ vi.clearAllMocks()+ })++ // A fresh install has no backend until a catalog fetch and a download finish.+ // Reporting that as a CPU build made a CUDA install look like it left the GPU+ // idle, and probing anyway would have blocked on the whole download.+ it('reports pending while no backend is configured', async () => {+ for (const versionBackend of ['', 'none', 'b9145', undefined]) {+ extension = new llamacpp_extension()+ extension['config'] = { version_backend: versionBackend } as never+ const getDevices = vi.spyOn(extension, 'getDevices')++ const result = await extension.verifyGpuOffload()++ expect(result.pending, String(versionBackend)).toBe(true)+ expect(result.status).toBe('ok')+ expect(result.backend).toBe('')+ expect(getDevices).not.toHaveBeenCalled()+ }+ })++ it('does not report pending once a backend is configured', async () => {+ await arm('linux-cuda-12-common_cpus-x64', [{ id: '0' }], [{ uuid: 'a' }])++ expect((await extension.verifyGpuOffload()).pending).toBeUndefined()+ })++ it('passes a CUDA backend with a visible device', async () => {+ await arm('linux-cuda-12-common_cpus-x64', [{ id: '0' }], [{ uuid: 'a' }])++ const result = await extension.verifyGpuOffload()++ expect(result.status).toBe('ok')+ expect(result.backend).toBe('linux-cuda-12-common_cpus-x64')+ })++ // The silent CPU-fallback case: the router is healthy, so nothing else notices.+ it('warns when a CUDA backend sees no devices but a GPU exists', async () => {+ await arm('linux-cuda-12-common_cpus-x64', [], [{ uuid: 'a' }])++ const result = await extension.verifyGpuOffload()++ expect(result.status).toBe('warning')+ expect(result.reason).toBe('runtimeUnreachable')+ })++ it('warns differently when the machine has no GPU at all', async () => {+ await arm('linux-cuda-12-common_cpus-x64', [], [])++ const result = await extension.verifyGpuOffload()++ expect(result.reason).toBe('noGpuHardware')+ })++ // getDevices spawns `llama-server --list-devices` with a 30s timeout, so a+ // CPU build must not pay for a probe whose answer is already known.+ it('passes a CPU backend without spawning the device probe', async () => {+ await arm('linux-common_cpus-x64', [], [])+ const getDevices = vi.spyOn(extension, 'getDevices')++ const result = await extension.verifyGpuOffload()++ expect(result.status).toBe('ok')+ expect(result.gpuExpected).toBe(false)+ expect(getDevices).not.toHaveBeenCalled()+ })++ // A throwing device probe means we do not know why; claiming "no GPU" would+ // send the user to buy hardware they already have.+ it('does not guess a reason when the device probe fails', async () => {+ extension = new llamacpp_extension()+ extension['config'] = {+ version_backend: 'b9145/linux-cuda-12-common_cpus-x64',+ } as never+ vi.spyOn(extension, 'getDevices').mockRejectedValue(+ new Error('libcudart.so.12: cannot open shared object file')+ )++ const result = await extension.verifyGpuOffload()++ expect(result.status).toBe('warning')+ expect(result.reason).toBeUndefined()+ expect(result.error).toContain('libcudart.so.12')+ })++ it('survives hardware detection returning nothing', async () => {+ await arm('linux-cuda-12-common_cpus-x64', [], undefined)++ const result = await extension.verifyGpuOffload()++ expect(result.reason).toBe('noGpuHardware')+ })+})++describe('bootstrapDefaultEmbedder failure reporting', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ })++ it('records why the bootstrap failed instead of only logging it', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue(null)+ vi.spyOn(extension, 'list').mockResolvedValue([] as never)+ vi.spyOn(extension, 'import').mockRejectedValue(new Error('offline'))++ await extension['bootstrapDefaultEmbedder']()++ expect(extension.getEmbedderBootstrapError()).toContain('offline')+ })++ it('leaves no error recorded on success', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue(null)+ vi.spyOn(extension, 'list').mockResolvedValue([+ { id: 'e', embedding: true },+ ] as never)++ await extension['bootstrapDefaultEmbedder']()++ expect(extension.getEmbedderBootstrapError()).toBeUndefined()+ })++ it('clears a previous error once a later attempt succeeds', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue(null)+ vi.spyOn(extension, 'list').mockResolvedValue([] as never)+ vi.spyOn(extension, 'import').mockRejectedValue(new Error('offline'))+ await extension['bootstrapDefaultEmbedder']()+ expect(extension.getEmbedderBootstrapError()).toBeDefined()++ vi.spyOn(extension, 'import').mockResolvedValue(undefined as never)+ vi.spyOn(extension, 'list').mockResolvedValue([+ { id: 'sentence-transformer-mini', embedding: true },+ ] as never)+ await extension['bootstrapDefaultEmbedder']()++ expect(extension.getEmbedderBootstrapError()).toBeUndefined()+ })++ // A cancelled download resolves without throwing. Trusting that resolution+ // marked the one-shot bootstrap done for a model that was never installed, so+ // it never retried and the embedder stayed permanently missing.+ it('does not mark done when the import resolves without installing anything', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue(null)+ vi.spyOn(extension, 'list').mockResolvedValue([] as never)+ const importSpy = vi+ .spyOn(extension, 'import')+ .mockResolvedValue(undefined as never)++ await extension['bootstrapDefaultEmbedder']()++ expect(importSpy).toHaveBeenCalled()+ expect(setBackendSetting).not.toHaveBeenCalled()+ expect(extension.getEmbedderBootstrapError()).toContain('did not complete')+ })+})++describe('reportMissingLibrariesFromError', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ extension['config'] = {+ version_backend: 'b9145/linux-cuda-12-common_cpus-x64',+ } as never+ })++ const emitted = async () => {+ const { events } = await import('@janhq/core')+ return vi.mocked(events.emit)+ }++ // Reuses the dependency dialog a failed static verification raises, instead+ // of leaving the user with a generic process error.+ it('raises the dependency dialog for a launch-time missing library', async () => {+ extension['reportMissingLibrariesFromError']({+ code: 'MISSING_SHARED_LIBRARY',+ missing_libraries: ['libcudart.so.12'],+ })++ expect(await emitted()).toHaveBeenCalledWith(+ 'onBackendVerificationFailed',+ {+ backend: 'linux-cuda-12-common_cpus-x64',+ version: 'b9145',+ missingLibraries: ['libcudart.so.12'],+ }+ )+ })++ it('ignores unrelated launch failures', async () => {+ extension['reportMissingLibrariesFromError']({+ code: 'LLAMA_CPP_PROCESS_ERROR',+ details: 'something else',+ })++ expect(await emitted()).not.toHaveBeenCalled()+ })++ // Nothing actionable to show, so the dialog would be an empty dead end.+ it('stays silent when no library name could be parsed', async () => {+ extension['reportMissingLibrariesFromError']({+ code: 'MISSING_SHARED_LIBRARY',+ })++ expect(await emitted()).not.toHaveBeenCalled()+ })++ it('tolerates a non-error value', async () => {+ extension['reportMissingLibrariesFromError'](undefined)+ extension['reportMissingLibrariesFromError']('boom')++ expect(await emitted()).not.toHaveBeenCalled()+ })+})++describe('verifyGpuOffload missing-library probe', () => {+ let extension: llamacpp_extension++ const arm = async (+ devices: unknown[],+ probe: unknown,+ gpus: unknown[] = [{ uuid: 'a' }]+ ) => {+ extension = new llamacpp_extension()+ extension['config'] = {+ version_backend: 'b9145/linux-cuda-12-common_cpus-x64',+ } as never+ vi.spyOn(extension, 'getDevices').mockResolvedValue(devices as never)+ const { getSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')+ vi.mocked(getSystemInfo).mockResolvedValue({ gpus } as never)+ const { probeBackendGpuLibraries } = await import('../backend')+ if (probe instanceof Error) {+ vi.mocked(probeBackendGpuLibraries).mockRejectedValue(probe)+ } else {+ vi.mocked(probeBackendGpuLibraries).mockResolvedValue(probe as never)+ }+ }++ beforeEach(() => {+ vi.clearAllMocks()+ })++ // ggml discards the loader error in a release build, so the probe is the only+ // way to name the dependency.+ it('names the missing library when a GPU backend sees no devices', async () => {+ await arm([], {+ loaded: [],+ inconclusive: false,+ failures: [+ {+ library: 'libggml-cuda.so',+ error: 'libnccl.so.2: cannot open shared object file',+ missing_libraries: ['libnccl.so.2'],+ },+ ],+ })++ const result = await extension.verifyGpuOffload()++ expect(result.status).toBe('warning')+ expect(result.reason).toBe('missingLibrary')+ expect(result.missingLibraries).toEqual(['libnccl.so.2'])+ })++ it('raises the dependency dialog with the probed libraries', async () => {+ await arm([], {+ loaded: [],+ inconclusive: false,+ failures: [+ {+ library: 'libggml-cuda.so',+ error: 'boom',+ missing_libraries: ['libnccl.so.2', 'libcublas.so.12'],+ },+ ],+ })++ await extension.verifyGpuOffload()++ const { events } = await import('@janhq/core')+ expect(vi.mocked(events.emit)).toHaveBeenCalledWith(+ 'onBackendVerificationFailed',+ {+ backend: 'linux-cuda-12-common_cpus-x64',+ version: 'b9145',+ missingLibraries: ['libnccl.so.2', 'libcublas.so.12'],+ }+ )+ })++ it('deduplicates libraries reported by several failures', async () => {+ await arm([], {+ loaded: [],+ inconclusive: false,+ failures: [+ { library: 'a.so', error: 'x', missing_libraries: ['libnccl.so.2'] },+ { library: 'b.so', error: 'y', missing_libraries: ['libnccl.so.2'] },+ ],+ })++ const result = await extension.verifyGpuOffload()++ expect(result.missingLibraries).toEqual(['libnccl.so.2'])+ })++ // An inconclusive probe establishes no cause, so the symptom-level verdict+ // must stand rather than a fabricated one.+ it('falls back to the symptom verdict when the probe is inconclusive', async () => {+ await arm([], { loaded: [], failures: [], inconclusive: true })++ const result = await extension.verifyGpuOffload()++ expect(result.reason).toBe('runtimeUnreachable')+ expect(result.missingLibraries).toBeUndefined()+ })++ it('falls back when the probe finds no failures', async () => {+ await arm([], { loaded: ['libggml-cuda.so'], failures: [], inconclusive: false })++ const result = await extension.verifyGpuOffload()++ expect(result.reason).toBe('runtimeUnreachable')+ })++ it('survives the probe throwing', async () => {+ await arm([], new Error('probe exploded'))++ const result = await extension.verifyGpuOffload()++ expect(result.reason).toBe('runtimeUnreachable')+ })++ // A working GPU must never pay for the probe.+ it('does not probe when devices are present', async () => {+ await arm([{ id: '0' }], { loaded: [], failures: [], inconclusive: false })++ const result = await extension.verifyGpuOffload()++ const { probeBackendGpuLibraries } = await import('../backend')+ expect(vi.mocked(probeBackendGpuLibraries)).not.toHaveBeenCalled()+ expect(result.status).toBe('ok')+ })+})++describe('createDownloadTaskId', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ })++ const taskId = (modelId: string) =>+ extension['createDownloadTaskId'](modelId) as string++ // The id becomes the Tauri event name `download-<taskId>`, which rejects dots.+ it('contains no dots', () => {+ expect(taskId('Jan-v3.5-4B-Q4_K_XL')).not.toContain('.')+ })++ // Truncating at the first dot collapsed every quant of a dotted model name onto+ // one id. Rust cancels an in-flight task whose id repeats and deletes its+ // partial file, so downloading one quant destroyed another's.+ it('keeps quants of the same dotted model distinct', () => {+ expect(taskId('Jan-v3.5-4B-Q4_K_XL')).not.toBe(+ taskId('Jan-v3.5-4B-Q8_0')+ )+ })++ it('keeps different versions of the same family distinct', () => {+ expect(taskId('Jan-v3.5-4B-Q4_K_XL')).not.toBe(+ taskId('Jan-v3.6-4B-Q4_K_XL')+ )+ })++ it('namespaces by provider and preserves the rest of the id', () => {+ expect(taskId('some/model-q4_k_m')).toBe('llamacpp/some/model-q4_k_m')+ })++ it('is stable for the same model id', () => {+ expect(taskId('Jan-v3.5-4B-Q4_K_XL')).toBe(taskId('Jan-v3.5-4B-Q4_K_XL'))+ })+})++describe('import deduplication', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ })++ // Two callers racing on one model both passed the model.yml guard and then+ // registered the same download task id, which Rust resolves by cancelling the+ // first and deleting its partial file.+ it('joins a concurrent import of the same model', async () => {+ let release: (() => void) | undefined+ const runImport = vi+ .spyOn(extension as never, 'runImport')+ .mockImplementation(+ () => new Promise<void>((resolve) => (release = resolve)) as never+ )++ const first = extension.import('m', { modelPath: 'u' } as never)+ const second = extension.import('m', { modelPath: 'u' } as never)++ expect(runImport).toHaveBeenCalledTimes(1)+ release?.()+ await Promise.all([first, second])+ })++ it('does not join imports of different models', async () => {+ const runImport = vi+ .spyOn(extension as never, 'runImport')+ .mockResolvedValue(undefined as never)++ await Promise.all([+ extension.import('a', { modelPath: 'u' } as never),+ extension.import('b', { modelPath: 'u' } as never),+ ])++ expect(runImport).toHaveBeenCalledTimes(2)+ })++ it('allows a fresh import once the previous one settled', async () => {+ const runImport = vi+ .spyOn(extension as never, 'runImport')+ .mockResolvedValue(undefined as never)++ await extension.import('m', { modelPath: 'u' } as never)+ await extension.import('m', { modelPath: 'u' } as never)++ expect(runImport).toHaveBeenCalledTimes(2)+ })++ // Both callers asked for the same work, so both must see it fail -- and the+ // slot has to clear so a retry is possible.+ it('rejects every joined caller and clears the slot', async () => {+ const runImport = vi+ .spyOn(extension as never, 'runImport')+ .mockRejectedValue(new Error('offline') as never)++ const first = extension.import('m', { modelPath: 'u' } as never)+ const second = extension.import('m', { modelPath: 'u' } as never)++ await expect(first).rejects.toThrow('offline')+ await expect(second).rejects.toThrow('offline')+ expect(runImport).toHaveBeenCalledTimes(1)++ runImport.mockResolvedValue(undefined as never)+ await extension.import('m', { modelPath: 'u' } as never)+ expect(runImport).toHaveBeenCalledTimes(2)+ })+})++describe('first-run provisioning gate', () => {+ let extension: llamacpp_extension++ beforeEach(() => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()+ })++ const armProvisioningSpies = () => ({+ configure: vi+ .spyOn(extension as never, 'configureBackends')+ .mockResolvedValue(undefined as never),+ router: vi+ .spyOn(extension as never, 'startRouter')+ .mockResolvedValue(undefined as never),+ embedder: vi+ .spyOn(extension as never, 'bootstrapDefaultEmbedder')+ .mockResolvedValue(undefined as never),+ })++ // A first run downloads hundreds of megabytes; the setup screen asks first.+ it('sets the consent flag and provisions when the setup screen asks', async () => {+ const spies = armProvisioningSpies()++ await extension.startFirstRunSetup()++ expect(setBackendSetting).toHaveBeenCalledWith(+ 'llamacpp-first-run-setup-started',+ 'true'+ )+ expect(spies.configure).toHaveBeenCalled()+ expect(spies.embedder).toHaveBeenCalled()+ })++ it('provisions only once however many callers ask', async () => {+ const spies = armProvisioningSpies()++ await Promise.all([+ extension.startFirstRunSetup(),+ extension.startFirstRunSetup(),+ extension['ensureProvisioned'](),+ ])++ expect(spies.configure).toHaveBeenCalledTimes(1)+ expect(spies.embedder).toHaveBeenCalledTimes(1)+ })++ // Skipping setup and later loading a local model still has to work.+ it('provisions on demand when the router is needed', async () => {+ const spies = armProvisioningSpies()+ vi.spyOn(extension as never, 'getRouterInfo').mockResolvedValue({+ port: 1234,+ } as never)++ await extension['ensureRouterReady']()++ expect(spies.configure).toHaveBeenCalledTimes(1)+ })++ it('still provisions when the persisted flag cannot be written', async () => {+ const spies = armProvisioningSpies()+ vi.mocked(setBackendSetting).mockRejectedValueOnce(new Error('disk full'))++ await extension.startFirstRunSetup()++ expect(spies.configure).toHaveBeenCalled()+ })++ it('treats an unreadable consent flag as not consented', async () => {+ vi.mocked(getBackendSetting).mockRejectedValue(new Error('unreadable'))++ expect(await extension['hasSetupConsent']()).toBe(false)+ })++ it('reads consent from the persisted flag', async () => {+ vi.mocked(getBackendSetting).mockResolvedValue('true')+ expect(await extension['hasSetupConsent']()).toBe(true)++ vi.mocked(getBackendSetting).mockResolvedValue(null)+ expect(await extension['hasSetupConsent']()).toBe(false)+ })+})diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 0d406c954..3478b316b 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -6884,6 +6884,7 @@ dependencies = ["hmac","jan-utils","lddtree",+ "libloading 0.8.9","log","nix 0.30.1","rand 0.8.5",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lockindex de96b347e..b40d708f8 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock@@ -3435,6 +3435,7 @@ dependencies = ["hmac","jan-utils","lddtree",+ "libloading 0.8.9","log","nix","rand 0.8.6",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlindex 177cf7ee9..d0e2408ab 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml@@ -15,6 +15,9 @@ base64 = "0.22.1"byteorder = "1.5.0"hmac = "0.12.1"jan-utils = { path = "../../utils" }+# Cross-platform dlopen/LoadLibrary with error strings, for the out-of-process+# backend load probe. Already present in the lockfile via other crates.+libloading = "0.8"walkdir = "2"log = "0.4"rand = "0.8"diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 46ec34390..22792d86f 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -52,6 +52,8 @@ const COMMANDS: &[&str] = &["build_backend_download_items","fetch_backend_checksums","verify_file_sha512",+ // Backend GPU library load probe+ "probe_backend_load",];fn main() {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.tsindex eeb10bca2..e5384f21f 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts@@ -12,6 +12,7 @@ import {BestBackendResult,UpdateCheckResult,SettingUpdateResult,+ LoadProbeResult,} from './types'// Helpers@@ -154,6 +155,25 @@ export async function getDevices(})}+/**+ * Loads the backend's GPU library the way llama-server would, to recover the+ * reason it cannot. A release build of ggml discards that error and silently+ * falls back to CPU, so this is the only way to name the missing dependency.+ */+export async function probeBackendLoad(+ backend: string,+ version: string,+ janDataFolder: string,+ isWindows: boolean+): Promise<LoadProbeResult> {+ return await invoke('plugin:llamacpp|probe_backend_load', {+ backend,+ version,+ janDataFolder,+ isWindows,+ })+}+export async function generateApiKey(modelId: string,apiSecret: stringdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex f41d128af..2de81a72e 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -205,3 +205,22 @@ export interface SettingUpdateResult {version?: stringbackend?: string}++/** One ggml GPU library that failed to load, with the cause. */+export interface LoadProbeFailure {+ library: string+ /** Raw loader message. */+ error: string+ /** Names parsed out of `error`, for install advice. */+ missing_libraries: string[]+}++export interface LoadProbeResult {+ loaded: string[]+ failures: LoadProbeFailure[]+ /**+ * The probe could not run, so an empty `failures` list must not be read as a+ * healthy backend.+ */+ inconclusive: boolean+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.mdindex b96ca3302..5fea63fb4 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md@@ -51,6 +51,7 @@ Default permissions for the llamacpp plugin- `allow-build-backend-download-items`- `allow-fetch-backend-checksums`- `allow-verify-file-sha512`+- `allow-probe-backend-load`## Permission Table@@ -948,6 +949,32 @@ Denies the prioritize_backends command without any pre-configured scope.<tr><td>+`llamacpp:allow-probe-backend-load`++</td>+<td>++Enables the probe_backend_load command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-probe-backend-load`++</td>+<td>++Denies the probe_backend_load command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-read-gguf-metadata`</td>diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.tomlindex 0fb70ba92..9cfeb8d78 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml@@ -56,5 +56,8 @@ permissions = ["allow-fetch-remote-supported-backends","allow-build-backend-download-items","allow-fetch-backend-checksums",- "allow-verify-file-sha512"+ "allow-verify-file-sha512",++ # Backend GPU library load probe+ "allow-probe-backend-load"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.jsonindex 494ee500a..bda297a75 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json@@ -702,6 +702,18 @@"const": "deny-prioritize-backends","markdownDescription": "Denies the prioritize_backends command without any pre-configured scope."},+ {+ "description": "Enables the probe_backend_load command without any pre-configured scope.",+ "type": "string",+ "const": "allow-probe-backend-load",+ "markdownDescription": "Enables the probe_backend_load command without any pre-configured scope."+ },+ {+ "description": "Denies the probe_backend_load command without any pre-configured scope.",+ "type": "string",+ "const": "deny-probe-backend-load",+ "markdownDescription": "Denies the probe_backend_load command without any pre-configured scope."+ },{"description": "Enables the read_gguf_metadata command without any pre-configured scope.","type": "string",@@ -859,10 +871,10 @@"markdownDescription": "Denies the verify_file_sha512 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-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\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-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`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`",+ "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-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\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-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`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`\n- `allow-probe-backend-load`","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-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\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-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`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`"+ "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-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\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-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`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`\n- `allow-probe-backend-load`"}]}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rsindex 667dd36ef..fd19161c9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs@@ -14,6 +14,8 @@ pub enum ErrorCode {ModelArchNotSupported,ModelLoadTimedOut,LlamaCppProcessError,+ MissingSharedLibrary,+ GpuDriverTooOld,// --- Memory Errors ---OutOfMemory,@@ -34,6 +36,10 @@ pub struct LlamacppError {pub message: String,#[serde(skip_serializing_if = "Option::is_none")]pub details: Option<String>,+ /// Library names the loader could not resolve, so the UI can turn them into+ /// install advice instead of showing raw stderr.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub missing_libraries: Option<Vec<String>>,}impl LlamacppError {@@ -42,6 +48,7 @@ impl LlamacppError {code,message,details,+ missing_libraries: None,}}@@ -64,6 +71,27 @@ impl LlamacppError {);}+ // A dynamic-loader failure is why a mismatched GPU backend dies on+ // launch; without this it lands on the generic process error.+ if is_missing_library(&lower_stderr) {+ let libs = extract_missing_libraries(stderr);+ let mut err = Self::new(+ ErrorCode::MissingSharedLibrary,+ "A library this backend depends on is missing.".into(),+ Some(stderr.into()),+ );+ err.missing_libraries = (!libs.is_empty()).then_some(libs);+ return err;+ }++ if is_driver_too_old(&lower_stderr) {+ return Self::new(+ ErrorCode::GpuDriverTooOld,+ "The installed GPU driver is too old for this backend.".into(),+ Some(stderr.into()),+ );+ }+if lower_stderr.contains("error loading model architecture") {return Self::new(ErrorCode::ModelArchNotSupported,@@ -79,6 +107,87 @@ impl LlamacppError {}}+// Deliberately specific: a bare "was not found" also matches a missing model+// file, which is a different failure with different advice.+const MISSING_LIBRARY_MARKERS: [&str; 5] = [+ "cannot open shared object file",+ "library not loaded",+ ".dll was not found",+ "the specified module could not be found",+ "image not found",+];++const DRIVER_TOO_OLD_MARKERS: [&str; 5] = [+ "driver version is insufficient",+ "cudaerrorinsufficientdriver",+ "error_incompatible_driver",+ "unsupported display driver",+ "forward compatibility was attempted on non supported",+];++fn is_missing_library(lower_stderr: &str) -> bool {+ MISSING_LIBRARY_MARKERS+ .iter()+ .any(|m| lower_stderr.contains(m))+}++fn is_driver_too_old(lower_stderr: &str) -> bool {+ DRIVER_TOO_OLD_MARKERS+ .iter()+ .any(|m| lower_stderr.contains(m))+}++fn looks_like_library(name: &str) -> bool {+ !name.is_empty()+ && !name.contains(char::is_whitespace)+ && (name.contains(".so") || name.ends_with(".dylib") || name.ends_with(".dll"))+}++/// Pulls unresolved library names out of loader diagnostics. Case is preserved,+/// so this reads the original stderr rather than a lowercased copy. Shared with+/// the load probe, which parses `dlerror()` text of the same shape.+pub(crate) fn extract_missing_libraries(stderr: &str) -> Vec<String> {+ let mut found: Vec<String> = Vec::new();++ for line in stderr.lines() {+ let lower = line.to_lowercase();++ // `<...>: libfoo.so.1: cannot open shared object file: ...`+ if let Some(idx) = lower.find("cannot open shared object file") {+ let head = line[..idx].trim_end_matches([' ', ':']);+ let candidate = head.rsplit([':', ' ']).next().unwrap_or("").trim();+ push_library(&mut found, candidate);+ }++ // macOS: `Library not loaded: @rpath/libfoo.dylib`+ if let Some(idx) = lower.find("library not loaded:") {+ let tail = line[idx + "library not loaded:".len()..].trim();+ let candidate = tail.split_whitespace().next().unwrap_or("");+ push_library(&mut found, basename(candidate));+ }++ // Windows: `because cudart64_12.dll was not found.`+ if let Some(idx) = lower.find(".dll was not found").map(|i| i + ".dll".len()) {+ let head = line[..idx].trim_end();+ let candidate = head.split_whitespace().last().unwrap_or("");+ push_library(&mut found, basename(candidate));+ }+ }++ found+}++fn basename(path: &str) -> &str {+ path.rsplit(['/', '\\']).next().unwrap_or(path)+}++fn push_library(found: &mut Vec<String>, candidate: &str) {+ let candidate = candidate.trim_matches(['\'', '"', '(', ')', ',', '.'].as_ref());+ if looks_like_library(candidate) && !found.iter().any(|f| f == candidate) {+ found.push(candidate.to_string());+ }+}+// Error type for server commands#[derive(Debug, thiserror::Error)]pub enum ServerError {@@ -124,3 +233,186 @@ impl serde::Serialize for ServerError {}pub type ServerResult<T> = Result<T, ServerError>;++#[cfg(test)]+mod tests {+ use super::*;++ fn classify(stderr: &str) -> LlamacppError {+ LlamacppError::from_stderr(stderr)+ }++ // The UI matches on these exact strings to pick a localized message, so the+ // wire format is part of the contract, not an implementation detail.+ #[test]+ fn error_codes_serialize_to_the_strings_the_ui_matches_on() {+ let cases = [+ (ErrorCode::BinaryNotFound, "BINARY_NOT_FOUND"),+ (ErrorCode::ModelFileNotFound, "MODEL_FILE_NOT_FOUND"),+ (ErrorCode::LibraryPathInvalid, "LIBRARY_PATH_INVALID"),+ (ErrorCode::ModelLoadFailed, "MODEL_LOAD_FAILED"),+ (ErrorCode::DraftModelLoadFailed, "DRAFT_MODEL_LOAD_FAILED"),+ (+ ErrorCode::MultimodalProjectorLoadFailed,+ "MULTIMODAL_PROJECTOR_LOAD_FAILED",+ ),+ (ErrorCode::ModelArchNotSupported, "MODEL_ARCH_NOT_SUPPORTED"),+ (ErrorCode::ModelLoadTimedOut, "MODEL_LOAD_TIMED_OUT"),+ (ErrorCode::LlamaCppProcessError, "LLAMA_CPP_PROCESS_ERROR"),+ (ErrorCode::MissingSharedLibrary, "MISSING_SHARED_LIBRARY"),+ (ErrorCode::GpuDriverTooOld, "GPU_DRIVER_TOO_OLD"),+ (ErrorCode::OutOfMemory, "OUT_OF_MEMORY"),+ (ErrorCode::InvalidArgument, "INVALID_ARGUMENT"),+ (ErrorCode::DeviceListParseFailed, "DEVICE_LIST_PARSE_FAILED"),+ (ErrorCode::IoError, "IO_ERROR"),+ (ErrorCode::InternalError, "INTERNAL_ERROR"),+ ];++ for (code, expected) in cases {+ assert_eq!(+ serde_json::to_string(&code).unwrap(),+ format!("\"{expected}\"")+ );+ }+ }++ #[test]+ fn a_serialized_error_carries_the_fields_the_ui_reads() {+ let err = LlamacppError::from_stderr(+ "libcudart.so.12: cannot open shared object file: No such file or directory",+ );+ let json: serde_json::Value = serde_json::to_value(&err).unwrap();++ assert_eq!(json["code"], "MISSING_SHARED_LIBRARY");+ assert!(json["details"].is_string());+ assert_eq!(json["missing_libraries"][0], "libcudart.so.12");+ }++ // Absent rather than null, so an optional field never reaches the UI as a+ // present-but-empty value.+ #[test]+ fn absent_optional_fields_are_omitted() {+ let err = LlamacppError::new(ErrorCode::InternalError, "boom".into(), None);+ let json: serde_json::Value = serde_json::to_value(&err).unwrap();++ assert!(json.get("details").is_none(), "{json}");+ assert!(json.get("missing_libraries").is_none(), "{json}");+ }++ #[test]+ fn classifies_the_linux_loader_missing_library_message() {+ let err = classify(+ "/home/u/.local/share/Jan/data/llamacpp/backends/b9145/linux-cuda-12-common_cpus-x64/build/bin/llama-server: \+ error while loading shared libraries: libcudart.so.12: cannot open shared object file: No such file or directory",+ );+ assert!(matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ assert_eq!(err.missing_libraries.as_deref(), Some(&["libcudart.so.12".to_string()][..]));+ }++ #[test]+ fn classifies_a_failed_ggml_backend_dlopen() {+ let err = classify(+ "ggml_backend_load_best: failed to load backend from /opt/jan/libggml-cuda.so: \+ libcublas.so.12: cannot open shared object file: No such file or directory",+ );+ assert!(matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ assert_eq!(err.missing_libraries.as_deref(), Some(&["libcublas.so.12".to_string()][..]));+ }++ #[test]+ fn classifies_the_macos_dyld_message() {+ let err = classify(+ "dyld[4213]: Library not loaded: @rpath/libggml-metal.dylib\n \+ Referenced from: /Applications/Jan.app/Contents/Resources/bin/llama-server\n \+ Reason: tried: '/usr/lib/libggml-metal.dylib' (no such file)",+ );+ assert!(matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ assert_eq!(err.missing_libraries.as_deref(), Some(&["libggml-metal.dylib".to_string()][..]));+ }++ #[test]+ fn classifies_the_windows_missing_dll_message() {+ let err = classify(+ "The code execution cannot proceed because cudart64_12.dll was not found. \+ Reinstalling the program may fix this problem.",+ );+ assert!(matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ assert_eq!(err.missing_libraries.as_deref(), Some(&["cudart64_12.dll".to_string()][..]));+ }++ #[test]+ fn reports_every_distinct_missing_library_once() {+ let err = classify(+ "libcublas.so.12: cannot open shared object file: No such file or directory\n\+ libcudart.so.12: cannot open shared object file: No such file or directory\n\+ libcublas.so.12: cannot open shared object file: No such file or directory",+ );+ assert_eq!(+ err.missing_libraries.as_deref(),+ Some(&["libcublas.so.12".to_string(), "libcudart.so.12".to_string()][..])+ );+ }++ // Classified even with no parseable name, so the user still learns the cause.+ #[test]+ fn classifies_a_windows_module_error_without_a_name() {+ let err = classify("LoadLibrary failed: The specified module could not be found.");+ assert!(matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ assert!(err.missing_libraries.is_none(), "{err:?}");+ }++ #[test]+ fn classifies_an_insufficient_cuda_driver() {+ for stderr in [+ "cuda error: CUDA driver version is insufficient for CUDA runtime version",+ "cudaErrorInsufficientDriver",+ "ggml_vulkan: vkCreateInstance failed: ERROR_INCOMPATIBLE_DRIVER",+ "forward compatibility was attempted on non supported HW",+ "system has unsupported display driver / cuda driver combination",+ ] {+ let err = classify(stderr);+ assert!(matches!(err.code, ErrorCode::GpuDriverTooOld), "{stderr} -> {err:?}");+ }+ }++ #[test]+ fn preserves_the_existing_classifications() {+ assert!(matches!(+ classify("ggml_backend_cuda_buffer_type_alloc_buffer: CUDA_ERROR_OUT_OF_MEMORY").code,+ ErrorCode::OutOfMemory+ ));+ assert!(matches!(+ classify("error loading model architecture: unknown arch 'foo'").code,+ ErrorCode::ModelArchNotSupported+ ));+ assert!(matches!(+ classify("something else entirely went wrong").code,+ ErrorCode::LlamaCppProcessError+ ));+ }++ #[test]+ fn always_keeps_raw_stderr_in_details() {+ let raw = "libcudart.so.12: cannot open shared object file: No such file or directory";+ assert_eq!(classify(raw).details.as_deref(), Some(raw));+ }++ // A missing model file is a different failure with different advice, and it+ // shares the "was not found" wording.+ #[test]+ fn does_not_treat_a_missing_model_file_as_a_missing_library() {+ let err = classify("gguf_init_from_file: model.gguf was not found");+ assert!(!matches!(err.code, ErrorCode::MissingSharedLibrary), "{err:?}");+ }++ // A plain path ending in .so must not be mistaken for the missing library.+ #[test]+ fn ignores_library_paths_that_are_not_the_missing_one() {+ let err = classify(+ "ggml_backend_load_best: failed to load backend from /opt/jan/libggml-cuda.so: \+ libcublas.so.12: cannot open shared object file: No such file or directory",+ );+ let libs = err.missing_libraries.unwrap();+ assert!(!libs.iter().any(|l| l.contains("ggml-cuda")), "{libs:?}");+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rsindex 347510301..0981f87db 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs@@ -12,6 +12,7 @@ mod commands;mod device;mod error;mod gguf;+pub mod load_probe;mod path;mod process;pub mod router;@@ -64,6 +65,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {backend::get_backend_exe_path,backend::check_backend_installed,backend::verify_backend_installation,+ load_probe::probe_backend_load,backend::fetch_remote_supported_backends,backend::build_backend_download_items])diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rsnew file mode 100644index 000000000..4010512ff--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rs@@ -0,0 +1,448 @@+//! Out-of-process `dlopen` probe for a backend's GPU library.+//!+//! In a release build, ggml discards the loader error when a backend library+//! fails to load (`ggml_backend_load_all_from_path` passes `silent = true`+//! under `NDEBUG`), so llama-server registers only the CPU backend and runs+//! normally. No stderr is produced and the process exits 0, which makes the+//! failure invisible to output parsing.+//!+//! Loading the library ourselves recovers the real reason. Static ELF analysis+//! is not equivalent: without the runtime search path it reports libraries that+//! sit beside the binary as missing. The probe therefore runs with the same+//! environment the router child gets, and in a subprocess, because initializing+//! a GPU runtime in-process can abort.++use crate::error::extract_missing_libraries;+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++pub const PROBE_FLAG: &str = "--internal-probe-load";++#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]+pub struct LoadProbeResult {+ /// Libraries that loaded cleanly.+ pub loaded: Vec<String>,+ /// One entry per library that failed to load.+ pub failures: Vec<LoadProbeFailure>,+ /// True when the probe could not run at all, so an empty `failures` list+ /// must not be read as success.+ pub inconclusive: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]+pub struct LoadProbeFailure {+ pub library: String,+ /// Raw loader message.+ pub error: String,+ /// Names parsed out of `error`, for install advice.+ pub missing_libraries: Vec<String>,+}++/// Backend-id substring -> the ggml library that implements it. Metal is+/// omitted: it is part of the platform on Apple Silicon and is not a separately+/// loadable failure mode.+const GPU_LIBRARY_KEYWORDS: [(&str, &str); 3] =+ [("cuda", "cuda"), ("vulkan", "vulkan"), ("hip", "hip")];++fn library_extension() -> &'static str {+ if cfg!(target_os = "windows") {+ "dll"+ } else if cfg!(target_os = "macos") {+ "dylib"+ } else {+ "so"+ }+}++fn library_prefix() -> &'static str {+ if cfg!(target_os = "windows") {+ "ggml-"+ } else {+ "libggml-"+ }+}++/// The ggml GPU library filenames to probe for a backend id, matching ggml's own+/// `[lib]ggml-<name>*.<ext>` naming.+pub fn gpu_library_candidates(backend: &str, entries: &[String]) -> Vec<String> {+ let lower = backend.to_lowercase();+ let keyword = GPU_LIBRARY_KEYWORDS+ .iter()+ .find(|(marker, _)| lower.contains(marker))+ .map(|(_, lib)| *lib);++ let Some(keyword) = keyword else {+ return Vec::new();+ };++ let stem = format!("{}{}", library_prefix(), keyword);+ let ext = library_extension();+ let mut matches: Vec<String> = entries+ .iter()+ .filter(|name| {+ let lower_name = name.to_lowercase();+ lower_name.starts_with(&stem) && lower_name.ends_with(&format!(".{ext}"))+ })+ .cloned()+ .collect();+ matches.sort();+ matches+}++/// Child-side entry point. Returns without doing anything unless invoked with+/// `PROBE_FLAG`, so it is safe to call unconditionally at startup.+pub fn run_load_probe_if_requested() {+ let mut args = std::env::args().skip(1);+ if args.next().as_deref() != Some(PROBE_FLAG) {+ return;+ }++ let targets: Vec<PathBuf> = args.map(PathBuf::from).collect();+ let result = probe_libraries(&targets);++ match serde_json::to_string(&result) {+ Ok(s) => {+ println!("{}", s);+ std::process::exit(0);+ }+ Err(e) => {+ eprintln!("serialize failed: {}", e);+ std::process::exit(3);+ }+ }+}++fn probe_libraries(targets: &[PathBuf]) -> LoadProbeResult {+ let mut result = LoadProbeResult::default();++ for target in targets {+ let name = target+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| target.to_string_lossy().to_string());++ // Safety: loading a library runs its initializers. This is why the probe+ // is confined to a subprocess.+ match unsafe { libloading::Library::new(target) } {+ Ok(lib) => {+ // Leak deliberately: unloading a GPU runtime mid-teardown has+ // its own crash modes, and this process exits immediately.+ std::mem::forget(lib);+ result.loaded.push(name);+ }+ Err(e) => {+ let error = e.to_string();+ result.failures.push(LoadProbeFailure {+ library: name,+ missing_libraries: extract_missing_libraries(&error),+ error,+ });+ }+ }+ }++ result+}++/// Parent-side entry point. Spawns this executable with `PROBE_FLAG` and the+/// same library search path the router child receives.+pub fn probe_out_of_process(+ bin_dir: Option<&Path>,+ cuda: &jan_utils::CudaPaths,+ targets: &[PathBuf],+) -> LoadProbeResult {+ let inconclusive = LoadProbeResult {+ inconclusive: true,+ ..Default::default()+ };++ if targets.is_empty() {+ return LoadProbeResult::default();+ }++ let exe = match std::env::current_exe() {+ Ok(p) => p,+ Err(e) => {+ log::warn!("load_probe: current_exe failed: {}", e);+ return inconclusive;+ }+ };++ let mut cmd = Command::new(&exe);+ cmd.arg(PROBE_FLAG);+ for target in targets {+ cmd.arg(target);+ }++ // Parity with the router child: the same search path, or the probe would+ // report libraries the real process resolves. This is the whole reason a+ // static ELF scan is not a substitute.+ let env = jan_utils::library_path_env(bin_dir, cuda);+ for (key, value) in &env.vars {+ cmd.env(key, value);+ }+ if let Some(dir) = &env.current_dir {+ cmd.current_dir(dir);+ }++ cmd.stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());++ let output = match cmd.output() {+ Ok(o) => o,+ Err(e) => {+ log::warn!("load_probe: failed to spawn subprocess: {}", e);+ return inconclusive;+ }+ };++ if !output.status.success() {+ log::warn!(+ "load_probe: subprocess exited with {:?}; stderr: {}",+ output.status.code(),+ String::from_utf8_lossy(&output.stderr).trim(),+ );+ return inconclusive;+ }++ match serde_json::from_slice::<LoadProbeResult>(&output.stdout) {+ Ok(o) => o,+ Err(e) => {+ log::warn!(+ "load_probe: malformed subprocess output: {} (stdout: {})",+ e,+ String::from_utf8_lossy(&output.stdout).trim(),+ );+ inconclusive+ }+ }+}++/// Loads the backend's GPU library the way llama-server would, reporting the+/// reason it cannot. Returns a clean result for CPU-only and macOS backends,+/// which have no separately loadable GPU library.+#[tauri::command]+pub async fn probe_backend_load(+ backend: String,+ version: String,+ jan_data_folder: String,+ is_windows: bool,+) -> Result<LoadProbeResult, crate::error::LlamacppError> {+ let exe_path = PathBuf::from(crate::backend::get_backend_exe_path(+ backend.clone(),+ version,+ jan_data_folder,+ is_windows,+ ));+ let Some(bin_dir) = exe_path.parent().map(PathBuf::from) else {+ return Ok(LoadProbeResult {+ inconclusive: true,+ ..Default::default()+ });+ };++ let entries: Vec<String> = match std::fs::read_dir(&bin_dir) {+ Ok(dir) => dir+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().to_string())+ .collect(),+ Err(e) => {+ log::warn!("load_probe: cannot read {}: {}", bin_dir.display(), e);+ return Ok(LoadProbeResult {+ inconclusive: true,+ ..Default::default()+ });+ }+ };++ let targets: Vec<PathBuf> = gpu_library_candidates(&backend, &entries)+ .into_iter()+ .map(|name| bin_dir.join(name))+ .collect();+ if targets.is_empty() {+ return Ok(LoadProbeResult::default());+ }++ // Spawning and waiting on a subprocess would otherwise block a runtime worker.+ tokio::task::spawn_blocking(move || {+ let cuda = jan_utils::find_cuda_paths().merged(jan_utils::find_rocm_paths());+ probe_out_of_process(Some(&bin_dir), &cuda, &targets)+ })+ .await+ .map_err(|e| {+ crate::error::LlamacppError::new(+ crate::error::ErrorCode::InternalError,+ "Backend load probe failed to run.".into(),+ Some(e.to_string()),+ )+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn entries() -> Vec<String> {+ vec![+ "libggml-base.so".to_string(),+ "libggml-base.so.0".to_string(),+ "libggml-cpu-haswell.so".to_string(),+ "libggml-cuda.so".to_string(),+ "libggml-vulkan.so".to_string(),+ "llama-server".to_string(),+ ]+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn picks_the_cuda_library_for_a_cuda_backend() {+ assert_eq!(+ gpu_library_candidates("linux-cuda-12-common_cpus-x64", &entries()),+ vec!["libggml-cuda.so".to_string()]+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn picks_the_vulkan_library_for_a_vulkan_backend() {+ assert_eq!(+ gpu_library_candidates("linux-vulkan-common_cpus-x64", &entries()),+ vec!["libggml-vulkan.so".to_string()]+ );+ }++ // CPU and base libraries are not the GPU failure mode and must not be+ // probed, or a CPU-only install would look like a GPU problem.+ #[cfg(target_os = "linux")]+ #[test]+ fn never_selects_cpu_or_base_libraries() {+ for backend in ["linux-cuda-12-common_cpus-x64", "linux-vulkan-common_cpus-x64"] {+ let picked = gpu_library_candidates(backend, &entries());+ assert!(+ !picked.iter().any(|p| p.contains("cpu") || p.contains("base")),+ "{picked:?}"+ );+ }+ }++ #[test]+ fn probes_nothing_for_a_cpu_backend() {+ assert!(gpu_library_candidates("linux-common_cpus-x64", &entries()).is_empty());+ }++ // Metal is part of the platform, not a separately loadable backend.+ #[test]+ fn probes_nothing_for_macos() {+ assert!(gpu_library_candidates("macos-arm64", &entries()).is_empty());+ }++ #[test]+ fn reports_a_missing_library_with_its_parsed_name() {+ let result = probe_libraries(&[PathBuf::from("/nonexistent/libggml-cuda.so")]);+ assert_eq!(result.failures.len(), 1, "{result:?}");+ assert_eq!(result.failures[0].library, "libggml-cuda.so");+ assert!(!result.failures[0].error.is_empty());+ assert!(result.loaded.is_empty());+ assert!(!result.inconclusive);+ }++ #[test]+ fn an_empty_target_list_is_conclusive_and_clean() {+ let result = probe_out_of_process(None, &jan_utils::CudaPaths::default(), &[]);+ assert_eq!(result, LoadProbeResult::default());+ assert!(!result.inconclusive);+ }++ // An empty failure list must not be mistaken for a healthy backend when the+ // probe never ran.+ #[test]+ fn inconclusive_is_distinct_from_success() {+ let inconclusive = LoadProbeResult {+ inconclusive: true,+ ..Default::default()+ };+ assert!(inconclusive.failures.is_empty());+ assert_ne!(inconclusive, LoadProbeResult::default());+ }+}++#[cfg(test)]+mod integration_tests {+ use super::*;++ /// Proves the probe's premise against a real install: the GPU library does+ /// NOT resolve without the backend's own directory on the search path, so a+ /// scan that omits that path reports libraries the real process resolves+ /// fine. The positive case cannot be asserted here, because+ /// `probe_out_of_process` re-execs `current_exe`, which under `cargo test`+ /// is the test harness rather than a binary that handles `PROBE_FLAG`; it+ /// requires the app binary wired up in `main.rs`.+ #[cfg(target_os = "linux")]+ #[test]+ #[ignore = "requires a locally installed GPU backend; run with --ignored"]+ fn a_real_backend_library_needs_its_own_directory_on_the_search_path() {+ let Some(bin_dir) = real_backend_bin_dir() else {+ eprintln!("skipped: no installed CUDA/Vulkan backend found");+ return;+ };+ let entries: Vec<String> = std::fs::read_dir(&bin_dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().to_string())+ .collect();++ let backend = bin_dir+ .ancestors()+ .nth(2)+ .and_then(|p| p.file_name())+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_default();++ let candidates = gpu_library_candidates(&backend, &entries);+ if candidates.is_empty() {+ eprintln!("skipped: {backend} is not a GPU backend");+ return;+ }+ // The selector must find a real file, not just match a synthetic list.+ for candidate in &candidates {+ assert!(bin_dir.join(candidate).is_file(), "{candidate} missing");+ }++ let targets: Vec<PathBuf> = candidates.iter().map(|c| bin_dir.join(c)).collect();+ let bare = probe_libraries(&targets);++ assert!(+ !bare.failures.is_empty(),+ "expected failure without the search path, proving a scan that omits \+ it cannot be trusted: {bare:?}"+ );+ // And the failure must name a library, which is what drives install advice.+ assert!(+ bare.failures+ .iter()+ .any(|f| !f.missing_libraries.is_empty()),+ "probe failure should name the unresolved library: {bare:?}"+ );+ }++ #[cfg(target_os = "linux")]+ fn real_backend_bin_dir() -> Option<PathBuf> {+ let home = std::env::var("HOME").ok()?;+ let base = PathBuf::from(home).join(".local/share/Jan/data/llamacpp/backends");+ for version in std::fs::read_dir(base).ok()?.filter_map(|e| e.ok()) {+ for backend in std::fs::read_dir(version.path()).ok()?.filter_map(|e| e.ok()) {+ let name = backend.file_name().to_string_lossy().to_string();+ if !["cuda", "vulkan", "hip"].iter().any(|k| name.contains(k)) {+ continue;+ }+ let bin = backend.path().join("build/bin");+ if bin.is_dir() {+ return Some(bin);+ }+ }+ }+ None+ }+}diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rsindex edb38d951..ba056d263 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs@@ -29,38 +29,9 @@ pub async fn get_status(state: State<'_, VectorDBState>) -> Result<Status, Vectolet temp = db::collection_path(&state.base_dir, "__status__");let conn = db::open_or_init_conn(&temp)?;- // Verbose version for startup diagnostics- let ann = {- if conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok() {- let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);- println!("[VectorDB] ✓ sqlite-vec already loaded");- true- } else {- unsafe { let _ = conn.load_extension_enable(); }- let paths = db::possible_sqlite_vec_paths();- println!("[VectorDB] Trying {} bundled paths...", paths.len());- let mut found = false;- for p in paths {- println!("[VectorDB] Trying: {}", p);- unsafe {- if conn.load_extension(&p, Some("sqlite3_vec_init")).is_ok()- && conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok()- {- let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);- println!("[VectorDB] ✓ sqlite-vec loaded from: {}", p);- found = true;- break;- }- }- }- if !found {- println!("[VectorDB] ✗ Failed to load sqlite-vec from all paths");- }- found- }- };-- println!("[VectorDB] ANN status: {}", if ann { "AVAILABLE ✓" } else { "NOT AVAILABLE ✗" });+ let ann = db::try_load_sqlite_vec_verbose(&conn);++ println!("[VectorDB] ANN status: {}", if ann { "AVAILABLE" } else { "NOT AVAILABLE" });Ok(Status { ann_available: ann })}diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rsindex b1f006df9..368ab9fdd 100644--- a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs@@ -69,40 +69,105 @@ pub fn open_or_init_conn(path: &PathBuf) -> Result<Connection, VectorDBError> {// ============================================================================pub fn try_load_sqlite_vec(conn: &Connection) -> bool {- // Check if vec0 module is already available- if conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok() {+ load_sqlite_vec(conn, false)+}++/// Same probe, narrating each candidate for startup diagnostics.+pub fn try_load_sqlite_vec_verbose(conn: &Connection) -> bool {+ load_sqlite_vec(conn, true)+}++fn vec0_module_available(conn: &Connection) -> bool {+ if conn+ .execute(+ "CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])",+ [],+ )+ .is_ok()+ {let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);return true;}+ false+}++fn load_sqlite_vec(conn: &Connection, verbose: bool) -> bool {+ if vec0_module_available(conn) {+ if verbose {+ println!("[VectorDB] sqlite-vec already loaded");+ }+ return true;+ }unsafe {let _ = conn.load_extension_enable();}let paths = possible_sqlite_vec_paths();+ if verbose {+ println!("[VectorDB] Trying {} sqlite-vec candidates...", paths.len());+ }for p in paths {- unsafe {- if conn.load_extension(&p, Some("sqlite3_vec_init")).is_ok()- && conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS temp.temp_vec USING vec0(embedding float[1])", []).is_ok()- {- let _ = conn.execute("DROP TABLE IF EXISTS temp.temp_vec", []);- return true;+ if verbose {+ println!("[VectorDB] Trying: {}", p);+ }+ let loaded = unsafe { conn.load_extension(&p, Some("sqlite3_vec_init")).is_ok() };+ if loaded && vec0_module_available(conn) {+ if verbose {+ println!("[VectorDB] sqlite-vec loaded from: {}", p);}+ return true;}}+ if verbose {+ println!("[VectorDB] sqlite-vec unavailable; using linear search");+ }false}+/// Filenames sqlite-vec ships under, without a platform suffix; SQLite appends+/// that itself. `vec0` is what most distro packages install.+const SQLITE_VEC_STEMS: [&str; 2] = ["sqlite-vec", "vec0"];++const SQLITE_VEC_SYSTEM_DIRS: &[&str] = if cfg!(target_os = "macos") {+ &["/opt/homebrew/lib", "/usr/local/lib", "/usr/lib"]+} else if cfg!(target_os = "windows") {+ &["C:\\Program Files\\sqlite-vec"]+} else {+ &[+ "/usr/lib/sqlite3",+ "/usr/local/lib/sqlite3",+ "/usr/lib/x86_64-linux-gnu",+ "/usr/lib/aarch64-linux-gnu",+ "/usr/lib64",+ "/usr/local/lib",+ "/usr/lib",+ ]+};+pub fn possible_sqlite_vec_paths() -> Vec<String> {+ build_sqlite_vec_paths(+ std::env::var("JAN_SQLITE_VEC_PATH").ok(),+ std::env::current_exe().ok(),+ )+}++fn build_sqlite_vec_paths(override_path: Option<String>, exe: Option<PathBuf>) -> Vec<String> {let mut paths = Vec::new();+ if let Some(custom) = override_path {+ if !custom.trim().is_empty() {+ paths.push(custom);+ }+ }+// Dev pathspaths.push("./src-tauri/resources/bin/sqlite-vec".to_string());paths.push("./resources/bin/sqlite-vec".to_string());// Exe-relative paths- if let Ok(exe) = std::env::current_exe() {+ if let Some(exe) = exe {if let Some(dir) = exe.parent() {let mut d = dir.to_path_buf();d.push("resources");@@ -122,6 +187,20 @@ pub fn possible_sqlite_vec_paths() -> Vec<String> {}}}++ // System installs: the library is not bundled, so a package-manager copy is+ // the usual source of ANN acceleration.+ for dir in SQLITE_VEC_SYSTEM_DIRS {+ for stem in SQLITE_VEC_STEMS {+ paths.push(format!("{dir}{}{stem}", std::path::MAIN_SEPARATOR));+ }+ }++ // Bare stems last, so the OS loader can search its own default paths.+ paths.extend(SQLITE_VEC_STEMS.iter().map(|s| s.to_string()));++ let mut seen = std::collections::HashSet::new();+ paths.retain(|p| seen.insert(p.clone()));paths}@@ -673,6 +752,66 @@ pub fn chunk_text(text: String, chunk_size: usize, chunk_overlap: usize) -> Vec<mod tests {use super::*;+ #[test]+ fn override_takes_priority_over_every_other_candidate() {+ let paths = build_sqlite_vec_paths(Some("/custom/vec".to_string()), None);+ assert_eq!(paths.first().map(String::as_str), Some("/custom/vec"));+ }++ #[test]+ fn blank_override_is_ignored() {+ let paths = build_sqlite_vec_paths(Some(" ".to_string()), None);+ assert!(!paths.iter().any(|p| p.trim().is_empty()), "{paths:?}");+ }++ #[test]+ fn bundled_paths_are_searched_before_system_paths() {+ let paths = build_sqlite_vec_paths(None, Some(PathBuf::from("/opt/jan/bin/jan")));+ let bundled = paths+ .iter()+ .position(|p| p.contains("resources"))+ .expect("a bundled candidate should exist");+ let system = paths+ .iter()+ .position(|p| !p.contains("resources") && p.starts_with('/'))+ .expect("a system candidate should exist");+ assert!(bundled < system, "{paths:?}");+ }++ // A package-manager install is the only way to get ANN now that the library+ // is deliberately not bundled.+ #[test]+ fn searches_system_library_directories() {+ let paths = build_sqlite_vec_paths(None, None);+ assert!(+ paths.iter().any(|p| p.starts_with("/usr/")+ || p.starts_with("/opt/")+ || p.starts_with("C:\\")),+ "{paths:?}"+ );+ }++ // A bare stem lets the OS loader consult LD_LIBRARY_PATH and its default+ // directories, which covers layouts we cannot enumerate.+ #[test]+ fn ends_with_bare_stems_for_the_loader_to_resolve() {+ let paths = build_sqlite_vec_paths(None, None);+ for stem in SQLITE_VEC_STEMS {+ assert!(paths.contains(&stem.to_string()), "missing {stem} in {paths:?}");+ }+ let first_bare = paths.iter().position(|p| !p.contains('/') && !p.contains('\\'));+ assert_eq!(first_bare.map(|i| i + SQLITE_VEC_STEMS.len()), Some(paths.len()));+ }++ #[test]+ fn candidates_are_unique() {+ let paths = build_sqlite_vec_paths(None, Some(PathBuf::from("/opt/jan/bin/jan")));+ let mut seen = paths.clone();+ seen.sort();+ seen.dedup();+ assert_eq!(seen.len(), paths.len(), "duplicate candidates in {paths:?}");+ }+#[test]fn serializes_a_finite_embedding() {assert_eq!(embedding_to_json(&[0.5, -0.25]).unwrap(), "[0.5,-0.25]");diff --git a/src-tauri/src/core/filesystem/commands.rs b/src-tauri/src/core/filesystem/commands.rsindex 783281a39..59acccea0 100644--- a/src-tauri/src/core/filesystem/commands.rs+++ b/src-tauri/src/core/filesystem/commands.rs@@ -174,18 +174,31 @@ pub fn read_yaml<R: Runtime>(Ok(data)}+/// Unpacking a backend archive is hundreds of megabytes of gzip and file IO. A+/// synchronous command would run it on the main thread and freeze the window+/// (and, on WebKitGTK, all rendering) for its whole duration, so the work is+/// handed to the blocking pool instead.#[tauri::command]-pub fn decompress<R: Runtime>(+pub async fn decompress<R: Runtime>(app: tauri::AppHandle<R>,- path: &str,- output_dir: &str,+ path: String,+ output_dir: String,) -> Result<(), String> {- let path_buf = std::path::PathBuf::from(path);+ let path_buf = std::path::PathBuf::from(&path);let (_jan_data_folder, output_dir_buf) =- resolve_app_path_within_jan_data_folder(app, output_dir)?;+ resolve_app_path_within_jan_data_folder(app, &output_dir)?;++ tauri::async_runtime::spawn_blocking(move || unpack_archive(&path_buf, &output_dir_buf))+ .await+ .map_err(|e| format!("Decompression task failed: {}", e))?+}+pub(crate) fn unpack_archive(+ path_buf: &std::path::Path,+ output_dir_buf: &std::path::Path,+) -> Result<(), String> {// Ensure output directory exists- fs::create_dir_all(&output_dir_buf).map_err(|e| {+ fs::create_dir_all(output_dir_buf).map_err(|e| {format!("Failed to create output directory {}: {}",output_dir_buf.to_string_lossy(),@@ -196,20 +209,21 @@ pub fn decompress<R: Runtime>(// Use short path on Windows to handle paths with spaces#[cfg(windows)]let file = {- if let Some(short_path) = jan_utils::path::get_short_path(&path_buf) {+ if let Some(short_path) = jan_utils::path::get_short_path(path_buf) {fs::File::open(&short_path).map_err(|e| e.to_string())?} else {- fs::File::open(&path_buf).map_err(|e| e.to_string())?+ fs::File::open(path_buf).map_err(|e| e.to_string())?}};#[cfg(not(windows))]- let file = fs::File::open(&path_buf).map_err(|e| e.to_string())?;- if path.ends_with(".tar.gz") {+ let file = fs::File::open(path_buf).map_err(|e| e.to_string())?;+ let name = path_buf.to_string_lossy();+ if name.ends_with(".tar.gz") {let tar = flate2::read::GzDecoder::new(file);let mut archive = tar::Archive::new(tar);- archive.unpack(&output_dir_buf).map_err(|e| e.to_string())?;- } else if path.ends_with(".zip") {+ archive.unpack(output_dir_buf).map_err(|e| e.to_string())?;+ } else if name.ends_with(".zip") {let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;for i in 0..zip.len() {let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;diff --git a/src-tauri/src/core/filesystem/tests.rs b/src-tauri/src/core/filesystem/tests.rsindex 1891c873d..0b48fa95f 100644--- a/src-tauri/src/core/filesystem/tests.rs+++ b/src-tauri/src/core/filesystem/tests.rs@@ -179,6 +179,52 @@ fn test_resolve_jan_scoped_path_rejects_absolute_path_outside_root() {let _ = fs::remove_dir_all(outside_path.parent().unwrap());}+#[test]+fn test_unpack_archive_tar_gz() {+ let dir = unique_test_dir("unpack");+ let nested = dir.join("build/bin");+ fs::create_dir_all(&nested).unwrap();+ File::create(nested.join("llama-server"))+ .unwrap()+ .write_all(b"binary")+ .unwrap();++ let archive_path = dir.join("backend.tar.gz");+ {+ let gz = flate2::write::GzEncoder::new(+ File::create(&archive_path).unwrap(),+ flate2::Compression::fast(),+ );+ let mut builder = tar::Builder::new(gz);+ builder.append_dir_all("build", dir.join("build")).unwrap();+ builder.into_inner().unwrap().finish().unwrap();+ }++ let out = dir.join("out");+ unpack_archive(&archive_path, &out).unwrap();+ assert_eq!(+ fs::read_to_string(out.join("build/bin/llama-server")).unwrap(),+ "binary"+ );++ let _ = fs::remove_dir_all(&dir);+}++#[test]+fn test_unpack_archive_rejects_unknown_extension() {+ let dir = unique_test_dir("unpack-bad");+ fs::create_dir_all(&dir).unwrap();+ let archive_path = dir.join("backend.rar");+ File::create(&archive_path)+ .unwrap()+ .write_all(b"x")+ .unwrap();++ assert!(unpack_archive(&archive_path, &dir.join("out")).is_err());++ let _ = fs::remove_dir_all(&dir);+}+fn unique_test_dir(label: &str) -> PathBuf {use std::time::{SystemTime, UNIX_EPOCH};diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 3de5058cb..996494f81 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -9,5 +9,8 @@ fn main() {// Exits early if invoked as the out-of-process lddtree helper.tauri_plugin_llamacpp::deps_analyzer::run_deps_analyzer_if_requested();+ // Exits early if invoked as the out-of-process backend load probe.+ tauri_plugin_llamacpp::load_probe::run_load_probe_if_requested();+app_lib::run();}diff --git a/src-tauri/utils/src/system.rs b/src-tauri/utils/src/system.rsindex 33af47d81..810d371cf 100644--- a/src-tauri/utils/src/system.rs+++ b/src-tauri/utils/src/system.rs@@ -69,12 +69,48 @@ impl CudaPaths {}}+/// Environment a child needs to resolve the backend's libraries. Returned+/// rather than applied so callers holding either a `tokio` or a `std` Command+/// share one implementation.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct LibraryEnv {+ pub vars: Vec<(String, String)>,+ pub current_dir: Option<std::path::PathBuf>,+}++// Mirrors the Command setter names so the path-building logic below reads the+// same whether it targets a Command or this struct.+impl LibraryEnv {+ fn env(&mut self, key: &str, value: impl AsRef<str>) {+ self.vars+ .push((key.to_string(), value.as_ref().to_string()));+ }++ fn current_dir(&mut self, dir: impl AsRef<Path>) {+ self.current_dir = Some(dir.as_ref().to_path_buf());+ }+}+/// Merges binary lib dir + CUDA paths into a single `command.env()` call per variable.pub fn setup_library_path(library_path: Option<&Path>,cuda: &CudaPaths,command: &mut tokio::process::Command,) {+ let env = library_path_env(library_path, cuda);+ for (key, value) in &env.vars {+ command.env(key, value);+ }+ if let Some(dir) = &env.current_dir {+ command.current_dir(dir);+ }+}++/// Computes the same overrides `setup_library_path` applies.+pub fn library_path_env(library_path: Option<&Path>, cuda: &CudaPaths) -> LibraryEnv {+ let mut env = LibraryEnv::default();+ let command = &mut env;+if cfg!(target_os = "linux") {let mut all_lib_dirs: Vec<String> = Vec::new();if let Some(lib_path) = library_path {@@ -152,6 +188,8 @@ pub fn setup_library_path(#[cfg(feature = "logging")]log::warn!("Library path setup not supported on this OS");}++ env}pub fn binary_requires_cuda(_bin_path: &Path) -> bool {diff --git a/web-app/src/containers/DownloadManegement.tsx b/web-app/src/containers/DownloadManegement.tsxindex e65cb564c..433a54915 100644--- a/web-app/src/containers/DownloadManegement.tsx+++ b/web-app/src/containers/DownloadManegement.tsx@@ -7,25 +7,21 @@ import { Progress } from '@/components/ui/progress'import { useDownloadStore } from '@/hooks/useDownloadStore'import { useAppUpdater } from '@/hooks/useAppUpdater'import { useServiceHub } from '@/hooks/useServiceHub'-import { DownloadEvent, DownloadState, events, AppEvent } from '@janhq/core'+import { events, AppEvent } from '@janhq/core'import { IconPlayerPause, IconPlayerPlay, IconX } from '@tabler/icons-react'import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { useTranslation } from '@/i18n/react-i18next-compat'-import { useNavigate } from '@tanstack/react-router'-import { route } from '@/constants/routes'import { DownloadIcon } from 'lucide-react'import { Button } from '@/components/ui/button'import { formatBytes } from '@/lib/utils'export function DownloadManagement() {const { t } = useTranslation()- const navigate = useNavigate()const [isPopoverOpen, setIsPopoverOpen] = useState(false)const serviceHub = useServiceHub()const {downloads,- updateProgress,localDownloadingModels,removeDownload,removeLocalDownloadingModel,@@ -148,122 +144,6 @@ export function DownloadManagement() {appUpdateState.downloadedBytes,])- const onFileDownloadUpdate = useCallback(- async (state: DownloadState) => {- updateProgress(- state.modelId,- state.percent,- state.modelId,- state.size?.transferred,- state.size?.total- )- },- [updateProgress]- )-- const onFileDownloadError = useCallback(- (state: DownloadState) => {- console.debug('onFileDownloadError', state)- removeDownload(state.modelId)- removeLocalDownloadingModel(state.modelId)-- const anyState = state as unknown as { error?: string }- const err = anyState?.error || ''-- if (err.includes('HTTP status 401')) {- toast.error('Hugging Face token required', {- id: 'download-failed',- description:- 'This model requires a Hugging Face access token. Add your token in Settings and retry.',- action: {- label: 'Open Settings',- onClick: () => navigate({ to: route.settings.general }),- },- })- return- }-- if (err.includes('HTTP status 403')) {- toast.error('Accept model license on Hugging Face', {- id: 'download-failed',- description:- 'You must accept the model’s license on its Hugging Face page before downloading.',- })- return- }-- if (err.includes('HTTP status 429')) {- toast.error('Rate limited by Hugging Face', {- id: 'download-failed',- description:- 'You have been rate-limited. Adding a token can increase rate limits. Please try again later.',- action: {- label: 'Open Settings',- onClick: () => navigate({ to: route.settings.general }),- },- })- return- }-- toast.error(t('common:toast.downloadFailed.title'), {- id: 'download-failed',- description: t('common:toast.downloadFailed.description', {- item: state.modelId,- }),- })- },- [removeDownload, removeLocalDownloadingModel, t, navigate]- )-- const onModelValidationStarted = useCallback(- (event: { modelId: string; downloadType: string }) => {- console.debug('onModelValidationStarted', event)-- // Show validation in progress toast- toast.info(t('common:toast.modelValidationStarted.title'), {- id: `model-validation-started-${event.modelId}`,- description: t('common:toast.modelValidationStarted.description', {- modelId: event.modelId,- }),- duration: Infinity,- })- },- [t]- )-- const onModelValidationFailed = useCallback(- (event: { modelId: string; error: string; reason: string }) => {- console.debug('onModelValidationFailed', event)-- // Dismiss the validation started toast- toast.dismiss(`model-validation-started-${event.modelId}`)-- removeDownload(event.modelId)- removeLocalDownloadingModel(event.modelId)-- // Show specific toast for validation failure- toast.error(t('common:toast.modelValidationFailed.title'), {- description: t('common:toast.modelValidationFailed.description', {- modelId: event.modelId,- }),- duration: 30000,- })- },- [removeDownload, removeLocalDownloadingModel, t]- )-- const onFileDownloadStopped = useCallback(- (state: DownloadState) => {- console.debug('onFileDownloadStopped', state)- // A pause stops the download via the same cancel path; keep the entry- // (with its partial progress) so it can be resumed.- if (useDownloadStore.getState().downloads[state.modelId]?.paused) return- removeDownload(state.modelId)- removeLocalDownloadingModel(state.modelId)- },- [removeDownload, removeLocalDownloadingModel]- )-const handlePauseDownload = useCallback(async (id: string) => {setPaused(id, true)@@ -331,82 +211,12 @@ export function DownloadManagement() {[removeDownload, removeLocalDownloadingModel, serviceHub, t])- const onFileDownloadSuccess = useCallback(- async (state: DownloadState) => {- console.debug('onFileDownloadSuccess', state)-- // Dismiss any validation started toast when download completes successfully- toast.dismiss(`model-validation-started-${state.modelId}`)-- removeDownload(state.modelId)- removeLocalDownloadingModel(state.modelId)- toast.success(t('common:toast.downloadComplete.title'), {- id: 'download-complete',- description: t('common:toast.downloadComplete.description', {- item: state.modelId,- }),- })- },- [removeDownload, removeLocalDownloadingModel, t]- )-- const onFileDownloadAndVerificationSuccess = useCallback(- async (state: DownloadState) => {- console.debug('onFileDownloadAndVerificationSuccess', state)-- // Dismiss any validation started toast when download and verification complete successfully- toast.dismiss(`model-validation-started-${state.modelId}`)-- removeDownload(state.modelId)- removeLocalDownloadingModel(state.modelId)- toast.success(t('common:toast.downloadAndVerificationComplete.title'), {- id: 'download-complete',- description: t(- 'common:toast.downloadAndVerificationComplete.description',- {- item: state.modelId,- }- ),- })- },- [removeDownload, removeLocalDownloadingModel, t]- )-useEffect(() => {- console.debug('DownloadListener: registering event listeners...')- events.on(DownloadEvent.onFileDownloadUpdate, onFileDownloadUpdate)- events.on(DownloadEvent.onFileDownloadError, onFileDownloadError)- events.on(DownloadEvent.onFileDownloadSuccess, onFileDownloadSuccess)- events.on(DownloadEvent.onFileDownloadStopped, onFileDownloadStopped)- events.on(DownloadEvent.onModelValidationStarted, onModelValidationStarted)- events.on(DownloadEvent.onModelValidationFailed, onModelValidationFailed)- events.on(- DownloadEvent.onFileDownloadAndVerificationSuccess,- onFileDownloadAndVerificationSuccess- )-- // Register app update event listenersevents.on(AppEvent.onAppUpdateDownloadUpdate, onAppUpdateDownloadUpdate)events.on(AppEvent.onAppUpdateDownloadSuccess, onAppUpdateDownloadSuccess)events.on(AppEvent.onAppUpdateDownloadError, onAppUpdateDownloadError)return () => {- console.debug('DownloadListener: unregistering event listeners...')- events.off(DownloadEvent.onFileDownloadUpdate, onFileDownloadUpdate)- events.off(DownloadEvent.onFileDownloadError, onFileDownloadError)- events.off(DownloadEvent.onFileDownloadSuccess, onFileDownloadSuccess)- events.off(DownloadEvent.onFileDownloadStopped, onFileDownloadStopped)- events.off(- DownloadEvent.onModelValidationStarted,- onModelValidationStarted- )- events.off(DownloadEvent.onModelValidationFailed, onModelValidationFailed)- events.off(- DownloadEvent.onFileDownloadAndVerificationSuccess,- onFileDownloadAndVerificationSuccess- )-- // Unregister app update event listenersevents.off(AppEvent.onAppUpdateDownloadUpdate, onAppUpdateDownloadUpdate)events.off(AppEvent.onAppUpdateDownloadSuccess,@@ -415,13 +225,6 @@ export function DownloadManagement() {events.off(AppEvent.onAppUpdateDownloadError, onAppUpdateDownloadError)}}, [- onFileDownloadUpdate,- onFileDownloadError,- onFileDownloadSuccess,- onFileDownloadStopped,- onModelValidationStarted,- onModelValidationFailed,- onFileDownloadAndVerificationSuccess,onAppUpdateDownloadUpdate,onAppUpdateDownloadSuccess,onAppUpdateDownloadError,diff --git a/web-app/src/containers/PromptJanModel.tsx b/web-app/src/containers/PromptJanModel.tsxdeleted file mode 100644index 48b2b0785..000000000--- a/web-app/src/containers/PromptJanModel.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { Button } from '@/components/ui/button'-import { useJanModelPromptDismissed } from '@/hooks/useJanModelPrompt'-import { useServiceHub } from '@/hooks/useServiceHub'-import { useDownloadStore } from '@/hooks/useDownloadStore'-import { useGeneralSetting } from '@/hooks/useGeneralSetting'-import { useMemo } from 'react'-import { SETUP_SCREEN_QUANTIZATIONS } from '@/constants/models'-import { useLatestJanModel } from '@/hooks/useLatestJanModel'--export function PromptJanModel() {-- const { setDismissedModelName } = useJanModelPromptDismissed()- const serviceHub = useServiceHub()- const { downloads, localDownloadingModels, addLocalDownloadingModel } =- useDownloadStore()- const huggingfaceToken = useGeneralSetting((state) => state.huggingfaceToken)-- const { model: janNewModel, loading: isLoading } = useLatestJanModel()-- const defaultVariant = useMemo(() => {- if (!janNewModel) return null-- for (const quantization of SETUP_SCREEN_QUANTIZATIONS) {- const variant = janNewModel.quants?.find((quant) =>- quant.model_id.toLowerCase().includes(quantization)- )- if (variant) return variant- }-- return janNewModel.quants?.[0]- }, [janNewModel])-- const isDownloading = useMemo(() => {- if (!defaultVariant) return false- return (- localDownloadingModels.has(defaultVariant.model_id) ||- Object.values(downloads).some((d) => d.id === defaultVariant.model_id)- )- }, [defaultVariant, localDownloadingModels, downloads])-- const handleDismiss = () => {- if (janNewModel) setDismissedModelName(janNewModel.model_name)- }-- const handleDownload = () => {- if (!defaultVariant || !janNewModel) return-- addLocalDownloadingModel(defaultVariant.model_id)- serviceHub.models().pullModelWithMetadata(- defaultVariant.model_id,- defaultVariant.path,- (- janNewModel.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || janNewModel.mmproj_models?.[0]- )?.path,- huggingfaceToken,- true- )- if (janNewModel) setDismissedModelName(janNewModel.model_name)- }-- if (isLoading || !janNewModel) return null-- return (- <div className="fixed bottom-4 right-4 z-50 p-4 shadow-lg bg-background w-4/5 md:w-100 border rounded-lg">- <div className="flex items-center gap-2">- <img src="/images/jan-logo.png" alt="Jan" className="size-5" />- <h2 className="font-medium">- {janNewModel?.display_name ?? janNewModel?.model_name ?? 'Jan Model'}- {defaultVariant && (- <span className="text-muted-foreground">- {' '}- ({defaultVariant.file_size})- </span>- )}- </h2>- </div>- <p className="mt-2 text-sm text-muted-foreground">- Get started with {janNewModel?.display_name ?? 'Jan'}, our recommended local AI model optimized for your device.- </p>- <div className="mt-4 flex justify-end space-x-2">- <Button- variant="ghost"- size="sm"- className="text-muted-foreground"- onClick={handleDismiss}- >- Later- </Button>- <Button- onClick={handleDownload}- disabled={!defaultVariant || isDownloading}- size="sm"- >- {isDownloading ? 'Downloading' : 'Download'}- </Button>- </div>- </div>- )-}diff --git a/web-app/src/containers/SetupScreen.tsx b/web-app/src/containers/SetupScreen.tsxindex 3d7780a32..9bc794da8 100644--- a/web-app/src/containers/SetupScreen.tsx+++ b/web-app/src/containers/SetupScreen.tsx@@ -11,11 +11,127 @@ import { SETUP_SCREEN_QUANTIZATIONS } from '@/constants/models'import { useLatestJanModel } from '@/hooks/useLatestJanModel'import { toast } from 'sonner'import { Button } from '@/components/ui/button'-import { IconEye, IconSquareCheck } from '@tabler/icons-react'-import { cn, formatBytes } from '@/lib/utils'+import { Progress } from '@/components/ui/progress'+import {+ IconAlertTriangle,+ IconArrowRight,+ IconCheck,+ IconCpu,+ IconEye,+ IconLoader2,+ IconSquareCheck,+} from '@tabler/icons-react'+import { cn } from '@/lib/utils'import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { useAnalytic } from '@/hooks/useAnalytic'+import {+ useSetupChecklist,+ type SetupStageState,+} from '@/hooks/useSetupChecklist'+import { pickMmproj, type SetupModelOption } from '@/lib/setupModelOptions'+import { AnalyticConsent } from './analytics/AnalyticConsent'+import { DependencyAdvice } from './dialogs/DependencyAdvice'import HeaderPage from './HeaderPage'+/**+ * One page of the setup flow. The model page is derived from download state+ * rather than from a readiness probe, so it does not come from+ * `useSetupChecklist` with the others.+ */+type WizardStep = {+ id: string+ labelKey: string+ status: SetupStageState['status']+ messageKey: string+ values?: Record<string, string | number>+ detail?: string+}++/**+ * Renders before the model metadata lands, so the name and size are optional and+ * the card does not pop into existence once the fetch resolves.+ */+function ModelCard({+ option,+ fallbackName,+ progress,+ isDownloading,+ isDownloaded,+ onDownload,+}: {+ option: SetupModelOption | null+ fallbackName?: string+ /** Completed fraction, 0 to 1. */+ progress: number+ isDownloading: boolean+ isDownloaded: boolean+ onDownload: () => void+}) {+ const { t } = useTranslation()+ const name =+ option?.displayName || fallbackName || t('setup:fallbackModelName')++ return (+ <div+ data-testid="setup-model-card"+ className="bg-secondary/50 p-3 rounded-lg border flex items-center gap-3"+ >+ <div className="shrink-0 size-12 bg-background rounded-xl flex items-center justify-center">+ <img src="/images/jan-logo.png" alt="Jan Logo" className="size-6" />+ </div>++ <div className="min-w-0 flex-1">+ <h2 className="font-semibold text-sm truncate">+ <span>{name}</span>+ {option?.fileSize && (+ <>+ + <span className="text-xs text-muted-foreground font-normal">+ · {option.fileSize}+ </span>+ </>+ )}+ </h2>+ <div className="text-muted-foreground text-sm mt-1.5 flex items-center gap-1">+ <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-secondary text-xs rounded-full">+ <IconSquareCheck size={12} />+ {t('setup:capabilityGeneral')}+ </span>+ {option?.multimodal && (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-secondary text-xs rounded-full">+ <IconEye size={12} />+ {t('setup:capabilityMultimodal')}+ </span>+ )}+ </div>+ </div>++ {/* The action sits with the thing it acts on rather than anchoring the+ screen, since downloading this model is not a precondition for the+ checks above it. */}+ <div className="shrink-0">+ {isDownloaded ? (+ <span className="inline-flex items-center gap-1 text-xs text-green-500">+ <IconCheck size={14} />+ {t('setup:modelInstalled')}+ </span>+ ) : isDownloading ? (+ <div className="flex w-20 items-center gap-2">+ <Progress className="border" value={progress * 100} />+ <span className="text-xs text-muted-foreground">+ {Math.round(progress * 100)}%+ </span>+ </div>+ ) : (+ <Button variant="outline" size="sm" onClick={onDownload}>+ {t('setup:download')}+ </Button>+ )}+ </div>+ </div>+ )+}+type CacheEntry = {status: 'RED' | 'YELLOW' | 'GREEN' | 'GREY'timestamp: number@@ -101,6 +217,28 @@ function SetupScreen() {const checkedModelId = useRef<string | null>(null)const [isSupportCheckComplete, setIsSupportCheckComplete] = useState(false)const huggingfaceToken = useGeneralSetting((state) => state.huggingfaceToken)+ // Nothing is probed until the user starts: the first page is an invitation,+ // not a progress report.+ const [hasStarted, setHasStarted] = useState(false)+ const beginSetup = useCallback(() => {+ setHasStarted(true)+ // Not awaited: the readiness checks are what report its progress.+ void serviceHub.models().startEngineSetup()+ }, [serviceHub])+ const { stages, warnings, gpu, isRunning, rerun } = useSetupChecklist({+ enabled: hasStarted,+ })+ const [showDetails, setShowDetails] = useState(false)+ const { productAnalyticPrompt } = useAnalytic()+ // `productAnalyticPrompt` flips to false the moment consent is answered, which+ // dropped that page out of the list and renumbered the flow under the user+ // ("Step 3 of 4" became "Step 3 of 3"). Latched instead, so the page count is+ // fixed once known.+ const [includesConsent, setIncludesConsent] = useState(false)+ useEffect(() => {+ if (productAnalyticPrompt) setIncludesConsent(true)+ }, [productAnalyticPrompt])+// Check model support for variants when janNewModel is availableuseEffect(() => {@@ -170,6 +308,7 @@ function SetupScreen() {fetchLatestJanModel(true)}, [fetchLatestJanModel])+const defaultVariant = useMemo(() => {if (!janNewModel) return null@@ -191,18 +330,6 @@ function SetupScreen() {}}- for (const quantization of SETUP_SCREEN_QUANTIZATIONS) {- if (quantization === 'q8_0') continue-- const variant = janNewModel.quants?.find((quant) =>- quant.model_id.toLowerCase().includes(quantization)- )-- if (variant && supportedVariants.get(variant.model_id) === 'RED') {- return variant- }- }-for (const quantization of SETUP_SCREEN_QUANTIZATIONS) {const variant = janNewModel.quants?.find((quant) =>quant.model_id.toLowerCase().includes(quantization)@@ -223,6 +350,26 @@ function SetupScreen() {return janNewModel.quants?.[0]}, [janNewModel, supportedVariants])+ // The recommended model as a uniform option, so the download path stays+ // independent of how the quant was chosen.+ const selected = useMemo<SetupModelOption | null>(() => {+ if (!janNewModel || !defaultVariant) return null+ return {+ modelName: janNewModel.model_name,+ displayName:+ janNewModel.display_name?.trim() || janNewModel.model_name || '',+ modelId: defaultVariant.model_id,+ path: defaultVariant.path,+ fileSize: defaultVariant.file_size,+ multimodal: (janNewModel.mmproj_models?.length ?? 0) > 0,+ mmprojPath: pickMmproj(janNewModel),+ }+ }, [janNewModel, defaultVariant])++ // The quant depends on the per-variant fit check, so a click before it lands+ // has to be queued rather than acted on.+ const isSelectionReady = Boolean(selected && isSupportCheckComplete)+const downloadProcesses = useMemo(() =>Object.values(downloads).map((download) => ({@@ -236,100 +383,101 @@ function SetupScreen() {)const isDownloading = useMemo(() => {- if (!defaultVariant) return false+ if (!selected) return falsereturn (- localDownloadingModels.has(defaultVariant.model_id) ||- downloadProcesses.some((e) => e.id === defaultVariant.model_id)+ localDownloadingModels.has(selected.modelId) ||+ downloadProcesses.some((e) => e.id === selected.modelId))- }, [defaultVariant, localDownloadingModels, downloadProcesses])+ }, [selected, localDownloadingModels, downloadProcesses])- const downloadedSize = useMemo(() => {- if (!defaultVariant) return { current: 0, total: 0 }- const process = downloadProcesses.find(- (e) => e.id === defaultVariant.model_id+ // Fraction rather than byte counts, matching how the Hub reports a download.+ const downloadProgress = useMemo(() => {+ if (!selected) return 0+ return (+ downloadProcesses.find((e) => e.id === selected.modelId)?.progress || 0)- return {- current: process?.current || 0,- total: process?.total || 0,- }- }, [defaultVariant, downloadProcesses])+ }, [selected, downloadProcesses])const isDownloaded = useMemo(() => {- if (!defaultVariant) return false+ if (!selected) return falsereturn llamaProvider?.models.some(- (m: { id: string }) => m.id === defaultVariant.model_id+ (m: { id: string }) => m.id === selected.modelId)- }, [defaultVariant, llamaProvider])+ }, [selected, llamaProvider])++ // Single download entry point for both the immediate and the queued path, so+ // the HF token and the skip-verification flag cannot drift between them.+ const startDownload = useCallback(+ (option: SetupModelOption) => {+ addLocalDownloadingModel(option.modelId)+ serviceHub+ .models()+ .pullModelWithMetadata(+ option.modelId,+ option.path,+ option.mmprojPath,+ huggingfaceToken,+ true+ )+ },+ [addLocalDownloadingModel, serviceHub, huggingfaceToken]+ )const handleQuickStart = useCallback(() => {- // If metadata is still loading, queue the download- if (!defaultVariant || !janNewModel || !isSupportCheckComplete) {+ setQuickStartInitiated(true)+ // Metadata still loading: remember the intent and download once it lands.+ if (!selected || !isSelectionReady) {setQuickStartQueued(true)- setQuickStartInitiated(true)return}-- setQuickStartInitiated(true)- addLocalDownloadingModel(defaultVariant.model_id)- serviceHub.models().pullModelWithMetadata(- defaultVariant.model_id,- defaultVariant.path,- (- janNewModel.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || janNewModel.mmproj_models?.[0]- )?.path,- huggingfaceToken, // Use HF token from general settings- true // Skip verification for faster download- )- }, [- defaultVariant,- janNewModel,- isSupportCheckComplete,- addLocalDownloadingModel,- serviceHub,- huggingfaceToken,- ])+ startDownload(selected)+ }, [selected, isSelectionReady, startDownload])// Use ref to track if we've already navigatedconst hasNavigatedRef = useRef(false)-- // Navigate when download completes - using event listener for reliability+ /** Pages the user has passed despite a warning; they must not reappear. */+ const [acknowledged, setAcknowledged] = useState<string[]>([])++ const completeSetup = useCallback(async () => {+ if (!selected || hasNavigatedRef.current) return+ hasNavigatedRef.current = true++ // Refresh providers so the model is available in the store before selecting+ const providers = await serviceHub.providers().getProviders()+ setProviders(providers)++ // On Windows the provider may list model IDs with backslashes (from filesystem paths)+ // while the catalog uses forward slashes, so try both formats+ const catalogId = selected.modelId+ const backslashId = catalogId.replace(/\//g, '\\')+ const found =+ selectModelProvider('llamacpp', catalogId) ||+ selectModelProvider('llamacpp', backslashId)+ const modelId = found ? found.id : catalogId++ toast.dismiss(`model-validation-started-${catalogId}`)+ localStorage.setItem(localStorageKey.setupCompleted, 'true')+ localStorage.setItem(+ localStorageKey.lastUsedModel,+ JSON.stringify({ provider: 'llamacpp', model: modelId })+ )+ navigate({+ to: route.home,+ replace: true,+ search: {+ threadModel: { id: modelId, provider: 'llamacpp' },+ },+ })+ }, [selected, navigate, selectModelProvider, serviceHub, setProviders])++ // Leaving setup is driven by the import event rather than by provider state,+ // which only refreshes afterwards. Warnings no longer gate this: each was its+ // own page and was passed deliberately before the model page was reached.useEffect(() => {-const onModelImported = async (payload: { modelId: string }) => {- if (!defaultVariant || hasNavigatedRef.current) return- if (payload.modelId !== defaultVariant.model_id) return-- hasNavigatedRef.current = true-- console.log('SetupScreen: Model imported, navigating to home...')-- // Refresh providers so the model is available in the store before selecting- const providers = await serviceHub.providers().getProviders()- setProviders(providers)-- // On Windows the provider may list model IDs with backslashes (from filesystem paths)- // while the catalog uses forward slashes, so try both formats- const catalogId = defaultVariant.model_id- const backslashId = catalogId.replace(/\//g, '\\')- const found = selectModelProvider('llamacpp', catalogId)- || selectModelProvider('llamacpp', backslashId)- const modelId = found ? found.id : catalogId-- toast.dismiss(`model-validation-started-${catalogId}`)- localStorage.setItem(localStorageKey.setupCompleted, 'true')- localStorage.setItem(- localStorageKey.lastUsedModel,- JSON.stringify({ provider: 'llamacpp', model: modelId })- )- navigate({- to: route.home,- replace: true,- search: {- threadModel: { id: modelId, provider: 'llamacpp' },- },- })+ if (!selected || hasNavigatedRef.current) return+ if (payload.modelId !== selected.modelId) return+ await completeSetup()}events.on(AppEvent.onModelImported, onModelImported)@@ -337,39 +485,137 @@ function SetupScreen() {return () => {events.off(AppEvent.onModelImported, onModelImported)}- }, [defaultVariant, navigate, selectModelProvider, serviceHub, setProviders])+ }, [selected, completeSetup])useEffect(() => {- if (- quickStartQueued &&- defaultVariant &&- janNewModel &&- isSupportCheckComplete- ) {+ if (quickStartQueued && selected && isSelectionReady) {setQuickStartQueued(false)- addLocalDownloadingModel(defaultVariant.model_id)- serviceHub- .models()- .pullModelWithMetadata(- defaultVariant.model_id,- defaultVariant.path,- (- janNewModel.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || janNewModel.mmproj_models?.[0]- )?.path,- undefined,- true- )+ startDownload(selected)+ }+ }, [quickStartQueued, selected, isSelectionReady, startDownload])++ // The model step reports the download the user starts here, so it is derived+ // from download state rather than from a readiness probe.+ // Named dependencies come from the same warning the standalone dialog would+ // have raised; the advice is rendered inline here instead.+ const dependencyWarning = warnings.find(+ (warning) => (warning.missingLibraries?.length ?? 0) > 0+ )+ const missingLibraries = dependencyWarning?.missingLibraries ?? []+ const dependencyBackend = dependencyWarning?.backend ?? ''++ const modelStep = useMemo<WizardStep>(() => {+ const model = selected?.displayName ?? ''+ const step = (+ status: SetupStageState['status'],+ messageKey: string,+ values?: Record<string, string | number>+ ): WizardStep => ({+ id: 'model',+ labelKey: 'setup:stageModel',+ status,+ messageKey,+ values,+ })++ if (isDownloaded) return step('ok', 'checkModelReady', { model })+ if (isDownloading) return step('running', 'checkModelDownloading', { model })+ if (!selected) return step('running', 'checkModelResolving')+ return step('pending', 'checkModelWaiting', {+ model,+ size: selected.fileSize || '',+ })+ }, [selected, isDownloaded, isDownloading])++ // One page at a time, each transient: it gives way as soon as its own+ // condition is met, and the model download is always last.+ //+ // The three readiness probes collapse into a single "set up llama.cpp" page:+ // the backend download and the embedding install are one wait from the user's+ // point of view, and the hardware probe only exists to label the GPU badge.+ const setupPage = useMemo<WizardStep>(() => {+ const byId = new Map(stages.map((stage) => [stage.id, stage]))+ const engine = byId.get('engine')+ const search = byId.get('search')+ const system = byId.get('system')++ // The first unresolved of the three decides what the page reports, so the+ // engine's own progress is shown before the checks that depend on it.+ const reporting =+ [engine, search, system].find((stage) => stage?.status === 'warning') ??+ [engine, search].find((stage) => stage?.status !== 'ok') ??+ engine++ return {+ id: 'setup',+ labelKey: 'setup:stageSetup',+ status: reporting?.status ?? 'pending',+ messageKey: reporting?.messageKey ?? '',+ values: reporting?.values,+ detail: reporting?.detail,+ }+ }, [stages])++ // Advanced only on the user's say-so. Auto-advancing skipped this page+ // entirely whenever the engine was already installed, which hid the GPU badge+ // -- the one thing on it the user cannot see anywhere else.+ const isSetupSettled = acknowledged.includes('setup')+ const isSetupComplete = ['engine', 'search', 'system'].every(+ (id) => stages.find((stage) => stage.id === id)?.status === 'ok'+ )+ /** The backend asset name, shown as a caption rather than as prose. */+ const engineBackendName = String(+ stages.find((stage) => stage.id === 'engine')?.values?.backend ?? ''+ )++ const pages = useMemo<WizardStep[]>(() => {+ const welcome: WizardStep = {+ id: 'welcome',+ labelKey: 'setup:welcomeTitle',+ status: 'pending',+ messageKey: '',}- }, [- quickStartQueued,- defaultVariant,- janNewModel,- isSupportCheckComplete,- addLocalDownloadingModel,- serviceHub,- ])+ const consent: WizardStep[] = includesConsent+ ? [+ {+ id: 'consent',+ labelKey: 'setup:stageConsent',+ status: 'pending',+ messageKey: '',+ },+ ]+ : []+ return [welcome, setupPage, ...consent, modelStep]+ }, [setupPage, modelStep, includesConsent])++ const isPageSettled = useCallback(+ (page: WizardStep) => {+ switch (page.id) {+ case 'welcome':+ return hasStarted+ case 'setup':+ return isSetupSettled+ case 'consent':+ return !productAnalyticPrompt+ default:+ return Boolean(isDownloaded)+ }+ },+ [hasStarted, isSetupSettled, productAnalyticPrompt, isDownloaded]+ )++ const currentIndex = pages.findIndex((page) => !isPageSettled(page))+ const currentPage = currentIndex === -1 ? undefined : pages[currentIndex]++ // A model already on disk (a repeat visit, or one fetched from the Hub) leaves+ // no import event to wait for.+ useEffect(() => {+ if (currentIndex === -1 && !hasNavigatedRef.current) void completeSetup()+ }, [currentIndex, completeSetup])++ const acknowledge = useCallback((id: string) => {+ setAcknowledged((prev) => (prev.includes(id) ? prev : [...prev, id]))+ }, [])// Handle error when quick start is queued but metadata fetch failsuseEffect(() => {@@ -396,96 +642,266 @@ function SetupScreen() {}, [quickStartInitiated, quickStartQueued, isDownloading, isDownloaded])+ const isWarning = currentPage?.status === 'warning'+ const isSetupPage = currentPage?.id === 'setup'++ // The engine reports its identity as a bare asset name, which is useful as a+ // caption but is not a sentence. The page supplies its own prose.+ const setupBody = isSetupComplete+ ? t('setup:setupDoneBody')+ : currentPage?.messageKey+ ? t(`setup:${currentPage.messageKey}`, currentPage.values)+ : t('setup:stageChecking')++ // The consent page has no subtitle of its own: AnalyticConsent's own detail+ // paragraph is the body, so a second one here would just repeat it.+ const body = () => {+ switch (currentPage?.id) {+ case 'welcome':+ return t('setup:welcomeBody')+ case 'model':+ return t('setup:description')+ case 'consent':+ return null+ default:+ return setupBody+ }+ }+return (<div className="relative flex flex-col h-svh w-full overflow-hidden">- {/* Content overlay */}- <div className="flex flex-col h-svh w-full">+ <div className="flex flex-col h-svh w-full"><HeaderPage />-- <div className="flex h-[calc(100%-60px)] items-center">- <div className="shrink-0 px-10 w-[480px] mx-auto overflow-auto pb-10 pointer-events-auto -mt-20">- <div className="mb-4">- <h1 className="font-studio font-medium text-2xl mb-1">- {isDownloading ? 'Sit tight, Jan is getting ready...' : 'Hey, welcome to Jan!'}- </h1>- <p className='text-muted-foreground leading-normal w-full mt-1'>{isDownloading ? 'This may take a few minutes.' : 'Jan needs a model to begin. Let’s set it up.'}</p>- </div>- <div className="flex gap-4 flex-col mt-6 relative z-50">- <div- className="w-full text-left"- >- <span className='mb-2 block text-sm font-medium'>Recommended model</span>- <div className={cn("bg-secondary/50 p-3 rounded-lg border transition-all hover:shadow disabled:opacity-60 flex justify-between items-start")}>- <div className="flex w-full items-start gap-4">- <div className="shrink-0 size-12 bg-background rounded-xl flex items-center justify-center">- <img src="/images/jan-logo.png" alt="Jan Logo" className='size-6' />- </div>- <div className="flex flex-col w-full h-full justify-center">- <div className="flex flex-1 items-center justify-between">- <h1 className="font-semibold text-sm mb-1">- <span>{janNewModel?.display_name ?? janNewModel?.model_name ?? 'Jan Model'}</span> <span className='text-xs text-muted-foreground'>· {defaultVariant?.file_size}</span>- </h1>- {(isDownloading) && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <svg- className="size-3 animate-spin"- viewBox="0 0 24 24"- fill="none"- >- <circle- className="opacity-25"- cx="12"- cy="12"- r="10"- stroke="currentColor"- strokeWidth="4"- />- <path- className="opacity-75"- fill="currentColor"- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"- />- </svg>- <span>- {formatBytes(downloadedSize.current, {- hideUnit: true,- minUnit: 'GB',- decimals: (value) => (value === 0 ? 0 : 1),- })}{' '}- /{' '}- {formatBytes(downloadedSize.total, {- hideUnit: true,- minUnit: 'GB',- decimals: (value) => (value === 0 ? 0 : 1),- })}- GB- </span>- </div>++ <div className="flex h-[calc(100%-60px)] items-center justify-center px-6">+ <div+ className="w-full max-w-[460px] rounded-2xl border bg-card/60 p-7 shadow-xl pointer-events-auto"+ data-testid="setup-wizard"+ data-page={currentPage?.id ?? 'done'}+ >+ {currentPage && (+ <>+ <div className="flex items-center justify-between gap-4">+ <span+ className="text-xs font-medium uppercase tracking-wider text-muted-foreground"+ data-testid="setup-step-counter"+ >+ {t('setup:stepCounter', {+ current: currentIndex + 1,+ total: pages.length,+ })}+ </span>+ {/* Segments rather than dots: they read as distance covered,+ which is what a first-run flow needs to convey. */}+ <span className="flex items-center gap-1" aria-hidden>+ {pages.map((page, index) => (+ <span+ key={page.id}+ className={cn(+ 'h-1 w-6 rounded-full transition-colors',+ index === currentIndex+ ? 'bg-primary'+ : index < currentIndex+ ? 'bg-muted-foreground/50'+ : 'bg-muted-foreground/15')}+ />+ ))}+ </span>+ </div>+ <div className="mt-6">+ {isSetupPage && (+ <span+ className={cn(+ 'mb-4 inline-flex size-9 items-center justify-center rounded-xl',+ isWarning+ ? 'bg-destructive/10 text-destructive'+ : isSetupComplete+ ? 'bg-green-500/10 text-green-400'+ : 'bg-muted text-muted-foreground'+ )}+ >+ {isWarning ? (+ <IconAlertTriangle size={18} />+ ) : isSetupComplete ? (+ <IconCheck size={18} />+ ) : (+ <IconLoader2 size={18} className="animate-spin" />+ )}+ </span>+ )}+ <h1 className="font-studio font-medium text-2xl tracking-tight">+ {isSetupPage && isSetupComplete+ ? t('setup:stageSetupDone')+ : t(currentPage.labelKey)}+ </h1>+ {body() && (+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">+ {body()}+ </p>+ )}+ </div>++ {currentPage.id === 'welcome' && (+ <Button className="mt-6 w-full" onClick={beginSetup}>+ {t('setup:startSetup')}+ </Button>+ )}++ {/* The one fact a user cannot infer from a progress line:+ whether the work they are waiting for lands on the GPU. */}+ {isSetupPage && (+ <div+ className={cn(+ 'mt-5 flex items-start gap-2.5 rounded-xl border px-3.5 py-3',+ gpu.willUse+ ? 'border-green-500/25 bg-green-500/8'+ : 'border-border bg-muted/40'+ )}+ data-testid="setup-gpu-badge"+ >+ <span+ className={cn(+ 'mt-0.5 shrink-0',+ gpu.willUse ? 'text-green-400' : 'text-muted-foreground'+ )}+ >+ {gpu.willUse === undefined ? (+ <IconLoader2 size={15} className="animate-spin" />+ ) : gpu.willUse ? (+ <IconCheck size={15} />+ ) : (+ <IconCpu size={15} />+ )}+ </span>+ <div className="min-w-0">+ <p+ className={cn(+ 'text-sm font-medium',+ gpu.willUse ? 'text-green-400' : 'text-foreground'+ )}+ >+ {gpu.willUse === undefined+ ? t('setup:badgeGpuUnknown')+ : gpu.willUse+ ? t('setup:badgeGpu')+ : t('setup:badgeCpu')}+ </p>+ {gpu.label && (+ <p className="mt-0.5 truncate text-xs text-muted-foreground">+ {gpu.label}+ </p>+ )}+ </div>+ </div>+ )}++ {isSetupPage && isWarning && (+ <div className="mt-4" data-testid="setup-page-warning">+ {warnings.length > 1 && (+ <p className="mb-2 text-xs text-destructive">+ {t('setup:otherWarnings', {+ count: warnings.length - 1,+ })}+ </p>+ )}+ {currentPage.detail && (+ <>+ <button+ type="button"+ className="text-xs text-muted-foreground underline"+ onClick={() => setShowDetails((prev) => !prev)}+ >+ {showDetails+ ? t('setup:hideDetails')+ : t('setup:showDetails')}+ </button>+ {showDetails && (+ <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-lg bg-muted/50 p-2.5 text-xs text-muted-foreground">+ {currentPage.detail}+ </pre>+ )}+ </>+ )}+ {missingLibraries.length > 0 && (+ <div className="mt-3">+ <DependencyAdvice+ backend={dependencyBackend}+ missingLibraries={missingLibraries}+ /></div>- <div className="text-muted-foreground text-sm mt-1.5 ">- <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-secondary text-xs rounded-full mr-1">- <IconSquareCheck size={12} />- General- </span>- {(janNewModel?.mmproj_models?.length ?? 0) > 0 && <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-secondary text-xs rounded-full">- <IconEye size={12} />- Multimodal- </span>}- </div>+ )}+ </div>+ )}++ {isSetupPage && (+ <>+ {/* The engine's asset name: a caption, never the sentence. */}+ {engineBackendName && (+ <p className="mt-3 truncate font-mono text-[11px] text-muted-foreground/60">+ {engineBackendName}+ </p>+ )}+ <div className="mt-5 flex items-center gap-3">+ {/* Continue once the work is done; the same button skips+ ahead while it is still running, since this page covers+ a backend download and waiting must not be the only+ option. */}+ <Button+ className="flex-1"+ onClick={() => acknowledge('setup')}+ >+ {isSetupComplete+ ? t('setup:continueStep')+ : isWarning+ ? t('setup:continueAnyway')+ : t('setup:skipStep')}+ </Button>+ {isWarning && !isRunning && (+ <Button+ variant="link"+ onClick={() => void rerun()}+ className="px-0"+ >+ {t('setup:retryChecks')}+ </Button>+ )}</div>+ </>+ )}++ {currentPage.id === 'consent' && (+ <div className="mt-5">+ <AnalyticConsent /></div>- </div>- <div className="flex flex-col relative z-50 items-start gap-2 mt-4">- <Button size="sm" disabled={isDownloading} onClick={handleQuickStart} className='flex items-center gap-2 w-full'>- {isDownloading ? 'Downloading' : 'Download'}- </Button>- </div>- </div>- </div>+ )}++ {currentPage.id === 'model' && (+ <div className="mt-5">+ <ModelCard+ option={selected}+ fallbackName={+ janNewModel?.display_name ?? janNewModel?.model_name+ }+ progress={downloadProgress}+ isDownloading={isDownloading}+ isDownloaded={Boolean(isDownloaded)}+ onDownload={handleQuickStart}+ />+ <button+ type="button"+ className="mt-3 inline-flex items-center gap-1 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"+ onClick={() => navigate({ to: route.hub.index })}+ >+ {t('setup:exploreHub')}+ <IconArrowRight size={12} />+ </button>+ </div>+ )}+ </>+ )}</div>-</div></div></div>diff --git a/web-app/src/containers/__tests__/DownloadManegement.test.tsx b/web-app/src/containers/__tests__/DownloadManegement.test.tsxindex 4a5500846..21cad4a82 100644--- a/web-app/src/containers/__tests__/DownloadManegement.test.tsx+++ b/web-app/src/containers/__tests__/DownloadManegement.test.tsx@@ -212,65 +212,12 @@ describe('DownloadManagement', () => {await waitFor(() => expect(hoisted.abortDownloadMock).toHaveBeenCalledWith('cloud-model'))})- it('handles HTTP 401 download error with settings toast action', () => {- render(<DownloadManagement />)- const handler = hoisted.eventHandlers['fde']- expect(handler).toBeDefined()- handler({ modelId: 'x', error: 'HTTP status 401 unauth' })- expect(hoisted.toastMock.error).toHaveBeenCalledWith(- 'Hugging Face token required',- expect.any(Object)- )- expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('x')- })- it('handles HTTP 403 download error', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['fde']({ modelId: 'y', error: 'HTTP status 403 denied' })- expect(hoisted.toastMock.error).toHaveBeenCalledWith(- 'Accept model license on Hugging Face',- expect.any(Object)- )- })- it('handles HTTP 429 rate-limit error', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['fde']({ modelId: 'z', error: 'HTTP status 429 slow down' })- expect(hoisted.toastMock.error).toHaveBeenCalledWith(- 'Rate limited by Hugging Face',- expect.any(Object)- )- })- it('handles generic download error with translated toast', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['fde']({ modelId: 'w', error: 'other' })- expect(hoisted.toastMock.error).toHaveBeenCalledWith(- 'common:toast.downloadFailed.title',- expect.any(Object)- )- })- it('on file download success, removes download and shows toast', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['fds']({ modelId: 'ok' })- expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('ok')- expect(hoisted.toastMock.success).toHaveBeenCalled()- })- it('on model validation started, shows info toast', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['mvs']({ modelId: 'v', downloadType: 'model' })- expect(hoisted.toastMock.info).toHaveBeenCalled()- })- it('on model validation failed, dismisses toast and removes download', () => {- render(<DownloadManagement />)- hoisted.eventHandlers['mvf']({ modelId: 'v', error: 'bad', reason: 'checksum' })- expect(hoisted.toastMock.dismiss).toHaveBeenCalledWith('model-validation-started-v')- expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('v')- expect(hoisted.toastMock.error).toHaveBeenCalled()- })it('on app update download success, shows success toast', () => {render(<DownloadManagement />)@@ -356,25 +303,7 @@ describe('DownloadManagement', () => {expect(hoisted.toastMock.error).toHaveBeenCalled()})- it('keeps the entry on stopped event when paused', () => {- hoisted.downloadStore.downloads = {- 'cloud-model': { name: 'cloud-model', progress: 0.3, paused: true },- }- render(<DownloadManagement />)- hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })- expect(hoisted.downloadStore.removeDownload).not.toHaveBeenCalled()- })- it('removes the entry on stopped event when not paused', () => {- hoisted.downloadStore.downloads = {- 'cloud-model': { name: 'cloud-model', progress: 0.3 },- }- render(<DownloadManagement />)- hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })- expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith(- 'cloud-model'- )- })it('does not show pause/resume for llamacpp direct downloads', () => {hoisted.downloadStore.downloads = {diff --git a/web-app/src/containers/__tests__/SetupScreen.test.tsx b/web-app/src/containers/__tests__/SetupScreen.test.tsxindex ffac5adfa..ab25f500b 100644--- a/web-app/src/containers/__tests__/SetupScreen.test.tsx+++ b/web-app/src/containers/__tests__/SetupScreen.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'import '@testing-library/jest-dom'// ---- Module mocks ----------------------------------------------------------@@ -19,7 +19,12 @@ const hoisted = vi.hoisted(() => ({setProviders: vi.fn(),},pullModelWithMetadataMock: vi.fn(),+ startEngineSetupMock: vi.fn().mockResolvedValue(undefined),+ verifyGpuOffloadMock: vi.fn(),+ verifyEmbeddingModelMock: vi.fn(),+ getHardwareInfoMock: vi.fn(),navigateMock: vi.fn(),+ productAnalyticPrompt: false,eventHandlers: {} as Record<string, any>,huggingfaceToken: 'hf-token',toastMock: {@@ -41,17 +46,22 @@ vi.mock('@/hooks/useDownloadStore', () => ({useDownloadStore: () => hoisted.downloadStore,}))-vi.mock('@/hooks/useServiceHub', () => ({- useServiceHub: () => ({+vi.mock('@/hooks/useServiceHub', () => {+ const stub = () => ({models: () => ({isModelSupported: vi.fn().mockResolvedValue('GREEN'),pullModelWithMetadata: hoisted.pullModelWithMetadataMock,+ startEngineSetup: hoisted.startEngineSetupMock,+ verifyGpuOffload: hoisted.verifyGpuOffloadMock,+ verifyEmbeddingModel: hoisted.verifyEmbeddingModelMock,}),providers: () => ({getProviders: vi.fn().mockResolvedValue([]),}),- }),-}))+ hardware: () => ({ getHardwareInfo: hoisted.getHardwareInfoMock }),+ })+ return { useServiceHub: stub, getServiceHub: stub }+})vi.mock('@/hooks/useLatestJanModel', () => ({useLatestJanModel: () => ({@@ -61,6 +71,14 @@ vi.mock('@/hooks/useLatestJanModel', () => ({}),}))+vi.mock('@/hooks/useAnalytic', () => ({+ useAnalytic: () => ({+ productAnalyticPrompt: hoisted.productAnalyticPrompt,+ setProductAnalytic: vi.fn(),+ setProductAnalyticPrompt: vi.fn(),+ }),+}))+vi.mock('@/hooks/useGeneralSetting', () => ({useGeneralSetting: (selector: any) =>selector({ huggingfaceToken: hoisted.huggingfaceToken }),@@ -78,6 +96,7 @@ vi.mock('@tanstack/react-router', () => ({vi.mock('@janhq/core', () => ({AppEvent: { onModelImported: 'onModelImported' },+ DownloadEvent: { onFileDownloadSuccess: 'onFileDownloadSuccess' },events: {on: vi.fn((name: string, handler: any) => {hoisted.eventHandlers[name] = handler@@ -96,7 +115,7 @@ vi.mock('@/constants/localStorage', () => ({}))vi.mock('@/constants/routes', () => ({- route: { home: '/' },+ route: { home: '/', hub: { index: '/hub/' } },}))vi.mock('@/constants/models', () => ({@@ -130,130 +149,627 @@ const sampleModel = {mmproj_models: [{ model_id: 'mmproj-f16', path: '/mmproj' }],}+// The readiness probes resolve after mount, so flush them before asserting to+// keep pending state updates out of the test.+const renderSetup = async () => {+ const utils = render(<SetupScreen />)+ await act(async () => {})+ return utils+}++/** Passes the welcome gate, which is where the flow now begins. */+const start = async () => {+ await act(async () => {+ fireEvent.click(screen.getByText('setup:startSetup'))+ })+}++const renderStarted = async () => {+ const utils = await renderSetup()+ await start()+ return utils+}++/** Advances past the llama.cpp setup page, which never auto-advances. */+const continueSetup = async () => {+ await act(async () => {+ fireEvent.click(+ screen.getByText(/setup:(continueStep|continueAnyway|skipStep)/)+ )+ })+}++const renderPastSetup = async () => {+ const utils = await renderStarted()+ await continueSetup()+ return utils+}++const currentPage = () =>+ screen.getByTestId('setup-wizard').getAttribute('data-page')+describe('SetupScreen', () => {beforeEach(() => {vi.clearAllMocks()- hoisted.janModel = null+ hoisted.janModel = sampleModelhoisted.metadataError = null+ hoisted.productAnalyticPrompt = falsehoisted.downloadStore.downloads = {}hoisted.downloadStore.localDownloadingModels = new Set()hoisted.providersMock.getProviderByName.mockReturnValue({ models: [] })hoisted.eventHandlers = {}+ // Healthy by default, so the wizard settles on the model page; individual+ // tests opt into a warning to hold an earlier page.+ hoisted.getHardwareInfoMock.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [{ name: 'RTX 4070', driver_version: '550.54' }],+ })+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 1,+ })+ hoisted.verifyEmbeddingModelMock.mockResolvedValue({+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ })localStorage.clear()})- it('renders welcome header when no download is active', () => {- render(<SetupScreen />)- expect(screen.getByText('Hey, welcome to Jan!')).toBeInTheDocument()- expect(screen.getByText('Download')).toBeInTheDocument()- })-- it('renders the header page component', () => {- render(<SetupScreen />)+ it('renders the header page component', async () => {+ await renderStarted()expect(screen.getByTestId('header-page')).toBeInTheDocument()})- it('calls fetchLatestJanModel on mount', () => {- render(<SetupScreen />)+ it('calls fetchLatestJanModel on mount', async () => {+ await renderStarted()expect(hoisted.fetchLatestJanModel).toHaveBeenCalledWith(true)})- it('shows the model display name once metadata is available', async () => {- hoisted.janModel = sampleModel- render(<SetupScreen />)- await waitFor(() => expect(screen.getByText(/Jan Model/)).toBeInTheDocument())+ it('runs the engine and embedding probes on mount', async () => {+ await renderStarted()+ expect(hoisted.verifyGpuOffloadMock).toHaveBeenCalled()+ expect(hoisted.verifyEmbeddingModelMock).toHaveBeenCalled()})- it('clicking download triggers pullModelWithMetadata once metadata is ready', async () => {- hoisted.janModel = sampleModel- render(<SetupScreen />)- fireEvent.click(screen.getByText('Download'))- await waitFor(() =>- expect(hoisted.downloadStore.addLocalDownloadingModel).toHaveBeenCalled()- )- await waitFor(() =>- expect(hoisted.pullModelWithMetadataMock).toHaveBeenCalled()- )+ it('routes all visible copy through i18n', async () => {+ await renderStarted()+ expect(screen.queryByText('Hey, welcome to Jan!')).not.toBeInTheDocument()+ expect(screen.queryByText('Recommended model')).not.toBeInTheDocument()+ expect(screen.queryByText('Download')).not.toBeInTheDocument()})- it('queues the download if metadata is not yet ready and user clicks Download', () => {- hoisted.janModel = null- render(<SetupScreen />)- const btn = screen.getByText('Download') as HTMLButtonElement- fireEvent.click(btn)- // No pull yet because metadata is null- expect(hoisted.pullModelWithMetadataMock).not.toHaveBeenCalled()+ describe('welcome gate', () => {+ it('opens on the welcome page', async () => {+ await renderSetup()++ expect(currentPage()).toBe('welcome')+ expect(screen.getByText('setup:welcomeTitle')).toBeInTheDocument()+ expect(screen.getByText('setup:startSetup')).toBeInTheDocument()+ })++ // The first page is an invitation, not a progress report: nothing is probed+ // until the user asks for it.+ it('probes nothing until the user starts', async () => {+ await renderSetup()++ expect(hoisted.verifyGpuOffloadMock).not.toHaveBeenCalled()+ expect(hoisted.verifyEmbeddingModelMock).not.toHaveBeenCalled()+ expect(hoisted.getHardwareInfoMock).not.toHaveBeenCalled()+ })++ it('begins the checks on start', async () => {+ await renderSetup()+ await start()++ expect(hoisted.verifyGpuOffloadMock).toHaveBeenCalled()+ expect(hoisted.verifyEmbeddingModelMock).toHaveBeenCalled()+ })++ // The engine's own provisioning is hundreds of megabytes. It used to run at+ // app launch regardless, which made asking pointless.+ it('does not provision the engine until the user starts', async () => {+ await renderSetup()++ expect(hoisted.startEngineSetupMock).not.toHaveBeenCalled()+ })++ it('provisions the engine on start', async () => {+ await renderSetup()+ await start()++ expect(hoisted.startEngineSetupMock).toHaveBeenCalledTimes(1)+ })++ it('does not offer the model download yet', async () => {+ await renderSetup()++ expect(screen.queryByTestId('setup-model-card')).not.toBeInTheDocument()+ expect(screen.queryByText('setup:download')).not.toBeInTheDocument()+ })})- it('shows downloading state when a matching download is active', () => {- hoisted.janModel = sampleModel- hoisted.downloadStore.downloads = {- 'jan-q4_k_m': {- name: 'jan-q4_k_m',- progress: 0.25,- current: 500_000_000,- total: 2_000_000_000,- },- }- render(<SetupScreen />)- expect(screen.getByText('Sit tight, Jan is getting ready...')).toBeInTheDocument()- expect(screen.getByText('Downloading')).toBeInTheDocument()+ describe('GPU badge', () => {+ const holdSetupPage = () =>+ hoisted.verifyEmbeddingModelMock.mockResolvedValue({+ status: 'ok',+ pending: true,+ })++ it('names the GPU when offload is confirmed', async () => {+ holdSetupPage()++ await renderStarted()++ expect(currentPage()).toBe('setup')+ expect(screen.getByTestId('setup-gpu-badge').textContent).toContain(+ 'setup:badgeGpu'+ )+ })++ // A GPU build that found no device runs on the CPU regardless of its name,+ // so the device count decides rather than the backend label.+ it('says CPU when a GPU build sees no device', async () => {+ holdSetupPage()+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'runtimeUnreachable',+ })++ await renderStarted()++ expect(screen.getByTestId('setup-gpu-badge').textContent).toContain(+ 'setup:badgeCpu'+ )+ })++ it('says CPU for a CPU-only build', async () => {+ holdSetupPage()+ hoisted.getHardwareInfoMock.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [],+ })+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ await renderStarted()++ expect(screen.getByTestId('setup-gpu-badge').textContent).toContain(+ 'setup:badgeCpu'+ )+ })++ // Neither answer is known until the engine has a backend.+ it('stays undecided while the engine is still setting up', async () => {+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ await renderStarted()++ expect(screen.getByTestId('setup-gpu-badge').textContent).toContain(+ 'setup:badgeGpuUnknown'+ )+ })})- it('shows error toast when queued download fails due to metadata error', async () => {- // First render with no model so quickstart gets queued- hoisted.janModel = null- const { rerender } = render(<SetupScreen />)- const btn = screen.getByText('Download') as HTMLButtonElement- fireEvent.click(btn)- // Now flip metadata error and rerender to trigger useEffect- hoisted.metadataError = new Error('fail')- rerender(<SetupScreen />)- await waitFor(() => expect(hoisted.toastMock.error).toHaveBeenCalled())+ describe('one page at a time', () => {+ it('shows only the current page', async () => {+ await renderPastSetup()++ expect(currentPage()).toBe('model')+ // Settled check pages are gone rather than stacked above this one.+ expect(screen.queryByText('setup:stageSetup')).not.toBeInTheDocument()+ expect(screen.queryByTestId('setup-gpu-badge')).not.toBeInTheDocument()+ })++ it('holds the setup page while the engine is still setting up', async () => {+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ await renderStarted()++ expect(currentPage()).toBe('setup')+ expect(screen.getByText('setup:checkEnginePreparing')).toBeInTheDocument()+ })++ it('holds the setup page while the embedding check is pending', async () => {+ hoisted.verifyEmbeddingModelMock.mockResolvedValue({+ status: 'ok',+ pending: true,+ })++ await renderStarted()++ expect(currentPage()).toBe('setup')+ })++ it('reports position within the flow', async () => {+ await renderStarted()+ expect(screen.getByTestId('setup-step-counter')).toBeInTheDocument()+ })++ // Auto-advancing skipped this page whenever the engine was already+ // installed, hiding the GPU badge.+ it('does not advance past the setup page on its own', async () => {+ await renderStarted()++ expect(currentPage()).toBe('setup')+ expect(screen.getByTestId('setup-gpu-badge')).toBeInTheDocument()+ })++ it('offers Continue once the setup work is done', async () => {+ await renderStarted()++ expect(screen.getByText('setup:continueStep')).toBeInTheDocument()+ })++ it('offers a skip while the setup work is still running', async () => {+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ await renderStarted()++ expect(screen.getByText('setup:skipStep')).toBeInTheDocument()+ })++ // An engine page can sit for the length of a backend download, so waiting+ // must never be the only option.+ it('lets the user skip a page that is still running', async () => {+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ await renderStarted()+ expect(currentPage()).toBe('setup')++ fireEvent.click(screen.getByText('setup:skipStep'))++ expect(currentPage()).toBe('model')+ })})- it('navigates home when onModelImported fires for the default variant', async () => {- hoisted.janModel = sampleModel- hoisted.providersMock.selectModelProvider.mockReturnValue({ id: 'jan-q4_k_m' })- render(<SetupScreen />)- // wait for registration- await waitFor(() => expect(hoisted.eventHandlers['onModelImported']).toBeDefined())- await hoisted.eventHandlers['onModelImported']({ modelId: 'jan-q4_k_m' })- await waitFor(() => expect(hoisted.navigateMock).toHaveBeenCalled())- expect(localStorage.getItem('sc')).toBe('true')+ describe('warnings', () => {+ const armEngineWarning = () =>+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'runtimeUnreachable',+ error: 'device probe exploded',+ })++ it('holds the page that warned', async () => {+ armEngineWarning()++ await renderStarted()++ expect(currentPage()).toBe('setup')+ expect(+ screen.getByText('setup:checkEngineRuntimeUnreachable')+ ).toBeInTheDocument()+ expect(screen.getByTestId('setup-page-warning')).toBeInTheDocument()+ })++ it('advances past it on Continue', async () => {+ armEngineWarning()++ await renderStarted()+ fireEvent.click(screen.getByText('setup:continueAnyway'))++ expect(currentPage()).toBe('model')+ })++ it('offers a re-run of the checks', async () => {+ armEngineWarning()++ await renderStarted()+ await act(async () => {+ fireEvent.click(screen.getByText('setup:retryChecks'))+ })++ expect(hoisted.verifyGpuOffloadMock).toHaveBeenCalledTimes(2)+ })++ it('exposes the raw failure detail behind a disclosure', async () => {+ armEngineWarning()++ await renderStarted()+ expect(screen.queryByText(/device probe exploded/)).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('setup:showDetails'))++ expect(screen.getByText(/device probe exploded/)).toBeInTheDocument()+ })++ it('shows dependency install advice inline instead of as a dialog', async () => {+ hoisted.verifyGpuOffloadMock.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'missingLibrary',+ missingLibraries: ['libnccl.so.2'],+ })++ await renderStarted()++ expect(screen.getByTestId('dependency-advice')).toBeInTheDocument()+ })++ it('shows no advice when no libraries are named', async () => {+ armEngineWarning()++ await renderStarted()++ expect(screen.queryByTestId('dependency-advice')).not.toBeInTheDocument()+ })})- it('ignores onModelImported for unrelated model ids', async () => {- hoisted.janModel = sampleModel- render(<SetupScreen />)- await waitFor(() => expect(hoisted.eventHandlers['onModelImported']).toBeDefined())- await hoisted.eventHandlers['onModelImported']({ modelId: 'some-other' })- expect(hoisted.navigateMock).not.toHaveBeenCalled()+ describe('consent page', () => {+ it('asks for consent as its own page when pending', async () => {+ hoisted.productAnalyticPrompt = true++ await renderPastSetup()++ expect(currentPage()).toBe('consent')+ expect(screen.getByTestId('analytic-consent')).toBeInTheDocument()+ })++ it('is skipped once consent has been answered', async () => {+ hoisted.productAnalyticPrompt = false++ await renderPastSetup()++ expect(currentPage()).toBe('model')+ expect(screen.queryByTestId('analytic-consent')).not.toBeInTheDocument()+ })++ // The model download is always last.+ it('precedes the model page', async () => {+ hoisted.productAnalyticPrompt = true++ await renderPastSetup()++ expect(currentPage()).not.toBe('model')+ expect(screen.queryByTestId('setup-model-card')).not.toBeInTheDocument()+ })})- it('does not auto-start download when model is already present in provider', async () => {- hoisted.janModel = sampleModel- hoisted.providersMock.getProviderByName.mockReturnValue({- models: [{ id: 'jan-q4_k_m' }],+ describe('model page', () => {+ it('offers exactly one model card', async () => {+ await renderPastSetup()+ expect(screen.getAllByTestId('setup-model-card')).toHaveLength(1)+ })++ it('renders the card before the metadata lands', async () => {+ hoisted.janModel = null++ await renderPastSetup()++ expect(screen.getByTestId('setup-model-card')).toBeInTheDocument()+ })++ // The action belongs with the model it acts on.+ it('puts the download action on the card', async () => {+ await renderPastSetup()++ expect(screen.getByTestId('setup-model-card')).toContainElement(+ screen.getByText('setup:download')+ )+ })++ it('downloads from the card action', async () => {+ await renderPastSetup()+ fireEvent.click(screen.getByText('setup:download'))++ await waitFor(() =>+ expect(hoisted.pullModelWithMetadataMock).toHaveBeenCalledWith(+ 'jan-q4_k_m',+ '/models/q4',+ '/mmproj',+ 'hf-token',+ true+ )+ )+ })++ // Matches the Hub: the button gives way to a progress bar rather than+ // sitting there looking pressable.+ it('replaces the action with progress while downloading', async () => {+ hoisted.downloadStore.downloads = {+ 'jan-q4_k_m': {+ name: 'jan-q4_k_m',+ progress: 0.25,+ current: 500_000_000,+ total: 2_000_000_000,+ },+ }++ await renderPastSetup()++ expect(screen.queryByText('setup:download')).not.toBeInTheDocument()+ expect(screen.getByText('25%')).toBeInTheDocument()+ })++ it('opens the Hub for further exploration', async () => {+ await renderPastSetup()+ fireEvent.click(screen.getByText('setup:exploreHub'))++ expect(hoisted.navigateMock).toHaveBeenCalledWith({ to: '/hub/' })+ })++ it('queues the download until the metadata lands, keeping the HF token', async () => {+ hoisted.janModel = null+ const { rerender } = await renderPastSetup()++ fireEvent.click(screen.getByText('setup:download'))+ expect(hoisted.pullModelWithMetadataMock).not.toHaveBeenCalled()++ hoisted.janModel = sampleModel+ await act(async () => {+ rerender(<SetupScreen />)+ })++ await waitFor(() =>+ expect(hoisted.pullModelWithMetadataMock).toHaveBeenCalledWith(+ 'jan-q4_k_m',+ '/models/q4',+ '/mmproj',+ 'hf-token',+ true+ )+ )+ })++ it('shows an error toast when the queued download loses its metadata', async () => {+ hoisted.janModel = null+ const { rerender } = await renderPastSetup()+ fireEvent.click(screen.getByText('setup:download'))++ hoisted.metadataError = new Error('fail')+ await act(async () => {+ rerender(<SetupScreen />)+ })++ expect(hoisted.toastMock.error).toHaveBeenCalled()+ })++ it('does not start a download on its own', async () => {+ await renderPastSetup()+ expect(hoisted.pullModelWithMetadataMock).not.toHaveBeenCalled()})- render(<SetupScreen />)- // Give useEffect chance to run- await new Promise((r) => setTimeout(r, 20))- expect(hoisted.pullModelWithMetadataMock).not.toHaveBeenCalled()})- it('Download button is disabled while downloading', () => {- hoisted.janModel = sampleModel- hoisted.downloadStore.downloads = {- 'jan-q4_k_m': {- name: 'jan-q4_k_m',- progress: 0.1,- current: 10,- total: 100,- },- }- render(<SetupScreen />)- const btn = screen.getByText('Downloading').closest('button') as HTMLButtonElement- expect(btn.disabled).toBe(true)+ // Answering consent used to remove its page from the flow, renumbering the+ // remaining steps under the user.+ describe('step numbering', () => {+ it('keeps the total fixed after consent is answered', async () => {+ hoisted.productAnalyticPrompt = true+ const { rerender } = await renderStarted()+ await continueSetup()+ expect(currentPage()).toBe('consent')+ const before = screen.getByTestId('setup-step-counter').textContent++ hoisted.productAnalyticPrompt = false+ await act(async () => {+ rerender(<SetupScreen />)+ })++ expect(currentPage()).toBe('model')+ expect(screen.getByTestId('setup-step-counter').textContent).toBe(before)+ })++ it('counts four pages when consent is pending', async () => {+ hoisted.productAnalyticPrompt = true++ await renderSetup()++ expect(+ screen.getByTestId('setup-wizard').querySelectorAll('span.h-1').length+ ).toBe(4)+ })++ it('counts three pages when consent is already answered', async () => {+ hoisted.productAnalyticPrompt = false++ await renderSetup()++ expect(+ screen.getByTestId('setup-wizard').querySelectorAll('span.h-1').length+ ).toBe(3)+ })+ })++ describe('leaving setup', () => {+ it('completes once the model is imported', async () => {+ hoisted.providersMock.selectModelProvider.mockReturnValue({+ id: 'jan-q4_k_m',+ })++ await renderPastSetup()+ await act(async () => {+ await hoisted.eventHandlers['onModelImported']({+ modelId: 'jan-q4_k_m',+ })+ })++ await waitFor(() => expect(hoisted.navigateMock).toHaveBeenCalled())+ expect(localStorage.getItem('sc')).toBe('true')+ })++ it('ignores an import of an unrelated model', async () => {+ await renderPastSetup()+ await act(async () => {+ await hoisted.eventHandlers['onModelImported']({+ modelId: 'some-other',+ })+ })++ expect(hoisted.navigateMock).not.toHaveBeenCalled()+ })++ // A model already on disk leaves no import event to wait for.+ it('completes without an import event when the model is already installed', async () => {+ hoisted.providersMock.getProviderByName.mockReturnValue({+ models: [{ id: 'jan-q4_k_m' }],+ })++ await renderPastSetup()++ await waitFor(() => expect(hoisted.navigateMock).toHaveBeenCalled())+ expect(hoisted.pullModelWithMetadataMock).not.toHaveBeenCalled()+ })++ // A warning was its own page and was passed deliberately, so it must not+ // also block the exit.+ it('completes after an acknowledged warning', async () => {+ hoisted.verifyEmbeddingModelMock.mockResolvedValue({+ status: 'warning',+ modelId: 'sentence-transformer-mini',+ problem: 'empty',+ })++ await renderStarted()+ expect(currentPage()).toBe('setup')+ await continueSetup()+ expect(currentPage()).toBe('model')++ await act(async () => {+ await hoisted.eventHandlers['onModelImported']({+ modelId: 'jan-q4_k_m',+ })+ })++ await waitFor(() => expect(hoisted.navigateMock).toHaveBeenCalled())+ })})})diff --git a/web-app/src/containers/analytics/AnalyticConsent.tsx b/web-app/src/containers/analytics/AnalyticConsent.tsxnew file mode 100644index 000000000..838431d2b--- /dev/null+++ b/web-app/src/containers/analytics/AnalyticConsent.tsx@@ -0,0 +1,45 @@+import { Button } from '@/components/ui/button'+import { useAnalytic } from '@/hooks/useAnalytic'+import posthog from 'posthog-js'+import { useTranslation } from '@/i18n/react-i18next-compat'++/**+ * The analytics consent question with neither a heading nor positioning of its+ * own, so it can be a step on the setup wizard (which supplies its own heading)+ * as well as a floating prompt for users who upgraded past onboarding.+ */+export function AnalyticConsent() {+ const { t } = useTranslation()+ const { setProductAnalyticPrompt, setProductAnalytic } = useAnalytic()++ const handleProductAnalytics = (isAllowed: boolean) => {+ if (isAllowed) {+ posthog.opt_in_capturing()+ } else {+ posthog.opt_out_capturing()+ }+ setProductAnalytic(isAllowed)+ setProductAnalyticPrompt(false)+ }++ return (+ <div data-testid="analytic-consent">+ <p className="text-xs text-muted-foreground leading-normal">+ {t('analyticsConsentDetail')}+ </p>+ <p className="mt-2 text-sm">{t('analyticsConsentQuestion')}</p>+ <div className="mt-4 flex justify-end space-x-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleProductAnalytics(false)}+ >+ {t('deny')}+ </Button>+ <Button size="sm" onClick={() => handleProductAnalytics(true)}>+ {t('allow')}+ </Button>+ </div>+ </div>+ )+}diff --git a/web-app/src/containers/analytics/PromptAnalytic.tsx b/web-app/src/containers/analytics/PromptAnalytic.tsxindex a5bdac6b3..f5303f32c 100644--- a/web-app/src/containers/analytics/PromptAnalytic.tsx+++ b/web-app/src/containers/analytics/PromptAnalytic.tsx@@ -1,57 +1,22 @@-import { Button } from '@/components/ui/button'-import { useAnalytic } from '@/hooks/useAnalytic'import { IconFileTextShield } from '@tabler/icons-react'-import posthog from 'posthog-js'import { useTranslation } from '@/i18n/react-i18next-compat'+import { AnalyticConsent } from './AnalyticConsent'+/**+ * Floating placement of the consent question, for users who are already past+ * onboarding. During first-run setup the wizard hosts the same question inline+ * under its own page heading.+ */export function PromptAnalytic() {const { t } = useTranslation()- const { setProductAnalyticPrompt, setProductAnalytic } = useAnalytic()-- const handleProductAnalytics = (isAllowed: boolean) => {- if (isAllowed) {- posthog.opt_in_capturing()- setProductAnalytic(true)- setProductAnalyticPrompt(false)- } else {- posthog.opt_out_capturing()- setProductAnalytic(false)- setProductAnalyticPrompt(false)- }- }return (<div className="fixed bottom-4 right-4 z-50 p-4 shadow-lg bg-background w-4/5 md:w-100 border rounded-lg">- <div className="flex items-center gap-2">+ <div className="mb-2 flex items-center gap-2"><IconFileTextShield className="text-muted-foreground" />- <h2 className="font-medium">- {t('helpUsImproveJan')}- </h2>- </div>- <p className="mt-2 text-xs text-muted-foreground leading-normal">- We collect anonymous data to understand feature usage. Your chats and- personal information are never tracked. You can change this anytime- in - <span className="font-medium text-muted-foreground">{`Settings > Privacy.`}</span>- </p>- <p className="mt-2 text-sm">- Would you like to help us to improve Jan?- </p>- <div className="mt-4 flex justify-end space-x-2">- <Button- variant="ghost"- size="sm"- onClick={() => handleProductAnalytics(false)}- >- {t('deny')}- </Button>- <Button- size="sm"- onClick={() => handleProductAnalytics(true)}- >- {t('allow')}- </Button>+ <h2 className="font-medium">{t('helpUsImproveJan')}</h2></div>+ <AnalyticConsent /></div>)}diff --git a/web-app/src/containers/dialogs/DependencyAdvice.tsx b/web-app/src/containers/dialogs/DependencyAdvice.tsxnew file mode 100644index 000000000..ddf9b6606--- /dev/null+++ b/web-app/src/containers/dialogs/DependencyAdvice.tsx@@ -0,0 +1,130 @@+import { ChevronDown, ChevronUp, ExternalLink } from 'lucide-react'+import { useState } from 'react'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { getInstallRecommendations } from '@/lib/backendDependencies'++/**+ * Turns missing library names into install advice. Shared by the standalone+ * dialog and the first-run wizard, which reports the same failure inline rather+ * than stacking a modal on top of itself.+ */+export function DependencyAdvice({+ backend,+ missingLibraries,+}: {+ backend: string+ missingLibraries: string[]+}) {+ const { t } = useTranslation()+ const [showRawLibs, setShowRawLibs] = useState(false)+ const { recommendations, uncovered } = getInstallRecommendations(+ missingLibraries,+ backend+ )++ return (+ <div className="space-y-3" data-testid="dependency-advice">+ {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 the 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">+ {missingLibraries.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>+ )}++ {recommendations.length > 0 && missingLibraries.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: missingLibraries.length,+ })}+ </button>+ {showRawLibs && (+ <ul className="mt-2 max-h-[120px] overflow-y-auto space-y-1">+ {missingLibraries.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>+ )+}diff --git a/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsxindex facfb80cd..95f6b75c0 100644--- a/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx+++ b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx@@ -7,10 +7,13 @@ import {DialogTitle,} from '@/components/ui/dialog'import { Button } from '@/components/ui/button'-import { AlertTriangle, ChevronDown, ChevronUp, ExternalLink } from 'lucide-react'+import { AlertTriangle } from 'lucide-react'import { useTranslation } from '@/i18n/react-i18next-compat'import { events, AppEvent } from '@janhq/core'import { useEffect, useState } from 'react'+import { useIsOnboarding } from '@/hooks/useIsOnboarding'+import { DependencyAdvice } from './DependencyAdvice'+import { getBackendDisplayName } from '@/lib/backendDependencies'type VerificationFailedPayload = {backend: string@@ -18,165 +21,17 @@ type VerificationFailedPayload = {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)+ // During first-run setup the same missing libraries are already reported on+ // the setup checklist's engine row, with the install advice inline. A modal on+ // top of the wizard would be the same finding twice.+ const isOnboarding = useIsOnboarding()useEffect(() => {const handler = (data: VerificationFailedPayload) => {setPayload(data)- setShowRawLibs(false)}events.on(AppEvent.onBackendVerificationFailed, handler)return () => {@@ -185,14 +40,11 @@ export default function MissingDependenciesDialog() {}, [])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}+ open={!!payload && !isOnboarding}onOpenChange={(open) => !open && setPayload(undefined)}><DialogContent showCloseButton={false}>@@ -214,110 +66,10 @@ export default function MissingDependenciesDialog() {</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>+ <DependencyAdvice+ backend={payload?.backend ?? ''}+ missingLibraries={allRawLibs}+ /><DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end"><Buttondiff --git a/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx b/web-app/src/hooks/__tests__/useDownloadEvents.test.tsxnew file mode 100644index 000000000..6d5768f04--- /dev/null+++ b/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx@@ -0,0 +1,214 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render } from '@testing-library/react'++const hoisted = vi.hoisted(() => ({+ downloadStore: {+ downloads: {} as Record<string, any>,+ updateProgress: vi.fn(),+ removeDownload: vi.fn(),+ removeLocalDownloadingModel: vi.fn(),+ },+ navigateMock: vi.fn(),+ toastMock: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ },+ eventHandlers: {} as Record<string, any>,+ offCalls: [] as string[],+}))++vi.mock('sonner', () => ({ toast: hoisted.toastMock }))++vi.mock('@/hooks/useDownloadStore', () => {+ const useDownloadStore: any = () => hoisted.downloadStore+ useDownloadStore.getState = () => hoisted.downloadStore+ return { useDownloadStore }+})++vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}))++vi.mock('@tanstack/react-router', () => ({+ useNavigate: () => hoisted.navigateMock,+}))++vi.mock('@/constants/routes', () => ({+ route: { settings: { general: '/settings/general' } },+}))++vi.mock('@janhq/core', () => ({+ DownloadEvent: {+ onFileDownloadUpdate: 'fdu',+ onFileDownloadError: 'fde',+ onFileDownloadSuccess: 'fds',+ onFileDownloadStopped: 'fdx',+ onModelValidationStarted: 'mvs',+ onModelValidationFailed: 'mvf',+ onFileDownloadAndVerificationSuccess: 'fdvs',+ },+ events: {+ on: vi.fn((name: string, handler: any) => {+ hoisted.eventHandlers[name] = handler+ }),+ off: vi.fn((name: string) => {+ hoisted.offCalls.push(name)+ }),+ },+}))++import { useDownloadEvents } from '../useDownloadEvents'++function Harness() {+ useDownloadEvents()+ return null+}++const mount = () => render(<Harness />)++describe('useDownloadEvents', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ hoisted.downloadStore.downloads = {}+ hoisted.eventHandlers = {}+ hoisted.offCalls = []+ })++ it('subscribes to every download event', () => {+ mount()+ for (const name of ['fdu', 'fde', 'fds', 'fdx', 'mvs', 'mvf', 'fdvs']) {+ expect(hoisted.eventHandlers[name], name).toBeDefined()+ }+ })++ it('unsubscribes on unmount', () => {+ mount().unmount()+ expect(hoisted.offCalls).toEqual(+ expect.arrayContaining(['fdu', 'fde', 'fds', 'fdx', 'mvs', 'mvf', 'fdvs'])+ )+ })++ // This is the bridge that makes progress visible anywhere in the app.+ it('feeds progress into the store keyed by model id', () => {+ mount()+ hoisted.eventHandlers['fdu']({+ modelId: 'jan-q4',+ percent: 0.5,+ size: { transferred: 100, total: 200 },+ })+ expect(hoisted.downloadStore.updateProgress).toHaveBeenCalledWith(+ 'jan-q4',+ 0.5,+ 'jan-q4',+ 100,+ 200+ )+ })++ it('tolerates a progress event with no size', () => {+ mount()+ hoisted.eventHandlers['fdu']({ modelId: 'jan-q4', percent: 0 })+ expect(hoisted.downloadStore.updateProgress).toHaveBeenCalledWith(+ 'jan-q4',+ 0,+ 'jan-q4',+ undefined,+ undefined+ )+ })++ it('handles HTTP 401 with a settings action', () => {+ mount()+ hoisted.eventHandlers['fde']({ modelId: 'x', error: 'HTTP status 401' })+ expect(hoisted.toastMock.error).toHaveBeenCalledWith(+ 'common:toast.downloadTokenRequired.title',+ expect.any(Object)+ )+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('x')+ })++ it('handles HTTP 403', () => {+ mount()+ hoisted.eventHandlers['fde']({ modelId: 'y', error: 'HTTP status 403' })+ expect(hoisted.toastMock.error).toHaveBeenCalledWith(+ 'common:toast.downloadLicenseRequired.title',+ expect.any(Object)+ )+ })++ it('handles HTTP 429', () => {+ mount()+ hoisted.eventHandlers['fde']({ modelId: 'z', error: 'HTTP status 429' })+ expect(hoisted.toastMock.error).toHaveBeenCalledWith(+ 'common:toast.downloadRateLimited.title',+ expect.any(Object)+ )+ })++ it('falls back to the generic failure toast', () => {+ mount()+ hoisted.eventHandlers['fde']({ modelId: 'w', error: 'other' })+ expect(hoisted.toastMock.error).toHaveBeenCalledWith(+ 'common:toast.downloadFailed.title',+ expect.any(Object)+ )+ })++ it('clears the download on success', () => {+ mount()+ hoisted.eventHandlers['fds']({ modelId: 'ok' })+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('ok')+ expect(+ hoisted.downloadStore.removeLocalDownloadingModel+ ).toHaveBeenCalledWith('ok')+ expect(hoisted.toastMock.success).toHaveBeenCalled()+ })++ it('clears the download on verified success', () => {+ mount()+ hoisted.eventHandlers['fdvs']({ modelId: 'ok' })+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('ok')+ expect(hoisted.toastMock.success).toHaveBeenCalled()+ })++ it('reports validation starting', () => {+ mount()+ hoisted.eventHandlers['mvs']({ modelId: 'v' })+ expect(hoisted.toastMock.info).toHaveBeenCalled()+ })++ it('clears the download when validation fails', () => {+ mount()+ hoisted.eventHandlers['mvf']({ modelId: 'v' })+ expect(hoisted.toastMock.dismiss).toHaveBeenCalledWith(+ 'model-validation-started-v'+ )+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith('v')+ expect(hoisted.toastMock.error).toHaveBeenCalled()+ })++ // A pause cancels the transfer through the same path, so the partial entry+ // has to survive for resume to have anything to resume.+ it('keeps a paused entry on a stopped event', () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': { name: 'cloud-model', progress: 0.3, paused: true },+ }+ mount()+ hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })+ expect(hoisted.downloadStore.removeDownload).not.toHaveBeenCalled()+ })++ it('removes an unpaused entry on a stopped event', () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': { name: 'cloud-model', progress: 0.3 },+ }+ mount()+ hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith(+ 'cloud-model'+ )+ })+})diff --git a/web-app/src/hooks/__tests__/useSetupChecklist.test.ts b/web-app/src/hooks/__tests__/useSetupChecklist.test.tsnew file mode 100644index 000000000..92300797b--- /dev/null+++ b/web-app/src/hooks/__tests__/useSetupChecklist.test.ts@@ -0,0 +1,756 @@+import { renderHook, waitFor, act } from '@testing-library/react'+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { useSetupChecklist } from '../useSetupChecklist'++const mockGetHardwareInfo = vi.fn()+const mockVerifyGpuOffload = vi.fn()+const mockVerifyEmbeddingModel = vi.fn()++const eventHandlers: Record<string, ((payload?: unknown) => void)[]> = {}+const emit = async (name: string, payload?: unknown) => {+ await act(async () => {+ ;(eventHandlers[name] ?? []).forEach((handler) => handler(payload))+ })+}++vi.mock('@janhq/core', () => ({+ AppEvent: { onModelImported: 'onModelImported' },+ DownloadEvent: { onFileDownloadSuccess: 'onFileDownloadSuccess' },+ events: {+ on: (name: string, handler: (payload?: unknown) => void) => {+ ;(eventHandlers[name] ??= []).push(handler)+ },+ off: (name: string, handler: (payload?: unknown) => void) => {+ eventHandlers[name] = (eventHandlers[name] ?? []).filter(+ (h) => h !== handler+ )+ },+ },+}))++vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({+ hardware: () => ({ getHardwareInfo: mockGetHardwareInfo }),+ models: () => ({+ verifyGpuOffload: mockVerifyGpuOffload,+ verifyEmbeddingModel: mockVerifyEmbeddingModel,+ }),+ }),+}))++const armHealthy = () => {+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [{ name: 'NVIDIA RTX 4070', driver_version: '550.54' }],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 1,+ })+ mockVerifyEmbeddingModel.mockResolvedValue({+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ })+}++const stageById = (+ stages: ReturnType<typeof useSetupChecklist>['stages'],+ id: string+) => stages.find((s) => s.id === id)!++describe('useSetupChecklist', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ for (const key of Object.keys(eventHandlers)) delete eventHandlers[key]+ })++ it('reports every stage ok on a healthy machine', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.stages.map((s) => s.status)).toEqual([+ 'ok',+ 'ok',+ 'ok',+ ])+ expect(result.current.warnings).toHaveLength(0)+ })++ it('exposes the three stages in a stable order', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.stages.map((s) => s.id)).toEqual([+ 'system',+ 'engine',+ 'search',+ ])+ })++ it('describes detected GPU hardware', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const system = stageById(result.current.stages, 'system')+ expect(system.messageKey).toBe('checkSystemGpu')+ expect(system.values).toMatchObject({+ gpus: 'NVIDIA RTX 4070',+ driver: '550.54',+ })+ })++ // On a hybrid laptop the integrated GPU usually sorts first, so listing only+ // the first entry reads as "no discrete GPU found".+ it('lists every detected GPU, not just the first', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Core i9-13900H' },+ gpus: [+ { name: 'Intel Iris Xe Graphics', vendor: 'Intel', total_memory: 2048 },+ {+ name: 'NVIDIA RTX 4070',+ vendor: 'NVIDIA',+ total_memory: 8192,+ driver_version: '550.54',+ },+ ],+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const system = stageById(result.current.stages, 'system')+ expect(system.values?.gpus).toBe(+ 'Intel Iris Xe Graphics (2 GB), NVIDIA RTX 4070 (8 GB)'+ )+ expect(system.status).toBe('ok')+ })++ it('omits the driver clause when no GPU reports one', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [{ name: 'AMD Radeon RX 7900 XTX', vendor: 'AMD' }],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-vulkan-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 1,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'system').messageKey).toBe(+ 'checkSystemGpuNoDriver'+ )+ })++ // The engine reports a healthy "running on CPU" here; only the cross-check+ // against detected hardware can tell that the GPU is being wasted.+ it('warns when a GPU is present but a CPU-only backend is installed', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('warning')+ expect(engine.messageKey).toBe('checkEngineGpuUnused')+ expect(engine.values).toMatchObject({+ backend: 'linux-common_cpus-x64',+ gpus: 'NVIDIA RTX 4070',+ })+ })++ it('stays ok for a CPU backend on a machine with no GPU', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('ok')+ expect(engine.messageKey).toBe('checkEngineCpu')+ })++ it('warns when the installed GPU build is for the wrong vendor', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [+ {+ name: 'AMD Radeon RX 7900 XTX',+ vendor: 'AMD',+ total_memory: 24576,+ driver_version: '24.1',+ },+ ],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 1,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('warning')+ expect(engine.messageKey).toBe('checkEngineVendorMismatch')+ expect(engine.values).toMatchObject({+ vendor: 'NVIDIA',+ gpus: 'AMD Radeon RX 7900 XTX (24 GB)',+ })+ })++ // Hardware detection failing must not turn a working engine into a warning.+ it('trusts the engine when hardware detection reports nothing', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue(null)++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'engine').status).toBe('ok')+ })++ it('describes a CPU-only machine without claiming a GPU', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [],+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const system = stageById(result.current.stages, 'system')+ expect(system.messageKey).toBe('checkSystemCpuOnly')+ expect(system.status).toBe('ok')+ })++ // The silent CPU-fallback case must reach the user as a warning.+ it('surfaces a GPU backend that cannot reach its GPU', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'runtimeUnreachable',+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('warning')+ expect(engine.messageKey).toBe('checkEngineRuntimeUnreachable')+ expect(result.current.warnings).toHaveLength(1)+ })++ it('distinguishes a machine with no GPU from an unreachable one', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'noGpuHardware',+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'engine').messageKey).toBe(+ 'checkEngineNoGpuHardware'+ )+ })++ // The cause is established, so the message names the dependency rather than+ // guessing at the driver.+ it('reports a named missing library instead of a generic GPU warning', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'missingLibrary',+ missingLibraries: ['libnccl.so.2', 'libcublas.so.12'],+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('warning')+ expect(engine.messageKey).toBe('checkEngineMissingLibrary')+ expect(engine.values).toMatchObject({+ backend: 'linux-cuda-12-common_cpus-x64',+ libraries: 'libnccl.so.2, libcublas.so.12',+ })+ })++ it('maps each embedding vector problem to its own message', async () => {+ const cases = {+ missing: 'checkSearchNoVector',+ empty: 'checkSearchNoVector',+ nonFinite: 'checkSearchInvalidVector',+ degenerate: 'checkSearchInvalidVector',+ } as const++ for (const [problem, expected] of Object.entries(cases)) {+ armHealthy()+ mockVerifyEmbeddingModel.mockResolvedValue({+ status: 'warning',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ problem,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'search').messageKey, problem).toBe(+ expected+ )+ }+ })++ it('reports the embedding model and dimension when healthy', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'search').values).toMatchObject({+ model: 'sentence-transformer-mini',+ dimension: 384,+ })+ })++ // One failing probe must not hide the verdicts of the others.+ it('keeps other stages meaningful when one check rejects', async () => {+ armHealthy()+ mockVerifyEmbeddingModel.mockRejectedValue(new Error('router down'))++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'system').status).toBe('ok')+ expect(stageById(result.current.stages, 'engine').status).toBe('ok')+ const search = stageById(result.current.stages, 'search')+ expect(search.status).toBe('warning')+ expect(search.detail).toContain('router down')+ })++ it('warns when hardware detection fails', async () => {+ armHealthy()+ mockGetHardwareInfo.mockRejectedValue(new Error('plugin missing'))++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const system = stageById(result.current.stages, 'system')+ expect(system.status).toBe('warning')+ expect(system.messageKey).toBe('checkSystemFailed')+ })++ it('reports an engine build that cannot run the check', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ unavailable: true,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'engine').messageKey).toBe(+ 'checkEngineUnavailable'+ )+ })++ it('does not run the probes when disabled', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist({ enabled: false }))++ expect(result.current.stages.every((s) => s.status === 'pending')).toBe(true)+ expect(mockVerifyEmbeddingModel).not.toHaveBeenCalled()+ expect(mockGetHardwareInfo).not.toHaveBeenCalled()+ })++ it('runs each probe once for a single mount', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1)+ expect(mockVerifyEmbeddingModel).toHaveBeenCalledTimes(1)+ })++ // A fresh install downloads a backend before it has one, so the engine row+ // must not accuse a not-yet-chosen backend of being CPU-only.+ it('shows the engine as still preparing while no backend is selected', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('running')+ expect(engine.messageKey).toBe('checkEnginePreparing')+ expect(result.current.warnings).toHaveLength(0)+ })++ // The engine reports this itself while it downloads a backend; the search+ // check cannot run before the router it depends on exists.+ it('shows both engine and search as pending while the engine sets itself up', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })+ mockVerifyEmbeddingModel.mockResolvedValue({ status: 'ok', pending: true })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'engine').status).toBe('running')+ expect(stageById(result.current.stages, 'engine').messageKey).toBe(+ 'checkEnginePreparing'+ )+ expect(stageById(result.current.stages, 'search').status).toBe('running')+ expect(stageById(result.current.stages, 'search').messageKey).toBe(+ 'checkSearchPreparing'+ )+ expect(result.current.warnings).toHaveLength(0)+ })++ // `unavailable` means the build cannot ever run the check, so it outranks a+ // transient pending state.+ it('prefers an unavailable verdict over a pending one', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ unavailable: true,+ pending: true,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(stageById(result.current.stages, 'engine').messageKey).toBe(+ 'checkEngineUnavailable'+ )+ })++ describe('following the engine background setup', () => {+ it('re-checks when the engine picks a backend', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('settingsChanged', { key: 'llamacpp_backend' })++ await waitFor(() =>+ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(2)+ )+ })++ it('ignores unrelated setting changes', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('settingsChanged', { key: 'some_other_setting' })+ await emit('settingsChanged', undefined)++ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1)+ })++ it('re-checks when the engine binary finishes downloading', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('onFileDownloadSuccess', { downloadType: 'Engine' })++ await waitFor(() =>+ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(2)+ )+ })++ it('ignores a model download finishing', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('onFileDownloadSuccess', { downloadType: 'Model' })++ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1)+ })++ it('re-checks when the embedding model is imported', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('onModelImported', { embedding: true })++ await waitFor(() =>+ expect(mockVerifyEmbeddingModel).toHaveBeenCalledTimes(2)+ )+ })++ it('ignores a chat model being imported', async () => {+ armHealthy()+ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await emit('onModelImported', { modelId: 'jan-v3', embedding: false })++ expect(mockVerifyEmbeddingModel).toHaveBeenCalledTimes(1)+ })++ it('stops listening once unmounted', async () => {+ armHealthy()+ const { result, unmount } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ unmount()+ await emit('onFileDownloadSuccess', { downloadType: 'Engine' })++ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1)+ })++ // Dropping it would strand the checklist on the verdict of the run that was+ // already in flight when the newer state landed.+ it('queues a request that arrives mid-run instead of dropping it', async () => {+ armHealthy()+ let release: (() => void) | undefined+ mockVerifyGpuOffload.mockImplementation(+ () =>+ new Promise((resolve) => {+ release = () =>+ resolve({+ status: 'ok',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 1,+ })+ })+ )++ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1))++ await emit('onFileDownloadSuccess', { downloadType: 'Engine' })+ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(1)++ await act(async () => {+ release?.()+ })++ await waitFor(() => expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(2))+ await act(async () => {+ release?.()+ })+ await waitFor(() => expect(result.current.isRunning).toBe(false))+ })+ })++ describe('gpu verdict', () => {+ it('confirms GPU use and names the hardware', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu).toEqual({+ willUse: true,+ label: 'NVIDIA RTX 4070',+ })+ })++ // A GPU build that found no device runs on the CPU regardless of its name.+ it('reports CPU when a GPU build sees no device', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: 'linux-cuda-12-common_cpus-x64',+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'runtimeUnreachable',+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBe(false)+ // The hardware is still named, so the badge can say what is going unused.+ expect(result.current.gpu.label).toBe('NVIDIA RTX 4070')+ })++ it('reports CPU for a CPU-only build', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Ryzen 7 5800X' },+ gpus: [],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu).toEqual({ willUse: false, label: '' })+ })++ // Neither answer is known until the engine has a backend.+ it('stays undecided while the engine is still setting up', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBeUndefined()+ expect(result.current.gpu.label).toBe('NVIDIA RTX 4070')+ })++ // Metal is implicit on Apple Silicon: the engine never calls a macOS build a+ // GPU build and never enumerates Metal as a device. Reading those absences+ // literally told Apple Silicon users they were on CPU.+ it('reports GPU use for a macOS build despite no device count', async () => {+ armHealthy()+ mockGetHardwareInfo.mockResolvedValue({+ cpu: { name: 'Apple M3 Max' },+ gpus: [],+ })+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: 'macos-arm64',+ gpuExpected: false,+ engineDeviceCount: 0,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBe(true)+ })++ it('still defers to pending on macOS before a backend is chosen', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBeUndefined()+ })++ it('stays undecided when the engine cannot report at all', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockResolvedValue({+ status: 'warning',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ unavailable: true,+ })++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBeUndefined()+ })++ it('stays undecided when the probe rejects', async () => {+ armHealthy()+ mockVerifyGpuOffload.mockRejectedValue(new Error('router down'))++ const { result } = renderHook(() => useSetupChecklist())++ await waitFor(() => expect(result.current.isRunning).toBe(false))+ expect(result.current.gpu.willUse).toBeUndefined()+ })+ })++ it('re-runs the probes on demand', async () => {+ armHealthy()++ const { result } = renderHook(() => useSetupChecklist())+ await waitFor(() => expect(result.current.isRunning).toBe(false))++ await act(async () => {+ await result.current.rerun()+ })++ expect(mockVerifyGpuOffload).toHaveBeenCalledTimes(2)+ })+})diff --git a/web-app/src/hooks/useDownloadEvents.ts b/web-app/src/hooks/useDownloadEvents.tsnew file mode 100644index 000000000..bb190101e--- /dev/null+++ b/web-app/src/hooks/useDownloadEvents.ts@@ -0,0 +1,196 @@+import { DownloadEvent, DownloadState, events } from '@janhq/core'+import { useCallback, useEffect } from 'react'+import { toast } from 'sonner'+import { useNavigate } from '@tanstack/react-router'+import { route } from '@/constants/routes'+import { useDownloadStore } from '@/hooks/useDownloadStore'+import { useTranslation } from '@/i18n/react-i18next-compat'++/**+ * Bridges download events into the download store.+ *+ * This must be mounted for the whole app lifetime, not alongside the download+ * popover: that popover lives in the sidebar or the header depending on layout,+ * and on the first-run setup screen neither copy is guaranteed to be mounted.+ * With no subscriber the Rust download still ran to completion while the UI+ * showed no progress and never cleared its "downloading" flag.+ */+export function useDownloadEvents() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const {+ updateProgress,+ removeDownload,+ removeLocalDownloadingModel,+ } = useDownloadStore()++ const onFileDownloadUpdate = useCallback(+ (state: DownloadState) => {+ updateProgress(+ state.modelId,+ state.percent,+ state.modelId,+ state.size?.transferred,+ state.size?.total+ )+ },+ [updateProgress]+ )++ const onFileDownloadError = useCallback(+ (state: DownloadState) => {+ removeDownload(state.modelId)+ removeLocalDownloadingModel(state.modelId)++ const err = (state as unknown as { error?: string })?.error || ''++ if (err.includes('HTTP status 401')) {+ toast.error(t('common:toast.downloadTokenRequired.title'), {+ id: 'download-failed',+ description: t('common:toast.downloadTokenRequired.description'),+ action: {+ label: t('common:toast.openSettings'),+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }++ if (err.includes('HTTP status 403')) {+ toast.error(t('common:toast.downloadLicenseRequired.title'), {+ id: 'download-failed',+ description: t('common:toast.downloadLicenseRequired.description'),+ })+ return+ }++ if (err.includes('HTTP status 429')) {+ toast.error(t('common:toast.downloadRateLimited.title'), {+ id: 'download-failed',+ description: t('common:toast.downloadRateLimited.description'),+ action: {+ label: t('common:toast.openSettings'),+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }++ toast.error(t('common:toast.downloadFailed.title'), {+ id: 'download-failed',+ description: t('common:toast.downloadFailed.description', {+ item: state.modelId,+ }),+ })+ },+ [removeDownload, removeLocalDownloadingModel, t, navigate]+ )++ const onModelValidationStarted = useCallback(+ (event: { modelId: string }) => {+ toast.info(t('common:toast.modelValidationStarted.title'), {+ id: `model-validation-started-${event.modelId}`,+ description: t('common:toast.modelValidationStarted.description', {+ modelId: event.modelId,+ }),+ duration: Infinity,+ })+ },+ [t]+ )++ const onModelValidationFailed = useCallback(+ (event: { modelId: string }) => {+ toast.dismiss(`model-validation-started-${event.modelId}`)+ removeDownload(event.modelId)+ removeLocalDownloadingModel(event.modelId)++ toast.error(t('common:toast.modelValidationFailed.title'), {+ description: t('common:toast.modelValidationFailed.description', {+ modelId: event.modelId,+ }),+ duration: 30000,+ })+ },+ [removeDownload, removeLocalDownloadingModel, t]+ )++ const onFileDownloadStopped = useCallback(+ (state: DownloadState) => {+ // A pause stops the download via the same cancel path; keep the entry+ // (with its partial progress) so it can be resumed.+ if (useDownloadStore.getState().downloads[state.modelId]?.paused) return+ removeDownload(state.modelId)+ removeLocalDownloadingModel(state.modelId)+ },+ [removeDownload, removeLocalDownloadingModel]+ )++ const onFileDownloadSuccess = useCallback(+ (state: DownloadState) => {+ toast.dismiss(`model-validation-started-${state.modelId}`)+ removeDownload(state.modelId)+ removeLocalDownloadingModel(state.modelId)+ toast.success(t('common:toast.downloadComplete.title'), {+ id: 'download-complete',+ description: t('common:toast.downloadComplete.description', {+ item: state.modelId,+ }),+ })+ },+ [removeDownload, removeLocalDownloadingModel, t]+ )++ const onFileDownloadAndVerificationSuccess = useCallback(+ (state: DownloadState) => {+ toast.dismiss(`model-validation-started-${state.modelId}`)+ removeDownload(state.modelId)+ removeLocalDownloadingModel(state.modelId)+ toast.success(t('common:toast.downloadAndVerificationComplete.title'), {+ id: 'download-complete',+ description: t(+ 'common:toast.downloadAndVerificationComplete.description',+ { item: state.modelId }+ ),+ })+ },+ [removeDownload, removeLocalDownloadingModel, t]+ )++ useEffect(() => {+ events.on(DownloadEvent.onFileDownloadUpdate, onFileDownloadUpdate)+ events.on(DownloadEvent.onFileDownloadError, onFileDownloadError)+ events.on(DownloadEvent.onFileDownloadSuccess, onFileDownloadSuccess)+ events.on(DownloadEvent.onFileDownloadStopped, onFileDownloadStopped)+ events.on(DownloadEvent.onModelValidationStarted, onModelValidationStarted)+ events.on(DownloadEvent.onModelValidationFailed, onModelValidationFailed)+ events.on(+ DownloadEvent.onFileDownloadAndVerificationSuccess,+ onFileDownloadAndVerificationSuccess+ )++ return () => {+ events.off(DownloadEvent.onFileDownloadUpdate, onFileDownloadUpdate)+ events.off(DownloadEvent.onFileDownloadError, onFileDownloadError)+ events.off(DownloadEvent.onFileDownloadSuccess, onFileDownloadSuccess)+ events.off(DownloadEvent.onFileDownloadStopped, onFileDownloadStopped)+ events.off(+ DownloadEvent.onModelValidationStarted,+ onModelValidationStarted+ )+ events.off(DownloadEvent.onModelValidationFailed, onModelValidationFailed)+ events.off(+ DownloadEvent.onFileDownloadAndVerificationSuccess,+ onFileDownloadAndVerificationSuccess+ )+ }+ }, [+ onFileDownloadUpdate,+ onFileDownloadError,+ onFileDownloadSuccess,+ onFileDownloadStopped,+ onModelValidationStarted,+ onModelValidationFailed,+ onFileDownloadAndVerificationSuccess,+ ])+}diff --git a/web-app/src/hooks/useIsOnboarding.ts b/web-app/src/hooks/useIsOnboarding.tsnew file mode 100644index 000000000..c1385458d--- /dev/null+++ b/web-app/src/hooks/useIsOnboarding.ts@@ -0,0 +1,16 @@+import { useModelProvider } from '@/hooks/useModelProvider'+import { hasUsableProvider } from '@/lib/providerReadiness'++/**+ * Whether first-run setup is still showing. The setup screen is the single+ * onboarding surface, so every other first-run prompt stays out of the way until+ * this is false -- otherwise they stack on top of it, each asking for something+ * the wizard already covers.+ *+ * Derived from the same gate the index route picks the setup screen by, so the+ * two cannot disagree.+ */+export function useIsOnboarding(): boolean {+ const providers = useModelProvider((state) => state.providers)+ return !hasUsableProvider(providers)+}diff --git a/web-app/src/hooks/useJanModelPrompt.ts b/web-app/src/hooks/useJanModelPrompt.tsindex 1a9422626..aee148ee1 100644--- a/web-app/src/hooks/useJanModelPrompt.ts+++ b/web-app/src/hooks/useJanModelPrompt.ts@@ -1,11 +1,6 @@import { localStorageKey } from '@/constants/localStorage'import { create } from 'zustand'import { createJSONStorage, persist } from 'zustand/middleware'-import { useModelProvider } from './useModelProvider'-import { useDownloadStore } from './useDownloadStore'-import { useLatestJanModel } from './useLatestJanModel'-import { predefinedProviders } from '@/constants/providers'-import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'import { backendStorage } from '@/lib/backendStorage'export type JanModelPromptDismissedState = {@@ -36,73 +31,3 @@ export const useJanModelPromptDismissed =}))--const MIN_VERSION = '0.7.6'--export const useJanModelPrompt = () => {- const { dismissedModelName, setDismissedModelName } =- useJanModelPromptDismissed()- const { getProviderByName, providers } = useModelProvider()- const { localDownloadingModels } = useDownloadStore()- const latestModel = useLatestJanModel((state) => state.model)-- const llamaProvider = getProviderByName('llamacpp')-- // Only show for versions >= MIN_VERSION- const isTargetVersion = VERSION >= MIN_VERSION-- // Check if user would be on SetupScreen (no valid providers)- const hasValidProviders = providers.some((provider) => {- const isPredefinedProvider = predefinedProviders.some(- (p) => p.provider === provider.provider- )- if (!isPredefinedProvider) {- return provider.models.length > 0- }- return (- providerHasRemoteApiKeys(provider) ||- (provider.provider === 'llamacpp' && provider.models.length) ||- (provider.provider === 'jan' && provider.models.length)- )- })- const isOnSetupScreen = !hasValidProviders-- // Build set of known quant model IDs from the latest Jan model- const latestModelQuantIds = new Set(- latestModel?.quants?.map((q) => q.model_id.toLowerCase()) ?? []- )-- // Check if any variant of the latest Jan model is downloaded- const isJanModelDownloaded =- latestModelQuantIds.size > 0 &&- (llamaProvider?.models.some(- (m: { id: string }) => latestModelQuantIds.has(m.id.toLowerCase())- ) ?? false)-- // Check if currently downloading any variant- const isDownloading =- latestModelQuantIds.size > 0 &&- Array.from(localDownloadingModels).some(- (id) => latestModelQuantIds.has(id.toLowerCase())- )-- // Dismissed only applies to the current latest model- const isDismissed =- latestModel != null &&- dismissedModelName === latestModel.model_name-- const showJanModelPrompt =- isTargetVersion &&- !isOnSetupScreen &&- !isDismissed &&- latestModel != null &&- !isJanModelDownloaded &&- !isDownloading-- return {- showJanModelPrompt,- setDismissedModelName,- isJanModelDownloaded,- isDownloading,- }-}diff --git a/web-app/src/hooks/useSetupChecklist.ts b/web-app/src/hooks/useSetupChecklist.tsnew file mode 100644index 000000000..1e6e3c8ed--- /dev/null+++ b/web-app/src/hooks/useSetupChecklist.ts@@ -0,0 +1,381 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import { AppEvent, DownloadEvent, events } from '@janhq/core'+import { getServiceHub } from '@/hooks/useServiceHub'+import { activeSetupScenario } from '@/lib/setupSimulation'+import {+ backendGpuFamily,+ describeGpus,+ evaluateBackendGpuMatch,+ type BackendGpuFamily,+ type DetectedGpu,+} from '@/lib/gpuBackendMatch'+import type {+ EmbeddingModelReport,+ EmbeddingVectorProblem,+ GpuOffloadReason,+ GpuOffloadReport,+} from '@/services/models/types'++export type SetupStageId = 'system' | 'engine' | 'search'+export type SetupStageStatus = 'pending' | 'running' | 'ok' | 'warning'++export interface SetupStageState {+ id: SetupStageId+ status: SetupStageStatus+ /** Key under the `setup` i18n namespace; the hook never produces prose. */+ messageKey?: string+ values?: Record<string, string | number>+ /** Raw technical detail for a disclosure area; never translated. */+ detail?: string+ /**+ * Structured form of the names in `values.libraries`, so install advice can be+ * rendered from them rather than parsed back out of the display string.+ */+ missingLibraries?: string[]+ /** The backend the libraries belong to, for platform-specific advice. */+ backend?: string+}++const STAGE_ORDER: SetupStageId[] = ['system', 'engine', 'search']++/** Emitted by the llamacpp extension; it predates the AppEvent enum. */+const ENGINE_SETTINGS_CHANGED = 'settingsChanged'++// `missingLibrary` is the same symptom as `runtimeUnreachable` with the cause+// identified, so it gets its own message naming the dependency.+const ENGINE_REASON_KEYS: Record<GpuOffloadReason, string> = {+ noGpuHardware: 'checkEngineNoGpuHardware',+ runtimeUnreachable: 'checkEngineRuntimeUnreachable',+ missingLibrary: 'checkEngineMissingLibrary',+}++// `missing`/`empty` mean nothing came back; `nonFinite`/`degenerate` mean a+// vector came back that would poison similarity scoring. Different causes,+// so different advice.+const VECTOR_PROBLEM_KEYS: Record<EmbeddingVectorProblem, string> = {+ missing: 'checkSearchNoVector',+ empty: 'checkSearchNoVector',+ nonFinite: 'checkSearchInvalidVector',+ degenerate: 'checkSearchInvalidVector',+}++/**+ * Whether inference will actually run on the GPU, for the badge the setup screen+ * shows. `willUse` stays undefined while the engine is still setting itself up,+ * since neither answer is known yet.+ */+export interface GpuVerdict {+ willUse?: boolean+ /** Detected hardware, e.g. `NVIDIA RTX 4070 (8 GB)`; empty when none. */+ label: string+}++function gpuVerdict(+ report: GpuOffloadReport | undefined,+ gpus: DetectedGpu[]+): GpuVerdict {+ const label = describeGpus(gpus)+ if (!report || report.pending || report.unavailable) return { label }++ // Metal is compiled into every macOS build and always present, so the engine+ // never reports it as "a GPU build" and never enumerates it as a device.+ // Reading those absences literally told Apple Silicon users they were on CPU.+ if (backendGpuFamily(report.backend) === 'metal') {+ return { willUse: true, label }+ }++ // Elsewhere a GPU build that found no device runs on the CPU regardless of+ // what is installed, so the device count decides rather than the name.+ return { willUse: report.gpuExpected && report.engineDeviceCount > 0, label }+}++const pendingStages = (): SetupStageState[] =>+ STAGE_ORDER.map((id) => ({ id, status: 'pending' }))++const errorDetail = (error: unknown): string =>+ error instanceof Error ? error.message : String(error)++type HardwareInfo = {+ cpu?: { name?: string }+ gpus?: DetectedGpu[]+}++// Naming the vendor a build requires is more actionable than naming the API,+// and the two vendor-locked families map one-to-one onto a vendor.+const FAMILY_VENDOR_NAMES: Partial<Record<BackendGpuFamily, string>> = {+ cuda: 'NVIDIA',+ hip: 'AMD',+}++function systemStage(info: HardwareInfo | null): SetupStageState {+ const gpus = info?.gpus ?? []+ if (gpus.length === 0) {+ return {+ id: 'system',+ status: 'ok',+ messageKey: 'checkSystemCpuOnly',+ values: { cpu: info?.cpu?.name ?? '' },+ }+ }++ // Every GPU is listed: on a hybrid laptop the integrated one often sorts+ // first, and reporting only that reads as "no discrete GPU found".+ const driver = gpus.find((gpu) => gpu.driver_version)?.driver_version+ return {+ id: 'system',+ status: 'ok',+ messageKey: driver ? 'checkSystemGpu' : 'checkSystemGpuNoDriver',+ values: { gpus: describeGpus(gpus), driver: driver ?? '' },+ }+}++function engineStage(+ report: GpuOffloadReport,+ gpus: DetectedGpu[]+): SetupStageState {+ if (report.unavailable) {+ return {+ id: 'engine',+ status: 'warning',+ messageKey: 'checkEngineUnavailable',+ }+ }+ if (report.pending) {+ return {+ id: 'engine',+ status: 'running',+ messageKey: 'checkEnginePreparing',+ }+ }+ if (report.status === 'ok') {+ // The engine only reports whether a GPU build found a device. It cannot+ // report the inverse, so a GPU left idle by a CPU-only build -- or a build+ // for the wrong vendor -- is caught here instead.+ const match = evaluateBackendGpuMatch(gpus, report.backend)+ // On a fresh install the engine is still downloading a backend, so there is+ // nothing to judge yet. Reported as in-progress, never as a warning: it+ // resolves on its own and the checklist re-runs when it does.+ if (match.kind === 'unknown') {+ return {+ id: 'engine',+ status: 'running',+ messageKey: 'checkEnginePreparing',+ }+ }+ if (match.kind === 'gpuUnused') {+ return {+ id: 'engine',+ status: 'warning',+ messageKey: 'checkEngineGpuUnused',+ values: { backend: report.backend, gpus: describeGpus(match.gpus) },+ }+ }+ if (match.kind === 'vendorMismatch') {+ return {+ id: 'engine',+ status: 'warning',+ messageKey: 'checkEngineVendorMismatch',+ values: {+ backend: report.backend,+ vendor: FAMILY_VENDOR_NAMES[match.family] ?? match.family,+ gpus: describeGpus(match.gpus),+ },+ }+ }+ return {+ id: 'engine',+ status: 'ok',+ messageKey: report.gpuExpected ? 'checkEngineGpu' : 'checkEngineCpu',+ values: { backend: report.backend },+ }+ }+ // A failed device probe leaves no reason code, so report the raw cause rather+ // than guess between "no GPU" and "unreachable GPU".+ const messageKey = report.reason+ ? ENGINE_REASON_KEYS[report.reason]+ : 'checkEngineProbeFailed'++ return {+ id: 'engine',+ status: 'warning',+ messageKey,+ values: {+ backend: report.backend,+ libraries: (report.missingLibraries ?? []).join(', '),+ },+ detail: report.error,+ missingLibraries: report.missingLibraries,+ backend: report.backend,+ }+}++function searchStage(report: EmbeddingModelReport): SetupStageState {+ if (report.unavailable) {+ return {+ id: 'search',+ status: 'warning',+ messageKey: 'checkSearchUnavailable',+ }+ }+ if (report.pending) {+ return {+ id: 'search',+ status: 'running',+ messageKey: 'checkSearchPreparing',+ }+ }+ if (report.status === 'ok') {+ return {+ id: 'search',+ status: 'ok',+ messageKey: 'checkSearchReady',+ values: { model: report.modelId ?? '', dimension: report.dimension ?? 0 },+ }+ }+ return {+ id: 'search',+ status: 'warning',+ messageKey: report.problem+ ? VECTOR_PROBLEM_KEYS[report.problem]+ : 'checkSearchProbeFailed',+ values: { model: report.modelId ?? '' },+ detail: report.error,+ }+}++/**+ * Runs the first-run readiness checks and reports each as a checklist row.+ * Every check is advisory: a failure produces a warning row, never a block, so+ * a false negative cannot strand a user whose install actually works.+ */+export function useSetupChecklist(options?: { enabled?: boolean }) {+ const enabled = options?.enabled ?? true+ const [stages, setStages] = useState<SetupStageState[]>(pendingStages)+ const [gpu, setGpu] = useState<GpuVerdict>({ label: '' })+ const [isRunning, setIsRunning] = useState(false)+ const runningRef = useRef(false)++ const rerunQueuedRef = useRef(false)++ const rerun = useCallback(async () => {+ // A request arriving mid-run is queued rather than dropped: it usually+ // carries newer state than the run in flight observed.+ if (runningRef.current) {+ rerunQueuedRef.current = true+ return+ }+ runningRef.current = true+ setIsRunning(true)+ setStages(STAGE_ORDER.map((id) => ({ id, status: 'running' })))++ const hub = getServiceHub()+ // A development override stands in for hardware nobody on the team has; it+ // is compiled out of a production build.+ const scenario = activeSetupScenario()+ // Run together and settle independently: one dead probe must not suppress+ // the verdicts of the others.+ const [system, engine, search] = scenario+ ? ([+ { status: 'fulfilled', value: scenario.hardware },+ { status: 'fulfilled', value: scenario.gpu },+ { status: 'fulfilled', value: scenario.embedding },+ ] as const)+ : await Promise.allSettled([+ hub.hardware().getHardwareInfo(),+ hub.models().verifyGpuOffload(),+ hub.models().verifyEmbeddingModel(),+ ])++ const hardware =+ system.status === 'fulfilled'+ ? (system.value as HardwareInfo | null)+ : null++ const next: SetupStageState[] = [+ system.status === 'fulfilled'+ ? systemStage(hardware)+ : {+ id: 'system',+ status: 'warning',+ messageKey: 'checkSystemFailed',+ detail: errorDetail(system.reason),+ },+ engine.status === 'fulfilled'+ ? engineStage(engine.value, hardware?.gpus ?? [])+ : {+ id: 'engine',+ status: 'warning',+ messageKey: 'checkEngineProbeFailed',+ detail: errorDetail(engine.reason),+ },+ search.status === 'fulfilled'+ ? searchStage(search.value)+ : {+ id: 'search',+ status: 'warning',+ messageKey: 'checkSearchProbeFailed',+ detail: errorDetail(search.reason),+ },+ ]++ setStages(next)+ setGpu(+ gpuVerdict(+ engine.status === 'fulfilled' ? engine.value : undefined,+ hardware?.gpus ?? []+ )+ )+ setIsRunning(false)+ runningRef.current = false++ if (rerunQueuedRef.current) {+ rerunQueuedRef.current = false+ void rerun()+ }+ }, [])++ useEffect(() => {+ if (enabled) void rerun()+ }, [enabled, rerun])++ // The first run of these checks races the engine's own background setup: the+ // backend is picked, then downloaded, then the router starts, then the+ // embedding model is fetched. Each milestone invalidates an earlier verdict,+ // so the checklist follows them instead of reporting a single early snapshot.+ useEffect(() => {+ if (!enabled) return++ const onEngineSettingChanged = (payload?: { key?: string }) => {+ if (+ payload?.key === 'llamacpp_version' ||+ payload?.key === 'llamacpp_backend'+ ) {+ void rerun()+ }+ }+ const onDownloadSuccess = (payload?: { downloadType?: string }) => {+ if (payload?.downloadType === 'Engine') void rerun()+ }+ const onModelImported = (payload?: { embedding?: boolean }) => {+ if (payload?.embedding) void rerun()+ }++ events.on(ENGINE_SETTINGS_CHANGED, onEngineSettingChanged)+ events.on(DownloadEvent.onFileDownloadSuccess, onDownloadSuccess)+ events.on(AppEvent.onModelImported, onModelImported)++ return () => {+ events.off(ENGINE_SETTINGS_CHANGED, onEngineSettingChanged)+ events.off(DownloadEvent.onFileDownloadSuccess, onDownloadSuccess)+ events.off(AppEvent.onModelImported, onModelImported)+ }+ }, [enabled, rerun])++ return {+ stages,+ warnings: stages.filter((s) => s.status === 'warning'),+ gpu,+ isRunning,+ rerun,+ }+}diff --git a/web-app/src/lib/__tests__/backendDependencies.test.ts b/web-app/src/lib/__tests__/backendDependencies.test.tsnew file mode 100644index 000000000..4ed7ce0a4--- /dev/null+++ b/web-app/src/lib/__tests__/backendDependencies.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from 'vitest'+import {+ getBackendDisplayName,+ getInstallRecommendations,+} from '../backendDependencies'++const CUDA12 = 'linux-cuda-12-common_cpus-x64'++describe('getBackendDisplayName', () => {+ it('names each CUDA major version', () => {+ expect(getBackendDisplayName('linux-cuda-11-common_cpus-x64')).toBe(+ 'NVIDIA CUDA 11 Backend'+ )+ expect(getBackendDisplayName(CUDA12)).toBe('NVIDIA CUDA 12 Backend')+ expect(getBackendDisplayName('win-cuda-13-common_cpus-x64')).toBe(+ 'NVIDIA CUDA 13 Backend'+ )+ })++ it('names the non-CUDA backends', () => {+ expect(getBackendDisplayName('linux-vulkan-common_cpus-x64')).toBe(+ 'Vulkan Backend'+ )+ expect(getBackendDisplayName('linux-common_cpus-x64')).toBe('CPU Backend')+ })++ it('passes an unrecognised backend through unchanged', () => {+ expect(getBackendDisplayName('something-new')).toBe('something-new')+ })+})++describe('getInstallRecommendations', () => {+ // A missing bundled lib means a corrupted download, not a missing toolkit, so+ // it must be claimed before the CUDA filter can absorb the name.+ it('attributes a missing bundled lib to the download, not to CUDA', () => {+ const { recommendations, uncovered } = getInstallRecommendations(+ ['libggml-cuda.so'],+ CUDA12+ )+ expect(recommendations).toHaveLength(1)+ expect(recommendations[0].label).toBe('Re-download the backend')+ expect(uncovered).toEqual([])+ })++ it('recommends the matching CUDA toolkit version', () => {+ const { recommendations } = getInstallRecommendations(+ ['libcublas.so.12'],+ CUDA12+ )+ expect(recommendations[0].label).toBe('NVIDIA CUDA Toolkit 12')+ expect(recommendations[0].url).toContain('nvidia.com')+ })++ // NCCL names appear on non-CUDA builds too; recommending it there would be+ // advice for a dependency that build never needed.+ it('only recommends NCCL on a CUDA build', () => {+ expect(+ getInstallRecommendations(['libnccl.so.2'], CUDA12).recommendations.map(+ (r) => r.label+ )+ ).toContain('NVIDIA NCCL')++ const vulkan = getInstallRecommendations(+ ['libnccl.so.2'],+ 'linux-vulkan-common_cpus-x64'+ )+ expect(vulkan.recommendations.map((r) => r.label)).not.toContain(+ 'NVIDIA NCCL'+ )+ expect(vulkan.uncovered).toEqual(['libnccl.so.2'])+ })++ it('recommends the Vulkan loader for a missing vulkan lib', () => {+ const { recommendations } = getInstallRecommendations(+ ['libvulkan.so.1'],+ 'linux-vulkan-common_cpus-x64'+ )+ expect(recommendations[0].label).toBe('Vulkan Runtime')+ })++ it('never counts one library under two recommendations', () => {+ const { recommendations, uncovered } = getInstallRecommendations(+ ['libggml-cuda.so', 'libcudart.so.12', 'libnccl.so.2'],+ CUDA12+ )+ const claimed = recommendations.flatMap((r) => r.libs)+ expect(new Set(claimed).size).toBe(claimed.length)+ expect([...claimed, ...uncovered].sort()).toEqual([+ 'libcudart.so.12',+ 'libggml-cuda.so',+ 'libnccl.so.2',+ ])+ })++ it('reports an unrecognised library as uncovered', () => {+ const { recommendations, uncovered } = getInstallRecommendations(+ ['libmystery.so.1'],+ CUDA12+ )+ expect(recommendations).toEqual([])+ expect(uncovered).toEqual(['libmystery.so.1'])+ })++ it('returns nothing for an empty list', () => {+ expect(getInstallRecommendations([], CUDA12)).toEqual({+ recommendations: [],+ uncovered: [],+ })+ })+})diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.tsnew file mode 100644index 000000000..5fade0897--- /dev/null+++ b/web-app/src/lib/__tests__/engineError.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { mockT } = vi.hoisted(() => ({+ mockT: vi.fn((key: string, opts?: Record<string, unknown>) =>+ opts ? `${key}|${JSON.stringify(opts)}` : key+ ),+}))++vi.mock('@/i18n/react-i18next-compat', () => ({+ i18n: { t: mockT },+}))++import {+ parseEngineError,+ describeEngineError,+ ENGINE_ERROR_CODES,+} from '../engineError'++describe('parseEngineError', () => {+ it('reads a Tauri-serialized engine error', () => {+ const parsed = parseEngineError({+ code: 'MISSING_SHARED_LIBRARY',+ message: 'A library this backend depends on is missing.',+ details: 'libnccl.so.2: cannot open shared object file',+ missing_libraries: ['libnccl.so.2'],+ })++ expect(parsed).toEqual({+ code: 'MISSING_SHARED_LIBRARY',+ message: 'A library this backend depends on is missing.',+ details: 'libnccl.so.2: cannot open shared object file',+ missingLibraries: ['libnccl.so.2'],+ })+ })++ it('returns undefined for things that are not engine errors', () => {+ expect(parseEngineError(new Error('plain'))).toBeUndefined()+ expect(parseEngineError('string')).toBeUndefined()+ expect(parseEngineError(null)).toBeUndefined()+ expect(parseEngineError(undefined)).toBeUndefined()+ expect(parseEngineError({ message: 'no code' })).toBeUndefined()+ })++ // An unrecognized code from a newer engine must not be treated as a known one.+ it('rejects an unknown code', () => {+ expect(parseEngineError({ code: 'SOMETHING_NEW' })).toBeUndefined()+ })++ it('unwraps an engine error nested behind a message string', () => {+ const inner = JSON.stringify({+ code: 'OUT_OF_MEMORY',+ message: 'Out of memory.',+ })+ const parsed = parseEngineError(new Error(`Failed to start model: ${inner}`))++ expect(parsed?.code).toBe('OUT_OF_MEMORY')+ })++ it('tolerates a non-array missing_libraries', () => {+ const parsed = parseEngineError({+ code: 'MISSING_SHARED_LIBRARY',+ missing_libraries: 'libnccl.so.2',+ })++ expect(parsed?.missingLibraries).toBeUndefined()+ })+})++describe('describeEngineError', () => {+ beforeEach(() => {+ mockT.mockClear()+ })++ it('translates a known code instead of showing the Rust message', () => {+ const text = describeEngineError({+ code: 'GPU_DRIVER_TOO_OLD',+ message: 'The installed GPU driver is too old for this backend.',+ })++ expect(mockT).toHaveBeenCalledWith('model-errors:engine.GPU_DRIVER_TOO_OLD')+ expect(text).toBe('model-errors:engine.GPU_DRIVER_TOO_OLD')+ expect(text).not.toContain('backend')+ })++ it('appends the missing library names, which are not translatable', () => {+ const text = describeEngineError({+ code: 'MISSING_SHARED_LIBRARY',+ missing_libraries: ['libnccl.so.2', 'libcublas.so.12'],+ })++ expect(mockT).toHaveBeenCalledWith('model-errors:engineMissingLibraries', {+ libraries: 'libnccl.so.2, libcublas.so.12',+ })+ expect(text).toContain('libnccl.so.2, libcublas.so.12')+ })++ it('has a key for every code the engine can emit', () => {+ for (const code of ENGINE_ERROR_CODES) {+ mockT.mockClear()+ describeEngineError({ code })+ expect(mockT).toHaveBeenCalledWith(`model-errors:engine.${code}`)+ }+ })++ // Never surface raw JSON, which is what the old path did for a plain object.+ it('falls back to a translated generic message for an unknown shape', () => {+ const text = describeEngineError({ weird: true })++ expect(text).toBe('model-errors:engine.unknown')+ expect(text).not.toContain('{')+ })++ it('keeps a plain Error message, which is already human-readable', () => {+ expect(describeEngineError(new Error('No running session found'))).toBe(+ 'No running session found'+ )+ })++ it('keeps a plain string error', () => {+ expect(describeEngineError('something broke')).toBe('something broke')+ })++ it('never returns an empty string', () => {+ for (const input of [new Error(''), '', ' ', {}, null, undefined]) {+ expect(describeEngineError(input).trim().length).toBeGreaterThan(0)+ }+ })+})diff --git a/web-app/src/lib/__tests__/gpuBackendMatch.test.ts b/web-app/src/lib/__tests__/gpuBackendMatch.test.tsnew file mode 100644index 000000000..023e5d6fd--- /dev/null+++ b/web-app/src/lib/__tests__/gpuBackendMatch.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it } from 'vitest'+import {+ backendGpuFamily,+ classifyVendor,+ describeGpus,+ evaluateBackendGpuMatch,+ gpuVendor,+ vendorSupportsFamily,+ type DetectedGpu,+} from '../gpuBackendMatch'++const nvidia: DetectedGpu = {+ name: 'NVIDIA GeForce RTX 4090',+ vendor: 'NVIDIA',+ total_memory: 24576,+ driver_version: '550.54.14',+}+const amd: DetectedGpu = {+ name: 'AMD Radeon RX 7900 XTX',+ vendor: 'AMD',+ total_memory: 24576,+}+const intel: DetectedGpu = {+ name: 'Intel Iris Xe Graphics',+ vendor: 'Intel',+ total_memory: 2048,+}++describe('classifyVendor', () => {+ it('maps the vendor strings the hardware plugin emits', () => {+ expect(classifyVendor('NVIDIA')).toBe('nvidia')+ expect(classifyVendor('AMD')).toBe('amd')+ expect(classifyVendor('Intel')).toBe('intel')+ })++ it('treats an unrecognised PCI vendor id as unknown', () => {+ expect(classifyVendor('Unknown (vendor_id: 5140)')).toBe('unknown')+ expect(classifyVendor(undefined)).toBe('unknown')+ expect(classifyVendor('')).toBe('unknown')+ })+})++describe('gpuVendor', () => {+ it('falls back to the device name when the vendor id is unknown', () => {+ expect(+ gpuVendor({ vendor: 'Unknown (vendor_id: 5140)', name: 'Radeon Pro W6800' })+ ).toBe('amd')+ })++ it('prefers the vendor id over the name', () => {+ expect(gpuVendor({ vendor: 'NVIDIA', name: 'Generic Display' })).toBe(+ 'nvidia'+ )+ })++ it('stays unknown when neither field is recognisable', () => {+ expect(gpuVendor({ vendor: 'Unknown (vendor_id: 1)', name: 'GPU' })).toBe(+ 'unknown'+ )+ })++ // Device names frequently omit the brand: `RTX 4070`, not `NVIDIA RTX 4070`.+ it('recognises bare NVIDIA product lines by name', () => {+ expect(gpuVendor({ name: 'RTX 4070' })).toBe('nvidia')+ expect(gpuVendor({ name: 'GTX 1660 Ti' })).toBe('nvidia')+ })+})++describe('backendGpuFamily', () => {+ it('recognises the backend asset names Jan ships', () => {+ expect(backendGpuFamily('linux-cuda-12-common_cpus-x64')).toBe('cuda')+ expect(backendGpuFamily('win-cuda-13-common_cpus-x64')).toBe('cuda')+ expect(backendGpuFamily('linux-vulkan-common_cpus-x64')).toBe('vulkan')+ expect(backendGpuFamily('win-hip-common_cpus-x64')).toBe('hip')+ expect(backendGpuFamily('linux-common_cpus-x64')).toBe('cpu')+ expect(backendGpuFamily('win-arm64')).toBe('cpu')+ })++ it('treats macOS builds as GPU-capable through Metal', () => {+ expect(backendGpuFamily('macos-arm64')).toBe('metal')+ expect(backendGpuFamily('macos-x64')).toBe('metal')+ })++ it('recognises the short cuda category names', () => {+ expect(backendGpuFamily('cuda-cu13.0')).toBe('cuda')+ })++ // An unnamed backend means the engine has not picked one yet. Reading it as+ // "CPU-only build" made a CUDA install report an idle GPU.+ it('reports an unselected backend as unknown, not cpu', () => {+ expect(backendGpuFamily('')).toBe('unknown')+ expect(backendGpuFamily(' ')).toBe('unknown')+ expect(backendGpuFamily(undefined)).toBe('unknown')+ expect(backendGpuFamily('none')).toBe('unknown')+ })+})++describe('vendorSupportsFamily', () => {+ it('locks cuda to nvidia and hip to amd', () => {+ expect(vendorSupportsFamily('nvidia', 'cuda')).toBe(true)+ expect(vendorSupportsFamily('amd', 'cuda')).toBe(false)+ expect(vendorSupportsFamily('amd', 'hip')).toBe(true)+ expect(vendorSupportsFamily('nvidia', 'hip')).toBe(false)+ })++ it('accepts any GPU for vulkan', () => {+ for (const vendor of ['nvidia', 'amd', 'intel', 'unknown'] as const) {+ expect(vendorSupportsFamily(vendor, 'vulkan'), vendor).toBe(true)+ }+ })++ it('never satisfies a cpu build', () => {+ expect(vendorSupportsFamily('nvidia', 'cpu')).toBe(false)+ })+})++describe('evaluateBackendGpuMatch', () => {+ it('is ok when the backend family matches a detected GPU', () => {+ expect(+ evaluateBackendGpuMatch([nvidia], 'linux-cuda-12-common_cpus-x64')+ ).toEqual({ kind: 'ok' })+ expect(+ evaluateBackendGpuMatch([amd], 'linux-hip-common_cpus-x64')+ ).toEqual({ kind: 'ok' })+ expect(+ evaluateBackendGpuMatch([intel], 'linux-vulkan-common_cpus-x64')+ ).toEqual({ kind: 'ok' })+ })++ it('reports noGpu for a CPU build on a machine with no GPU', () => {+ expect(evaluateBackendGpuMatch([], 'linux-common_cpus-x64')).toEqual({+ kind: 'noGpu',+ })+ expect(evaluateBackendGpuMatch(undefined, 'linux-common_cpus-x64')).toEqual({+ kind: 'noGpu',+ })+ })++ it('reports gpuUnused when a GPU is present but a CPU build is installed', () => {+ expect(evaluateBackendGpuMatch([nvidia], 'linux-common_cpus-x64')).toEqual({+ kind: 'gpuUnused',+ gpus: [nvidia],+ })+ })++ it('reports a vendor mismatch for a cuda build on an AMD-only machine', () => {+ expect(+ evaluateBackendGpuMatch([amd], 'linux-cuda-12-common_cpus-x64')+ ).toEqual({ kind: 'vendorMismatch', family: 'cuda', gpus: [amd] })+ })++ it('reports a vendor mismatch for a hip build on an NVIDIA-only machine', () => {+ expect(+ evaluateBackendGpuMatch([nvidia], 'linux-hip-common_cpus-x64')+ ).toEqual({ kind: 'vendorMismatch', family: 'hip', gpus: [nvidia] })+ })++ it('accepts a cuda build on a hybrid machine where only one GPU is NVIDIA', () => {+ expect(+ evaluateBackendGpuMatch([intel, nvidia], 'linux-cuda-12-common_cpus-x64')+ ).toEqual({ kind: 'ok' })+ })++ it('reports unknown while no backend is selected yet', () => {+ expect(evaluateBackendGpuMatch([nvidia], '')).toEqual({ kind: 'unknown' })+ expect(evaluateBackendGpuMatch([nvidia], undefined)).toEqual({+ kind: 'unknown',+ })+ expect(evaluateBackendGpuMatch([nvidia], 'none')).toEqual({+ kind: 'unknown',+ })+ })++ it('never warns about a macOS build', () => {+ expect(evaluateBackendGpuMatch([], 'macos-arm64')).toEqual({ kind: 'ok' })+ })++ // A mismatch claim would tell the user to reinstall a backend that works.+ it('does not claim a mismatch when no vendor could be identified', () => {+ expect(+ evaluateBackendGpuMatch(+ [{ name: 'Display Adapter', vendor: 'Unknown (vendor_id: 5140)' }],+ 'linux-cuda-12-common_cpus-x64'+ )+ ).toEqual({ kind: 'ok' })+ })++ it('does not claim a mismatch when no GPU was detected at all', () => {+ expect(+ evaluateBackendGpuMatch([], 'linux-cuda-12-common_cpus-x64')+ ).toEqual({ kind: 'ok' })+ })++ it('still reports a mismatch when one GPU is identified and none match', () => {+ expect(+ evaluateBackendGpuMatch(+ [{ vendor: 'Unknown (vendor_id: 5140)' }, amd],+ 'linux-cuda-12-common_cpus-x64'+ )+ ).toMatchObject({ kind: 'vendorMismatch', family: 'cuda' })+ })+})++describe('describeGpus', () => {+ it('renders name and rounded VRAM', () => {+ expect(describeGpus([nvidia])).toBe('NVIDIA GeForce RTX 4090 (24 GB)')+ })++ it('joins multiple GPUs', () => {+ expect(describeGpus([intel, nvidia])).toBe(+ 'Intel Iris Xe Graphics (2 GB), NVIDIA GeForce RTX 4090 (24 GB)'+ )+ })++ it('omits VRAM when unreported and falls back to the vendor', () => {+ expect(describeGpus([{ vendor: 'AMD' }])).toBe('AMD')+ })++ it('drops entries with nothing to say', () => {+ expect(describeGpus([{}, nvidia])).toBe('NVIDIA GeForce RTX 4090 (24 GB)')+ })+})diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.tsindex c1f73cc90..04c219ebd 100644--- a/web-app/src/lib/__tests__/model-factory.deep.test.ts+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts@@ -260,6 +260,25 @@ describe('model-factory deep coverage', () => {mockStartModel.mockRejectedValueOnce({ code: 'ENOMEM' })await expect(ModelFactory.createModel('m', mkProvider('llamacpp'), {})).rejects.toThrow('Failed to start model:')})++ // A serialized engine error is a plain object; it used to reach the user as+ // raw JSON including the Rust-authored English message.+ it('does not leak a serialized engine error as raw JSON', async () => {+ mockStartModel.mockRejectedValueOnce({+ code: 'MISSING_SHARED_LIBRARY',+ message: 'A library this backend depends on is missing.',+ details: 'libnccl.so.2: cannot open shared object file',+ missing_libraries: ['libnccl.so.2'],+ })++ const err = await ModelFactory.createModel('m', mkProvider('llamacpp'), {}).catch(+ (e) => e as Error+ )++ expect(err.message).not.toContain('{')+ expect(err.message).not.toContain('backend depends on')+ expect(err.message).toContain('libnccl.so.2')+ })})/* mlx internals */diff --git a/web-app/src/lib/__tests__/providerReadiness.test.ts b/web-app/src/lib/__tests__/providerReadiness.test.tsnew file mode 100644index 000000000..7926cca3b--- /dev/null+++ b/web-app/src/lib/__tests__/providerReadiness.test.ts@@ -0,0 +1,142 @@+import { describe, it, expect, vi } from 'vitest'++vi.mock('@/constants/providers', () => ({+ predefinedProviders: [+ { provider: 'openai' },+ { provider: 'anthropic' },+ { provider: 'llamacpp' },+ { provider: 'jan' },+ ],+}))++import { isProviderUsable, hasUsableProvider } from '../providerReadiness'++const provider = (over: Record<string, unknown> = {}) =>+ ({ provider: 'openai', models: [], ...over }) as never++describe('isProviderUsable', () => {+ it('accepts a predefined remote provider holding an API key', () => {+ expect(isProviderUsable(provider({ api_key: 'sk-x' }))).toBe(true)+ })++ it('accepts a predefined remote provider with only a fallback key', () => {+ expect(+ isProviderUsable(provider({ api_key_fallbacks: ['sk-fallback'] }))+ ).toBe(true)+ })++ it('rejects a predefined remote provider with no key', () => {+ expect(isProviderUsable(provider())).toBe(false)+ })++ // A remote provider listing models still cannot serve them without a key.+ it('rejects a predefined remote provider that only has models', () => {+ expect(isProviderUsable(provider({ models: [{ id: 'gpt-4' }] }))).toBe(+ false+ )+ })++ it('accepts llamacpp once it has a model, with no key', () => {+ expect(+ isProviderUsable(+ provider({ provider: 'llamacpp', models: [{ id: 'jan-v2' }] })+ )+ ).toBe(true)+ })++ it('rejects llamacpp with no models', () => {+ expect(isProviderUsable(provider({ provider: 'llamacpp' }))).toBe(false)+ })++ it('accepts jan once it has a model', () => {+ expect(+ isProviderUsable(provider({ provider: 'jan', models: [{ id: 'm' }] }))+ ).toBe(true)+ })++ // Custom providers are user-configured endpoints, so models alone qualify.+ it('accepts a custom provider with models and no key', () => {+ expect(+ isProviderUsable(provider({ provider: 'my-server', models: [{ id: 'm' }] }))+ ).toBe(true)+ })++ it('rejects a custom provider with no models', () => {+ expect(isProviderUsable(provider({ provider: 'my-server' }))).toBe(false)+ })++ // The original returned `provider.models.length`, a number, from a callback+ // typed as boolean. Keep the contract strictly boolean.+ it('always returns a boolean', () => {+ for (const p of [+ provider(),+ provider({ provider: 'llamacpp', models: [{ id: 'm' }] }),+ provider({ provider: 'custom', models: [{ id: 'm' }] }),+ ]) {+ expect(typeof isProviderUsable(p)).toBe('boolean')+ }+ })++ it('tolerates a provider with no models array', () => {+ expect(+ isProviderUsable({ provider: 'llamacpp' } as never)+ ).toBe(false)+ })++ // Jan bootstraps an embedding model during first-run setup. Counting it ended+ // onboarding before the user had any model to chat with.+ it('does not count an embedding-only local provider as usable', () => {+ expect(+ isProviderUsable({+ provider: 'llamacpp',+ models: [{ id: 'sentence-transformer-mini', embedding: true }],+ } as never)+ ).toBe(false)+ })++ it('recognises an embedding model declared only by capability', () => {+ expect(+ isProviderUsable({+ provider: 'llamacpp',+ models: [{ id: 'e5-small', capabilities: ['embeddings'] }],+ } as never)+ ).toBe(false)+ })++ it('is usable once a chat model joins the embedding model', () => {+ expect(+ isProviderUsable({+ provider: 'llamacpp',+ models: [+ { id: 'sentence-transformer-mini', embedding: true },+ { id: 'jan-v3-q4_k_xl' },+ ],+ } as never)+ ).toBe(true)+ })+})++describe('hasUsableProvider', () => {+ it('is false for an empty list', () => {+ expect(hasUsableProvider([])).toBe(false)+ })++ it('is false when every provider is unusable', () => {+ expect(+ hasUsableProvider([provider(), provider({ provider: 'llamacpp' })])+ ).toBe(false)+ })++ it('is true when any single provider is usable', () => {+ expect(+ hasUsableProvider([+ provider(),+ provider({ provider: 'llamacpp', models: [{ id: 'm' }] }),+ ])+ ).toBe(true)+ })++ it('tolerates a missing list', () => {+ expect(hasUsableProvider(undefined as never)).toBe(false)+ })+})diff --git a/web-app/src/lib/__tests__/setupModelOptions.test.ts b/web-app/src/lib/__tests__/setupModelOptions.test.tsnew file mode 100644index 000000000..355f5b834--- /dev/null+++ b/web-app/src/lib/__tests__/setupModelOptions.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest'+import { pickMmproj } from '../setupModelOptions'+import type { CatalogModel } from '@/services/models/types'++const model = (over: Partial<CatalogModel> = {}): CatalogModel => ({+ model_name: 'org/some-model',+ description: '',+ downloads: 100,+ quants: [{ model_id: 'some-model-q4_k_m', path: 'p/q4', file_size: '4 GB' }],+ ...over,+})++describe('pickMmproj', () => {+ it('prefers the F16 projector', () => {+ expect(+ pickMmproj(+ model({+ mmproj_models: [+ { model_id: 'mmproj-q8_0', path: 'p/q8', file_size: '1 GB' },+ { model_id: 'mmproj-f16', path: 'p/f16', file_size: '2 GB' },+ ],+ })+ )+ ).toBe('p/f16')+ })++ it('falls back to the first projector when F16 is absent', () => {+ expect(+ pickMmproj(+ model({+ mmproj_models: [+ { model_id: 'mmproj-q8_0', path: 'p/q8', file_size: '1 GB' },+ ],+ })+ )+ ).toBe('p/q8')+ })++ it('returns nothing for a text-only model', () => {+ expect(pickMmproj(model())).toBeUndefined()+ expect(pickMmproj(model({ mmproj_models: [] }))).toBeUndefined()+ })+})diff --git a/web-app/src/lib/__tests__/setupSimulation.test.ts b/web-app/src/lib/__tests__/setupSimulation.test.tsnew file mode 100644index 000000000..d422efe3d--- /dev/null+++ b/web-app/src/lib/__tests__/setupSimulation.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest'+import { SETUP_SCENARIOS } from '../setupSimulation'+import { backendGpuFamily } from '../gpuBackendMatch'++// These scenarios stand in for hardware the team does not have, so a drift+// between them and the report shapes would silently make them useless.+describe('SETUP_SCENARIOS', () => {+ const names = Object.keys(SETUP_SCENARIOS)++ it('covers the states that need special hardware to reach', () => {+ expect(names).toEqual(+ expect.arrayContaining([+ 'provisioning',+ 'missingLibrary',+ 'gpuUnreachable',+ 'gpuUnused',+ 'metal',+ 'cpuOnly',+ 'brokenEmbedder',+ ])+ )+ })++ it.each(names)('%s reports a complete gpu offload shape', (name) => {+ const { gpu } = SETUP_SCENARIOS[name]+ expect(typeof gpu.backend).toBe('string')+ expect(typeof gpu.gpuExpected).toBe('boolean')+ expect(typeof gpu.engineDeviceCount).toBe('number')+ expect(['ok', 'warning']).toContain(gpu.status)+ })++ it.each(names)('%s reports a complete embedding shape', (name) => {+ expect(['ok', 'warning']).toContain(SETUP_SCENARIOS[name].embedding.status)+ })++ it('names a real backend wherever it claims one', () => {+ for (const name of names) {+ const { backend } = SETUP_SCENARIOS[name].gpu+ if (!backend) continue+ expect(backendGpuFamily(backend), name).not.toBe('unknown')+ }+ })++ it('pairs a missingLibrary reason with the library names', () => {+ for (const name of names) {+ const { gpu } = SETUP_SCENARIOS[name]+ if (gpu.reason !== 'missingLibrary') continue+ expect(gpu.missingLibraries?.length, name).toBeGreaterThan(0)+ }+ })++ it('models Apple Silicon as a macOS backend with no enumerated device', () => {+ const { gpu } = SETUP_SCENARIOS.metal+ expect(backendGpuFamily(gpu.backend)).toBe('metal')+ expect(gpu.engineDeviceCount).toBe(0)+ expect(gpu.gpuExpected).toBe(false)+ })+})diff --git a/web-app/src/lib/backendDependencies.ts b/web-app/src/lib/backendDependencies.tsnew file mode 100644index 000000000..829390d66--- /dev/null+++ b/web-app/src/lib/backendDependencies.ts@@ -0,0 +1,150 @@+/** Maps a raw backend identifier to a human-readable display name. */+export 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+}++export 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.+ */+export 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 }+}+diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 1320f414e..c0d27eca5 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -29,6 +29,8 @@ import {} from '@/lib/webSearchTool'import { useAppState } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'+import { describeEngineError } from '@/lib/engineError'+import { i18n } from '@/i18n/react-i18next-compat'import { ExtensionManager } from '@/lib/extension'import { getLlamacppExtension } from '@/lib/llamacppRouterProps'import {@@ -1206,7 +1208,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Stop from an actual model-load failure.if (error instanceof Error && error.name === 'AbortError') throw errorthrow new Error(- `Failed to create model: ${error instanceof Error ? error.message : JSON.stringify(error)}`+ i18n.t('model-errors:createModelFailed', {+ reason: describeEngineError(error),+ }))}diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.tsnew file mode 100644index 000000000..365dc10cb--- /dev/null+++ b/web-app/src/lib/engineError.ts@@ -0,0 +1,119 @@+import { i18n } from '@/i18n/react-i18next-compat'++/**+ * Mirrors `ErrorCode` in `tauri-plugin-llamacpp/src/error.rs`. The Rust side has+ * a test pinning these exact strings, since they cross the IPC boundary as the+ * contract this file matches on.+ */+export const ENGINE_ERROR_CODES = [+ 'BINARY_NOT_FOUND',+ 'MODEL_FILE_NOT_FOUND',+ 'LIBRARY_PATH_INVALID',+ 'MODEL_LOAD_FAILED',+ 'DRAFT_MODEL_LOAD_FAILED',+ 'MULTIMODAL_PROJECTOR_LOAD_FAILED',+ 'MODEL_ARCH_NOT_SUPPORTED',+ 'MODEL_LOAD_TIMED_OUT',+ 'LLAMA_CPP_PROCESS_ERROR',+ 'MISSING_SHARED_LIBRARY',+ 'GPU_DRIVER_TOO_OLD',+ 'OUT_OF_MEMORY',+ 'INVALID_ARGUMENT',+ 'DEVICE_LIST_PARSE_FAILED',+ 'IO_ERROR',+ 'INTERNAL_ERROR',+] as const++export type EngineErrorCode = (typeof ENGINE_ERROR_CODES)[number]++export interface EngineError {+ code: EngineErrorCode+ message?: string+ /** Raw engine output. Technical, shown only in a details area. */+ details?: string+ missingLibraries?: string[]+}++const KNOWN_CODES: ReadonlySet<string> = new Set(ENGINE_ERROR_CODES)++function readEngineErrorObject(value: unknown): EngineError | undefined {+ if (typeof value !== 'object' || value === null) return undefined++ const record = value as {+ code?: unknown+ message?: unknown+ details?: unknown+ missing_libraries?: unknown+ }+ if (typeof record.code !== 'string' || !KNOWN_CODES.has(record.code)) {+ return undefined+ }++ const missingLibraries = Array.isArray(record.missing_libraries)+ ? record.missing_libraries.filter(+ (lib): lib is string => typeof lib === 'string'+ )+ : undefined++ return {+ code: record.code as EngineErrorCode,+ ...(typeof record.message === 'string' ? { message: record.message } : {}),+ ...(typeof record.details === 'string' ? { details: record.details } : {}),+ ...(missingLibraries?.length ? { missingLibraries } : {}),+ }+}++/**+ * Recovers a structured engine error, including one that an intermediate layer+ * already stringified into an Error message.+ */+export function parseEngineError(error: unknown): EngineError | undefined {+ const direct = readEngineErrorObject(error)+ if (direct) return direct++ const text =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : undefined+ if (!text) return undefined++ const start = text.indexOf('{')+ const end = text.lastIndexOf('}')+ if (start === -1 || end <= start) return undefined++ try {+ return readEngineErrorObject(JSON.parse(text.slice(start, end + 1)))+ } catch {+ return undefined+ }+}++/**+ * A localized, user-facing description of an engine failure. Replaces the raw+ * English the Rust layer produces, and the raw JSON a serialized error used to+ * turn into when it reached a template expecting an Error.+ */+export function describeEngineError(error: unknown): string {+ const engineError = parseEngineError(error)++ if (engineError) {+ const description = i18n.t(`model-errors:engine.${engineError.code}`)+ if (engineError.missingLibraries?.length) {+ return `${description} ${i18n.t('model-errors:engineMissingLibraries', {+ libraries: engineError.missingLibraries.join(', '),+ })}`+ }+ return description+ }++ const fallback =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : ''++ return fallback.trim() || i18n.t('model-errors:engine.unknown')+}diff --git a/web-app/src/lib/gpuBackendMatch.ts b/web-app/src/lib/gpuBackendMatch.tsnew file mode 100644index 000000000..1a785c8e8--- /dev/null+++ b/web-app/src/lib/gpuBackendMatch.ts@@ -0,0 +1,153 @@+/**+ * Cross-checks detected GPU hardware against the llama.cpp backend that is+ * actually installed.+ *+ * The engine's own readiness probe can only answer "does this GPU build see a+ * device". It is silent in the inverse case -- a machine with a discrete GPU+ * running a CPU-only build reports a healthy "running on CPU", which is+ * indistinguishable from a machine that has no GPU at all. That case is the+ * most expensive one to leave undetected, so it is derived here from the two+ * facts the setup checklist already holds.+ */++export type GpuVendor = 'nvidia' | 'amd' | 'intel' | 'unknown'++export type BackendGpuFamily =+ | 'cuda'+ | 'vulkan'+ | 'hip'+ | 'metal'+ | 'cpu'+ | 'unknown'++export interface DetectedGpu {+ name?: string+ vendor?: string+ total_memory?: number+ driver_version?: string+}++export type BackendGpuMatch =+ /** The installed backend can drive at least one detected GPU. */+ | { kind: 'ok' }+ /** No backend is selected yet, so nothing can be concluded. */+ | { kind: 'unknown' }+ /** No GPU present, and a CPU build is the correct choice. */+ | { kind: 'noGpu' }+ /** A GPU is present but the installed build is CPU-only. */+ | { kind: 'gpuUnused'; gpus: DetectedGpu[] }+ /** A GPU build is installed that none of the detected GPUs can run. */+ | { kind: 'vendorMismatch'; family: BackendGpuFamily; gpus: DetectedGpu[] }++const VENDOR_PATTERNS: [GpuVendor, RegExp][] = [+ ['nvidia', /nvidia|geforce|\b[gr]tx\b|quadro|tesla/i],+ ['amd', /\bamd\b|radeon|\bati\b/i],+ ['intel', /intel|\barc\b/i],+]++export function classifyVendor(vendor: string | undefined): GpuVendor {+ if (!vendor) return 'unknown'+ for (const [known, pattern] of VENDOR_PATTERNS) {+ if (pattern.test(vendor)) return known+ }+ return 'unknown'+}++/**+ * Vendor is reported by the PCI id, which comes back as `Unknown (vendor_id: N)`+ * for anything outside the three known ids. Falling back to the device name+ * keeps a rebranded OEM card from being misread as a foreign vendor.+ */+export function gpuVendor(gpu: DetectedGpu): GpuVendor {+ const byVendor = classifyVendor(gpu.vendor)+ if (byVendor !== 'unknown') return byVendor+ return classifyVendor(gpu.name)+}++const FAMILY_MARKERS: [BackendGpuFamily, RegExp][] = [+ ['cuda', /cuda|\bcu\d/i],+ ['vulkan', /vulkan/i],+ ['hip', /\bhip\b|rocm/i],+]++/**+ * An absent backend name means the engine has not finished picking one yet -- on+ * a fresh install that takes a backend download. It must not read as "CPU-only+ * build", which is what made a CUDA install report an idle GPU.+ */+export function backendGpuFamily(backend: string | undefined): BackendGpuFamily {+ const name = backend?.trim()+ if (!name || name === 'none') return 'unknown'+ for (const [family, pattern] of FAMILY_MARKERS) {+ if (pattern.test(name)) return family+ }+ // Metal is compiled into every macOS build and needs no separate runtime, so+ // a macOS backend name with no GPU marker still means GPU-capable.+ if (/^mac|darwin/i.test(name)) return 'metal'+ return 'cpu'+}++/** Vulkan is driver-provided on every modern GPU; CUDA and HIP are vendor-locked. */+export function vendorSupportsFamily(+ vendor: GpuVendor,+ family: BackendGpuFamily+): boolean {+ switch (family) {+ case 'cuda':+ return vendor === 'nvidia'+ case 'hip':+ return vendor === 'amd'+ case 'vulkan':+ case 'metal':+ return true+ case 'cpu':+ case 'unknown':+ return false+ }+}++export function evaluateBackendGpuMatch(+ gpus: DetectedGpu[] | undefined,+ backend: string | undefined+): BackendGpuMatch {+ const detected = gpus ?? []+ const family = backendGpuFamily(backend)++ if (family === 'unknown') return { kind: 'unknown' }++ if (family === 'metal') return { kind: 'ok' }++ if (family === 'cpu') {+ return detected.length > 0+ ? { kind: 'gpuUnused', gpus: detected }+ : { kind: 'noGpu' }+ }++ const vendors = detected.map(gpuVendor)+ if (vendors.some((vendor) => vendorSupportsFamily(vendor, family))) {+ return { kind: 'ok' }+ }++ // Claiming a mismatch requires knowing what the hardware actually is. With+ // no GPU detected, or none whose vendor could be identified, the engine's own+ // verdict is the better evidence -- a false mismatch warning would send users+ // to reinstall a backend that works.+ if (vendors.every((vendor) => vendor === 'unknown')) {+ return { kind: 'ok' }+ }++ return { kind: 'vendorMismatch', family, gpus: detected }+}++/** `NVIDIA GeForce RTX 4090 (24 GB)`, joined for a one-line checklist row. */+export function describeGpus(gpus: DetectedGpu[]): string {+ return gpus+ .map((gpu) => {+ const name = gpu.name?.trim() || gpu.vendor?.trim() || ''+ const gib = gpu.total_memory ? Math.round(gpu.total_memory / 1024) : 0+ if (!name) return gib ? `${gib} GB` : ''+ return gib ? `${name} (${gib} GB)` : name+ })+ .filter(Boolean)+ .join(', ')+}diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex 79154b6fd..882a2a7d0 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -74,6 +74,8 @@ import {getMutualExclusionDrops,getProviderApiType,} from '@/lib/providerCaps'+import { describeEngineError } from '@/lib/engineError'+import { i18n } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'import { useGeneralSetting } from '@/hooks/useGeneralSetting'import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'@@ -913,8 +915,12 @@ export class ModelFactory {}} catch (error) {console.error('Failed to start llamacpp model:', error)+ // A serialized engine error is a plain object, so the previous+ // `instanceof Error` path stringified it into raw JSON for the user.throw new Error(- `Failed to start model: ${error instanceof Error ? error.message : JSON.stringify(error)}`+ i18n.t('model-errors:startModelFailed', {+ reason: describeEngineError(error),+ }))}}@@ -926,7 +932,9 @@ export class ModelFactory {)if (!sessionInfo) {- throw new Error(`No running session found for model: ${modelId}`)+ throw new Error(+ i18n.t('model-errors:noRunningSession', { model: modelId })+ )}const onLlamacppServerError = provider@@ -997,7 +1005,9 @@ export class ModelFactory {} catch (error) {console.error('Failed to start MLX model:', error)throw new Error(- `Failed to start model: ${error instanceof Error ? error.message : JSON.stringify(error)}`+ i18n.t('model-errors:startModelFailed', {+ reason: describeEngineError(error),+ }))}}diff --git a/web-app/src/lib/providerReadiness.ts b/web-app/src/lib/providerReadiness.tsnew file mode 100644index 000000000..f6108815d--- /dev/null+++ b/web-app/src/lib/providerReadiness.ts@@ -0,0 +1,56 @@+import { predefinedProviders } from '@/constants/providers'+import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'++type ModelLike = {+ id: string+ embedding?: boolean+ capabilities?: string[]+}++type ProviderLike = {+ provider: string+ models?: ModelLike[]+ api_key?: string+ api_key_fallbacks?: string[]+}++/** Local engines are usable on models alone; they need no credential. */+const KEYLESS_PREDEFINED_PROVIDERS = ['llamacpp', 'jan']++/**+ * An embedding model cannot answer a message. Jan installs one on its own during+ * first-run setup, so counting it would end onboarding before the user has any+ * model to chat with.+ */+function isChatCapable(model: ModelLike): boolean {+ return !model.embedding && !model.capabilities?.includes('embeddings')+}++/**+ * Whether the user can actually send a message through this provider: a+ * credential for a remote one, or an installed model for a local or custom one.+ * Naming a model is not enough for a remote provider, since nothing can serve it+ * without a key.+ */+export function isProviderUsable(provider: ProviderLike): boolean {+ const hasModels = (provider.models ?? []).some(isChatCapable)++ const isPredefined = predefinedProviders.some(+ (p) => p.provider === provider.provider+ )+ // A custom provider is a user-configured endpoint, so models alone qualify.+ if (!isPredefined) return hasModels++ return (+ providerHasRemoteApiKeys(provider) ||+ (KEYLESS_PREDEFINED_PROVIDERS.includes(provider.provider) && hasModels)+ )+}++/**+ * The gate that decides whether onboarding is still required. Shared so the+ * setup route and the post-setup nudge cannot drift apart.+ */+export function hasUsableProvider(providers: ProviderLike[]): boolean {+ return (providers ?? []).some(isProviderUsable)+}diff --git a/web-app/src/lib/setupModelOptions.ts b/web-app/src/lib/setupModelOptions.tsnew file mode 100644index 000000000..c4a942554--- /dev/null+++ b/web-app/src/lib/setupModelOptions.ts@@ -0,0 +1,28 @@+import type { CatalogModel } from '@/services/models/types'++/**+ * The single model the first-run screen offers, in a shape the download path can+ * consume without knowing where it came from. Anything beyond this model is+ * reached through the Hub rather than duplicated onto the setup screen.+ */+export interface SetupModelOption {+ /** Catalog model name; the Hub route key. */+ modelName: string+ displayName: string+ /** Id of the quant that will be downloaded. */+ modelId: string+ path: string+ fileSize: string+ multimodal: boolean+ mmprojPath?: string+}++/** F16 first, which is the projector quality the Hub publishes for every model. */+export function pickMmproj(model: CatalogModel): string | undefined {+ const projectors = model.mmproj_models ?? []+ if (projectors.length === 0) return undefined+ return (+ projectors.find((p) => p.model_id.toLowerCase() === 'mmproj-f16') ??+ projectors[0]+ ).path+}diff --git a/web-app/src/lib/setupSimulation.ts b/web-app/src/lib/setupSimulation.tsnew file mode 100644index 000000000..c271b23c2--- /dev/null+++ b/web-app/src/lib/setupSimulation.ts@@ -0,0 +1,200 @@+import type {+ EmbeddingModelReport,+ GpuOffloadReport,+} from '@/services/models/types'+import type { DetectedGpu } from '@/lib/gpuBackendMatch'++/**+ * Development-only overrides for the first-run readiness reports.+ *+ * The degraded paths -- a missing CUDA library, an unreachable GPU, a broken+ * embedder, Apple Metal -- each need hardware or a broken install to reach, so+ * without this they ship untested by anyone who does not own the machine.+ *+ * Enable from the devtools console and reload; the names are the keys of+ * SETUP_SCENARIOS below:+ *+ * localStorage.setItem('setup-scenario', 'missingLibrary')+ * localStorage.removeItem('setup-scenario') // back to real probes+ *+ * Inert in a production build: `import.meta.env.DEV` is statically false there,+ * so the whole lookup is dropped.+ */++export interface SetupScenario {+ hardware: { cpu?: { name?: string }; gpus?: DetectedGpu[] } | null+ gpu: GpuOffloadReport+ embedding: EmbeddingModelReport+}++const NVIDIA: DetectedGpu = {+ name: 'NVIDIA GeForce RTX 3090',+ vendor: 'NVIDIA',+ total_memory: 24576,+ driver_version: '550.54.14',+}++const CUDA = 'linux-cuda-13-common_cpus-x64'++export const SETUP_SCENARIOS: Record<string, SetupScenario> = {+ /** Mid-provisioning: the backend is still downloading. */+ provisioning: {+ hardware: { cpu: { name: 'Ryzen 9 7950X' }, gpus: [NVIDIA] },+ gpu: {+ status: 'ok',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ pending: true,+ },+ embedding: { status: 'ok', pending: true },+ },++ /** The reported case: a CUDA build whose GPU libraries are not installed. */+ missingLibrary: {+ hardware: { cpu: { name: 'Ryzen 9 7950X' }, gpus: [NVIDIA] },+ gpu: {+ status: 'warning',+ backend: CUDA,+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'missingLibrary',+ missingLibraries: ['libnccl.so.2', 'libcublas.so.12'],+ error:+ 'libnccl.so.2: cannot open shared object file: No such file or directory',+ },+ embedding: {+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ },+ },++ /** Driver or runtime too old: the library loads but enumerates no device. */+ gpuUnreachable: {+ hardware: { cpu: { name: 'Ryzen 9 7950X' }, gpus: [NVIDIA] },+ gpu: {+ status: 'warning',+ backend: CUDA,+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'runtimeUnreachable',+ error: 'no CUDA-capable device is detected',+ },+ embedding: {+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ },+ },++ /** A discrete GPU sitting idle behind a CPU-only build. */+ gpuUnused: {+ hardware: { cpu: { name: 'Ryzen 9 7950X' }, gpus: [NVIDIA] },+ gpu: {+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ },+ embedding: {+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ },+ },++ /** Apple Silicon: Metal is implicit, so the engine reports no GPU build. */+ metal: {+ hardware: { cpu: { name: 'Apple M3 Max' }, gpus: [] },+ gpu: {+ status: 'ok',+ backend: 'macos-arm64',+ gpuExpected: false,+ engineDeviceCount: 0,+ },+ embedding: {+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ },+ },++ /** No GPU at all: the badge should say CPU without implying a fault. */+ cpuOnly: {+ hardware: { cpu: { name: 'Intel Core i5-10400' }, gpus: [] },+ gpu: {+ status: 'ok',+ backend: 'linux-common_cpus-x64',+ gpuExpected: false,+ engineDeviceCount: 0,+ },+ embedding: {+ status: 'ok',+ modelId: 'sentence-transformer-mini',+ dimension: 384,+ },+ },++ /** The embedder installed but cannot produce a usable vector. */+ brokenEmbedder: {+ hardware: { cpu: { name: 'Ryzen 9 7950X' }, gpus: [NVIDIA] },+ gpu: {+ status: 'ok',+ backend: CUDA,+ gpuExpected: true,+ engineDeviceCount: 1,+ },+ embedding: {+ status: 'warning',+ modelId: 'sentence-transformer-mini',+ problem: 'degenerate',+ dimension: 384,+ error: 'embedding vector was all zeroes (check the pooling type)',+ },+ },++ /** Every check unhappy at once, to see how the page prioritises. */+ everythingBroken: {+ hardware: null,+ gpu: {+ status: 'warning',+ backend: CUDA,+ gpuExpected: true,+ engineDeviceCount: 0,+ reason: 'missingLibrary',+ missingLibraries: ['libcudart.so.13'],+ error: 'libcudart.so.13: cannot open shared object file',+ },+ embedding: {+ status: 'warning',+ modelId: 'sentence-transformer-mini',+ problem: 'missing',+ error: 'llama.cpp router is not running. Please restart the app.',+ },+ },+}++export const SETUP_SCENARIO_STORAGE_KEY = 'setup-scenario'++/** The active scenario, or undefined in a production build. */+export function activeSetupScenario(): SetupScenario | undefined {+ if (!import.meta.env.DEV) return undefined+ try {+ const name = localStorage.getItem(SETUP_SCENARIO_STORAGE_KEY)+ if (!name) return undefined+ const scenario = SETUP_SCENARIOS[name]+ if (!scenario) {+ console.warn(+ `[setup] Unknown scenario "${name}". Available: ${Object.keys(+ SETUP_SCENARIOS+ ).join(', ')}`+ )+ return undefined+ }+ console.info(`[setup] Simulating the "${name}" scenario.`)+ return scenario+ } catch {+ return undefined+ }+}diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsnew file mode 100644index 000000000..468bcdb31--- /dev/null+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -0,0 +1,149 @@+import { describe, it, expect } from 'vitest'+import { readFileSync, readdirSync, statSync } from 'node:fs'+import { join, resolve } from 'node:path'++const SRC = resolve(__dirname, '../..')+const LOCALE_DIR = resolve(__dirname, '../en')++/** Namespaces whose keys are asserted to exist. */+const GUARDED_NAMESPACES = ['setup', 'model-errors']++/**+ * Keys the code composes at runtime (`t(`setup:${stage.messageKey}`)`), which a+ * static scan cannot see. Listed explicitly so a renamed key still fails here+ * rather than silently rendering the key to the user.+ */+const DYNAMIC_KEYS: Record<string, string[]> = {+ setup: [+ 'stageModel',+ 'stageConsent',+ 'checkModelResolving',+ 'checkModelWaiting',+ 'checkModelDownloading',+ 'checkModelReady',+ 'checkSystemGpu',+ 'checkSystemGpuNoDriver',+ 'checkSystemCpuOnly',+ 'checkSystemFailed',+ 'checkEnginePreparing',+ 'checkEngineGpu',+ 'checkEngineCpu',+ 'checkEngineGpuUnused',+ 'checkEngineVendorMismatch',+ 'checkEngineNoGpuHardware',+ 'checkEngineRuntimeUnreachable',+ 'checkEngineMissingLibrary',+ 'checkEngineProbeFailed',+ 'checkEngineUnavailable',+ 'checkSearchPreparing',+ 'checkSearchReady',+ 'checkSearchNoVector',+ 'checkSearchInvalidVector',+ 'checkSearchProbeFailed',+ 'checkSearchUnavailable',+ ],+ 'model-errors': [+ 'engine.unknown',+ 'engine.BINARY_NOT_FOUND',+ 'engine.MODEL_FILE_NOT_FOUND',+ 'engine.LIBRARY_PATH_INVALID',+ 'engine.MODEL_LOAD_FAILED',+ 'engine.DRAFT_MODEL_LOAD_FAILED',+ 'engine.MULTIMODAL_PROJECTOR_LOAD_FAILED',+ 'engine.MODEL_ARCH_NOT_SUPPORTED',+ 'engine.MODEL_LOAD_TIMED_OUT',+ 'engine.LLAMA_CPP_PROCESS_ERROR',+ 'engine.MISSING_SHARED_LIBRARY',+ 'engine.GPU_DRIVER_TOO_OLD',+ 'engine.OUT_OF_MEMORY',+ 'engine.INVALID_ARGUMENT',+ 'engine.DEVICE_LIST_PARSE_FAILED',+ 'engine.IO_ERROR',+ 'engine.INTERNAL_ERROR',+ ],+}++function sourceFiles(dir: string, acc: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ if (entry === 'node_modules' || entry === 'locales') continue+ const full = join(dir, entry)+ if (statSync(full).isDirectory()) {+ sourceFiles(full, acc)+ } else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) {+ acc.push(full)+ }+ }+ return acc+}++function loadNamespace(namespace: string): Record<string, unknown> {+ return JSON.parse(readFileSync(join(LOCALE_DIR, `${namespace}.json`), 'utf8'))+}++function resolveKey(bundle: Record<string, unknown>, key: string): boolean {+ return (+ key.split('.').reduce<unknown>((node, part) => {+ if (node && typeof node === 'object' && part in node) {+ return (node as Record<string, unknown>)[part]+ }+ return undefined+ }, bundle) !== undefined+ )+}++/** Literal `'<ns>:<key>'` occurrences, which is how keys are normally written. */+function referencedKeys(): Map<string, Set<string>> {+ const found = new Map<string, Set<string>>(+ GUARDED_NAMESPACES.map((ns) => [ns, new Set<string>()])+ )+ const pattern = new RegExp(+ `['"\`](${GUARDED_NAMESPACES.join('|')}):([A-Za-z0-9_.]+)['"\`]`,+ 'g'+ )++ for (const file of sourceFiles(SRC)) {+ const content = readFileSync(file, 'utf8')+ for (const match of content.matchAll(pattern)) {+ found.get(match[1])!.add(match[2])+ }+ }+ return found+}++describe('en locale keys', () => {+ it.each(GUARDED_NAMESPACES)(+ 'has every statically referenced %s key',+ (namespace) => {+ const bundle = loadNamespace(namespace)+ const missing = [...referencedKeys().get(namespace)!].filter(+ (key) => !resolveKey(bundle, key)+ )+ expect(missing, `missing from ${namespace}.json`).toEqual([])+ }+ )++ it.each(Object.keys(DYNAMIC_KEYS))(+ 'has every runtime-composed %s key',+ (namespace) => {+ const bundle = loadNamespace(namespace)+ const missing = DYNAMIC_KEYS[namespace].filter(+ (key) => !resolveKey(bundle, key)+ )+ expect(missing, `missing from ${namespace}.json`).toEqual([])+ }+ )++ // A key left in the file but referenced nowhere is the state setup.json was+ // in before this work: ten strings kept in every locale for a screen that no+ // longer existed.+ it('has no unreferenced setup keys', () => {+ const bundle = loadNamespace('setup')+ const referenced = referencedKeys().get('setup')!+ const dynamic = new Set(DYNAMIC_KEYS.setup)++ const unused = Object.keys(bundle).filter(+ (key) => !referenced.has(key) && !dynamic.has(key)+ )+ expect(unused).toEqual([])+ })+})diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex e7edeb56b..74ee66a7f 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -37,6 +37,8 @@"hub": "Hub","helpSupport": "Help & Support","helpUsImproveJan": "Help Us Improve Jan",+ "analyticsConsentDetail": "We collect anonymous data to understand feature usage. Your chats and personal information are never tracked. You can change this anytime in Settings > Privacy.",+ "analyticsConsentQuestion": "Would you like to help us to improve Jan?","unstarAll": "Unstar All","unstar": "Unstar","deleteAll": "Delete All",@@ -443,6 +445,19 @@"title": "Download Failed","description": "{{item}} download failed"},+ "openSettings": "Open Settings",+ "downloadTokenRequired": {+ "title": "Hugging Face token required",+ "description": "This model requires a Hugging Face access token. Add your token in Settings and retry."+ },+ "downloadLicenseRequired": {+ "title": "Accept model license on Hugging Face",+ "description": "You must accept the model's license on its Hugging Face page before downloading."+ },+ "downloadRateLimited": {+ "title": "Rate limited by Hugging Face",+ "description": "You have been rate-limited. Adding a token can increase rate limits. Please try again later."+ },"modelValidationStarted": {"title": "Validating Model","description": "Downloaded model \"{{modelId}}\" successfully. Verifying integrity..."diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.jsonindex 5377baae5..92bf79bbb 100644--- a/web-app/src/locales/en/model-errors.json+++ b/web-app/src/locales/en/model-errors.json@@ -6,5 +6,33 @@"increaseContextSize": "Increase Context Size","lastRequestOverflowed": "Last request overflowed the context window.","contextOverflowDetail": "This request needed {{request}} tokens, but the model’s context window holds only {{context}}.",- "contextOverflowGeneric": "The request exceeds the available context size."+ "contextOverflowGeneric": "The request exceeds the available context size.",+ "engine": {+ "unknown": "The model engine reported an unexpected error.",+ "BINARY_NOT_FOUND": "The engine program is missing. Reinstalling the engine from Settings should restore it.",+ "MODEL_FILE_NOT_FOUND": "The model file could not be found. It may have been moved or deleted.",+ "LIBRARY_PATH_INVALID": "The engine's library folder is invalid. Reinstalling the engine from Settings should restore it.",+ "MODEL_LOAD_FAILED": "The model could not be loaded.",+ "DRAFT_MODEL_LOAD_FAILED": "The draft model could not be loaded. Turning off speculative decoding will let the main model run.",+ "MULTIMODAL_PROJECTOR_LOAD_FAILED": "The vision component of this model could not be loaded, so images will not work.",+ "MODEL_ARCH_NOT_SUPPORTED": "This model's architecture is not supported by the current engine. Updating the engine from Settings may add support.",+ "MODEL_LOAD_TIMED_OUT": "The model took too long to load and was stopped. A smaller model or a smaller context size usually helps.",+ "LLAMA_CPP_PROCESS_ERROR": "The model process stopped unexpectedly.",+ "MISSING_SHARED_LIBRARY": "A library the engine needs is missing, so it cannot start.",+ "GPU_DRIVER_TOO_OLD": "Your GPU driver is too old for this engine. Updating the driver, or switching to the CPU engine in Settings, will fix this.",+ "OUT_OF_MEMORY": "There is not enough memory to run this model. A smaller model or a smaller context size usually helps.",+ "INVALID_ARGUMENT": "One of the model's settings is not valid.",+ "DEVICE_LIST_PARSE_FAILED": "Jan could not read the list of available devices from the engine.",+ "IO_ERROR": "A file could not be read or written while starting the model.",+ "INTERNAL_ERROR": "Something went wrong inside Jan while starting the model."+ },+ "engineMissingLibraries": "Missing: {{libraries}}",+ "startModelFailed": "Failed to start model: {{reason}}",+ "createModelFailed": "Failed to create model: {{reason}}",+ "noRunningSession": "No running session found for model: {{model}}",+ "serverPortOccupied": "Port has been occupied",+ "serverPortOccupiedDescription": "Port {{port}} is already in use. Please try a different port.",+ "serverInvalidModelPath": "Invalid or inaccessible model path",+ "serverStartModelFailed": "Failed to start model",+ "serverStartFailed": "Failed to start server"}diff --git a/web-app/src/locales/en/setup.json b/web-app/src/locales/en/setup.jsonindex 899652a2a..6faf669db 100644--- a/web-app/src/locales/en/setup.json+++ b/web-app/src/locales/en/setup.json@@ -1,13 +1,54 @@{- "welcome": "Welcome to Jan",- "description": "To get started, quickly launch with Jan Model or choose to set up your own local or remote provider",- "descriptionWeb": "To get started, you'll need to connect to a cloud model using an API key",- "quickStart": "Quick start with Jan Model",- "quickStartDescription": "No setup needed",+ "description": "Download the recommended model to start chatting, or browse the Hub for another one.","quickStartFailed": "Something went wrong. Please try again.",- "downloading": "Downloading Jan Model...",- "downloadingDescription": "Please wait while we download the model. This may take a few minutes.",- "orDivider": "or",- "localModel": "Set up local model",- "remoteProvider": "Set up remote provider"-}\ No newline at end of file+ "exploreHub": "Browse other models in the Hub",+ "download": "Download",+ "modelInstalled": "Installed",+ "capabilityGeneral": "General",+ "capabilityMultimodal": "Multimodal",+ "fallbackModelName": "Jan Model",+ "stageModel": "Your first model",+ "checkModelResolving": "Finding the recommended model...",+ "checkModelWaiting": "{{model}} ({{size}}) ready to download",+ "checkModelDownloading": "Downloading {{model}}...",+ "checkModelReady": "{{model}} is ready",+ "stageChecking": "Checking...",+ "checkSystemGpu": "{{gpus}}, driver {{driver}}",+ "checkSystemGpuNoDriver": "{{gpus}}",+ "checkSystemCpuOnly": "{{cpu}}, no GPU detected",+ "checkSystemFailed": "Could not read hardware details",+ "checkEnginePreparing": "Downloading and setting up the inference engine...",+ "checkEngineGpu": "{{backend}}",+ "checkEngineCpu": "{{backend}}, running on CPU",+ "checkEngineGpuUnused": "{{backend}} is a CPU-only build, so {{gpus}} will sit idle. Pick a GPU backend in Settings to use it.",+ "checkEngineVendorMismatch": "{{backend}} needs an {{vendor}} GPU, but Jan found {{gpus}}. Jan will run on CPU.",+ "checkEngineNoGpuHardware": "{{backend}} is a GPU build, but no GPU was found. Jan will run on CPU, which is slower.",+ "checkEngineRuntimeUnreachable": "{{backend}} cannot reach your GPU, so Jan will run on CPU. This usually means the GPU driver or runtime needs updating.",+ "checkEngineMissingLibrary": "{{backend}} cannot start because a required library is missing ({{libraries}}), so Jan will run on CPU.",+ "checkEngineProbeFailed": "Could not confirm the engine can use your GPU",+ "checkEngineUnavailable": "This engine build cannot report GPU status",+ "checkSearchPreparing": "Waiting for the engine before checking the embedding model...",+ "checkSearchReady": "{{model}}, {{dimension}} dimensions",+ "checkSearchNoVector": "The embedding model returned no result, so file search will not work yet",+ "checkSearchInvalidVector": "The embedding model returned an unusable result, so file search may return nothing",+ "checkSearchProbeFailed": "Could not verify the embedding model",+ "checkSearchUnavailable": "This engine build cannot verify the embedding model",+ "showDetails": "Show details",+ "hideDetails": "Hide details",+ "continueAnyway": "Continue",+ "retryChecks": "Re-run checks",+ "stepCounter": "Step {{current}} of {{total}}",+ "stageConsent": "Help improve Jan",+ "skipStep": "Skip for now",+ "welcomeTitle": "Jan needs to set up on your system",+ "welcomeBody": "This takes a few minutes: Jan downloads its inference engine and a small model for file search. You can keep using your computer while it runs.",+ "startSetup": "Let's start",+ "stageSetup": "Setting up llama.cpp",+ "badgeGpu": "Will use your GPU",+ "badgeCpu": "Will run on CPU",+ "badgeGpuUnknown": "Checking GPU support...",+ "otherWarnings": "{{count}} other checks also need attention.",+ "continueStep": "Continue",+ "stageSetupDone": "Engine ready",+ "setupDoneBody": "Jan will run local models with llama.cpp."+}diff --git a/web-app/src/providers/DownloadEventListener.tsx b/web-app/src/providers/DownloadEventListener.tsxnew file mode 100644index 000000000..5b4bb28d9--- /dev/null+++ b/web-app/src/providers/DownloadEventListener.tsx@@ -0,0 +1,10 @@+import { useDownloadEvents } from '@/hooks/useDownloadEvents'++/**+ * Keeps the download store fed for the whole app lifetime. Mounted at the root+ * rather than beside the download popover, which is not present on every screen.+ */+export function DownloadEventListener() {+ useDownloadEvents()+ return null+}diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex ebc48d00b..52bd54bd3 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -12,9 +12,8 @@ import { route } from '@/constants/routes'import { ExtensionProvider } from '@/providers/ExtensionProvider'import { ToasterProvider } from '@/providers/ToasterProvider'import { useAnalytic } from '@/hooks/useAnalytic'+import { useIsOnboarding } from '@/hooks/useIsOnboarding'import { PromptAnalytic } from '@/containers/analytics/PromptAnalytic'-import { useJanModelPrompt } from '@/hooks/useJanModelPrompt'-import { PromptJanModel } from '@/containers/PromptJanModel'import { AnalyticProvider } from '@/providers/AnalyticProvider'import { useLeftPanel } from '@/hooks/useLeftPanel'import { TranslationProvider } from '@/i18n/TranslationContext'@@ -22,6 +21,7 @@ import OutOfContextPromiseModal from '@/containers/dialogs/OutOfContextDialog'import AttachmentIngestionDialog from '@/containers/dialogs/AttachmentIngestionDialog'import GlobalError from '@/containers/GlobalError'import { GlobalEventHandler } from '@/providers/GlobalEventHandler'+import { DownloadEventListener } from '@/providers/DownloadEventListener'import { ServiceHubProvider } from '@/providers/ServiceHubProvider'import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'import { LeftSidebar } from '@/components/left-sidebar'@@ -39,7 +39,9 @@ export const Route = createRootRoute({const AppLayout = () => {const { productAnalyticPrompt } = useAnalytic()- const { showJanModelPrompt } = useJanModelPrompt()+ // The setup screen is the only onboarding surface: everything below that would+ // otherwise stack on top of it is deferred until it is done.+ const isOnboarding = useIsOnboarding()const {open: isLeftPanelOpen,setLeftPanel,@@ -69,7 +71,7 @@ const AppLayout = () => {/>)}<DialogAppUpdater />- <BackendUpdater />+ {!isOnboarding && <BackendUpdater />}<LeftSidebar /><SidebarInset><div className="bg-neutral-50 dark:bg-background size-full">@@ -77,8 +79,7 @@ const AppLayout = () => {</div></SidebarInset>- {productAnalyticPrompt && <PromptAnalytic />}- {showJanModelPrompt && <PromptJanModel />}+ {productAnalyticPrompt && !isOnboarding && <PromptAnalytic />}</SidebarProvider></div>)@@ -123,6 +124,7 @@ function RootLayout() {<ExtensionProvider><DataProvider /><GlobalEventHandler />+ <DownloadEventListener />{IS_LOGS_ROUTE ? <LogsLayout /> : <AppLayout />}</ExtensionProvider>{/* <TanStackRouterDevtools position="bottom-right" /> */}diff --git a/web-app/src/routes/__tests__/__root.test.tsx b/web-app/src/routes/__tests__/__root.test.tsxindex 7ef6a8857..993aa5dcf 100644--- a/web-app/src/routes/__tests__/__root.test.tsx+++ b/web-app/src/routes/__tests__/__root.test.tsx@@ -6,7 +6,7 @@ import React from 'react'const h = vi.hoisted(() => ({productAnalyticPrompt: false,- showJanModelPrompt: false,+ isOnboarding: false,leftPanelOpen: true,sidebarWidth: 260,setLeftPanel: vi.fn(),@@ -53,6 +53,9 @@ vi.mock('@/providers/AnalyticProvider', () => ({vi.mock('@/providers/GlobalEventHandler', () => ({GlobalEventHandler: () => <div data-testid="global-event" />,}))+vi.mock('@/providers/DownloadEventListener', () => ({+ DownloadEventListener: () => <div data-testid="download-events" />,+}))vi.mock('@/providers/ServiceHubProvider', () => ({ServiceHubProvider: ({ children }: any) => (<div data-testid="service-hub">{children}</div>@@ -85,9 +88,6 @@ vi.mock('@/containers/dialogs/ErrorDialog', () => ({vi.mock('@/containers/analytics/PromptAnalytic', () => ({PromptAnalytic: () => <div data-testid="prompt-analytic" />,}))-vi.mock('@/containers/PromptJanModel', () => ({- PromptJanModel: () => <div data-testid="prompt-jan" />,-}))vi.mock('@/containers/GlobalError', () => ({default: ({ error }: any) => <div data-testid="global-error">{error?.message}</div>,}))@@ -112,8 +112,8 @@ vi.mock('@/components/ui/sidebar', () => ({vi.mock('@/hooks/useAnalytic', () => ({useAnalytic: () => ({ productAnalyticPrompt: h.productAnalyticPrompt }),}))-vi.mock('@/hooks/useJanModelPrompt', () => ({- useJanModelPrompt: () => ({ showJanModelPrompt: h.showJanModelPrompt }),+vi.mock('@/hooks/useIsOnboarding', () => ({+ useIsOnboarding: () => h.isOnboarding,}))vi.mock('@/hooks/useLeftPanel', () => ({useLeftPanel: () => ({@@ -143,7 +143,7 @@ describe('__root route', () => {beforeEach(() => {vi.clearAllMocks()h.productAnalyticPrompt = false- h.showJanModelPrompt = false+ h.isOnboarding = false// reset document statedocument.body.className = ''const loader = document.getElementById('initial-loader')@@ -176,24 +176,36 @@ describe('__root route', () => {expect(screen.getByTestId('backend-updater')).toBeInTheDocument()})+ // Mounted here rather than beside the download popover, which is absent on+ // some screens -- including first-run setup.+ it('listens for download events for the whole app lifetime', () => {+ renderComponent()+ expect(screen.getByTestId('download-events')).toBeInTheDocument()+ })+it('renders PromptAnalytic when productAnalyticPrompt is true', () => {h.productAnalyticPrompt = truerenderComponent()expect(screen.getByTestId('prompt-analytic')).toBeInTheDocument()})- it('does not render PromptAnalytic when productAnalyticPrompt is false', () => {- h.productAnalyticPrompt = false+ // The setup screen is the single onboarding surface; these would otherwise+ // stack on top of it asking for things the wizard already covers.+ it('defers the analytics prompt and backend updater while onboarding', () => {+ h.isOnboarding = true+ h.productAnalyticPrompt = truerenderComponent()expect(screen.queryByTestId('prompt-analytic')).not.toBeInTheDocument()+ expect(screen.queryByTestId('backend-updater')).not.toBeInTheDocument()})- it('renders PromptJanModel when showJanModelPrompt is true', () => {- h.showJanModelPrompt = true+ it('does not render PromptAnalytic when productAnalyticPrompt is false', () => {+ h.productAnalyticPrompt = falserenderComponent()- expect(screen.getByTestId('prompt-jan')).toBeInTheDocument()+ expect(screen.queryByTestId('prompt-analytic')).not.toBeInTheDocument()})+it('uses LogsLayout on /logs path (no sidebar)', () => {window.history.pushState({}, '', '/logs')renderComponent()diff --git a/web-app/src/routes/index.tsx b/web-app/src/routes/index.tsxindex 6f6026d70..4a6b5509c 100644--- a/web-app/src/routes/index.tsx+++ b/web-app/src/routes/index.tsx@@ -9,8 +9,7 @@ import { cn } from '@/lib/utils'import { useModelProvider } from '@/hooks/useModelProvider'import SetupScreen from '@/containers/SetupScreen'import { route } from '@/constants/routes'-import { predefinedProviders } from '@/constants/providers'-import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'+import { hasUsableProvider } from '@/lib/providerReadiness'type ThreadModel = {id: string@@ -43,26 +42,7 @@ function Index() {const { setCurrentThreadId } = useThreads()useTools()- // Conditional to check if there are any valid providers- // required min 1 api_key or 1 model in llama.cpp or jan provider- // Custom providers (not in predefinedProviders) don't require api_key but need models- const hasValidProviders = providers.some((provider) => {- const isPredefinedProvider = predefinedProviders.some(- (p) => p.provider === provider.provider- )-- // Custom providers don't need API key validation but must have models- if (!isPredefinedProvider) {- return provider.models.length > 0- }-- // Predefined providers need either API key or models (for llamacpp/jan)- return (- providerHasRemoteApiKeys(provider) ||- (provider.provider === 'llamacpp' && provider.models.length) ||- (provider.provider === 'jan' && provider.models.length)- )- })+ const hasValidProviders = hasUsableProvider(providers)useEffect(() => {setCurrentThreadId(undefined)diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsxindex a3a30f94b..e3ad61612 100644--- a/web-app/src/routes/settings/local-api-server.tsx+++ b/web-app/src/routes/settings/local-api-server.tsx@@ -191,23 +191,25 @@ function LocalAPIServerContent() {// Port-related errors (highest priority)if (errorMsg.includes('Address already in use')) {- toast.error('Port has been occupied', {- description: `Port ${serverPort} is already in use. Please try a different port.`,+ toast.error(t('model-errors:serverPortOccupied'), {+ description: t('model-errors:serverPortOccupiedDescription', {+ port: serverPort,+ }),})}// Model-related errorselse if (errorMsg.includes('Invalid or inaccessible model path')) {- toast.error('Invalid or inaccessible model path', {+ toast.error(t('model-errors:serverInvalidModelPath'), {description: errorMsg,})} else if (errorMsg.includes('model')) {- toast.error('Failed to start model', {+ toast.error(t('model-errors:serverStartModelFailed'), {description: errorMsg,})}// Generic server errorselse {- toast.error('Failed to start server', {+ toast.error(t('model-errors:serverStartFailed'), {description: errorMsg,})}diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex 231767702..cebc53cc4 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -22,6 +22,8 @@ import type {HuggingFaceRepo,CatalogModel,ModelValidationResult,+ EmbeddingModelReport,+ GpuOffloadReport,} from './types'import {extractToolContextFromContent,@@ -668,6 +670,65 @@ export class DefaultModelsService implements ModelsService {}}+ async verifyEmbeddingModel(): Promise<EmbeddingModelReport> {+ try {+ const engine = this.getEngine('llamacpp') as AIEngine & {+ verifyEmbeddingModel?: () => Promise<EmbeddingModelReport>+ }+ if (engine && typeof engine.verifyEmbeddingModel === 'function') {+ return await engine.verifyEmbeddingModel()+ }+ return { status: 'warning', unavailable: true }+ } catch (error) {+ return {+ status: 'warning',+ error: error instanceof Error ? error.message : String(error),+ }+ }+ }++ /**+ * Asks the local engine to begin its first-run provisioning (backend download,+ * router start, embedding model). Deliberately fire-and-forget from the+ * caller's point of view: progress is reported by the readiness checks, and a+ * failure here must not stop the setup screen from advancing.+ */+ async startEngineSetup(): Promise<void> {+ try {+ const engine = this.getEngine('llamacpp') as AIEngine & {+ startFirstRunSetup?: () => Promise<void>+ }+ if (engine && typeof engine.startFirstRunSetup === 'function') {+ await engine.startFirstRunSetup()+ }+ } catch (error) {+ console.warn('Failed to start engine setup:', error)+ }+ }++ async verifyGpuOffload(): Promise<GpuOffloadReport> {+ const unknown: GpuOffloadReport = {+ status: 'warning',+ backend: '',+ gpuExpected: false,+ engineDeviceCount: 0,+ }+ try {+ const engine = this.getEngine('llamacpp') as AIEngine & {+ verifyGpuOffload?: () => Promise<GpuOffloadReport>+ }+ if (engine && typeof engine.verifyGpuOffload === 'function') {+ return await engine.verifyGpuOffload()+ }+ return { ...unknown, unavailable: true }+ } catch (error) {+ return {+ ...unknown,+ error: error instanceof Error ? error.message : String(error),+ }+ }+ }+async validateGgufFile(filePath: string): Promise<ModelValidationResult> {try {const engine = this.getEngine('llamacpp') as AIEngine & {diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex 98be35fbc..2186c91bc 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -185,4 +185,48 @@ export interface ModelsService {): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY'>validateGgufFile(filePath: string): Promise<ModelValidationResult>getTokensCount(modelId: string, messages: ThreadMessage[]): Promise<number>+ startEngineSetup(): Promise<void>+ verifyEmbeddingModel(): Promise<EmbeddingModelReport>+ verifyGpuOffload(): Promise<GpuOffloadReport>+}++// Mirrors the llamacpp extension's readiness module across the extension+// boundary, the same way DeviceList is redeclared for the hardware service.+export type EmbeddingVectorProblem =+ | 'missing'+ | 'empty'+ | 'nonFinite'+ | 'degenerate'++export type GpuOffloadReason =+ | 'noGpuHardware'+ | 'runtimeUnreachable'+ | 'missingLibrary'++interface ReadinessReport {+ status: 'ok' | 'warning'+ /** Raw technical detail for a disclosure area; never translated. */+ error?: string+ /** The engine build cannot run this check at all. */+ unavailable?: boolean+ /**+ * The engine has not finished its own setup, so nothing was concluded. Distinct+ * from `unavailable`: this one resolves on its own.+ */+ pending?: boolean+}++export interface EmbeddingModelReport extends ReadinessReport {+ modelId?: string+ dimension?: number+ problem?: EmbeddingVectorProblem+}++export interface GpuOffloadReport extends ReadinessReport {+ backend: string+ gpuExpected: boolean+ engineDeviceCount: number+ reason?: GpuOffloadReason+ /** Set only for `missingLibrary`; names are not translatable. */+ missingLibraries?: string[]}