Skip to content

armgit / jan

Public Imported from GitHub
0

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

fix(llamacpp): restart the engine when its GPU set changed, on Refresh and before a load (#9347, part 1) (#9348)

Thinh Le8c0615520239
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index f6d2da8c4..8d6b2c14a 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -7,92 +7,95 @@
*/
import {
- AIEngine,
- type EmbeddingEngine,
- getJanDataFolderPath,
- fs,
- joinPath,
- modelInfo,
- SessionInfo,
- UnloadResult,
- chatCompletion,
- chatCompletionChunk,
- ImportOptions,
- type SpecDraftKind,
- chatCompletionRequest,
- events,
- AppEvent,
- DownloadEvent,
- chatCompletionRequestMessage,
- SettingComponentProps,
- DropdownComponentProps,
- logger,
+ AIEngine,
+ type EmbeddingEngine,
+ getJanDataFolderPath,
+ fs,
+ joinPath,
+ modelInfo,
+ SessionInfo,
+ UnloadResult,
+ chatCompletion,
+ chatCompletionChunk,
+ ImportOptions,
+ type SpecDraftKind,
+ chatCompletionRequest,
+ events,
+ AppEvent,
+ DownloadEvent,
+ chatCompletionRequestMessage,
+ SettingComponentProps,
+ DropdownComponentProps,
+ logger,
} from '@janhq/core'
import {
- readSettingsFile,
- writeSettingsFile,
- settingsFileExists,
+ readSettingsFile,
+ writeSettingsFile,
+ settingsFileExists,
} from './settings-store'
import { listen } from '@tauri-apps/api/event'
import { invoke } from '@tauri-apps/api/core'
import {
- getProxyConfig,
- buildEmbedBatches,
- mergeEmbedResponses,
- detectEmbeddingFromGgufMeta,
- detectMtpLayersFromGgufMeta,
- resolveSpecDraftKind,
- detectTemplateKwargsFromChatTemplate,
- getDefaultEmbeddingModelId,
- setDefaultEmbeddingModelId,
- type EmbedBatchResult,
+ getProxyConfig,
+ buildEmbedBatches,
+ mergeEmbedResponses,
+ detectEmbeddingFromGgufMeta,
+ detectMtpLayersFromGgufMeta,
+ resolveSpecDraftKind,
+ detectTemplateKwargsFromChatTemplate,
+ getDefaultEmbeddingModelId,
+ setDefaultEmbeddingModelId,
+ type EmbedBatchResult,
} from './util'
import { loopbackFetch } from './loopback-fetch'
import {
- generatePreset,
- threadCacheDir,
- DEFAULT_EMBEDDING_UBATCH,
+ generatePreset,
+ threadCacheDir,
+ DEFAULT_EMBEDDING_UBATCH,
} from './preset'
import {
- evaluateEmbeddingVector,
- evaluateGpuOffload,
- backendFromDeviceIds,
- type EmbeddingVectorProblem,
- type GpuOffloadCheck,
- type ReadinessStatus,
+ evaluateEmbeddingVector,
+ evaluateGpuOffload,
+ backendFromDeviceIds,
+ type EmbeddingVectorProblem,
+ type GpuOffloadCheck,
+ type ReadinessStatus,
} from './readiness'
import {
- getBackendSetting,
- setBackendSetting,
- removeBackendSetting,
+ getBackendSetting,
+ setBackendSetting,
+ removeBackendSetting,
} from './backend-settings'
import { basename } from '@tauri-apps/api/path'
import {
- asI32,
- loadLlamaModel,
- readGgufMetadata,
- findGgufTensors,
- isModelSupported,
- unloadLlamaModel,
- startEngine,
- eraseThreadSlotState,
- getEngineInfo as pluginGetEngineInfo,
- getEngineVersion as pluginGetEngineVersion,
- reloadEngineModels,
- engineDevices,
- generateApiKey as pluginGenerateApiKey,
- findSessionByModel as pluginFindSessionByModel,
- ensureSessionReady as pluginEnsureSessionReady,
- getLoadedModels as pluginGetLoadedModels,
- LlamacppConfig,
- DownloadItem,
- ModelConfig,
- TemplateKwarg,
- EmbeddingResponse,
- ModelProps,
- DeviceList,
- EngineVersion,
+ asI32,
+ loadLlamaModel,
+ readGgufMetadata,
+ findGgufTensors,
+ isModelSupported,
+ unloadLlamaModel,
+ startEngine,
+ stopEngine,
+ beginEngineRestart,
+ endEngineRestart,
+ eraseThreadSlotState,
+ getEngineInfo as pluginGetEngineInfo,
+ getEngineVersion as pluginGetEngineVersion,
+ reloadEngineModels,
+ engineDevices,
+ generateApiKey as pluginGenerateApiKey,
+ findSessionByModel as pluginFindSessionByModel,
+ ensureSessionReady as pluginEnsureSessionReady,
+ getLoadedModels as pluginGetLoadedModels,
+ LlamacppConfig,
+ DownloadItem,
+ ModelConfig,
+ TemplateKwarg,
+ EmbeddingResponse,
+ ModelProps,
+ DeviceList,
+ EngineVersion,
} from '@janhq/tauri-plugin-llamacpp-api'
import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
@@ -109,48 +112,48 @@ const TEMPLATE_KWARGS_CHECK_VERSION = 1
// value is read; cosmetic / process-only keys (models_max, timeout,
// llamacpp_env) are handled separately or not at all.
const PRESET_AFFECTING_KEYS = new Set<string>([
- 'fit',
- 'fit_target',
- 'fit_ctx',
- 'flash_attn',
- 'cache_type_k',
- 'cache_type_v',
- 'parallel',
- 'cont_batching',
- 'threads',
- 'threads_batch',
- 'n_predict',
- 'batch_size',
- 'ubatch_size',
- 'n_cpu_moe',
- 'n_cpu_ffn',
- 'no_kv_offload',
- 'device',
- 'split_mode',
- 'main_gpu',
- 'no_mmap',
- 'mlock',
- 'rope_scaling',
- 'rope_freq_base',
- 'rope_freq_scale',
- 'ctx_shift',
- 'cache_ram',
- // persist_thread_cache decides whether slot-save-path is emitted at all;
- // thread_cache_size is not a preset key but rides the same reload, which
- // carries it to the worker (see reload_engine_models).
- 'persist_thread_cache',
- 'thread_cache_size',
- 'cache_reuse',
- 'swa_full',
- 'keep',
- 'kv_unified',
- 'tensor_split',
- 'no_op_offload',
- 'ctx_checkpoints',
- 'checkpoint_min_step',
- 'kv_unified_per_slot',
- 'reasoning_preserve',
- 'lazy_mode',
+ 'fit',
+ 'fit_target',
+ 'fit_ctx',
+ 'flash_attn',
+ 'cache_type_k',
+ 'cache_type_v',
+ 'parallel',
+ 'cont_batching',
+ 'threads',
+ 'threads_batch',
+ 'n_predict',
+ 'batch_size',
+ 'ubatch_size',
+ 'n_cpu_moe',
+ 'n_cpu_ffn',
+ 'no_kv_offload',
+ 'device',
+ 'split_mode',
+ 'main_gpu',
+ 'no_mmap',
+ 'mlock',
+ 'rope_scaling',
+ 'rope_freq_base',
+ 'rope_freq_scale',
+ 'ctx_shift',
+ 'cache_ram',
+ // persist_thread_cache decides whether slot-save-path is emitted at all;
+ // thread_cache_size is not a preset key but rides the same reload, which
+ // carries it to the worker (see reload_engine_models).
+ 'persist_thread_cache',
+ 'thread_cache_size',
+ 'cache_reuse',
+ 'swa_full',
+ 'keep',
+ 'kv_unified',
+ 'tensor_split',
+ 'no_op_offload',
+ 'ctx_checkpoints',
+ 'checkpoint_min_step',
+ 'kv_unified_per_slot',
+ 'reasoning_preserve',
+ 'lazy_mode',
])
@@ -163,14 +166,14 @@ const PRESET_AFFECTING_KEYS = new Set<string>([
type YamlSettingValue = string | number | boolean | null
type PersistedProviderSetting = {
- controller_props?: {
- value?: unknown
- }
+ controller_props?: {
+ value?: unknown
+ }
}
type PersistedModelState = {
- id?: unknown
- settings?: Record<string, PersistedProviderSetting>
+ id?: unknown
+ settings?: Record<string, PersistedProviderSetting>
}
const MODEL_PROVIDER_STORE_KEY = 'model-provider'
@@ -179,9 +182,9 @@ const EMBEDDER_BOOTSTRAP_KEY = 'llamacpp-embedder-bootstrapped'
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'
+ '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_v2'
+ 'llamacpp_model_yaml_backfill_v2'
/// The GPU-layers value the old UI shipped as its default. v1 of the backfill
/// copied it into every model.yml, which pins offload to 100 layers and defeats
@@ -198,164 +201,164 @@ const DEFAULT_TIMEOUT = 600
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
+ 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
+ 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.
const coerceFloatSetting = (v: unknown): YamlSettingValue => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) ? n : null
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) ? n : null
}
const coerceIntSetting = (v: unknown): YamlSettingValue => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) ? Math.floor(n) : null
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) ? Math.floor(n) : null
}
const MODEL_SETTINGS_YAML_MAPPING: Record<
- string,
- {
- yamlKey: string
- coerce: (v: unknown) => YamlSettingValue
- }
+ string,
+ {
+ yamlKey: string
+ coerce: (v: unknown) => YamlSettingValue
+ }
> = {
- // Sampling defaults: persisted to model.yml and emitted into the router
- // preset so they apply server-side to every request (chat and external API),
- // overridable per-request. Keys mirror MODEL_SAMPLING_SETTING_KEYS in the
- // web-app transport.
- temperature: { yamlKey: 'temperature', coerce: coerceFloatSetting },
- top_k: { yamlKey: 'top_k', coerce: coerceIntSetting },
- top_p: { yamlKey: 'top_p', coerce: coerceFloatSetting },
- min_p: { yamlKey: 'min_p', coerce: coerceFloatSetting },
- // Not coerceIntSetting: upstream throws on a negative window on both the
- // preset path and the per-request path, so a legacy -1 from the old
- // "-1 = full context" UI has to be dropped, not passed through. Omitting the
- // key lets upstream's own default (64) apply.
- repeat_last_n: {
- yamlKey: 'repeat_last_n',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null
- },
- },
- repeat_penalty: { yamlKey: 'repeat_penalty', coerce: coerceFloatSetting },
- presence_penalty: { yamlKey: 'presence_penalty', coerce: coerceFloatSetting },
- frequency_penalty: {
- yamlKey: 'frequency_penalty',
- coerce: coerceFloatSetting,
- },
- ctx_len: {
- yamlKey: 'ctx_size',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
- },
- },
- ngl: {
- yamlKey: 'n_gpu_layers',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- // -1 is auto (VRAM-aware) and -2 or below means all layers, so the floor
- // is -2 rather than 0.
- return Number.isFinite(n) && n >= -2 ? Math.floor(n) : null
- },
- },
- chat_template: {
- yamlKey: 'chat_template',
- coerce: (v) =>
- typeof v === 'string' && v.trim().length > 0 ? v : null,
- },
- grammar: {
- yamlKey: 'grammar',
- coerce: (v) =>
- typeof v === 'string' && v.trim().length > 0 ? v : null,
- },
- batch_size: {
- yamlKey: 'batch_size',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
- },
- },
- ubatch_size: {
- yamlKey: 'ubatch_size',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
- },
+ // Sampling defaults: persisted to model.yml and emitted into the router
+ // preset so they apply server-side to every request (chat and external API),
+ // overridable per-request. Keys mirror MODEL_SAMPLING_SETTING_KEYS in the
+ // web-app transport.
+ temperature: { yamlKey: 'temperature', coerce: coerceFloatSetting },
+ top_k: { yamlKey: 'top_k', coerce: coerceIntSetting },
+ top_p: { yamlKey: 'top_p', coerce: coerceFloatSetting },
+ min_p: { yamlKey: 'min_p', coerce: coerceFloatSetting },
+ // Not coerceIntSetting: upstream throws on a negative window on both the
+ // preset path and the per-request path, so a legacy -1 from the old
+ // "-1 = full context" UI has to be dropped, not passed through. Omitting the
+ // key lets upstream's own default (64) apply.
+ repeat_last_n: {
+ yamlKey: 'repeat_last_n',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null
},
- cpu_moe: {
- yamlKey: 'cpu_moe',
- coerce: (v) => (v === true ? true : null),
+ },
+ repeat_penalty: { yamlKey: 'repeat_penalty', coerce: coerceFloatSetting },
+ presence_penalty: { yamlKey: 'presence_penalty', coerce: coerceFloatSetting },
+ frequency_penalty: {
+ yamlKey: 'frequency_penalty',
+ coerce: coerceFloatSetting,
+ },
+ ctx_len: {
+ yamlKey: 'ctx_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
},
- n_cpu_moe: {
- yamlKey: 'n_cpu_moe',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
- },
+ },
+ ngl: {
+ yamlKey: 'n_gpu_layers',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ // -1 is auto (VRAM-aware) and -2 or below means all layers, so the floor
+ // is -2 rather than 0.
+ return Number.isFinite(n) && n >= -2 ? Math.floor(n) : null
},
- n_cpu_ffn: {
- yamlKey: 'n_cpu_ffn',
- coerce: (v) => {
- if (v === '' || v == null) return null
- const n = typeof v === 'number' ? v : Number(v)
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
- },
+ },
+ chat_template: {
+ yamlKey: 'chat_template',
+ coerce: (v) =>
+ typeof v === 'string' && v.trim().length > 0 ? v : null,
+ },
+ grammar: {
+ yamlKey: 'grammar',
+ coerce: (v) =>
+ typeof v === 'string' && v.trim().length > 0 ? v : null,
+ },
+ batch_size: {
+ yamlKey: 'batch_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
},
- no_kv_offload: {
- yamlKey: 'no_kv_offload',
- coerce: (v) => (v === true ? true : null),
+ },
+ ubatch_size: {
+ yamlKey: 'ubatch_size',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
},
- override_tensor_buffer_t: {
- yamlKey: 'override_tensor',
- coerce: (v) =>
- typeof v === 'string' && v.trim().length > 0 ? v.trim() : null,
+ },
+ cpu_moe: {
+ yamlKey: 'cpu_moe',
+ coerce: (v) => (v === true ? true : null),
+ },
+ n_cpu_moe: {
+ yamlKey: 'n_cpu_moe',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
},
- offload_mmproj: {
- yamlKey: 'mmproj_offload',
- coerce: (v) => (v === false ? false : null),
+ },
+ n_cpu_ffn: {
+ yamlKey: 'n_cpu_ffn',
+ coerce: (v) => {
+ if (v === '' || v == null) return null
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null
},
+ },
+ no_kv_offload: {
+ yamlKey: 'no_kv_offload',
+ coerce: (v) => (v === true ? true : null),
+ },
+ override_tensor_buffer_t: {
+ yamlKey: 'override_tensor',
+ coerce: (v) =>
+ typeof v === 'string' && v.trim().length > 0 ? v.trim() : null,
+ },
+ offload_mmproj: {
+ yamlKey: 'mmproj_offload',
+ coerce: (v) => (v === false ? false : null),
+ },
}
async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {
- try {
- const raw = await getBackendSetting(MODEL_PROVIDER_STORE_KEY)
- if (!raw) return []
- const parsed = JSON.parse(raw)
- const providers = parsed?.state?.providers
- if (!Array.isArray(providers)) return []
- const llamacpp = providers.find(
- (provider: { provider?: unknown }) => provider?.provider === 'llamacpp'
- )
- return Array.isArray(llamacpp?.models) ? llamacpp.models : []
- } catch (error) {
- logger.warn('Failed to read persisted llamacpp model settings:', error)
- return []
- }
+ try {
+ const raw = await getBackendSetting(MODEL_PROVIDER_STORE_KEY)
+ if (!raw) return []
+ const parsed = JSON.parse(raw)
+ const providers = parsed?.state?.providers
+ if (!Array.isArray(providers)) return []
+ const llamacpp = providers.find(
+ (provider: { provider?: unknown }) => provider?.provider === 'llamacpp'
+ )
+ return Array.isArray(llamacpp?.models) ? llamacpp.models : []
+ } catch (error) {
+ logger.warn('Failed to read persisted llamacpp model settings:', error)
+ return []
+ }
}
/**
@@ -366,38 +369,38 @@ async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {
* llama.cpp's flat `llama-bXXXX/...`).
*/
async function findLlamaServerDir(
- rootDir: string,
- serverName: string
+ rootDir: string,
+ serverName: string
): Promise<string | null> {
- // Note: fs.readdirSync returns absolute child paths (see
- // src-tauri/src/core/filesystem/commands.rs::readdir_sync), not basenames.
- const queue: string[] = [rootDir]
- while (queue.length > 0) {
- const current = queue.shift() as string
- let entries: string[]
- try {
- entries = await fs.readdirSync(current)
- } catch {
- continue
- }
- for (const entryPath of entries) {
- let stat
- try {
- stat = await fs.fileStat(entryPath)
- } catch {
- continue
- }
- if (!stat) continue
- const entryName = await basename(entryPath)
- if (!stat.isDirectory && entryName === serverName) {
- return current
- }
- if (stat.isDirectory) {
- queue.push(entryPath)
- }
- }
- }
- return null
+ // Note: fs.readdirSync returns absolute child paths (see
+ // src-tauri/src/core/filesystem/commands.rs::readdir_sync), not basenames.
+ const queue: string[] = [rootDir]
+ while (queue.length > 0) {
+ const current = queue.shift() as string
+ let entries: string[]
+ try {
+ entries = await fs.readdirSync(current)
+ } catch {
+ continue
+ }
+ for (const entryPath of entries) {
+ let stat
+ try {
+ stat = await fs.fileStat(entryPath)
+ } catch {
+ continue
+ }
+ if (!stat) continue
+ const entryName = await basename(entryPath)
+ if (!stat.isDirectory && entryName === serverName) {
+ return current
+ }
+ if (stat.isDirectory) {
+ queue.push(entryPath)
+ }
+ }
+ }
+ return null
}
// Folder structure for llamacpp extension:
@@ -415,2772 +418,2983 @@ async function findLlamaServerDir(
// - e.g. libcudart.so.12
export default class llamacpp_extension extends AIEngine implements EmbeddingEngine {
- provider: string = 'llamacpp'
- timeout: number = 600
- llamacpp_env: string = ''
- readonly providerId: string = 'llamacpp'
-
- private config: LlamacppConfig
- private providerPath!: string
- private 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?: string
- /**
- * True while the fallback embedder is being fetched.
- *
- * The old readiness gate keyed off "no backend selected yet", which happened
- * to cover this window on a fresh install. The engine ships with the app now,
- * so that proxy is gone and this is the direct signal -- without it, a normal
- * first-run download is reported as a failed embedding check.
- */
- private embedderBootstrapping = false
- private loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises
- private unlistenValidationStarted?: () => void
-
- private enginePort?: number
- private engineApiKey?: string
- private engineVersion?: EngineVersion
- private presetPath?: string
- private engineStartLock: Promise<void> | null = null
- private userModelsMax: number = 1
- private engineEmbeddingBonus: number = 0
- private loadedChatOrder: string[] = []
-
- // The engine worker spawn runs off the onLoad critical path; awaited via
- // ensureEngineReady() 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
-
- await this.migrateLocalStorageToFile()
-
- // The engine is bundled at a pinned version, so there is no backend or
- // version to migrate or select. `registerSettings` drops the keys that no
- // longer exist in SETTINGS (llamacpp_version, llamacpp_backend,
- // check_for_updates, auto_update_engine, verify_backend_deps) from the
- // persisted set on its own.
- const settings = structuredClone(SETTINGS)
- await this.registerSettings(settings)
-
- let loadedConfig: any = {}
- for (const item of settings) {
- const defaultValue = item.controllerProps.value
- // Use the potentially updated default value from the settings array as the fallback for getSetting
- loadedConfig[item.key] = await this.getSetting<typeof defaultValue>(
- item.key,
- defaultValue
- )
- }
- this.config = loadedConfig as LlamacppConfig
-
- // Auto-fit is disabled by default on all platforms; ctx-size owns context
- // sizing. Force off for users a prior build left with fit enabled.
- await this.migrateFitOff()
-
- await this.migrateAutoUnloadToModelsMax()
-
- await this.migrateParallelToDefault()
-
- this.timeout = asI32(this.config.timeout, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT
- this.llamacpp_env = this.config.llamacpp_env
-
- // This sets the base directory where model files for this provider are stored.
- await this.getProviderPath()
-
- await this.migratePersistedModelSettingsToYaml()
-
- // Set up validation event listeners to bridge Tauri events to frontend
- this.unlistenValidationStarted = await listen<{
- modelId: string
- downloadType: string
- }>('onModelValidationStarted', (event) => {
- events.emit(DownloadEvent.onModelValidationStarted, event.payload)
+ provider: string = 'llamacpp'
+ timeout: number = 600
+ llamacpp_env: string = ''
+ readonly providerId: string = 'llamacpp'
+
+ private config: LlamacppConfig
+ private providerPath!: string
+ private 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?: string
+ /**
+ * True while the fallback embedder is being fetched.
+ *
+ * The old readiness gate keyed off "no backend selected yet", which happened
+ * to cover this window on a fresh install. The engine ships with the app now,
+ * so that proxy is gone and this is the direct signal -- without it, a normal
+ * first-run download is reported as a failed embedding check.
+ */
+ private embedderBootstrapping = false
+ private loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises
+ private unlistenValidationStarted?: () => void
+
+ private enginePort?: number
+ private engineApiKey?: string
+ private engineVersion?: EngineVersion
+ private presetPath?: string
+ private engineStartLock: Promise<void> | null = null
+ // Requests holding the engine's port and key (see acquireEngineLease), and the
+ // gate a device restart raises so that none is admitted while it decides.
+ private engineLeases = 0
+ private engineGate: Promise<void> | null = null
+ // Reconciliations run one after another; see reconcileEngineDevices.
+ private reconcileQueue: Promise<void> = Promise.resolve()
+ private userModelsMax: number = 1
+ private engineEmbeddingBonus: number = 0
+ private loadedChatOrder: string[] = []
+
+ // The engine worker spawn runs off the onLoad critical path; awaited via
+ // ensureEngineReady() 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
+
+ await this.migrateLocalStorageToFile()
+
+ // The engine is bundled at a pinned version, so there is no backend or
+ // version to migrate or select. `registerSettings` drops the keys that no
+ // longer exist in SETTINGS (llamacpp_version, llamacpp_backend,
+ // check_for_updates, auto_update_engine, verify_backend_deps) from the
+ // persisted set on its own.
+ const settings = structuredClone(SETTINGS)
+ await this.registerSettings(settings)
+
+ let loadedConfig: any = {}
+ for (const item of settings) {
+ const defaultValue = item.controllerProps.value
+ // Use the potentially updated default value from the settings array as the fallback for getSetting
+ loadedConfig[item.key] = await this.getSetting<typeof defaultValue>(
+ item.key,
+ defaultValue
+ )
+ }
+ this.config = loadedConfig as LlamacppConfig
+
+ // Auto-fit is disabled by default on all platforms; ctx-size owns context
+ // sizing. Force off for users a prior build left with fit enabled.
+ await this.migrateFitOff()
+
+ await this.migrateAutoUnloadToModelsMax()
+
+ await this.migrateParallelToDefault()
+
+ this.timeout = asI32(this.config.timeout, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT
+ this.llamacpp_env = this.config.llamacpp_env
+
+ // This sets the base directory where model files for this provider are stored.
+ await this.getProviderPath()
+
+ await this.migratePersistedModelSettingsToYaml()
+
+ // Set up validation event listeners to bridge Tauri events to frontend
+ this.unlistenValidationStarted = await listen<{
+ modelId: string
+ downloadType: string
+ }>('onModelValidationStarted', (event) => {
+ events.emit(DownloadEvent.onModelValidationStarted, event.payload)
+ })
+
+ // Deferred off onLoad so the UI unblocks; performLoad awaits it via
+ // ensureEngineReady(). The engine is bundled with the app now, so there is
+ // no backend catalog fetch and no hundreds-of-megabytes download to ask
+ // consent for -- only the fallback embedder, which bootstrapDefaultEmbedder
+ // still gates on setup consent.
+ this.backgroundInit = this.ensureProvisioned()
+ }
+
+ 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()
+ }
+
+ /**
+ * Starts the engine, 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.
+ *
+ * There is no backend selection step any more -- the engine is linked into
+ * the shipped worker at a pinned version, so the ordering dance between
+ * "download a backend first" and "start first for availability" is gone.
+ */
+ private ensureProvisioned(): Promise<void> {
+ this.provisioning ??= (async () => {
+ try {
+ await this.startEngine()
+ } catch (e) {
+ logger.error('Engine failed to start during provisioning:', e)
+ this.reportMissingLibrariesFromError(e)
+ }
+ await this.bootstrapDefaultEmbedder()
+ })()
+ this.backgroundInit = this.provisioning
+ return this.provisioning
+ }
+
+ /**
+ * One-shot startup install of the fallback embedder so the router reserves
+ * the +1 embedding slot from its first start instead of importing the model
+ * mid-session on the first RAG call. Runs after the router is up so the
+ * download never delays chat availability; the import's preset refresh then
+ * resizes models_max via an idle restart (nothing is loaded yet at startup).
+ * The persisted flag keeps this from resurrecting a model the user deleted,
+ * and is only set on success so a failed download retries next launch.
+ */
+ private async bootstrapDefaultEmbedder(): Promise<void> {
+ try {
+ if (await getBackendSetting(EMBEDDER_BOOTSTRAP_KEY)) return
+ if (!(await this.hasEmbedderInstalled())) {
+ // Set only around the actual fetch, and only when there is one to do:
+ // an install that is already present must not flash a pending state.
+ this.embedderBootstrapping = true
+ await this.import(FALLBACK_EMBEDDING_MODEL_ID, {
+ modelPath: FALLBACK_EMBEDDING_MODEL_URL,
})
-
- // Deferred off onLoad so the UI unblocks; performLoad awaits it via
- // ensureEngineReady(). The engine is bundled with the app now, so there is
- // no backend catalog fetch and no hundreds-of-megabytes download to ask
- // consent for -- only the fallback embedder, which bootstrapDefaultEmbedder
- // still gates on setup consent.
- this.backgroundInit = this.ensureProvisioned()
- }
-
- 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)
+ // 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`
+ )
}
- await this.ensureProvisioned()
- }
-
- /**
- * Starts the engine, 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.
- *
- * There is no backend selection step any more -- the engine is linked into
- * the shipped worker at a pinned version, so the ordering dance between
- * "download a backend first" and "start first for availability" is gone.
- */
- private ensureProvisioned(): Promise<void> {
- this.provisioning ??= (async () => {
- try {
- await this.startEngine()
- } catch (e) {
- logger.error('Engine failed to start during provisioning:', e)
- this.reportMissingLibrariesFromError(e)
- }
- await this.bootstrapDefaultEmbedder()
- })()
- this.backgroundInit = this.provisioning
- return this.provisioning
- }
-
- /**
- * One-shot startup install of the fallback embedder so the router reserves
- * the +1 embedding slot from its first start instead of importing the model
- * mid-session on the first RAG call. Runs after the router is up so the
- * download never delays chat availability; the import's preset refresh then
- * resizes models_max via an idle restart (nothing is loaded yet at startup).
- * The persisted flag keeps this from resurrecting a model the user deleted,
- * and is only set on success so a failed download retries next launch.
- */
- private async bootstrapDefaultEmbedder(): Promise<void> {
+ 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
+ )
+ } finally {
+ // In `finally` so a thrown import cannot leave the checklist reporting
+ // "downloading" for the rest of the session.
+ this.embedderBootstrapping = false
+ }
+ }
+
+ private async hasEmbedderInstalled(): Promise<boolean> {
+ const models = await this.list()
+ return models.some((m) => (m as { embedding?: boolean }).embedding === true)
+ }
+
+ /**
+ * 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.
+ */
+ /**
+ * A launch failure that names unresolvable libraries is the one dependency
+ * problem a bundled engine still has: the GPU driver runtime (CUDA, Vulkan)
+ * lives on the user's machine, not in the app. Raises the same dependency
+ * dialog the old pre-flight backend verification did.
+ */
+ 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
+
+ // The engine is bundled, so there is no selected variant to name. The
+ // unresolved library itself identifies the runtime that is missing, and
+ // getBackendDisplayName matches on exactly these substrings.
+ const joined = libs.join(' ').toLowerCase()
+ const backend = ['cuda', 'vulkan', 'hip', 'metal'].find((b) =>
+ joined.includes(b)
+ )
+ events.emit(AppEvent.onBackendVerificationFailed, {
+ backend: backend ?? '',
+ missingLibraries: libs,
+ })
+ }
+
+ 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> {
+ // Downloading it is not a defect. Probing mid-download would fail on a
+ // model that is simply not there yet and report a warning for it.
+ if (this.embedderBootstrapping) {
+ 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)),
+ }
+ }
+ }
+
+ /**
+ * 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> {
+ let devices: DeviceList[]
+ try {
+ devices = await this.getDevices()
+ } 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: false,
+ 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)
+ }
+
+ return {
+ backend: backendFromDeviceIds(devices.map((d) => d.id)),
+ ...evaluateGpuOffload({
+ engineDeviceCount: devices.length,
+ hardwareGpuCount,
+ }),
+ }
+ }
+
+ override async getSettings(): Promise<SettingComponentProps[]> {
+ return readSettingsFile()
+ }
+
+ override async updateSettings(
+ componentProps: Partial<SettingComponentProps>[]
+ ): Promise<void> {
+ const current = await readSettingsFile()
+ const changed: { key: string; value: unknown }[] = []
+ const updated = current.length
+ ? current.map((s) => {
+ const patch = componentProps.find((p) => p.key === s.key)
+ if (patch?.controllerProps) {
+ const nextValue = (patch.controllerProps as { value?: unknown })
+ .value
+ const prevValue = (s.controllerProps as { value?: unknown }).value
+ if (nextValue !== prevValue) {
+ changed.push({ key: s.key, value: nextValue })
+ }
+ return {
+ ...s,
+ controllerProps: { ...s.controllerProps, value: nextValue },
+ } as SettingComponentProps
+ }
+ return s
+ })
+ : ((): SettingComponentProps[] => {
+ const arr = componentProps as SettingComponentProps[]
+ for (const s of arr) {
+ changed.push({
+ key: s.key,
+ value: (s.controllerProps as { value?: unknown })?.value,
+ })
+ }
+ return arr
+ })()
+ await writeSettingsFile(updated)
+ const previousConfig = { ...this.config }
+ const previousTimeout = this.timeout
+ const previousEnv = this.llamacpp_env
+ for (const { key, value } of changed) {
+ this.onSettingUpdate(key, value)
+ }
+ if (this.presetRefreshTimer) {
+ clearTimeout(this.presetRefreshTimer)
+ this.presetRefreshTimer = null
+ // Startup migrations are included in the initial preset. Once loaded,
+ // an awaited settings save must include engine application, not merely
+ // schedule it after the caller has already sent its next request.
+ if (this.backgroundInit) {
try {
- if (await getBackendSetting(EMBEDDER_BOOTSTRAP_KEY)) return
- if (!(await this.hasEmbedderInstalled())) {
- // Set only around the actual fetch, and only when there is one to do:
- // an install that is already present must not flash a pending state.
- this.embedderBootstrapping = true
- 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
- )
- } finally {
- // In `finally` so a thrown import cannot leave the checklist reporting
- // "downloading" for the rest of the session.
- this.embedderBootstrapping = false
- }
+ await this.refreshEnginePreset()
+ } catch (error) {
+ this.config = previousConfig
+ this.timeout = previousTimeout
+ this.llamacpp_env = previousEnv
+ await writeSettingsFile(current)
+ throw error
+ }
+ }
+ }
+ }
+
+ override async registerSettings(
+ settings: SettingComponentProps[]
+ ): Promise<void> {
+ settings.forEach((s) => {
+ s.extensionName = this.name
+ })
+ const old = await readSettingsFile()
+ if (old.length) {
+ settings.forEach((s) => {
+ const prev = old.find((o) => o.key === s.key)
+ if (!prev) return
+ const cp = s.controllerProps as Record<string, unknown>
+ const pcp = prev.controllerProps as Record<string, unknown>
+ if (pcp.value !== undefined) cp.value = pcp.value
+ if ('options' in cp) {
+ const newOptions = (cp.options as unknown[]) ?? []
+ if (newOptions.length === 0 && Array.isArray(pcp.options)) {
+ cp.options = pcp.options
+ }
+ const opts = (cp.options as { value: unknown }[]) ?? []
+ if (opts.length && !opts.some((o) => o.value === cp.value)) {
+ cp.value = opts[0]?.value
+ }
+ }
+ })
+ }
+ await writeSettingsFile(settings)
+ }
+
+ // The ONLY sanctioned localStorage use in this extension: a one-time read +
+ // clear migrating pre-backend llamacpp settings into the file store. All
+ // other persistence goes through backend-settings.ts. Guarded by
+ // no-localstorage.test.ts via the `localstorage-migration-allowed` markers.
+ private async migrateLocalStorageToFile(): Promise<void> {
+ if (await settingsFileExists()) return
+ if (!this.name) return
+ let raw: string | null = null
+ try {
+ raw = localStorage.getItem(this.name) // localstorage-migration-allowed
+ } catch {
+ raw = null
}
-
- private async hasEmbedderInstalled(): Promise<boolean> {
- const models = await this.list()
- return models.some((m) => (m as { embedding?: boolean }).embedding === true)
- }
-
- /**
- * 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.
- */
- /**
- * A launch failure that names unresolvable libraries is the one dependency
- * problem a bundled engine still has: the GPU driver runtime (CUDA, Vulkan)
- * lives on the user's machine, not in the app. Raises the same dependency
- * dialog the old pre-flight backend verification did.
- */
- 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
-
- // The engine is bundled, so there is no selected variant to name. The
- // unresolved library itself identifies the runtime that is missing, and
- // getBackendDisplayName matches on exactly these substrings.
- const joined = libs.join(' ').toLowerCase()
- const backend = ['cuda', 'vulkan', 'hip', 'metal'].find((b) =>
- joined.includes(b)
+ if (!raw) return
+ try {
+ const parsed = JSON.parse(raw)
+ if (Array.isArray(parsed)) {
+ await writeSettingsFile(parsed as SettingComponentProps[])
+ logger.info(
+ `Migrated llamacpp settings from localStorage → file (${parsed.length} entries)`
)
- events.emit(AppEvent.onBackendVerificationFailed, {
- backend: backend ?? '',
- missingLibraries: libs,
- })
+ }
+ } catch (e) {
+ logger.warn('Failed to migrate localStorage settings to file:', e)
+ return
}
+ try {
+ localStorage.removeItem(this.name) // localstorage-migration-allowed
+ } catch (e) {
+ logger.warn('Failed to clear migrated localStorage entry:', e)
+ }
+ }
+
+ /**
+ * Serialized: two concurrent calls would each run the stop-then-spawn
+ * sequence, and the second would kill the worker the first had just brought
+ * up. A late caller gets the in-flight start rather than a restart.
+ */
+ private async startEngine(): Promise<void> {
+ const inflight = this.engineStartLock
+ if (inflight) {
+ logger.info('startEngine already in progress; awaiting the in-flight run')
+ await inflight.catch(() => undefined)
+ return
+ }
+ this.engineStartLock = this.runStartEngine().finally(() => {
+ this.engineStartLock = null
+ })
+ return this.engineStartLock
+ }
+
+ private async runStartEngine(): Promise<void> {
+ const providerPath = await this.getProviderPath()
+ const janDataFolderPath = await getJanDataFolderPath()
+ const { path: presetPath, embeddingCount } = await generatePreset(
+ providerPath,
+ janDataFolderPath,
+ this.config
+ )
+
+ const modelsMax = this.resolveModelsMax(embeddingCount)
+
+ // Idempotent in the plugin: a second start returns the running worker
+ // rather than orphaning it, so a redundant call is a no-op instead of a
+ // cold restart. That is also why there is no adoption dance here: the
+ // worker exits on stdin EOF, which the OS delivers when this process dies
+ // by any means -- including SIGKILL, where kill_on_drop never runs -- so
+ // there is nothing to adopt or reap. Not because a child dies with its
+ // parent; it does not, it gets reparented.
+ const envs: Record<string, string> = {}
+ envs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)
+ if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
+
+ const info = await startEngine(
+ presetPath,
+ modelsMax,
+ this.resolveThreadCacheBudget(),
+ envs
+ )
+ this.enginePort = info.port
+ this.engineApiKey = info.api_key
+ this.presetPath = presetPath
+ // The load log never says which GPU llama.cpp picked, so record what the
+ // worker initialised and which devices the user's setting names.
+ logger.info(
+ `Engine devices at start: ${info.devices ? this.deviceKeys(info.devices).join(', ') : 'not reported'}; device setting: ${String(this.config.device ?? '') || '(auto)'}`
+ )
+ logger.info(
+ `Engine worker started on port ${info.port} (pid ${info.pid}, models_max=${modelsMax}, ${info.models.length} models registered, preset=${presetPath})`
+ )
+ }
+
+ /**
+ * Drops a thread's saved prompt cache, for a thread the user deleted.
+ *
+ * Best-effort by design: the cache is invisible to the user and the store
+ * prunes by size anyway, so failing here must not make deleting a thread
+ * fail. Returns how many states were dropped.
+ */
+ async forgetThreadCache(threadId: string): Promise<number> {
+ try {
+ return await eraseThreadSlotState({
+ threadId,
+ cacheDir: threadCacheDir(await this.getProviderPath()),
+ })
+ } catch (e) {
+ logger.warn(`could not drop the saved cache for thread ${threadId}: ${e}`)
+ return 0
+ }
+ }
+
+ /**
+ * The disk budget for saved thread caches, in MiB.
+ *
+ * 0 is the off switch on the worker side, so the toggle and the size collapse
+ * into one number: a disabled feature and a zero budget are the same thing,
+ * and keeping them separate would let the worker create a directory it would
+ * never write to.
+ */
+ private resolveThreadCacheBudget(): number {
+ if (this.config.persist_thread_cache === false) return 0
+ const raw = Number(this.config.thread_cache_size)
+ if (!Number.isFinite(raw) || raw <= 0) return 0
+ return Math.floor(raw)
+ }
+
+ /**
+ * `models_max` including the embedding slot bonus.
+ *
+ * Reserves one extra slot when any embedder is installed so loading it does
+ * not evict the user's chat model. Only one embedding model is ever resident
+ * (RAG calls load() once per request), so the bonus is +1 regardless of how
+ * many are installed. 0 (unlimited) stays unlimited.
+ */
+ private resolveModelsMax(embeddingCount: number): number {
+ const raw = (this.config as { models_max?: unknown }).models_max
+ let modelsMax = 1
+ if (typeof raw === 'number') modelsMax = raw
+ else if (typeof raw === 'string' && raw.trim().length > 0) {
+ const n = parseInt(raw, 10)
+ if (!Number.isNaN(n) && n >= 0) modelsMax = n
+ }
+ this.userModelsMax = modelsMax
+ const bonus = modelsMax > 0 && embeddingCount > 0 ? 1 : 0
+ this.engineEmbeddingBonus = bonus
+ return modelsMax + bonus
+ }
+
+ /**
+ * Apply a preset change (model added/removed/renamed or a per-model setting)
+ * to the running worker. Models whose preset section is unchanged stay
+ * loaded, so an embedder import or a settings write no longer cold-reloads
+ * the model the user is talking to.
+ *
+ * Unlike the router this also resizes `models_max`, so a change in the
+ * embedding slot bonus no longer needs a restart either -- which was the one
+ * remaining case that evicted a live chat model.
+ */
+ private async refreshEnginePreset(): Promise<void> {
+ if (!(await this.getEngineInfo())) {
+ await this.startEngine() // cold start
+ return
+ }
+
+ const providerPath = await this.getProviderPath()
+ const janDataFolderPath = await getJanDataFolderPath()
+ const { path: presetPath, embeddingCount } = await generatePreset(
+ providerPath,
+ janDataFolderPath,
+ this.config
+ )
+ this.presetPath = presetPath
- getEmbedderBootstrapError(): string | undefined {
- return this.embedderBootstrapError
+ try {
+ const report = await reloadEngineModels(
+ presetPath,
+ this.resolveModelsMax(embeddingCount),
+ this.resolveThreadCacheBudget()
+ )
+ logger.info(
+ `Engine preset reloaded: +${report.added.length} ~${report.changed.length} -${report.removed.length}, ${report.kept.length} kept loaded`
+ )
+ } catch (e) {
+ logger.warn('Live engine reload failed; falling back to restart:', e)
+ await this.startEngine()
+ }
+ }
+
+ /**
+ * Public accessor for downstream consumers. Returns `null` if the engine
+ * worker hasn't started successfully yet.
+ */
+ async getEngineInfo(): Promise<{ port: number; apiKey: string } | null> {
+ // Deliberately not answered from the cached port: get_engine_info is the
+ // one place a worker that died is noticed -- it reaps the handle and
+ // reports nothing running -- and every caller here uses this as the
+ // liveness probe before deciding whether to respawn. Answering from
+ // enginePort would keep handing out a closed port for the rest of the
+ // session, which is exactly the crash the worker process exists to survive.
+ try {
+ const info = await pluginGetEngineInfo()
+ if (info) {
+ this.enginePort = info.port
+ this.engineApiKey = info.api_key
+ return { port: info.port, apiKey: info.api_key }
+ }
+ this.enginePort = undefined
+ this.engineApiKey = undefined
+ } catch (e) {
+ logger.warn('get_engine_info failed:', e)
+ }
+ return null
+ }
+
+ /**
+ * The bundled engine's identity. Cached after the first call: these are
+ * compile-time constants of the plugin, so they cannot change while the app
+ * is running, and the settings screen asks on every mount.
+ */
+ async getEngineVersion(): Promise<EngineVersion> {
+ if (!this.engineVersion) {
+ this.engineVersion = await pluginGetEngineVersion()
+ }
+ return this.engineVersion
+ }
+
+ /**
+ * Fetch runtime properties for a loaded model from the router's
+ * `/props?model=<id>` endpoint. Returns `undefined` if the router isn't
+ * running, the model isn't loaded, or the response is unusable. `nCtx` is
+ * the post-fit value — what `fit_ctx` settled on — so it's the right
+ * denominator for the token-usage popup.
+ */
+ async getModelProps(
+ modelId: string
+ ): Promise<
+ | (ModelProps & {
+ modalities?: { vision: boolean; video: boolean; audio: boolean }
+ })
+ | undefined
+ > {
+ const engine = await this.getEngineInfo()
+ if (!engine || !modelId) return undefined
+ // A request naming an unloaded model loads it on demand, so `/props` alone
+ // would trigger a load. Gate on the loaded-set first.
+ try {
+ const loaded = await this.getLoadedModels()
+ if (!loaded.includes(modelId)) return undefined
+ } catch {
+ return undefined
+ }
+ try {
+ const url = `http://127.0.0.1:${engine.port}/props?model=${encodeURIComponent(modelId)}`
+ const res = await loopbackFetch(url, {
+ headers: { Authorization: `Bearer ${engine.apiKey}` },
+ })
+ if (!res.ok) return undefined
+ const json = (await res.json()) as {
+ default_generation_settings?: { n_ctx?: number }
+ total_slots?: number
+ model_alias?: string
+ is_sleeping?: boolean
+ modalities?: { vision?: boolean; video?: boolean; audio?: boolean }
+ }
+ const n = json?.default_generation_settings?.n_ctx
+ if (typeof n !== 'number' || n <= 0) return undefined
+ const m = json.modalities
+ return {
+ nCtx: n,
+ totalSlots:
+ typeof json.total_slots === 'number' ? json.total_slots : undefined,
+ modelAlias: json.model_alias,
+ isSleeping: !!json.is_sleeping,
+ modalities: m
+ ? { vision: !!m.vision, video: !!m.video, audio: !!m.audio }
+ : undefined,
+ }
+ } catch {
+ return undefined
+ }
+ }
+
+ private async readMmprojCapabilities(
+ mmprojPath: string
+ ): Promise<{ vision: boolean; audio: boolean }> {
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullPath = await joinPath([janDataFolderPath, mmprojPath])
+ const meta = (await readGgufMetadata(fullPath)).metadata ?? {}
+ const truthy = (v: string | undefined) =>
+ typeof v === 'string' && v.toLowerCase() === 'true'
+ const vision = truthy(meta['clip.has_vision_encoder'])
+ const audio = truthy(meta['clip.has_audio_encoder'])
+ if (!vision && !audio) return { vision: true, audio: false }
+ return { vision, audio }
+ } catch (error) {
+ logger.warn('Failed to read mmproj capabilities:', error)
+ return { vision: true, audio: false }
}
+ }
- /**
- * 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> {
- // Downloading it is not a defect. Probing mid-download would fail on a
- // model that is simply not there yet and report a warning for it.
- if (this.embedderBootstrapping) {
- return { status: 'ok', pending: true }
- }
+ private async migrateAutoUnloadToModelsMax(): Promise<void> {
+ const MIGRATION_KEY = 'llamacpp_models_max_migrated_v1'
+ if (await getBackendSetting(MIGRATION_KEY)) return
- 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)),
+ try {
+ const old = await this.getSetting<boolean | undefined>(
+ 'auto_unload',
+ undefined
+ )
+ if (old !== undefined) {
+ const targetValue = old ? '1' : '0'
+ const settings = await this.getSettings()
+ await this.updateSettings(
+ settings.map((item) => {
+ if (item.key === 'models_max') {
+ item.controllerProps.value = targetValue
}
- }
+ return item
+ })
+ )
+ ; (this.config as any).models_max = targetValue
+ logger.info(
+ `Migrated auto_unload=${old} -> models_max=${targetValue}`
+ )
+ }
+ } catch (e) {
+ logger.warn('migrateAutoUnloadToModelsMax 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> {
- let devices: DeviceList[]
- try {
- devices = await this.getDevices()
- } 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: false,
- 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)
- }
+ await setBackendSetting(MIGRATION_KEY, '1')
+ }
- return {
- backend: backendFromDeviceIds(devices.map((d) => d.id)),
- ...evaluateGpuOffload({
- engineDeviceCount: devices.length,
- hardwareGpuCount,
- }),
- }
- }
+ // The old default was 1 plus two slots Jan reserved for background work and
+ // Cowork; both now share slot 0, so the reservation is gone and a persisted
+ // 1 would pin the engine to a single slot rather than letting it resolve its
+ // own count. Only the old default value is moved.
+ private async migrateParallelToDefault(): Promise<void> {
+ const MIGRATION_KEY = 'llamacpp_parallel_default_v1'
+ if (await getBackendSetting(MIGRATION_KEY)) return
- override async getSettings(): Promise<SettingComponentProps[]> {
- return readSettingsFile()
- }
-
- override async updateSettings(
- componentProps: Partial<SettingComponentProps>[]
- ): Promise<void> {
- const current = await readSettingsFile()
- const changed: { key: string; value: unknown }[] = []
- const updated = current.length
- ? current.map((s) => {
- const patch = componentProps.find((p) => p.key === s.key)
- if (patch?.controllerProps) {
- const nextValue = (patch.controllerProps as { value?: unknown })
- .value
- const prevValue = (s.controllerProps as { value?: unknown }).value
- if (nextValue !== prevValue) {
- changed.push({ key: s.key, value: nextValue })
- }
- return {
- ...s,
- controllerProps: { ...s.controllerProps, value: nextValue },
- } as SettingComponentProps
- }
- return s
- })
- : ((): SettingComponentProps[] => {
- const arr = componentProps as SettingComponentProps[]
- for (const s of arr) {
- changed.push({
- key: s.key,
- value: (s.controllerProps as { value?: unknown })?.value,
- })
- }
- return arr
- })()
- await writeSettingsFile(updated)
- const previousConfig = { ...this.config }
- const previousTimeout = this.timeout
- const previousEnv = this.llamacpp_env
- for (const { key, value } of changed) {
- this.onSettingUpdate(key, value)
- }
- if (this.presetRefreshTimer) {
- clearTimeout(this.presetRefreshTimer)
- this.presetRefreshTimer = null
- // Startup migrations are included in the initial preset. Once loaded,
- // an awaited settings save must include engine application, not merely
- // schedule it after the caller has already sent its next request.
- if (this.backgroundInit) {
- try {
- await this.refreshEnginePreset()
- } catch (error) {
- this.config = previousConfig
- this.timeout = previousTimeout
- this.llamacpp_env = previousEnv
- await writeSettingsFile(current)
- throw error
- }
+ try {
+ if (asI32(this.config.parallel, 0) === 1) {
+ const settings = await this.getSettings()
+ await this.updateSettings(
+ settings.map((item) => {
+ if (item.key === 'parallel') {
+ item.controllerProps.value = 0
}
- }
- }
-
- override async registerSettings(
- settings: SettingComponentProps[]
- ): Promise<void> {
- settings.forEach((s) => {
- s.extensionName = this.name
+ return item
+ })
+ )
+ this.config.parallel = 0
+ logger.info('Migrated parallel: 1 -> 0 (llama.cpp default)')
+ }
+ } catch (e) {
+ logger.warn('migrateParallelToDefault failed:', e)
+ return
+ }
+
+ await setBackendSetting(MIGRATION_KEY, '1')
+ }
+
+ private async migrateFitOff(): Promise<void> {
+ const MIGRATION_KEY = 'llamacpp_fit_off_v1'
+ if (await getBackendSetting(MIGRATION_KEY)) return
+
+ if (this.config.fit === true) {
+ const settings = await this.getSettings()
+ await this.updateSettings(
+ settings.map((item) => {
+ if (item.key === 'fit') {
+ item.controllerProps.value = false
+ }
+ return item
})
- const old = await readSettingsFile()
- if (old.length) {
- settings.forEach((s) => {
- const prev = old.find((o) => o.key === s.key)
- if (!prev) return
- const cp = s.controllerProps as Record<string, unknown>
- const pcp = prev.controllerProps as Record<string, unknown>
- if (pcp.value !== undefined) cp.value = pcp.value
- if ('options' in cp) {
- const newOptions = (cp.options as unknown[]) ?? []
- if (newOptions.length === 0 && Array.isArray(pcp.options)) {
- cp.options = pcp.options
- }
- const opts = (cp.options as { value: unknown }[]) ?? []
- if (opts.length && !opts.some((o) => o.value === cp.value)) {
- cp.value = opts[0]?.value
- }
- }
- })
- }
- await writeSettingsFile(settings)
+ )
+ this.config.fit = false
+ logger.info('Migrated fit setting: disabled')
}
- // The ONLY sanctioned localStorage use in this extension: a one-time read +
- // clear migrating pre-backend llamacpp settings into the file store. All
- // other persistence goes through backend-settings.ts. Guarded by
- // no-localstorage.test.ts via the `localstorage-migration-allowed` markers.
- private async migrateLocalStorageToFile(): Promise<void> {
- if (await settingsFileExists()) return
- if (!this.name) return
- let raw: string | null = null
- try {
- raw = localStorage.getItem(this.name) // localstorage-migration-allowed
- } catch {
- raw = null
- }
- if (!raw) return
- try {
- const parsed = JSON.parse(raw)
- if (Array.isArray(parsed)) {
- await writeSettingsFile(parsed as SettingComponentProps[])
- logger.info(
- `Migrated llamacpp settings from localStorage → file (${parsed.length} entries)`
- )
- }
- } catch (e) {
- logger.warn('Failed to migrate localStorage settings to file:', e)
- return
- }
- try {
- localStorage.removeItem(this.name) // localstorage-migration-allowed
- } catch (e) {
- logger.warn('Failed to clear migrated localStorage entry:', e)
- }
- }
+ await setBackendSetting(MIGRATION_KEY, '1')
+ }
- /**
- * Serialized: two concurrent calls would each run the stop-then-spawn
- * sequence, and the second would kill the worker the first had just brought
- * up. A late caller gets the in-flight start rather than a restart.
- */
- private async startEngine(): Promise<void> {
- const inflight = this.engineStartLock
- if (inflight) {
- logger.info('startEngine already in progress; awaiting the in-flight run')
- await inflight.catch(() => undefined)
- return
- }
- this.engineStartLock = this.runStartEngine().finally(() => {
- this.engineStartLock = null
- })
- return this.engineStartLock
+ private async migratePersistedModelSettingsToYaml(): Promise<void> {
+ if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return
+
+ const persistedModels = await readPersistedLlamacppModels()
+ const providerPath = await this.getProviderPath()
+
+ // v1's n_gpu_layers stamp lives in model.yml, not in the persisted
+ // settings, so it has to be swept even when nothing is persisted.
+ await this.stripLegacyNglFromModelYaml(providerPath)
+
+ if (persistedModels.length === 0) {
+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
+ return
}
- private async runStartEngine(): Promise<void> {
- const providerPath = await this.getProviderPath()
- const janDataFolderPath = await getJanDataFolderPath()
- const { path: presetPath, embeddingCount } = await generatePreset(
- providerPath,
- janDataFolderPath,
- this.config
- )
+ for (const persistedModel of persistedModels) {
+ const modelId =
+ typeof persistedModel.id === 'string' ? persistedModel.id : undefined
+ if (!modelId || !persistedModel.settings) continue
- const modelsMax = this.resolveModelsMax(embeddingCount)
-
- // Idempotent in the plugin: a second start returns the running worker
- // rather than orphaning it, so a redundant call is a no-op instead of a
- // cold restart. That is also why there is no adoption dance here: the
- // worker exits on stdin EOF, which the OS delivers when this process dies
- // by any means -- including SIGKILL, where kill_on_drop never runs -- so
- // there is nothing to adopt or reap. Not because a child dies with its
- // parent; it does not, it gets reparented.
- const envs: Record<string, string> = {}
- envs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)
- if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
-
- const info = await startEngine(
- presetPath,
- modelsMax,
- this.resolveThreadCacheBudget(),
- envs
- )
- this.enginePort = info.port
- this.engineApiKey = info.api_key
- this.presetPath = presetPath
+ const configPath = await joinPath([
+ providerPath,
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(configPath))) continue
+
+ const cfg = (await invoke<ModelConfig>('read_yaml', {
+ path: configPath,
+ })) as ModelConfig & Record<string, unknown>
+
+ let touched = false
+
+ // Undo v1's n_gpu_layers stamp so upstream's auto offload applies again.
+ if (cfg.n_gpu_layers === LEGACY_NGL_DEFAULT) {
+ delete (cfg as Record<string, unknown>).n_gpu_layers
+ touched = true
logger.info(
- `Engine worker started on port ${info.port} (pid ${info.pid}, models_max=${modelsMax}, ${info.models.length} models registered, preset=${presetPath})`
+ `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${modelId}; GPU offload is auto again`
)
- }
+ }
- /**
- * Drops a thread's saved prompt cache, for a thread the user deleted.
- *
- * Best-effort by design: the cache is invisible to the user and the store
- * prunes by size anyway, so failing here must not make deleting a thread
- * fail. Returns how many states were dropped.
- */
- async forgetThreadCache(threadId: string): Promise<number> {
- try {
- return await eraseThreadSlotState({
- threadId,
- cacheDir: threadCacheDir(await this.getProviderPath()),
- })
- } catch (e) {
- logger.warn(`could not drop the saved cache for thread ${threadId}: ${e}`)
- return 0
- }
- }
+ for (const [sidebarKey, persistedSetting] of Object.entries(
+ persistedModel.settings
+ )) {
+ const mapping = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
+ if (!mapping) continue
- /**
- * The disk budget for saved thread caches, in MiB.
- *
- * 0 is the off switch on the worker side, so the toggle and the size collapse
- * into one number: a disabled feature and a zero budget are the same thing,
- * and keeping them separate would let the worker create a directory it would
- * never write to.
- */
- private resolveThreadCacheBudget(): number {
- if (this.config.persist_thread_cache === false) return 0
- const raw = Number(this.config.thread_cache_size)
- if (!Number.isFinite(raw) || raw <= 0) return 0
- return Math.floor(raw)
- }
-
- /**
- * `models_max` including the embedding slot bonus.
- *
- * Reserves one extra slot when any embedder is installed so loading it does
- * not evict the user's chat model. Only one embedding model is ever resident
- * (RAG calls load() once per request), so the bonus is +1 regardless of how
- * many are installed. 0 (unlimited) stays unlimited.
- */
- private resolveModelsMax(embeddingCount: number): number {
- const raw = (this.config as { models_max?: unknown }).models_max
- let modelsMax = 1
- if (typeof raw === 'number') modelsMax = raw
- else if (typeof raw === 'string' && raw.trim().length > 0) {
- const n = parseInt(raw, 10)
- if (!Number.isNaN(n) && n >= 0) modelsMax = n
- }
- this.userModelsMax = modelsMax
- const bonus = modelsMax > 0 && embeddingCount > 0 ? 1 : 0
- this.engineEmbeddingBonus = bonus
- return modelsMax + bonus
- }
-
- /**
- * Apply a preset change (model added/removed/renamed or a per-model setting)
- * to the running worker. Models whose preset section is unchanged stay
- * loaded, so an embedder import or a settings write no longer cold-reloads
- * the model the user is talking to.
- *
- * Unlike the router this also resizes `models_max`, so a change in the
- * embedding slot bonus no longer needs a restart either -- which was the one
- * remaining case that evicted a live chat model.
- */
- private async refreshEnginePreset(): Promise<void> {
- if (!(await this.getEngineInfo())) {
- await this.startEngine() // cold start
- return
+ if (mapping.yamlKey in cfg) continue
+
+ const value = persistedSetting?.controller_props?.value
+ // Never re-copy the legacy default; that is what v1 did.
+ if (sidebarKey === 'ngl' && Number(value) === LEGACY_NGL_DEFAULT) {
+ continue
}
- const providerPath = await this.getProviderPath()
- const janDataFolderPath = await getJanDataFolderPath()
- const { path: presetPath, embeddingCount } = await generatePreset(
- providerPath,
- janDataFolderPath,
- this.config
- )
- this.presetPath = presetPath
+ const next = mapping.coerce(value)
+ if (next === null) continue
- try {
- const report = await reloadEngineModels(
- presetPath,
- this.resolveModelsMax(embeddingCount),
- this.resolveThreadCacheBudget()
- )
- logger.info(
- `Engine preset reloaded: +${report.added.length} ~${report.changed.length} -${report.removed.length}, ${report.kept.length} kept loaded`
- )
- } catch (e) {
- logger.warn('Live engine reload failed; falling back to restart:', e)
- await this.startEngine()
- }
- }
+ ; (cfg as Record<string, unknown>)[mapping.yamlKey] = next
+ touched = true
+ }
- /**
- * Public accessor for downstream consumers. Returns `null` if the engine
- * worker hasn't started successfully yet.
- */
- async getEngineInfo(): Promise<{ port: number; apiKey: string } | null> {
- // Deliberately not answered from the cached port: get_engine_info is the
- // one place a worker that died is noticed -- it reaps the handle and
- // reports nothing running -- and every caller here uses this as the
- // liveness probe before deciding whether to respawn. Answering from
- // enginePort would keep handing out a closed port for the rest of the
- // session, which is exactly the crash the worker process exists to survive.
- try {
- const info = await pluginGetEngineInfo()
- if (info) {
- this.enginePort = info.port
- this.engineApiKey = info.api_key
- return { port: info.port, apiKey: info.api_key }
- }
- this.enginePort = undefined
- this.engineApiKey = undefined
- } catch (e) {
- logger.warn('get_engine_info failed:', e)
- }
- return null
+ if (touched) {
+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
+ }
}
- /**
- * The bundled engine's identity. Cached after the first call: these are
- * compile-time constants of the plugin, so they cannot change while the app
- * is running, and the settings screen asks on every mount.
- */
- async getEngineVersion(): Promise<EngineVersion> {
- if (!this.engineVersion) {
- this.engineVersion = await pluginGetEngineVersion()
- }
- return this.engineVersion
- }
-
- /**
- * Fetch runtime properties for a loaded model from the router's
- * `/props?model=<id>` endpoint. Returns `undefined` if the router isn't
- * running, the model isn't loaded, or the response is unusable. `nCtx` is
- * the post-fit value — what `fit_ctx` settled on — so it's the right
- * denominator for the token-usage popup.
- */
- async getModelProps(
- modelId: string
- ): Promise<
- | (ModelProps & {
- modalities?: { vision: boolean; video: boolean; audio: boolean }
- })
- | undefined
- > {
- const engine = await this.getEngineInfo()
- if (!engine || !modelId) return undefined
- // A request naming an unloaded model loads it on demand, so `/props` alone
- // would trigger a load. Gate on the loaded-set first.
- try {
- const loaded = await this.getLoadedModels()
- if (!loaded.includes(modelId)) return undefined
- } catch {
- return undefined
- }
- try {
- const url = `http://127.0.0.1:${engine.port}/props?model=${encodeURIComponent(modelId)}`
- const res = await loopbackFetch(url, {
- headers: { Authorization: `Bearer ${engine.apiKey}` },
- })
- if (!res.ok) return undefined
- const json = (await res.json()) as {
- default_generation_settings?: { n_ctx?: number }
- total_slots?: number
- model_alias?: string
- is_sleeping?: boolean
- modalities?: { vision?: boolean; video?: boolean; audio?: boolean }
- }
- const n = json?.default_generation_settings?.n_ctx
- if (typeof n !== 'number' || n <= 0) return undefined
- const m = json.modalities
- return {
- nCtx: n,
- totalSlots:
- typeof json.total_slots === 'number' ? json.total_slots : undefined,
- modelAlias: json.model_alias,
- isSleeping: !!json.is_sleeping,
- modalities: m
- ? { vision: !!m.vision, video: !!m.video, audio: !!m.audio }
- : undefined,
- }
- } catch {
- return undefined
- }
- }
+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
+ }
- private async readMmprojCapabilities(
- mmprojPath: string
- ): Promise<{ vision: boolean; audio: boolean }> {
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const fullPath = await joinPath([janDataFolderPath, mmprojPath])
- const meta = (await readGgufMetadata(fullPath)).metadata ?? {}
- const truthy = (v: string | undefined) =>
- typeof v === 'string' && v.toLowerCase() === 'true'
- const vision = truthy(meta['clip.has_vision_encoder'])
- const audio = truthy(meta['clip.has_audio_encoder'])
- if (!vision && !audio) return { vision: true, audio: false }
- return { vision, audio }
- } catch (error) {
- logger.warn('Failed to read mmproj capabilities:', error)
- return { vision: true, audio: false }
- }
- }
+ /**
+ * Removes v1's `n_gpu_layers: 100` stamp from every model.yml.
+ *
+ * Separate from the settings backfill because the stamp is in the yaml even
+ * for models that no longer appear in the persisted provider settings, so
+ * iterating the persisted list would miss them.
+ */
+ private async stripLegacyNglFromModelYaml(providerPath: string): Promise<void> {
+ const modelsDir = await joinPath([providerPath, 'models'])
+ if (!(await fs.existsSync(modelsDir))) return
- private async migrateAutoUnloadToModelsMax(): Promise<void> {
- const MIGRATION_KEY = 'llamacpp_models_max_migrated_v1'
- if (await getBackendSetting(MIGRATION_KEY)) return
+ let entries: string[] = []
+ try {
+ entries = await fs.readdirSync(modelsDir)
+ } catch (e) {
+ logger.warn('Could not list models while sweeping legacy ngl:', e)
+ return
+ }
+
+ for (const entry of entries) {
+ const configPath = await joinPath([entry, 'model.yml'])
+ try {
+ if (!(await fs.existsSync(configPath))) continue
+ // Read as a bag rather than ModelConfig: that type covers the
+ // plugin's own fields, not every per-model key the sidebar writes.
+ const cfg = await fs.readYaml<Record<string, unknown>>(configPath)
+ if (cfg?.n_gpu_layers !== LEGACY_NGL_DEFAULT) continue
+ delete cfg.n_gpu_layers
+ await fs.writeYaml(configPath, cfg)
+ logger.info(
+ `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${configPath}`
+ )
+ } catch (e) {
+ // Per-model isolation: one unreadable yaml must not block the sweep.
+ logger.warn(`Legacy ngl sweep skipped ${configPath}:`, e)
+ }
+ }
+ }
+
+ async getProviderPath(): Promise<string> {
+ if (!this.providerPath) {
+ this.providerPath = await joinPath([
+ await getJanDataFolderPath(),
+ this.providerId,
+ ])
+ }
+ return this.providerPath
+ }
+
+ override async onUnload(): Promise<void> {
+ // Terminate all active sessions
+
+ // Clean up validation event listeners
+ if (this.unlistenValidationStarted) {
+ this.unlistenValidationStarted()
+ }
+
+ // Deliberately does NOT stop the engine worker. It outlives any single
+ // extension instance: the app owns its lifetime and stops it on
+ // ExitRequested/Exit. An extension teardown is not an app exit -- React
+ // StrictMode and HMR both unload and immediately reload us, and awaiting
+ // backgroundInit here (as this used to) meant blocking until the worker was
+ // up, then killing exactly the process it had just started.
+ this.enginePort = undefined
+ this.engineApiKey = undefined
+ }
+
+ onSettingUpdate<T>(key: string, value: T): void {
+ this.config[key] = value
+
+ if (key === 'llamacpp_env') {
+ this.llamacpp_env = value as string
+ } else if (key === 'timeout') {
+ // Clamped through the plugin's own coercion: the field is a text input, so
+ // clearing it yields '' and a bare cast produced NaN. 0 or negative would
+ // make the request timeout fire immediately and abort every stream.
+ this.timeout = asI32(value, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT
+ } else if (key === 'models_max') {
+ // Not a `[*]` preset key, so it is deliberately absent from
+ // PRESET_AFFECTING_KEYS -- but the worker still has to be told, or
+ // "Max Concurrently Loaded Models" only ever updated this.config.
+ this.schedulePresetRefresh()
+ } else if (PRESET_AFFECTING_KEYS.has(key)) {
+ // The running worker was started with the previous preset; without a
+ // reload the new value is invisible to inference. Debounced so a flurry
+ // of slider/dropdown updates collapses into one bounce.
+ this.schedulePresetRefresh()
+ }
+ }
+
+ private presetRefreshTimer: ReturnType<typeof setTimeout> | null = null
+ private schedulePresetRefresh(): void {
+ if (this.presetRefreshTimer) clearTimeout(this.presetRefreshTimer)
+ this.presetRefreshTimer = setTimeout(() => {
+ this.presetRefreshTimer = null
+ this.refreshEnginePreset().catch((e) =>
+ logger.warn('Preset refresh after settings update failed:', e)
+ )
+ }, 600)
+ }
+
+ private async generateApiKey(modelId: string, port: string): Promise<string> {
+ const hash = await pluginGenerateApiKey(modelId + port, this.apiSecret)
+ return hash
+ }
+
+ override async get(modelId: string): Promise<modelInfo | undefined> {
+ const modelPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ ])
+ const path = await joinPath([modelPath, 'model.yml'])
+
+ if (!(await fs.existsSync(path))) return undefined
+
+ const modelConfig = await invoke<ModelConfig>('read_yaml', {
+ path,
+ })
+
+ const isEmbedding = await this.resolveEmbeddingConfig(modelId, modelConfig)
+ await this.resolveMtpLayersConfig(modelId, modelConfig)
+ const templateKwargs = await this.resolveTemplateKwargsConfig(
+ modelId,
+ modelConfig
+ )
+
+ return {
+ id: modelId,
+ name: modelConfig.name ?? modelId,
+ quant_type: undefined, // TODO: parse quantization type from model.yml or model.gguf
+ providerId: this.provider,
+ port: 0, // port is not known until the model is loaded
+ sizeBytes: modelConfig.size_bytes ?? 0,
+ embedding: isEmbedding,
+ template_kwargs: templateKwargs,
+ } as modelInfo
+ }
+
+ async getModelContextLimit(modelId: string): Promise<number | undefined> {
+ const config = await invoke<ModelConfig>('read_yaml', {
+ path: await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml']),
+ })
+ const path = await joinPath([await getJanDataFolderPath(), config.model_path])
+ const { metadata } = await readGgufMetadata(path)
+ const limit = Number(metadata?.[`${metadata?.['general.architecture']}.context_length`])
+ return Number.isInteger(limit) && limit > 0 ? limit : undefined
+ }
+
+ /**
+ * Checks if embedding status is known. If not, reads GGUF, detects it,
+ * and updates the model.yml for future performance.
+ */
+ private async resolveEmbeddingConfig(
+ modelId: string,
+ modelConfig: ModelConfig
+ ): Promise<boolean> {
+ const cfg = modelConfig as ModelConfig & { embedding_check_v?: number }
+ const hasFlag = typeof cfg.embedding === 'boolean'
+ const upToDate = cfg.embedding_check_v === EMBEDDING_CHECK_VERSION
+ if (hasFlag && upToDate) {
+ return cfg.embedding as boolean
+ }
+ if (hasFlag && cfg.embedding === true) {
+ return true
+ }
+
+ let isEmbedding = false
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullModelPath = await joinPath([
+ janDataFolderPath,
+ modelConfig.model_path,
+ ])
- try {
- const old = await this.getSetting<boolean | undefined>(
- 'auto_unload',
- undefined
- )
- if (old !== undefined) {
- const targetValue = old ? '1' : '0'
- const settings = await this.getSettings()
- await this.updateSettings(
- settings.map((item) => {
- if (item.key === 'models_max') {
- item.controllerProps.value = targetValue
- }
- return item
- })
- )
- ;(this.config as any).models_max = targetValue
- logger.info(
- `Migrated auto_unload=${old} -> models_max=${targetValue}`
- )
- }
- } catch (e) {
- logger.warn('migrateAutoUnloadToModelsMax failed:', e)
- return
+ if (await fs.existsSync(fullModelPath)) {
+ const metadata = await readGgufMetadata(fullModelPath)
+ if (detectEmbeddingFromGgufMeta(metadata.metadata)) {
+ isEmbedding = true
}
+ }
+ } catch (e) {
+ logger.warn(`Failed to check metadata for ${modelId}`, e)
+ return cfg.embedding === true
+ }
- await setBackendSetting(MIGRATION_KEY, '1')
+ try {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+
+ cfg.embedding = isEmbedding
+ cfg.embedding_check_v = EMBEDDING_CHECK_VERSION
+ if (isEmbedding) {
+ const c = cfg as ModelConfig & {
+ pooling?: string
+ ubatch_size?: number
+ batch_size?: number
+ }
+ if (!c.pooling) c.pooling = 'mean'
+ if (!c.ubatch_size) c.ubatch_size = 2048
+ if (!c.batch_size) c.batch_size = 2048
+ }
+
+ await invoke<void>('write_yaml', {
+ data: cfg,
+ savePath: configPath,
+ })
+ } catch (e) {
+ logger.warn(`Failed to update config for ${modelId}`, e)
+ }
+
+ return isEmbedding
+ }
+
+ private async resolveMtpLayersConfig(
+ modelId: string,
+ modelConfig: ModelConfig
+ ): Promise<number> {
+ const cfg = modelConfig as ModelConfig & {
+ mtp_layers?: number
+ mtp_check_v?: number
+ }
+ if (
+ typeof cfg.mtp_layers === 'number' &&
+ cfg.mtp_check_v === MTP_CHECK_VERSION
+ ) {
+ return cfg.mtp_layers
+ }
+
+ let mtpLayers = 0
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullModelPath = await joinPath([
+ janDataFolderPath,
+ modelConfig.model_path,
+ ])
+ if (await fs.existsSync(fullModelPath)) {
+ const metadata = await readGgufMetadata(fullModelPath)
+ mtpLayers = detectMtpLayersFromGgufMeta(metadata.metadata)
+ }
+ } catch (e) {
+ logger.warn(`Failed to check MTP metadata for ${modelId}`, e)
+ return cfg.mtp_layers ?? 0
}
- // The old default was 1 plus two slots Jan reserved for background work and
- // Cowork; both now share slot 0, so the reservation is gone and a persisted
- // 1 would pin the engine to a single slot rather than letting it resolve its
- // own count. Only the old default value is moved.
- private async migrateParallelToDefault(): Promise<void> {
- const MIGRATION_KEY = 'llamacpp_parallel_default_v1'
- if (await getBackendSetting(MIGRATION_KEY)) return
+ try {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ cfg.mtp_layers = mtpLayers
+ cfg.mtp_check_v = MTP_CHECK_VERSION
+ await invoke<void>('write_yaml', {
+ data: cfg,
+ savePath: configPath,
+ })
+ } catch (e) {
+ logger.warn(`Failed to persist MTP layers for ${modelId}`, e)
+ }
+
+ return mtpLayers
+ }
+
+ /**
+ * Detect which chat-template kwargs (e.g. `preserve_thinking`) a model's
+ * embedded jinja template accepts, caching the result in model.yml. Migrates
+ * pre-existing models lazily the first time list() sees a stale check version.
+ */
+ private async resolveTemplateKwargsConfig(
+ modelId: string,
+ modelConfig: ModelConfig
+ ): Promise<TemplateKwarg[]> {
+ const cfg = modelConfig as ModelConfig & {
+ template_kwargs?: TemplateKwarg[]
+ template_kwargs_check_v?: number
+ }
+ if (
+ Array.isArray(cfg.template_kwargs) &&
+ cfg.template_kwargs_check_v === TEMPLATE_KWARGS_CHECK_VERSION
+ ) {
+ return cfg.template_kwargs
+ }
+
+ let kwargs: TemplateKwarg[] = []
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullModelPath = await joinPath([
+ janDataFolderPath,
+ modelConfig.model_path,
+ ])
+ if (await fs.existsSync(fullModelPath)) {
+ const metadata = await readGgufMetadata(fullModelPath)
+ kwargs = detectTemplateKwargsFromChatTemplate(
+ metadata.metadata?.['tokenizer.chat_template']
+ )
+ }
+ } catch (e) {
+ logger.warn(`Failed to check template kwargs for ${modelId}`, e)
+ return cfg.template_kwargs ?? []
+ }
+ try {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ cfg.template_kwargs = kwargs
+ cfg.template_kwargs_check_v = TEMPLATE_KWARGS_CHECK_VERSION
+ await invoke<void>('write_yaml', {
+ data: cfg,
+ savePath: configPath,
+ })
+ } catch (e) {
+ logger.warn(`Failed to persist template kwargs for ${modelId}`, e)
+ }
+
+ return kwargs
+ }
+
+ // Implement the required LocalProvider interface methods
+ override async list(): Promise<modelInfo[]> {
+ const modelsDir = await joinPath([await this.getProviderPath(), 'models'])
+ if (!(await fs.existsSync(modelsDir))) {
+ await fs.mkdir(modelsDir)
+ }
+
+ // Legacy migration is best-effort: a failure here must never blank the
+ // model list. Pre-router users without anything to migrate would never
+ // notice, but a single throw used to bubble out of list() and return [].
+ try {
+ await this.migrateLegacyModels()
+ } catch (err) {
+ logger.warn(`list: migrateLegacyModels failed, continuing: ${String(err)}`)
+ }
+
+ let modelIds: string[] = []
+
+ // DFS. Mirror the defensive pattern in preset.ts: an unreadable entry
+ // (Windows AV quarantine, junction, locked file) must not kill the whole
+ // scan — log and continue past it.
+ let stack = [modelsDir]
+ while (stack.length > 0) {
+ const currentDir = stack.pop()
+
+ // check if model.yml exists
+ const modelConfigPath = await joinPath([currentDir, 'model.yml'])
+ if (await fs.existsSync(modelConfigPath)) {
+ // +1 to remove the leading slash
+ // NOTE: this does not handle Windows path \\
+ modelIds.push(currentDir.slice(modelsDir.length + 1))
+ continue
+ }
+
+ let children: string[] = []
+ try {
+ children = await fs.readdirSync(currentDir)
+ } catch (err) {
+ logger.warn(`list: readdir failed for ${currentDir}: ${String(err)}`)
+ continue
+ }
+ for (const child of children) {
try {
- if (asI32(this.config.parallel, 0) === 1) {
- const settings = await this.getSettings()
- await this.updateSettings(
- settings.map((item) => {
- if (item.key === 'parallel') {
- item.controllerProps.value = 0
- }
- return item
- })
- )
- this.config.parallel = 0
- logger.info('Migrated parallel: 1 -> 0 (llama.cpp default)')
- }
- } catch (e) {
- logger.warn('migrateParallelToDefault failed:', e)
- return
+ const dirInfo = await fs.fileStat(child)
+ if (!dirInfo?.isDirectory) continue
+ stack.push(child)
+ } catch (err) {
+ logger.warn(`list: stat failed for ${child}: ${String(err)}`)
}
-
- await setBackendSetting(MIGRATION_KEY, '1')
+ }
}
- private async migrateFitOff(): Promise<void> {
- const MIGRATION_KEY = 'llamacpp_fit_off_v1'
- if (await getBackendSetting(MIGRATION_KEY)) return
-
- if (this.config.fit === true) {
- const settings = await this.getSettings()
- await this.updateSettings(
- settings.map((item) => {
- if (item.key === 'fit') {
- item.controllerProps.value = false
- }
- return item
- })
- )
- this.config.fit = false
- logger.info('Migrated fit setting: disabled')
- }
+ // Per-model isolation: one malformed model.yml (or a write_yaml failure
+ // inside resolveEmbeddingConfig) must not discard the other entries.
+ let modelInfos: modelInfo[] = []
+ for (const modelId of modelIds) {
+ try {
+ const path = await joinPath([modelsDir, modelId, 'model.yml'])
+ const modelConfig = await invoke<ModelConfig>('read_yaml', { path })
+ const isEmbedding = await this.resolveEmbeddingConfig(
+ modelId,
+ modelConfig
+ )
+ const templateKwargs = await this.resolveTemplateKwargsConfig(
+ modelId,
+ modelConfig
+ )
- await setBackendSetting(MIGRATION_KEY, '1')
+ const capabilities: string[] = []
+ if (modelConfig.mmproj_path) {
+ const caps = await this.readMmprojCapabilities(
+ modelConfig.mmproj_path
+ )
+ if (caps.vision) capabilities.push('vision')
+ if (caps.audio) capabilities.push('audio')
+ // 'video' is intentionally NOT derived from the mmproj here — video
+ // support also depends on the backend being built with MTMD_VIDEO,
+ // which the GGUF can't reveal. It's reconciled from /props after the
+ // model loads (see useReconcileVideoCapability).
+ }
+
+ const mp = modelConfig.model_path ?? ''
+ const isAbsolute = mp.startsWith('/') || /^[A-Za-z]:[\\/]/.test(mp)
+
+ const modelInfo = {
+ id: modelId,
+ name: modelConfig.name ?? modelId,
+ quant_type: undefined, // TODO: parse quantization type from model.yml or model.gguf
+ providerId: this.provider,
+ port: 0, // port is not known until the model is loaded
+ sizeBytes: modelConfig.size_bytes ?? 0,
+ embedding: isEmbedding,
+ imported: isAbsolute,
+ capabilities: capabilities.length > 0 ? capabilities : undefined,
+ template_kwargs: templateKwargs,
+ } as modelInfo
+ modelInfos.push(modelInfo)
+ } catch (err) {
+ logger.warn(`list: skipping model ${modelId}: ${String(err)}`)
+ }
}
- private async migratePersistedModelSettingsToYaml(): Promise<void> {
- if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return
+ return modelInfos
+ }
- const persistedModels = await readPersistedLlamacppModels()
- const providerPath = await this.getProviderPath()
+ private async migrateLegacyModels() {
+ // Attempt to migrate only once
+ if ((await getBackendSetting('cortex_models_migrated')) === 'true') return
- // v1's n_gpu_layers stamp lives in model.yml, not in the persisted
- // settings, so it has to be swept even when nothing is persisted.
- await this.stripLegacyNglFromModelYaml(providerPath)
+ const janDataFolderPath = await getJanDataFolderPath()
+ const modelsDir = await joinPath([janDataFolderPath, 'models'])
+ if (!(await fs.existsSync(modelsDir))) return
- if (persistedModels.length === 0) {
- await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
- return
- }
-
- for (const persistedModel of persistedModels) {
- const modelId =
- typeof persistedModel.id === 'string' ? persistedModel.id : undefined
- if (!modelId || !persistedModel.settings) continue
+ // DFS
+ let stack = [modelsDir]
+ while (stack.length > 0) {
+ const currentDir = stack.pop()
- const configPath = await joinPath([
- providerPath,
+ const files = await fs.readdirSync(currentDir)
+ for (const child of files) {
+ try {
+ const childPath = await joinPath([currentDir, child])
+ const stat = await fs.fileStat(childPath)
+ if (
+ files.some((e) => e.endsWith('model.yml')) &&
+ !child.endsWith('model.yml')
+ )
+ continue
+ if (!stat.isDirectory && child.endsWith('.yml')) {
+ // check if model.yml exists
+ const modelConfigPath = child
+ if (await fs.existsSync(modelConfigPath)) {
+ const legacyModelConfig = await invoke<{
+ files: string[]
+ model: string
+ }>('read_yaml', {
+ path: modelConfigPath,
+ })
+ const legacyModelPath = legacyModelConfig.files?.[0]
+ if (!legacyModelPath) continue
+ // +1 to remove the leading slash
+ // NOTE: this does not handle Windows path \\
+ let modelId = currentDir.slice(modelsDir.length + 1)
+
+ modelId =
+ modelId !== 'imported'
+ ? modelId.replace(/^(cortex\.so|huggingface\.co)[\/\\]/, '')
+ : (await basename(child)).replace('.yml', '')
+
+ const modelName = legacyModelConfig.model ?? modelId
+ const configPath = await joinPath([
+ await this.getProviderPath(),
'models',
modelId,
'model.yml',
- ])
- if (!(await fs.existsSync(configPath))) continue
+ ])
+ if (await fs.existsSync(configPath)) continue // Don't reimport
- const cfg = (await invoke<ModelConfig>('read_yaml', {
- path: configPath,
- })) as ModelConfig & Record<string, unknown>
+ // this is relative to Jan's data folder
+ const modelDir = `${this.providerId}/models/${modelId}`
- let touched = false
-
- // Undo v1's n_gpu_layers stamp so upstream's auto offload applies again.
- if (cfg.n_gpu_layers === LEGACY_NGL_DEFAULT) {
- delete (cfg as Record<string, unknown>).n_gpu_layers
- touched = true
- logger.info(
- `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${modelId}; GPU offload is auto again`
+ let size_bytes = (
+ await fs.fileStat(
+ await joinPath([janDataFolderPath, legacyModelPath])
)
+ ).size
+
+ const modelConfig = {
+ model_path: legacyModelPath,
+ mmproj_path: undefined, // legacy models do not have mmproj
+ name: modelName,
+ size_bytes,
+ } as ModelConfig
+ await fs.mkdir(await joinPath([janDataFolderPath, modelDir]))
+ await invoke<void>('write_yaml', {
+ data: modelConfig,
+ savePath: configPath,
+ })
+ continue
}
+ }
+ } catch (error) {
+ logger.error(`Error migrating model ${child}:`, error)
+ }
+ }
- for (const [sidebarKey, persistedSetting] of Object.entries(
- persistedModel.settings
- )) {
- const mapping = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
- if (!mapping) continue
-
- if (mapping.yamlKey in cfg) continue
-
- const value = persistedSetting?.controller_props?.value
- // Never re-copy the legacy default; that is what v1 did.
- if (sidebarKey === 'ngl' && Number(value) === LEGACY_NGL_DEFAULT) {
- continue
- }
+ let subdirs: string[] = []
+ try {
+ subdirs = await fs.readdirSync(currentDir)
+ } catch (err) {
+ logger.warn(
+ `migrateLegacyModels: readdir failed for ${currentDir}: ${String(err)}`
+ )
+ continue
+ }
+ for (const child of subdirs) {
+ try {
+ const dirInfo = await fs.fileStat(child)
+ if (!dirInfo?.isDirectory) continue
+ stack.push(child)
+ } catch (err) {
+ logger.warn(
+ `migrateLegacyModels: stat failed for ${child}: ${String(err)}`
+ )
+ }
+ }
+ }
+ await setBackendSetting('cortex_models_migrated', 'true')
+ }
+
+ /**
+ * Update a model with new information.
+ * @param modelId
+ * @param model
+ */
+ async update(modelId: string, model: Partial<modelInfo>): Promise<void> {
+ const modelFolderPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ ])
+ const modelConfig = await invoke<ModelConfig>('read_yaml', {
+ path: await joinPath([modelFolderPath, 'model.yml']),
+ })
+ const newFolderPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ model.id,
+ ])
+ // Check if newFolderPath exists
+ if (await fs.existsSync(newFolderPath)) {
+ throw new Error(`Model with ID ${model.id} already exists`)
+ }
+ const newModelConfigPath = await joinPath([newFolderPath, 'model.yml'])
+ await fs.mv(modelFolderPath, newFolderPath).then(() =>
+ // now replace what values have previous model name with format
+ invoke('write_yaml', {
+ data: {
+ ...modelConfig,
+ model_path: modelConfig?.model_path?.replace(
+ `${this.providerId}/models/${modelId}`,
+ `${this.providerId}/models/${model.id}`
+ ),
+ mmproj_path: modelConfig?.mmproj_path?.replace(
+ `${this.providerId}/models/${modelId}`,
+ `${this.providerId}/models/${model.id}`
+ ),
+ },
+ savePath: newModelConfigPath,
+ })
+ )
- const next = mapping.coerce(value)
- if (next === null) continue
+ // The router's preset still references the old model id until we
+ // regenerate; without this a `POST /models/load <new-id>` would 404.
+ try {
+ await this.refreshEnginePreset()
+ } catch (e) {
+ logger.warn(`Router restart after model rename (${modelId} → ${model.id}) failed`, e)
+ }
+ }
+
+ /**
+ * 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 modelId
+ if (!/^[a-zA-Z0-9/_\-\.]+$/.test(id)) return false
+
+ // check for empty parts or path traversal
+ const parts = id.split('/')
+ return parts.every((s) => s !== '' && s !== '.' && s !== '..')
+ }
+
+ if (!isValidModelId(modelId))
+ throw new Error(
+ `Invalid modelId: ${modelId}. Only alphanumeric and / _ - . characters are allowed.`
+ )
+
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (await fs.existsSync(configPath))
+ throw new Error(`Model ${modelId} already exists`)
+
+ // this is relative to Jan's data folder
+ const modelDir = `${this.providerId}/models/${modelId}`
+
+ // we only use these from opts
+ // opts.modelPath: URL to the model file
+ // opts.mmprojPath: URL to the mmproj file
+
+ let downloadItems: DownloadItem[] = []
+
+ const maybeDownload = async (path: string, saveName: string) => {
+ // if URL, add to downloadItems, and return local path
+ if (path.startsWith('https://')) {
+ const localPath = `${modelDir}/${saveName}`
+ downloadItems.push({
+ url: path,
+ save_path: localPath,
+ proxy: await getProxyConfig(),
+ sha256:
+ saveName === 'model.gguf'
+ ? opts.modelSha256
+ : saveName === 'mmproj.gguf'
+ ? opts.mmprojSha256
+ : undefined,
+ size:
+ saveName === 'model.gguf'
+ ? opts.modelSize
+ : saveName === 'mmproj.gguf'
+ ? opts.mmprojSize
+ : undefined,
+ model_id: modelId,
+ })
+ return localPath
+ }
+
+ // if local file (absolute path), check if it exists
+ // and return the path
+ if (!(await fs.existsSync(path)))
+ throw new Error(`File not found: ${path}`)
+ return path
+ }
+
+ let modelPath = await maybeDownload(opts.modelPath, 'model.gguf')
+ let mmprojPath = opts.mmprojPath
+ ? await maybeDownload(opts.mmprojPath, 'mmproj.gguf')
+ : undefined
+ // Speculative-decoding draft companion; paired with the main model. The
+ // file name stays `mtp.gguf` for every flavour: it is the local name of
+ // the paired draft, and changing it would orphan existing installs.
+ let draftModelPath = opts.specDraftPath
+ ? await maybeDownload(opts.specDraftPath, 'mtp.gguf')
+ : undefined
+
+ if (downloadItems.length > 0) {
+ try {
+ // emit download update event on progress
+ const onProgress = (transferred: number, total: number) => {
+ events.emit(DownloadEvent.onFileDownloadUpdate, {
+ modelId,
+ percent: transferred / total,
+ size: { transferred, total },
+ downloadType: 'Model',
+ })
+ }
+ const downloadManager = window.core.extensionManager.getByName(
+ '@janhq/download-extension'
+ )
+ await downloadManager.downloadFiles(
+ downloadItems,
+ this.createDownloadTaskId(modelId),
+ onProgress
+ )
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : String(error)
+
+ // Check if this is a cancellation
+ const isCancellationError =
+ errorMessage.includes('Download cancelled') ||
+ errorMessage.includes('Validation cancelled') ||
+ errorMessage.includes('Hash computation cancelled') ||
+ errorMessage.includes('cancelled') ||
+ errorMessage.includes('aborted')
+
+ // Check if this is a validation failure
+ const isValidationError =
+ errorMessage.includes('Hash verification failed') ||
+ errorMessage.includes('Size verification failed') ||
+ errorMessage.includes('Failed to verify file')
+
+ // Pause and cancel both surface here as a cancellation; treat as a
+ // stop (emit stopped, return) so it never becomes an error toast.
+ if (isCancellationError) {
+ logger.info('Download stopped for model:', modelId)
+ events.emit(DownloadEvent.onFileDownloadStopped, {
+ modelId,
+ downloadType: 'Model',
+ })
+ return
+ }
- ;(cfg as Record<string, unknown>)[mapping.yamlKey] = next
- touched = true
- }
+ logger.error('Error downloading model:', modelId, opts, error)
+ if (isValidationError) {
+ // Cancel any other download tasks for this model
+ try {
+ this.abortImport(modelId)
+ } catch (cancelError) {
+ logger.warn('Failed to cancel download task:', cancelError)
+ }
- if (touched) {
- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
- }
+ // Emit validation failure event
+ events.emit(DownloadEvent.onModelValidationFailed, {
+ modelId,
+ downloadType: 'Model',
+ error: errorMessage,
+ reason: 'validation_failed',
+ })
+ } else {
+ // Regular download error
+ events.emit(DownloadEvent.onFileDownloadError, {
+ modelId,
+ downloadType: 'Model',
+ error: errorMessage,
+ })
}
-
- await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')
+ throw error
+ }
}
- /**
- * Removes v1's `n_gpu_layers: 100` stamp from every model.yml.
- *
- * Separate from the settings backfill because the stamp is in the yaml even
- * for models that no longer appear in the persisted provider settings, so
- * iterating the persisted list would miss them.
- */
- private async stripLegacyNglFromModelYaml(providerPath: string): Promise<void> {
- const modelsDir = await joinPath([providerPath, 'models'])
- if (!(await fs.existsSync(modelsDir))) return
+ // Validate GGUF files
+ const janDataFolderPath = await getJanDataFolderPath()
+ const fullModelPath = await joinPath([janDataFolderPath, modelPath])
+ let isEmbedding = false
+ let mtpLayers = 0
+ let specKind: SpecDraftKind = 'mtp'
+ let templateKwargs: TemplateKwarg[] = []
+ let resolvedName: string | undefined
- let entries: string[] = []
- try {
- entries = await fs.readdirSync(modelsDir)
- } catch (e) {
- logger.warn('Could not list models while sweeping legacy ngl:', e)
- return
- }
+ try {
+ // Validate main model file
+ const modelMetadata = await readGgufMetadata(fullModelPath)
+ logger.info(
+ `Model GGUF validation successful: version ${modelMetadata.version}, tensors: ${modelMetadata.tensor_count}`
+ )
+
+ if (detectEmbeddingFromGgufMeta(modelMetadata.metadata)) {
+ isEmbedding = true
+ }
+ mtpLayers = detectMtpLayersFromGgufMeta(modelMetadata.metadata)
+ templateKwargs = detectTemplateKwargsFromChatTemplate(
+ modelMetadata.metadata?.['tokenizer.chat_template']
+ )
+
+ const rawName = modelMetadata.metadata?.['general.name']
+ if (typeof rawName === 'string') {
+ const normalized = rawName.trim().replace(/\s+/g, '-')
+ if (normalized.length > 0) resolvedName = normalized
+ }
+
+ // Validate mmproj file if present
+ if (mmprojPath) {
+ const fullMmprojPath = await joinPath([janDataFolderPath, mmprojPath])
+ const mmprojMetadata = await readGgufMetadata(fullMmprojPath)
+ logger.info(
+ `Mmproj GGUF validation successful: version ${mmprojMetadata.version}, tensors: ${mmprojMetadata.tensor_count}`
+ )
+ }
+
+ // Validate the draft, decide which spec type it implements, and read
+ // its head count (the main gguf usually lacks nextn_predict_layers when
+ // MTP ships as a separate file).
+ if (draftModelPath) {
+ const fullDraftPath = await joinPath([janDataFolderPath, draftModelPath])
+ const draftMetadata = await readGgufMetadata(fullDraftPath)
+ // Only asked for a DFlash-architecture draft, since that is the one
+ // case a tensor decides (DSpark = DFlash + Markov head).
+ const hasMarkovHead =
+ draftMetadata.metadata?.['general.architecture'] === 'dflash'
+ ? (await findGgufTensors(fullDraftPath, [MARKOV_HEAD_TENSOR]))
+ .length > 0
+ : undefined
+ specKind = resolveSpecDraftKind(draftMetadata.metadata, {
+ hasMarkovHead,
+ hint: opts.specDraftKind,
+ })
+ const draftLayers = detectMtpLayersFromGgufMeta(draftMetadata.metadata)
+ // Only an MTP head reports nextn layers; the other flavours have none,
+ // and the count is what makes the settings panel offer the toggle.
+ mtpLayers = draftLayers > 0 ? draftLayers : Math.max(mtpLayers, 1)
+ }
+ } catch (error) {
+ logger.error('GGUF validation failed:', error)
+ throw new Error(
+ `Invalid GGUF file(s): ${error.message || 'File format validation failed'
+ }`
+ )
+ }
+
+ // Calculate file sizes
+ let size_bytes = (await fs.fileStat(fullModelPath)).size
+ if (mmprojPath) {
+ size_bytes += (
+ await fs.fileStat(await joinPath([janDataFolderPath, mmprojPath]))
+ ).size
+ }
+ if (draftModelPath) {
+ size_bytes += (
+ await fs.fileStat(await joinPath([janDataFolderPath, draftModelPath]))
+ ).size
+ }
+
+ if (!resolvedName) {
+ const base = opts.modelPath.split(/[\\/]/).pop() ?? modelId
+ resolvedName = base.replace(/\.gguf$/i, '') || modelId
+ }
+
+ // TODO: add updateModelConfig() method
+ const modelConfig = {
+ model_path: modelPath,
+ mmproj_path: mmprojPath,
+ name: resolvedName,
+ size_bytes,
+ model_sha256: opts.modelSha256,
+ model_size_bytes: opts.modelSize,
+ mmproj_sha256: opts.mmprojSha256,
+ mmproj_size_bytes: opts.mmprojSize,
+ embedding: isEmbedding,
+ embedding_check_v: EMBEDDING_CHECK_VERSION,
+ mtp_layers: mtpLayers,
+ mtp_check_v: MTP_CHECK_VERSION,
+ template_kwargs: templateKwargs,
+ template_kwargs_check_v: TEMPLATE_KWARGS_CHECK_VERSION,
+ // A separate draft gguf is downloaded only to be used, so enable it by
+ // default. Embedded-MTP models stay opt-in (no flag written here) and
+ // need no spec_type: their flavour is always draft-mtp.
+ ...(draftModelPath
+ ? {
+ mtp_model_path: draftModelPath,
+ mtp: true,
+ spec_type: `draft-${specKind}`,
+ }
+ : {}),
+ ...(isEmbedding
+ ? { pooling: 'mean', ubatch_size: 2048, batch_size: 2048 }
+ : {}),
+ } as ModelConfig
+ await fs.mkdir(await joinPath([janDataFolderPath, modelDir]))
+ await invoke<void>('write_yaml', {
+ data: modelConfig,
+ savePath: configPath,
+ })
+ events.emit(AppEvent.onModelImported, {
+ modelId,
+ modelPath,
+ mmprojPath,
+ size_bytes,
+ model_sha256: opts.modelSha256,
+ model_size_bytes: opts.modelSize,
+ mmproj_sha256: opts.mmprojSha256,
+ mmproj_size_bytes: opts.mmprojSize,
+ embedding: isEmbedding,
+ })
+
+ if (downloadItems.length > 0) {
+ events.emit(DownloadEvent.onFileDownloadAndVerificationSuccess, {
+ modelId,
+ downloadType: 'Model',
+ })
+ }
- for (const entry of entries) {
- const configPath = await joinPath([entry, 'model.yml'])
- try {
- if (!(await fs.existsSync(configPath))) continue
- // Read as a bag rather than ModelConfig: that type covers the
- // plugin's own fields, not every per-model key the sidebar writes.
- const cfg = await fs.readYaml<Record<string, unknown>>(configPath)
- if (cfg?.n_gpu_layers !== LEGACY_NGL_DEFAULT) continue
- delete cfg.n_gpu_layers
- await fs.writeYaml(configPath, cfg)
- logger.info(
- `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${configPath}`
- )
- } catch (e) {
- // Per-model isolation: one unreadable yaml must not block the sweep.
- logger.warn(`Legacy ngl sweep skipped ${configPath}:`, e)
- }
- }
+ try {
+ await this.refreshEnginePreset()
+ } catch (e) {
+ logger.warn(`Router refresh after import(${modelId}) failed:`, e)
}
+ }
- async getProviderPath(): Promise<string> {
- if (!this.providerPath) {
- this.providerPath = await joinPath([
- await getJanDataFolderPath(),
- this.providerId,
- ])
- }
- return this.providerPath
+ /**
+ * Deletes the entire model folder for a given modelId
+ * @param modelId The model ID to delete
+ */
+ private async deleteModelFolder(modelId: string): Promise<void> {
+ try {
+ const modelDir = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ ])
+
+ if (await fs.existsSync(modelDir)) {
+ logger.info(`Cleaning up model directory: ${modelDir}`)
+ await fs.rm(modelDir)
+ }
+ } catch (deleteError) {
+ logger.warn('Failed to delete model directory:', deleteError)
}
+ }
+
+ override async abortImport(modelId: string): Promise<void> {
+ // Cancel any active download task
+ // prepend provider name to avoid name collision
+ const taskId = this.createDownloadTaskId(modelId)
+ const downloadManager = window.core.extensionManager.getByName(
+ '@janhq/download-extension'
+ )
- override async onUnload(): Promise<void> {
- // Terminate all active sessions
+ try {
+ await downloadManager.cancelDownload(taskId)
+ } catch (cancelError) {
+ logger.warn('Failed to cancel download task:', cancelError)
+ }
+
+ // Delete the entire model folder if it exists (for validation failures)
+ await this.deleteModelFolder(modelId)
+ }
+
+ override async pauseImport(modelId: string): Promise<void> {
+ const taskId = this.createDownloadTaskId(modelId)
+ const downloadManager = window.core.extensionManager.getByName(
+ '@janhq/download-extension'
+ )
+ // Pause keeps the partial .tmp for resume; the model folder is preserved.
+ await downloadManager.pauseDownload(taskId)
+ }
+
+ private async getRandomPort(): Promise<number> {
+ return 49152 + Math.floor(Math.random() * (65535 - 49152))
+ }
+
+ private parseEnvFromString(
+ target: Record<string, string>,
+ envString: string
+ ): void {
+ envString
+ .split(';')
+ .filter((pair) => pair.trim())
+ .forEach((pair) => {
+ const [key, ...valueParts] = pair.split('=')
+ const cleanKey = key?.trim()
- // Clean up validation event listeners
- if (this.unlistenValidationStarted) {
- this.unlistenValidationStarted()
+ if (
+ cleanKey &&
+ valueParts.length > 0 &&
+ !cleanKey.startsWith('LLAMA')
+ ) {
+ target[cleanKey] = valueParts.join('=').trim()
}
+ })
+ }
- // Deliberately does NOT stop the engine worker. It outlives any single
- // extension instance: the app owns its lifetime and stops it on
- // ExitRequested/Exit. An extension teardown is not an app exit -- React
- // StrictMode and HMR both unload and immediately reload us, and awaiting
- // backgroundInit here (as this used to) meant blocking until the worker was
- // up, then killing exactly the process it had just started.
- this.enginePort = undefined
- this.engineApiKey = undefined
+ override async load(
+ modelId: string,
+ _settings?: unknown,
+ isEmbedding: boolean = false
+ ): Promise<SessionInfo> {
+ const sInfo = await this.findSessionByModel(modelId)
+ if (sInfo) {
+ throw new Error('Model already loaded!!')
}
- onSettingUpdate<T>(key: string, value: T): void {
- this.config[key] = value
-
- if (key === 'llamacpp_env') {
- this.llamacpp_env = value as string
- } else if (key === 'timeout') {
- // Clamped through the plugin's own coercion: the field is a text input, so
- // clearing it yields '' and a bare cast produced NaN. 0 or negative would
- // make the request timeout fire immediately and abort every stream.
- this.timeout = asI32(value, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT
- } else if (key === 'models_max') {
- // Not a `[*]` preset key, so it is deliberately absent from
- // PRESET_AFFECTING_KEYS -- but the worker still has to be told, or
- // "Max Concurrently Loaded Models" only ever updated this.config.
- this.schedulePresetRefresh()
- } else if (PRESET_AFFECTING_KEYS.has(key)) {
- // The running worker was started with the previous preset; without a
- // reload the new value is invisible to inference. Debounced so a flurry
- // of slider/dropdown updates collapses into one bounce.
- this.schedulePresetRefresh()
- }
+ if (this.loadingModels.has(modelId)) {
+ return this.loadingModels.get(modelId)!
}
- private presetRefreshTimer: ReturnType<typeof setTimeout> | null = null
- private schedulePresetRefresh(): void {
- if (this.presetRefreshTimer) clearTimeout(this.presetRefreshTimer)
- this.presetRefreshTimer = setTimeout(() => {
- this.presetRefreshTimer = null
- this.refreshEnginePreset().catch((e) =>
- logger.warn('Preset refresh after settings update failed:', e)
- )
- }, 600)
+ const loadingPromise = this.performLoad(modelId, isEmbedding)
+ this.loadingModels.set(modelId, loadingPromise)
+
+ try {
+ return await loadingPromise
+ } finally {
+ this.loadingModels.delete(modelId)
+ }
+ }
+
+ // Awaits the deferred startup, then makes one direct attempt if the worker
+ // still isn't up. Safe to call redundantly: start_engine returns the running
+ // worker rather than spawning a second one.
+ private async ensureEngineReady(): Promise<void> {
+ await this.ensureProvisioned().catch(() => undefined)
+ if (!(await this.getEngineInfo())) {
+ await this.startEngine()
+ }
+ }
+
+ private async performLoad(
+ modelId: string,
+ isEmbedding: boolean = false
+ ): Promise<SessionInfo> {
+ await this.ensureEngineReady()
+ // The worker lists GPUs once, at start. A laptop that left eco mode (or lost
+ // its dGPU) since then would load this model onto the wrong device, and the
+ // user would have to find Settings > Hardware > Refresh to fix it.
+ try {
+ await this.reconcileEngineDevices(modelId)
+ } catch (e) {
+ // A failed restart surfaces as "engine is not running" just below.
+ logger.warn('Could not re-check the engine devices before loading:', e)
+ }
+ if (!(await this.getEngineInfo())) {
+ throw new Error(
+ 'The llama.cpp engine is not running. Please restart the app.'
+ )
}
- private async generateApiKey(modelId: string, port: string): Promise<string> {
- const hash = await pluginGenerateApiKey(modelId + port, this.apiSecret)
- return hash
+ if (!isEmbedding) {
+ await this.evictChatIfAtCapacity(modelId)
}
- override async get(modelId: string): Promise<modelInfo | undefined> {
- const modelPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- ])
- const path = await joinPath([modelPath, 'model.yml'])
-
- if (!(await fs.existsSync(path))) return undefined
-
- const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path,
- })
-
- const isEmbedding = await this.resolveEmbeddingConfig(modelId, modelConfig)
- await this.resolveMtpLayersConfig(modelId, modelConfig)
- const templateKwargs = await this.resolveTemplateKwargsConfig(
- modelId,
- modelConfig
- )
-
- return {
- id: modelId,
- name: modelConfig.name ?? modelId,
- quant_type: undefined, // TODO: parse quantization type from model.yml or model.gguf
- providerId: this.provider,
- port: 0, // port is not known until the model is loaded
- sizeBytes: modelConfig.size_bytes ?? 0,
- embedding: isEmbedding,
- template_kwargs: templateKwargs,
- } as modelInfo
- }
-
- async getModelContextLimit(modelId: string): Promise<number | undefined> {
- const config = await invoke<ModelConfig>('read_yaml', {
- path: await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml']),
- })
- const path = await joinPath([await getJanDataFolderPath(), config.model_path])
- const { metadata } = await readGgufMetadata(path)
- const limit = Number(metadata?.[`${metadata?.['general.architecture']}.context_length`])
- return Number.isInteger(limit) && limit > 0 ? limit : undefined
- }
-
- /**
- * Checks if embedding status is known. If not, reads GGUF, detects it,
- * and updates the model.yml for future performance.
- */
- private async resolveEmbeddingConfig(
- modelId: string,
- modelConfig: ModelConfig
- ): Promise<boolean> {
- const cfg = modelConfig as ModelConfig & { embedding_check_v?: number }
- const hasFlag = typeof cfg.embedding === 'boolean'
- const upToDate = cfg.embedding_check_v === EMBEDDING_CHECK_VERSION
- if (hasFlag && upToDate) {
- return cfg.embedding as boolean
- }
- if (hasFlag && cfg.embedding === true) {
- return true
- }
-
- let isEmbedding = false
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const fullModelPath = await joinPath([
- janDataFolderPath,
- modelConfig.model_path,
- ])
-
- if (await fs.existsSync(fullModelPath)) {
- const metadata = await readGgufMetadata(fullModelPath)
- if (detectEmbeddingFromGgufMeta(metadata.metadata)) {
- isEmbedding = true
- }
- }
- } catch (e) {
- logger.warn(`Failed to check metadata for ${modelId}`, e)
- return cfg.embedding === true
- }
-
- try {
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
-
- cfg.embedding = isEmbedding
- cfg.embedding_check_v = EMBEDDING_CHECK_VERSION
- if (isEmbedding) {
- const c = cfg as ModelConfig & {
- pooling?: string
- ubatch_size?: number
- batch_size?: number
- }
- if (!c.pooling) c.pooling = 'mean'
- if (!c.ubatch_size) c.ubatch_size = 2048
- if (!c.batch_size) c.batch_size = 2048
- }
-
- await invoke<void>('write_yaml', {
- data: cfg,
- savePath: configPath,
- })
- } catch (e) {
- logger.warn(`Failed to update config for ${modelId}`, e)
- }
-
- return isEmbedding
- }
-
- private async resolveMtpLayersConfig(
- modelId: string,
- modelConfig: ModelConfig
- ): Promise<number> {
- const cfg = modelConfig as ModelConfig & {
- mtp_layers?: number
- mtp_check_v?: number
- }
- if (
- typeof cfg.mtp_layers === 'number' &&
- cfg.mtp_check_v === MTP_CHECK_VERSION
- ) {
- return cfg.mtp_layers
- }
-
- let mtpLayers = 0
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const fullModelPath = await joinPath([
- janDataFolderPath,
- modelConfig.model_path,
- ])
- if (await fs.existsSync(fullModelPath)) {
- const metadata = await readGgufMetadata(fullModelPath)
- mtpLayers = detectMtpLayersFromGgufMeta(metadata.metadata)
- }
- } catch (e) {
- logger.warn(`Failed to check MTP metadata for ${modelId}`, e)
- return cfg.mtp_layers ?? 0
- }
-
- try {
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- cfg.mtp_layers = mtpLayers
- cfg.mtp_check_v = MTP_CHECK_VERSION
- await invoke<void>('write_yaml', {
- data: cfg,
- savePath: configPath,
- })
- } catch (e) {
- logger.warn(`Failed to persist MTP layers for ${modelId}`, e)
- }
-
- return mtpLayers
- }
-
- /**
- * Detect which chat-template kwargs (e.g. `preserve_thinking`) a model's
- * embedded jinja template accepts, caching the result in model.yml. Migrates
- * pre-existing models lazily the first time list() sees a stale check version.
- */
- private async resolveTemplateKwargsConfig(
- modelId: string,
- modelConfig: ModelConfig
- ): Promise<TemplateKwarg[]> {
- const cfg = modelConfig as ModelConfig & {
- template_kwargs?: TemplateKwarg[]
- template_kwargs_check_v?: number
- }
- if (
- Array.isArray(cfg.template_kwargs) &&
- cfg.template_kwargs_check_v === TEMPLATE_KWARGS_CHECK_VERSION
- ) {
- return cfg.template_kwargs
- }
-
- let kwargs: TemplateKwarg[] = []
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const fullModelPath = await joinPath([
- janDataFolderPath,
- modelConfig.model_path,
- ])
- if (await fs.existsSync(fullModelPath)) {
- const metadata = await readGgufMetadata(fullModelPath)
- kwargs = detectTemplateKwargsFromChatTemplate(
- metadata.metadata?.['tokenizer.chat_template']
- )
- }
- } catch (e) {
- logger.warn(`Failed to check template kwargs for ${modelId}`, e)
- return cfg.template_kwargs ?? []
- }
-
- try {
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- cfg.template_kwargs = kwargs
- cfg.template_kwargs_check_v = TEMPLATE_KWARGS_CHECK_VERSION
- await invoke<void>('write_yaml', {
- data: cfg,
- savePath: configPath,
- })
- } catch (e) {
- logger.warn(`Failed to persist template kwargs for ${modelId}`, e)
- }
-
- return kwargs
+ try {
+ const info = await loadLlamaModel(modelId, isEmbedding)
+ if (!isEmbedding) {
+ this.loadedChatOrder = this.loadedChatOrder.filter((m) => m !== modelId)
+ this.loadedChatOrder.push(modelId)
+ }
+ return info
+ } catch (error) {
+ logger.error('Error in load command:\n', error)
+ throw error
}
+ }
- // Implement the required LocalProvider interface methods
- override async list(): Promise<modelInfo[]> {
- const modelsDir = await joinPath([await this.getProviderPath(), 'models'])
- if (!(await fs.existsSync(modelsDir))) {
- await fs.mkdir(modelsDir)
- }
+ /**
+ * Enforce `userModelsMax` against chat models only. Reconciles the local
+ * FIFO against the router's loaded set, then unloads the oldest chat model
+ * if loading `incomingModelId` would exceed the user-configured cap.
+ */
+ private async evictChatIfAtCapacity(incomingModelId: string): Promise<void> {
+ if (this.userModelsMax <= 0) return // unlimited
- // Legacy migration is best-effort: a failure here must never blank the
- // model list. Pre-router users without anything to migrate would never
- // notice, but a single throw used to bubble out of list() and return [].
- try {
- await this.migrateLegacyModels()
- } catch (err) {
- logger.warn(`list: migrateLegacyModels failed, continuing: ${String(err)}`)
- }
-
- let modelIds: string[] = []
-
- // DFS. Mirror the defensive pattern in preset.ts: an unreadable entry
- // (Windows AV quarantine, junction, locked file) must not kill the whole
- // scan — log and continue past it.
- let stack = [modelsDir]
- while (stack.length > 0) {
- const currentDir = stack.pop()
-
- // check if model.yml exists
- const modelConfigPath = await joinPath([currentDir, 'model.yml'])
- if (await fs.existsSync(modelConfigPath)) {
- // +1 to remove the leading slash
- // NOTE: this does not handle Windows path \\
- modelIds.push(currentDir.slice(modelsDir.length + 1))
- continue
- }
-
- let children: string[] = []
- try {
- children = await fs.readdirSync(currentDir)
- } catch (err) {
- logger.warn(`list: readdir failed for ${currentDir}: ${String(err)}`)
- continue
- }
- for (const child of children) {
- try {
- const dirInfo = await fs.fileStat(child)
- if (!dirInfo?.isDirectory) continue
- stack.push(child)
- } catch (err) {
- logger.warn(`list: stat failed for ${child}: ${String(err)}`)
- }
- }
- }
-
- // Per-model isolation: one malformed model.yml (or a write_yaml failure
- // inside resolveEmbeddingConfig) must not discard the other entries.
- let modelInfos: modelInfo[] = []
- for (const modelId of modelIds) {
- try {
- const path = await joinPath([modelsDir, modelId, 'model.yml'])
- const modelConfig = await invoke<ModelConfig>('read_yaml', { path })
- const isEmbedding = await this.resolveEmbeddingConfig(
- modelId,
- modelConfig
- )
- const templateKwargs = await this.resolveTemplateKwargsConfig(
- modelId,
- modelConfig
- )
-
- const capabilities: string[] = []
- if (modelConfig.mmproj_path) {
- const caps = await this.readMmprojCapabilities(
- modelConfig.mmproj_path
- )
- if (caps.vision) capabilities.push('vision')
- if (caps.audio) capabilities.push('audio')
- // 'video' is intentionally NOT derived from the mmproj here — video
- // support also depends on the backend being built with MTMD_VIDEO,
- // which the GGUF can't reveal. It's reconciled from /props after the
- // model loads (see useReconcileVideoCapability).
- }
-
- const mp = modelConfig.model_path ?? ''
- const isAbsolute = mp.startsWith('/') || /^[A-Za-z]:[\\/]/.test(mp)
-
- const modelInfo = {
- id: modelId,
- name: modelConfig.name ?? modelId,
- quant_type: undefined, // TODO: parse quantization type from model.yml or model.gguf
- providerId: this.provider,
- port: 0, // port is not known until the model is loaded
- sizeBytes: modelConfig.size_bytes ?? 0,
- embedding: isEmbedding,
- imported: isAbsolute,
- capabilities: capabilities.length > 0 ? capabilities : undefined,
- template_kwargs: templateKwargs,
- } as modelInfo
- modelInfos.push(modelInfo)
- } catch (err) {
- logger.warn(`list: skipping model ${modelId}: ${String(err)}`)
- }
- }
-
- return modelInfos
+ let loaded: string[] = []
+ try {
+ loaded = await this.getLoadedModels()
+ } catch {
+ // If we can't introspect, fall back to the local FIFO — better to
+ // over-evict than to violate the cap.
+ loaded = [...this.loadedChatOrder]
+ }
+ const loadedSet = new Set(loaded)
+ this.loadedChatOrder = this.loadedChatOrder.filter(
+ (m) => loadedSet.has(m) && m !== incomingModelId
+ )
+
+ while (this.loadedChatOrder.length >= this.userModelsMax) {
+ const victim = this.loadedChatOrder.shift()
+ if (!victim) break
+ try {
+ const result = await unloadLlamaModel(victim)
+ if (!result.success) {
+ logger.warn(
+ `Pre-eviction of ${victim} reported failure: ${result.error}`
+ )
+ } else {
+ logger.info(
+ `Pre-evicted chat model ${victim} to make room for ${incomingModelId}`
+ )
+ }
+ } catch (e) {
+ logger.warn(`Pre-eviction of ${victim} threw:`, e)
+ }
+ }
+ }
+
+ override async unload(modelId: string): Promise<UnloadResult> {
+ const sInfo = await this.findSessionByModel(modelId)
+ if (!sInfo) {
+ throw new Error(`No active session found for model: ${modelId}`)
}
-
- private async migrateLegacyModels() {
- // Attempt to migrate only once
- if ((await getBackendSetting('cortex_models_migrated')) === 'true') return
-
- const janDataFolderPath = await getJanDataFolderPath()
- const modelsDir = await joinPath([janDataFolderPath, 'models'])
- if (!(await fs.existsSync(modelsDir))) return
-
- // DFS
- let stack = [modelsDir]
- while (stack.length > 0) {
- const currentDir = stack.pop()
-
- const files = await fs.readdirSync(currentDir)
- for (const child of files) {
- try {
- const childPath = await joinPath([currentDir, child])
- const stat = await fs.fileStat(childPath)
- if (
- files.some((e) => e.endsWith('model.yml')) &&
- !child.endsWith('model.yml')
- )
- continue
- if (!stat.isDirectory && child.endsWith('.yml')) {
- // check if model.yml exists
- const modelConfigPath = child
- if (await fs.existsSync(modelConfigPath)) {
- const legacyModelConfig = await invoke<{
- files: string[]
- model: string
- }>('read_yaml', {
- path: modelConfigPath,
- })
- const legacyModelPath = legacyModelConfig.files?.[0]
- if (!legacyModelPath) continue
- // +1 to remove the leading slash
- // NOTE: this does not handle Windows path \\
- let modelId = currentDir.slice(modelsDir.length + 1)
-
- modelId =
- modelId !== 'imported'
- ? modelId.replace(/^(cortex\.so|huggingface\.co)[\/\\]/, '')
- : (await basename(child)).replace('.yml', '')
-
- const modelName = legacyModelConfig.model ?? modelId
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- if (await fs.existsSync(configPath)) continue // Don't reimport
-
- // this is relative to Jan's data folder
- const modelDir = `${this.providerId}/models/${modelId}`
-
- let size_bytes = (
- await fs.fileStat(
- await joinPath([janDataFolderPath, legacyModelPath])
- )
- ).size
-
- const modelConfig = {
- model_path: legacyModelPath,
- mmproj_path: undefined, // legacy models do not have mmproj
- name: modelName,
- size_bytes,
- } as ModelConfig
- await fs.mkdir(await joinPath([janDataFolderPath, modelDir]))
- await invoke<void>('write_yaml', {
- data: modelConfig,
- savePath: configPath,
- })
- continue
- }
- }
- } catch (error) {
- logger.error(`Error migrating model ${child}:`, error)
- }
- }
-
- let subdirs: string[] = []
- try {
- subdirs = await fs.readdirSync(currentDir)
- } catch (err) {
- logger.warn(
- `migrateLegacyModels: readdir failed for ${currentDir}: ${String(err)}`
- )
- continue
- }
- for (const child of subdirs) {
- try {
- const dirInfo = await fs.fileStat(child)
- if (!dirInfo?.isDirectory) continue
- stack.push(child)
- } catch (err) {
- logger.warn(
- `migrateLegacyModels: stat failed for ${child}: ${String(err)}`
- )
- }
- }
- }
- await setBackendSetting('cortex_models_migrated', 'true')
- }
-
- /**
- * Update a model with new information.
- * @param modelId
- * @param model
- */
- async update(modelId: string, model: Partial<modelInfo>): Promise<void> {
- const modelFolderPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- ])
- const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path: await joinPath([modelFolderPath, 'model.yml']),
- })
- const newFolderPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- model.id,
- ])
- // Check if newFolderPath exists
- if (await fs.existsSync(newFolderPath)) {
- throw new Error(`Model with ID ${model.id} already exists`)
- }
- const newModelConfigPath = await joinPath([newFolderPath, 'model.yml'])
- await fs.mv(modelFolderPath, newFolderPath).then(() =>
- // now replace what values have previous model name with format
- invoke('write_yaml', {
- data: {
- ...modelConfig,
- model_path: modelConfig?.model_path?.replace(
- `${this.providerId}/models/${modelId}`,
- `${this.providerId}/models/${model.id}`
- ),
- mmproj_path: modelConfig?.mmproj_path?.replace(
- `${this.providerId}/models/${modelId}`,
- `${this.providerId}/models/${model.id}`
- ),
- },
- savePath: newModelConfigPath,
- })
+ try {
+ const result = await unloadLlamaModel(modelId)
+ if (result.success) {
+ this.loadedChatOrder = this.loadedChatOrder.filter((m) => m !== modelId)
+ logger.info(`Successfully unloaded model ${modelId}`)
+ } else {
+ logger.warn(`Failed to unload model ${modelId}: ${result.error}`)
+ }
+ return result
+ } catch (error) {
+ logger.error('Error in unload command:', error)
+ return {
+ success: false,
+ error: `Failed to unload model: ${error}`,
+ }
+ }
+ }
+
+ /**
+ * 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 taskId unique across providers
+ return `${this.provider}/${modelId.replace(/\./g, '-')}`
+ }
+
+ private async *handleStreamingResponse(
+ url: string,
+ headers: HeadersInit,
+ body: string,
+ abortController?: AbortController
+ ): AsyncIterable<chatCompletionChunk> {
+ // AbortSignal.any() is not available in all runtimes (e.g. WebKit/JavaScriptCore),
+ // so we manually combine the timeout and external abort signals.
+ const combinedController = new AbortController()
+ const timeoutId = setTimeout(
+ () => combinedController.abort(new Error('Request timed out')),
+ this.timeout * 1000
+ )
+ if (abortController?.signal) {
+ if (abortController.signal.aborted) {
+ combinedController.abort(abortController.signal.reason)
+ } else {
+ abortController.signal.addEventListener(
+ 'abort',
+ () => combinedController.abort(abortController.signal.reason),
+ { once: true }
)
+ }
+ }
+ const response = await loopbackFetch(url, {
+ method: 'POST',
+ headers,
+ body,
+ connectTimeout: Number(this.timeout) * 1000, // default 10 minutes
+ signal: combinedController.signal,
+ }).finally(() => clearTimeout(timeoutId))
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => null)
+ throw new Error(
+ `API request failed with status ${response.status}: ${JSON.stringify(
+ errorData
+ )}`
+ )
+ }
+
+ if (!response.body) {
+ throw new Error('Response body is null')
+ }
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder('utf-8')
+ let buffer = ''
+ let jsonStr = ''
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
- // The router's preset still references the old model id until we
- // regenerate; without this a `POST /models/load <new-id>` would 404.
- try {
- await this.refreshEnginePreset()
- } catch (e) {
- logger.warn(`Router restart after model rename (${modelId} → ${model.id}) failed`, e)
- }
- }
-
- /**
- * 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 modelId
- if (!/^[a-zA-Z0-9/_\-\.]+$/.test(id)) return false
-
- // check for empty parts or path traversal
- const parts = id.split('/')
- return parts.every((s) => s !== '' && s !== '.' && s !== '..')
- }
-
- if (!isValidModelId(modelId))
- throw new Error(
- `Invalid modelId: ${modelId}. Only alphanumeric and / _ - . characters are allowed.`
- )
-
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- if (await fs.existsSync(configPath))
- throw new Error(`Model ${modelId} already exists`)
-
- // this is relative to Jan's data folder
- const modelDir = `${this.providerId}/models/${modelId}`
-
- // we only use these from opts
- // opts.modelPath: URL to the model file
- // opts.mmprojPath: URL to the mmproj file
-
- let downloadItems: DownloadItem[] = []
-
- const maybeDownload = async (path: string, saveName: string) => {
- // if URL, add to downloadItems, and return local path
- if (path.startsWith('https://')) {
- const localPath = `${modelDir}/${saveName}`
- downloadItems.push({
- url: path,
- save_path: localPath,
- proxy: await getProxyConfig(),
- sha256:
- saveName === 'model.gguf'
- ? opts.modelSha256
- : saveName === 'mmproj.gguf'
- ? opts.mmprojSha256
- : undefined,
- size:
- saveName === 'model.gguf'
- ? opts.modelSize
- : saveName === 'mmproj.gguf'
- ? opts.mmprojSize
- : undefined,
- model_id: modelId,
- })
- return localPath
- }
-
- // if local file (absolute path), check if it exists
- // and return the path
- if (!(await fs.existsSync(path)))
- throw new Error(`File not found: ${path}`)
- return path
- }
-
- let modelPath = await maybeDownload(opts.modelPath, 'model.gguf')
- let mmprojPath = opts.mmprojPath
- ? await maybeDownload(opts.mmprojPath, 'mmproj.gguf')
- : undefined
- // Speculative-decoding draft companion; paired with the main model. The
- // file name stays `mtp.gguf` for every flavour: it is the local name of
- // the paired draft, and changing it would orphan existing installs.
- let draftModelPath = opts.specDraftPath
- ? await maybeDownload(opts.specDraftPath, 'mtp.gguf')
- : undefined
-
- if (downloadItems.length > 0) {
- try {
- // emit download update event on progress
- const onProgress = (transferred: number, total: number) => {
- events.emit(DownloadEvent.onFileDownloadUpdate, {
- modelId,
- percent: transferred / total,
- size: { transferred, total },
- downloadType: 'Model',
- })
- }
- const downloadManager = window.core.extensionManager.getByName(
- '@janhq/download-extension'
- )
- await downloadManager.downloadFiles(
- downloadItems,
- this.createDownloadTaskId(modelId),
- onProgress
- )
- } catch (error) {
- const errorMessage =
- error instanceof Error ? error.message : String(error)
-
- // Check if this is a cancellation
- const isCancellationError =
- errorMessage.includes('Download cancelled') ||
- errorMessage.includes('Validation cancelled') ||
- errorMessage.includes('Hash computation cancelled') ||
- errorMessage.includes('cancelled') ||
- errorMessage.includes('aborted')
-
- // Check if this is a validation failure
- const isValidationError =
- errorMessage.includes('Hash verification failed') ||
- errorMessage.includes('Size verification failed') ||
- errorMessage.includes('Failed to verify file')
-
- // Pause and cancel both surface here as a cancellation; treat as a
- // stop (emit stopped, return) so it never becomes an error toast.
- if (isCancellationError) {
- logger.info('Download stopped for model:', modelId)
- events.emit(DownloadEvent.onFileDownloadStopped, {
- modelId,
- downloadType: 'Model',
- })
- return
- }
-
- logger.error('Error downloading model:', modelId, opts, error)
- if (isValidationError) {
- // Cancel any other download tasks for this model
- try {
- this.abortImport(modelId)
- } catch (cancelError) {
- logger.warn('Failed to cancel download task:', cancelError)
- }
-
- // Emit validation failure event
- events.emit(DownloadEvent.onModelValidationFailed, {
- modelId,
- downloadType: 'Model',
- error: errorMessage,
- reason: 'validation_failed',
- })
- } else {
- // Regular download error
- events.emit(DownloadEvent.onFileDownloadError, {
- modelId,
- downloadType: 'Model',
- error: errorMessage,
- })
- }
- throw error
- }
- }
-
- // Validate GGUF files
- const janDataFolderPath = await getJanDataFolderPath()
- const fullModelPath = await joinPath([janDataFolderPath, modelPath])
- let isEmbedding = false
- let mtpLayers = 0
- let specKind: SpecDraftKind = 'mtp'
- let templateKwargs: TemplateKwarg[] = []
- let resolvedName: string | undefined
-
- try {
- // Validate main model file
- const modelMetadata = await readGgufMetadata(fullModelPath)
- logger.info(
- `Model GGUF validation successful: version ${modelMetadata.version}, tensors: ${modelMetadata.tensor_count}`
- )
-
- if (detectEmbeddingFromGgufMeta(modelMetadata.metadata)) {
- isEmbedding = true
- }
- mtpLayers = detectMtpLayersFromGgufMeta(modelMetadata.metadata)
- templateKwargs = detectTemplateKwargsFromChatTemplate(
- modelMetadata.metadata?.['tokenizer.chat_template']
- )
-
- const rawName = modelMetadata.metadata?.['general.name']
- if (typeof rawName === 'string') {
- const normalized = rawName.trim().replace(/\s+/g, '-')
- if (normalized.length > 0) resolvedName = normalized
- }
-
- // Validate mmproj file if present
- if (mmprojPath) {
- const fullMmprojPath = await joinPath([janDataFolderPath, mmprojPath])
- const mmprojMetadata = await readGgufMetadata(fullMmprojPath)
- logger.info(
- `Mmproj GGUF validation successful: version ${mmprojMetadata.version}, tensors: ${mmprojMetadata.tensor_count}`
- )
- }
-
- // Validate the draft, decide which spec type it implements, and read
- // its head count (the main gguf usually lacks nextn_predict_layers when
- // MTP ships as a separate file).
- if (draftModelPath) {
- const fullDraftPath = await joinPath([janDataFolderPath, draftModelPath])
- const draftMetadata = await readGgufMetadata(fullDraftPath)
- // Only asked for a DFlash-architecture draft, since that is the one
- // case a tensor decides (DSpark = DFlash + Markov head).
- const hasMarkovHead =
- draftMetadata.metadata?.['general.architecture'] === 'dflash'
- ? (await findGgufTensors(fullDraftPath, [MARKOV_HEAD_TENSOR]))
- .length > 0
- : undefined
- specKind = resolveSpecDraftKind(draftMetadata.metadata, {
- hasMarkovHead,
- hint: opts.specDraftKind,
- })
- const draftLayers = detectMtpLayersFromGgufMeta(draftMetadata.metadata)
- // Only an MTP head reports nextn layers; the other flavours have none,
- // and the count is what makes the settings panel offer the toggle.
- mtpLayers = draftLayers > 0 ? draftLayers : Math.max(mtpLayers, 1)
- }
- } catch (error) {
- logger.error('GGUF validation failed:', error)
- throw new Error(
- `Invalid GGUF file(s): ${
- error.message || 'File format validation failed'
- }`
- )
- }
-
- // Calculate file sizes
- let size_bytes = (await fs.fileStat(fullModelPath)).size
- if (mmprojPath) {
- size_bytes += (
- await fs.fileStat(await joinPath([janDataFolderPath, mmprojPath]))
- ).size
- }
- if (draftModelPath) {
- size_bytes += (
- await fs.fileStat(await joinPath([janDataFolderPath, draftModelPath]))
- ).size
- }
-
- if (!resolvedName) {
- const base = opts.modelPath.split(/[\\/]/).pop() ?? modelId
- resolvedName = base.replace(/\.gguf$/i, '') || modelId
- }
-
- // TODO: add updateModelConfig() method
- const modelConfig = {
- model_path: modelPath,
- mmproj_path: mmprojPath,
- name: resolvedName,
- size_bytes,
- model_sha256: opts.modelSha256,
- model_size_bytes: opts.modelSize,
- mmproj_sha256: opts.mmprojSha256,
- mmproj_size_bytes: opts.mmprojSize,
- embedding: isEmbedding,
- embedding_check_v: EMBEDDING_CHECK_VERSION,
- mtp_layers: mtpLayers,
- mtp_check_v: MTP_CHECK_VERSION,
- template_kwargs: templateKwargs,
- template_kwargs_check_v: TEMPLATE_KWARGS_CHECK_VERSION,
- // A separate draft gguf is downloaded only to be used, so enable it by
- // default. Embedded-MTP models stay opt-in (no flag written here) and
- // need no spec_type: their flavour is always draft-mtp.
- ...(draftModelPath
- ? {
- mtp_model_path: draftModelPath,
- mtp: true,
- spec_type: `draft-${specKind}`,
- }
- : {}),
- ...(isEmbedding
- ? { pooling: 'mean', ubatch_size: 2048, batch_size: 2048 }
- : {}),
- } as ModelConfig
- await fs.mkdir(await joinPath([janDataFolderPath, modelDir]))
- await invoke<void>('write_yaml', {
- data: modelConfig,
- savePath: configPath,
- })
- events.emit(AppEvent.onModelImported, {
- modelId,
- modelPath,
- mmprojPath,
- size_bytes,
- model_sha256: opts.modelSha256,
- model_size_bytes: opts.modelSize,
- mmproj_sha256: opts.mmprojSha256,
- mmproj_size_bytes: opts.mmprojSize,
- embedding: isEmbedding,
- })
-
- if (downloadItems.length > 0) {
- events.emit(DownloadEvent.onFileDownloadAndVerificationSuccess, {
- modelId,
- downloadType: 'Model',
- })
- }
-
- try {
- await this.refreshEnginePreset()
- } catch (e) {
- logger.warn(`Router refresh after import(${modelId}) failed:`, e)
+ if (done) {
+ break
}
- }
- /**
- * Deletes the entire model folder for a given modelId
- * @param modelId The model ID to delete
- */
- private async deleteModelFolder(modelId: string): Promise<void> {
- try {
- const modelDir = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- ])
+ buffer += decoder.decode(value, { stream: true })
- if (await fs.existsSync(modelDir)) {
- logger.info(`Cleaning up model directory: ${modelDir}`)
- await fs.rm(modelDir)
- }
- } catch (deleteError) {
- logger.warn('Failed to delete model directory:', deleteError)
- }
- }
+ // Process complete lines in the buffer
+ const lines = buffer.split('\n')
+ buffer = lines.pop() || '' // Keep the last incomplete line in the buffer
- override async abortImport(modelId: string): Promise<void> {
- // Cancel any active download task
- // prepend provider name to avoid name collision
- const taskId = this.createDownloadTaskId(modelId)
- const downloadManager = window.core.extensionManager.getByName(
- '@janhq/download-extension'
- )
-
- try {
- await downloadManager.cancelDownload(taskId)
- } catch (cancelError) {
- logger.warn('Failed to cancel download task:', cancelError)
+ for (const line of lines) {
+ const trimmedLine = line.trim()
+ if (!trimmedLine || trimmedLine === 'data: [DONE]') {
+ continue
+ }
+
+ if (trimmedLine.startsWith('data: ')) {
+ jsonStr = trimmedLine.slice(6)
+ } else if (trimmedLine.startsWith('error: ')) {
+ jsonStr = trimmedLine.slice(7)
+ const error = JSON.parse(jsonStr)
+ throw new Error(error.message)
+ } else {
+ // it should not normally reach here
+ throw new Error('Malformed chunk')
+ }
+ try {
+ const data = JSON.parse(jsonStr)
+ const chunk = data as chatCompletionChunk
+
+ yield chunk
+ } catch (e) {
+ logger.error('Error parsing JSON from stream or server error:', e)
+ // re‑throw so the async iterator terminates with an error
+ throw e
+ }
}
-
- // Delete the entire model folder if it exists (for validation failures)
- await this.deleteModelFolder(modelId)
+ }
+ } finally {
+ reader.releaseLock()
}
+ }
- override async pauseImport(modelId: string): Promise<void> {
- const taskId = this.createDownloadTaskId(modelId)
- const downloadManager = window.core.extensionManager.getByName(
- '@janhq/download-extension'
- )
- // Pause keeps the partial .tmp for resume; the model folder is preserved.
- await downloadManager.pauseDownload(taskId)
- }
-
- private async getRandomPort(): Promise<number> {
- return 49152 + Math.floor(Math.random() * (65535 - 49152))
- }
-
- private parseEnvFromString(
- target: Record<string, string>,
- envString: string
- ): void {
- envString
- .split(';')
- .filter((pair) => pair.trim())
- .forEach((pair) => {
- const [key, ...valueParts] = pair.split('=')
- const cleanKey = key?.trim()
-
- if (
- cleanKey &&
- valueParts.length > 0 &&
- !cleanKey.startsWith('LLAMA')
- ) {
- target[cleanKey] = valueParts.join('=').trim()
- }
- })
- }
-
- override async load(
- modelId: string,
- _settings?: unknown,
- isEmbedding: boolean = false
- ): Promise<SessionInfo> {
- const sInfo = await this.findSessionByModel(modelId)
- if (sInfo) {
- throw new Error('Model already loaded!!')
- }
-
- if (this.loadingModels.has(modelId)) {
- return this.loadingModels.get(modelId)!
- }
-
- const loadingPromise = this.performLoad(modelId, isEmbedding)
- this.loadingModels.set(modelId, loadingPromise)
-
- try {
- return await loadingPromise
- } finally {
- this.loadingModels.delete(modelId)
- }
- }
+ private async findSessionByModel(
+ modelId: string
+ ): Promise<SessionInfo | null> {
+ try {
+ return await pluginFindSessionByModel(modelId)
+ } catch (e) {
+ logger.error(e)
+ throw new Error(String(e))
+ }
+ }
+
+ private async ensureHealthySession(modelId: string): Promise<SessionInfo> {
+ return pluginEnsureSessionReady(modelId, false)
+ }
+
+ override async chat(
+ opts: chatCompletionRequest,
+ abortController?: AbortController
+ ): Promise<chatCompletion | AsyncIterable<chatCompletionChunk>> {
+ const release = await this.acquireEngineLease()
+ let streaming = false
+ try {
+ const result = await this.chatOnEngine(opts, abortController)
+ if (opts.stream && Symbol.asyncIterator in result) {
+ // The caller reads the stream after this returns, so the lease goes
+ // with it. An abort drops it too, in case the stream is never read; one
+ // that already happened (before this call, or while the session was
+ // being resolved) fires no event from here on, so it is checked now.
+ streaming = true
+ const signal = abortController?.signal
+ if (signal?.aborted) {
+ release()
+ } else {
+ signal?.addEventListener('abort', release, { once: true })
+ }
+ return this.releaseWhenDone(release, result)
+ }
+ return result
+ } finally {
+ if (!streaming) release()
+ }
+ }
+
+ private async chatOnEngine(
+ opts: chatCompletionRequest,
+ abortController?: AbortController
+ ): Promise<chatCompletion | AsyncIterable<chatCompletionChunk>> {
+ const sessionInfo = await this.ensureHealthySession(opts.model)
+ const baseUrl = `http://localhost:${sessionInfo.port}/v1`
+ const url = `${baseUrl}/chat/completions`
+ const headers = {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${sessionInfo.api_key}`,
+ }
+ // always enable prompt progress return if stream is true
+ // Requires llamacpp version > b6399
+ // Example json returned from server
+ // {"choices":[{"finish_reason":null,"index":0,"delta":{"role":"assistant","content":null}}],"created":1758113912,"id":"chatcmpl-UwZwgxQKyJMo7WzMzXlsi90YTUK2BJro","model":"qwen","system_fingerprint":"b1-e4912fc","object":"chat.completion.chunk","prompt_progress":{"total":36,"cache":0,"processed":36,"time_ms":5706760300}}
+ // (chunk.prompt_progress?.processed / chunk.prompt_progress?.total) * 100
+ // chunk.prompt_progress?.cache is for past tokens already in kv cache
+ opts.return_progress = true
+ // Per-chunk timings so callers can track live token counts during
+ // generation instead of only once the stream finishes.
+ opts.timings_per_token = true
+
+ const body = JSON.stringify(opts)
+ if (opts.stream) {
+ return this.handleStreamingResponse(url, headers, body, abortController)
+ }
+ // Handle non-streaming response
+ const response = await loopbackFetch(url, {
+ method: 'POST',
+ headers,
+ body,
+ signal: abortController?.signal,
+ })
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => null)
+ throw new Error(
+ `API request failed with status ${response.status}: ${JSON.stringify(
+ errorData
+ )}`
+ )
+ }
+
+ const completionResponse = (await response.json()) as chatCompletion
+
+ return completionResponse
+ }
+
+ override async delete(modelId: string): Promise<void> {
+ const modelDir = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ ])
+
+ if (!(await fs.existsSync(await joinPath([modelDir, 'model.yml'])))) {
+ throw new Error(`Model ${modelId} does not exist`)
+ }
+
+ await fs.rm(modelDir)
- // Awaits the deferred startup, then makes one direct attempt if the worker
- // still isn't up. Safe to call redundantly: start_engine returns the running
- // worker rather than spawning a second one.
- private async ensureEngineReady(): Promise<void> {
- await this.ensureProvisioned().catch(() => undefined)
- if (!(await this.getEngineInfo())) {
- await this.startEngine()
- }
+ try {
+ await this.refreshEnginePreset()
+ } catch (e) {
+ logger.warn(`Router refresh after delete(${modelId}) failed:`, e)
}
+ }
- private async performLoad(
- modelId: string,
- isEmbedding: boolean = false
- ): Promise<SessionInfo> {
- await this.ensureEngineReady()
- if (!(await this.getEngineInfo())) {
- throw new Error(
- 'The llama.cpp engine is not running. Please restart the app.'
- )
- }
-
- if (!isEmbedding) {
- await this.evictChatIfAtCapacity(modelId)
- }
-
- try {
- const info = await loadLlamaModel(modelId, isEmbedding)
- if (!isEmbedding) {
- this.loadedChatOrder = this.loadedChatOrder.filter((m) => m !== modelId)
- this.loadedChatOrder.push(modelId)
- }
- return info
- } catch (error) {
- logger.error('Error in load command:\n', error)
- throw error
- }
- }
+ override async getLoadedModels(): Promise<string[]> {
+ try {
+ let models: string[] = await pluginGetLoadedModels()
+ return models
+ } catch (e) {
+ logger.error(e)
+ throw new Error(e)
+ }
+ }
+
+ /**
+ * Check if mmproj.gguf file exists for a given model ID
+ * @param modelId - The model ID to check for mmproj.gguf
+ * @returns Promise<boolean> - true if mmproj.gguf exists, false otherwise
+ */
+ async checkMmprojExists(modelId: string): Promise<boolean> {
+ try {
+ const modelConfigPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+
+ const modelConfig = await invoke<ModelConfig>('read_yaml', {
+ path: modelConfigPath,
+ })
+
+ // If mmproj_path is not defined in YAML, return false
+ if (modelConfig.mmproj_path) {
+ return true
+ }
+
+ const mmprojPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'mmproj.gguf',
+ ])
+ return await fs.existsSync(mmprojPath)
+ } catch (e) {
+ logger.error(`Error checking mmproj.gguf for model ${modelId}:`, e)
+ return false
+ }
+ }
+
+ async getMtpInfo(modelId: string): Promise<{
+ mtp_layers: number
+ mtp: boolean
+ spec_draft_n_max?: number
+ spec_draft_n_min?: number
+ spec_draft_p_min?: number
+ }> {
+ const path = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(path))) {
+ return { mtp_layers: 0, mtp: false }
+ }
+ const cfg = (await invoke<ModelConfig>('read_yaml', { path })) as ModelConfig & {
+ mtp_layers?: number
+ mtp?: boolean
+ spec_draft_n_max?: number
+ spec_draft_n_min?: number
+ spec_draft_p_min?: number
+ }
+ return {
+ mtp_layers: typeof cfg.mtp_layers === 'number' ? cfg.mtp_layers : 0,
+ mtp: cfg.mtp === true,
+ spec_draft_n_max: cfg.spec_draft_n_max,
+ spec_draft_n_min: cfg.spec_draft_n_min,
+ spec_draft_p_min: cfg.spec_draft_p_min,
+ }
+ }
+
+ async updateMtpSettings(
+ modelId: string,
+ patch: {
+ mtp?: boolean
+ spec_draft_n_max?: number | null
+ spec_draft_n_min?: number | null
+ spec_draft_p_min?: number | null
+ }
+ ): Promise<void> {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(configPath))) {
+ throw new Error(`model.yml not found for ${modelId}`)
+ }
+ const cfg = (await invoke<ModelConfig>('read_yaml', { path: configPath })) as ModelConfig & {
+ mtp?: boolean
+ spec_draft_n_max?: number
+ spec_draft_n_min?: number
+ spec_draft_p_min?: number
+ }
+
+ if (typeof patch.mtp === 'boolean') cfg.mtp = patch.mtp
+ const assignNumeric = (
+ key: 'spec_draft_n_max' | 'spec_draft_n_min' | 'spec_draft_p_min',
+ value: number | null | undefined
+ ) => {
+ if (value === null) {
+ delete cfg[key]
+ } else if (typeof value === 'number' && Number.isFinite(value)) {
+ cfg[key] = value
+ }
+ }
+ if ('spec_draft_n_max' in patch) assignNumeric('spec_draft_n_max', patch.spec_draft_n_max)
+ if ('spec_draft_n_min' in patch) assignNumeric('spec_draft_n_min', patch.spec_draft_n_min)
+ if ('spec_draft_p_min' in patch) assignNumeric('spec_draft_p_min', patch.spec_draft_p_min)
+
+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
- /**
- * Enforce `userModelsMax` against chat models only. Reconciles the local
- * FIFO against the router's loaded set, then unloads the oldest chat model
- * if loading `incomingModelId` would exceed the user-configured cap.
- */
- private async evictChatIfAtCapacity(incomingModelId: string): Promise<void> {
- if (this.userModelsMax <= 0) return // unlimited
+ try {
+ await this.refreshEnginePreset()
+ } catch (e) {
+ logger.warn(`Failed to restart router after MTP update for ${modelId}`, e)
+ }
+ }
+
+ /**
+ * Persist a per-model setting into `model.yml` and apply the engine preset
+ * before resolving. A failed application restores the saved configuration
+ * and rejects so the caller can report the error.
+ *
+ * Sidebar keys are mapped to the canonical `model.yml` / preset keys here.
+ * Keys not in the mapping are silently ignored because they are Jan-side
+ * concerns or are not emitted by `preset.ts`.
+ */
+ async updateModelSettings(
+ modelId: string,
+ patch: Record<string, string | number | boolean | null | undefined>
+ ): Promise<void> {
+ const configPath = await joinPath([
+ await this.getProviderPath(),
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ if (!(await fs.existsSync(configPath))) {
+ throw new Error(`model.yml not found for ${modelId}`)
+ }
+ const cfg = (await invoke<ModelConfig>('read_yaml', {
+ path: configPath,
+ })) as ModelConfig & Record<string, unknown>
+ const previousConfig = { ...cfg }
+
+ let touched = false
+ for (const [sidebarKey, value] of Object.entries(patch)) {
+ const m = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
+ if (!m) continue
+ const next = m.coerce(value)
+ if (next === null) {
+ if (m.yamlKey in cfg) {
+ delete (cfg as Record<string, unknown>)[m.yamlKey]
+ touched = true
+ }
+ } else {
+ ; (cfg as Record<string, unknown>)[m.yamlKey] = next
+ touched = true
+ }
+ }
+
+ if (!touched) return
+
+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
- let loaded: string[] = []
- try {
- loaded = await this.getLoadedModels()
- } catch {
- // If we can't introspect, fall back to the local FIFO — better to
- // over-evict than to violate the cap.
- loaded = [...this.loadedChatOrder]
- }
- const loadedSet = new Set(loaded)
- this.loadedChatOrder = this.loadedChatOrder.filter(
- (m) => loadedSet.has(m) && m !== incomingModelId
+ try {
+ await this.refreshEnginePreset()
+ } catch (e) {
+ await invoke<void>('write_yaml', {
+ data: previousConfig,
+ savePath: configPath,
+ })
+ throw e
+ }
+ }
+
+ /** Stable identity of a device list: id and name, not the changing free memory. */
+ private deviceKeys(list: ReadonlyArray<{ id: string; name: string }>): string[] {
+ return list.map((d) => `${d.id}|${d.name}`).sort()
+ }
+
+ /** The machine's devices right now, or null when they could not be listed. */
+ private async currentDeviceKeys(
+ envs: Record<string, string>
+ ): Promise<string[] | null> {
+ try {
+ const list = await engineDevices(envs)
+ return Array.isArray(list) ? this.deviceKeys(list) : null
+ } catch (e) {
+ logger.warn('Could not enumerate the engine devices:', e)
+ return null
+ }
+ }
+
+ /**
+ * A request holds this from before it resolves the worker's port and key
+ * until it is done with them, so a restart cannot stop the worker in between:
+ * `reconcileEngineDevices` declines while any lease is held, and while it
+ * decides, new leases queue behind it. The worker's own idle check cannot
+ * cover that, because it only sees requests the worker has already admitted.
+ */
+ private async acquireEngineLease(): Promise<() => void> {
+ while (this.engineGate) await this.engineGate
+ // No await between the last gate check and this increment.
+ this.engineLeases++
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ this.engineLeases--
+ }
+ }
+
+ private async withEngineLease<T>(fn: () => Promise<T>): Promise<T> {
+ const release = await this.acquireEngineLease()
+ try {
+ return await fn()
+ } finally {
+ release()
+ }
+ }
+
+ /**
+ * Keeps the lease for as long as a stream is being read, and drops it when
+ * the reader finishes, fails or stops early. A stream that is never read
+ * keeps it until the request is aborted; that only defers a restart.
+ */
+ private async *releaseWhenDone<T>(
+ release: () => void,
+ stream: AsyncIterable<T>
+ ): AsyncIterable<T> {
+ try {
+ yield* stream
+ } finally {
+ release()
+ }
+ }
+
+ /**
+ * Restarts the engine when the machine now offers different devices than the
+ * running worker initialised, so a GPU that appeared after launch is used for
+ * the next load instead of only being listed in Settings.
+ *
+ * The baseline is what the worker itself reported when it started, so it is
+ * right even if the GPU appeared between the worker starting and this call,
+ * and for a worker this page did not start. A worker that reported nothing
+ * has no baseline, so the answer is 'unchanged'.
+ *
+ * It never interrupts work: a request holding a lease, a generation in
+ * flight, or a load of a model other than `loadingModelId` returns 'busy' and
+ * leaves the worker alone. A load passes its own id because it is already
+ * registered as loading by the time it asks.
+ *
+ * Two layers keep requests safe. The lease and gate here cover this
+ * extension's own requests. The native local API proxy, the agent loop and
+ * the model-lifecycle commands hold a lease in Rust, from before they read
+ * the worker's address until their response is finished, and
+ * `beginEngineRestart` only agrees when none is held; while the restart runs,
+ * those requests wait for the new worker instead of failing.
+ */
+ async reconcileEngineDevices(
+ loadingModelId?: string
+ ): Promise<'unchanged' | 'restarted' | 'busy'> {
+ // One at a time. Each owns the gate from its idle check until its restart is
+ // done; a second one raising its own gate would, on finishing, clear it
+ // while the first is still deciding, and a request admitted in between
+ // would never be seen by the first one's idle check.
+ const run = this.reconcileQueue.then(() =>
+ this.reconcileOnce(loadingModelId)
+ )
+ this.reconcileQueue = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ private async reconcileOnce(
+ loadingModelId?: string
+ ): Promise<'unchanged' | 'restarted' | 'busy'> {
+ const engine = await pluginGetEngineInfo().catch(() => null)
+ if (!engine?.devices) return 'unchanged'
+ const before = this.deviceKeys(engine.devices)
+
+ const envs: Record<string, string> = {}
+ if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
+ const now = await this.currentDeviceKeys(envs)
+ if (!now || now.join('\n') === before.join('\n')) return 'unchanged'
+
+ // The gate goes up before the idle check and stays up through the stop, so
+ // no request can be admitted between them. The extension targets ES2018,
+ // which has no Promise.withResolvers, hence the executor.
+ let openGate = () => { }
+ this.engineGate = new Promise<void>((resolve) => {
+ openGate = resolve
+ })
+ try {
+ const otherLoads = [...this.loadingModels.keys()].some(
+ (id) => id !== loadingModelId
+ )
+ // The native side claims the worker last: it refuses while a proxy, agent
+ // or lifecycle request holds it or a generation runs, and once it agrees,
+ // every native request waits until the restart is over.
+ if (this.engineLeases > 0 || otherLoads || !(await beginEngineRestart())) {
+ logger.info('Device list changed but the engine is busy; not restarting')
+ return 'busy'
+ }
+
+ try {
+ logger.info(
+ `Device list changed (${before.join(', ')} -> ${now.join(', ')}); restarting the engine`
)
+ await stopEngine()
+ this.loadedChatOrder = []
+ this.enginePort = undefined
+ this.engineApiKey = undefined
+ await this.startEngine()
+ return 'restarted'
+ } finally {
+ await endEngineRestart().catch(() => undefined)
+ }
+ } finally {
+ this.engineGate = null
+ openGate()
+ }
+ }
+
+ async getDevices(): Promise<DeviceList[]> {
+ // set envs
+ const envs: Record<string, string> = {}
+ if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
- while (this.loadedChatOrder.length >= this.userModelsMax) {
- const victim = this.loadedChatOrder.shift()
- if (!victim) break
- try {
- const result = await unloadLlamaModel(victim)
- if (!result.success) {
- logger.warn(
- `Pre-eviction of ${victim} reported failure: ${result.error}`
- )
- } else {
- logger.info(
- `Pre-evicted chat model ${victim} to make room for ${incomingModelId}`
- )
- }
- } catch (e) {
- logger.warn(`Pre-eviction of ${victim} threw:`, e)
- }
- }
- }
-
- override async unload(modelId: string): Promise<UnloadResult> {
- const sInfo = await this.findSessionByModel(modelId)
- if (!sInfo) {
- throw new Error(`No active session found for model: ${modelId}`)
- }
- try {
- const result = await unloadLlamaModel(modelId)
- if (result.success) {
- this.loadedChatOrder = this.loadedChatOrder.filter((m) => m !== modelId)
- logger.info(`Successfully unloaded model ${modelId}`)
- } else {
- logger.warn(`Failed to unload model ${modelId}: ${result.error}`)
- }
- return result
- } catch (error) {
- logger.error('Error in unload command:', error)
- return {
- success: false,
- error: `Failed to unload model: ${error}`,
+ try {
+ const dList = await engineDevices(envs)
+ // On Linux with AMD GPUs, llama.cpp via Vulkan may report UMA (shared) memory as device-local.
+ // For clearer UX, override with dedicated VRAM from the hardware plugin when available.
+ try {
+ const sysInfo = await getSystemInfo()
+ if (sysInfo?.os_type === 'linux' && Array.isArray(sysInfo.gpus)) {
+ const usage = await getSystemUsage()
+ if (usage && Array.isArray(usage.gpus)) {
+ const uuidToUsage: Record<
+ string,
+ { total_memory: number; used_memory: number }
+ > = {}
+ for (const u of usage.gpus as any[]) {
+ if (u && typeof u.uuid === 'string') {
+ uuidToUsage[u.uuid] = u
+ }
}
- }
- }
- /**
- * 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 taskId unique across providers
- return `${this.provider}/${modelId.replace(/\./g, '-')}`
- }
-
- private async *handleStreamingResponse(
- url: string,
- headers: HeadersInit,
- body: string,
- abortController?: AbortController
- ): AsyncIterable<chatCompletionChunk> {
- // AbortSignal.any() is not available in all runtimes (e.g. WebKit/JavaScriptCore),
- // so we manually combine the timeout and external abort signals.
- const combinedController = new AbortController()
- const timeoutId = setTimeout(
- () => combinedController.abort(new Error('Request timed out')),
- this.timeout * 1000
- )
- if (abortController?.signal) {
- if (abortController.signal.aborted) {
- combinedController.abort(abortController.signal.reason)
- } else {
- abortController.signal.addEventListener(
- 'abort',
- () => combinedController.abort(abortController.signal.reason),
- { once: true }
- )
+ const indexToAmdUuid = new Map<number, string>()
+ for (const gpu of sysInfo.gpus as any[]) {
+ const vendorStr =
+ typeof gpu?.vendor === 'string'
+ ? gpu.vendor
+ : typeof gpu?.vendor === 'object' && gpu.vendor !== null
+ ? String(gpu.vendor)
+ : ''
+ if (
+ vendorStr.toUpperCase().includes('AMD') &&
+ gpu?.vulkan_info &&
+ typeof gpu.vulkan_info.index === 'number' &&
+ typeof gpu.uuid === 'string'
+ ) {
+ indexToAmdUuid.set(gpu.vulkan_info.index, gpu.uuid)
+ }
}
- }
- const response = await loopbackFetch(url, {
- method: 'POST',
- headers,
- body,
- connectTimeout: Number(this.timeout) * 1000, // default 10 minutes
- signal: combinedController.signal,
- }).finally(() => clearTimeout(timeoutId))
- if (!response.ok) {
- const errorData = await response.json().catch(() => null)
- throw new Error(
- `API request failed with status ${response.status}: ${JSON.stringify(
- errorData
- )}`
- )
- }
-
- if (!response.body) {
- throw new Error('Response body is null')
- }
-
- const reader = response.body.getReader()
- const decoder = new TextDecoder('utf-8')
- let buffer = ''
- let jsonStr = ''
- try {
- while (true) {
- const { done, value } = await reader.read()
-
- if (done) {
- break
- }
- buffer += decoder.decode(value, { stream: true })
-
- // Process complete lines in the buffer
- const lines = buffer.split('\n')
- buffer = lines.pop() || '' // Keep the last incomplete line in the buffer
-
- for (const line of lines) {
- const trimmedLine = line.trim()
- if (!trimmedLine || trimmedLine === 'data: [DONE]') {
- continue
- }
-
- if (trimmedLine.startsWith('data: ')) {
- jsonStr = trimmedLine.slice(6)
- } else if (trimmedLine.startsWith('error: ')) {
- jsonStr = trimmedLine.slice(7)
- const error = JSON.parse(jsonStr)
- throw new Error(error.message)
- } else {
- // it should not normally reach here
- throw new Error('Malformed chunk')
- }
- try {
- const data = JSON.parse(jsonStr)
- const chunk = data as chatCompletionChunk
-
- yield chunk
- } catch (e) {
- logger.error('Error parsing JSON from stream or server error:', e)
- // re‑throw so the async iterator terminates with an error
- throw e
+ if (indexToAmdUuid.size > 0) {
+ const adjusted = dList.map((dev) => {
+ if (dev.id?.startsWith('Vulkan')) {
+ const match = /^Vulkan(\d+)/.exec(dev.id)
+ if (match) {
+ const vIdx = Number(match[1])
+ const uuid = indexToAmdUuid.get(vIdx)
+ if (uuid) {
+ const u = uuidToUsage[uuid]
+ if (
+ u &&
+ typeof u.total_memory === 'number' &&
+ typeof u.used_memory === 'number'
+ ) {
+ const total = Math.max(0, Math.floor(u.total_memory))
+ const free = Math.max(
+ 0,
+ Math.floor(u.total_memory - u.used_memory)
+ )
+ return { ...dev, mem: total, free }
+ }
}
+ }
}
+ return dev
+ })
+ return adjusted
}
- } finally {
- reader.releaseLock()
+ }
}
- }
+ } catch (e) {
+ logger.warn('Device memory override (AMD/Linux) failed:', e)
+ }
- private async findSessionByModel(
- modelId: string
- ): Promise<SessionInfo | null> {
- try {
- return await pluginFindSessionByModel(modelId)
- } catch (e) {
- logger.error(e)
- throw new Error(String(e))
- }
- }
-
- private async ensureHealthySession(modelId: string): Promise<SessionInfo> {
- return pluginEnsureSessionReady(modelId, false)
- }
-
- override async chat(
- opts: chatCompletionRequest,
- abortController?: AbortController
- ): Promise<chatCompletion | AsyncIterable<chatCompletionChunk>> {
- const sessionInfo = await this.ensureHealthySession(opts.model)
- const baseUrl = `http://localhost:${sessionInfo.port}/v1`
- const url = `${baseUrl}/chat/completions`
- const headers = {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${sessionInfo.api_key}`,
- }
- // always enable prompt progress return if stream is true
- // Requires llamacpp version > b6399
- // Example json returned from server
- // {"choices":[{"finish_reason":null,"index":0,"delta":{"role":"assistant","content":null}}],"created":1758113912,"id":"chatcmpl-UwZwgxQKyJMo7WzMzXlsi90YTUK2BJro","model":"qwen","system_fingerprint":"b1-e4912fc","object":"chat.completion.chunk","prompt_progress":{"total":36,"cache":0,"processed":36,"time_ms":5706760300}}
- // (chunk.prompt_progress?.processed / chunk.prompt_progress?.total) * 100
- // chunk.prompt_progress?.cache is for past tokens already in kv cache
- opts.return_progress = true
- // Per-chunk timings so callers can track live token counts during
- // generation instead of only once the stream finishes.
- opts.timings_per_token = true
-
- const body = JSON.stringify(opts)
- if (opts.stream) {
- return this.handleStreamingResponse(url, headers, body, abortController)
- }
- // Handle non-streaming response
- const response = await loopbackFetch(url, {
- method: 'POST',
- headers,
- body,
- signal: abortController?.signal,
+ return dList
+ } catch (error) {
+ logger.error('Failed to query devices:\n', error)
+ throw new Error('Failed to load llamacpp backend')
+ }
+ }
+
+ /**
+ * Resolves the default/preferred embedding model, importing and loading
+ * sentence-transformer-mini as the fallback, then ensures a session exists.
+ * Shared by embed() and getEmbeddingContextSize() so both agree on which
+ * model is "the" embedding model.
+ */
+ private async ensureEmbeddingModelLoaded(): Promise<SessionInfo> {
+ const downloadedModelList = await this.list()
+ const installedEmbedding = downloadedModelList.filter(
+ (m) => (m as any).embedding === true
+ )
+ const hasMini = downloadedModelList.some(
+ (m) => m.id === FALLBACK_EMBEDDING_MODEL_ID
+ )
+ let preferred = await getDefaultEmbeddingModelId('llamacpp')
+
+ if (!preferred && installedEmbedding.length === 1 && !hasMini) {
+ preferred = installedEmbedding[0].id
+ await setDefaultEmbeddingModelId('llamacpp', preferred)
+ logger.info(
+ `Auto-promoted "${preferred}" as default embedding model (single installed model, sentence-transformer-mini not present)`
+ )
+ }
+
+ const preferredMatch =
+ preferred && installedEmbedding.find((m) => m.id === preferred)
+
+ if (preferred && !preferredMatch) {
+ logger.warn(
+ `Default embedding model "${preferred}" not installed; falling back to sentence-transformer-mini`
+ )
+ }
+
+ const targetModelId = preferredMatch
+ ? (preferred as string)
+ : FALLBACK_EMBEDDING_MODEL_ID
+
+ let sInfo = await this.findSessionByModel(targetModelId)
+ if (!sInfo) {
+ if (targetModelId === FALLBACK_EMBEDDING_MODEL_ID && !hasMini) {
+ await this.import(FALLBACK_EMBEDDING_MODEL_ID, {
+ modelPath: FALLBACK_EMBEDDING_MODEL_URL,
})
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => null)
- throw new Error(
- `API request failed with status ${response.status}: ${JSON.stringify(
- errorData
- )}`
- )
- }
-
- const completionResponse = (await response.json()) as chatCompletion
-
- return completionResponse
- }
-
- override async delete(modelId: string): Promise<void> {
- const modelDir = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- ])
-
- if (!(await fs.existsSync(await joinPath([modelDir, 'model.yml'])))) {
- throw new Error(`Model ${modelId} does not exist`)
- }
-
- await fs.rm(modelDir)
-
- try {
- await this.refreshEnginePreset()
- } catch (e) {
- logger.warn(`Router refresh after delete(${modelId}) failed:`, e)
- }
- }
-
- override async getLoadedModels(): Promise<string[]> {
- try {
- let models: string[] = await pluginGetLoadedModels()
- return models
- } catch (e) {
- logger.error(e)
- throw new Error(e)
- }
- }
-
- /**
- * Check if mmproj.gguf file exists for a given model ID
- * @param modelId - The model ID to check for mmproj.gguf
- * @returns Promise<boolean> - true if mmproj.gguf exists, false otherwise
- */
- async checkMmprojExists(modelId: string): Promise<boolean> {
- try {
- const modelConfigPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
-
- const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path: modelConfigPath,
- })
-
- // If mmproj_path is not defined in YAML, return false
- if (modelConfig.mmproj_path) {
- return true
- }
-
- const mmprojPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'mmproj.gguf',
- ])
- return await fs.existsSync(mmprojPath)
- } catch (e) {
- logger.error(`Error checking mmproj.gguf for model ${modelId}:`, e)
- return false
- }
- }
-
- async getMtpInfo(modelId: string): Promise<{
- mtp_layers: number
- mtp: boolean
- spec_draft_n_max?: number
- spec_draft_n_min?: number
- spec_draft_p_min?: number
- }> {
- const path = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- if (!(await fs.existsSync(path))) {
- return { mtp_layers: 0, mtp: false }
- }
- const cfg = (await invoke<ModelConfig>('read_yaml', { path })) as ModelConfig & {
- mtp_layers?: number
- mtp?: boolean
- spec_draft_n_max?: number
- spec_draft_n_min?: number
- spec_draft_p_min?: number
- }
- return {
- mtp_layers: typeof cfg.mtp_layers === 'number' ? cfg.mtp_layers : 0,
- mtp: cfg.mtp === true,
- spec_draft_n_max: cfg.spec_draft_n_max,
- spec_draft_n_min: cfg.spec_draft_n_min,
- spec_draft_p_min: cfg.spec_draft_p_min,
- }
- }
-
- async updateMtpSettings(
- modelId: string,
- patch: {
- mtp?: boolean
- spec_draft_n_max?: number | null
- spec_draft_n_min?: number | null
- spec_draft_p_min?: number | null
- }
- ): Promise<void> {
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- if (!(await fs.existsSync(configPath))) {
- throw new Error(`model.yml not found for ${modelId}`)
- }
- const cfg = (await invoke<ModelConfig>('read_yaml', { path: configPath })) as ModelConfig & {
- mtp?: boolean
- spec_draft_n_max?: number
- spec_draft_n_min?: number
- spec_draft_p_min?: number
- }
-
- if (typeof patch.mtp === 'boolean') cfg.mtp = patch.mtp
- const assignNumeric = (
- key: 'spec_draft_n_max' | 'spec_draft_n_min' | 'spec_draft_p_min',
- value: number | null | undefined
- ) => {
- if (value === null) {
- delete cfg[key]
- } else if (typeof value === 'number' && Number.isFinite(value)) {
- cfg[key] = value
- }
- }
- if ('spec_draft_n_max' in patch) assignNumeric('spec_draft_n_max', patch.spec_draft_n_max)
- if ('spec_draft_n_min' in patch) assignNumeric('spec_draft_n_min', patch.spec_draft_n_min)
- if ('spec_draft_p_min' in patch) assignNumeric('spec_draft_p_min', patch.spec_draft_p_min)
-
- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
-
- try {
- await this.refreshEnginePreset()
- } catch (e) {
- logger.warn(`Failed to restart router after MTP update for ${modelId}`, e)
- }
- }
-
- /**
- * Persist a per-model setting into `model.yml` and apply the engine preset
- * before resolving. A failed application restores the saved configuration
- * and rejects so the caller can report the error.
- *
- * Sidebar keys are mapped to the canonical `model.yml` / preset keys here.
- * Keys not in the mapping are silently ignored because they are Jan-side
- * concerns or are not emitted by `preset.ts`.
- */
- async updateModelSettings(
- modelId: string,
- patch: Record<string, string | number | boolean | null | undefined>
- ): Promise<void> {
- const configPath = await joinPath([
- await this.getProviderPath(),
- 'models',
- modelId,
- 'model.yml',
- ])
- if (!(await fs.existsSync(configPath))) {
- throw new Error(`model.yml not found for ${modelId}`)
- }
- const cfg = (await invoke<ModelConfig>('read_yaml', {
- path: configPath,
- })) as ModelConfig & Record<string, unknown>
- const previousConfig = { ...cfg }
-
- let touched = false
- for (const [sidebarKey, value] of Object.entries(patch)) {
- const m = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]
- if (!m) continue
- const next = m.coerce(value)
- if (next === null) {
- if (m.yamlKey in cfg) {
- delete (cfg as Record<string, unknown>)[m.yamlKey]
- touched = true
- }
- } else {
- ;(cfg as Record<string, unknown>)[m.yamlKey] = next
- touched = true
- }
- }
-
- if (!touched) return
-
- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
-
- try {
- await this.refreshEnginePreset()
- } catch (e) {
- await invoke<void>('write_yaml', {
- data: previousConfig,
- savePath: configPath,
- })
- throw e
- }
- }
-
- async getDevices(): Promise<DeviceList[]> {
- // set envs
- const envs: Record<string, string> = {}
- if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
-
- try {
- const dList = await engineDevices(envs)
- // On Linux with AMD GPUs, llama.cpp via Vulkan may report UMA (shared) memory as device-local.
- // For clearer UX, override with dedicated VRAM from the hardware plugin when available.
- try {
- const sysInfo = await getSystemInfo()
- if (sysInfo?.os_type === 'linux' && Array.isArray(sysInfo.gpus)) {
- const usage = await getSystemUsage()
- if (usage && Array.isArray(usage.gpus)) {
- const uuidToUsage: Record<
- string,
- { total_memory: number; used_memory: number }
- > = {}
- for (const u of usage.gpus as any[]) {
- if (u && typeof u.uuid === 'string') {
- uuidToUsage[u.uuid] = u
- }
- }
-
- const indexToAmdUuid = new Map<number, string>()
- for (const gpu of sysInfo.gpus as any[]) {
- const vendorStr =
- typeof gpu?.vendor === 'string'
- ? gpu.vendor
- : typeof gpu?.vendor === 'object' && gpu.vendor !== null
- ? String(gpu.vendor)
- : ''
- if (
- vendorStr.toUpperCase().includes('AMD') &&
- gpu?.vulkan_info &&
- typeof gpu.vulkan_info.index === 'number' &&
- typeof gpu.uuid === 'string'
- ) {
- indexToAmdUuid.set(gpu.vulkan_info.index, gpu.uuid)
- }
- }
-
- if (indexToAmdUuid.size > 0) {
- const adjusted = dList.map((dev) => {
- if (dev.id?.startsWith('Vulkan')) {
- const match = /^Vulkan(\d+)/.exec(dev.id)
- if (match) {
- const vIdx = Number(match[1])
- const uuid = indexToAmdUuid.get(vIdx)
- if (uuid) {
- const u = uuidToUsage[uuid]
- if (
- u &&
- typeof u.total_memory === 'number' &&
- typeof u.used_memory === 'number'
- ) {
- const total = Math.max(0, Math.floor(u.total_memory))
- const free = Math.max(
- 0,
- Math.floor(u.total_memory - u.used_memory)
- )
- return { ...dev, mem: total, free }
- }
- }
- }
- }
- return dev
- })
- return adjusted
- }
- }
- }
- } catch (e) {
- logger.warn('Device memory override (AMD/Linux) failed:', e)
- }
-
- return dList
- } catch (error) {
- logger.error('Failed to query devices:\n', error)
- throw new Error('Failed to load llamacpp backend')
- }
- }
-
- /**
- * Resolves the default/preferred embedding model, importing and loading
- * sentence-transformer-mini as the fallback, then ensures a session exists.
- * Shared by embed() and getEmbeddingContextSize() so both agree on which
- * model is "the" embedding model.
- */
- private async ensureEmbeddingModelLoaded(): Promise<SessionInfo> {
- const downloadedModelList = await this.list()
- const installedEmbedding = downloadedModelList.filter(
- (m) => (m as any).embedding === true
- )
- const hasMini = downloadedModelList.some(
- (m) => m.id === FALLBACK_EMBEDDING_MODEL_ID
+ }
+ sInfo = await this.load(targetModelId, undefined, true)
+ }
+ return sInfo as SessionInfo
+ }
+
+ /**
+ * Actual post-fit context window of the embedding model, read from the
+ * router's /props endpoint (the same source getModelProps uses for chat
+ * models). Used by RAG ingestion to size chunks so they don't exceed the
+ * model's n_ctx (e.g. sentence-transformer-mini natively caps at 256).
+ */
+ async getEmbeddingContextSize(): Promise<number | undefined> {
+ const sInfo = await this.ensureEmbeddingModelLoaded()
+ const props = await this.getModelProps(sInfo.model_id)
+ return props?.nCtx
+ }
+
+ /**
+ * Real token counts from the embedding model's own tokenizer via /tokenize
+ * on its session port. Char-based chunking can't reliably predict token
+ * count (subword tokenizers vary widely by content), so callers that need
+ * a hard guarantee against exceed_context_size_error should verify with
+ * this rather than estimating from character length.
+ */
+ async countEmbeddingTokens(texts: string[]): Promise<number[]> {
+ return this.withEngineLease(() => this.countEmbeddingTokensOnEngine(texts))
+ }
+
+ private async countEmbeddingTokensOnEngine(
+ texts: string[]
+ ): Promise<number[]> {
+ const sInfo = await this.ensureEmbeddingModelLoaded()
+ const counts: number[] = []
+ for (const text of texts) {
+ const res = await loopbackFetch(`http://localhost:${sInfo.port}/tokenize`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${sInfo.api_key}`,
+ },
+ body: JSON.stringify({ content: text, model: sInfo.model_id }),
+ })
+ if (!res.ok) {
+ throw new Error(`Tokenize request failed with status ${res.status}`)
+ }
+ const json = (await res.json()) as { tokens?: unknown[] }
+ counts.push(Array.isArray(json.tokens) ? json.tokens.length : 0)
+ }
+ return counts
+ }
+
+ /**
+ * Token budget for one embedding request.
+ *
+ * Deliberately not the engine-wide `ubatch_size`: preset.ts pins every
+ * embedding model's section to its own ubatch (DEFAULT_EMBEDDING_UBATCH) and
+ * to `ctx-size = 0`, so the real ceiling is the embedder's own trained
+ * context -- 512 on MiniLM. llama.cpp rejects a batch wider than either with
+ * no retry path, so the budget is the smaller of the two.
+ */
+ private async embedBatchBudget(sInfo: SessionInfo): Promise<number> {
+ let budget = DEFAULT_EMBEDDING_UBATCH
+ try {
+ const props = await this.getModelProps(sInfo.model_id)
+ const nCtx = props?.nCtx
+ if (typeof nCtx === 'number' && nCtx > 0) {
+ budget = Math.min(budget, nCtx)
+ }
+ } catch (e) {
+ // Without /props the pinned ubatch is still a valid ceiling.
+ logger.warn('Could not read embedder context size; using the pinned ubatch:', e)
+ }
+ return budget
+ }
+
+ async embed(text: string[]): Promise<EmbeddingResponse> {
+ // Held for every batch: the session's port and key are resolved once, so a
+ // restart between batches would fail the rest of them. Taken before the
+ // model is ensured, so a load this triggers sees a held lease and does not
+ // restart the engine under the embedding it was started for.
+ return this.withEngineLease(() => this.embedOnEngine(text))
+ }
+
+ private async embedOnEngine(text: string[]): Promise<EmbeddingResponse> {
+ const sInfo = await this.ensureEmbeddingModelLoaded()
+ const batches = buildEmbedBatches(text, await this.embedBatchBudget(sInfo))
+
+ const attemptRequest = async (
+ session: SessionInfo,
+ batchInput: string[]
+ ) => {
+ const baseUrl = `http://localhost:${session.port}/v1/embeddings`
+ const headers = {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${session.api_key}`,
+ }
+ const body = JSON.stringify({
+ input: batchInput,
+ model: session.model_id,
+ encoding_format: 'float',
+ })
+ const response = await loopbackFetch(baseUrl, {
+ method: 'POST',
+ headers,
+ body,
+ })
+ return response
+ }
+
+ const sendBatch = async (batchInput: string[]) => {
+ const response = await attemptRequest(sInfo, batchInput)
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => null)
+ throw new Error(
+ `API request failed with status ${response.status}: ${JSON.stringify(errorData)}`
)
- let preferred = await getDefaultEmbeddingModelId('llamacpp')
-
- if (!preferred && installedEmbedding.length === 1 && !hasMini) {
- preferred = installedEmbedding[0].id
- await setDefaultEmbeddingModelId('llamacpp', preferred)
- logger.info(
- `Auto-promoted "${preferred}" as default embedding model (single installed model, sentence-transformer-mini not present)`
- )
- }
-
- const preferredMatch =
- preferred && installedEmbedding.find((m) => m.id === preferred)
-
- if (preferred && !preferredMatch) {
- logger.warn(
- `Default embedding model "${preferred}" not installed; falling back to sentence-transformer-mini`
- )
- }
-
- const targetModelId = preferredMatch
- ? (preferred as string)
- : FALLBACK_EMBEDDING_MODEL_ID
-
- let sInfo = await this.findSessionByModel(targetModelId)
- if (!sInfo) {
- if (targetModelId === FALLBACK_EMBEDDING_MODEL_ID && !hasMini) {
- await this.import(FALLBACK_EMBEDDING_MODEL_ID, {
- modelPath: FALLBACK_EMBEDDING_MODEL_URL,
- })
- }
- sInfo = await this.load(targetModelId, undefined, true)
- }
- return sInfo as SessionInfo
- }
-
- /**
- * Actual post-fit context window of the embedding model, read from the
- * router's /props endpoint (the same source getModelProps uses for chat
- * models). Used by RAG ingestion to size chunks so they don't exceed the
- * model's n_ctx (e.g. sentence-transformer-mini natively caps at 256).
- */
- async getEmbeddingContextSize(): Promise<number | undefined> {
- const sInfo = await this.ensureEmbeddingModelLoaded()
- const props = await this.getModelProps(sInfo.model_id)
- return props?.nCtx
- }
-
- /**
- * Real token counts from the embedding model's own tokenizer via /tokenize
- * on its session port. Char-based chunking can't reliably predict token
- * count (subword tokenizers vary widely by content), so callers that need
- * a hard guarantee against exceed_context_size_error should verify with
- * this rather than estimating from character length.
- */
- async countEmbeddingTokens(texts: string[]): Promise<number[]> {
- const sInfo = await this.ensureEmbeddingModelLoaded()
- const counts: number[] = []
- for (const text of texts) {
- const res = await loopbackFetch(`http://localhost:${sInfo.port}/tokenize`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${sInfo.api_key}`,
- },
- body: JSON.stringify({ content: text, model: sInfo.model_id }),
- })
- if (!res.ok) {
- throw new Error(`Tokenize request failed with status ${res.status}`)
- }
- const json = (await res.json()) as { tokens?: unknown[] }
- counts.push(Array.isArray(json.tokens) ? json.tokens.length : 0)
- }
- return counts
- }
-
- /**
- * Token budget for one embedding request.
- *
- * Deliberately not the engine-wide `ubatch_size`: preset.ts pins every
- * embedding model's section to its own ubatch (DEFAULT_EMBEDDING_UBATCH) and
- * to `ctx-size = 0`, so the real ceiling is the embedder's own trained
- * context -- 512 on MiniLM. llama.cpp rejects a batch wider than either with
- * no retry path, so the budget is the smaller of the two.
- */
- private async embedBatchBudget(sInfo: SessionInfo): Promise<number> {
- let budget = DEFAULT_EMBEDDING_UBATCH
- try {
- const props = await this.getModelProps(sInfo.model_id)
- const nCtx = props?.nCtx
- if (typeof nCtx === 'number' && nCtx > 0) {
- budget = Math.min(budget, nCtx)
- }
- } catch (e) {
- // Without /props the pinned ubatch is still a valid ceiling.
- logger.warn('Could not read embedder context size; using the pinned ubatch:', e)
- }
- return budget
- }
-
- async embed(text: string[]): Promise<EmbeddingResponse> {
- const sInfo = await this.ensureEmbeddingModelLoaded()
- const batches = buildEmbedBatches(text, await this.embedBatchBudget(sInfo))
-
- const attemptRequest = async (
- session: SessionInfo,
- batchInput: string[]
- ) => {
- const baseUrl = `http://localhost:${session.port}/v1/embeddings`
- const headers = {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${session.api_key}`,
- }
- const body = JSON.stringify({
- input: batchInput,
- model: session.model_id,
- encoding_format: 'float',
- })
- const response = await loopbackFetch(baseUrl, {
- method: 'POST',
- headers,
- body,
- })
- return response
- }
+ }
+ return (await response.json()) as EmbedBatchResult
+ }
+
+ const batchResults: Array<{ result: EmbedBatchResult; offset: number }> = []
+ for (const { batch, offset } of batches) {
+ const result = await sendBatch(batch)
+ batchResults.push({ result, offset })
+ }
+
+ return mergeEmbedResponses(
+ sInfo.model_id,
+ batchResults
+ ) as EmbeddingResponse
+ }
+
+ /**
+ * Check if a tool is supported by the model
+ * Currently read from GGUF chat_template
+ * @param modelId
+ * @returns
+ */
+ async isToolSupported(modelId: string): Promise<boolean> {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const modelConfigPath = await joinPath([
+ this.providerPath,
+ 'models',
+ modelId,
+ 'model.yml',
+ ])
+ const modelConfig = await invoke<ModelConfig>('read_yaml', {
+ path: modelConfigPath,
+ })
+ // model option is required
+ // NOTE: model_path and mmproj_path can be either relative to Jan's data folder or absolute path
+ const modelPath = await joinPath([
+ janDataFolderPath,
+ modelConfig.model_path,
+ ])
+ return (await readGgufMetadata(modelPath)).metadata?.[
+ 'tokenizer.chat_template'
+ ]?.includes('tools')
+ }
+
+ /**
+ * Check the support status of a model by its path (local/remote)
+ *
+ * Returns:
+ * - "RED" → weights don't fit in total memory
+ * - "YELLOW" → weights fit in VRAM but need system RAM, or KV cache doesn't fit
+ * - "GREEN" → both weights + KV cache fit in VRAM
+ */
+ async isModelSupported(
+ path: string,
+ ctxSize?: number
+ ): Promise<'RED' | 'YELLOW' | 'GREEN'> {
+ try {
+ const result = await isModelSupported(path, Number(ctxSize))
+ return result
+ } catch (e) {
+ throw new Error(String(e))
+ }
+ }
+
+ /**
+ * Validate GGUF file and check for unsupported architectures like CLIP
+ */
+ async validateGgufFile(filePath: string): Promise<{
+ isValid: boolean
+ error?: string
+ metadata?: any
+ }> {
+ try {
+ logger.info(`Validating GGUF file: ${filePath}`)
+ const metadata = await readGgufMetadata(filePath)
- const sendBatch = async (batchInput: string[]) => {
- const response = await attemptRequest(sInfo, batchInput)
- if (!response.ok) {
- const errorData = await response.json().catch(() => null)
- throw new Error(
- `API request failed with status ${response.status}: ${JSON.stringify(errorData)}`
- )
- }
- return (await response.json()) as EmbedBatchResult
- }
+ // Check if architecture is 'clip' which is not supported for text generation
+ const architecture = metadata.metadata?.['general.architecture']
+ logger.info(`Model architecture: ${architecture}`)
- const batchResults: Array<{ result: EmbedBatchResult; offset: number }> = []
- for (const { batch, offset } of batches) {
- const result = await sendBatch(batch)
- batchResults.push({ result, offset })
+ if (architecture === 'clip') {
+ const errorMessage =
+ 'This model has CLIP architecture and cannot be imported as a text generation model. CLIP models are designed for vision tasks and require different handling.'
+ logger.error('CLIP architecture detected:', architecture)
+ return {
+ isValid: false,
+ error: errorMessage,
+ metadata,
}
+ }
- return mergeEmbedResponses(
- sInfo.model_id,
- batchResults
- ) as EmbeddingResponse
- }
-
- /**
- * Check if a tool is supported by the model
- * Currently read from GGUF chat_template
- * @param modelId
- * @returns
- */
- async isToolSupported(modelId: string): Promise<boolean> {
+ logger.info('Model validation passed. Architecture:', architecture)
+ return {
+ isValid: true,
+ metadata,
+ }
+ } catch (error) {
+ logger.error('Failed to validate GGUF file:', error)
+ return {
+ isValid: false,
+ error: `Failed to read model metadata: ${error instanceof Error ? error.message : 'Unknown error'
+ }`,
+ }
+ }
+ }
+
+ async getTokensCount(opts: chatCompletionRequest): Promise<number> {
+ let imageTokens = 0
+ const hasImages = opts.messages.some(
+ (msg) =>
+ Array.isArray(msg.content) &&
+ msg.content.some((content) => content.type === 'image_url')
+ )
+
+ if (hasImages) {
+ try {
const janDataFolderPath = await getJanDataFolderPath()
const modelConfigPath = await joinPath([
- this.providerPath,
- 'models',
- modelId,
- 'model.yml',
+ this.providerPath,
+ 'models',
+ opts.model,
+ 'model.yml',
])
const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path: modelConfigPath,
+ path: modelConfigPath,
})
- // model option is required
- // NOTE: model_path and mmproj_path can be either relative to Jan's data folder or absolute path
- const modelPath = await joinPath([
+ if (modelConfig.mmproj_path) {
+ const mmprojPath = await joinPath([
janDataFolderPath,
- modelConfig.model_path,
- ])
- return (await readGgufMetadata(modelPath)).metadata?.[
- 'tokenizer.chat_template'
- ]?.includes('tools')
- }
-
- /**
- * Check the support status of a model by its path (local/remote)
- *
- * Returns:
- * - "RED" → weights don't fit in total memory
- * - "YELLOW" → weights fit in VRAM but need system RAM, or KV cache doesn't fit
- * - "GREEN" → both weights + KV cache fit in VRAM
- */
- async isModelSupported(
- path: string,
- ctxSize?: number
- ): Promise<'RED' | 'YELLOW' | 'GREEN'> {
- try {
- const result = await isModelSupported(path, Number(ctxSize))
- return result
- } catch (e) {
- throw new Error(String(e))
- }
- }
-
- /**
- * Validate GGUF file and check for unsupported architectures like CLIP
- */
- async validateGgufFile(filePath: string): Promise<{
- isValid: boolean
- error?: string
- metadata?: any
- }> {
- try {
- logger.info(`Validating GGUF file: ${filePath}`)
- const metadata = await readGgufMetadata(filePath)
-
- // Check if architecture is 'clip' which is not supported for text generation
- const architecture = metadata.metadata?.['general.architecture']
- logger.info(`Model architecture: ${architecture}`)
-
- if (architecture === 'clip') {
- const errorMessage =
- 'This model has CLIP architecture and cannot be imported as a text generation model. CLIP models are designed for vision tasks and require different handling.'
- logger.error('CLIP architecture detected:', architecture)
- return {
- isValid: false,
- error: errorMessage,
- metadata,
- }
- }
-
- logger.info('Model validation passed. Architecture:', architecture)
- return {
- isValid: true,
- metadata,
- }
- } catch (error) {
- logger.error('Failed to validate GGUF file:', error)
- return {
- isValid: false,
- error: `Failed to read model metadata: ${
- error instanceof Error ? error.message : 'Unknown error'
- }`,
- }
- }
- }
-
- async getTokensCount(opts: chatCompletionRequest): Promise<number> {
- let imageTokens = 0
- const hasImages = opts.messages.some(
- (msg) =>
- Array.isArray(msg.content) &&
- msg.content.some((content) => content.type === 'image_url')
- )
-
- if (hasImages) {
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const modelConfigPath = await joinPath([
- this.providerPath,
- 'models',
- opts.model,
- 'model.yml',
- ])
- const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path: modelConfigPath,
- })
- if (modelConfig.mmproj_path) {
- const mmprojPath = await joinPath([
- janDataFolderPath,
- modelConfig.mmproj_path,
- ])
- const metadata = await readGgufMetadata(mmprojPath)
- imageTokens = await this.calculateImageTokens(
- opts.messages,
- metadata.metadata
- )
- }
- } catch (error) {
- logger.warn('Failed to calculate image tokens:', error)
- imageTokens = this.estimateImageTokensFallback(opts.messages)
- }
- }
-
- let textChars = 0
- for (const msg of opts.messages) {
- if (typeof msg.content === 'string') {
- textChars += msg.content.length
- } else if (Array.isArray(msg.content)) {
- for (const part of msg.content) {
- if (part.type === 'text' && typeof part.text === 'string') {
- textChars += part.text.length
- }
- }
- }
- }
- const textTokens = Math.ceil(textChars / 4)
- return textTokens + imageTokens
- }
-
- private async calculateImageTokens(
- messages: chatCompletionRequestMessage[],
- metadata: Record<string, string>
- ): Promise<number> {
- // Extract vision parameters from metadata
- const projectionDim =
- Math.floor(Number(metadata['clip.vision.projection_dim']) / 10) || 256
-
- // Count images in messages
- let imageCount = 0
- for (const message of messages) {
- if (Array.isArray(message.content)) {
- imageCount += message.content.filter(
- (content) => content.type === 'image_url'
- ).length
- }
- }
-
- logger.info(
- `Calculated ${projectionDim} tokens per image, ${imageCount} images total`
- )
- return projectionDim * imageCount - imageCount // remove the lingering <__image__> placeholder token
- }
-
- private estimateImageTokensFallback(
- messages: chatCompletionRequestMessage[]
- ): number {
- // Fallback estimation if metadata reading fails
- const estimatedTokensPerImage = 256 // Gemma's siglip
-
- let imageCount = 0
- for (const message of messages) {
- if (Array.isArray(message.content)) {
- imageCount += message.content.filter(
- (content) => content.type === 'image_url'
- ).length
- }
- }
-
- logger.warn(
- `Fallback estimation: ${estimatedTokensPerImage} tokens per image, ${imageCount} images total`
- )
- return imageCount * estimatedTokensPerImage - imageCount // remove the lingering <__image__> placeholder token
- }
+ modelConfig.mmproj_path,
+ ])
+ const metadata = await readGgufMetadata(mmprojPath)
+ imageTokens = await this.calculateImageTokens(
+ opts.messages,
+ metadata.metadata
+ )
+ }
+ } catch (error) {
+ logger.warn('Failed to calculate image tokens:', error)
+ imageTokens = this.estimateImageTokensFallback(opts.messages)
+ }
+ }
+
+ let textChars = 0
+ for (const msg of opts.messages) {
+ if (typeof msg.content === 'string') {
+ textChars += msg.content.length
+ } else if (Array.isArray(msg.content)) {
+ for (const part of msg.content) {
+ if (part.type === 'text' && typeof part.text === 'string') {
+ textChars += part.text.length
+ }
+ }
+ }
+ }
+ const textTokens = Math.ceil(textChars / 4)
+ return textTokens + imageTokens
+ }
+
+ private async calculateImageTokens(
+ messages: chatCompletionRequestMessage[],
+ metadata: Record<string, string>
+ ): Promise<number> {
+ // Extract vision parameters from metadata
+ const projectionDim =
+ Math.floor(Number(metadata['clip.vision.projection_dim']) / 10) || 256
+
+ // Count images in messages
+ let imageCount = 0
+ for (const message of messages) {
+ if (Array.isArray(message.content)) {
+ imageCount += message.content.filter(
+ (content) => content.type === 'image_url'
+ ).length
+ }
+ }
+
+ logger.info(
+ `Calculated ${projectionDim} tokens per image, ${imageCount} images total`
+ )
+ return projectionDim * imageCount - imageCount // remove the lingering <__image__> placeholder token
+ }
+
+ private estimateImageTokensFallback(
+ messages: chatCompletionRequestMessage[]
+ ): number {
+ // Fallback estimation if metadata reading fails
+ const estimatedTokensPerImage = 256 // Gemma's siglip
+
+ let imageCount = 0
+ for (const message of messages) {
+ if (Array.isArray(message.content)) {
+ imageCount += message.content.filter(
+ (content) => content.type === 'image_url'
+ ).length
+ }
+ }
+
+ logger.warn(
+ `Fallback estimation: ${estimatedTokensPerImage} tokens per image, ${imageCount} images total`
+ )
+ return imageCount * estimatedTokensPerImage - imageCount // remove the lingering <__image__> placeholder token
+ }
}
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index 5f0c3f349..ed6bc347f 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -7,7 +7,11 @@ import {
reloadEngineModels,
startEngine,
} from '@janhq/tauri-plugin-llamacpp-api'
-import type { ReloadReport } from '@janhq/tauri-plugin-llamacpp-api'
+import type {
+ ReloadReport,
+ SessionInfo,
+} from '@janhq/tauri-plugin-llamacpp-api'
+import * as api from '@janhq/tauri-plugin-llamacpp-api'
import { generatePreset } from '../preset'
import * as store from '../settings-store'
@@ -56,6 +60,8 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {
models_max: 1,
}),
engineDevices: vi.fn().mockResolvedValue([]),
+ beginEngineRestart: vi.fn().mockResolvedValue(true),
+ endEngineRestart: vi.fn().mockResolvedValue(undefined),
eraseThreadSlotState: vi.fn().mockResolvedValue(0),
}
})
@@ -106,7 +112,7 @@ describe('llamacpp_extension', () => {
describe('resolveThreadCacheBudget', () => {
const budget = (cfg: Record<string, unknown>): number => {
// `config` is populated by onLoad, which is not run here.
- ;(extension as any).config = { ...((extension as any).config ?? {}), ...cfg }
+ ; (extension as any).config = { ...((extension as any).config ?? {}), ...cfg }
return (extension as any).resolveThreadCacheBudget()
}
@@ -142,12 +148,12 @@ describe('llamacpp_extension', () => {
describe('getProviderPath', () => {
it('should return correct provider path', async () => {
const { getJanDataFolderPath, joinPath } = await import('@janhq/core')
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp')
const result = await extension.getProviderPath()
-
+
expect(result).toBe('/path/to/jan/llamacpp')
})
})
@@ -155,7 +161,7 @@ describe('llamacpp_extension', () => {
describe('list', () => {
it('should return empty array when models directory does not exist', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/models')
vi.mocked(fs.existsSync)
@@ -165,21 +171,21 @@ describe('llamacpp_extension', () => {
vi.mocked(fs.readdirSync).mockResolvedValue([]) // empty directory after creation
const result = await extension.list()
-
+
expect(result).toEqual([])
})
it('should return model list when models exist', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
const { invoke } = await import('@tauri-apps/api/core')
-
+
// Set up providerPath first
extension['providerPath'] = '/path/to/jan/llamacpp'
-
+
const modelsDir = '/path/to/jan/llamacpp/models'
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
-
+
// Mock joinPath to handle the directory traversal logic
vi.mocked(joinPath).mockImplementation((paths) => {
if (paths.length === 1) {
@@ -187,15 +193,15 @@ describe('llamacpp_extension', () => {
}
return Promise.resolve(paths.join('/'))
})
-
+
vi.mocked(fs.existsSync)
.mockResolvedValueOnce(true) // modelsDir exists
.mockResolvedValueOnce(false) // model.yml doesn't exist at modelsDir level
.mockResolvedValueOnce(true) // model.yml exists in test-model dir
-
+
vi.mocked(fs.readdirSync).mockResolvedValue(['test-model'])
vi.mocked(fs.fileStat).mockResolvedValue({ isDirectory: true, size: 1000 })
-
+
vi.mocked(invoke).mockResolvedValue({
model_path: 'test-model/model.gguf',
name: 'Test Model',
@@ -203,7 +209,7 @@ describe('llamacpp_extension', () => {
})
const result = await extension.list()
-
+
// Note: There's a bug in the original code where it pushes just the child name
// instead of the full path, causing the model ID to be empty
expect(result).toEqual([
@@ -231,7 +237,7 @@ describe('llamacpp_extension', () => {
it('should throw error if model already exists', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/models/test-model/model.yml')
vi.mocked(fs.existsSync).mockResolvedValue(true)
@@ -249,13 +255,13 @@ describe('llamacpp_extension', () => {
tensor_count: 1,
metadata: { 'general.architecture': 'llama' },
} as any)
-
+
const mockDownloadManager = {
downloadFiles: vi.fn().mockResolvedValue(undefined)
}
-
+
window.core.extensionManager.getByName = vi.fn().mockReturnValue(mockDownloadManager)
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))
vi.mocked(fs.existsSync).mockResolvedValue(false)
@@ -263,8 +269,8 @@ describe('llamacpp_extension', () => {
vi.mocked(fs.mkdir).mockResolvedValue(undefined)
vi.mocked(invoke).mockResolvedValue(undefined)
- await extension.import('test-model', {
- modelPath: 'https://example.com/model.gguf'
+ await extension.import('test-model', {
+ modelPath: 'https://example.com/model.gguf'
})
expect(mockDownloadManager.downloadFiles).toHaveBeenCalled()
@@ -326,10 +332,10 @@ describe('llamacpp_extension', () => {
auto_update_engine: false,
auto_unload: true
}
-
+
// Set up providerPath
extension['providerPath'] = '/path/to/jan/llamacpp'
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))
@@ -465,7 +471,7 @@ describe('llamacpp_extension', () => {
}
const result = await extension.chat(request)
-
+
expect(result).toEqual(mockResponse)
expect(httpFetch).toHaveBeenCalledWith(
'http://localhost:3000/v1/chat/completions',
@@ -483,7 +489,7 @@ describe('llamacpp_extension', () => {
describe('delete', () => {
it('should throw error if model does not exist', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))
vi.mocked(fs.existsSync).mockResolvedValue(false)
@@ -493,14 +499,14 @@ describe('llamacpp_extension', () => {
it('should delete model successfully', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
-
+
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))
vi.mocked(fs.existsSync).mockResolvedValue(true)
vi.mocked(fs.rm).mockResolvedValue(undefined)
await extension.delete('test-model')
-
+
expect(fs.rm).toHaveBeenCalledWith('/path/to/jan/llamacpp/models/test-model')
})
})
@@ -1504,6 +1510,444 @@ describe('forgetThreadCache', () => {
})
})
+describe('reconcileEngineDevices', () => {
+ const ECO = [{ id: 'Vulkan0', name: 'Intel UHD', mem: 100, free: 90 }]
+ const HYBRID = [
+ ...ECO,
+ { id: 'CUDA0', name: 'NVIDIA RTX 4060 Laptop', mem: 8000, free: 7000 },
+ ]
+ let extension: llamacpp_extension
+
+ // The worker reported only the iGPU when it started.
+ const startedInEcoMode = async () => {
+ vi.mocked(api.getEngineInfo).mockResolvedValue({
+ port: 39271,
+ api_key: 'k',
+ pid: 1234,
+ models: [],
+ devices: ECO.map(({ id, name }) => ({ id, name })),
+ })
+ vi.mocked(api.engineDevices).mockResolvedValue(ECO as never)
+ vi.mocked(api.beginEngineRestart).mockResolvedValue(true)
+ vi.mocked(api.endEngineRestart).mockResolvedValue(undefined)
+ vi.mocked(api.stopEngine).mockResolvedValue(undefined)
+ extension = new llamacpp_extension()
+ // Standing in for the real spawn, which the plugin does.
+ return vi
+ .spyOn(extension as never, 'runStartEngine' as never)
+ .mockResolvedValue(undefined as never)
+ }
+
+ beforeEach(() => vi.clearAllMocks())
+
+ it('restarts once a GPU has appeared, so the next load can use it', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(api.stopEngine).toHaveBeenCalledTimes(1)
+ expect(spawn).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves the engine alone when the devices are the same', async () => {
+ const spawn = await startedInEcoMode()
+ // Free memory moves constantly; it must not count as a change.
+ vi.mocked(api.engineDevices).mockResolvedValue([
+ { ...ECO[0], free: 12 },
+ ] as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('unchanged')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ it('never interrupts a generation in flight', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ vi.mocked(api.beginEngineRestart).mockResolvedValue(false)
+
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ it('never interrupts a model that is still loading', async () => {
+ await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ const inFlight = Promise.withResolvers<SessionInfo>()
+ const loading = extension as unknown as {
+ loadingModels: Map<string, Promise<SessionInfo>>
+ }
+ loading.loadingModels.set('m', inFlight.promise)
+
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when no engine is running', async () => {
+ await startedInEcoMode()
+ vi.mocked(api.getEngineInfo).mockResolvedValue(null as never)
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('unchanged')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ })
+
+ it('does not restart on a failed enumeration, since that says nothing about GPUs', async () => {
+ await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockRejectedValue(new Error('timed out'))
+
+ expect(await extension.reconcileEngineDevices()).toBe('unchanged')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ })
+
+ // The native side holds requests back for as long as a restart it agreed to is
+ // open, so it has to hear about the end however the restart goes.
+ it('releases native requests after a restart, once the new worker is up', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(api.endEngineRestart).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(api.endEngineRestart).mock.invocationCallOrder[0]).toBeGreaterThan(
+ spawn.mock.invocationCallOrder[0]
+ )
+ })
+
+ it('releases native requests even when stopping the worker fails', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ vi.mocked(api.stopEngine).mockRejectedValue(new Error('stop failed'))
+
+ await expect(extension.reconcileEngineDevices()).rejects.toThrow('stop failed')
+ expect(api.endEngineRestart).toHaveBeenCalledTimes(1)
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ it('releases native requests even when the new worker will not start', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ spawn.mockRejectedValue(new Error('spawn failed'))
+
+ await expect(extension.reconcileEngineDevices()).rejects.toThrow('spawn failed')
+ expect(api.endEngineRestart).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not release anything it never claimed', async () => {
+ await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ vi.mocked(api.beginEngineRestart).mockResolvedValue(false)
+
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+ expect(api.endEngineRestart).not.toHaveBeenCalled()
+ })
+
+ // The worker reports what it initialised, so the baseline cannot be skewed by
+ // when this page happened to enumerate: a GPU that showed up after the worker
+ // started but before the first comparison is still a change.
+ it('compares against what the worker reported, however late the first check is', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ // The first enumeration this page ever makes already sees the dGPU.
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(spawn).toHaveBeenCalledTimes(1)
+ })
+
+ it('treats "no GPU" as a baseline, so a GPU appearing is a change', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.getEngineInfo).mockResolvedValue({
+ port: 39271,
+ api_key: 'k',
+ pid: 1234,
+ models: [],
+ devices: [],
+ })
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(spawn).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves a worker alone that did not report its devices', async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.getEngineInfo).mockResolvedValue({
+ port: 39271,
+ api_key: 'k',
+ pid: 1234,
+ models: [],
+ devices: null,
+ })
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ expect(await extension.reconcileEngineDevices()).toBe('unchanged')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ // The reporter's log shows the dGPU absent from the engine on 9 of 21 starts.
+ // Waiting for a visit to Settings > Hardware leaves every other load on the
+ // iGPU, so the load itself has to notice.
+ describe('before a model load', () => {
+ const session = { model_id: 'm', pid: 1, port: 2, api_key: 'k' }
+
+ const arm = async () => {
+ const spawn = await startedInEcoMode()
+ vi.spyOn(extension as never, 'findSessionByModel' as never).mockResolvedValue(
+ null as never
+ )
+ vi.spyOn(extension as never, 'ensureEngineReady' as never).mockResolvedValue(
+ undefined as never
+ )
+ vi.spyOn(
+ extension as never,
+ 'evictChatIfAtCapacity' as never
+ ).mockResolvedValue(undefined as never)
+ vi.mocked(api.loadLlamaModel).mockResolvedValue(session as never)
+ return spawn
+ }
+
+ it('restarts an idle engine first, so the model lands on the GPU that appeared', async () => {
+ const spawn = await arm()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+
+ await extension.load('m')
+
+ expect(api.stopEngine).toHaveBeenCalledTimes(1)
+ expect(spawn).toHaveBeenCalledTimes(1)
+ // The model must go to the new engine, not the one that was stopped.
+ expect(
+ vi.mocked(api.stopEngine).mock.invocationCallOrder[0]
+ ).toBeLessThan(vi.mocked(api.loadLlamaModel).mock.invocationCallOrder[0])
+ expect(spawn.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(api.loadLlamaModel).mock.invocationCallOrder[0]
+ )
+ })
+
+ it('leaves the engine alone when the devices are unchanged', async () => {
+ const spawn = await arm()
+
+ await extension.load('m')
+
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(spawn).not.toHaveBeenCalled()
+ expect(api.loadLlamaModel).toHaveBeenCalledTimes(1)
+ })
+
+ it('still loads, on the running engine, while another model is loading', async () => {
+ const spawn = await arm()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ const inFlight = Promise.withResolvers<SessionInfo>()
+ const loading = extension as unknown as {
+ loadingModels: Map<string, Promise<SessionInfo>>
+ }
+ loading.loadingModels.set('other', inFlight.promise)
+
+ await extension.load('m')
+
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(spawn).not.toHaveBeenCalled()
+ expect(api.loadLlamaModel).toHaveBeenCalledTimes(1)
+ })
+
+ it('still loads when the enumeration itself fails', async () => {
+ await arm()
+ vi.mocked(api.engineDevices).mockRejectedValue(new Error('timed out'))
+
+ await extension.load('m')
+
+ expect(api.stopEngine).not.toHaveBeenCalled()
+ expect(api.loadLlamaModel).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ // The restart stops a worker that a request may already hold the port of, so
+ // the worker's own idle check is not enough: it only sees requests the worker
+ // has admitted. Requests lease the engine from before they resolve a session.
+ describe('requests using the engine', () => {
+ const session = { model_id: 'm', pid: 1, port: 2, api_key: 'k' }
+ const request = { model: 'm', messages: [] } as never
+
+ const armChat = async () => {
+ const spawn = await startedInEcoMode()
+ vi.mocked(api.engineDevices).mockResolvedValue(HYBRID as never)
+ const ensureSession = vi
+ .spyOn(extension as never, 'ensureHealthySession' as never)
+ .mockResolvedValue(session as never)
+ return { spawn, ensureSession }
+ }
+
+ // Chat and embeddings go out through the no-proxy client, not global fetch.
+ beforeEach(() => httpFetch.mockReset())
+
+ it('are not cut off by a restart while one is in flight, even if the worker looks idle', async () => {
+ const { spawn } = await armChat()
+ const reply = Promise.withResolvers<Response>()
+ httpFetch.mockReturnValue(reply.promise)
+
+ const chat = extension.chat(request)
+ await vi.waitFor(() => expect(httpFetch).toHaveBeenCalled())
+
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+ expect(api.stopEngine).not.toHaveBeenCalled()
+
+ reply.resolve({ ok: true, json: async () => ({ id: 'c' }) } as Response)
+ await chat
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(spawn).toHaveBeenCalledTimes(1)
+ })
+
+ it('wait for a restart under way and then use the new engine', async () => {
+ const { spawn, ensureSession } = await armChat()
+ httpFetch.mockResolvedValue({ ok: true, json: async () => ({}) })
+ const stopped = Promise.withResolvers<void>()
+ vi.mocked(api.stopEngine).mockReturnValue(stopped.promise)
+
+ const restart = extension.reconcileEngineDevices()
+ await vi.waitFor(() => expect(api.stopEngine).toHaveBeenCalled())
+ // Asked while the restart is stopping the worker. Admitted straight away,
+ // it would resolve the port of the worker being stopped, so the session
+ // must only be resolved once the new worker is up.
+ const chat = extension.chat(request)
+
+ stopped.resolve()
+ expect(await restart).toBe('restarted')
+ await chat
+
+ expect(spawn.mock.invocationCallOrder[0]).toBeLessThan(
+ ensureSession.mock.invocationCallOrder[0]
+ )
+ })
+
+ it('keep the engine for as long as a stream is being read', async () => {
+ const { spawn } = await armChat()
+ vi.spyOn(extension as never, 'handleStreamingResponse' as never).mockImplementation(
+ async function*() {
+ yield { id: '1' }
+ yield { id: '2' }
+ } as never
+ )
+
+ const stream = (await extension.chat({
+ ...(request as object),
+ stream: true,
+ } as never)) as AsyncIterable<unknown>
+ // Returned, not read: the caller still holds the port.
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+
+ const seen: unknown[] = []
+ for await (const chunk of stream) seen.push(chunk)
+ expect(seen).toHaveLength(2)
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ expect(spawn).toHaveBeenCalledTimes(1)
+ })
+
+ it('let go of the engine when a reader stops a stream early', async () => {
+ await armChat()
+ vi.spyOn(extension as never, 'handleStreamingResponse' as never).mockImplementation(
+ async function*() {
+ yield { id: '1' }
+ yield { id: '2' }
+ } as never
+ )
+
+ const stream = (await extension.chat({
+ ...(request as object),
+ stream: true,
+ } as never)) as AsyncIterable<unknown>
+ for await (const _chunk of stream) break
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ })
+
+ // An abort that happened before the stream was handed over fires no event
+ // the listener will ever see, and a stream nobody reads never releases.
+ it('let go of the engine for a stream whose request was already aborted', async () => {
+ await armChat()
+ vi.spyOn(extension as never, 'handleStreamingResponse' as never).mockImplementation(
+ async function*() {
+ yield { id: '1' }
+ } as never
+ )
+ const controller = new AbortController()
+ controller.abort()
+
+ // Returned and dropped, never read.
+ await extension.chat(
+ { ...(request as object), stream: true } as never,
+ controller
+ )
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ })
+
+ it('let go of the engine when the request fails', async () => {
+ const { ensureSession } = await armChat()
+ ensureSession.mockRejectedValue(new Error('model not loaded'))
+
+ await expect(extension.chat(request)).rejects.toThrow('model not loaded')
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ })
+
+ // Settings > Hardware > Refresh and a model load can both ask at once. The
+ // second must not raise its own gate over the first's and clear it on its
+ // way out while the first is still deciding.
+ it('are not admitted while an earlier restart is still deciding, however many ask', async () => {
+ const { spawn, ensureSession } = await armChat()
+ httpFetch.mockResolvedValue({ ok: true, json: async () => ({}) })
+ const idle = Promise.withResolvers<boolean>()
+ vi.mocked(api.beginEngineRestart)
+ .mockReturnValueOnce(idle.promise)
+ .mockResolvedValue(false)
+
+ const first = extension.reconcileEngineDevices('m')
+ await vi.waitFor(() => expect(api.beginEngineRestart).toHaveBeenCalledTimes(1))
+ const second = extension.reconcileEngineDevices()
+ // Let everything that can settle without the first's idle answer settle.
+ // Unqueued, that is the whole of the second one, which returns busy and
+ // clears the gate the first still needs.
+ for (let i = 0; i < 50; i++) await Promise.resolve()
+ const chat = extension.chat(request)
+
+ idle.resolve(true)
+ expect(await first).toBe('restarted')
+ await second
+ await chat
+
+ expect(spawn.mock.invocationCallOrder[0]).toBeLessThan(
+ ensureSession.mock.invocationCallOrder[0]
+ )
+ })
+
+ it('keep the engine for every batch of an embedding', async () => {
+ await armChat()
+ vi.spyOn(extension as never, 'ensureEmbeddingModelLoaded' as never).mockResolvedValue(
+ session as never
+ )
+ vi.spyOn(extension as never, 'embedBatchBudget' as never).mockResolvedValue(
+ 512 as never
+ )
+ const reply = Promise.withResolvers<Response>()
+ httpFetch.mockReturnValue(reply.promise)
+
+ const embedding = extension.embed(['a'])
+ await vi.waitFor(() => expect(httpFetch).toHaveBeenCalled())
+
+ expect(await extension.reconcileEngineDevices()).toBe('busy')
+
+ reply.resolve({
+ ok: true,
+ json: async () => ({ data: [{ embedding: [0.1], index: 0 }] }),
+ } as Response)
+ await embedding
+
+ expect(await extension.reconcileEngineDevices()).toBe('restarted')
+ })
+ })
+})
+
// Jan's requests to its own engine must not be captured by a proxy. reqwest
// reads HTTP(S)_PROXY and the OS proxy and only skips loopback when NO_PROXY
// names it, so each request names a proxy of its own whose no-proxy list
@@ -1596,7 +2040,7 @@ describe('engine requests bypass a configured proxy', () => {
model: 'test-model',
messages: [{ role: 'user', content: 'hi' }],
}
- await extension.chat({ ...request, stream: false }).catch(() => {})
+ await extension.chat({ ...request, stream: false }).catch(() => { })
expectDirect('/v1/chat/completions')
httpFetch.mockClear()
@@ -1606,7 +2050,7 @@ describe('engine requests bypass a configured proxy', () => {
})) as AsyncIterable<unknown>
await stream[Symbol.asyncIterator]()
.next()
- .catch(() => {})
+ .catch(() => { })
expectDirect('/v1/chat/completions')
})
})
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 84e7cac66..741707843 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -38,6 +38,8 @@ const COMMANDS: &[&str] = &[
"engine_devices",
"force_stop_engine",
"engine_slots_idle",
+ "begin_engine_restart",
+ "end_engine_restart",
"erase_thread_slot_state",
// GGUF commands
"read_gguf_metadata",
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index 44df8bead..13b6ab3b3 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -1,19 +1,19 @@
import { invoke } from '@tauri-apps/api/core'
import {
- SessionInfo,
- DeviceList,
- UnloadResult,
- ReloadReport,
- EngineInfo,
- EngineVersion,
- GgufMetadata,
+ SessionInfo,
+ DeviceList,
+ UnloadResult,
+ ReloadReport,
+ EngineInfo,
+ EngineVersion,
+ GgufMetadata,
} from './types'
// Helpers
function asNumber(v: any, defaultValue = 0): number {
- if (v === '' || v === null || v === undefined) return defaultValue
- const n = Number(v)
- return isFinite(n) ? n : defaultValue
+ if (v === '' || v === null || v === undefined) return defaultValue
+ const n = Number(v)
+ return isFinite(n) ? n : defaultValue
}
const I32_MAX = 2147483647
@@ -25,64 +25,64 @@ const I32_MIN = -2147483648
* `timeout`, and a second hand-rolled one would drift.
*/
export function asI32(v: any, defaultValue = 0): number {
- const n = Math.trunc(asNumber(v, defaultValue))
- if (n > I32_MAX) return I32_MAX
- if (n < I32_MIN) return I32_MIN
- return n
+ const n = Math.trunc(asNumber(v, defaultValue))
+ if (n > I32_MAX) return I32_MAX
+ if (n < I32_MIN) return I32_MIN
+ return n
}
export async function loadLlamaModel(
- modelId: string,
- isEmbedding: boolean = false
+ modelId: string,
+ isEmbedding: boolean = false
): Promise<SessionInfo> {
- return await invoke('plugin:llamacpp|load_llama_model', {
- modelId,
- isEmbedding,
- })
+ return await invoke('plugin:llamacpp|load_llama_model', {
+ modelId,
+ isEmbedding,
+ })
}
export async function unloadLlamaModel(modelId: string): Promise<UnloadResult> {
- return await invoke('plugin:llamacpp|unload_llama_model', { modelId })
+ return await invoke('plugin:llamacpp|unload_llama_model', { modelId })
}
export async function ensureSessionReady(
- modelId: string,
- isEmbedding: boolean = false
+ modelId: string,
+ isEmbedding: boolean = false
): Promise<SessionInfo> {
- return await invoke('plugin:llamacpp|ensure_session_ready', {
- modelId,
- isEmbedding,
- })
+ return await invoke('plugin:llamacpp|ensure_session_ready', {
+ modelId,
+ isEmbedding,
+ })
}
export async function getDevices(
- backendPath: string,
- envs: Record<string, string> = {}
+ backendPath: string,
+ envs: Record<string, string> = {}
): Promise<DeviceList[]> {
- return await invoke('plugin:llamacpp|get_devices', {
- backendPath,
- envs,
- })
+ return await invoke('plugin:llamacpp|get_devices', {
+ backendPath,
+ envs,
+ })
}
export async function generateApiKey(
- modelId: string,
- apiSecret: string
+ modelId: string,
+ apiSecret: string
): Promise<string> {
- return await invoke('plugin:llamacpp|generate_api_key', {
- modelId,
- apiSecret,
- })
+ return await invoke('plugin:llamacpp|generate_api_key', {
+ modelId,
+ apiSecret,
+ })
}
export async function findSessionByModel(
- modelId: string
+ modelId: string
): Promise<SessionInfo | null> {
- return await invoke('plugin:llamacpp|find_session_by_model', { modelId })
+ return await invoke('plugin:llamacpp|find_session_by_model', { modelId })
}
export async function getLoadedModels(): Promise<string[]> {
- return await invoke('plugin:llamacpp|get_loaded_models')
+ return await invoke('plugin:llamacpp|get_loaded_models')
}
/**
@@ -97,26 +97,26 @@ export async function getLoadedModels(): Promise<string[]> {
* than a boolean.
*/
export async function startEngine(
- presetPath: string,
- modelsMax: number,
- slotCacheMib: number = 0,
- envs: Record<string, string> = {}
+ presetPath: string,
+ modelsMax: number,
+ slotCacheMib: number = 0,
+ envs: Record<string, string> = {}
): Promise<EngineInfo> {
- return await invoke('plugin:llamacpp|start_engine', {
- presetPath,
- modelsMax,
- slotCacheMib: asI32(slotCacheMib),
- envs,
- })
+ return await invoke('plugin:llamacpp|start_engine', {
+ presetPath,
+ modelsMax,
+ slotCacheMib: asI32(slotCacheMib),
+ envs,
+ })
}
export async function stopEngine(): Promise<void> {
- return await invoke('plugin:llamacpp|stop_engine')
+ return await invoke('plugin:llamacpp|stop_engine')
}
/** Null when no worker is running, including after one died. */
export async function getEngineInfo(): Promise<EngineInfo | null> {
- return await invoke('plugin:llamacpp|get_engine_info')
+ return await invoke('plugin:llamacpp|get_engine_info')
}
/**
@@ -127,7 +127,7 @@ export async function getEngineInfo(): Promise<EngineInfo | null> {
* rather than of any process.
*/
export async function getEngineVersion(): Promise<EngineVersion> {
- return await invoke('plugin:llamacpp|get_engine_version')
+ return await invoke('plugin:llamacpp|get_engine_version')
}
/**
@@ -138,9 +138,9 @@ export async function getEngineVersion(): Promise<EngineVersion> {
* the engine is statically linked into the worker.
*/
export async function engineDevices(
- envs: Record<string, string> = {}
+ envs: Record<string, string> = {}
): Promise<DeviceList[]> {
- return await invoke('plugin:llamacpp|engine_devices', { envs })
+ return await invoke('plugin:llamacpp|engine_devices', { envs })
}
/**
@@ -155,7 +155,7 @@ export async function engineDevices(
* busy-on-exit dialog offers; use `stopEngine` everywhere else.
*/
export async function forceStopEngine(): Promise<void> {
- return await invoke('plugin:llamacpp|force_stop_engine')
+ return await invoke('plugin:llamacpp|force_stop_engine')
}
/**
@@ -163,7 +163,24 @@ export async function forceStopEngine(): Promise<void> {
* unloaded. Omit `modelId` to ask about the whole worker.
*/
export async function engineSlotsIdle(modelId?: string): Promise<boolean> {
- return await invoke('plugin:llamacpp|engine_slots_idle', { modelId })
+ return await invoke('plugin:llamacpp|engine_slots_idle', { modelId })
+}
+
+/**
+ * Claims the worker for a restart. `false` means a request holds it or a
+ * generation is running, so nothing was claimed and the worker must be left
+ * alone. On `true`, native requests (the local API server, the agent loop and
+ * the model-lifecycle commands) wait until `endEngineRestart`, so none can
+ * resolve the old worker's address after this answer. Always pair a `true`
+ * with `endEngineRestart`.
+ */
+export async function beginEngineRestart(): Promise<boolean> {
+ return await invoke('plugin:llamacpp|begin_engine_restart')
+}
+
+/** Lets native requests through again. Harmless without a restart in progress. */
+export async function endEngineRestart(): Promise<void> {
+ return await invoke('plugin:llamacpp|end_engine_restart')
}
/**
@@ -176,33 +193,33 @@ export async function engineSlotsIdle(modelId?: string): Promise<boolean> {
* look and the answer is 0.
*/
export async function eraseThreadSlotState(args: {
- threadId?: string
- modelId?: string
- cacheDir?: string
+ threadId?: string
+ modelId?: string
+ cacheDir?: string
}): Promise<number> {
- return await invoke('plugin:llamacpp|erase_thread_slot_state', {
- threadId: args.threadId,
- modelId: args.modelId,
- cacheDir: args.cacheDir,
- })
+ return await invoke('plugin:llamacpp|erase_thread_slot_state', {
+ threadId: args.threadId,
+ modelId: args.modelId,
+ cacheDir: args.cacheDir,
+ })
}
export async function reloadEngineModels(
- presetPath: string,
- modelsMax?: number,
- slotCacheMib?: number
+ presetPath: string,
+ modelsMax?: number,
+ slotCacheMib?: number
): Promise<ReloadReport> {
- return await invoke('plugin:llamacpp|reload_engine_models', {
- presetPath,
- modelsMax,
- slotCacheMib:
- slotCacheMib === undefined ? undefined : asI32(slotCacheMib),
- })
+ return await invoke('plugin:llamacpp|reload_engine_models', {
+ presetPath,
+ modelsMax,
+ slotCacheMib:
+ slotCacheMib === undefined ? undefined : asI32(slotCacheMib),
+ })
}
// GGUF commands
export async function readGgufMetadata(path: string): Promise<GgufMetadata> {
- return await invoke('plugin:llamacpp|read_gguf_metadata', { path })
+ return await invoke('plugin:llamacpp|read_gguf_metadata', { path })
}
/**
@@ -212,25 +229,25 @@ export async function readGgufMetadata(path: string): Promise<GgufMetadata> {
* large model to answer one would be far more data than the answer.
*/
export async function findGgufTensors(
- path: string,
- names: string[]
+ path: string,
+ names: string[]
): Promise<string[]> {
- return await invoke('plugin:llamacpp|find_gguf_tensors', { path, names })
+ return await invoke('plugin:llamacpp|find_gguf_tensors', { path, names })
}
export async function isModelSupported(
- path: string,
- ctxSize?: number
+ path: string,
+ ctxSize?: number
): Promise<'RED' | 'YELLOW' | 'GREEN'> {
- return await invoke('plugin:llamacpp|is_model_supported', {
- path,
- ctxSize,
- })
+ return await invoke('plugin:llamacpp|is_model_supported', {
+ path,
+ ctxSize,
+ })
}
// Cleanup commands
export async function cleanupLlamaProcesses(): Promise<void> {
- return await invoke('plugin:llamacpp|cleanup_llama_processes')
+ return await invoke('plugin:llamacpp|cleanup_llama_processes')
}
export * from './types'
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index 92ff0e948..4bf61051c 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -12,6 +12,12 @@ export interface UnloadResult {
error?: string
}
+/** Mirrors `engine::worker::DeviceIdentity`: a device without its memory. */
+export interface DeviceIdentity {
+ id: string
+ name: string
+}
+
/** Mirrors `engine::commands::EngineInfo`. */
export interface EngineInfo {
port: number
@@ -19,6 +25,13 @@ export interface EngineInfo {
pid: number
/** Model ids the worker registered from the preset. */
models: string[]
+ /**
+ * The devices the running worker itself initialised, or null when it did not
+ * say. `[]` means the machine has no GPU, which is a real answer. The worker
+ * lists its devices once, at start, so this is what a later enumeration is
+ * compared against to notice a GPU that appeared or vanished.
+ */
+ devices: DeviceIdentity[] | null
}
/** Mirrors `engine::commands::EngineVersion`. */
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
index 68ffcea7a..9fe80c998 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -21,6 +21,8 @@ permissions = [
"allow-engine-devices",
"allow-force-stop-engine",
"allow-engine-slots-idle",
+ "allow-begin-engine-restart",
+ "allow-end-engine-restart",
"allow-erase-thread-slot-state",
# GGUF
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
index e63708735..449c3620f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
@@ -718,6 +718,41 @@ char * jan_llama_devices_json(void) {
return buf;
}
+// jan_llama_devices_json without the memory query, which is the only part that
+// touches the GPU; the id and description are read from ggml's registry.
+char * jan_llama_device_identities_json(void) {
+ std::string out = "[";
+ try {
+ bool first = true;
+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
+ ggml_backend_dev_t dev = ggml_backend_dev_get(i);
+ if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
+ continue;
+ }
+ if (!first) {
+ out += ',';
+ }
+ first = false;
+ out += "{\"id\":";
+ out += json_quote(ggml_backend_dev_name(dev));
+ out += ",\"name\":";
+ out += json_quote(ggml_backend_dev_description(dev));
+ out += '}';
+ }
+ } catch (...) {
+ // Same stance as jan_llama_devices_json: an empty list is recoverable.
+ out = "[";
+ }
+ out += ']';
+
+ char * buf = static_cast<char *>(std::malloc(out.size() + 1));
+ if (buf == nullptr) {
+ return nullptr;
+ }
+ std::memcpy(buf, out.c_str(), out.size() + 1);
+ return buf;
+}
+
void jan_llama_string_free(char * s) {
std::free(s);
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
index 0190e7bba..e28ea37cb 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h
@@ -92,6 +92,13 @@ void jan_llama_load_backends(const char * dir);
// Never NULL; free the result with jan_llama_string_free.
char * jan_llama_devices_json(void);
+// The same devices as {id, name} only, never asking one for its memory. A
+// worker that stays up lists its devices with this: for a CUDA device the
+// memory query in jan_llama_devices_json creates a context that the process
+// then holds for as long as it runs. Names need no such call.
+// Never NULL; free the result with jan_llama_string_free.
+char * jan_llama_device_identities_json(void);
+
void jan_llama_string_free(char * s);
// The llama.cpp the shim was compiled against, for the pin assertion in
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
index e1b65a946..db8b287a0 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs
@@ -87,6 +87,17 @@ fn parse_args() -> Result<Args, String> {
Ok(out)
}
+/// The devices this process initialised, as `[{"id","name"}]`, for the
+/// handshake. `null` when they cannot be read: the app treats that as "not
+/// reported", which is different from `[]`, "no GPU on this machine". Uses the
+/// memory-free listing on purpose; see `Engine::device_identities_json`.
+fn device_identities() -> serde_json::Value {
+ tauri_plugin_llamacpp::engine::Engine::device_identities_json()
+ .ok()
+ .and_then(|json| serde_json::from_str(&json).ok())
+ .unwrap_or(serde_json::Value::Null)
+}
+
#[tokio::main]
async fn main() {
let args = match parse_args() {
@@ -205,6 +216,9 @@ async fn main() {
// Set by build.rs for a CUDA engine; null otherwise. The app sets it
// against the NVIDIA driver to explain a driver that is too old.
"cuda_toolkit": option_env!("JAN_ENGINE_CUDA_TOOLKIT"),
+ // What this process itself initialised. The app compares it with a
+ // later enumeration to notice a GPU that appeared or vanished since.
+ "devices": device_identities(),
})
);
// stdout is a pipe to the supervisor, so it is block-buffered.
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index 59125019f..a3134f4fd 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -6,7 +6,7 @@ use std::time::Duration;
use tauri::{Emitter, Manager, Runtime, State};
use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};
-use crate::state::{LlamacppState, SessionInfo};
+use crate::state::{EngineLease, LlamacppState, SessionInfo};
type HmacSha256 = Hmac<Sha256>;
@@ -26,15 +26,20 @@ struct ModelRequestBody<'a> {
/// One place resolves the worker, so `load_llama_model`, `unload_llama_model`,
/// `ensure_session_ready`, `find_session_by_model`, `get_loaded_models` and the
/// health probes all reach it the same way.
+///
+/// The lease comes back with the address and must be held until the request
+/// that uses it is done: without it a device-change restart can stop this
+/// worker between the lookup and the send.
async fn engine_endpoint<R: Runtime>(
app_handle: &tauri::AppHandle<R>,
-) -> Result<(u16, String, u32), String> {
+) -> Result<(u16, String, u32, EngineLease), String> {
let state: State<Arc<LlamacppState>> = app_handle.state();
+ let lease = state.lease().await;
let guard = state.engine.lock().await;
let h = guard
.as_ref()
.ok_or_else(|| "no llama.cpp engine is running".to_string())?;
- Ok((h.port, h.api_key.clone(), h.pid))
+ Ok((h.port, h.api_key.clone(), h.pid, lease))
}
/// Loopback only, so never through a proxy; see `loopback_client_builder`.
@@ -616,7 +621,7 @@ pub async fn load_llama_model<R: Runtime>(
model_id: String,
is_embedding: bool,
) -> ServerResult<SessionInfo> {
- let (port, api_key, pid) = engine_endpoint(&app_handle)
+ let (port, api_key, pid, _lease) = engine_endpoint(&app_handle)
.await
.map_err(ServerError::InvalidArgument)?;
post_load(&app_handle, port, &api_key, &model_id).await?;
@@ -634,7 +639,7 @@ pub async fn unload_llama_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
model_id: String,
) -> ServerResult<UnloadResult> {
- let (port, api_key, _pid) = engine_endpoint(&app_handle)
+ let (port, api_key, _pid, _lease) = engine_endpoint(&app_handle)
.await
.map_err(ServerError::InvalidArgument)?;
match post_unload(port, &api_key, &model_id).await {
@@ -660,7 +665,7 @@ pub async fn ensure_session_ready<R: Runtime>(
model_id: String,
is_embedding: bool,
) -> Result<SessionInfo, String> {
- let (port, api_key, pid) = engine_endpoint(&app_handle).await?;
+ let (port, api_key, pid, _lease) = engine_endpoint(&app_handle).await?;
post_load(&app_handle, port, &api_key, &model_id)
.await
.map_err(|e| e.to_string())?;
@@ -678,7 +683,7 @@ pub async fn find_session_by_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
model_id: String,
) -> Result<Option<SessionInfo>, String> {
- let (port, api_key, pid) = match engine_endpoint(&app_handle).await {
+ let (port, api_key, pid, _lease) = match engine_endpoint(&app_handle).await {
Ok(v) => v,
Err(_) => return Ok(None),
};
@@ -700,7 +705,7 @@ pub async fn find_session_by_model<R: Runtime>(
pub async fn get_loaded_models<R: Runtime>(
app_handle: tauri::AppHandle<R>,
) -> Result<Vec<String>, String> {
- let (port, api_key, _pid) = match engine_endpoint(&app_handle).await {
+ let (port, api_key, _pid, _lease) = match engine_endpoint(&app_handle).await {
Ok(v) => v,
Err(_) => return Ok(Vec::new()),
};
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
index 307dd0840..d5f01ef95 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs
@@ -20,6 +20,11 @@ pub struct EngineInfo {
pub pid: u32,
/// Registered model ids, from the preset the worker read.
pub models: Vec<String>,
+ /// The devices this worker initialised, `None` when it did not say. Both
+ /// `start_engine` and `get_engine_info` read it off the running worker, so
+ /// a caller that attaches to an existing worker gets that worker's own
+ /// baseline rather than whatever the machine offers now.
+ pub devices: Option<Vec<worker::DeviceIdentity>>,
}
impl From<&WorkerHandle> for EngineInfo {
@@ -29,6 +34,7 @@ impl From<&WorkerHandle> for EngineInfo {
api_key: h.api_key.clone(),
pid: h.pid,
models: h.models.clone(),
+ devices: h.devices.clone(),
}
}
}
@@ -459,6 +465,43 @@ pub async fn engine_slots_idle(
})
}
+/// Claims the engine for a restart, or says it cannot.
+///
+/// `false` means a request holds the worker (a native proxy or agent request
+/// that resolved its address and has not finished) or a generation is in
+/// flight: restarting now would cut it off. On `true` every new request waits
+/// until `end_engine_restart`, so none resolves the old worker's address after
+/// the caller's idle check, which is the gap the extension's own lease cannot
+/// close from JavaScript.
+#[tauri::command]
+pub async fn begin_engine_restart(
+ state: State<'_, Arc<LlamacppState>>,
+) -> Result<bool, String> {
+ if !state.begin_restart().await {
+ return Ok(false);
+ }
+ // Checked after the claim: nothing new can start from here, so what the
+ // worker reports is everything there will be.
+ let running = {
+ let guard = state.engine.lock().await;
+ guard.as_ref().map(|h| (h.port, h.api_key.clone()))
+ };
+ if let Some((port, api_key)) = running {
+ if !busy_models(port, &api_key).await.is_empty() {
+ state.end_restart().await;
+ return Ok(false);
+ }
+ }
+ Ok(true)
+}
+
+/// Lets requests through again. Safe to call without a restart in progress.
+#[tauri::command]
+pub async fn end_engine_restart(state: State<'_, Arc<LlamacppState>>) -> Result<(), String> {
+ state.end_restart().await;
+ Ok(())
+}
+
/// Drops saved state without a worker, by editing the directory in this
/// process.
///
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
index 6c7371a85..a6838b22d 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs
@@ -63,6 +63,7 @@ mod imp {
fn jan_llama_response_free(res: ResponseHandle);
fn jan_llama_load_backends(dir: *const c_char);
fn jan_llama_devices_json() -> *mut c_char;
+ fn jan_llama_device_identities_json() -> *mut c_char;
fn jan_llama_string_free(s: *mut c_char);
fn jan_llama_version() -> *const c_char;
fn jan_llama_build_number() -> c_int;
@@ -256,6 +257,22 @@ mod imp {
Ok(json)
}
+ /// The offloadable devices as `[{"id","name"}]`, without their memory.
+ ///
+ /// For a worker that stays up: `devices_json` asks each device how much
+ /// memory it has, and for a CUDA device that call creates a context the
+ /// process then holds for as long as it runs. Names need no such call.
+ pub fn device_identities_json() -> Result<String, EngineError> {
+ // SAFETY: as `devices_json`.
+ let raw = unsafe { jan_llama_device_identities_json() };
+ if raw.is_null() {
+ return Err(EngineError::Unavailable);
+ }
+ let json = unsafe { CStr::from_ptr(raw) }.to_string_lossy().into_owned();
+ unsafe { jan_llama_string_free(raw) };
+ Ok(json)
+ }
+
pub fn linked_version() -> Result<String, EngineError> {
// SAFETY: returns a pointer to a static string in the shim.
Ok(unsafe { CStr::from_ptr(jan_llama_version()) }
@@ -430,6 +447,9 @@ mod imp {
pub fn devices_json() -> Result<String, EngineError> {
Err(EngineError::Unavailable)
}
+ pub fn device_identities_json() -> Result<String, EngineError> {
+ Err(EngineError::Unavailable)
+ }
pub fn linked_version() -> Result<String, EngineError> {
Err(EngineError::Unavailable)
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
index 0d7fa671b..0f9c5127e 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs
@@ -14,10 +14,20 @@ use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
+use serde::{Deserialize, Serialize};
use tauri_plugin_hardware::vendor::nvidia::CudaVersion;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
+/// A device as the engine names it: the id a `device` setting uses and the
+/// human name. Deliberately without memory, which changes constantly and says
+/// nothing about whether the set of GPUs is the same.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DeviceIdentity {
+ pub id: String,
+ pub name: String,
+}
+
/// The worker prints this and nothing else on stdout, then serves. Reading a
/// structured line beats the router path's stderr scraping: there is no
/// version-dependent log phrasing to match, and no race against a log file.
@@ -29,6 +39,11 @@ pub struct Handshake {
/// The CUDA toolkit the engine was built with, which decides how new an
/// NVIDIA driver it needs.
pub cuda_toolkit: Option<CudaVersion>,
+ /// The devices the worker itself initialised, as it saw them at start.
+ /// `None` when it did not say (a worker that predates the field, or one
+ /// that could not list them), which is not the same as `Some(vec![])`: an
+ /// empty list is a real answer, "this machine has no GPU".
+ pub devices: Option<Vec<DeviceIdentity>>,
}
#[derive(Debug, PartialEq, Eq)]
@@ -282,11 +297,24 @@ pub fn parse_handshake(line: &str) -> Result<Handshake, WorkerError> {
.get("cuda_toolkit")
.and_then(serde_json::Value::as_str)
.and_then(CudaVersion::parse);
+ // `null` or absent means "not reported", which must stay distinct from an
+ // empty list. One unreadable entry makes the whole list untrustworthy as a
+ // baseline, so it reads as not reported rather than as a shorter list that
+ // would later look like a change.
+ let devices = v
+ .get("devices")
+ .and_then(serde_json::Value::as_array)
+ .and_then(|a| {
+ a.iter()
+ .map(|d| serde_json::from_value::<DeviceIdentity>(d.clone()).ok())
+ .collect::<Option<Vec<_>>>()
+ });
Ok(Handshake {
port,
pid,
models,
cuda_toolkit,
+ devices,
})
}
@@ -374,6 +402,12 @@ pub struct WorkerHandle {
pub models: Vec<String>,
/// The CUDA toolkit the engine was built with, when it reported one.
pub cuda_toolkit: Option<CudaVersion>,
+ /// The devices the worker itself initialised, from its handshake (`None`
+ /// when it did not say). It lists its GPUs once, at start, so this is the
+ /// baseline a later enumeration is compared against. Kept on the handle,
+ /// not in the webview, so it survives a page reload and always describes
+ /// the worker that is actually running.
+ pub devices: Option<Vec<DeviceIdentity>>,
child: Child,
/// Declared after `child` so it is dropped after it: the graceful stop must
/// get its turn before closing the job would kill the worker outright.
@@ -595,6 +629,7 @@ pub async fn spawn(
api_key: api_key.to_string(),
models: hs.models,
cuda_toolkit: hs.cuda_toolkit,
+ devices: hs.devices,
child,
#[cfg(windows)]
_job: job,
@@ -825,6 +860,7 @@ mod tests {
pid: 1234,
models: vec!["a".into(), "b".into()],
cuda_toolkit: Some(CudaVersion { major: 13, minor: 2 }),
+ devices: None,
}
);
}
@@ -853,6 +889,52 @@ mod tests {
}
}
+ fn id_name(id: &str, name: &str) -> DeviceIdentity {
+ DeviceIdentity {
+ id: id.into(),
+ name: name.into(),
+ }
+ }
+
+ #[test]
+ fn parse_handshake_reads_the_devices_the_worker_initialised() {
+ let hs = parse_handshake(
+ r#"{"port":8080,"devices":[{"id":"CUDA0","name":"RTX 4060"},{"id":"Vulkan1","name":"UHD"}]}"#,
+ )
+ .unwrap();
+ assert_eq!(
+ hs.devices,
+ Some(vec![id_name("CUDA0", "RTX 4060"), id_name("Vulkan1", "UHD")])
+ );
+ }
+
+ // "No GPU" is a real baseline: a GPU appearing later must read as a change.
+ // Not reporting is not that, or a worker that predates the field would be
+ // restarted on every check.
+ #[test]
+ fn parse_handshake_tells_no_devices_from_devices_not_reported() {
+ let none = parse_handshake(r#"{"port":8080,"devices":[]}"#).unwrap();
+ assert_eq!(none.devices, Some(vec![]));
+ for line in [
+ r#"{"port":8080}"#,
+ r#"{"port":8080,"devices":null}"#,
+ r#"{"port":8080,"devices":"CUDA0"}"#,
+ ] {
+ assert_eq!(parse_handshake(line).unwrap().devices, None, "{line}");
+ }
+ }
+
+ // A truncated list as a baseline would look like a GPU appearing, and
+ // restart the engine for nothing.
+ #[test]
+ fn parse_handshake_does_not_trust_a_list_with_an_unreadable_entry() {
+ let hs = parse_handshake(
+ r#"{"port":8080,"devices":[{"id":"CUDA0","name":"RTX"},{"id":"Vulkan1"}]}"#,
+ )
+ .unwrap();
+ assert_eq!(hs.devices, None);
+ }
+
#[test]
fn parse_handshake_rejects_a_missing_or_impossible_port() {
// Port 0 would mean "the OS did not assign one", which is never a
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index d1555f018..4383514fa 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -30,6 +30,8 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
engine::commands::engine_devices,
engine::commands::force_stop_engine,
engine::commands::engine_slots_idle,
+ engine::commands::begin_engine_restart,
+ engine::commands::end_engine_restart,
engine::commands::erase_thread_slot_state,
commands::generate_api_key,
commands::ensure_session_ready,
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
index af1bebe8c..12b594b81 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
@@ -1,5 +1,9 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
use serde::{Deserialize, Serialize};
-use tokio::sync::Mutex;
+use tokio::sync::{Mutex, OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
@@ -17,13 +21,78 @@ pub struct LlamacppState {
/// It is what turns an eviction Jan did not initiate into a frontend
/// event, so it is aborted whenever the worker stops.
pub unload_watcher: Mutex<Option<tokio::task::JoinHandle<()>>>,
+ /// Requests hold the read side from before they resolve the worker's
+ /// address until they are done with it; a device-change restart takes the
+ /// write side. Reading `engine` and sending are two steps, so without this
+ /// a restart could land between them and the request would hit a stopped
+ /// worker.
+ lifecycle: Arc<RwLock<()>>,
+ /// The write side of `lifecycle` while a device-change restart is running.
+ /// A restart spans two frontend calls (stop, then start), so it is kept
+ /// here between them.
+ restart: Mutex<Option<RestartGuard>>,
+ /// Identifies the current restart, so the watchdog that frees an abandoned
+ /// one never frees a later one.
+ restart_epoch: AtomicU64,
}
+/// A restart the frontend began and never finished (the page reloaded
+/// mid-restart) would otherwise hold every request back for good.
+const RESTART_MAX: Duration = Duration::from_secs(120);
+
+/// Held by a request that resolved the engine worker's address, so the worker
+/// is not restarted while the request still depends on it. Dropping it, which
+/// includes the end of a streamed response, releases it.
+#[must_use = "the lease only protects the worker while it is held"]
+pub struct EngineLease(#[allow(dead_code)] OwnedRwLockReadGuard<()>);
+
+impl EngineLease {
+ /// Ties the lease to a response body, so it lasts until the body has been
+ /// read to its end or dropped. A streamed response is read long after the
+ /// handler that built it has returned, and a restart landing in between
+ /// would cut the client off.
+ pub fn guard<B: hyper::body::Body + Unpin>(self, body: B) -> LeasedBody<B> {
+ LeasedBody { inner: body, _lease: self }
+ }
+}
+
+/// A body that keeps an [`EngineLease`] alive for as long as it exists.
+pub struct LeasedBody<B> {
+ inner: B,
+ _lease: EngineLease,
+}
+
+impl<B: hyper::body::Body + Unpin> hyper::body::Body for LeasedBody<B> {
+ type Data = B::Data;
+ type Error = B::Error;
+
+ fn poll_frame(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
+ std::pin::Pin::new(&mut self.inner).poll_frame(cx)
+ }
+
+ fn is_end_stream(&self) -> bool {
+ self.inner.is_end_stream()
+ }
+
+ fn size_hint(&self) -> hyper::body::SizeHint {
+ self.inner.size_hint()
+ }
+}
+
+/// Proof that no request holds a lease, and none can take one until it drops.
+pub(crate) struct RestartGuard(#[allow(dead_code)] OwnedRwLockWriteGuard<()>);
+
impl Default for LlamacppState {
fn default() -> Self {
Self {
engine: Mutex::new(None),
unload_watcher: Mutex::new(None),
+ lifecycle: Arc::new(RwLock::new(())),
+ restart: Mutex::new(None),
+ restart_epoch: AtomicU64::new(0),
}
}
}
@@ -32,4 +101,162 @@ impl LlamacppState {
pub fn new() -> Self {
Self::default()
}
+
+ /// Take this before reading `engine` and keep it until the request that
+ /// read it is finished. It waits while a restart is in progress, so a
+ /// request that arrives mid-restart is served by the new worker instead of
+ /// failing because there is none.
+ pub async fn lease(&self) -> EngineLease {
+ EngineLease(self.lifecycle.clone().read_owned().await)
+ }
+
+ /// `None` while any request holds a lease. Never waits: a restart that
+ /// cannot start now is a restart that would interrupt work, and the caller
+ /// reports that as busy rather than queueing behind it (which would also
+ /// make every later request queue behind the queued restart).
+ pub(crate) fn try_restart_guard(&self) -> Option<RestartGuard> {
+ self.lifecycle
+ .clone()
+ .try_write_owned()
+ .ok()
+ .map(RestartGuard)
+ }
+
+ /// Starts a restart if no request is using the worker. Until
+ /// `end_restart` (or `RESTART_MAX`), new leases wait.
+ pub(crate) async fn begin_restart(self: &Arc<Self>) -> bool {
+ let Some(guard) = self.try_restart_guard() else {
+ return false;
+ };
+ let epoch = self.restart_epoch.fetch_add(1, Ordering::SeqCst) + 1;
+ *self.restart.lock().await = Some(guard);
+ let state = self.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(RESTART_MAX).await;
+ if state.restart_epoch.load(Ordering::SeqCst) == epoch {
+ log::warn!("a device-change restart was never finished; releasing it");
+ state.restart.lock().await.take();
+ }
+ });
+ true
+ }
+
+ pub(crate) async fn end_restart(&self) {
+ self.restart_epoch.fetch_add(1, Ordering::SeqCst);
+ self.restart.lock().await.take();
+ }
+}
+
+#[cfg(test)]
+mod lifecycle_tests {
+ use super::LlamacppState;
+ use std::time::Duration;
+
+ #[tokio::test]
+ async fn a_held_lease_refuses_a_restart() {
+ let state = LlamacppState::new();
+ let lease = state.lease().await;
+ assert!(state.try_restart_guard().is_none());
+ drop(lease);
+ assert!(state.try_restart_guard().is_some());
+ }
+
+ #[tokio::test]
+ async fn any_one_of_several_leases_is_enough_to_refuse() {
+ let state = LlamacppState::new();
+ let first = state.lease().await;
+ let second = state.lease().await;
+ drop(first);
+ assert!(state.try_restart_guard().is_none());
+ drop(second);
+ assert!(state.try_restart_guard().is_some());
+ }
+
+ #[tokio::test]
+ async fn a_request_arriving_mid_restart_waits_for_it_then_proceeds() {
+ let state = std::sync::Arc::new(LlamacppState::new());
+ let restart = state.try_restart_guard().expect("idle, so the restart starts");
+
+ let waiter = {
+ let state = state.clone();
+ tokio::spawn(async move { state.lease().await })
+ };
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ assert!(!waiter.is_finished(), "a lease must not be granted mid-restart");
+
+ drop(restart);
+ let lease = tokio::time::timeout(Duration::from_secs(2), waiter)
+ .await
+ .expect("the request proceeds once the restart is over")
+ .unwrap();
+ drop(lease);
+ }
+
+ /// A body fed by hand, standing in for a streamed engine response.
+ struct ChannelBody(tokio::sync::mpsc::Receiver<bytes::Bytes>);
+
+ impl hyper::body::Body for ChannelBody {
+ type Data = bytes::Bytes;
+ type Error = std::convert::Infallible;
+
+ fn poll_frame(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<Option<Result<hyper::body::Frame<bytes::Bytes>, Self::Error>>> {
+ self.0.poll_recv(cx).map(|c| c.map(|b| Ok(hyper::body::Frame::data(b))))
+ }
+ }
+
+ fn channel_body() -> (tokio::sync::mpsc::Sender<bytes::Bytes>, ChannelBody) {
+ let (tx, rx) = tokio::sync::mpsc::channel(4);
+ (tx, ChannelBody(rx))
+ }
+
+ // The lease has to outlive the handler: the response is streamed after it
+ // returns, and a restart that lands mid-stream would cut the client off.
+ #[tokio::test]
+ async fn a_streamed_response_keeps_its_lease_until_it_is_read_to_the_end() {
+ use http_body_util::BodyExt;
+ let state = LlamacppState::new();
+ let (tx, body) = channel_body();
+ let mut body = state.lease().await.guard(body);
+
+ tx.send(bytes::Bytes::from_static(b"chunk")).await.unwrap();
+ let frame = body.frame().await.unwrap().unwrap();
+ assert_eq!(frame.into_data().unwrap(), "chunk");
+ assert!(
+ state.try_restart_guard().is_none(),
+ "still streaming: the lease must still be held"
+ );
+
+ drop(tx);
+ assert!(body.frame().await.is_none());
+ drop(body);
+ assert!(state.try_restart_guard().is_some());
+ }
+
+ #[tokio::test]
+ async fn a_response_dropped_unread_releases_its_lease() {
+ let state = LlamacppState::new();
+ let body = state
+ .lease()
+ .await
+ .guard(http_body_util::Full::new(bytes::Bytes::from_static(b"whole body")));
+ assert!(state.try_restart_guard().is_none());
+ // The client went away without reading anything.
+ drop(body);
+ assert!(state.try_restart_guard().is_some());
+ }
+
+ #[tokio::test]
+ async fn a_refused_restart_does_not_block_later_requests() {
+ let state = LlamacppState::new();
+ let lease = state.lease().await;
+ assert!(state.try_restart_guard().is_none());
+ // A queued writer would make this wait behind it; a refused one must not.
+ let another = tokio::time::timeout(Duration::from_secs(1), state.lease())
+ .await
+ .expect("the refused restart left no writer queued");
+ drop((lease, another));
+ }
}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 6a1e98553..dbba9dac8 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -3461,6 +3461,11 @@ async fn orchestrate_inner(
args: &OrchestrationArgs,
steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
) -> Result<serde_json::Value, String> {
+ // The upstream address is resolved once below and reused for every turn, so
+ // the lease is held for the whole run: a device-change restart must not stop
+ // the worker between two turns of it.
+ #[cfg(not(feature = "cli"))]
+ let _engine_lease = args.llama_state.lease().await;
let OrchestrationArgs {
client,
provider_configs,
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 58143ac05..92109af00 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -66,6 +66,12 @@ fn body_channel() -> (BodySender, ResBody) {
(BodySender(tx), body)
}
+/// Keeps `lease` alive until `body` has been read to its end or dropped, which
+/// is when the client has everything it asked the engine for or has gone away.
+fn hold_lease(body: ResBody, lease: tauri_plugin_llamacpp::state::EngineLease) -> ResBody {
+ BodyExt::boxed(lease.guard(body))
+}
+
/// Transform Anthropic /messages API body to OpenAI /chat/completions body
pub(crate) fn transform_anthropic_to_openai(body: &serde_json::Value) -> Option<serde_json::Value> {
let model = body.get("model")?.as_str()?;
@@ -2515,18 +2521,37 @@ async fn start_server_internal(
let jan_data_folder = jan_data_folder.clone();
let svc = service_fn(move |req| {
- proxy_request(
- req,
- client.clone(),
- config.clone(),
- llama_state.clone(),
- mlx_sessions.clone(),
- provider_configs.clone(),
- model_param_defaults.clone(),
- mcp_servers.clone(),
- mcp_settings.clone(),
- jan_data_folder.clone(),
- )
+ let client = client.clone();
+ let config = config.clone();
+ let llama_state = llama_state.clone();
+ let mlx_sessions = mlx_sessions.clone();
+ let provider_configs = provider_configs.clone();
+ let model_param_defaults = model_param_defaults.clone();
+ let mcp_servers = mcp_servers.clone();
+ let mcp_settings = mcp_settings.clone();
+ let jan_data_folder = jan_data_folder.clone();
+ async move {
+ // Taken before the request resolves the engine's address and
+ // kept until its response body is finished, so a device-change
+ // restart cannot stop the worker between the two. A request
+ // arriving mid-restart waits here and is then served by the
+ // new worker instead of failing with "no models are running".
+ let lease = llama_state.lease().await;
+ let response = proxy_request(
+ req,
+ client,
+ config,
+ llama_state,
+ mlx_sessions,
+ provider_configs,
+ model_param_defaults,
+ mcp_servers,
+ mcp_settings,
+ jan_data_folder,
+ )
+ .await?;
+ Ok::<_, hyper::Error>(response.map(|body| hold_lease(body, lease)))
+ }
});
tokio::spawn(async move {
diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.json
index d9e7d5c91..6ecac28bd 100644
--- a/web-app/src/locales/en/settings.json
+++ b/web-app/src/locales/en/settings.json
@@ -160,6 +160,8 @@
"deviceListError": "Couldn't read GPU devices",
"noDevicesDesc": "No GPUs are visible to the llama.cpp engine. Models will run on the CPU.",
"gpuDisabled": "Disabled",
+ "engineRestartedForDevices": "Your GPUs changed, so the local engine was restarted. Models reload on next use.",
+ "engineBusyDevicesChanged": "Your GPUs changed, but a model is busy. Stop it, then press Refresh to use the new GPU.",
"backendApiDesc": "How llama.cpp talks to this GPU",
"backendSelectDesc": "Use this API for this GPU",
"unifiedMemory": "Unified Memory",
diff --git a/web-app/src/routes/settings/__tests__/hardware.test.tsx b/web-app/src/routes/settings/__tests__/hardware.test.tsx
index 7c4f5ff5e..aad872f4b 100644
--- a/web-app/src/routes/settings/__tests__/hardware.test.tsx
+++ b/web-app/src/routes/settings/__tests__/hardware.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
-import { render, screen, waitFor } from '@testing-library/react'
+import { render, screen, waitFor, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
// Mock all the dependencies with minimal implementation
@@ -14,9 +14,18 @@ vi.mock('@/containers/HeaderPage', () => ({
}))
vi.mock('@/containers/Card', () => ({
- Card: ({ title, children }: { title?: string; children: React.ReactNode }) => (
+ Card: ({
+ title,
+ header,
+ children,
+ }: {
+ title?: string
+ header?: React.ReactNode
+ children: React.ReactNode
+ }) => (
<div data-testid="card">
{title && <div>{title}</div>}
+ {header}
{children}
</div>
),
@@ -83,6 +92,36 @@ vi.mock('@/hooks/useModelProvider', () => ({
}),
}))
+// A stable hub, so a test can see exactly what Refresh asked the services to do.
+const hub = vi.hoisted(() => ({
+ reconcile: vi.fn(),
+ setActiveModels: vi.fn(),
+ toast: { info: vi.fn(), warning: vi.fn() },
+}))
+
+vi.mock('sonner', () => ({ toast: hub.toast }))
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({
+ window: () => ({ openSystemMonitorWindow: vi.fn() }),
+ hardware: () => ({
+ refreshHardwareInfo: vi.fn().mockResolvedValue(undefined),
+ getHardwareInfo: vi.fn().mockResolvedValue(null),
+ getSystemUsage: vi.fn().mockResolvedValue(null),
+ reconcileLlamacppDevices: hub.reconcile,
+ }),
+ models: () => ({
+ stopAllModels: vi.fn(),
+ getActiveModels: vi.fn().mockResolvedValue([]),
+ }),
+ }),
+}))
+
+vi.mock('@/hooks/useAppState', () => ({
+ useAppState: (sel: (s: unknown) => unknown) =>
+ sel({ setActiveModels: hub.setActiveModels }),
+}))
+
vi.mock('@/services/hardware', () => ({
getHardwareInfo: vi.fn(() => Promise.resolve({})),
getSystemUsage: vi.fn(() => Promise.resolve({})),
@@ -203,6 +242,45 @@ describe('Hardware Settings', () => {
})
})
+ describe('Refresh and a GPU that appeared after launch', () => {
+ const press = async () => {
+ const Component = Route.component as React.ComponentType
+ render(<Component />)
+ // The page renders a placeholder until hardware data arrives.
+ fireEvent.click(await screen.findByText('settings:hardware.refresh'))
+ }
+
+ it('says the engine restarted and clears the loaded-model list', async () => {
+ hub.reconcile.mockResolvedValue('restarted')
+ await press()
+ await waitFor(() =>
+ expect(hub.toast.info).toHaveBeenCalledWith(
+ 'settings:hardware.engineRestartedForDevices'
+ )
+ )
+ expect(hub.setActiveModels).toHaveBeenCalledWith([])
+ })
+
+ it('asks the user to stop the busy model instead of interrupting it', async () => {
+ hub.reconcile.mockResolvedValue('busy')
+ await press()
+ await waitFor(() =>
+ expect(hub.toast.warning).toHaveBeenCalledWith(
+ 'settings:hardware.engineBusyDevicesChanged'
+ )
+ )
+ expect(hub.setActiveModels).not.toHaveBeenCalled()
+ })
+
+ it('stays quiet when nothing changed', async () => {
+ hub.reconcile.mockResolvedValue('unchanged')
+ await press()
+ await waitFor(() => expect(hub.reconcile).toHaveBeenCalled())
+ expect(hub.toast.info).not.toHaveBeenCalled()
+ expect(hub.toast.warning).not.toHaveBeenCalled()
+ })
+ })
+
it('hides GPU devices on macOS', async () => {
global.IS_MACOS = true
const Component = Route.component as React.ComponentType
diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsx
index 3f168f842..f92995c6d 100644
--- a/web-app/src/routes/settings/hardware.tsx
+++ b/web-app/src/routes/settings/hardware.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from '@/i18n/react-i18next-compat'
import { useHardware, type GPU } from '@/hooks/useHardware'
import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'
import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
import { IconDeviceDesktopAnalytics, IconRefresh } from '@tabler/icons-react'
import { useServiceHub } from '@/hooks/useServiceHub'
import type {
@@ -441,7 +442,19 @@ function HardwareContent() {
])
if (hardwareData) setHardwareData(hardwareData)
if (systemUsage) updateSystemUsage(systemUsage)
- if (!IS_MACOS) fetchDevices()
+ if (!IS_MACOS) {
+ // A GPU that appeared after launch (a laptop leaving eco mode) is listed
+ // by the fresh enumeration, but the running engine cannot use it until
+ // it restarts.
+ const outcome = await serviceHub.hardware().reconcileLlamacppDevices()
+ if (outcome === 'restarted') {
+ setActiveModels([])
+ toast.info(t('settings:hardware.engineRestartedForDevices'))
+ } else if (outcome === 'busy') {
+ toast.warning(t('settings:hardware.engineBusyDevicesChanged'))
+ }
+ fetchDevices()
+ }
} catch (error) {
console.error('Failed to refresh hardware:', error)
} finally {
diff --git a/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts b/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts
index f8448c145..d35cedff6 100644
--- a/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts
+++ b/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts
@@ -51,6 +51,28 @@ describe('TauriHardwareService – coverage', () => {
})
})
+ describe('reconcileLlamacppDevices', () => {
+ it('asks the llamacpp extension to reconcile and returns its answer', async () => {
+ const reconcileEngineDevices = vi.fn().mockResolvedValue('restarted')
+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue({
+ reconcileEngineDevices,
+ })
+
+ await expect(svc.reconcileLlamacppDevices()).resolves.toBe('restarted')
+ expect(window.core.extensionManager.getByName).toHaveBeenCalledWith(
+ '@janhq/llamacpp-extension'
+ )
+ })
+
+ it('is unchanged when the extension is absent or too old to reconcile', async () => {
+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue(undefined)
+ await expect(svc.reconcileLlamacppDevices()).resolves.toBe('unchanged')
+
+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue({})
+ await expect(svc.reconcileLlamacppDevices()).resolves.toBe('unchanged')
+ })
+ })
+
describe('refreshHardwareInfo', () => {
it('invokes plugin:hardware|refresh_system_info', async () => {
const { invoke } = await import('@tauri-apps/api/core')
diff --git a/web-app/src/services/hardware/default.ts b/web-app/src/services/hardware/default.ts
index 3bdfb516d..1b97783a6 100644
--- a/web-app/src/services/hardware/default.ts
+++ b/web-app/src/services/hardware/default.ts
@@ -17,6 +17,10 @@ export class DefaultHardwareService implements HardwareService {
return []
}
+ async reconcileLlamacppDevices(): Promise<'unchanged' | 'restarted' | 'busy'> {
+ return 'unchanged'
+ }
+
async setActiveGpus(data: { gpus: number[] }): Promise<void> {
console.log('setActiveGpus called with data:', data)
// No-op - not implemented in default service
diff --git a/web-app/src/services/hardware/tauri.ts b/web-app/src/services/hardware/tauri.ts
index 7f2e26f33..322251357 100644
--- a/web-app/src/services/hardware/tauri.ts
+++ b/web-app/src/services/hardware/tauri.ts
@@ -26,6 +26,14 @@ export class TauriHardwareService extends DefaultHardwareService {
return llamacppExtension.getDevices()
}
+ async reconcileLlamacppDevices(): Promise<'unchanged' | 'restarted' | 'busy'> {
+ const llamacppExtension = window.core.extensionManager.getByName(
+ '@janhq/llamacpp-extension'
+ )
+ if (!llamacppExtension?.reconcileEngineDevices) return 'unchanged'
+ return llamacppExtension.reconcileEngineDevices()
+ }
+
async setActiveGpus(data: { gpus: number[] }): Promise<void> {
// TODO: llama.cpp extension should handle this
console.log(data)
diff --git a/web-app/src/services/hardware/types.ts b/web-app/src/services/hardware/types.ts
index a32be25a8..c3e3c14ec 100644
--- a/web-app/src/services/hardware/types.ts
+++ b/web-app/src/services/hardware/types.ts
@@ -17,6 +17,12 @@ export interface HardwareService {
getHardwareInfo(): Promise<HardwareData | null>
getSystemUsage(): Promise<SystemUsage | null>
getLlamacppDevices(): Promise<DeviceList[]>
+ /**
+ * Restarts the llama.cpp engine when the machine now offers different devices
+ * than the running engine started with. 'busy' means a model is loading or
+ * generating, so nothing was touched.
+ */
+ reconcileLlamacppDevices(): Promise<'unchanged' | 'restarted' | 'busy'>
setActiveGpus(data: { gpus: number[] }): Promise<void>
/** Invalidates cached GPU detection so next getHardwareInfo() re-detects. Use after system resume (e.g. Linux sleep). */
refreshHardwareInfo(): Promise<void>