Skip to content

armgit / jan

Public Imported from GitHub
0

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

Feat: llamacpp router mode (#8130)

Akarshan Biswas37f5ab630529
diff --git a/core/src/types/message/messageEntity.ts b/core/src/types/message/messageEntity.ts
index 10d180637..c90481525 100644
--- a/core/src/types/message/messageEntity.ts
+++ b/core/src/types/message/messageEntity.ts
@@ -140,6 +140,7 @@ export enum ContentType {
Text = 'text',
Reasoning = 'reasoning',
Image = 'image_url',
+ InputAudio = 'input_audio',
ToolCall = 'tool_call',
}
@@ -161,6 +162,15 @@ export type ImageContentValue = {
url?: string
}
+/**
+ * The `InputAudioContentValue` type carries base64-encoded audio for OAI-compatible
+ * `input_audio` content parts (supported by llama.cpp mtmd-capable models).
+ */
+export type InputAudioContentValue = {
+ data: string
+ format: 'wav' | 'mp3'
+}
+
/**
* The `ThreadContent` type defines the shape of a message's content object
* @data_transfer_object
@@ -171,6 +181,8 @@ export type ThreadContent = {
text?: ContentValue
// For image content
image_url?: ImageContentValue
+ // For input_audio content
+ input_audio?: InputAudioContentValue
// For tool call content
tool_call_id?: string
tool_name?: string
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 0354d09fc..2c5df7ca9 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -30,18 +30,16 @@
"controllerProps": { "value": true }
},
{
- "key": "auto_unload",
- "title": "Auto-Unload Old Models",
- "description": "Automatically unloads models that are not in use to free up memory. Ensure only one model is loaded at a time.",
- "controllerType": "checkbox",
- "controllerProps": { "value": true }
- },
- {
- "key": "auto_restart_on_crash",
- "title": "Auto-Restart Crashed Models",
- "description": "Automatically reloads a model if its llama-server process crashes.",
- "controllerType": "checkbox",
- "controllerProps": { "value": false }
+ "key": "models_max",
+ "title": "Max Concurrently Loaded Models",
+ "description": "Maximum number of models the router will keep loaded at once. 0 = unlimited.",
+ "controllerType": "input",
+ "controllerProps": {
+ "value": "1",
+ "placeholder": "e.g 1",
+ "type": "number",
+ "textAlign": "right"
+ }
},
{
"key": "timeout",
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 1134ce49c..6d7ab1206 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -39,21 +39,24 @@ import {
getProxyConfig,
buildEmbedBatches,
mergeEmbedResponses,
+ detectEmbeddingFromGgufMeta,
+ getDefaultEmbeddingModelId,
+ setDefaultEmbeddingModelId,
type EmbedBatchResult,
} from './util'
+import { generatePreset } from './preset'
import { basename } from '@tauri-apps/api/path'
import {
loadLlamaModel,
readGgufMetadata,
- getModelSize,
isModelSupported,
unloadLlamaModel,
LlamacppConfig,
DownloadItem,
ModelConfig,
EmbeddingResponse,
+ ModelProps,
DeviceList,
- SystemMemory,
mapOldBackendToNew,
findLatestVersionForBackend,
prioritizeBackends,
@@ -64,7 +67,7 @@ import {
} from '@janhq/tauri-plugin-llamacpp-api'
import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
-// Error message constant - matches web-app/src/utils/error.ts
+const EMBEDDING_CHECK_VERSION = 3
/**
* Override the default app.log function to use Jan's logging system.
@@ -116,7 +119,6 @@ function parseBuildNumber(version: string): number | null {
export default class llamacpp_extension extends AIEngine {
provider: string = 'llamacpp'
- autoUnload: boolean = true
timeout: number = 600
llamacpp_env: string = ''
readonly providerId: string = 'llamacpp'
@@ -130,6 +132,11 @@ export default class llamacpp_extension extends AIEngine {
private loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises
private unlistenValidationStarted?: () => void
+ private routerPort?: number
+ private routerApiKey?: string
+ private userModelsMax: number = 1
+ private loadedChatOrder: string[] = []
+
override async onLoad(): Promise<void> {
super.onLoad() // Calls registerEngine() from AIEngine
@@ -163,26 +170,243 @@ export default class llamacpp_extension extends AIEngine {
// Migration v3: enable fit on Windows/Linux with a discrete GPU
await this.migrateFitPlatformDefault()
- this.autoUnload = this.config.auto_unload
+ await this.migrateAutoUnloadToModelsMax()
+
this.timeout = this.config.timeout
this.llamacpp_env = this.config.llamacpp_env
// This sets the base directory where model files for this provider are stored.
- this.getProviderPath()
+ await this.getProviderPath()
// Set up validation event listeners to bridge Tauri events to frontend
this.unlistenValidationStarted = await listen<{
modelId: string
downloadType: string
}>('onModelValidationStarted', (event) => {
- console.debug(
- 'LlamaCPP: bridging onModelValidationStarted event',
- event.payload
- )
events.emit(DownloadEvent.onModelValidationStarted, event.payload)
})
- this.configureBackends()
+ // configureBackends is async; await it so the router has a backend to
+ // launch. Failures here previously surfaced via unhandled rejection — the
+ // try/catch below preserves that fail-soft behavior for the router step.
+ try {
+ await this.configureBackends()
+ } catch (e) {
+ logger.error('configureBackends failed during onLoad:', e)
+ }
+
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.error('Router failed to start during onLoad:', e)
+ }
+ }
+
+ private async startRouter(): Promise<void> {
+ const versionBackend = this.config?.version_backend
+ if (
+ !versionBackend ||
+ versionBackend === 'none' ||
+ !versionBackend.includes('/')
+ ) {
+ logger.info(
+ 'Router will start once backend is configured (no version_backend yet).'
+ )
+ return
+ }
+
+ const [version, backend] = versionBackend.split('/')
+ if (!version || !backend) {
+ logger.warn(
+ `Skipping router start; malformed version_backend: ${versionBackend}`
+ )
+ return
+ }
+
+ const providerPath = await this.getProviderPath()
+ const janDataFolderPath = await getJanDataFolderPath()
+ const { path: presetPath, embeddingCount } = await generatePreset(
+ providerPath,
+ janDataFolderPath,
+ this.config
+ )
+
+ const backendExe = await getBackendExePath(backend, version)
+ const port = await this.getRandomPort()
+ const apiKey = await this.generateApiKey('router', String(port))
+
+ const envs: Record<string, string> = {}
+ envs['LLAMA_API_KEY'] = apiKey
+ envs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)
+ if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
+
+ const rawMax = (this.config as any).models_max
+ let modelsMax = 1
+ if (typeof rawMax === 'number') modelsMax = rawMax
+ else if (typeof rawMax === 'string' && rawMax.trim().length > 0) {
+ const n = parseInt(rawMax, 10)
+ if (!Number.isNaN(n) && n >= 0) modelsMax = n
+ }
+ // Reserve extra slots for embedding models so loading an embedder doesn't
+ // evict the user's chat model. `models_max` governs chat models only;
+ // Jan pre-evicts the oldest chat model in `performLoad` so the router's
+ // LRU never picks the embedding. 0 (unlimited) stays unlimited.
+ const userModelsMax = modelsMax
+ this.userModelsMax = userModelsMax
+ if (modelsMax > 0 && embeddingCount > 0) {
+ modelsMax += embeddingCount
+ }
+
+ // Defensive: if a router is already running (hot reload / dev), stop it
+ // first so start_router doesn't reject.
+ try {
+ const existing = await invoke<{ port: number; api_key: string } | null>(
+ 'plugin:llamacpp|get_router_info'
+ )
+ if (existing) {
+ await invoke('plugin:llamacpp|stop_router').catch(() => undefined)
+ }
+ } catch {
+ /* ignore probe failures */
+ }
+
+ const info = await invoke<{ port: number; api_key: string; pid: number }>(
+ 'plugin:llamacpp|start_router',
+ {
+ backendExe,
+ presetPath,
+ port,
+ apiKey,
+ modelsMax,
+ defaultArgs: [] as string[],
+ envs,
+ }
+ )
+
+ this.routerPort = info.port
+ this.routerApiKey = info.api_key
+ logger.info(
+ `Router started on port ${info.port} (pid ${info.pid}, models_max=${modelsMax} [user=${userModelsMax}, +${embeddingCount} embedding], preset=${presetPath})`
+ )
+ }
+
+ /**
+ * Public accessor for downstream consumers. Returns `null` if the router
+ * hasn't been started successfully yet.
+ */
+ async getRouterInfo(): Promise<{ port: number; apiKey: string } | null> {
+ if (this.routerPort != null && this.routerApiKey) {
+ return { port: this.routerPort, apiKey: this.routerApiKey }
+ }
+ try {
+ const info = await invoke<
+ { port: number; api_key: string; pid: number } | null
+ >('plugin:llamacpp|get_router_info')
+ if (info) {
+ this.routerPort = info.port
+ this.routerApiKey = info.api_key
+ return { port: info.port, apiKey: info.api_key }
+ }
+ } catch (e) {
+ logger.warn('get_router_info failed:', e)
+ }
+ return null
+ }
+
+ /**
+ * 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 | undefined> {
+ const router = await this.getRouterInfo()
+ if (!router || !modelId) return undefined
+ // Router runs with models_autoload=true, so `/props?model=X` against an
+ // unloaded model 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:${router.port}/props?model=${encodeURIComponent(modelId)}`
+ const res = await fetch(url, {
+ headers: { Authorization: `Bearer ${router.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
+ }
+ const n = json?.default_generation_settings?.n_ctx
+ if (typeof n !== 'number' || n <= 0) return undefined
+ return {
+ nCtx: n,
+ totalSlots:
+ typeof json.total_slots === 'number' ? json.total_slots : undefined,
+ modelAlias: json.model_alias,
+ isSleeping: !!json.is_sleeping,
+ }
+ } 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 }
+ }
+ }
+
+ private async migrateAutoUnloadToModelsMax(): Promise<void> {
+ const MIGRATION_KEY = 'llamacpp_models_max_migrated_v1'
+ if (localStorage.getItem(MIGRATION_KEY)) return
+
+ 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
+ }
+
+ localStorage.setItem(MIGRATION_KEY, '1')
}
private getStoredBackendType(): string | null {
@@ -848,6 +1072,14 @@ export default class llamacpp_extension extends AIEngine {
if (this.unlistenValidationStarted) {
this.unlistenValidationStarted()
}
+
+ try {
+ await invoke('plugin:llamacpp|stop_router')
+ } catch (e) {
+ logger.warn('stop_router during onUnload failed (ignored):', e)
+ }
+ this.routerPort = undefined
+ this.routerApiKey = undefined
}
onSettingUpdate<T>(key: string, value: T): void {
@@ -880,13 +1112,16 @@ export default class llamacpp_extension extends AIEngine {
if (result.version && result.backend) {
this.config.device = ''
await this.ensureBackendReady(result.backend, result.version)
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.warn('Router restart after backend update failed:', e)
+ }
}
} catch (e) {
logger.error('Error in onSettingUpdate async block:', e)
}
})()
- } else if (key === 'auto_unload') {
- this.autoUnload = value as boolean
} else if (key === 'llamacpp_env') {
this.llamacpp_env = value as string
} else if (key === 'timeout') {
@@ -937,12 +1172,16 @@ export default class llamacpp_extension extends AIEngine {
modelId: string,
modelConfig: ModelConfig
): Promise<boolean> {
- // Fast exit: if explicitly set in config, return it
- if (typeof modelConfig.embedding === 'boolean') {
- return modelConfig.embedding
+ 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
}
- // Migration logic: Detect from GGUF
let isEmbedding = false
try {
const janDataFolderPath = await getJanDataFolderPath()
@@ -953,20 +1192,15 @@ export default class llamacpp_extension extends AIEngine {
if (await fs.existsSync(fullModelPath)) {
const metadata = await readGgufMetadata(fullModelPath)
- // Check for BERT-based architectures usually used for embeddings
- // You can expand this list (e.g., 'nomic-bert', 'xlm-roberta')
- const arch = metadata.metadata['general.architecture']
- if (arch === 'bert' || arch === 'nomic-bert') {
+ if (detectEmbeddingFromGgufMeta(metadata.metadata)) {
isEmbedding = true
}
}
} catch (e) {
- // If GGUF read fails, default to false but log it
logger.warn(`Failed to check metadata for ${modelId}`, e)
- return false
+ return cfg.embedding === true
}
- // Persist the result back to model.yml so we don't read GGUF next time
try {
const configPath = await joinPath([
await this.getProviderPath(),
@@ -975,12 +1209,21 @@ export default class llamacpp_extension extends AIEngine {
'model.yml',
])
- // Update the local object
- modelConfig.embedding = isEmbedding
+ 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
+ }
- // Write to disk
await invoke<void>('write_yaml', {
- data: modelConfig,
+ data: cfg,
savePath: configPath,
})
} catch (e) {
@@ -1039,7 +1282,11 @@ export default class llamacpp_extension extends AIEngine {
const capabilities: string[] = []
if (modelConfig.mmproj_path) {
- capabilities.push('vision')
+ const caps = await this.readMmprojCapabilities(
+ modelConfig.mmproj_path
+ )
+ if (caps.vision) capabilities.push('vision')
+ if (caps.audio) capabilities.push('audio')
}
const mp = modelConfig.model_path ?? ''
@@ -1435,9 +1682,7 @@ export default class llamacpp_extension extends AIEngine {
`Model GGUF validation successful: version ${modelMetadata.version}, tensors: ${modelMetadata.tensor_count}`
)
- // check if the model is an embedding model
- const architecture = modelMetadata.metadata['general.architecture']
- if (architecture === 'bert' || architecture === 'nomic-bert') {
+ if (detectEmbeddingFromGgufMeta(modelMetadata.metadata)) {
isEmbedding = true
}
@@ -1478,6 +1723,10 @@ export default class llamacpp_extension extends AIEngine {
mmproj_sha256: opts.mmprojSha256,
mmproj_size_bytes: opts.mmprojSize,
embedding: isEmbedding,
+ embedding_check_v: EMBEDDING_CHECK_VERSION,
+ ...(isEmbedding
+ ? { pooling: 'mean', ubatch_size: 2048, batch_size: 2048 }
+ : {}),
} as ModelConfig
await fs.mkdir(await joinPath([janDataFolderPath, modelDir]))
await invoke<void>('write_yaml', {
@@ -1502,6 +1751,12 @@ export default class llamacpp_extension extends AIEngine {
downloadType: 'Model',
})
}
+
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.warn(`Router refresh after import(${modelId}) failed:`, e)
+ }
}
/**
@@ -1543,17 +1798,8 @@ export default class llamacpp_extension extends AIEngine {
await this.deleteModelFolder(modelId)
}
- /**
- * Function to find a random port
- */
private async getRandomPort(): Promise<number> {
- try {
- const port = await invoke<number>('plugin:llamacpp|get_random_port')
- return port
- } catch {
- logger.error('Unable to find a suitable port')
- throw new Error('Unable to find a suitable port for model')
- }
+ return 49152 + Math.floor(Math.random() * (65535 - 49152))
}
private parseEnvFromString(
@@ -1579,32 +1825,24 @@ export default class llamacpp_extension extends AIEngine {
override async load(
modelId: string,
- overrideSettings?: Partial<LlamacppConfig>,
+ _overrideSettings?: Partial<LlamacppConfig>,
isEmbedding: boolean = false,
- bypassAutoUnload: boolean = false
+ _bypassAutoUnload: boolean = false
): Promise<SessionInfo> {
const sInfo = await this.findSessionByModel(modelId)
if (sInfo) {
throw new Error('Model already loaded!!')
}
- // If this model is already being loaded, return the existing promise
if (this.loadingModels.has(modelId)) {
return this.loadingModels.get(modelId)!
}
- // Create the loading promise
- const loadingPromise = this.performLoad(
- modelId,
- overrideSettings,
- isEmbedding,
- bypassAutoUnload
- )
+ const loadingPromise = this.performLoad(modelId, isEmbedding)
this.loadingModels.set(modelId, loadingPromise)
try {
- const result = await loadingPromise
- return result
+ return await loadingPromise
} finally {
this.loadingModels.delete(modelId)
}
@@ -1612,157 +1850,86 @@ export default class llamacpp_extension extends AIEngine {
private async performLoad(
modelId: string,
- overrideSettings?: Partial<LlamacppConfig>,
- isEmbedding: boolean = false,
- bypassAutoUnload: boolean = false
+ isEmbedding: boolean = false
): Promise<SessionInfo> {
- const loadedModels = await this.getLoadedModels()
-
- // Get OTHER models that are currently loading (exclude current model)
- const otherLoadingPromises = Array.from(this.loadingModels.entries())
- .filter(([id, _]) => id !== modelId)
- .map(([_, promise]) => promise)
-
- if (
- this.autoUnload &&
- !isEmbedding &&
- !bypassAutoUnload &&
- (loadedModels.length > 0 || otherLoadingPromises.length > 0)
- ) {
- // Wait for OTHER loading models to finish, then unload everything
- if (otherLoadingPromises.length > 0) {
- await Promise.all(otherLoadingPromises)
- }
-
- // Now unload all loaded Text models excluding embedding models
- const allLoadedModels = await this.getLoadedModels()
- if (allLoadedModels.length > 0) {
- const sessionInfos: (SessionInfo | null)[] = await Promise.all(
- allLoadedModels.map(async (modelId) => {
- try {
- return await this.findSessionByModel(modelId)
- } catch (e) {
- logger.warn(`Unable to find session for model "${modelId}": ${e}`)
- return null
- }
- })
- )
-
- const nonEmbeddingModels: string[] = sessionInfos
- .filter(
- (s): s is SessionInfo => s !== null && s.is_embedding === false
- )
- .map((s) => s.model_id)
-
- if (nonEmbeddingModels.length > 0) {
- await Promise.all(
- nonEmbeddingModels.map((modelId) => this.unload(modelId))
- )
- }
- }
- }
-
- const envs: Record<string, string> = {}
- const cfg = { ...this.config, ...(overrideSettings ?? {}) }
- const [version, backend] = cfg.version_backend.split('/')
-
- if (!version || !backend) {
+ const router = await this.getRouterInfo()
+ if (!router) {
throw new Error(
- 'Initial setup for the backend failed due to a network issue. Please restart the app!'
+ 'llama.cpp router is not running. Please restart the app.'
)
}
- // Version-aware flash_attn handling:
- // llama.cpp b6325+ changed --flash-attn from a boolean flag to a string
- // For older versions, "auto" is not a valid value so we fall back to "off"
- // (i.e. don't send the flag at all).
- if (cfg.flash_attn === 'auto' && !backend.startsWith('ik')) {
- const buildNum = parseBuildNumber(version)
- if (buildNum !== null && buildNum < 6325) {
- cfg.flash_attn = 'off'
- }
+ if (!isEmbedding) {
+ await this.evictChatIfAtCapacity(modelId)
}
- // Ensure backend is downloaded and ready before proceeding
- await this.ensureBackendReady(backend, version)
-
- const janDataFolderPath = await getJanDataFolderPath()
- const modelConfigPath = await joinPath([
- this.providerPath,
- 'models',
- modelId,
- 'model.yml',
- ])
- const modelConfig = await invoke<ModelConfig>('read_yaml', {
- path: modelConfigPath,
- })
- const port = await this.getRandomPort()
-
- // Generate API key
- const api_key = await this.generateApiKey(modelId, String(port))
- envs['LLAMA_API_KEY'] = api_key
- envs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)
-
- // Set user envs
- if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)
-
- // Resolve model path
- const modelPath = await joinPath([
- janDataFolderPath,
- modelConfig.model_path,
- ])
-
- // Resolve mmproj path if present
- let mmprojPath: string | undefined = undefined
- if (modelConfig.mmproj_path) {
- mmprojPath = await joinPath([janDataFolderPath, modelConfig.mmproj_path])
+ 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
}
+ }
- // Migrate old env vars
- if (typeof cfg.fit === 'string') cfg.fit = true
+ /**
+ * 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
- logger.info(
- 'Calling Tauri command load_llama_model with config:',
- JSON.stringify(cfg)
+ 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
)
- const backendPath = await getBackendExePath(backend, version)
- try {
- const sInfo = await loadLlamaModel(
- backendPath,
- modelId,
- modelPath,
- port,
- cfg,
- envs,
- mmprojPath,
- isEmbedding,
- Number(this.timeout)
- )
- return sInfo
- } catch (error) {
- logger.error('Error in load command:\n', error)
- throw error
+ 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: SessionInfo = await this.findSessionByModel(modelId)
+ const sInfo = await this.findSessionByModel(modelId)
if (!sInfo) {
throw new Error(`No active session found for model: ${modelId}`)
}
- const pid = sInfo.pid
try {
- // Pass the PID as the session_id
- const result = await unloadLlamaModel(pid)
-
- // If successful, remove from active sessions
+ const result = await unloadLlamaModel(modelId)
if (result.success) {
- logger.info(`Successfully unloaded model with PID ${pid}`)
+ this.loadedChatOrder = this.loadedChatOrder.filter((m) => m !== modelId)
+ logger.info(`Successfully unloaded model ${modelId}`)
} else {
- logger.warn(`Failed to unload model: ${result.error}`)
+ logger.warn(`Failed to unload model ${modelId}: ${result.error}`)
}
-
return result
} catch (error) {
logger.error('Error in unload command:', error)
@@ -1934,15 +2101,14 @@ export default class llamacpp_extension extends AIEngine {
}
}
- private async findSessionByModel(modelId: string): Promise<SessionInfo> {
+ private async findSessionByModel(
+ modelId: string
+ ): Promise<SessionInfo | null> {
try {
- let sInfo = await invoke<SessionInfo>(
+ return await invoke<SessionInfo | null>(
'plugin:llamacpp|find_session_by_model',
- {
- modelId,
- }
+ { modelId }
)
- return sInfo
} catch (e) {
logger.error(e)
throw new Error(String(e))
@@ -1952,6 +2118,7 @@ export default class llamacpp_extension extends AIEngine {
private async ensureHealthySession(modelId: string): Promise<SessionInfo> {
return invoke<SessionInfo>('plugin:llamacpp|ensure_session_ready', {
modelId,
+ isEmbedding: false,
})
}
@@ -2012,6 +2179,12 @@ export default class llamacpp_extension extends AIEngine {
}
await fs.rm(modelDir)
+
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.warn(`Router refresh after delete(${modelId}) failed:`, e)
+ }
}
override async getLoadedModels(): Promise<string[]> {
@@ -2161,22 +2334,45 @@ export default class llamacpp_extension extends AIEngine {
}
async embed(text: string[]): Promise<EmbeddingResponse> {
- // Ensure the sentence-transformer model is present
- let sInfo = await this.findSessionByModel('sentence-transformer-mini')
+ const downloadedModelList = await this.list()
+ const installedEmbedding = downloadedModelList.filter(
+ (m) => (m as any).embedding === true
+ )
+ const hasMini = downloadedModelList.some(
+ (m) => m.id === 'sentence-transformer-mini'
+ )
+ let preferred = getDefaultEmbeddingModelId('llamacpp')
+
+ if (!preferred && installedEmbedding.length === 1 && !hasMini) {
+ preferred = installedEmbedding[0].id
+ 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)
+ : 'sentence-transformer-mini'
+
+ let sInfo = await this.findSessionByModel(targetModelId)
if (!sInfo) {
- const downloadedModelList = await this.list()
- if (
- !downloadedModelList.some(
- (model) => model.id === 'sentence-transformer-mini'
- )
- ) {
+ if (targetModelId === 'sentence-transformer-mini' && !hasMini) {
await this.import('sentence-transformer-mini', {
modelPath:
'https://huggingface.co/second-state/All-MiniLM-L6-v2-Embedding-GGUF/resolve/main/all-MiniLM-L6-v2-ggml-model-f16.gguf?download=true',
})
}
- // Load specifically in embedding mode
- sInfo = await this.load('sentence-transformer-mini', undefined, true)
+ sInfo = await this.load(targetModelId, undefined, true)
}
const ubatchSize =
@@ -2208,25 +2404,14 @@ export default class llamacpp_extension extends AIEngine {
}
const sendBatch = async (batchInput: string[]) => {
- let response = await attemptRequest(sInfo as SessionInfo, batchInput)
-
- // If embeddings endpoint is not available (501), reload with embedding mode and retry once
- if (response.status === 501) {
- try {
- await this.unload('sentence-transformer-mini')
- } catch {}
- sInfo = await this.load('sentence-transformer-mini', undefined, true)
- response = await attemptRequest(sInfo as SessionInfo, batchInput)
- }
-
+ const response = await attemptRequest(sInfo as SessionInfo, batchInput)
if (!response.ok) {
const errorData = await response.json().catch(() => null)
throw new Error(
`API request failed with status ${response.status}: ${JSON.stringify(errorData)}`
)
}
- const responseData = (await response.json()) as EmbedBatchResult
- return responseData
+ return (await response.json()) as EmbedBatchResult
}
const batchResults: Array<{ result: EmbedBatchResult; offset: number }> = []
@@ -2301,9 +2486,6 @@ export default class llamacpp_extension extends AIEngine {
logger.info(`Validating GGUF file: ${filePath}`)
const metadata = await readGgufMetadata(filePath)
- // Log full metadata for debugging
- logger.info('Full GGUF metadata:', JSON.stringify(metadata, null, 2))
-
// Check if architecture is 'clip' which is not supported for text generation
const architecture = metadata.metadata?.['general.architecture']
logger.info(`Model architecture: ${architecture}`)
@@ -2336,37 +2518,6 @@ export default class llamacpp_extension extends AIEngine {
}
async getTokensCount(opts: chatCompletionRequest): Promise<number> {
- const sessionInfo = await this.findSessionByModel(opts.model)
- if (!sessionInfo) {
- throw new Error(`No active session found for model: ${opts.model}`)
- }
-
- // Token counting should be side-effect free (no auto-restart/unload).
- const isRunning = await invoke<boolean>('plugin:llamacpp|is_process_running', {
- pid: sessionInfo.pid,
- })
- if (!isRunning) {
- throw new Error('Model has crashed! Please reload!')
- }
-
- try {
- const healthResponse = await fetch(
- `http://localhost:${sessionInfo.port}/health`
- )
- if (!healthResponse.ok) {
- throw new Error('unhealthy')
- }
- } catch (_e) {
- throw new Error('Model appears to have crashed! Please reload!')
- }
-
- const baseUrl = `http://localhost:${sessionInfo.port}`
- const headers = {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${sessionInfo.api_key}`,
- }
-
- // Count image tokens first
let imageTokens = 0
const hasImages = opts.messages.some(
(msg) =>
@@ -2375,76 +2526,48 @@ export default class llamacpp_extension extends AIEngine {
)
if (hasImages) {
- logger.info('Conversation has images')
try {
- // Read mmproj metadata to get vision parameters
- logger.info(`MMPROJ PATH: ${sessionInfo.mmproj_path}`)
-
- const metadata = await readGgufMetadata(sessionInfo.mmproj_path)
- logger.info(`mmproj metadata: ${JSON.stringify(metadata.metadata)}`)
- imageTokens = await this.calculateImageTokens(
- opts.messages,
- metadata.metadata
- )
+ 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)
- // Fallback to a rough estimate if metadata reading fails
imageTokens = this.estimateImageTokensFallback(opts.messages)
}
}
- // Calculate text tokens
- // Use chat_template_kwargs from opts if provided, otherwise default to disable enable_thinking
- const tokenizeRequest = {
- messages: opts.messages,
- chat_template_kwargs: opts.chat_template_kwargs || {
- enable_thinking: false,
- },
- }
-
- try {
- let parseResponse = await fetch(`${baseUrl}/apply-template`, {
- method: 'POST',
- headers: headers,
- body: JSON.stringify(tokenizeRequest),
- })
-
- if (!parseResponse.ok) {
- const errorData = await parseResponse.json().catch(() => null)
- throw new Error(
- `API request failed with status ${
- parseResponse.status
- }: ${JSON.stringify(errorData)}`
- )
- }
-
- const parsedPrompt = await parseResponse.json()
-
- const response = await fetch(`${baseUrl}/tokenize`, {
- method: 'POST',
- headers: headers,
- body: JSON.stringify({
- content: parsedPrompt.prompt,
- }),
- })
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => null)
- throw new Error(
- `API request failed with status ${response.status}: ${JSON.stringify(
- errorData
- )}`
- )
+ 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 dataTokens = await response.json()
- const textTokens = dataTokens.tokens?.length || 0
-
- return textTokens + imageTokens
- } catch (e) {
- console.warn(String(e))
}
- return 0
+ const textTokens = Math.ceil(textChars / 4)
+ return textTokens + imageTokens
}
private async calculateImageTokens(
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
new file mode 100644
index 000000000..2af3c64af
--- /dev/null
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -0,0 +1,239 @@
+/**
+ * @file Generates the llama-server router preset INI from per-model `model.yml`
+ * files under `<providerPath>/models/<modelId>/model.yml`.
+ *
+ * Phase 2 keeps the preset minimal — model path, mmproj, chat-template,
+ * load-on-startup=false. A small `[*]` global section pulls a couple of
+ * conservative defaults from `LlamacppConfig`. Per-model setting fidelity
+ * is deferred to Phase 3.
+ */
+
+import { fs, joinPath } from '@janhq/core'
+import { invoke } from '@tauri-apps/api/core'
+import type { LlamacppConfig, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'
+
+// ModelConfig is intentionally widened — model.yml may carry extra fields like
+// `chat_template` that aren't yet in the strict typing.
+type ModelYaml = ModelConfig & {
+ chat_template?: string
+ ctx_size?: number
+ n_gpu_layers?: number
+ flash_attn?: string
+ cache_type_k?: string
+ cache_type_v?: string
+ parallel?: number
+ cont_batching?: boolean
+ pooling?: 'none' | 'mean' | 'cls' | 'last' | 'rank'
+ ubatch_size?: number
+ batch_size?: number
+}
+
+const DEFAULT_EMBEDDING_UBATCH = 2048
+
+function escapeIniValue(v: string): string {
+ // INI values for llama-server are read as strings; trim surrounding whitespace
+ // and strip stray newlines that would break parsing.
+ return String(v).replace(/[\r\n]+/g, ' ').trim()
+}
+
+/**
+ * Walks `<providerPath>/models/*` recursively for `model.yml` files and emits
+ * a router preset INI to `<providerPath>/router.preset.ini`. Returns the
+ * absolute path of the written file.
+ */
+export async function generatePreset(
+ providerPath: string,
+ janDataFolderPath: string,
+ config: LlamacppConfig
+): Promise<{ path: string; embeddingCount: number }> {
+ const modelsDir = await joinPath([providerPath, 'models'])
+
+ // Ensure the directory exists; an empty install is fine — we still emit a
+ // valid (mostly empty) preset so the router can start.
+ if (!(await fs.existsSync(modelsDir))) {
+ await fs.mkdir(modelsDir)
+ }
+
+ // DFS for any directory containing model.yml — mirrors the logic in
+ // index.ts:list() so nested model IDs (e.g. "huggingface/foo") work.
+ const modelEntries: { modelId: string; configPath: string }[] = []
+ const stack: string[] = [modelsDir]
+ while (stack.length > 0) {
+ const currentDir = stack.pop() as string
+ const modelConfigPath = await joinPath([currentDir, 'model.yml'])
+ if (await fs.existsSync(modelConfigPath)) {
+ // +1 to drop leading separator. NOTE: matches index.ts behavior; not
+ // Windows-`\\`-aware, same trade-off as the existing list() impl.
+ const modelId = currentDir.slice(modelsDir.length + 1)
+ if (modelId.length > 0) {
+ modelEntries.push({ modelId, configPath: modelConfigPath })
+ }
+ continue
+ }
+ let children: string[] = []
+ try {
+ children = await fs.readdirSync(currentDir)
+ } catch {
+ continue
+ }
+ for (const child of children) {
+ try {
+ const stat = await fs.fileStat(child)
+ if (stat?.isDirectory) stack.push(child)
+ } catch {
+ /* ignore unreadable entries */
+ }
+ }
+ }
+
+ modelEntries.sort((a, b) => a.modelId.localeCompare(b.modelId))
+
+ const lines: string[] = []
+
+ lines.push('[*]')
+ if (typeof config.fit === 'boolean') {
+ lines.push(`fit = ${config.fit ? 'on' : 'off'}`)
+ }
+ if (typeof config.fit_target === 'string' && config.fit_target.length > 0) {
+ lines.push(`fit-target = ${escapeIniValue(config.fit_target)}`)
+ }
+ const fitCtxNum =
+ typeof config.fit_ctx === 'number'
+ ? config.fit_ctx
+ : typeof config.fit_ctx === 'string' && config.fit_ctx.length > 0
+ ? Number(config.fit_ctx)
+ : NaN
+ if (Number.isFinite(fitCtxNum) && fitCtxNum > 0) {
+ lines.push(`fit-ctx = ${fitCtxNum}`)
+ }
+ if (typeof config.ctx_size === 'number' && config.ctx_size > 0) {
+ lines.push(`ctx-size = ${config.ctx_size}`)
+ }
+ if (typeof config.n_gpu_layers === 'number' && config.n_gpu_layers >= 0) {
+ lines.push(`n-gpu-layers = ${config.n_gpu_layers}`)
+ }
+ if (
+ typeof config.flash_attn === 'string' &&
+ (config.flash_attn === 'on' || config.flash_attn === 'off')
+ ) {
+ lines.push(`flash-attn = ${config.flash_attn}`)
+ }
+ if (typeof config.cache_type_k === 'string' && config.cache_type_k.length > 0) {
+ lines.push(`cache-type-k = ${escapeIniValue(config.cache_type_k)}`)
+ }
+ if (typeof config.cache_type_v === 'string' && config.cache_type_v.length > 0) {
+ lines.push(`cache-type-v = ${escapeIniValue(config.cache_type_v)}`)
+ }
+ if (typeof config.parallel === 'number' && config.parallel > 0) {
+ lines.push(`parallel = ${config.parallel}`)
+ }
+ if (typeof config.cont_batching === 'boolean') {
+ lines.push(`cont-batching = ${config.cont_batching}`)
+ }
+ lines.push('')
+
+ // ---------- per-model sections ----------
+ let embeddingCount = 0
+ for (const { modelId, configPath } of modelEntries) {
+ let mc: ModelYaml
+ try {
+ mc = await invoke<ModelYaml>('read_yaml', { path: configPath })
+ } catch {
+ // Skip unreadable model entries rather than aborting the whole preset.
+ continue
+ }
+
+ if (!mc?.model_path) continue
+
+ const modelAbs = await joinPath([janDataFolderPath, mc.model_path])
+
+ lines.push(`[${modelId}]`)
+ lines.push(`model = ${escapeIniValue(modelAbs)}`)
+
+ if (mc.mmproj_path) {
+ const mmprojAbs = await joinPath([janDataFolderPath, mc.mmproj_path])
+ lines.push(`mmproj = ${escapeIniValue(mmprojAbs)}`)
+ }
+
+ if (mc.chat_template && mc.chat_template.trim().length > 0) {
+ lines.push(`chat-template = ${escapeIniValue(mc.chat_template)}`)
+ }
+
+ if (typeof mc.ctx_size === 'number' && mc.ctx_size > 0) {
+ lines.push(`ctx-size = ${mc.ctx_size}`)
+ }
+ if (typeof mc.n_gpu_layers === 'number' && mc.n_gpu_layers >= 0) {
+ lines.push(`n-gpu-layers = ${mc.n_gpu_layers}`)
+ }
+ if (
+ typeof mc.flash_attn === 'string' &&
+ (mc.flash_attn === 'on' || mc.flash_attn === 'off')
+ ) {
+ lines.push(`flash-attn = ${mc.flash_attn}`)
+ }
+ if (typeof mc.cache_type_k === 'string' && mc.cache_type_k.length > 0) {
+ lines.push(`cache-type-k = ${escapeIniValue(mc.cache_type_k)}`)
+ }
+ if (typeof mc.cache_type_v === 'string' && mc.cache_type_v.length > 0) {
+ lines.push(`cache-type-v = ${escapeIniValue(mc.cache_type_v)}`)
+ }
+ if (typeof mc.parallel === 'number' && mc.parallel > 0) {
+ lines.push(`parallel = ${mc.parallel}`)
+ }
+ if (typeof mc.cont_batching === 'boolean') {
+ lines.push(`cont-batching = ${mc.cont_batching}`)
+ }
+
+ if (mc.embedding === true) {
+ embeddingCount++
+ lines.push('embeddings = true')
+ const pooling =
+ typeof mc.pooling === 'string' && mc.pooling.length > 0
+ ? mc.pooling
+ : 'mean'
+ lines.push(`pooling = ${escapeIniValue(pooling)}`)
+ const ubatch =
+ typeof mc.ubatch_size === 'number' && mc.ubatch_size > 0
+ ? mc.ubatch_size
+ : DEFAULT_EMBEDDING_UBATCH
+ const batch =
+ typeof mc.batch_size === 'number' && mc.batch_size >= ubatch
+ ? mc.batch_size
+ : ubatch
+ lines.push(`ubatch-size = ${ubatch}`)
+ lines.push(`batch-size = ${batch}`)
+ }
+
+ lines.push('load-on-startup = false')
+ lines.push('')
+ }
+
+ const outPath = await joinPath([providerPath, 'router.preset.ini'])
+ const tmpPath = await joinPath([providerPath, 'router.preset.ini.tmp'])
+ const body = lines.join('\n')
+
+ // Atomic write: tmp + rename. fs.mv overwrites on Tauri's side.
+ await fs.writeFileSync(tmpPath, body)
+ try {
+ // Best-effort cleanup of any prior file before rename — fs.mv may not
+ // overwrite on all platforms.
+ if (await fs.existsSync(outPath)) {
+ try {
+ await fs.rm(outPath)
+ } catch {
+ /* ignore */
+ }
+ }
+ await fs.mv(tmpPath, outPath)
+ } catch {
+ // Fallback: if rename fails, write directly to the target.
+ await fs.writeFileSync(outPath, body)
+ try {
+ await fs.rm(tmpPath)
+ } catch {
+ /* ignore */
+ }
+ }
+
+ return { path: outPath, embeddingCount }
+}
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index d8148fde4..00bd37214 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -25,6 +25,13 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {
...actual,
mapOldBackendToNew: vi.fn(),
removeOldBackendVersions: vi.fn(),
+ readGgufMetadata: vi.fn().mockResolvedValue({
+ version: 3,
+ tensor_count: 1,
+ metadata: { 'general.architecture': 'llama' },
+ }),
+ loadLlamaModel: vi.fn(),
+ unloadLlamaModel: vi.fn(),
}
})
describe('llamacpp_extension', () => {
@@ -43,7 +50,9 @@ describe('llamacpp_extension', () => {
it('should initialize with correct default values', () => {
expect(extension.provider).toBe('llamacpp')
expect(extension.providerId).toBe('llamacpp')
- expect(extension.autoUnload).toBe(true)
+ // autoUnload was removed in Phase 2 — replaced by `models_max` setting
+ // applied at router start time.
+ expect(extension.timeout).toBe(600)
})
})
@@ -116,12 +125,15 @@ describe('llamacpp_extension', () => {
// instead of the full path, causing the model ID to be empty
expect(result).toEqual([
{
- id: '', // This should be 'test-model' but the original code has a bug
+ id: '',
name: 'Test Model',
quant_type: undefined,
providerId: 'llamacpp',
port: 0,
- sizeBytes: 1000000
+ sizeBytes: 1000000,
+ embedding: false,
+ imported: false,
+ capabilities: undefined,
}
])
})
@@ -147,6 +159,12 @@ describe('llamacpp_extension', () => {
it('should import model from URL', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
const { invoke } = await import('@tauri-apps/api/core')
+ const apiModule = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(apiModule.readGgufMetadata).mockResolvedValue({
+ version: 3,
+ tensor_count: 1,
+ metadata: { 'general.architecture': 'llama' },
+ } as any)
const mockDownloadManager = {
downloadFiles: vi.fn().mockResolvedValue(undefined)
@@ -173,12 +191,17 @@ describe('llamacpp_extension', () => {
describe('load', () => {
it('should throw error if model is already loaded', async () => {
- // Mock that model is already loaded
- extension['activeSessions'].set(123, {
- model_id: 'test-model',
- pid: 123,
- port: 3000,
- api_key: 'test-key'
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|find_session_by_model') {
+ return {
+ model_id: 'test-model',
+ pid: 123,
+ port: 3000,
+ api_key: 'test-key',
+ }
+ }
+ return undefined
})
await expect(extension.load('test-model')).rejects.toThrow('Model already loaded!!')
@@ -187,21 +210,13 @@ describe('llamacpp_extension', () => {
it('should load model successfully', async () => {
const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')
const { invoke } = await import('@tauri-apps/api/core')
-
- // Mock system info for getBackendExePath
- const getSystemInfo = vi.fn().mockResolvedValue({
- os_type: 'linux'
- })
-
- // Mock backend functions to avoid download
+
const backendModule = await import('../backend')
vi.mocked(backendModule.isBackendInstalled).mockResolvedValue(true)
vi.mocked(backendModule.getBackendExePath).mockResolvedValue('/path/to/backend/executable')
-
- // Mock fs for backend check
+
vi.mocked(fs.existsSync).mockResolvedValue(true)
-
- // Mock configuration
+
extension['config'] = {
version_backend: 'v1.0.0/win-avx2-x64',
ctx_size: 2048,
@@ -237,80 +252,92 @@ describe('llamacpp_extension', () => {
vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')
vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))
-
- // Mock model config
- vi.mocked(invoke)
- .mockResolvedValueOnce({ // read_yaml
- model_path: 'test-model/model.gguf',
- name: 'Test Model',
- size_bytes: 1000000
- })
- .mockResolvedValueOnce('test-api-key') // generate_api_key
- .mockResolvedValueOnce({ // load_llama_model
- model_id: 'test-model',
- pid: 123,
- port: 3000,
- api_key: 'test-api-key'
- })
- // Mock successful health check
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: vi.fn().mockResolvedValue({ status: 'ok' })
- })
-
- const result = await extension.load('test-model')
-
- expect(result).toEqual({
+ const expectedSession = {
model_id: 'test-model',
pid: 123,
port: 3000,
- api_key: 'test-api-key'
+ api_key: 'test-api-key',
+ }
+
+ const apiModule = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(apiModule.loadLlamaModel).mockResolvedValue(expectedSession as any)
+
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ switch (cmd) {
+ case 'plugin:llamacpp|find_session_by_model':
+ return null
+ case 'plugin:llamacpp|get_router_info':
+ return { port: 4000, api_key: 'router-key', pid: 999 }
+ case 'plugin:llamacpp|load_llama_model':
+ return expectedSession
+ default:
+ return undefined
+ }
})
-
- expect(extension['activeSessions'].get(123)).toEqual({
- model_id: 'test-model',
- pid: 123,
- port: 3000,
- api_key: 'test-api-key'
+
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'ok' }),
})
+
+ const result = await extension.load('test-model')
+
+ expect(result).toEqual(expectedSession)
})
})
describe('unload', () => {
it('should throw error if no active session found', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|find_session_by_model') {
+ throw new Error('No active session found')
+ }
+ return undefined
+ })
await expect(extension.unload('nonexistent-model')).rejects.toThrow('No active session found')
})
it('should unload model successfully', async () => {
const { invoke } = await import('@tauri-apps/api/core')
-
- // Set up active session
- extension['activeSessions'].set(123, {
- model_id: 'test-model',
- pid: 123,
- port: 3000,
- api_key: 'test-key'
+ const apiModule = await import('@janhq/tauri-plugin-llamacpp-api')
+
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|find_session_by_model') {
+ return {
+ model_id: 'test-model',
+ pid: 123,
+ port: 3000,
+ api_key: 'test-key',
+ }
+ }
+ return undefined
})
-
- vi.mocked(invoke).mockResolvedValue({
+ vi.mocked(apiModule.unloadLlamaModel).mockResolvedValue({
success: true,
- error: null
- })
+ error: null,
+ } as any)
const result = await extension.unload('test-model')
-
+
expect(result).toEqual({
success: true,
- error: null
+ error: null,
})
-
- expect(extension['activeSessions'].has(123)).toBe(false)
})
})
describe('chat', () => {
it('should throw error if no active session found', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|ensure_session_ready') {
+ throw new Error('No active session found')
+ }
+ return undefined
+ })
+
const request = {
model: 'nonexistent-model',
messages: [{ role: 'user', content: 'Hello' }]
@@ -321,16 +348,18 @@ describe('llamacpp_extension', () => {
it('should handle non-streaming chat request', async () => {
const { invoke } = await import('@tauri-apps/api/core')
-
- // Set up active session
- extension['activeSessions'].set(123, {
- model_id: 'test-model',
- pid: 123,
- port: 3000,
- api_key: 'test-key'
- })
- vi.mocked(invoke).mockResolvedValue(true) // is_process_running
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|ensure_session_ready') {
+ return {
+ model_id: 'test-model',
+ pid: 123,
+ port: 3000,
+ api_key: 'test-key',
+ }
+ }
+ return true
+ })
const mockResponse = {
id: 'test-id',
@@ -548,22 +577,16 @@ describe('llamacpp_extension', () => {
describe('getLoadedModels', () => {
it('should return list of loaded models', async () => {
- extension['activeSessions'].set(123, {
- model_id: 'model1',
- pid: 123,
- port: 3000,
- api_key: 'key1'
- })
-
- extension['activeSessions'].set(456, {
- model_id: 'model2',
- pid: 456,
- port: 3001,
- api_key: 'key2'
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|get_loaded_models') {
+ return ['model1', 'model2']
+ }
+ return undefined
})
const result = await extension.getLoadedModels()
-
+
expect(result).toEqual(['model1', 'model2'])
})
})
diff --git a/extensions/llamacpp-extension/src/test/setup.ts b/extensions/llamacpp-extension/src/test/setup.ts
index 464491dc2..8a113a7f1 100644
--- a/extensions/llamacpp-extension/src/test/setup.ts
+++ b/extensions/llamacpp-extension/src/test/setup.ts
@@ -40,6 +40,19 @@ vi.mock('@tauri-apps/api/core', () => ({
invoke: vi.fn(),
}))
+vi.mock('@tauri-apps/plugin-log', () => ({
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ debug: vi.fn(),
+ trace: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn().mockResolvedValue(() => undefined),
+ emit: vi.fn(),
+}))
+
// Mock Tauri path API
vi.mock('@tauri-apps/api/path', () => ({
basename: vi.fn(),
@@ -69,5 +82,15 @@ vi.mock('@janhq/core', () => ({
events: {
emit: vi.fn(),
},
+ AppEvent: {
+ onModelImported: 'onModelImported',
+ onBackendVerificationFailed: 'onBackendVerificationFailed',
+ },
+ DownloadEvent: {
+ onFileDownloadUpdate: 'onFileDownloadUpdate',
+ onFileDownloadStopped: 'onFileDownloadStopped',
+ onModelValidationStarted: 'onModelValidationStarted',
+ onModelValidationFailed: 'onModelValidationFailed',
+ },
AIEngine: vi.fn(),
}))
\ No newline at end of file
diff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.ts
index 5286eb250..05bb0d175 100644
--- a/extensions/llamacpp-extension/src/util.test.ts
+++ b/extensions/llamacpp-extension/src/util.test.ts
@@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { getProxyConfig } from './util'
+import {
+ buildEmbedBatches,
+ estimateTokensFromText,
+ getProxyConfig,
+ truncateToTokenBudget,
+} from './util'
// Mock console.log and console.error to avoid noise in tests
const mockConsole = {
@@ -524,3 +529,52 @@ describe('getProxyConfig', () => {
})
})
})
+
+describe('truncateToTokenBudget', () => {
+ it('returns input unchanged when under the budget', () => {
+ expect(truncateToTokenBudget('hello world', 100, 3)).toBe('hello world')
+ })
+
+ it('slices to maxTokens * charsPerToken when over the budget', () => {
+ const long = 'a'.repeat(1000)
+ const out = truncateToTokenBudget(long, 10, 3)
+ expect(out.length).toBe(30)
+ })
+})
+
+describe('buildEmbedBatches', () => {
+ it('packs small inputs into a single batch', () => {
+ const batches = buildEmbedBatches(['hi', 'there'], 512, 3)
+ expect(batches).toHaveLength(1)
+ expect(batches[0]).toEqual({ batch: ['hi', 'there'], offset: 0 })
+ })
+
+ it('splits inputs across batches when token budget is exceeded', () => {
+ const oneSafeChunk = 'a'.repeat(3 * 200)
+ const batches = buildEmbedBatches(
+ [oneSafeChunk, oneSafeChunk, oneSafeChunk],
+ 512,
+ 3
+ )
+ expect(batches.length).toBeGreaterThanOrEqual(2)
+ const flat = batches.flatMap((b) => b.batch)
+ expect(flat).toHaveLength(3)
+ const offsets = batches.map((b) => b.offset)
+ expect(offsets).toEqual([...offsets].sort((a, b) => a - b))
+ })
+
+ it('truncates oversize inputs instead of forwarding them whole', () => {
+ const huge = 'x'.repeat(20000)
+ const batches = buildEmbedBatches([huge], 512, 3)
+ expect(batches).toHaveLength(1)
+ const sent = batches[0].batch[0]
+ expect(sent.length).toBeLessThan(huge.length)
+ expect(estimateTokensFromText(sent, 3)).toBeLessThanOrEqual(
+ Math.floor(512 * 0.5)
+ )
+ })
+
+ it('throws on ubatch_size too small to satisfy the safety margin', () => {
+ expect(() => buildEmbedBatches(['hi'], 1, 3)).toThrow(/too small/)
+ })
+})
diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.ts
index 006a77812..0f4ea79da 100644
--- a/extensions/llamacpp-extension/src/util.ts
+++ b/extensions/llamacpp-extension/src/util.ts
@@ -32,6 +32,36 @@ interface ProxyState {
noProxy: string
}
+export function getDefaultEmbeddingModelId(
+ provider: string = 'llamacpp'
+): string | undefined {
+ try {
+ const raw = localStorage.getItem('default-embedding-model')
+ if (!raw) return undefined
+ const parsed = JSON.parse(raw)
+ const map = parsed?.state?.defaultByProvider
+ const id = map && map[provider]
+ return typeof id === 'string' && id.length > 0 ? id : undefined
+ } catch {
+ return undefined
+ }
+}
+
+export function setDefaultEmbeddingModelId(provider: string, modelId: string) {
+ try {
+ const raw = localStorage.getItem('default-embedding-model')
+ const parsed = raw ? JSON.parse(raw) : { state: {}, version: 0 }
+ const state = parsed.state ?? {}
+ const map = state.defaultByProvider ?? {}
+ map[provider] = modelId
+ parsed.state = { ...state, defaultByProvider: map }
+ if (parsed.version === undefined) parsed.version = 0
+ localStorage.setItem('default-embedding-model', JSON.stringify(parsed))
+ } catch {
+ /* localStorage write failed; non-fatal */
+ }
+}
+
export function getProxyConfig(): Record<
string,
string | string[] | boolean
@@ -122,16 +152,59 @@ export type EmbedBatchResult = {
const DEFAULT_CHARS_PER_TOKEN = 3
const UBATCH_SAFETY_MARGIN = 0.5
+export const EMBEDDING_GGUF_ARCHS = new Set([
+ 'bert',
+ 'nomic-bert',
+ 'nomic-bert-moe',
+ 'jina-bert-v2',
+ 'jina-bert-v3',
+ 'xlm-roberta',
+ 'mpnet',
+ 't5encoder',
+])
+
+export function isEmbeddingArchitecture(arch: unknown): boolean {
+ return typeof arch === 'string' && EMBEDDING_GGUF_ARCHS.has(arch)
+}
+
+export function detectEmbeddingFromGgufMeta(
+ meta: Record<string, unknown> | undefined
+): boolean {
+ if (!meta) return false
+ const arch = meta['general.architecture']
+ if (typeof arch !== 'string') return false
+ if (EMBEDDING_GGUF_ARCHS.has(arch)) return true
+ if (arch.toLowerCase().includes('embed')) return true
+ const raw = meta[`${arch}.pooling_type`]
+ const n =
+ typeof raw === 'number'
+ ? raw
+ : typeof raw === 'string' && raw.length > 0
+ ? Number(raw)
+ : NaN
+ return Number.isFinite(n) && n > 0
+}
+
export function estimateTokensFromText(text: string, charsPerToken = DEFAULT_CHARS_PER_TOKEN): number {
return Math.max(1, Math.ceil(text.length / Math.max(charsPerToken, 1)))
}
+export function truncateToTokenBudget(
+ text: string,
+ maxTokens: number,
+ charsPerToken = DEFAULT_CHARS_PER_TOKEN
+): string {
+ const cpt = Math.max(charsPerToken, 1)
+ const maxChars = Math.max(1, maxTokens) * cpt
+ if (text.length <= maxChars) return text
+ return text.slice(0, maxChars)
+}
+
export function buildEmbedBatches(
inputs: string[],
ubatchSize: number,
charsPerToken = DEFAULT_CHARS_PER_TOKEN
): EmbedBatch[] {
- // Ensure ubatch_size is large enough for at least 1 token with safety margin
const minUbatchSize = Math.ceil(1 / UBATCH_SAFETY_MARGIN)
if (ubatchSize < minUbatchSize) {
throw new Error(
@@ -155,18 +228,13 @@ export function buildEmbedBatches(
}
}
- for (const text of inputs) {
+ for (const raw of inputs) {
+ const text =
+ estimateTokensFromText(raw, charsPerToken) > safeLimit
+ ? truncateToTokenBudget(raw, safeLimit, charsPerToken)
+ : raw
const estTokens = estimateTokensFromText(text, charsPerToken)
- // If single text exceeds safe limit, still allow it as single batch
- // (ensure at least one text per batch)
- if (estTokens > safeLimit) {
- if (current.length) push()
- batches.push({ batch: [text], offset })
- offset += 1
- continue
- }
-
if (currentTokens + estTokens > safeLimit && current.length) {
push()
}
@@ -177,7 +245,6 @@ export function buildEmbedBatches(
push()
- // Validate that no batch is empty
if (batches.some(b => b.batch.length === 0)) {
throw new Error('Internal error: empty batch detected')
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 23d7b2908..3a653e893 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -4,6 +4,10 @@ const COMMANDS: &[&str] = &[
// LlamaCpp server commands
"load_llama_model",
"unload_llama_model",
+ // Router-mode commands (Phase 1)
+ "start_router",
+ "stop_router",
+ "get_router_info",
"get_devices",
"generate_api_key",
"is_process_running",
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 13a48e3d9..177167154 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -46,7 +46,10 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {
version_backend: asString(config.version_backend),
auto_update_engine: asBool(config.auto_update_engine),
auto_unload: asBool(config.auto_unload),
- auto_restart_on_crash: asBool(config.auto_restart_on_crash),
+ models_max:
+ typeof config.models_max === 'number'
+ ? config.models_max
+ : asI32(config.models_max, 1),
timeout: asI32(config.timeout, 600),
llamacpp_env: asString(config.llamacpp_env),
@@ -101,34 +104,28 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {
}
}
-// LlamaCpp server commands
export async function loadLlamaModel(
- backendPath: string,
modelId: string,
- modelPath: string,
- port: number,
- cfg: LlamacppConfig,
- envs: Record<string, string>,
- mmprojPath?: string,
- isEmbedding: boolean = false,
- timeout: number = 600
+ isEmbedding: boolean = false
): Promise<SessionInfo> {
- const config = normalizeLlamacppConfig(cfg)
return await invoke('plugin:llamacpp|load_llama_model', {
- backendPath,
modelId,
- modelPath,
- port,
- config,
- envs,
- mmprojPath,
isEmbedding,
- timeout,
})
}
-export async function unloadLlamaModel(pid: number): Promise<UnloadResult> {
- return await invoke('plugin:llamacpp|unload_llama_model', { pid })
+export async function unloadLlamaModel(modelId: string): Promise<UnloadResult> {
+ return await invoke('plugin:llamacpp|unload_llama_model', { modelId })
+}
+
+export async function ensureSessionReady(
+ modelId: string,
+ isEmbedding: boolean = false
+): Promise<SessionInfo> {
+ return await invoke('plugin:llamacpp|ensure_session_ready', {
+ modelId,
+ isEmbedding,
+ })
}
export async function getDevices(
@@ -151,14 +148,6 @@ export async function generateApiKey(
})
}
-export async function isProcessRunning(pid: number): Promise<boolean> {
- return await invoke('plugin:llamacpp|is_process_running', { pid })
-}
-
-export async function getRandomPort(): Promise<number> {
- return await invoke('plugin:llamacpp|get_random_port')
-}
-
export async function findSessionByModel(
modelId: string
): Promise<SessionInfo | null> {
@@ -169,16 +158,6 @@ export async function getLoadedModels(): Promise<string[]> {
return await invoke('plugin:llamacpp|get_loaded_models')
}
-export async function getAllSessions(): Promise<SessionInfo[]> {
- return await invoke('plugin:llamacpp|get_all_sessions')
-}
-
-export async function getSessionByModel(
- modelId: string
-): Promise<SessionInfo | null> {
- return await invoke('plugin:llamacpp|get_session_by_model', { modelId })
-}
-
// GGUF commands
export async function readGgufMetadata(path: string): Promise<GgufMetadata> {
return await invoke('plugin:llamacpp|read_gguf_metadata', { path })
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 f058f97d0..56c9f4659 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -3,10 +3,8 @@ export interface SessionInfo {
pid: number
port: number
model_id: string
- model_path: string
is_embedding: boolean
api_key: string
- mmproj_path?: string
}
export interface UnloadResult {
@@ -20,6 +18,13 @@ export interface DeviceInfo {
memory: number
}
+export interface ModelProps {
+ nCtx: number
+ totalSlots?: number
+ modelAlias?: string
+ isSleeping?: boolean
+}
+
export interface GgufMetadata {
version: number
tensor_count: number
@@ -31,7 +36,7 @@ export type LlamacppConfig = {
version_backend: string
auto_update_engine: boolean
auto_unload: boolean
- auto_restart_on_crash: boolean
+ models_max: string | number
timeout: number
llamacpp_env: string
fit: boolean
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
index 09ee44ede..884f5f421 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -7,6 +7,9 @@ Default permissions for the llamacpp plugin
- `allow-cleanup-llama-processes`
- `allow-load-llama-model`
- `allow-unload-llama-model`
+- `allow-start-router`
+- `allow-stop-router`
+- `allow-get-router-info`
- `allow-get-devices`
- `allow-generate-api-key`
- `allow-is-process-running`
@@ -548,6 +551,32 @@ Denies the get_random_port command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-get-router-info`
+
+</td>
+<td>
+
+Enables the get_router_info command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-get-router-info`
+
+</td>
+<td>
+
+Denies the get_router_info command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-get-session-by-model`
</td>
@@ -1146,6 +1175,58 @@ Denies the should_migrate_backend command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-start-router`
+
+</td>
+<td>
+
+Enables the start_router command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-start-router`
+
+</td>
+<td>
+
+Denies the start_router command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:allow-stop-router`
+
+</td>
+<td>
+
+Enables the stop_router command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-stop-router`
+
+</td>
+<td>
+
+Denies the stop_router command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-unload-llama-model`
</td>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
index 3be448c8a..883ec5d09 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -7,6 +7,9 @@ permissions = [
# LlamaCpp server commands
"allow-load-llama-model",
"allow-unload-llama-model",
+ "allow-start-router",
+ "allow-stop-router",
+ "allow-get-router-info",
"allow-get-devices",
"allow-generate-api-key",
"allow-is-process-running",
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
index e3f7c6c01..659d82e4f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -522,6 +522,18 @@
"const": "deny-get-random-port",
"markdownDescription": "Denies the get_random_port command without any pre-configured scope."
},
+ {
+ "description": "Enables the get_router_info command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-router-info",
+ "markdownDescription": "Enables the get_router_info command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_router_info command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-router-info",
+ "markdownDescription": "Denies the get_router_info command without any pre-configured scope."
+ },
{
"description": "Enables the get_session_by_model command without any pre-configured scope.",
"type": "string",
@@ -798,6 +810,30 @@
"const": "deny-should-migrate-backend",
"markdownDescription": "Denies the should_migrate_backend command without any pre-configured scope."
},
+ {
+ "description": "Enables the start_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-router",
+ "markdownDescription": "Enables the start_router command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-router",
+ "markdownDescription": "Denies the start_router command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-router",
+ "markdownDescription": "Enables the stop_router command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-router",
+ "markdownDescription": "Denies the stop_router command without any pre-configured scope."
+ },
{
"description": "Enables the unload_llama_model command without any pre-configured scope.",
"type": "string",
@@ -835,10 +871,10 @@
"markdownDescription": "Denies the verify_backend_installation command without any pre-configured scope."
},
{
- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`",
+ "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-get-router-info`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`"
+ "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-get-router-info`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-plan-model-load`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs
deleted file mode 100644
index d1b03f34c..000000000
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs
+++ /dev/null
@@ -1,1380 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-fn default_parallel() -> i32 {
- 1
- }
-fn default_reasoning() -> String {
- "auto".to_string()
-}
-fn default_cache_ram() -> i32 {
- -1
-}
-fn default_cache_reuse() -> i32 {
- 0
-}
-fn default_keep() -> i32 {
- 0
-}
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct LlamacppConfig {
- pub version_backend: String,
- pub auto_update_engine: bool,
- pub auto_unload: bool,
- #[serde(default)]
- pub auto_restart_on_crash: bool,
- pub timeout: i32,
- pub llamacpp_env: String,
- pub fit: bool,
- pub fit_target: String,
- pub fit_ctx: String,
- pub chat_template: String,
- pub n_gpu_layers: i32,
- pub offload_mmproj: bool,
- pub cpu_moe: bool,
- pub n_cpu_moe: i32,
- pub override_tensor_buffer_t: String,
- pub ctx_size: i32,
- pub threads: i32,
- pub threads_batch: i32,
- pub n_predict: i32,
- pub batch_size: i32,
- pub ubatch_size: i32,
- pub device: String,
- pub split_mode: String,
- pub main_gpu: i32,
- pub flash_attn: String,
- pub cont_batching: bool,
- pub no_mmap: bool,
- pub mlock: bool,
- pub no_kv_offload: bool,
- pub cache_type_k: String,
- pub cache_type_v: String,
- pub defrag_thold: f32,
- pub rope_scaling: String,
- pub rope_scale: f32,
- pub rope_freq_base: f32,
- pub rope_freq_scale: f32,
- pub ctx_shift: bool,
- #[serde(default = "default_parallel")]
- pub parallel: i32,
- #[serde(default = "default_reasoning")]
- pub reasoning: String,
- #[serde(default = "default_cache_ram")]
- pub cache_ram: i32,
- #[serde(default = "default_cache_reuse")]
- pub cache_reuse: i32,
- #[serde(default)]
- pub swa_full: bool,
- #[serde(default = "default_keep")]
- pub keep: i32,
-}
-
-/// Minimum llama.cpp build number that changed --flash-attn from a boolean
-/// flag to a string argument accepting auto|on|off (upstream PR #15434).
-const FLASH_ATTN_STRING_ARG_MIN_BUILD: u32 = 6325;
-
-pub struct ArgumentBuilder {
- args: Vec<String>,
- config: LlamacppConfig,
- version: String,
- backend: String,
- is_embedding: bool,
-}
-
-impl ArgumentBuilder {
- pub fn new(config: LlamacppConfig, is_embedding: bool) -> Result<Self, String> {
- let mut parts = config.version_backend.splitn(2, '/');
- let version = parts
- .next()
- .ok_or("Invalid version_backend format")?
- .to_string();
- let backend = parts
- .next()
- .ok_or("Invalid version_backend format")?
- .to_string();
-
- Ok(Self {
- args: Vec::new(),
- config,
- version,
- backend,
- is_embedding,
- })
- }
-
- /// Parse the build number from a version string like "b6325".
- /// Returns `None` if the format doesn't match.
- fn parse_build_number(&self) -> Option<u32> {
- self.version
- .strip_prefix('b')
- .and_then(|s| s.parse::<u32>().ok())
- }
-
- /// Build all arguments based on configuration
- pub fn build(
- mut self,
- model_id: &str,
- model_path: &str,
- port: u16,
- mmproj_path: Option<String>,
- ) -> Vec<String> {
- // Disable llama-server webui for non-ik backends
- if !self.backend.starts_with("ik") {
- self.args.push("--no-webui".to_string());
- }
-
- self.args.push("--jinja".to_string());
-
- match self.config.reasoning.as_str() {
- "on" | "off" => {
- self.args.push("--reasoning".to_string());
- self.args.push(self.config.reasoning.clone());
- }
- _ => {}
- }
-
- if self.config.cache_ram >= 0 {
- self.args.push("--cache-ram".to_string());
- self.args.push(self.config.cache_ram.to_string());
- }
-
- if self.config.cache_reuse > 0 {
- self.args.push("--cache-reuse".to_string());
- self.args.push(self.config.cache_reuse.to_string());
- }
-
- if self.config.swa_full {
- self.args.push("--swa-full".to_string());
- }
-
- if self.config.keep != 0 {
- self.args.push("--keep".to_string());
- self.args.push(self.config.keep.to_string());
- }
-
- // Model path (required)
- self.args.push("-m".to_string());
- self.args.push(model_path.to_string());
-
- // CPU MOE settings
- self.add_cpu_moe_args();
-
- // Tensor buffer override
- self.add_tensor_buffer_override();
-
- // Multimodal projector settings
- self.add_mmproj_args(mmproj_path);
-
- // Model alias and port
- self.args.push("-a".to_string());
- self.args.push(model_id.to_string());
- self.args.push("--port".to_string());
- self.args.push(port.to_string());
-
- // Chat template
- self.add_chat_template();
-
- // GPU layers
- self.add_gpu_layers();
-
- // Thread settings
- self.add_thread_settings();
-
- // Batch settings
- self.add_batch_settings();
-
- // Device and split mode
- self.add_device_settings();
-
- // Flash attention
- self.add_flash_attention();
-
- // Boolean flags
- self.add_boolean_flags();
-
- // Parallel sequences
- self.add_parallel_settings();
-
- // Embedding vs text generation specific args
- if self.is_embedding {
- self.add_embedding_args();
- } else {
- self.add_text_generation_args();
- }
- // llama fit
- // forks like ik is not supported
- if !self.backend.starts_with("ik") {
- self.add_fit_settings();
- }
-
- self.args
- }
-
- fn add_cpu_moe_args(&mut self) {
- if self.config.cpu_moe {
- self.args.push("--cpu-moe".to_string());
- }
-
- if self.config.n_cpu_moe > 0 {
- self.args.push("--n-cpu-moe".to_string());
- self.args.push(self.config.n_cpu_moe.to_string());
- }
- }
-
- fn add_tensor_buffer_override(&mut self) {
- if !self.config.override_tensor_buffer_t.is_empty() {
- self.args.push("--override-tensor".to_string());
- self.args.push(self.config.override_tensor_buffer_t.clone());
- }
- }
-
- fn add_mmproj_args(&mut self, mmproj_path: Option<String>) {
- if let Some(path) = mmproj_path.filter(|p| !p.is_empty()) {
- self.args.push("--mmproj".to_string());
- self.args.push(path);
-
- if !self.config.offload_mmproj {
- self.args.push("--no-mmproj-offload".to_string());
- }
- }
- }
-
- fn add_chat_template(&mut self) {
- if !self.config.chat_template.is_empty() {
- self.args.push("--chat-template".to_string());
- self.args.push(self.config.chat_template.clone());
- }
- }
-
- fn add_gpu_layers(&mut self) {
- let gpu_layers = if self.config.n_gpu_layers >= 0 && self.config.n_gpu_layers != 100 {
- // 100 means load all layers
- self.config.n_gpu_layers
- } else {
- -1
- };
- self.args.push("-ngl".to_string());
- self.args.push(gpu_layers.to_string());
- }
-
- fn add_thread_settings(&mut self) {
- if self.config.threads > 0 {
- self.args.push("--threads".to_string());
- self.args.push(self.config.threads.to_string());
- }
-
- if self.config.threads_batch > 0 {
- self.args.push("--threads-batch".to_string());
- self.args.push(self.config.threads_batch.to_string());
- }
- }
-
- fn add_batch_settings(&mut self) {
- if self.config.batch_size > 0 && self.config.batch_size != 2048 {
- self.args.push("--batch-size".to_string());
- self.args.push(self.config.batch_size.to_string());
- }
-
- if self.config.ubatch_size > 0 && self.config.ubatch_size != 512 {
- self.args.push("--ubatch-size".to_string());
- self.args.push(self.config.ubatch_size.to_string());
- }
- }
-
- fn add_device_settings(&mut self) {
- if !self.config.device.is_empty() {
- self.args.push("--device".to_string());
- self.args.push(self.config.device.clone());
- }
-
- if !self.config.split_mode.is_empty() && self.config.split_mode != "layer" {
- self.args.push("--split-mode".to_string());
- self.args.push(self.config.split_mode.clone());
- }
-
- if self.config.main_gpu != 0 {
- self.args.push("--main-gpu".to_string());
- self.args.push(self.config.main_gpu.to_string());
- }
- }
-
- fn add_flash_attention(&mut self) {
- if self.backend.starts_with("ik") {
- // ik fork uses old -fa flag
- if self.config.flash_attn == "on" {
- self.args.push("-fa".to_string());
- }
- return;
- }
-
- let supports_string_arg = self
- .parse_build_number()
- .is_some_and(|b| b >= FLASH_ATTN_STRING_ARG_MIN_BUILD);
-
- if supports_string_arg {
- // b6325+: --flash-attn accepts auto|on|off as a value
- match self.config.flash_attn.as_str() {
- "auto" | "on" | "off" => {
- self.args.push("--flash-attn".to_string());
- self.args.push(self.config.flash_attn.clone());
- }
- _ => {} // unknown value → don't pass
- }
- } else {
- // Older versions: --flash-attn is a boolean flag (no value)
- if self.config.flash_attn == "on" {
- self.args.push("--flash-attn".to_string());
- }
- // "auto" and "off" → don't pass --flash-attn
- }
- }
-
- fn add_boolean_flags(&mut self) {
- if self.config.ctx_shift {
- self.args.push("--context-shift".to_string());
- }
-
- if self.config.cont_batching {
- self.args.push("--cont-batching".to_string());
- }
-
- if self.config.no_mmap {
- self.args.push("--no-mmap".to_string());
- }
-
- if self.config.mlock {
- self.args.push("--mlock".to_string());
- }
-
- if self.config.no_kv_offload {
- self.args.push("--no-kv-offload".to_string());
- }
- }
-
- fn add_parallel_settings(&mut self) {
- if self.config.parallel > 0 {
- self.args.push("--parallel".to_string());
- self.args.push(self.config.parallel.to_string());
- if self.config.parallel == 1 {
- // https://github.com/ggml-org/llama.cpp/issues/17450
- self.args.push("-kvu".to_string());
- }
- }
- }
-
- fn add_embedding_args(&mut self) {
- self.args.push("--embedding".to_string());
- self.args.push("--pooling".to_string());
- self.args.push("mean".to_string());
- }
-
- fn add_text_generation_args(&mut self) {
- // With fit on, llama.cpp's fit code handles sizing. With fit off and
- // no --ctx-size, it would load at n_ctx_train and OOM on small GPUs;
- // fall back to 4096.
- if !self.config.fit {
- let ctx = if self.config.ctx_size > 0 {
- self.config.ctx_size
- } else {
- 4096
- };
- self.args.push("--ctx-size".to_string());
- self.args.push(ctx.to_string());
- }
-
- if self.config.n_predict > 0 {
- self.args.push("--n-predict".to_string());
- self.args.push(self.config.n_predict.to_string());
- }
-
- if !self.config.cache_type_k.is_empty() && self.config.cache_type_k != "f16" {
- self.args.push("--cache-type-k".to_string());
- self.args.push(self.config.cache_type_k.clone());
- }
-
- // cache_type_v only if flash_attn is not 'off' and value is not f16/f32
- // cache_type_v needs divisibility check but since users want to tinker around it, should allow them to do so
- if self.config.flash_attn != "off"
- && !self.config.cache_type_v.is_empty()
- && self.config.cache_type_v != "f16"
- && self.config.cache_type_v != "f32"
- {
- self.args.push("--cache-type-v".to_string());
- self.args.push(self.config.cache_type_v.clone());
- }
-
- if (self.config.defrag_thold - 0.1).abs() > f32::EPSILON {
- self.args.push("--defrag-thold".to_string());
- self.args.push(self.config.defrag_thold.to_string());
- }
-
- self.add_rope_settings();
- }
-
- fn add_rope_settings(&mut self) {
- if !self.config.rope_scaling.is_empty() && self.config.rope_scaling != "none" {
- self.args.push("--rope-scaling".to_string());
- self.args.push(self.config.rope_scaling.clone());
- }
-
- if (self.config.rope_scale - 1.0).abs() > f32::EPSILON {
- self.args.push("--rope-scale".to_string());
- self.args.push(self.config.rope_scale.to_string());
- }
-
- if self.config.rope_freq_base != 0.0 {
- self.args.push("--rope-freq-base".to_string());
- self.args.push(self.config.rope_freq_base.to_string());
- }
-
- if (self.config.rope_freq_scale - 1.0).abs() > f32::EPSILON {
- self.args.push("--rope-freq-scale".to_string());
- self.args.push(self.config.rope_freq_scale.to_string());
- }
- }
-
- fn add_fit_settings(&mut self) {
- // Handle fit on/off
- if !self.config.fit {
- self.args.push("--fit".to_string());
- self.args.push("off".to_string());
- } else if self.config.fit {
- self.args.push("--fit".to_string());
- self.args.push("on".to_string());
- }
- if self.config.fit {
- if !self.config.fit_ctx.is_empty() && self.config.fit_ctx != "4096" {
- self.args.push("--fit-ctx".to_string());
- self.args.push(self.config.fit_ctx.clone());
- }
-
- if !self.config.fit_target.is_empty() && self.config.fit_target != "1024" {
- self.args.push("--fit-target".to_string());
- self.args.push(self.config.fit_target.clone());
- }
- }
- }
-}
-// -- Tests
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn default_config() -> LlamacppConfig {
- LlamacppConfig {
- version_backend: "v1.0/standard".to_string(),
- auto_update_engine: false,
- auto_unload: false,
- auto_restart_on_crash: false,
- timeout: 120,
- llamacpp_env: String::new(),
- fit: false,
- fit_ctx: String::new(),
- fit_target: String::new(),
- chat_template: String::new(),
- n_gpu_layers: 100,
- offload_mmproj: true,
- cpu_moe: false,
- n_cpu_moe: 0,
- override_tensor_buffer_t: String::new(),
- ctx_size: 2048,
- threads: 0,
- threads_batch: 0,
- n_predict: 0,
- batch_size: 0,
- ubatch_size: 0,
- device: String::new(),
- split_mode: "layer".to_string(),
- main_gpu: 0,
- flash_attn: "auto".to_string(),
- cont_batching: false,
- no_mmap: false,
- mlock: false,
- no_kv_offload: false,
- cache_type_k: "f16".to_string(),
- cache_type_v: "f16".to_string(),
- defrag_thold: 0.1,
- rope_scaling: "none".to_string(),
- rope_scale: 1.0,
- rope_freq_base: 0.0,
- rope_freq_scale: 1.0,
- ctx_shift: false,
- parallel: 1,
- reasoning: "auto".to_string(),
- cache_ram: -1,
- cache_reuse: 0,
- swa_full: false,
- keep: 0,
- }
- }
-
- fn assert_arg_pair(args: &[String], flag: &str, value: &str) {
- let pos = args
- .iter()
- .position(|arg| arg == flag)
- .unwrap_or_else(|| panic!("Flag '{}' not found in args: {:?}", flag, args));
- assert_eq!(
- args.get(pos + 1).unwrap(),
- value,
- "Expected '{}' after flag '{}', but got '{:?}'",
- value,
- flag,
- args.get(pos + 1)
- );
- }
-
- fn assert_has_flag(args: &[String], flag: &str) {
- assert!(
- args.contains(&flag.to_string()),
- "Flag '{}' not found in args: {:?}",
- flag,
- args
- );
- }
-
- fn assert_no_flag(args: &[String], flag: &str) {
- assert!(
- !args.contains(&flag.to_string()),
- "Flag '{}' should not be present in args: {:?}",
- flag,
- args
- );
- }
-
- #[test]
- fn test_basic_required_arguments() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test-model", "/path/to/model", 8080, None);
-
- assert_has_flag(&args, "--no-webui");
- assert_has_flag(&args, "--jinja");
- assert_arg_pair(&args, "-m", "/path/to/model");
- assert_arg_pair(&args, "-a", "test-model");
- assert_arg_pair(&args, "--port", "8080");
- }
-
- #[test]
- fn test_gpu_layers_default_100() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "-ngl", "-1");
- }
-
- #[test]
- fn test_gpu_layers_custom_value() {
- let mut config = default_config();
- config.n_gpu_layers = 32;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "-ngl", "32");
- }
-
- #[test]
- fn test_gpu_layers_negative_value() {
- let mut config = default_config();
- config.n_gpu_layers = -1;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "-ngl", "-1");
- }
-
- #[test]
- fn test_embedding_mode_arguments() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, true).unwrap();
- let args = builder.build("embed-model", "/path/to/model", 8080, None);
-
- assert_has_flag(&args, "--embedding");
- assert_arg_pair(&args, "--pooling", "mean");
- }
-
- #[test]
- fn test_text_generation_mode_no_embedding_flags() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--embedding");
- assert_no_flag(&args, "--pooling");
- }
-
- #[test]
- fn test_thread_settings() {
- let mut config = default_config();
- config.threads = 8;
- config.threads_batch = 4;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--threads", "8");
- assert_arg_pair(&args, "--threads-batch", "4");
- }
-
- #[test]
- fn test_thread_settings_zero_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--threads");
- assert_no_flag(&args, "--threads-batch");
- }
-
- #[test]
- fn test_batch_settings_default_values_not_added() {
- let mut config = default_config();
- config.batch_size = 2048;
- config.ubatch_size = 512;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--batch-size");
- assert_no_flag(&args, "--ubatch-size");
- }
-
- #[test]
- fn test_batch_settings_custom_values() {
- let mut config = default_config();
- config.batch_size = 1024;
- config.ubatch_size = 256;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--batch-size", "1024");
- assert_arg_pair(&args, "--ubatch-size", "256");
- }
-
- #[test]
- fn test_ik_backend_no_webui_flag() {
- let mut config = default_config();
- config.version_backend = "v1.0/ik-backend".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--no-webui");
- }
-
- #[test]
- fn test_standard_backend_flash_attention() {
- let mut config = default_config();
- config.flash_attn = "on".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_has_flag(&args, "--flash-attn");
- assert_no_flag(&args, "-fa");
- }
-
- #[test]
- fn test_old_version_flash_attention_off_not_added() {
- let mut config = default_config();
- config.version_backend = "b6000/standard".to_string();
- config.flash_attn = "off".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--flash-attn");
- assert_no_flag(&args, "-fa");
- }
-
- #[test]
- fn test_new_version_flash_attention_off_sends_value() {
- let mut config = default_config();
- config.version_backend = "b6325/standard".to_string();
- config.flash_attn = "off".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--flash-attn", "off");
- assert_no_flag(&args, "-fa");
- }
-
- #[test]
- fn test_ik_backend_flash_attention() {
- let mut config = default_config();
- config.version_backend = "v1.0/ik-backend".to_string();
- config.flash_attn = "on".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_has_flag(&args, "-fa");
- assert_no_flag(&args, "--flash-attn");
- }
-
- #[test]
- fn test_flash_attention_auto_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--flash-attn");
- }
-
- #[test]
- fn test_cpu_moe_flags() {
- let mut config = default_config();
- config.cpu_moe = true;
- config.n_cpu_moe = 4;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_has_flag(&args, "--cpu-moe");
- assert_arg_pair(&args, "--n-cpu-moe", "4");
- }
-
- #[test]
- fn test_cpu_moe_zero_not_added() {
- let mut config = default_config();
- config.cpu_moe = false;
- config.n_cpu_moe = 0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cpu-moe");
- assert_no_flag(&args, "--n-cpu-moe");
- }
-
- #[test]
- fn test_mmproj_path_provided() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, Some("/path/to/mmproj".to_string()));
-
- assert_arg_pair(&args, "--mmproj", "/path/to/mmproj");
- }
-
- #[test]
- fn test_mmproj_path_empty_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, Some(String::new()));
-
- assert_no_flag(&args, "--mmproj");
- assert_no_flag(&args, "--no-mmproj-offload");
- }
-
- #[test]
- fn test_mmproj_offload_disabled_adds_no_mmproj_offload_flag() {
- let mut config = default_config();
- config.offload_mmproj = false;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, Some("/path/to/mmproj".to_string()));
-
- assert_arg_pair(&args, "--mmproj", "/path/to/mmproj");
- assert_has_flag(&args, "--no-mmproj-offload");
- }
-
- #[test]
- fn test_mmproj_offload_enabled_does_not_add_no_mmproj_offload_flag() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, Some("/path/to/mmproj".to_string()));
-
- assert_arg_pair(&args, "--mmproj", "/path/to/mmproj");
- assert_no_flag(&args, "--no-mmproj-offload");
- }
-
- #[test]
- fn test_mmproj_offload_disabled_without_mmproj_does_not_add_flag() {
- let mut config = default_config();
- config.offload_mmproj = false;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--mmproj");
- assert_no_flag(&args, "--no-mmproj-offload");
- }
-
- #[test]
- fn test_chat_template() {
- let mut config = default_config();
- config.chat_template = "custom-template".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--chat-template", "custom-template");
- }
-
- #[test]
- fn test_empty_chat_template_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--chat-template");
- }
-
- #[test]
- fn test_device_settings() {
- let mut config = default_config();
- config.device = "cuda:0".to_string();
- config.split_mode = "row".to_string();
- config.main_gpu = 1;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--device", "cuda:0");
- assert_arg_pair(&args, "--split-mode", "row");
- assert_arg_pair(&args, "--main-gpu", "1");
- }
-
- #[test]
- fn test_split_mode_layer_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--split-mode");
- }
-
- #[test]
- fn test_main_gpu_zero_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--main-gpu");
- }
-
- #[test]
- fn test_boolean_flags_enabled() {
- let mut config = default_config();
- config.ctx_shift = true;
- config.cont_batching = true;
- config.no_mmap = true;
- config.mlock = true;
- config.no_kv_offload = true;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_has_flag(&args, "--context-shift");
- assert_has_flag(&args, "--cont-batching");
- assert_has_flag(&args, "--no-mmap");
- assert_has_flag(&args, "--mlock");
- assert_has_flag(&args, "--no-kv-offload");
- }
-
- #[test]
- fn test_boolean_flags_disabled() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--context-shift");
- assert_no_flag(&args, "--cont-batching");
- assert_no_flag(&args, "--no-mmap");
- assert_no_flag(&args, "--mlock");
- assert_no_flag(&args, "--no-kv-offload");
- }
-
- #[test]
- fn test_ctx_size_custom_value() {
- let mut config = default_config();
- config.ctx_size = 4096;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--ctx-size", "4096");
- }
-
- #[test]
- fn test_ctx_size_falls_back_to_4096_when_fit_off_and_unset() {
- let mut config = default_config();
- config.fit = false;
- config.ctx_size = 0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--ctx-size", "4096");
- }
-
- #[test]
- fn test_ctx_size_omitted_when_fit_on() {
- let mut config = default_config();
- config.fit = true;
- config.ctx_size = 8192;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--ctx-size");
- }
-
- #[test]
- fn test_n_predict() {
- let mut config = default_config();
- config.n_predict = 512;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--n-predict", "512");
- }
-
- #[test]
- fn test_cache_type_k_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cache-type-k");
- }
-
- #[test]
- fn test_cache_type_k_custom_value() {
- let mut config = default_config();
- config.cache_type_k = "q8_0".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-type-k", "q8_0");
- }
-
- #[test]
- fn test_cache_type_v_with_flash_attn() {
- let mut config = default_config();
- config.flash_attn = "on".to_string();
- config.cache_type_v = "q8_0".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-type-v", "q8_0");
- }
-
- #[test]
- fn test_cache_type_v_without_flash_attn_not_added() {
- let mut config = default_config();
- config.flash_attn = "off".to_string();
- config.cache_type_v = "q8_0".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cache-type-v");
- }
-
- #[test]
- fn test_cache_type_v_with_auto_flash_attn() {
- // "auto" != "off", so cache_type_v should be included (changed from requiring "on")
- let mut config = default_config(); // flash_attn defaults to "auto"
- config.cache_type_v = "q8_0".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-type-v", "q8_0");
- }
-
- #[test]
- fn test_cache_type_v_f16_not_added() {
- let mut config = default_config();
- config.flash_attn = "on".to_string();
- config.cache_type_v = "f16".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cache-type-v");
- }
-
- #[test]
- fn test_defrag_thold_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--defrag-thold");
- }
-
- #[test]
- fn test_defrag_thold_custom_value() {
- let mut config = default_config();
- config.defrag_thold = 0.5;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--defrag-thold", "0.5");
- }
-
- #[test]
- fn test_rope_scaling_none_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--rope-scaling");
- }
-
- #[test]
- fn test_rope_scaling_custom_value() {
- let mut config = default_config();
- config.rope_scaling = "linear".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--rope-scaling", "linear");
- }
-
- #[test]
- fn test_rope_scale_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--rope-scale");
- }
-
- #[test]
- fn test_rope_scale_custom_value() {
- let mut config = default_config();
- config.rope_scale = 2.0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--rope-scale", "2");
- }
-
- #[test]
- fn test_rope_freq_base_zero_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--rope-freq-base");
- }
-
- #[test]
- fn test_rope_freq_base_custom_value() {
- let mut config = default_config();
- config.rope_freq_base = 10000.0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--rope-freq-base", "10000");
- }
-
- #[test]
- fn test_rope_freq_scale_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--rope-freq-scale");
- }
-
- #[test]
- fn test_rope_freq_scale_custom_value() {
- let mut config = default_config();
- config.rope_freq_scale = 0.5;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--rope-freq-scale", "0.5");
- }
-
- #[test]
- fn test_tensor_buffer_override() {
- let mut config = default_config();
- config.override_tensor_buffer_t = "f32".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--override-tensor", "f32");
- }
-
- #[test]
- fn test_fit_off() {
- let mut config = default_config();
- config.fit = false;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--fit", "off");
- assert_no_flag(&args, "--fit-ctx");
- assert_no_flag(&args, "--fit-target");
- }
-
- #[test]
- fn test_fit_on_with_defaults() {
- let mut config = default_config();
- config.fit = true;
- config.fit_ctx = "4096".to_string();
- config.fit_target = "1024".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--fit", "on");
- assert_no_flag(&args, "--fit-ctx");
- assert_no_flag(&args, "--fit-target");
- }
-
- #[test]
- fn test_fit_on_with_custom_values() {
- let mut config = default_config();
- config.fit = true;
- config.fit_ctx = "8192".to_string();
- config.fit_target = "2048".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--fit", "on");
- assert_arg_pair(&args, "--fit-ctx", "8192");
- assert_arg_pair(&args, "--fit-target", "2048");
- }
-
- #[test]
- fn test_fit_not_added_for_ik_backend() {
- let mut config = default_config();
- config.version_backend = "v1.0/ik-backend".to_string();
- config.fit = true;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--fit");
- assert_no_flag(&args, "--fit-ctx");
- assert_no_flag(&args, "--fit-target");
- }
-
- #[test]
- fn test_invalid_version_backend_format() {
- let mut config = default_config();
- config.version_backend = "invalid-format".to_string();
-
- let result = ArgumentBuilder::new(config, false);
- assert!(result.is_err());
- if let Err(e) = result {
- assert_eq!(e, "Invalid version_backend format");
- }
- }
-
- #[test]
- fn test_complex_configuration() {
- let mut config = default_config();
- config.n_gpu_layers = 50;
- config.threads = 16;
- config.threads_batch = 8;
- config.batch_size = 1024;
- config.ctx_size = 4096;
- config.flash_attn = "on".to_string();
- config.cont_batching = true;
- config.rope_scaling = "linear".to_string();
- config.rope_scale = 2.0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("complex-model", "/model/path", 9000, None);
-
- assert_arg_pair(&args, "-ngl", "50");
- assert_arg_pair(&args, "--threads", "16");
- assert_arg_pair(&args, "--threads-batch", "8");
- assert_arg_pair(&args, "--batch-size", "1024");
- assert_arg_pair(&args, "--ctx-size", "4096");
- assert_has_flag(&args, "--flash-attn");
- assert_has_flag(&args, "--cont-batching");
- assert_arg_pair(&args, "--rope-scaling", "linear");
- assert_arg_pair(&args, "--rope-scale", "2");
- assert_arg_pair(&args, "--port", "9000");
- }
-
- #[test]
- fn test_parallel_not_added_when_zero() {
- let mut config = default_config();
- config.parallel = 0;
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--parallel");
- assert_no_flag(&args, "-kvu");
- }
-
- #[test]
- fn test_parallel_1_adds_parallel_and_kvu() {
- let config = default_config(); // default is 1
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--parallel", "1");
- assert_has_flag(&args, "-kvu");
- }
-
- #[test]
- fn test_reasoning_auto_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--reasoning");
- }
-
- #[test]
- fn test_reasoning_on_passes_value() {
- let mut config = default_config();
- config.reasoning = "on".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--reasoning", "on");
- }
-
- #[test]
- fn test_reasoning_off_passes_value() {
- let mut config = default_config();
- config.reasoning = "off".to_string();
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--reasoning", "off");
- }
-
- #[test]
- fn test_cache_ram_default_unlimited_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cache-ram");
- }
-
- #[test]
- fn test_cache_ram_zero_disables() {
- let mut config = default_config();
- config.cache_ram = 0;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-ram", "0");
- }
-
- #[test]
- fn test_cache_ram_custom_value() {
- let mut config = default_config();
- config.cache_ram = 4096;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-ram", "4096");
- }
-
- #[test]
- fn test_cache_reuse_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--cache-reuse");
- }
-
- #[test]
- fn test_cache_reuse_custom_value() {
- let mut config = default_config();
- config.cache_reuse = 256;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--cache-reuse", "256");
- }
-
- #[test]
- fn test_swa_full_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--swa-full");
- }
-
- #[test]
- fn test_swa_full_enabled() {
- let mut config = default_config();
- config.swa_full = true;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_has_flag(&args, "--swa-full");
- }
-
- #[test]
- fn test_keep_default_not_added() {
- let config = default_config();
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_no_flag(&args, "--keep");
- }
-
- #[test]
- fn test_keep_custom_value() {
- let mut config = default_config();
- config.keep = 32;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--keep", "32");
- }
-
- #[test]
- fn test_keep_negative_keep_all() {
- let mut config = default_config();
- config.keep = -1;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--keep", "-1");
- }
-
- #[test]
- fn test_parallel_greater_than_1_no_kvu() {
- let mut config = default_config();
- config.parallel = 4;
-
- let builder = ArgumentBuilder::new(config, false).unwrap();
- let args = builder.build("test", "/path", 8080, None);
-
- assert_arg_pair(&args, "--parallel", "4");
- assert_no_flag(&args, "-kvu");
- }
-}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs
index 0721b1c8f..0d63ed17c 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs
@@ -1,73 +1,22 @@
+use std::sync::Arc;
+
use tauri::{Manager, Runtime};
pub async fn cleanup_processes<R: Runtime>(app_handle: &tauri::AppHandle<R>) {
- // Access the global AppState from the main app
- let app_state = match app_handle.try_state::<crate::state::LlamacppState>() {
+ let app_state = match app_handle.try_state::<Arc<crate::state::LlamacppState>>() {
Some(state) => state,
None => {
log::warn!("LlamacppState not found in app_handle");
return;
}
};
- let mut map = app_state.llama_server_process.lock().await;
- let pids: Vec<i32> = map.keys().cloned().collect();
- for pid in pids {
- if let Some(session) = map.remove(&pid) {
- let mut child = session.child;
- #[cfg(unix)]
- {
- use nix::sys::signal::{kill, Signal};
- use nix::unistd::Pid;
- use tokio::time::{timeout, Duration};
-
- if let Some(raw_pid) = child.id() {
- let raw_pid = raw_pid as i32;
- log::info!("Sending SIGTERM to PID {} during shutdown", raw_pid);
- let _ = kill(Pid::from_raw(raw_pid), Signal::SIGTERM);
-
- match timeout(Duration::from_secs(2), child.wait()).await {
- Ok(Ok(status)) => {
- log::info!("Process {} exited gracefully: {}", raw_pid, status)
- }
- Ok(Err(e)) => {
- log::error!("Error waiting after SIGTERM for {}: {}", raw_pid, e)
- }
- Err(_) => {
- log::warn!("SIGTERM timed out for PID {}; sending SIGKILL", raw_pid);
- let _ = kill(Pid::from_raw(raw_pid), Signal::SIGKILL);
- let _ = child.wait().await;
- }
- }
- }
- }
- #[cfg(all(windows, target_arch = "x86_64"))]
- {
- if let Some(raw_pid) = child.id() {
- log::warn!(
- "Gracefully terminating is unsupported on Windows, force-killing PID {}",
- raw_pid
- );
-
- // Since we know a graceful shutdown doesn't work and there are no child processes
- // to worry about, we can use `child.kill()` directly. On Windows, this is
- // a forceful termination via the `TerminateProcess` API.
- if let Err(e) = child.kill().await {
- log::error!("Failed to send kill signal to PID {}: {}. It may have already terminated.", raw_pid, e);
- }
- match child.wait().await {
- Ok(status) => log::info!(
- "process {} has been terminated. Final exit status: {}",
- raw_pid,
- status
- ),
- Err(e) => log::error!(
- "Error waiting on child process {} after kill: {}",
- raw_pid,
- e
- ),
- }
- }
- }
+ let maybe_handle = {
+ let mut guard = app_state.router.lock().await;
+ guard.take()
+ };
+ if let Some(handle) = maybe_handle {
+ if let Err(e) = crate::router::stop_router(handle).await {
+ log::warn!("Failed to stop router during cleanup: {}", e);
}
}
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index dcbde906c..c9f863b43 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -2,45 +2,15 @@ use base64::{engine::general_purpose, Engine as _};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::collections::HashMap;
-use std::process::Stdio;
use std::sync::Arc;
-use std::time::{SystemTime, UNIX_EPOCH};
use std::time::Duration;
-use tauri::{Emitter, Manager, Runtime, State};
-use tokio::io::{AsyncBufReadExt, BufReader};
-use tokio::process::Command;
-use tokio::sync::{mpsc, Mutex};
-use tokio::time::Instant;
+use tauri::{Manager, Runtime, State};
-use crate::args::{ArgumentBuilder, LlamacppConfig};
use crate::device::{get_devices_from_backend, DeviceInfo};
use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};
-use crate::path::{validate_binary_path, validate_mmproj_path, validate_model_path};
-use crate::process::{
- find_session_by_model_id, get_all_active_sessions, get_all_loaded_model_ids,
- get_random_available_port, is_process_running_by_pid,
-};
-use crate::state::{LLamaBackendSession, LlamacppState, SessionInfo};
-use jan_utils::{
- binary_requires_cuda, find_cuda_paths, setup_library_path, setup_windows_process_flags,
-};
-
-#[cfg(unix)]
-use crate::process::graceful_terminate_process;
-
-#[cfg(all(windows, target_arch = "x86_64"))]
-use crate::process::force_terminate_process;
+use crate::state::{LlamacppState, SessionInfo};
type HmacSha256 = Hmac<Sha256>;
-const AUTO_RESTART_MAX_ATTEMPTS: usize = 3;
-const AUTO_RESTART_WINDOW_MS: u64 = 5 * 60 * 1000;
-
-#[derive(Clone, serde::Serialize)]
-struct SessionLifecycleEvent {
- model_id: String,
- pid: Option<i32>,
- message: String,
-}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct UnloadResult {
@@ -48,376 +18,304 @@ pub struct UnloadResult {
error: Option<String>,
}
-/// Core model loading logic usable without an AppHandle (CLI / test support).
-pub async fn load_llama_model_impl(
- process_map_arc: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
- backend_path: &str,
- model_id: String,
- model_path: String,
- port: u16,
- config: LlamacppConfig,
- envs: HashMap<String, String>,
- mmproj_path: Option<String>,
- is_embedding: bool,
- timeout: u64,
-) -> ServerResult<SessionInfo> {
- let mut process_map = process_map_arc.lock().await;
- let launch_config = crate::state::SessionLaunchConfig {
- backend_path: backend_path.to_string(),
- model_id: model_id.clone(),
- model_path: model_path.clone(),
- port,
- config: config.clone(),
- envs: envs.clone(),
- mmproj_path: mmproj_path.clone(),
- is_embedding,
- timeout,
- };
-
- log::info!("Attempting to launch server at path: {:?}", backend_path);
- log::info!("Using configuration: {:?}", config);
-
- let bin_path = validate_binary_path(backend_path)?;
-
- // Build arguments using the ArgumentBuilder
- let builder = ArgumentBuilder::new(config.clone(), is_embedding)
- .map_err(|e| ServerError::InvalidArgument(e))?;
-
- let mut args = builder.build(&model_id, &model_path, port, mmproj_path.clone());
+#[derive(serde::Serialize)]
+struct ModelRequestBody<'a> {
+ model: &'a str,
+}
- log::info!("Generated arguments: {:?}", args);
+async fn router_endpoint<R: Runtime>(
+ app_handle: &tauri::AppHandle<R>,
+) -> Result<(u16, String, u32), String> {
+ let state: State<Arc<LlamacppState>> = app_handle.state();
+ let guard = state.router.lock().await;
+ let h = guard.as_ref().ok_or_else(|| "router not started".to_string())?;
+ Ok((h.port, h.api_key.clone(), h.pid))
+}
- // Validate paths
- let model_path_pb = validate_model_path(&mut args)?;
- let mmproj_path_pb = validate_mmproj_path(&mut args)?;
+async fn http_client() -> reqwest::Client {
+ reqwest::Client::builder()
+ .timeout(Duration::from_secs(600))
+ .build()
+ .unwrap_or_else(|_| reqwest::Client::new())
+}
- let mmproj_path_string = if let Some(ref _mmproj_pb) = mmproj_path_pb {
- // Find the actual mmproj path from args after validation/conversion
- if let Some(mmproj_index) = args.iter().position(|arg| arg == "--mmproj") {
- Some(args[mmproj_index + 1].clone())
- } else {
- None
+async fn post_load(port: u16, api_key: &str, model_id: &str) -> ServerResult<()> {
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models/load", port);
+ let resp = client
+ .post(&url)
+ .bearer_auth(api_key)
+ .json(&ModelRequestBody { model: model_id })
+ .send()
+ .await
+ .map_err(|e| {
+ ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ "Failed to call router /models/load".into(),
+ Some(e.to_string()),
+ ))
+ })?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ if !body.to_lowercase().contains("already") {
+ return Err(ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ format!("Router rejected model load (status {})", status),
+ Some(body),
+ )));
}
- } else {
- None
- };
-
- log::info!(
- "MMPROJ Path string: {}",
- &mmproj_path_string.as_ref().unwrap_or(&"None".to_string())
- );
-
- let api_key: String = envs
- .get("LLAMA_API_KEY")
- .map(|s| s.to_string())
- .unwrap_or_default();
-
- // Configure the command to run the server
- let mut command = Command::new(&bin_path);
-
- command.args(args);
- command.envs(envs);
+ }
- command.stdout(Stdio::piped());
- command.stderr(Stdio::piped());
- setup_windows_process_flags(&mut command);
+ // /models/load returns success once loading is *initiated*; poll /models
+ // until the entry transitions from "loading" to "loaded" (or fails).
+ wait_until_loaded(port, api_key, model_id, Duration::from_secs(600)).await
+}
- let cuda = find_cuda_paths();
- if cuda.lib_paths.is_empty() && cuda.bin_paths.is_empty() && binary_requires_cuda(&bin_path) {
- log::warn!(
- "llama.cpp backend appears to require CUDA, but CUDA not found. Process may fail to start. Please install cuda runtime and try again!"
- );
- }
- setup_library_path(bin_path.parent(), &cuda, &mut command);
-
- // Spawn the child process
- let mut child = command.spawn().map_err(ServerError::Io)?;
-
- let stderr = child.stderr.take().expect("stderr was piped");
- let stdout = child.stdout.take().expect("stdout was piped");
-
- // Create channels for communication between tasks
- let (ready_tx, mut ready_rx) = mpsc::channel::<bool>(1);
-
- // Spawn task to monitor stdout for readiness
- let stdout_ready_tx = ready_tx.clone();
- let _stdout_task = tokio::spawn(async move {
- let mut reader = BufReader::new(stdout);
- let mut byte_buffer = Vec::new();
-
- loop {
- byte_buffer.clear();
- match reader.read_until(b'\n', &mut byte_buffer).await {
- Ok(0) => break, // EOF
- Ok(_) => {
- let line = String::from_utf8_lossy(&byte_buffer);
- let line = line.trim_end();
- if !line.is_empty() {
- log::info!("[llamacpp stdout] {}", line);
- }
+async fn wait_until_loaded(
+ port: u16,
+ api_key: &str,
+ model_id: &str,
+ timeout: Duration,
+) -> ServerResult<()> {
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models", port);
+ let start = std::time::Instant::now();
+ let poll_interval = Duration::from_millis(250);
- // Check for readiness indicators
- let line_lower = line.to_lowercase();
- if line_lower.contains("http server listening")
- || line_lower.contains("all slots are idle")
- || line_lower.contains("starting the main loop")
- {
- log::info!("Server appears to be ready based on stdout: '{}'", line);
- let _ = stdout_ready_tx.send(true).await;
- }
- }
- Err(e) => {
- log::error!("Error reading stdout: {}", e);
- break;
- }
- }
- }
- });
-
- // Spawn task to capture stderr and monitor for errors
- let stderr_task = tokio::spawn(async move {
- let mut reader = BufReader::new(stderr);
- let mut byte_buffer = Vec::new();
- let mut stderr_buffer = String::new();
-
- loop {
- byte_buffer.clear();
- match reader.read_until(b'\n', &mut byte_buffer).await {
- Ok(0) => break, // EOF
- Ok(_) => {
- let line = String::from_utf8_lossy(&byte_buffer);
- let line = line.trim_end();
-
- if !line.is_empty() {
- stderr_buffer.push_str(line);
- stderr_buffer.push('\n');
- log::info!("[llamacpp] {}", line);
-
- // Check for readiness indicator
- let line_lower = line.to_string().to_lowercase();
- if line_lower.contains("server is listening on")
- || line_lower.contains("starting the main loop")
- || line_lower.contains("server listening on")
- {
- log::info!("Model appears to be ready based on logs: '{}'", line);
- let _ = ready_tx.send(true).await;
- }
+ loop {
+ let resp = client
+ .get(&url)
+ .bearer_auth(api_key)
+ .send()
+ .await
+ .map_err(|e| {
+ ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ "Failed to poll router /models".into(),
+ Some(e.to_string()),
+ ))
+ })?;
+
+ let json: serde_json::Value = resp.json().await.map_err(|e| {
+ ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ "Invalid JSON from /models".into(),
+ Some(e.to_string()),
+ ))
+ })?;
+
+ let entry = json
+ .get("data")
+ .and_then(|d| d.as_array())
+ .and_then(|arr| {
+ arr.iter()
+ .find(|m| m.get("id").and_then(|v| v.as_str()) == Some(model_id))
+ });
+
+ if let Some(entry) = entry {
+ let status = entry.get("status");
+ let value = status
+ .and_then(|s| s.get("value"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ match value {
+ "loaded" => return Ok(()),
+ "loading" => {}
+ "unloaded" | "sleeping" => {
+ let failed = status
+ .and_then(|s| s.get("failed"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if failed {
+ let exit_code = status
+ .and_then(|s| s.get("exit_code"))
+ .and_then(|v| v.as_i64());
+ return Err(ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ format!("Model {} failed to load", model_id),
+ Some(format!("exit_code={:?}", exit_code)),
+ )));
}
}
- Err(e) => {
- log::error!("Error reading logs: {}", e);
- break;
+ other => {
+ log::warn!("Unknown model status value: {}", other);
}
}
}
- stderr_buffer
- });
-
- // Check if process exited early
- if let Some(status) = child.try_wait()? {
- if !status.success() {
- let stderr_output = stderr_task.await.unwrap_or_default();
- log::error!("llama.cpp failed early with code {:?}", status);
- log::error!("{}", stderr_output);
- return Err(LlamacppError::from_stderr(&stderr_output).into());
+ if start.elapsed() >= timeout {
+ return Err(ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::ModelLoadTimedOut,
+ format!("Timed out waiting for model {} to load", model_id),
+ Some(format!("waited {:?}", timeout)),
+ )));
}
+ tokio::time::sleep(poll_interval).await;
}
+}
- // Wait for server to be ready or timeout
- let timeout_duration = Duration::from_secs(timeout);
- let start_time = Instant::now();
- log::info!("Waiting for model session to be ready...");
-
- loop {
- tokio::select! {
- // Server is ready
- Some(true) = ready_rx.recv() => {
- log::info!("Model is ready to accept requests!");
- break;
- }
- // Check for process exit more frequently
- _ = tokio::time::sleep(Duration::from_millis(50)) => {
- // Check if process exited
- if let Some(status) = child.try_wait()? {
- let stderr_output = stderr_task.await.unwrap_or_default();
- if !status.success() {
- log::error!("llama.cpp exited with error code {:?}", status);
- return Err(LlamacppError::from_stderr(&stderr_output).into());
- } else {
- log::error!("llama.cpp exited successfully but without ready signal");
- return Err(LlamacppError::from_stderr(&stderr_output).into());
- }
- }
-
- // Timeout check
- if start_time.elapsed() > timeout_duration {
- log::error!("Timeout waiting for server to be ready");
- let _ = child.kill().await;
- let stderr_output = stderr_task.await.unwrap_or_default();
- return Err(LlamacppError::new(
- ErrorCode::ModelLoadTimedOut,
- "The model took too long to load and timed out.".into(),
- Some(format!("Timeout: {}s\n\nStderr:\n{}", timeout_duration.as_secs(), stderr_output)),
- ).into());
- }
- }
- }
+async fn post_unload(port: u16, api_key: &str, model_id: &str) -> Result<(), String> {
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models/unload", port);
+ let resp = client
+ .post(&url)
+ .bearer_auth(api_key)
+ .json(&ModelRequestBody { model: model_id })
+ .send()
+ .await
+ .map_err(|e| format!("Failed to call /models/unload: {}", e))?;
+ if !resp.status().is_success() {
+ let status = resp.status();
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("Router rejected unload (status {}): {}", status, body));
}
- // Get the PID to use as session ID
- let pid = child.id().map(|id| id as i32).unwrap_or(-1);
-
- log::info!("Server process started with PID: {} and is ready", pid);
- let session_info = SessionInfo {
- pid: pid.clone(),
- port: port.into(),
- model_id: model_id,
- model_path: model_path_pb.display().to_string(),
- is_embedding: is_embedding,
- api_key: api_key,
- mmproj_path: mmproj_path_string,
- };
-
- // Insert session info to process_map
- process_map.insert(
- pid.clone(),
- LLamaBackendSession {
- child,
- info: session_info.clone(),
- launch: launch_config,
- restart_attempt_timestamps_ms: Vec::new(),
- },
- );
-
- Ok(session_info)
+ // /models/unload returns once shutdown is *initiated*; poll until the
+ // entry actually leaves the "loaded"/"loading" states. Preset's
+ // stop-timeout defaults to 10s, so 30s of slack is plenty.
+ wait_until_unloaded(port, api_key, model_id, Duration::from_secs(30))
+ .await
+ .map_err(|e| format!("{}", e))
}
-fn now_ms() -> u64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
+async fn wait_until_unloaded(
+ port: u16,
+ api_key: &str,
+ model_id: &str,
+ timeout: Duration,
+) -> ServerResult<()> {
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models", port);
+ let start = std::time::Instant::now();
+ let poll_interval = Duration::from_millis(250);
-fn can_attempt_restart(session: &mut LLamaBackendSession) -> bool {
- let cutoff = now_ms().saturating_sub(AUTO_RESTART_WINDOW_MS);
- session
- .restart_attempt_timestamps_ms
- .retain(|ts| *ts >= cutoff);
- session.restart_attempt_timestamps_ms.len() < AUTO_RESTART_MAX_ATTEMPTS
-}
+ loop {
+ let resp = client
+ .get(&url)
+ .bearer_auth(api_key)
+ .send()
+ .await
+ .map_err(|e| {
+ ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ "Failed to poll router /models".into(),
+ Some(e.to_string()),
+ ))
+ })?;
+ let json: serde_json::Value = resp.json().await.map_err(|e| {
+ ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ "Invalid JSON from /models".into(),
+ Some(e.to_string()),
+ ))
+ })?;
+
+ let entry = json
+ .get("data")
+ .and_then(|d| d.as_array())
+ .and_then(|arr| {
+ arr.iter()
+ .find(|m| m.get("id").and_then(|v| v.as_str()) == Some(model_id))
+ });
+
+ // No entry at all → treat as unloaded.
+ let still_loaded = entry
+ .and_then(|e| e.get("status"))
+ .and_then(|s| s.get("value"))
+ .and_then(|v| v.as_str())
+ .map(|v| matches!(v, "loaded" | "loading"))
+ .unwrap_or(false);
+ if !still_loaded {
+ return Ok(());
+ }
-fn start_session_exit_monitor<R: Runtime>(app_handle: tauri::AppHandle<R>, model_id: String) {
- tokio::spawn(async move {
- loop {
- tokio::time::sleep(Duration::from_millis(1000)).await;
-
- let maybe_exited = {
- let state: State<LlamacppState> = app_handle.state();
- let mut map = state.llama_server_process.lock().await;
-
- let maybe_session = map
- .values_mut()
- .find(|session| session.info.model_id == model_id);
-
- let Some(session) = maybe_session else {
- // Session no longer exists (unloaded manually or cleaned up); stop watching.
- return;
- };
-
- match session.child.try_wait() {
- Ok(Some(_status)) => true,
- Ok(None) => false,
- Err(err) => {
- log::warn!(
- "Failed to inspect process state for model '{}': {}",
- model_id,
- err
- );
- false
- }
- }
- };
+ if start.elapsed() >= timeout {
+ return Err(ServerError::Llamacpp(LlamacppError::new(
+ ErrorCode::InternalError,
+ format!("Timed out waiting for model {} to unload", model_id),
+ Some(format!("waited {:?}", timeout)),
+ )));
+ }
+ tokio::time::sleep(poll_interval).await;
+ }
+}
- if maybe_exited {
- let _ = ensure_session_ready(app_handle.clone(), model_id.clone()).await;
- }
+async fn router_loaded_model_ids(port: u16, api_key: &str) -> Result<Vec<String>, String> {
+ // Router-aware listing: `/models` (not `/v1/models`, which is OAI-compat
+ // and returns a single element). Each entry has a `status` object whose
+ // `value` is one of "loaded" / "loading" / "unloaded" / "sleeping".
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models", port);
+ let resp = client
+ .get(&url)
+ .bearer_auth(api_key)
+ .send()
+ .await
+ .map_err(|e| format!("Failed to query /models: {}", e))?;
+ if !resp.status().is_success() {
+ return Err(format!("/models returned {}", resp.status()));
+ }
+ let json: serde_json::Value = resp
+ .json()
+ .await
+ .map_err(|e| format!("Invalid JSON from /models: {}", e))?;
+ let data = json
+ .get("data")
+ .and_then(|d| d.as_array())
+ .cloned()
+ .unwrap_or_default();
+ let mut ids = Vec::new();
+ for m in &data {
+ let Some(id) = m.get("id").and_then(|v| v.as_str()) else {
+ continue;
+ };
+ let loaded = m
+ .get("status")
+ .and_then(|s| s.get("value"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.eq_ignore_ascii_case("loaded"))
+ .unwrap_or(false);
+ if loaded {
+ ids.push(id.to_string());
}
- });
+ }
+ Ok(ids)
}
-/// Load a llama model and start the server
#[tauri::command]
pub async fn load_llama_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
- backend_path: &str,
model_id: String,
- model_path: String,
- port: u16,
- config: LlamacppConfig,
- envs: HashMap<String, String>,
- mmproj_path: Option<String>,
is_embedding: bool,
- timeout: u64,
) -> ServerResult<SessionInfo> {
- let state: State<LlamacppState> = app_handle.state();
- let session_info = load_llama_model_impl(
- state.llama_server_process.clone(),
- backend_path,
+ let (port, api_key, pid) = router_endpoint(&app_handle)
+ .await
+ .map_err(|e| ServerError::InvalidArgument(e))?;
+ post_load(port, &api_key, &model_id).await?;
+ Ok(SessionInfo {
+ pid: pid as i32,
+ port: port as i32,
model_id,
- model_path,
- port,
- config,
- envs,
- mmproj_path,
is_embedding,
- timeout,
- )
- .await?;
-
- // Observe process exit from plugin side immediately after load.
- start_session_exit_monitor(app_handle, session_info.model_id.clone());
-
- Ok(session_info)
+ api_key,
+ })
}
-/// Unload a llama model by terminating its process
#[tauri::command]
pub async fn unload_llama_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
- pid: i32,
+ model_id: String,
) -> ServerResult<UnloadResult> {
- let state: State<LlamacppState> = app_handle.state();
- let mut map = state.llama_server_process.lock().await;
-
- if let Some(session) = map.remove(&pid) {
- let mut child = session.child;
-
- #[cfg(unix)]
- {
- graceful_terminate_process(&mut child).await;
- }
-
- #[cfg(all(windows, target_arch = "x86_64"))]
- {
- force_terminate_process(&mut child).await;
- }
-
- Ok(UnloadResult {
- success: true,
- error: None,
- })
- } else {
- log::warn!("No server with PID '{}' found", pid);
- Ok(UnloadResult {
- success: true,
- error: None,
- })
+ let (port, api_key, _pid) = router_endpoint(&app_handle)
+ .await
+ .map_err(|e| ServerError::InvalidArgument(e))?;
+ match post_unload(port, &api_key, &model_id).await {
+ Ok(()) => Ok(UnloadResult { success: true, error: None }),
+ Err(e) => Ok(UnloadResult { success: false, error: Some(e) }),
}
}
-/// Get available devices from the llama.cpp backend
#[tauri::command]
pub async fn get_devices(
backend_path: &str,
@@ -426,7 +324,6 @@ pub async fn get_devices(
get_devices_from_backend(backend_path, envs).await
}
-/// Generate API key using HMAC-SHA256
#[tauri::command]
pub fn generate_api_key(model_id: String, api_secret: String) -> Result<String, String> {
let mut mac = HmacSha256::new_from_slice(api_secret.as_bytes())
@@ -438,173 +335,126 @@ pub fn generate_api_key(model_id: String, api_secret: String) -> Result<String,
Ok(hash)
}
-/// Check if a process is still running
-#[tauri::command]
-pub async fn is_process_running<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- pid: i32,
-) -> Result<bool, String> {
- is_process_running_by_pid(app_handle, pid).await
-}
-
#[tauri::command]
pub async fn ensure_session_ready<R: Runtime>(
app_handle: tauri::AppHandle<R>,
model_id: String,
+ is_embedding: bool,
) -> Result<SessionInfo, String> {
- let state: State<LlamacppState> = app_handle.state();
- let process_map_arc = state.llama_server_process.clone();
-
- // Step 1: resolve session by model_id and check if alive from source-of-truth child handle.
- let (dead_pid, maybe_restart_launch) = {
- let mut map = process_map_arc.lock().await;
- let maybe_entry = map
- .iter_mut()
- .find(|(_, session)| session.info.model_id == model_id);
-
- let Some((pid, session)) = maybe_entry else {
- return Err(format!("No active session found for model: {}", model_id));
- };
-
- match session.child.try_wait() {
- Ok(None) => {
- return Ok(session.info.clone());
- }
- Ok(Some(status)) => {
- let _ = app_handle.emit(
- "llamacpp://session-exited",
- SessionLifecycleEvent {
- model_id: model_id.clone(),
- pid: Some(*pid),
- message: format!("Process exited with status: {}", status),
- },
- );
- if !session.launch.config.auto_restart_on_crash {
- return Err("Model appears to have crashed! Please reload!".to_string());
- }
- if !can_attempt_restart(session) {
- let _ = app_handle.emit(
- "llamacpp://session-restart-failed",
- SessionLifecycleEvent {
- model_id: model_id.clone(),
- pid: Some(*pid),
- message: "Auto-restart attempt limit reached".to_string(),
- },
- );
- return Err(format!(
- "Model \"{}\" crashed repeatedly. Auto-restart limit reached ({} attempts in {} minutes). Please reload manually.",
- model_id,
- AUTO_RESTART_MAX_ATTEMPTS,
- AUTO_RESTART_WINDOW_MS / 60000
- ));
- }
-
- log::warn!(
- "Model '{}' exited with status {:?}. Attempting automatic restart.",
- model_id,
- status
- );
- let _ = app_handle.emit(
- "llamacpp://session-restarting",
- SessionLifecycleEvent {
- model_id: model_id.clone(),
- pid: Some(*pid),
- message: "Attempting automatic restart".to_string(),
- },
- );
-
- session.restart_attempt_timestamps_ms.push(now_ms());
- (Some(*pid), Some(session.launch.clone()))
- }
- Err(err) => {
- return Err(format!("Failed to inspect session process state: {}", err));
- }
- }
- };
-
- // Step 2: remove dead session before restart.
- if let Some(pid) = dead_pid {
- let mut map = process_map_arc.lock().await;
- map.remove(&pid);
- }
-
- // Step 3: restart using original launch config.
- let launch = maybe_restart_launch
- .ok_or_else(|| "Unable to restart model session: launch configuration missing".to_string())?;
-
- let restarted = load_llama_model_impl(
- process_map_arc,
- &launch.backend_path,
- launch.model_id,
- launch.model_path,
- launch.port,
- launch.config,
- launch.envs,
- launch.mmproj_path,
- launch.is_embedding,
- launch.timeout,
- )
- .await
- .map_err(|e| {
- let _ = app_handle.emit(
- "llamacpp://session-restart-failed",
- SessionLifecycleEvent {
- model_id: model_id.clone(),
- pid: dead_pid,
- message: format!("Automatic restart failed: {}", e),
- },
- );
- format!("Model crashed and automatic restart failed: {}", e)
- })?;
-
- let _ = app_handle.emit(
- "llamacpp://session-restarted",
- SessionLifecycleEvent {
- model_id: model_id.clone(),
- pid: Some(restarted.pid),
- message: "Automatic restart successful".to_string(),
- },
- );
-
- Ok(restarted)
-}
-
-/// Get a random available port
-#[tauri::command]
-pub async fn get_random_port<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<u16, String> {
- get_random_available_port(app_handle).await
+ let (port, api_key, pid) = router_endpoint(&app_handle).await?;
+ post_load(port, &api_key, &model_id)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(SessionInfo {
+ pid: pid as i32,
+ port: port as i32,
+ model_id,
+ is_embedding,
+ api_key,
+ })
}
-/// Find session information by model ID
#[tauri::command]
pub async fn find_session_by_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
model_id: String,
) -> Result<Option<SessionInfo>, String> {
- find_session_by_model_id(app_handle, &model_id).await
+ let (port, api_key, pid) = match router_endpoint(&app_handle).await {
+ Ok(v) => v,
+ Err(_) => return Ok(None),
+ };
+ let ids = router_loaded_model_ids(port, &api_key).await?;
+ if ids.iter().any(|id| id == &model_id) {
+ Ok(Some(SessionInfo {
+ pid: pid as i32,
+ port: port as i32,
+ model_id,
+ is_embedding: false,
+ api_key,
+ }))
+ } else {
+ Ok(None)
+ }
}
-/// Get all loaded model IDs
#[tauri::command]
pub async fn get_loaded_models<R: Runtime>(
app_handle: tauri::AppHandle<R>,
) -> Result<Vec<String>, String> {
- get_all_loaded_model_ids(app_handle).await
+ let (port, api_key, _pid) = match router_endpoint(&app_handle).await {
+ Ok(v) => v,
+ Err(_) => return Ok(Vec::new()),
+ };
+ router_loaded_model_ids(port, &api_key).await
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Clone)]
+pub struct RouterInfo {
+ pub port: u16,
+ pub api_key: String,
+ pub pid: u32,
}
-/// Get all active sessions
#[tauri::command]
-pub async fn get_all_sessions<R: Runtime>(
+#[allow(clippy::too_many_arguments)]
+pub async fn start_router<R: Runtime>(
app_handle: tauri::AppHandle<R>,
-) -> Result<Vec<SessionInfo>, String> {
- get_all_active_sessions(app_handle).await
+ backend_exe: String,
+ preset_path: String,
+ port: u16,
+ api_key: String,
+ models_max: u32,
+ default_args: Vec<String>,
+ envs: HashMap<String, String>,
+) -> Result<RouterInfo, String> {
+ let state: State<Arc<LlamacppState>> = app_handle.state();
+ let mut guard = state.router.lock().await;
+ if guard.is_some() {
+ return Err("Router is already running.".to_string());
+ }
+
+ let handle = crate::router::start_router(
+ std::path::PathBuf::from(backend_exe),
+ std::path::PathBuf::from(preset_path),
+ port,
+ api_key,
+ models_max,
+ default_args,
+ envs,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let info = RouterInfo {
+ port: handle.port,
+ api_key: handle.api_key.clone(),
+ pid: handle.pid,
+ };
+ *guard = Some(handle);
+ Ok(info)
+}
+
+#[tauri::command]
+pub async fn stop_router<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {
+ let state: State<Arc<LlamacppState>> = app_handle.state();
+ let mut guard = state.router.lock().await;
+ if let Some(handle) = guard.take() {
+ crate::router::stop_router(handle)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ Ok(())
}
-/// Get session information by model ID
#[tauri::command]
-pub async fn get_session_by_model<R: Runtime>(
+pub async fn get_router_info<R: Runtime>(
app_handle: tauri::AppHandle<R>,
- model_id: String,
-) -> Result<Option<SessionInfo>, String> {
- find_session_by_model_id(app_handle, &model_id).await
+) -> Result<Option<RouterInfo>, String> {
+ let state: State<Arc<LlamacppState>> = app_handle.state();
+ let guard = state.router.lock().await;
+ Ok(guard.as_ref().map(|h| RouterInfo {
+ port: h.port,
+ api_key: h.api_key.clone(),
+ pid: h.pid,
+ }))
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 410e8e3f0..1ffdc6727 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -1,9 +1,10 @@
+use std::sync::Arc;
+
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
-mod args;
mod backend;
pub mod cleanup;
pub mod deps_analyzer;
@@ -13,36 +14,30 @@ mod error;
mod gguf;
mod path;
mod process;
+pub mod router;
pub mod state;
-pub use args::LlamacppConfig;
pub use cleanup::cleanup_llama_processes;
-pub use commands::load_llama_model_impl;
-pub use state::{LLamaBackendSession, LlamacppState};
+pub use commands::stop_router;
+pub use state::LlamacppState;
-/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("llamacpp")
.invoke_handler(tauri::generate_handler![
- // Cleanup command
cleanup::cleanup_llama_processes,
- // LlamaCpp server commands
commands::load_llama_model,
commands::unload_llama_model,
+ commands::start_router,
+ commands::stop_router,
+ commands::get_router_info,
commands::get_devices,
commands::generate_api_key,
- commands::is_process_running,
commands::ensure_session_ready,
- commands::get_random_port,
commands::find_session_by_model,
commands::get_loaded_models,
- commands::get_all_sessions,
- commands::get_session_by_model,
- // GGUF commands
gguf::commands::read_gguf_metadata,
gguf::commands::estimate_kv_cache_size,
gguf::commands::get_model_size,
gguf::commands::is_model_supported,
- // Backend management
backend::map_old_backend_to_new,
backend::get_local_installed_backends,
backend::list_supported_backends,
@@ -57,7 +52,6 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
backend::validate_backend_string,
backend::should_migrate_backend,
backend::handle_setting_update,
- // Backend path & download commands
backend::get_backend_dir,
backend::get_backend_exe_path,
backend::check_backend_installed,
@@ -66,8 +60,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
backend::build_backend_download_items
])
.setup(|app, _api| {
- // Initialize and manage the plugin state
- app.manage(state::LlamacppState::new());
+ app.manage(Arc::new(state::LlamacppState::new()));
Ok(())
})
.build()
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs
index 9b489d510..743479097 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs
@@ -1,278 +1,43 @@
-use std::path::PathBuf;
-
-use crate::error::{ErrorCode, LlamacppError, ServerResult};
-
-#[cfg(windows)]
-use jan_utils::path::get_short_path;
-
-/// Validate that a binary path exists and is accessible
-pub fn validate_binary_path(backend_path: &str) -> ServerResult<PathBuf> {
- let server_path_buf = PathBuf::from(backend_path);
- if !server_path_buf.exists() {
- let err_msg = format!("Binary not found at {:?}", backend_path);
- log::error!(
- "Server binary not found at expected path: {:?}",
- backend_path
- );
- return Err(LlamacppError::new(
- ErrorCode::BinaryNotFound,
- "The llama.cpp server binary could not be found.".into(),
- Some(err_msg),
- )
- .into());
- }
- Ok(server_path_buf)
-}
-
-/// Validate model path exists and update args with platform-appropriate path format
-pub fn validate_model_path(args: &mut Vec<String>) -> ServerResult<PathBuf> {
- let model_path_index = args.iter().position(|arg| arg == "-m").ok_or_else(|| {
- LlamacppError::new(
- ErrorCode::ModelLoadFailed,
- "Model path argument '-m' is missing.".into(),
- None,
- )
- })?;
-
- let model_path = args.get(model_path_index + 1).cloned().ok_or_else(|| {
- LlamacppError::new(
- ErrorCode::ModelLoadFailed,
- "Model path was not provided after '-m' flag.".into(),
- None,
- )
- })?;
-
- let model_path_pb = PathBuf::from(&model_path);
- if !model_path_pb.exists() {
- let err_msg = format!(
- "Invalid or inaccessible model path: {}",
- model_path_pb.display()
- );
- log::error!("{}", &err_msg);
- return Err(LlamacppError::new(
- ErrorCode::ModelFileNotFound,
- "The specified model file does not exist or is not accessible.".into(),
- Some(err_msg),
- )
- .into());
- }
-
- // Update the path in args with appropriate format for the platform
- #[cfg(windows)]
- {
- // use short path on Windows
- if let Some(short) = get_short_path(&model_path_pb) {
- args[model_path_index + 1] = short;
- } else {
- args[model_path_index + 1] = model_path_pb.display().to_string();
- }
- }
- #[cfg(not(windows))]
- {
- args[model_path_index + 1] = model_path_pb.display().to_string();
- }
-
- Ok(model_path_pb)
-}
-
-/// Validate mmproj path exists and update args with platform-appropriate path format
-pub fn validate_mmproj_path(args: &mut Vec<String>) -> ServerResult<Option<PathBuf>> {
- let mmproj_path_index = match args.iter().position(|arg| arg == "--mmproj") {
- Some(index) => index,
- None => return Ok(None), // mmproj is optional
- };
-
- let mmproj_path = args.get(mmproj_path_index + 1).cloned().ok_or_else(|| {
- LlamacppError::new(
- ErrorCode::ModelLoadFailed,
- "Mmproj path was not provided after '--mmproj' flag.".into(),
- None,
- )
- })?;
-
- let mmproj_path_pb = PathBuf::from(&mmproj_path);
- if !mmproj_path_pb.exists() {
- let err_msg = format!(
- "Invalid or inaccessible mmproj path: {}",
- mmproj_path_pb.display()
- );
- log::error!("{}", &err_msg);
- return Err(LlamacppError::new(
- ErrorCode::ModelFileNotFound,
- "The specified mmproj file does not exist or is not accessible.".into(),
- Some(err_msg),
- )
- .into());
- }
-
- #[cfg(windows)]
- {
- // use short path on Windows
- if let Some(short) = get_short_path(&mmproj_path_pb) {
- args[mmproj_path_index + 1] = short;
- } else {
- args[mmproj_path_index + 1] = mmproj_path_pb.display().to_string();
- }
- }
- #[cfg(not(windows))]
- {
- args[mmproj_path_index + 1] = mmproj_path_pb.display().to_string();
- }
-
- Ok(Some(mmproj_path_pb))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tempfile::NamedTempFile;
-
- #[test]
- fn test_validate_binary_path_existing() {
- let temp_file = NamedTempFile::new().unwrap();
- let path = temp_file.path().to_str().unwrap();
-
- let result = validate_binary_path(path);
- assert!(result.is_ok());
- assert_eq!(result.unwrap(), PathBuf::from(path));
- }
-
- #[test]
- fn test_validate_binary_path_nonexistent() {
- let nonexistent_path = "/tmp/definitely_does_not_exist_123456789";
- let result = validate_binary_path(nonexistent_path);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_validate_model_path_valid() {
- let temp_file = NamedTempFile::new().unwrap();
- let path = temp_file.path().to_str().unwrap();
-
- let mut args = vec!["-m".to_string(), path.to_string(), "--verbose".to_string()];
- let result = validate_model_path(&mut args);
-
- assert!(result.is_ok());
- assert_eq!(result.unwrap(), PathBuf::from(path));
- // Args should be updated with the path
- #[cfg(windows)]
- {
- // On Windows, the path might be converted to short path format
- // Just verify that the path in args[1] points to the same file
- assert!(PathBuf::from(&args[1]).exists());
- }
- #[cfg(not(windows))]
- {
- assert_eq!(args[1], temp_file.path().display().to_string());
- }
- }
-
- #[test]
- fn test_validate_model_path_missing_flag() {
- let mut args = vec!["--verbose".to_string(), "value".to_string()];
- let result = validate_model_path(&mut args);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_validate_model_path_missing_value() {
- let mut args = vec!["-m".to_string()];
- let result = validate_model_path(&mut args);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_validate_model_path_nonexistent_file() {
- let nonexistent_path = "/tmp/nonexistent_model_123456789.gguf";
- let mut args = vec!["-m".to_string(), nonexistent_path.to_string()];
- let result = validate_model_path(&mut args);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_validate_mmproj_path_valid() {
- let temp_file = NamedTempFile::new().unwrap();
- let path = temp_file.path().to_str().unwrap();
-
- let mut args = vec!["--mmproj".to_string(), path.to_string(), "--verbose".to_string()];
- let result = validate_mmproj_path(&mut args);
-
- assert!(result.is_ok());
- assert!(result.unwrap().is_some());
- // Args should be updated with the path
- #[cfg(windows)]
- {
- // On Windows, the path might be converted to short path format
- // Just verify that the path in args[1] points to the same file
- assert!(PathBuf::from(&args[1]).exists());
- }
- #[cfg(not(windows))]
- {
- assert_eq!(args[1], temp_file.path().display().to_string());
- }
- }
-
- #[test]
- fn test_validate_mmproj_path_missing() {
- let mut args = vec!["--verbose".to_string(), "value".to_string()];
- let result = validate_mmproj_path(&mut args);
- assert!(result.is_ok());
- assert!(result.unwrap().is_none()); // mmproj is optional
- }
-
- #[test]
- fn test_validate_mmproj_path_missing_value() {
- let mut args = vec!["--mmproj".to_string()];
- let result = validate_mmproj_path(&mut args);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_validate_mmproj_path_nonexistent_file() {
- let nonexistent_path = "/tmp/nonexistent_mmproj_123456789.gguf";
- let mut args = vec!["--mmproj".to_string(), nonexistent_path.to_string()];
- let result = validate_mmproj_path(&mut args);
- assert!(result.is_err());
- }
-
-
- #[test]
- fn test_validate_model_path_multiple_m_flags() {
- let temp_file = NamedTempFile::new().unwrap();
- let path = temp_file.path().to_str().unwrap();
-
- // Multiple -m flags - should use the first one
- let mut args = vec![
- "-m".to_string(),
- path.to_string(),
- "--verbose".to_string(),
- "-m".to_string(),
- "another_path".to_string()
- ];
- let result = validate_model_path(&mut args);
-
- assert!(result.is_ok());
- assert_eq!(result.unwrap(), PathBuf::from(path));
- }
-
- #[test]
- fn test_validate_mmproj_path_multiple_flags() {
- let temp_file = NamedTempFile::new().unwrap();
- let path = temp_file.path().to_str().unwrap();
-
- // Multiple --mmproj flags - should use the first one
- let mut args = vec![
- "--mmproj".to_string(),
- path.to_string(),
- "--verbose".to_string(),
- "--mmproj".to_string(),
- "another_path".to_string()
- ];
- let result = validate_mmproj_path(&mut args);
-
- assert!(result.is_ok());
- let result_path = result.unwrap();
- assert!(result_path.is_some());
- assert_eq!(result_path.unwrap(), PathBuf::from(path));
- }
-}
+use std::path::PathBuf;
+
+use crate::error::{ErrorCode, LlamacppError, ServerResult};
+
+pub fn validate_binary_path(backend_path: &str) -> ServerResult<PathBuf> {
+ let server_path_buf = PathBuf::from(backend_path);
+ if !server_path_buf.exists() {
+ let err_msg = format!("Binary not found at {:?}", backend_path);
+ log::error!(
+ "Server binary not found at expected path: {:?}",
+ backend_path
+ );
+ return Err(LlamacppError::new(
+ ErrorCode::BinaryNotFound,
+ "The llama.cpp server binary could not be found.".into(),
+ Some(err_msg),
+ )
+ .into());
+ }
+ Ok(server_path_buf)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::NamedTempFile;
+
+ #[test]
+ fn test_validate_binary_path_existing() {
+ let temp_file = NamedTempFile::new().unwrap();
+ let path = temp_file.path().to_str().unwrap();
+ let result = validate_binary_path(path);
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), PathBuf::from(path));
+ }
+
+ #[test]
+ fn test_validate_binary_path_nonexistent() {
+ let nonexistent_path = "/tmp/definitely_does_not_exist_123456789";
+ let result = validate_binary_path(nonexistent_path);
+ assert!(result.is_err());
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/process.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/process.rs
index 06d83fcb0..695204be3 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/process.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/process.rs
@@ -1,55 +1,3 @@
-use std::collections::HashSet;
-use sysinfo::{Pid, System};
-use tauri::{Manager, Runtime, State};
-
-use crate::state::{LlamacppState, SessionInfo};
-use jan_utils::generate_random_port;
-
-/// Check if a process is running by PID
-pub async fn is_process_running_by_pid<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- pid: i32,
-) -> Result<bool, String> {
- let mut system = System::new();
- system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
- let process_pid = Pid::from(pid as usize);
- let alive = system.process(process_pid).is_some();
-
- if !alive {
- let state: State<LlamacppState> = app_handle.state();
- let mut map = state.llama_server_process.lock().await;
- map.remove(&pid);
- }
-
- Ok(alive)
-}
-
-/// Get a random available port, avoiding ports used by existing sessions
-pub async fn get_random_available_port<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<u16, String> {
- // Get all active ports from sessions
- let state: State<LlamacppState> = app_handle.state();
- let map = state.llama_server_process.lock().await;
-
- let used_ports: HashSet<u16> = map
- .values()
- .filter_map(|session| {
- // Convert valid ports to u16 (filter out placeholder ports like -1)
- if session.info.port > 0 && session.info.port <= u16::MAX as i32 {
- Some(session.info.port as u16)
- } else {
- None
- }
- })
- .collect();
-
- drop(map); // unlock early
-
- generate_random_port(&used_ports)
-}
-
-/// Gracefully terminate a process on Unix systems
#[cfg(unix)]
pub async fn graceful_terminate_process(child: &mut tokio::process::Child) {
use nix::sys::signal::{kill, Signal};
@@ -77,18 +25,18 @@ pub async fn graceful_terminate_process(child: &mut tokio::process::Child) {
}
}
-/// Force terminate a process on Windows
#[cfg(all(windows, target_arch = "x86_64"))]
pub async fn force_terminate_process(child: &mut tokio::process::Child) {
+ // Graceful shutdown is not implemented on Windows: llama-server's console
+ // handler only reacts to CTRL_C_EVENT (server.cpp), and
+ // GenerateConsoleCtrlEvent(CTRL_C_EVENT, pid) is only deliverable with
+ // group ID 0 — which would also terminate this process. CTRL_BREAK_EVENT
+ // can target a specific group but the server ignores it.
if let Some(raw_pid) = child.id() {
log::warn!(
"gracefully killing is unsupported on Windows, force-killing PID {}",
raw_pid
);
-
- // Since we know a graceful shutdown doesn't work and there are no child processes
- // to worry about, we can use `child.kill()` directly. On Windows, this is
- // a forceful termination via the `TerminateProcess` API.
if let Err(e) = child.kill().await {
log::error!(
"Failed to send kill signal to PID {}: {}. It may have already terminated.",
@@ -96,7 +44,6 @@ pub async fn force_terminate_process(child: &mut tokio::process::Child) {
e
);
}
-
match child.wait().await {
Ok(status) => log::info!(
"process {} has been terminated. Final exit status: {}",
@@ -111,44 +58,3 @@ pub async fn force_terminate_process(child: &mut tokio::process::Child) {
}
}
}
-
-/// Find a session by model ID
-pub async fn find_session_by_model_id<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- model_id: &str,
-) -> Result<Option<SessionInfo>, String> {
- let state: State<LlamacppState> = app_handle.state();
- let map = state.llama_server_process.lock().await;
-
- let session_info = map
- .values()
- .find(|backend_session| backend_session.info.model_id == model_id)
- .map(|backend_session| backend_session.info.clone());
-
- Ok(session_info)
-}
-
-/// Get all loaded model IDs
-pub async fn get_all_loaded_model_ids<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<Vec<String>, String> {
- let state: State<LlamacppState> = app_handle.state();
- let map = state.llama_server_process.lock().await;
-
- let model_ids = map
- .values()
- .map(|backend_session| backend_session.info.model_id.clone())
- .collect();
-
- Ok(model_ids)
-}
-
-/// Get all active sessions
-pub async fn get_all_active_sessions<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
-) -> Result<Vec<SessionInfo>, String> {
- let state: State<LlamacppState> = app_handle.state();
- let map = state.llama_server_process.lock().await;
- let sessions: Vec<SessionInfo> = map.values().map(|s| s.info.clone()).collect();
- Ok(sessions)
-}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
new file mode 100644
index 000000000..e670ee825
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
@@ -0,0 +1,368 @@
+//! Router-mode lifecycle for `llama-server`.
+//!
+//! Phase 1 of the router refactor: spawn / health-check / shut down a single
+//! `llama-server` instance running in router mode (no `-m` / `-hf` flag, models
+//! are loaded on demand via the HTTP API). This module is intentionally
+//! standalone — it does NOT touch the existing per-model session map.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::time::Duration;
+
+use tokio::io::{AsyncBufReadExt, BufReader};
+use tokio::process::{Child, Command};
+use tokio::sync::mpsc;
+use tokio::time::Instant;
+
+use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};
+use jan_utils::{binary_requires_cuda, find_cuda_paths, setup_library_path, setup_windows_process_flags};
+
+/// A handle to a running router-mode `llama-server` process.
+pub struct RouterHandle {
+ pub child: Child,
+ pub port: u16,
+ pub api_key: String,
+ pub pid: u32,
+}
+
+/// Build the argv for router mode. Pure / unit-testable.
+///
+/// `models_max == 0` is forwarded as-is; the upstream README documents 0 as
+/// "unlimited" — we let the server interpret that.
+pub fn router_args(
+ preset_path: &Path,
+ port: u16,
+ api_key: &str,
+ models_max: u32,
+ default_args: &[String],
+) -> Vec<String> {
+ let mut args: Vec<String> = vec![
+ "--models-preset".to_string(),
+ preset_path.to_string_lossy().to_string(),
+ "--models-max".to_string(),
+ models_max.to_string(),
+ "--host".to_string(),
+ "127.0.0.1".to_string(),
+ "--port".to_string(),
+ port.to_string(),
+ "--api-key".to_string(),
+ api_key.to_string(),
+ "--no-webui".to_string(),
+ ];
+ args.extend(default_args.iter().cloned());
+ args
+}
+
+/// Spawn `llama-server` in router mode and wait for it to become ready.
+///
+/// On readiness-detection failure or spawn failure, the child is killed before
+/// returning the error.
+pub async fn start_router(
+ backend_exe: PathBuf,
+ preset_path: PathBuf,
+ port: u16,
+ api_key: String,
+ models_max: u32,
+ default_args: Vec<String>,
+ envs: HashMap<String, String>,
+) -> Result<RouterHandle, ServerError> {
+ log::info!(
+ "Starting llama-server in router mode: exe={:?} preset={:?} port={} models_max={}",
+ backend_exe,
+ preset_path,
+ port,
+ models_max
+ );
+
+ let args = router_args(&preset_path, port, &api_key, models_max, &default_args);
+ log::info!("Router argv: {:?}", args);
+
+ // Resolve readiness timeout (seconds). Match existing convention by
+ // honoring LLAMA_ARG_TIMEOUT if set in the env map; otherwise default 60s.
+ let timeout_secs: u64 = envs
+ .get("LLAMA_ARG_TIMEOUT")
+ .and_then(|s| s.parse::<u64>().ok())
+ .unwrap_or(60);
+
+ let mut command = Command::new(&backend_exe);
+ command.args(&args);
+ command.envs(&envs);
+ command.stdout(Stdio::piped());
+ command.stderr(Stdio::piped());
+ command.kill_on_drop(true);
+ setup_windows_process_flags(&mut command);
+
+ let cuda = find_cuda_paths();
+ if cuda.lib_paths.is_empty()
+ && cuda.bin_paths.is_empty()
+ && binary_requires_cuda(&backend_exe)
+ {
+ log::warn!(
+ "llama.cpp router backend appears to require CUDA, but CUDA not found. \
+ Process may fail to start."
+ );
+ }
+ setup_library_path(backend_exe.parent(), &cuda, &mut command);
+
+ let mut child = command.spawn().map_err(ServerError::Io)?;
+
+ let stderr = child.stderr.take().expect("stderr was piped");
+ let stdout = child.stdout.take().expect("stdout was piped");
+
+ let (ready_tx, mut ready_rx) = mpsc::channel::<bool>(1);
+
+ // stdout reader (replicates the marker-detection patterns in commands.rs)
+ let stdout_ready_tx = ready_tx.clone();
+ let _stdout_task = tokio::spawn(async move {
+ let mut reader = BufReader::new(stdout);
+ let mut byte_buffer = Vec::new();
+ loop {
+ byte_buffer.clear();
+ match reader.read_until(b'\n', &mut byte_buffer).await {
+ Ok(0) => break,
+ Ok(_) => {
+ let line = String::from_utf8_lossy(&byte_buffer);
+ let line = line.trim_end();
+ if !line.is_empty() {
+ log::info!("[llamacpp-router stdout] {}", line);
+ }
+ let line_lower = line.to_lowercase();
+ if line_lower.contains("http server listening")
+ || line_lower.contains("server is listening on")
+ || line_lower.contains("server listening on")
+ || line_lower.contains("starting the main loop")
+ {
+ let _ = stdout_ready_tx.send(true).await;
+ }
+ }
+ Err(e) => {
+ log::error!("Error reading router stdout: {}", e);
+ break;
+ }
+ }
+ }
+ });
+
+ let stderr_task = tokio::spawn(async move {
+ let mut reader = BufReader::new(stderr);
+ let mut byte_buffer = Vec::new();
+ let mut stderr_buffer = String::new();
+ loop {
+ byte_buffer.clear();
+ match reader.read_until(b'\n', &mut byte_buffer).await {
+ Ok(0) => break,
+ Ok(_) => {
+ let line = String::from_utf8_lossy(&byte_buffer);
+ let line = line.trim_end();
+ if !line.is_empty() {
+ stderr_buffer.push_str(line);
+ stderr_buffer.push('\n');
+ log::info!("[llamacpp-router] {}", line);
+ let line_lower = line.to_lowercase();
+ if line_lower.contains("server is listening on")
+ || line_lower.contains("server listening on")
+ || line_lower.contains("starting the main loop")
+ || line_lower.contains("http server listening")
+ {
+ let _ = ready_tx.send(true).await;
+ }
+ }
+ }
+ Err(e) => {
+ log::error!("Error reading router stderr: {}", e);
+ break;
+ }
+ }
+ }
+ stderr_buffer
+ });
+
+ // Early-exit check.
+ if let Some(status) = child.try_wait()? {
+ let stderr_output = stderr_task.await.unwrap_or_default();
+ log::error!("llama-server router exited early with status {:?}", status);
+ return Err(LlamacppError::from_stderr(&stderr_output).into());
+ }
+
+ let timeout_duration = Duration::from_secs(timeout_secs);
+ let start_time = Instant::now();
+ log::info!("Waiting for router to be ready (timeout={}s)...", timeout_secs);
+
+ loop {
+ tokio::select! {
+ Some(true) = ready_rx.recv() => {
+ log::info!("llama-server router is ready.");
+ break;
+ }
+ _ = tokio::time::sleep(Duration::from_millis(50)) => {
+ if let Some(status) = child.try_wait()? {
+ let stderr_output = stderr_task.await.unwrap_or_default();
+ log::error!("llama-server router exited before readiness: {:?}", status);
+ return Err(LlamacppError::from_stderr(&stderr_output).into());
+ }
+ if start_time.elapsed() > timeout_duration {
+ log::error!("Timeout waiting for router to be ready");
+ let _ = child.kill().await;
+ let stderr_output = stderr_task.await.unwrap_or_default();
+ return Err(LlamacppError::new(
+ ErrorCode::ModelLoadTimedOut,
+ "Router took too long to start and timed out.".into(),
+ Some(format!(
+ "Timeout: {}s\n\nStderr:\n{}",
+ timeout_duration.as_secs(),
+ stderr_output
+ )),
+ )
+ .into());
+ }
+ }
+ }
+ }
+
+ let pid = child.id().unwrap_or(0);
+ Ok(RouterHandle {
+ child,
+ port,
+ api_key,
+ pid,
+ })
+}
+
+/// Gracefully shut down a router process.
+///
+/// Unloads loaded models over HTTP first so children flush GPU / KV cache
+/// state, then terminates the router itself (SIGTERM→SIGKILL on Unix, forced
+/// kill on Windows).
+pub async fn stop_router(mut handle: RouterHandle) -> ServerResult<()> {
+ unload_all_models_best_effort(handle.port, &handle.api_key).await;
+
+ #[cfg(unix)]
+ {
+ crate::process::graceful_terminate_process(&mut handle.child).await;
+ }
+ #[cfg(all(windows, target_arch = "x86_64"))]
+ {
+ crate::process::force_terminate_process(&mut handle.child).await;
+ }
+ #[cfg(not(any(unix, all(windows, target_arch = "x86_64"))))]
+ {
+ let _ = handle.child.kill().await;
+ let _ = handle.child.wait().await;
+ }
+ Ok(())
+}
+
+async fn unload_all_models_best_effort(port: u16, api_key: &str) {
+ let overall = Duration::from_secs(10);
+ let _ = tokio::time::timeout(overall, async {
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(5))
+ .build()
+ {
+ Ok(c) => c,
+ Err(e) => {
+ log::warn!("stop_router: failed to build http client: {}", e);
+ return;
+ }
+ };
+
+ let list_url = format!("http://127.0.0.1:{}/models", port);
+ let resp = match client.get(&list_url).bearer_auth(api_key).send().await {
+ Ok(r) => r,
+ Err(e) => {
+ log::warn!("stop_router: GET /models failed (router likely already down): {}", e);
+ return;
+ }
+ };
+ let json: serde_json::Value = match resp.json().await {
+ Ok(v) => v,
+ Err(e) => {
+ log::warn!("stop_router: invalid JSON from /models: {}", e);
+ return;
+ }
+ };
+ let ids: Vec<String> = json
+ .get("data")
+ .and_then(|d| d.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter(|m| {
+ m.get("status")
+ .and_then(|s| s.get("value"))
+ .and_then(|v| v.as_str())
+ .map(|s| matches!(s, "loaded" | "loading"))
+ .unwrap_or(false)
+ })
+ .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+
+ if ids.is_empty() {
+ return;
+ }
+ log::info!("stop_router: unloading {} model(s) before shutdown", ids.len());
+
+ let unload_url = format!("http://127.0.0.1:{}/models/unload", port);
+ let tasks = ids.into_iter().map(|id| {
+ let client = client.clone();
+ let url = unload_url.clone();
+ let key = api_key.to_string();
+ tokio::spawn(async move {
+ let body = serde_json::json!({ "model": id });
+ match client.post(&url).bearer_auth(&key).json(&body).send().await {
+ Ok(r) if r.status().is_success() => {}
+ Ok(r) => log::warn!("stop_router: unload {} returned {}", id, r.status()),
+ Err(e) => log::warn!("stop_router: unload {} failed: {}", id, e),
+ }
+ })
+ });
+ for t in tasks {
+ let _ = t.await;
+ }
+ })
+ .await;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ #[test]
+ fn router_args_contains_required_flags() {
+ let preset = PathBuf::from("/tmp/preset.ini");
+ let args = router_args(&preset, 1337, "secret-key", 4, &[]);
+
+ // Required flags present
+ let joined = args.join(" ");
+ assert!(joined.contains("--models-preset /tmp/preset.ini"));
+ assert!(!args.iter().any(|a| a == "--no-models-autoload"));
+ assert!(joined.contains("--models-max 4"));
+ assert!(joined.contains("--host 127.0.0.1"));
+ assert!(joined.contains("--port 1337"));
+ assert!(joined.contains("--api-key secret-key"));
+ assert!(args.iter().any(|a| a == "--no-webui"));
+ }
+
+ #[test]
+ fn router_args_appends_default_args_in_order() {
+ let preset = PathBuf::from("/tmp/p.ini");
+ let extras = vec!["--threads".to_string(), "8".to_string(), "--metrics".to_string()];
+ let args = router_args(&preset, 8080, "k", 2, &extras);
+
+ // The defaults must appear after our base flags, preserving order.
+ let last_three: Vec<&String> = args.iter().rev().take(3).collect::<Vec<_>>().into_iter().rev().collect();
+ assert_eq!(last_three, vec![&extras[0], &extras[1], &extras[2]]);
+ }
+
+ #[test]
+ fn router_args_passes_through_models_max_zero() {
+ // README: 0 means unlimited; we forward as-is.
+ let preset = PathBuf::from("/tmp/p.ini");
+ let args = router_args(&preset, 8080, "k", 0, &[]);
+ let joined = args.join(" ");
+ assert!(joined.contains("--models-max 0"));
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
index c827942f3..28b96a76e 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs
@@ -1,50 +1,23 @@
use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use std::sync::Arc;
-use tokio::process::Child;
use tokio::sync::Mutex;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
- pub pid: i32, // opaque handle for unload/chat
- pub port: i32, // llama-server output port
+ pub pid: i32,
+ pub port: i32,
pub model_id: String,
- pub model_path: String, // path of the loaded model
pub is_embedding: bool,
pub api_key: String,
- #[serde(default)]
- pub mmproj_path: Option<String>,
}
-#[derive(Debug, Clone)]
-pub struct SessionLaunchConfig {
- pub backend_path: String,
- pub model_id: String,
- pub model_path: String,
- pub port: u16,
- pub config: crate::args::LlamacppConfig,
- pub envs: HashMap<String, String>,
- pub mmproj_path: Option<String>,
- pub is_embedding: bool,
- pub timeout: u64,
-}
-
-pub struct LLamaBackendSession {
- pub child: Child,
- pub info: SessionInfo,
- pub launch: SessionLaunchConfig,
- pub restart_attempt_timestamps_ms: Vec<u64>,
-}
-
-/// LlamaCpp plugin state
pub struct LlamacppState {
- pub llama_server_process: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ pub router: Mutex<Option<crate::router::RouterHandle>>,
}
impl Default for LlamacppState {
fn default() -> Self {
Self {
- llama_server_process: Arc::new(Mutex::new(HashMap::new())),
+ router: Mutex::new(None),
}
}
}
diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rs
index c3650afd9..7bcdf1ff8 100644
--- a/src-tauri/src/bin/jan-cli.rs
+++ b/src-tauri/src/bin/jan-cli.rs
@@ -16,10 +16,12 @@ use app_lib::core::cli::{
cli_delete_thread, cli_get_data_folder, cli_get_thread,
cli_list_messages, cli_list_threads, discover_llamacpp_binary,
discover_mlx_binary, download_hf_model, fetch_hf_gguf_files, init_llamacpp_state,
- init_mlx_state, list_models, load_llama_model_impl, load_mlx_model_impl,
+ init_mlx_state, list_models, load_mlx_model_impl,
looks_like_hf_repo, resolve_model_by_id, resolve_model_engine, HfFileInfo,
- LlamacppConfig, MlxConfig,
+ MlxConfig,
};
+use tauri_plugin_llamacpp::router as llamacpp_router;
+use tauri_plugin_llamacpp::state::LlamacppState;
use std::path::PathBuf;
// ── Top-level CLI ──────────────────────────────────────────────────────────
@@ -928,24 +930,21 @@ async fn handle_serve(args: ServeArgs) {
},
};
+ let _ = (n_gpu_layers, ctx_size, fit, threads, resolved_model_path, resolved_mmproj);
let llama_state = Arc::new(init_llamacpp_state());
let mut envs: HashMap<String, String> = HashMap::new();
if !api_key.is_empty() {
- envs.insert("LLAMA_API_KEY".to_string(), api_key);
+ envs.insert("LLAMA_API_KEY".to_string(), api_key.clone());
}
- let config = build_llamacpp_config(n_gpu_layers, ctx_size, timeout as i32, fit, threads);
-
- match load_llama_model_impl(
- llama_state.llama_server_process.clone(),
+ match ensure_router_and_load(
+ &llama_state,
&bin_path,
- model_id.clone(),
- resolved_model_path,
+ &model_id,
port,
- config,
- envs,
- resolved_mmproj,
+ api_key,
embedding,
+ envs,
timeout,
)
.await
@@ -960,17 +959,105 @@ async fn handle_serve(args: ServeArgs) {
wait_for_shutdown(info.pid).await;
}
Err(e) => {
- finish_progress(pb, format!("✗ Failed to load {model_id}"));
- eprintln!(
- "\n{}",
- serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}"))
- );
+ finish_progress(pb, format!("✗ Failed to load {model_id}: {e}"));
std::process::exit(1);
}
}
}
}
+struct RouterServeInfo {
+ pid: i32,
+ port: u16,
+ #[allow(dead_code)]
+ api_key: String,
+}
+
+async fn ensure_router_and_load(
+ llama_state: &std::sync::Arc<LlamacppState>,
+ bin_path: &str,
+ model_id: &str,
+ port: u16,
+ api_key: String,
+ is_embedding: bool,
+ envs: HashMap<String, String>,
+ timeout: u64,
+) -> Result<RouterServeInfo, String> {
+ if is_embedding {
+ return Err(
+ "--embedding on the llamacpp engine requires router preset support; \
+ use the desktop UI to load embedding models for now."
+ .to_string(),
+ );
+ }
+
+ let preset_path = cli_get_data_folder()
+ .join("llamacpp")
+ .join("router.preset.ini");
+ if !preset_path.exists() {
+ return Err(format!(
+ "Router preset not found at {}; run the desktop app once to generate it, \
+ or implement a Rust preset generator.",
+ preset_path.display()
+ ));
+ }
+
+ let already_running = { llama_state.router.lock().await.is_some() };
+ if !already_running {
+ let router_api_key = if api_key.is_empty() {
+ uuid::Uuid::new_v4().to_string()
+ } else {
+ api_key.clone()
+ };
+ let mut router_envs = envs.clone();
+ router_envs
+ .entry("LLAMA_ARG_TIMEOUT".to_string())
+ .or_insert_with(|| timeout.to_string());
+
+ let handle = llamacpp_router::start_router(
+ std::path::PathBuf::from(bin_path),
+ preset_path,
+ port,
+ router_api_key,
+ 0,
+ Vec::new(),
+ router_envs,
+ )
+ .await
+ .map_err(|e| format!("{e:?}"))?;
+ let mut guard = llama_state.router.lock().await;
+ *guard = Some(handle);
+ }
+
+ let (router_port, router_key, router_pid) = {
+ let guard = llama_state.router.lock().await;
+ let h = guard
+ .as_ref()
+ .ok_or_else(|| "Router unexpectedly missing after start".to_string())?;
+ (h.port, h.api_key.clone(), h.pid)
+ };
+
+ let url = format!("http://127.0.0.1:{router_port}/models/load");
+ let resp = reqwest::Client::new()
+ .post(&url)
+ .header("Authorization", format!("Bearer {router_key}"))
+ .json(&serde_json::json!({ "model": model_id }))
+ .send()
+ .await
+ .map_err(|e| format!("Failed to POST {url}: {e}"))?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("Router /models/load returned {status}: {body}"));
+ }
+
+ Ok(RouterServeInfo {
+ pid: router_pid as i32,
+ port: router_port,
+ api_key: router_key,
+ })
+}
+
/// Block until Ctrl+C, then terminate the child process.
async fn wait_for_shutdown(pid: i32) {
tokio::signal::ctrl_c().await.ok();
@@ -1265,85 +1352,29 @@ async fn start_model_server(
std::process::exit(1);
}
};
+ let _ = (n_gpu_layers, ctx_size, fit, model_path, mmproj);
let llama_state = Arc::new(init_llamacpp_state());
let mut envs: HashMap<String, String> = HashMap::new();
if !api_key.is_empty() { envs.insert("LLAMA_API_KEY".to_string(), api_key.clone()); }
- // When fit is on, let llama.cpp decide the context size automatically.
- let effective_ctx_size = if fit { 0 } else { ctx_size };
- let config = build_llamacpp_config(n_gpu_layers, effective_ctx_size, 120, fit, 0);
- let info = match load_llama_model_impl(
- llama_state.llama_server_process.clone(),
+ let info = match ensure_router_and_load(
+ &llama_state,
&bin_path,
- model_id.to_string(),
- model_path,
+ model_id,
port,
- config,
- envs,
- mmproj.map(|p| p.to_string_lossy().into_owned()),
+ api_key,
false,
+ envs,
120,
).await {
Ok(info) => info,
Err(e) => {
- finish_progress(pb, format!("✗ Failed to load {model_id}"));
- eprintln!("{}", serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}")));
+ finish_progress(pb, format!("✗ Failed to load {model_id}: {e}"));
std::process::exit(1);
}
};
let url = format!("http://127.0.0.1:{}", info.port);
finish_progress(pb, format!("✓ {model_id} ready · {url}"));
- (info.pid, info.port as u16)
+ (info.pid, info.port)
}
}
-// ── LlamaCPP config builder ────────────────────────────────────────────────
-
-/// Build a `LlamacppConfig` with the values the CLI controls; everything else
-/// stays at a sensible default.
-fn build_llamacpp_config(n_gpu_layers: i32, ctx_size: i32, timeout: i32, fit: bool, threads: i32) -> LlamacppConfig {
- LlamacppConfig {
- version_backend: "cli/llama-server".to_string(),
- auto_update_engine: false,
- auto_unload: false,
- auto_restart_on_crash: false,
- timeout,
- llamacpp_env: String::new(),
- fit,
- fit_target: String::new(),
- fit_ctx: String::new(),
- chat_template: String::new(),
- n_gpu_layers,
- offload_mmproj: true,
- cpu_moe: false,
- n_cpu_moe: 0,
- override_tensor_buffer_t: String::new(),
- ctx_size,
- threads,
- threads_batch: 0,
- n_predict: -1,
- batch_size: 512,
- ubatch_size: 512,
- device: String::new(),
- split_mode: String::new(),
- main_gpu: 0,
- flash_attn: "auto".to_string(),
- cont_batching: true,
- no_mmap: false,
- mlock: false,
- no_kv_offload: false,
- cache_type_k: "q8_0".to_string(),
- cache_type_v: "q8_0".to_string(),
- defrag_thold: -1.0,
- rope_scaling: String::new(),
- rope_scale: 0.0,
- rope_freq_base: 0.0,
- rope_freq_scale: 0.0,
- ctx_shift: false,
- parallel: 1,
- reasoning: "auto".to_string(),
- cache_ram: -1,
- cache_reuse: 0,
- swa_full: false,
- keep: 0,
- }
-}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index f4e65df1d..1d9241c78 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -16,8 +16,6 @@ use crate::core::threads::{
use tauri_plugin_llamacpp::state::LlamacppState;
use tauri_plugin_mlx::state::MlxState;
-// Re-export impl functions and config types so the binary can call them directly
-pub use tauri_plugin_llamacpp::{load_llama_model_impl, LlamacppConfig};
pub use tauri_plugin_mlx::{load_mlx_model_impl, MlxConfig};
pub use tauri_plugin_mlx::state::SessionInfo;
@@ -107,7 +105,7 @@ pub async fn cli_start_server(
) -> Result<u16, String> {
proxy::start_server(
app_state.server_handle.clone(),
- llama_state.llama_server_process.clone(),
+ llama_state.clone(),
mlx_state.mlx_server_process.clone(),
host,
port,
diff --git a/src-tauri/src/core/server/commands.rs b/src-tauri/src/core/server/commands.rs
index 171ac533a..232901c3f 100644
--- a/src-tauri/src/core/server/commands.rs
+++ b/src-tauri/src/core/server/commands.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use tauri::{AppHandle, Manager, Runtime, State};
use tauri_plugin_llamacpp::state::LlamacppState;
use tauri_plugin_mlx::state::MlxState;
@@ -34,15 +36,15 @@ pub async fn start_server<R: Runtime>(
enable_server_tool_execution,
} = config;
let server_handle = state.server_handle.clone();
- let llama_state: State<LlamacppState> = app_handle.state();
- let sessions = llama_state.llama_server_process.clone();
+ let llama_state: State<Arc<LlamacppState>> = app_handle.state();
+ let llama_state_arc = llama_state.inner().clone();
let mlx_state: State<MlxState> = app_handle.state();
let mlx_sessions = mlx_state.mlx_server_process.clone();
let actual_port = proxy::start_server(
server_handle,
- sessions,
+ llama_state_arc,
mlx_sessions,
host,
port,
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index c69eec752..a0fd54d14 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -11,7 +11,7 @@ use std::fs;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
-use tauri_plugin_llamacpp::LLamaBackendSession;
+use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::Mutex;
use crate::core::{
@@ -507,7 +507,7 @@ pub fn get_destination_path(original_path: &str, prefix: &str) -> String {
remove_prefix(original_path, prefix)
}
-use tauri_plugin_mlx::state::{MlxBackendSession, SessionInfo};
+use tauri_plugin_mlx::state::MlxBackendSession;
use rmcp::model::{CallToolRequestParam, CallToolResult};
@@ -617,15 +617,71 @@ fn mcp_call_result_to_string(result: &CallToolResult) -> String {
}
}
+async fn router_upstream(
+ llama_state: &LlamacppState,
+ destination_path: &str,
+) -> Option<(String, String)> {
+ let guard = llama_state.router.lock().await;
+ guard.as_ref().map(|h| {
+ (
+ format!("http://127.0.0.1:{}/v1{}", h.port, destination_path),
+ h.api_key.clone(),
+ )
+ })
+}
+
+async fn router_list_models(llama_state: &LlamacppState, client: &Client) -> Vec<String> {
+ let (url, key) = {
+ let guard = llama_state.router.lock().await;
+ match guard.as_ref() {
+ Some(h) => (
+ format!("http://127.0.0.1:{}/v1/models", h.port),
+ h.api_key.clone(),
+ ),
+ None => return Vec::new(),
+ }
+ };
+ let resp = match client
+ .get(&url)
+ .header("Authorization", format!("Bearer {key}"))
+ .send()
+ .await
+ {
+ Ok(r) => r,
+ Err(e) => {
+ log::warn!("Failed to query router /v1/models: {e}");
+ return Vec::new();
+ }
+ };
+ if !resp.status().is_success() {
+ return Vec::new();
+ }
+ let json: serde_json::Value = match resp.json().await {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ json.get("data")
+ .and_then(|d| d.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(str::to_owned))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+async fn router_first_model(llama_state: &LlamacppState, client: &Client) -> Option<String> {
+ router_list_models(llama_state, client).await.into_iter().next()
+}
+
async fn resolve_upstream_for_model(
model_id: &str,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
- sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
) -> Result<(String, Vec<String>), String> {
let destination_path = "/chat/completions";
- // Prefer remote provider if model is registered there.
let pc = provider_configs.lock().await;
let provider_name = pc
.iter()
@@ -654,17 +710,6 @@ async fn resolve_upstream_for_model(
}
}
- // Fall back to local sessions.
- let sessions_guard = sessions.lock().await;
- if let Some(session) = sessions_guard.values().find(|s| s.info.model_id == model_id) {
- let target_port = session.info.port;
- return Ok((
- format!("http://127.0.0.1:{target_port}/v1{destination_path}"),
- vec![session.info.api_key.clone()],
- ));
- }
- drop(sessions_guard);
-
let mlx_guard = mlx_sessions.lock().await;
if let Some(info) = mlx_guard.values().find(|s| s.info.model_id == model_id) {
let target_port = info.info.port;
@@ -673,6 +718,11 @@ async fn resolve_upstream_for_model(
vec![info.info.api_key.clone()],
));
}
+ drop(mlx_guard);
+
+ if let Some((url, key)) = router_upstream(&llama_state, destination_path).await {
+ return Ok((url, vec![key]));
+ }
Err(format!("No upstream session found for model '{model_id}'"))
}
@@ -873,7 +923,7 @@ async fn run_server_side_openai_orchestration(
json_body: &serde_json::Value,
client: &Client,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
- sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
mcp_servers: SharedMcpServers,
mcp_settings: Arc<Mutex<McpSettings>>,
@@ -911,9 +961,9 @@ async fn run_server_side_openai_orchestration(
}
}
if model_id.is_none() {
- let sessions_guard = sessions.lock().await;
- model_id = sessions_guard.values().next().map(|s| s.info.model_id.clone());
- drop(sessions_guard);
+ if let Some(first) = router_first_model(&llama_state, client).await {
+ model_id = Some(first);
+ }
}
if model_id.is_none() {
let mlx_guard = mlx_sessions.lock().await;
@@ -927,7 +977,7 @@ async fn run_server_side_openai_orchestration(
let (upstream_url, session_api_keys) = resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
- sessions.clone(),
+ llama_state.clone(),
mlx_sessions.clone(),
)
.await?;
@@ -1022,7 +1072,7 @@ async fn proxy_request(
req: Request<Body>,
client: Client,
config: ProxyConfig,
- sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
mcp_servers: SharedMcpServers,
@@ -1352,7 +1402,7 @@ async fn proxy_request(
&openai_body,
&client,
provider_configs.clone(),
- sessions.clone(),
+ llama_state.clone(),
mlx_sessions.clone(),
mcp_servers.clone(),
mcp_settings.clone(),
@@ -1423,12 +1473,6 @@ async fn proxy_request(
session_api_keys = provider_cfg.bearer_key_chain();
}
} else {
- // No remote provider, try local sessions
- let sessions_guard = sessions.lock().await;
- let llama_session = sessions_guard
- .values()
- .find(|s| s.info.model_id == model_id);
-
let mlx_session_info = {
let mlx_guard = mlx_sessions.lock().await;
mlx_guard
@@ -1437,16 +1481,16 @@ async fn proxy_request(
.map(|s| s.info.clone())
};
- if let Some(session) = llama_session {
- let target_port = session.info.port;
- session_api_keys = vec![session.info.api_key.clone()];
- target_base_url =
- Some(format!("http://127.0.0.1:{}/v1/messages", target_port));
- } else if let Some(info) = mlx_session_info {
+ if let Some(info) = mlx_session_info {
let target_port = info.port;
session_api_keys = vec![info.api_key.clone()];
target_base_url =
Some(format!("http://127.0.0.1:{}/v1/messages", target_port));
+ } else if let Some((url, key)) =
+ router_upstream(&llama_state, "/messages").await
+ {
+ session_api_keys = vec![key];
+ target_base_url = Some(url);
} else {
log::warn!("No running session found for model_id: {model_id}");
let mut error_response =
@@ -1610,7 +1654,7 @@ async fn proxy_request(
// Resolve model to use for orchestration.
let model_override = json_body.get("model").and_then(|v| v.as_str());
- let mut model_id: Option<String> = None;
+ let mut model_id: Option<String>;
if let Some(ov) = model_override {
model_id = Some(ov.to_string());
@@ -1619,26 +1663,14 @@ async fn proxy_request(
if !trimmed.is_empty() && trimmed != "*" {
model_id = Some(trimmed.to_string());
} else {
- // Fall back to the first available local session model.
- let sessions_guard = sessions.lock().await;
- if let Some(session) = sessions_guard.values().next() {
- model_id = Some(session.info.model_id.clone());
- }
- drop(sessions_guard);
-
+ model_id = router_first_model(&llama_state, &client).await;
if model_id.is_none() {
let mlx_guard = mlx_sessions.lock().await;
model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
}
}
} else {
- // Fall back to the first available local session model.
- let sessions_guard = sessions.lock().await;
- if let Some(session) = sessions_guard.values().next() {
- model_id = Some(session.info.model_id.clone());
- }
- drop(sessions_guard);
-
+ model_id = router_first_model(&llama_state, &client).await;
if model_id.is_none() {
let mlx_guard = mlx_sessions.lock().await;
model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
@@ -1682,7 +1714,7 @@ async fn proxy_request(
let (upstream_url, session_api_keys) = match resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
- sessions.clone(),
+ llama_state.clone(),
mlx_sessions.clone(),
)
.await
@@ -1881,7 +1913,7 @@ async fn proxy_request(
&json_body,
&client,
provider_configs.clone(),
- sessions.clone(),
+ llama_state.clone(),
mlx_sessions.clone(),
mcp_servers.clone(),
mcp_settings.clone(),
@@ -1972,38 +2004,20 @@ async fn proxy_request(
log::error!("Provider config not found for '{provider}'");
}
} else {
- // No remote provider found, check for local session
- let sessions_guard = sessions.lock().await;
-
- // Use original model_id for local session lookup
let sessions_find_model = model_id;
- // Check both llama.cpp and MLX sessions
- let llama_session = sessions_guard
- .values()
- .find(|s| s.info.model_id == sessions_find_model);
-
- let (mlx_session_info, mlx_count) = {
- let mut mlx_session_info: Option<SessionInfo> = None;
- let mlx_count;
+ let mlx_session_info = {
let mlx_guard = mlx_sessions.lock().await;
- mlx_count = mlx_guard.len();
- if let Some(session) = mlx_guard
+ mlx_guard
.values()
.find(|s| s.info.model_id == sessions_find_model)
- {
- // Clone just the SessionInfo since MlxBackendSession is not Clone
- mlx_session_info = Some(session.info.clone());
- }
- (mlx_session_info, mlx_count)
+ .map(|s| s.info.clone())
};
- let total_sessions = sessions_guard.len() + mlx_count;
-
- // mlx_session_info is Option<SessionInfo>, use as_ref to get Option<&SessionInfo>
- let mlx_session = mlx_session_info.as_ref();
+ let router_up =
+ router_upstream(&llama_state, &destination_path).await;
- if total_sessions == 0 {
+ if mlx_session_info.is_none() && router_up.is_none() {
log::warn!(
"Request for model '{model_id}' but no models are running."
);
@@ -2020,20 +2034,17 @@ async fn proxy_request(
.unwrap());
}
- if let Some(session) = llama_session {
- let target_port = session.info.port;
- session_api_keys = vec![session.info.api_key.clone()];
- log::debug!("Found llama.cpp session for model_id {model_id}");
- target_base_url = Some(format!(
- "http://127.0.0.1:{target_port}/v1{destination_path}"
- ));
- } else if let Some(info) = mlx_session {
+ if let Some(info) = mlx_session_info {
let target_port = info.port;
session_api_keys = vec![info.api_key.clone()];
log::debug!("Found MLX session for model_id {model_id}");
target_base_url = Some(format!(
"http://127.0.0.1:{target_port}/v1{destination_path}"
));
+ } else if let Some((url, key)) = router_up {
+ log::debug!("Routing model_id {model_id} via llamacpp router");
+ session_api_keys = vec![key];
+ target_base_url = Some(url);
} else {
log::warn!("No running session found for model_id: {model_id}");
let mut error_response =
@@ -2084,20 +2095,18 @@ async fn proxy_request(
(hyper::Method::GET, "/models") => {
log::debug!("Handling GET /v1/models request");
- // Get local llama.cpp sessions
- let sessions_guard = sessions.lock().await;
- let local_models: Vec<_> = sessions_guard
- .values()
- .map(|session| {
+ let local_models: Vec<_> = router_list_models(&llama_state, &client)
+ .await
+ .into_iter()
+ .map(|id| {
serde_json::json!({
- "id": session.info.model_id,
+ "id": id,
"object": "model",
"created": 1,
"owned_by": "llama.cpp"
})
})
.collect();
- drop(sessions_guard);
// Get MLX sessions
let mlx_models: Vec<_> = {
@@ -2645,7 +2654,7 @@ pub async fn is_server_running(server_handle: Arc<Mutex<Option<ServerHandle>>>)
#[allow(clippy::too_many_arguments)]
pub async fn start_server(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
- sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
host: String,
port: u16,
@@ -2661,7 +2670,7 @@ pub async fn start_server(
) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
start_server_internal(
server_handle,
- sessions,
+ llama_state,
mlx_sessions,
host,
port,
@@ -2680,7 +2689,7 @@ pub async fn start_server(
async fn start_server_internal(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
- sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
+ llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
host: String,
port: u16,
@@ -2730,7 +2739,7 @@ async fn start_server_internal(
let make_svc = make_service_fn(move |_conn| {
let client = client.clone();
let config = config.clone();
- let sessions = sessions.clone();
+ let llama_state = llama_state.clone();
let mlx_sessions = mlx_sessions.clone();
let provider_configs = provider_configs.clone();
let mcp_servers = mcp_servers.clone();
@@ -2743,7 +2752,7 @@ async fn start_server_internal(
req,
client.clone(),
config.clone(),
- sessions.clone(),
+ llama_state.clone(),
mlx_sessions.clone(),
provider_configs.clone(),
mcp_servers.clone(),
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c97cda5d8..74ebe8c2b 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -259,6 +259,17 @@ pub fn run() {
.expect("error while running tauri application");
// Handle app lifecycle events
app.run(|app, event| {
+ if let RunEvent::ExitRequested { .. } = event {
+ let app_handle = app.clone();
+ tokio::task::block_in_place(|| {
+ tauri::async_runtime::block_on(async {
+ if let Err(e) = tauri_plugin_llamacpp::stop_router(app_handle).await {
+ log::warn!("stop_router on ExitRequested failed: {}", e);
+ }
+ })
+ });
+ return;
+ }
if let RunEvent::Exit = event {
let app_handle = app.clone();
@@ -302,9 +313,9 @@ pub fn run() {
}
if let Err(e) = cleanup_llama_processes(app_handle.clone()).await {
- log::warn!("Failed to cleanup llama processes: {}", e);
+ log::warn!("Failed to shut down llama-server router: {}", e);
} else {
- log::info!("Llama processes cleaned up successfully");
+ log::info!("Llama-server router shut down successfully");
}
#[cfg(feature = "mlx")]
diff --git a/web-app/src/components/PromptProgress.tsx b/web-app/src/components/PromptProgress.tsx
index a2d0f2b5e..31da1585c 100644
--- a/web-app/src/components/PromptProgress.tsx
+++ b/web-app/src/components/PromptProgress.tsx
@@ -3,26 +3,28 @@ import { Loader } from 'lucide-react'
export function PromptProgress() {
const promptProgress = useAppState((state) => state.promptProgress)
+ const loadingModel = useAppState((state) => state.loadingModel)
const percentage =
promptProgress && promptProgress.total > 0
? Math.round((promptProgress.processed / promptProgress.total) * 100)
: 0
- // Show progress only when promptProgress exists and has valid data, and not completed
- if (
- !promptProgress ||
- !promptProgress.total ||
- promptProgress.total <= 0 ||
- percentage >= 100
- ) {
- return <Loader className="animate-spin w-4 h-4" />
- }
+ const showReading =
+ promptProgress &&
+ promptProgress.total > 0 &&
+ percentage < 100
+
+ const label = loadingModel
+ ? 'Loading model…'
+ : showReading
+ ? `Reading: ${percentage}%`
+ : 'Working…'
return (
- <div className="flex items-center gap-2 text-sm text-muted-foreground mb-2">
- <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
- <span>Reading: {percentage}%</span>
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader className="animate-spin w-4 h-4" />
+ <span>{label}</span>
</div>
)
}
diff --git a/web-app/src/components/TokenCounter.tsx b/web-app/src/components/TokenCounter.tsx
index 9ce006fec..af52fa5d8 100644
--- a/web-app/src/components/TokenCounter.tsx
+++ b/web-app/src/components/TokenCounter.tsx
@@ -8,34 +8,43 @@ import {
} from '@/components/ui/tooltip'
import { useTokensCount } from '@/hooks/useTokensCount'
import { ThreadMessage } from '@janhq/core'
+import {
+ IconBrain,
+ IconArrowUp,
+ IconArrowDown,
+ IconSum,
+ IconRulerMeasure,
+ IconStack2,
+ IconPhoto,
+ IconMicrophone,
+ IconMoon,
+ IconAdjustmentsAlt,
+} from '@tabler/icons-react'
interface TokenCounterProps {
messages?: ThreadMessage[]
className?: string
compact?: boolean
- additionalTokens?: number // For vision tokens or other additions
- additionalContextText?: string
- uploadedFiles?: Array<{
- name: string
- type: string
- size: number
- base64: string
- dataUrl: string
- }>
+ additionalTokens?: number
+}
+
+const WARN_PCT = 85
+const OVER_PCT = 100
+
+const formatNumber = (num: number) => {
+ if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`
+ if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`
+ return num.toString()
}
+const formatExact = (num: number) => num.toLocaleString()
+
export const TokenCounter = memo(function TokenCounter({
messages = [],
className,
additionalTokens = 0,
- additionalContextText,
- uploadedFiles = [],
}: TokenCounterProps) {
- const { calculateTokens, ...tokenData } = useTokensCount(
- messages,
- uploadedFiles,
- additionalContextText
- )
+ const { calculateTokens, ...tokenData } = useTokensCount(messages)
const [isAnimating, setIsAnimating] = useState(false)
const [prevTokenCount, setPrevTokenCount] = useState(0)
@@ -44,70 +53,85 @@ export const TokenCounter = memo(function TokenCounter({
{}
)
- // Manual calculation - trigger on click
const handleCalculateTokens = () => {
calculateTokens()
}
- // Handle token count changes with proper debouncing and cleanup
useEffect(() => {
const currentTotal = tokenData.tokenCount + additionalTokens
const timers = timersRef.current
-
- // Clear any existing timers
if (timers.update) clearTimeout(timers.update)
if (timers.anim) clearTimeout(timers.anim)
if (currentTotal !== prevTokenCount) {
setIsUpdating(true)
-
- // Clear updating state after a longer delay for smoother transitions
- timers.update = setTimeout(() => {
- setIsUpdating(false)
- }, 250)
-
- // Only animate for significant changes and avoid animating on initial load
- if (prevTokenCount > 0) {
- const difference = Math.abs(currentTotal - prevTokenCount)
- if (difference > 10) {
- // Increased threshold to reduce micro-animations
- setIsAnimating(true)
- timers.anim = setTimeout(() => {
- setIsAnimating(false)
- }, 600)
- }
+ timers.update = setTimeout(() => setIsUpdating(false), 250)
+ if (prevTokenCount > 0 && Math.abs(currentTotal - prevTokenCount) > 10) {
+ setIsAnimating(true)
+ timers.anim = setTimeout(() => setIsAnimating(false), 600)
}
-
setPrevTokenCount(currentTotal)
}
- // Cleanup function
return () => {
if (timers.update) clearTimeout(timers.update)
if (timers.anim) clearTimeout(timers.anim)
}
}, [tokenData.tokenCount, additionalTokens, prevTokenCount])
- const totalTokens = useMemo(() => {
- return tokenData.tokenCount + additionalTokens
- }, [tokenData.tokenCount, additionalTokens])
+ const totalTokens = useMemo(
+ () => tokenData.tokenCount + additionalTokens,
+ [tokenData.tokenCount, additionalTokens]
+ )
- // Percentage calculation to match useTokensCount exactly
- const adjustedPercentage = useMemo(() => {
+ const pct = useMemo(() => {
if (!tokenData.maxTokens) return undefined
return (totalTokens / tokenData.maxTokens) * 100
}, [totalTokens, tokenData.maxTokens])
- // Check if percentage exceeds max (100%)
- const isOverLimit = useMemo(() => {
- return adjustedPercentage !== undefined && adjustedPercentage > 100
- }, [adjustedPercentage])
+ const tier: 'ok' | 'warn' | 'over' = useMemo(() => {
+ if (pct === undefined) return 'ok'
+ if (pct >= OVER_PCT) return 'over'
+ if (pct >= WARN_PCT) return 'warn'
+ return 'ok'
+ }, [pct])
- const formatNumber = (num: number) => {
- if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
- if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
- return num.toString()
- }
+ // n_ctx from /props is required for a meaningful denominator. Without it,
+ // hide entirely rather than render a misleading 0%/0 indicator.
+ if (!tokenData.maxTokens) return null
+
+ const textCls =
+ tier === 'over'
+ ? 'text-destructive'
+ : tier === 'warn'
+ ? 'text-amber-500'
+ : 'text-foreground'
+ const ringCls =
+ tier === 'over'
+ ? 'stroke-destructive'
+ : tier === 'warn'
+ ? 'stroke-amber-500'
+ : 'stroke-primary'
+ const barCls =
+ tier === 'over'
+ ? 'bg-destructive'
+ : tier === 'warn'
+ ? 'bg-amber-500'
+ : 'bg-primary'
+
+ const { inputTokens, outputTokens, modelProps, modelDisplayName } = tokenData
+ const remaining = Math.max(0, tokenData.maxTokens - totalTokens)
+ const showFittedBadge =
+ tokenData.fitEnabled &&
+ typeof tokenData.configuredCtxLen === 'number' &&
+ tokenData.configuredCtxLen !== tokenData.maxTokens
+ const hasModalities =
+ tokenData.modalities?.vision || tokenData.modalities?.audio
+ const showFooter =
+ showFittedBadge ||
+ hasModalities ||
+ modelProps?.isSleeping ||
+ (modelProps?.totalSlots !== undefined && modelProps.totalSlots > 1)
return (
<TooltipProvider delayDuration={isUpdating ? 1200 : 400}>
@@ -117,18 +141,16 @@ export const TokenCounter = memo(function TokenCounter({
className={cn('relative cursor-pointer', className)}
onClick={handleCalculateTokens}
>
- {/* Main compact display */}
<div className="flex items-center gap-2 px-2 py-1 rounded-md bg-background border border-border">
<span
className={cn(
'text-xs font-medium tabular-nums transition-all duration-500 ease-out',
- isOverLimit ? 'text-destructive' : 'text-primary',
+ textCls,
isAnimating && 'scale-110'
)}
>
- {adjustedPercentage?.toFixed(1) || '0.0'}%
+ {pct?.toFixed(1) ?? '0.0'}%
</span>
-
<div className="relative size-4 shrink-0">
<svg
className="size-4 transform -rotate-90"
@@ -141,7 +163,7 @@ export const TokenCounter = memo(function TokenCounter({
stroke="currentColor"
strokeWidth="1.5"
fill="none"
- className="text-muted-foreground"
+ className="text-muted-foreground/40"
/>
<circle
cx="8"
@@ -151,14 +173,12 @@ export const TokenCounter = memo(function TokenCounter({
strokeWidth="1.5"
fill="none"
strokeDasharray={`${2 * Math.PI * 6}`}
- strokeDashoffset={`${2 * Math.PI * 6 * (1 - (adjustedPercentage || 0) / 100)}`}
+ strokeDashoffset={`${2 * Math.PI * 6 * (1 - Math.min(pct ?? 0, 100) / 100)}`}
className={cn(
'transition-all duration-500 ease-out',
- isOverLimit ? 'stroke-destructive' : 'stroke-primary'
+ ringCls
)}
- style={{
- transformOrigin: 'center',
- }}
+ style={{ transformOrigin: 'center' }}
/>
</svg>
</div>
@@ -168,67 +188,157 @@ export const TokenCounter = memo(function TokenCounter({
<TooltipContent
side="bottom"
align="center"
- sideOffset={5}
+ sideOffset={6}
showArrow={false}
- className="min-w-60 max-w-60 bg-background border"
+ className="min-w-72 max-w-80 bg-background border p-0 overflow-hidden"
>
- {/* Detailed breakdown panel */}
- <>
- {/* Header with percentage and progress bar */}
- <div className="mb-3">
- <div className="flex items-center justify-between mb-2">
- <span
- className={cn(
- 'text-lg font-semibold tabular-nums',
- isOverLimit ? 'text-destructive' : 'text-primary'
- )}
- >
- {adjustedPercentage?.toFixed(1) || '0.0'}%
- </span>
- <span className="text-sm text-muted-foreground font-mono">
- {formatNumber(totalTokens)} /{' '}
- {formatNumber(tokenData.maxTokens || 0)}
- </span>
- </div>
-
- {/* Progress bar */}
- <div className="w-full h-2 bg-secondary/20 rounded-full overflow-hidden">
- <div
- className={cn(
- 'h-2 rounded-full transition-all duration-500 ease-out',
- isOverLimit ? 'bg-destructive' : 'bg-primary'
- )}
- style={{
- width: `${Math.min(adjustedPercentage || 0, 100)}%`,
- }}
- />
+ {/* Header */}
+ <div className="flex items-center gap-2 px-3 py-2.5 border-b border-border">
+ <IconBrain className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <div className="text-xs font-medium text-foreground">
+ Context window
</div>
+ {modelDisplayName && (
+ <div className="text-[11px] text-muted-foreground truncate">
+ {modelDisplayName}
+ </div>
+ )}
</div>
+ {modelProps?.isSleeping && (
+ <IconMoon
+ className="size-3.5 text-muted-foreground"
+ aria-label="Model sleeping"
+ />
+ )}
+ </div>
- {/* Token breakdown */}
- <div className="space-y-2 mb-3">
- <div className="flex items-center justify-between text-sm">
- <span className="text-muted-foreground">Text</span>
- <span className="text-foreground font-mono">
- {formatNumber(Math.max(0, tokenData.tokenCount))}
- </span>
- </div>
+ {/* Progress block */}
+ <div className="px-3 py-2.5">
+ <div className="flex items-baseline justify-between mb-1.5">
+ <span
+ className={cn(
+ 'text-xl font-semibold tabular-nums leading-none',
+ textCls
+ )}
+ >
+ {pct?.toFixed(1) ?? '0.0'}%
+ </span>
+ <span className="text-xs text-muted-foreground tabular-nums font-mono">
+ {formatNumber(totalTokens)} /{' '}
+ {formatNumber(tokenData.maxTokens)}
+ </span>
+ </div>
+ <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden">
+ <div
+ className={cn(
+ 'h-full rounded-full transition-all duration-500 ease-out',
+ barCls
+ )}
+ style={{ width: `${Math.min(pct ?? 0, 100)}%` }}
+ />
</div>
+ </div>
+
+ {/* Token breakdown */}
+ <div className="px-3 py-2 border-t border-border space-y-1.5">
+ {typeof inputTokens === 'number' && inputTokens > 0 && (
+ <Row
+ icon={<IconArrowUp className="size-3.5" />}
+ label="Prompt"
+ value={formatExact(inputTokens)}
+ />
+ )}
+ {typeof outputTokens === 'number' && outputTokens > 0 && (
+ <Row
+ icon={<IconArrowDown className="size-3.5" />}
+ label="Completion"
+ value={formatExact(outputTokens)}
+ />
+ )}
+ <Row
+ icon={<IconSum className="size-3.5" />}
+ label="Used"
+ value={formatExact(totalTokens)}
+ strong
+ />
+ <Row
+ icon={<IconRulerMeasure className="size-3.5" />}
+ label="Remaining"
+ value={formatExact(remaining)}
+ />
+ </div>
- {/* Remaining tokens */}
- <div className="border-t border-border pt-2">
- <div className="flex items-center justify-between text-sm">
- <span className="text-muted-foreground">Remaining</span>
- <span className="text-foreground font-semibold font-mono">
- {formatNumber(
- Math.max(0, (tokenData.maxTokens || 0) - totalTokens)
- )}
+ {/* Footer: fit + slots + modalities */}
+ {showFooter && (
+ <div className="px-3 py-2 border-t border-border flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
+ {showFittedBadge && (
+ <span
+ className="flex items-center gap-1"
+ title={`Configured ctx_len: ${formatExact(tokenData.configuredCtxLen!)}`}
+ >
+ <IconAdjustmentsAlt className="size-3" />
+ Fitted to {formatNumber(tokenData.maxTokens)}
</span>
- </div>
+ )}
+ {modelProps?.totalSlots !== undefined &&
+ modelProps.totalSlots > 1 && (
+ <span className="flex items-center gap-1">
+ <IconStack2 className="size-3" />
+ {modelProps.totalSlots} slots
+ </span>
+ )}
+ {tokenData.modalities?.vision && (
+ <span
+ className="flex items-center gap-1"
+ title="Vision input supported"
+ >
+ <IconPhoto className="size-3" />
+ Vision
+ </span>
+ )}
+ {tokenData.modalities?.audio && (
+ <span
+ className="flex items-center gap-1"
+ title="Audio input supported"
+ >
+ <IconMicrophone className="size-3" />
+ Audio
+ </span>
+ )}
</div>
- </>
+ )}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
})
+
+function Row({
+ icon,
+ label,
+ value,
+ strong,
+}: {
+ icon: React.ReactNode
+ label: string
+ value: string
+ strong?: boolean
+}) {
+ return (
+ <div className="flex items-center justify-between text-xs">
+ <span className="flex items-center gap-1.5 text-muted-foreground">
+ {icon}
+ {label}
+ </span>
+ <span
+ className={cn(
+ 'font-mono tabular-nums',
+ strong ? 'text-foreground font-semibold' : 'text-foreground'
+ )}
+ >
+ {value}
+ </span>
+ </div>
+ )
+}
diff --git a/web-app/src/components/__tests__/PromptProgress.test.tsx b/web-app/src/components/__tests__/PromptProgress.test.tsx
index 31f633e03..ff200decb 100644
--- a/web-app/src/components/__tests__/PromptProgress.test.tsx
+++ b/web-app/src/components/__tests__/PromptProgress.test.tsx
@@ -23,7 +23,9 @@ describe('PromptProgress', () => {
total: 150,
}
- mockUseAppState.mockReturnValue(mockProgress)
+ mockUseAppState.mockImplementation((selector) =>
+ selector({ promptProgress: mockProgress, loadingModel: false })
+ )
render(<PromptProgress />)
@@ -38,7 +40,9 @@ describe('PromptProgress', () => {
total: 0,
}
- mockUseAppState.mockReturnValue(mockProgress)
+ mockUseAppState.mockImplementation((selector) =>
+ selector({ promptProgress: mockProgress, loadingModel: false })
+ )
const { container } = render(<PromptProgress />)
diff --git a/web-app/src/components/__tests__/TokenCounter.test.tsx b/web-app/src/components/__tests__/TokenCounter.test.tsx
index 09637c819..230170776 100644
--- a/web-app/src/components/__tests__/TokenCounter.test.tsx
+++ b/web-app/src/components/__tests__/TokenCounter.test.tsx
@@ -75,8 +75,9 @@ describe('TokenCounter', () => {
render(<TokenCounter />)
const percentElements = screen.getAllByText('50.0%')
const span = percentElements[0]
- expect(span.className).toContain('text-primary')
+ expect(span.className).toContain('text-foreground')
expect(span.className).not.toContain('text-destructive')
+ expect(span.className).not.toContain('text-amber-500')
})
it('calls calculateTokens when clicked', async () => {
@@ -97,10 +98,16 @@ describe('TokenCounter', () => {
expect(circles.length).toBe(2)
})
- it('shows 0.0% when maxTokens is 0 (no model selected)', () => {
+ it('renders nothing when maxTokens is unavailable', () => {
+ mockTokens({ tokenCount: 0, maxTokens: undefined })
+ const { container } = render(<TokenCounter />)
+ expect(container.firstChild).toBeNull()
+ })
+
+ it('renders nothing when maxTokens is 0', () => {
mockTokens({ tokenCount: 0, maxTokens: 0 })
- render(<TokenCounter />)
- expect(screen.getAllByText('0.0%').length).toBeGreaterThanOrEqual(1)
+ const { container } = render(<TokenCounter />)
+ expect(container.firstChild).toBeNull()
})
describe('formatNumber helper (via rendered output)', () => {
@@ -123,14 +130,22 @@ describe('TokenCounter', () => {
})
})
- it('shows token breakdown with Text and Remaining labels', () => {
+ it('shows token breakdown with Used and Remaining labels', () => {
mockTokens({ tokenCount: 500, maxTokens: 1000 })
- const { container } = render(<TokenCounter />)
+ render(<TokenCounter />)
const tooltipContent = screen.getByTestId('tooltip-content')
- expect(tooltipContent.textContent).toContain('Text')
+ expect(tooltipContent.textContent).toContain('Used')
expect(tooltipContent.textContent).toContain('Remaining')
})
+ it('shows Context window header', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ render(<TokenCounter />)
+ expect(
+ screen.getByTestId('tooltip-content').textContent
+ ).toContain('Context window')
+ })
+
it('shows correct remaining tokens', () => {
mockTokens({ tokenCount: 300, maxTokens: 1000 })
const { container } = render(<TokenCounter />)
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsx
index 93b7748a5..b0aec5205 100644
--- a/web-app/src/components/ai-elements/tool.tsx
+++ b/web-app/src/components/ai-elements/tool.tsx
@@ -131,7 +131,7 @@ export const ToolContent = memo(
({ className, children, ...props }: ToolContentProps) => (
<CollapsibleContent
className={cn(
- 'mt-4 text-sm relative',
+ 'overflow-hidden text-sm relative data-[state=open]:mt-4',
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
className
)}
diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.ts
index c8fdb5f41..b5bf2342c 100644
--- a/web-app/src/constants/localStorage.ts
+++ b/web-app/src/constants/localStorage.ts
@@ -28,6 +28,7 @@ export const localStorageKey = {
janModelPromptDismissed: 'jan-model-prompt-dismissed',
agentMode: 'agent-mode',
latestJanModel: 'latest-jan-model',
+ defaultEmbeddingModel: 'default-embedding-model',
}
export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24
diff --git a/web-app/src/containers/Capabilities.tsx b/web-app/src/containers/Capabilities.tsx
index 5cf5aea62..0600fe3cc 100644
--- a/web-app/src/containers/Capabilities.tsx
+++ b/web-app/src/containers/Capabilities.tsx
@@ -55,7 +55,6 @@ const Capabilities = memo(function Capabilities({ capabilities }: CapabilitiesPr
<TooltipTrigger asChild>
<span
className="flex items-center gap-1 size-5 hover:bg-secondary rounded text-muted-foreground justify-center last:mr-1 transition-all"
- title={capability}
>
{icon}
</span>
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 536666a3f..b63cc1a77 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -21,7 +21,8 @@ import {
import { ArrowRight, PlusIcon } from 'lucide-react'
import {
IconPhoto,
- IconAtom,
+ IconMusic,
+ IconBrain,
IconTool,
IconCodeCircle2,
IconPlayerStopFilled,
@@ -82,6 +83,7 @@ import {
Attachment,
createImageAttachment,
createDocumentAttachment,
+ createAudioAttachment,
} from '@/types/attachment'
import JanBrowserExtensionDialog from '@/containers/dialogs/JanBrowserExtensionDialog'
import { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'
@@ -208,27 +210,6 @@ const ChatInput = memo(function ChatInput({
const assistantCount = assistants?.length || 0
- // Tool schemas sent to the model are not part of ThreadMessage[]; add them here only.
- // Do not include system instructions — they are already present in messages and counted by useTokensCount.
- const tokenCounterAdditionalContext = useMemo(() => {
- const toolsText = tools
- .map((tool) => {
- const schema = (() => {
- try {
- return JSON.stringify(tool.inputSchema ?? {})
- } catch {
- return '{}'
- }
- })()
- return `Tool ${tool.server}::${tool.name}\nDescription: ${tool.description}\nSchema: ${schema}`
- })
- .join('\n\n')
-
- if (!toolsText) return ''
- return `Available tools:\n${toolsText}`
- }, [tools])
-
- // No auto-selection: let the user explicitly pick an assistant
// Jan Browser Extension hook
const {
@@ -374,14 +355,21 @@ const ChatInput = memo(function ChatInput({
const assistant = currentThread?.assistants?.[0]
setCurrentAssistant(assistant)
- // Build file parts for AI SDK
- const files = attachments
+ const imageFiles = attachments
.filter((att) => att.type === 'image' && att.dataUrl)
.map((att) => ({
type: 'file',
mediaType: att.mimeType ?? 'image/jpeg',
url: att.dataUrl!,
}))
+ const audioFiles = attachments
+ .filter((att) => att.type === 'audio' && att.dataUrl)
+ .map((att) => ({
+ type: 'file',
+ mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
+ url: att.dataUrl!,
+ }))
+ const files = [...imageFiles, ...audioFiles]
onSubmit(prompt, files.length > 0 ? files : undefined)
setPrompt('')
@@ -393,14 +381,21 @@ const ChatInput = memo(function ChatInput({
`${TEMPORARY_CHAT_QUERY_ID}=true`
)
- // Build message payload with attachments
- const files = attachments
+ const imageFiles = attachments
.filter((att) => att.type === 'image' && att.dataUrl)
.map((att) => ({
type: 'file',
mediaType: att.mimeType ?? 'image/jpeg',
url: att.dataUrl!,
}))
+ const audioFiles = attachments
+ .filter((att) => att.type === 'audio' && att.dataUrl)
+ .map((att) => ({
+ type: 'file',
+ mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
+ url: att.dataUrl!,
+ }))
+ const files = [...imageFiles, ...audioFiles]
const messagePayload = {
text: prompt,
@@ -559,6 +554,8 @@ const ChatInput = memo(function ChatInput({
)
const fileInputRef = useRef<HTMLInputElement>(null)
+ const audioInputRef = useRef<HTMLInputElement>(null)
+ const audioSupported = !!selectedModel?.capabilities?.includes('audio')
const processNewDocumentAttachments = useCallback(
async (docs: Attachment[]) => {
@@ -1121,7 +1118,6 @@ const ChatInput = memo(function ChatInput({
if (files && files.length > 0) {
void processImageFiles(Array.from(files))
- // Reset the file input value to allow re-uploading the same file
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
@@ -1132,6 +1128,159 @@ const ChatInput = memo(function ChatInput({
}
}
+ const decodeAudioDuration = (dataUrl: string): Promise<number | undefined> =>
+ new Promise((resolve) => {
+ try {
+ const audio = new Audio()
+ audio.preload = 'metadata'
+ audio.onloadedmetadata = () => {
+ const d = audio.duration
+ resolve(Number.isFinite(d) && d > 0 ? d : undefined)
+ }
+ audio.onerror = () => resolve(undefined)
+ audio.src = dataUrl
+ } catch {
+ resolve(undefined)
+ }
+ })
+
+ const processAudioFiles = useCallback(
+ async (files: File[]) => {
+ const maxBytes = 25 * 1024 * 1024
+ const oversized: string[] = []
+ const invalid: string[] = []
+ const prepared: Attachment[] = []
+
+ for (const file of Array.from(files)) {
+ const lower = file.name.toLowerCase()
+ const ext = lower.split('.').pop()
+ const isWav = file.type === 'audio/wav' || file.type === 'audio/x-wav' || ext === 'wav'
+ const isMp3 = file.type === 'audio/mpeg' || file.type === 'audio/mp3' || ext === 'mp3'
+ if (!isWav && !isMp3) {
+ invalid.push(file.name)
+ continue
+ }
+ if (file.size > maxBytes) {
+ oversized.push(file.name)
+ continue
+ }
+ const fmt: 'wav' | 'mp3' = isWav ? 'wav' : 'mp3'
+ const mimeType = fmt === 'wav' ? 'audio/wav' : 'audio/mpeg'
+ const dataUrl: string = await new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => {
+ const r = reader.result
+ if (typeof r === 'string') resolve(r)
+ else reject(new Error('read failed'))
+ }
+ reader.onerror = () => reject(reader.error ?? new Error('read failed'))
+ reader.readAsDataURL(file)
+ })
+ const base64 = dataUrl.split(',')[1] ?? ''
+ const durationSec = await decodeAudioDuration(dataUrl)
+ prepared.push(
+ createAudioAttachment({
+ name: file.name,
+ base64,
+ dataUrl,
+ mimeType,
+ audioFormat: fmt,
+ size: file.size,
+ durationSec,
+ })
+ )
+ }
+
+ const current = useChatAttachments.getState().getAttachments(attachmentsKey)
+ const existingNames = new Set(
+ current.filter((a) => a.type === 'audio').map((a) => a.name)
+ )
+ const duplicates: string[] = []
+ const newOnes: Attachment[] = []
+ for (const att of prepared) {
+ if (existingNames.has(att.name)) {
+ duplicates.push(att.name)
+ continue
+ }
+ newOnes.push(att)
+ }
+
+ if (newOnes.length > 0) {
+ setAttachmentsForThread(attachmentsKey, (prev) => [...prev, ...newOnes])
+ }
+
+ if (duplicates.length > 0) {
+ toast.warning('Some audio files already attached', {
+ description: `${duplicates.join(', ')} ${duplicates.length === 1 ? 'is' : 'are'} already in the list`,
+ })
+ }
+ const errors: string[] = []
+ if (oversized.length > 0) {
+ errors.push(
+ `Audio file${oversized.length > 1 ? 's' : ''} too large (max 25MB): ${oversized.join(', ')}`
+ )
+ }
+ if (invalid.length > 0) {
+ errors.push(
+ `Invalid audio type${invalid.length > 1 ? 's' : ''} (only WAV, MP3 allowed): ${invalid.join(', ')}`
+ )
+ }
+ if (errors.length > 0) {
+ setMessage(errors.join(' | '))
+ if (audioInputRef.current) audioInputRef.current.value = ''
+ }
+ },
+ [attachmentsKey, setAttachmentsForThread]
+ )
+
+ const handleAudioFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = e.target.files
+ if (files && files.length > 0) {
+ void processAudioFiles(Array.from(files))
+ if (audioInputRef.current) audioInputRef.current.value = ''
+ }
+ if (textareaRef.current) textareaRef.current.focus()
+ }
+
+ const openAudioPicker = useCallback(async () => {
+ if (isPlatformTauri()) {
+ try {
+ const selected = await serviceHub.dialog().open({
+ multiple: true,
+ filters: [{ name: 'Audio', extensions: ['wav', 'mp3'] }],
+ })
+ if (selected) {
+ const paths = Array.isArray(selected) ? selected : [selected]
+ const files: File[] = []
+ for (const path of paths) {
+ try {
+ const { convertFileSrc } = await import('@tauri-apps/api/core')
+ const fileUrl = convertFileSrc(path)
+ const response = await fetch(fileUrl)
+ if (!response.ok) throw new Error(response.statusText)
+ const blob = await response.blob()
+ const fileName = path.split(/[\\/]/).filter(Boolean).pop() || 'audio'
+ const ext = fileName.toLowerCase().split('.').pop()
+ const mimeType = ext === 'mp3' ? 'audio/mpeg' : 'audio/wav'
+ files.push(new File([blob], fileName, { type: mimeType }))
+ } catch (error) {
+ console.error('Failed to read audio file:', error)
+ toast.error('Failed to read audio file', {
+ description: error instanceof Error ? error.message : String(error),
+ })
+ }
+ }
+ if (files.length > 0) await processAudioFiles(files)
+ }
+ } catch (error) {
+ console.error('Failed to open audio dialog:', error)
+ }
+ if (textareaRef.current) textareaRef.current.focus()
+ } else {
+ audioInputRef.current?.click()
+ }
+ }, [serviceHub, processAudioFiles])
+
// Open the image picker dialog (extracted for reuse)
const openImagePicker = useCallback(async () => {
if (isPlatformTauri()) {
@@ -1253,11 +1402,12 @@ const ChatInput = memo(function ChatInput({
]
)
+ const dropAcceptsAnything = hasMmproj || audioSupported
+
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
- // Only allow drag if model supports mmproj
- if (hasMmproj) {
+ if (dropAcceptsAnything) {
setIsDragOver(true)
}
}
@@ -1276,8 +1426,7 @@ const ChatInput = memo(function ChatInput({
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
- // Ensure drag state is maintained during drag over
- if (hasMmproj) {
+ if (dropAcceptsAnything) {
setIsDragOver(true)
}
}
@@ -1287,32 +1436,67 @@ const ChatInput = memo(function ChatInput({
e.stopPropagation()
setIsDragOver(false)
- // Only allow drop if model supports mmproj
- if (!hasMmproj) {
- return
- }
-
- // Check if dataTransfer exists (it might not in some Tauri scenarios)
+ if (!dropAcceptsAnything) return
if (!e.dataTransfer) {
console.warn('No dataTransfer available in drop event')
return
}
- const files = e.dataTransfer.files
- if (files && files.length > 0) {
- // Create a synthetic event to reuse existing file handling logic
+ const dropped = Array.from(e.dataTransfer.files ?? [])
+ if (dropped.length === 0) return
+
+ const isAudioFile = (f: File) => {
+ const ext = f.name.toLowerCase().split('.').pop()
+ return (
+ f.type === 'audio/wav' ||
+ f.type === 'audio/x-wav' ||
+ f.type === 'audio/mpeg' ||
+ f.type === 'audio/mp3' ||
+ ext === 'wav' ||
+ ext === 'mp3'
+ )
+ }
+
+ const audioOnes = audioSupported ? dropped.filter(isAudioFile) : []
+ const otherOnes = dropped.filter((f) => !audioOnes.includes(f))
+
+ if (otherOnes.length > 0 && hasMmproj) {
+ const dt = new DataTransfer()
+ otherOnes.forEach((f) => dt.items.add(f))
const syntheticEvent = {
- target: {
- files: files,
- },
+ target: { files: dt.files },
} as React.ChangeEvent<HTMLInputElement>
-
handleFileChange(syntheticEvent)
}
+ if (audioOnes.length > 0) {
+ void processAudioFiles(audioOnes)
+ }
}
const handlePaste = async (e: React.ClipboardEvent) => {
- // Only process images if model supports mmproj
+ if (audioSupported) {
+ const clipboardItems = e.clipboardData?.items
+ if (clipboardItems && clipboardItems.length > 0) {
+ const audioFiles: File[] = []
+ for (const item of Array.from(clipboardItems)) {
+ if (
+ item.type === 'audio/wav' ||
+ item.type === 'audio/x-wav' ||
+ item.type === 'audio/mpeg' ||
+ item.type === 'audio/mp3'
+ ) {
+ const f = item.getAsFile()
+ if (f) audioFiles.push(f)
+ }
+ }
+ if (audioFiles.length > 0) {
+ e.preventDefault()
+ await processAudioFiles(audioFiles)
+ return
+ }
+ }
+ }
+
if (hasMmproj) {
const clipboardItems = e.clipboardData?.items
let hasProcessedImage = false
@@ -1444,11 +1628,11 @@ const ChatInput = memo(function ChatInput({
isFocused && 'ring-1 ring-ring/50',
isDragOver && 'ring-2 ring-ring/50 border-primary'
)}
- data-drop-zone={hasMmproj ? 'true' : undefined}
- onDragEnter={hasMmproj ? handleDragEnter : undefined}
- onDragLeave={hasMmproj ? handleDragLeave : undefined}
- onDragOver={hasMmproj ? handleDragOver : undefined}
- onDrop={hasMmproj ? handleDrop : undefined}
+ data-drop-zone={dropAcceptsAnything ? 'true' : undefined}
+ onDragEnter={dropAcceptsAnything ? handleDragEnter : undefined}
+ onDragLeave={dropAcceptsAnything ? handleDragLeave : undefined}
+ onDragOver={dropAcceptsAnything ? handleDragOver : undefined}
+ onDrop={dropAcceptsAnything ? handleDrop : undefined}
>
{attachments.length > 0 && (
<div className="flex flex-col gap-2 p-2 pb-0">
@@ -1457,7 +1641,14 @@ const ChatInput = memo(function ChatInput({
.map((att, idx) => ({ att, idx }))
.map(({ att, idx }) => {
const isImage = att.type === 'image'
+ const isAudio = att.type === 'audio'
const ext = att.fileType || att.mimeType?.split('/')[1]
+ const durLabel =
+ isAudio && typeof att.durationSec === 'number'
+ ? `${Math.floor(att.durationSec / 60)}:${Math.floor(att.durationSec % 60)
+ .toString()
+ .padStart(2, '0')}`
+ : undefined
return (
<div
key={`${att.type}-${idx}-${att.name}`}
@@ -1471,13 +1662,21 @@ const ChatInput = memo(function ChatInput({
'flex items-center justify-center'
)}
>
- {/* Inner content by state */}
{isImage && att.dataUrl ? (
<img
className="object-cover w-full h-full"
src={att.dataUrl}
alt={`${att.name}`}
/>
+ ) : isAudio ? (
+ <div className="flex flex-col items-center justify-center text-muted-foreground">
+ <IconMusic size={20} />
+ {durLabel && (
+ <span className="text-[10px] leading-none mt-0.5 tabular-nums opacity-70">
+ {durLabel}
+ </span>
+ )}
+ </div>
) : (
<div className="flex flex-col items-center justify-center text-muted-foreground">
<IconPaperclip size={18} />
@@ -1501,9 +1700,13 @@ const ChatInput = memo(function ChatInput({
<div className="opacity-70">
{isImage
? att.mimeType || 'image'
- : ext
- ? `.${ext}`
- : 'document'}
+ : isAudio
+ ? att.audioFormat
+ ? `.${att.audioFormat}${durLabel ? ` · ${durLabel}` : ''}`
+ : 'audio'
+ : ext
+ ? `.${ext}`
+ : 'document'}
{att.size
? ` · ${formatBytes(att.size, {
decimals: (_, unit) =>
@@ -1511,6 +1714,13 @@ const ChatInput = memo(function ChatInput({
})}`
: ''}
</div>
+ {isAudio && att.dataUrl && (
+ <audio
+ controls
+ src={att.dataUrl}
+ className="mt-1 w-56"
+ />
+ )}
</div>
</TooltipContent>
</Tooltip>
@@ -1633,7 +1843,6 @@ const ChatInput = memo(function ChatInput({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
- {/* Vision image attachment - always enabled, prompts to download vision model if needed */}
<DropdownMenuItem onClick={handleImagePickerClick}>
<IconPhoto size={18} className="text-muted-foreground" />
<span>Add Images</span>
@@ -1645,6 +1854,20 @@ const ChatInput = memo(function ChatInput({
onChange={handleFileChange}
/>
</DropdownMenuItem>
+ {audioSupported && (
+ <DropdownMenuItem onClick={() => void openAudioPicker()}>
+ <IconMusic size={18} className="text-muted-foreground" />
+ <span>Add Audio</span>
+ <input
+ type="file"
+ ref={audioInputRef}
+ className="hidden"
+ multiple
+ accept="audio/wav,audio/mpeg,.wav,.mp3"
+ onChange={handleAudioFileChange}
+ />
+ </DropdownMenuItem>
+ )}
{/* RAG document attachments - desktop-only via dialog; shown when feature enabled */}
<DropdownMenuItem
onClick={handleAttachDocsIngest}
@@ -1934,21 +2157,120 @@ const ChatInput = memo(function ChatInput({
</Tooltip>
)}
- {!effectiveAgentMode && selectedModel?.capabilities?.includes('reasoning') && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <IconAtom
- size={18}
- className="text-muted-foreground"
- />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>{t('reasoning')}</p>
- </TooltipContent>
- </Tooltip>
- )}
+ {!effectiveAgentMode &&
+ selectedProvider === 'llamacpp' &&
+ (() => {
+ const reasoningValue =
+ (selectedModel?.settings?.reasoning?.controller_props
+ ?.value as 'auto' | 'on' | 'off' | undefined) ?? 'auto'
+ const setReasoning = (value: 'auto' | 'on' | 'off') => {
+ if (!selectedProvider || !selectedModel) return
+ const providerObj = getProviderByName(selectedProvider)
+ if (!providerObj) return
+ const modelIndex = providerObj.models.findIndex(
+ (m) => m.id === selectedModel.id
+ )
+ if (modelIndex === -1) return
+ const existing =
+ selectedModel.settings?.reasoning ?? {
+ key: 'reasoning',
+ title: 'Reasoning',
+ description: '',
+ controller_type: 'dropdown',
+ controller_props: { value },
+ }
+ const updatedModel = {
+ ...selectedModel,
+ settings: {
+ ...selectedModel.settings,
+ reasoning: {
+ ...existing,
+ controller_props: {
+ ...(existing.controller_props ?? {}),
+ value,
+ },
+ },
+ },
+ } as Model
+ const updatedModels = [...providerObj.models]
+ updatedModels[modelIndex] = updatedModel
+ updateProvider(selectedProvider, {
+ models: updatedModels,
+ })
+ // selectedModel is a snapshot, not a live derivation —
+ // re-select to refresh it so the dropdown UI and the
+ // chat transport both observe the new value.
+ selectModelProvider(selectedProvider, selectedModel.id)
+ }
+ const label =
+ reasoningValue === 'on'
+ ? 'On'
+ : reasoningValue === 'off'
+ ? 'Off'
+ : 'Auto'
+ const tooltipText =
+ reasoningValue === 'on'
+ ? 'Reasoning forced on for every request.'
+ : reasoningValue === 'off'
+ ? 'Reasoning disabled for every request.'
+ : "Reasoning auto-detected from the model's chat template."
+ return (
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1 px-1.5"
+ >
+ <IconBrain
+ size={18}
+ className={cn(
+ 'text-muted-foreground',
+ reasoningValue === 'on' && 'text-primary',
+ reasoningValue === 'off' && 'opacity-50'
+ )}
+ />
+ <span className="text-xs text-muted-foreground lowercase">
+ {label}
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{tooltipText}</p>
+ </TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onClick={() => setReasoning('auto')}>
+ Auto
+ {reasoningValue === 'auto' && (
+ <span className="ml-auto text-xs text-muted-foreground">
+ ✓
+ </span>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setReasoning('on')}>
+ On
+ {reasoningValue === 'on' && (
+ <span className="ml-auto text-xs text-muted-foreground">
+ ✓
+ </span>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setReasoning('off')}>
+ Off
+ {reasoningValue === 'off' && (
+ <span className="ml-auto text-xs text-muted-foreground">
+ ✓
+ </span>
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ })()}
</div>
</div>
@@ -1962,16 +2284,6 @@ const ChatInput = memo(function ChatInput({
<TokenCounter
messages={threadMessages || []}
compact={true}
- additionalContextText={tokenCounterAdditionalContext}
- uploadedFiles={attachments
- .filter((a) => a.type === 'image' && a.dataUrl)
- .map((a) => ({
- name: a.name,
- type: a.mimeType || getFileTypeFromExtension(a.name),
- size: a.size || 0,
- base64: a.base64 || '',
- dataUrl: a.dataUrl!,
- }))}
/>
</div>
)}
@@ -2042,19 +2354,7 @@ const ChatInput = memo(function ChatInput({
!initialMessage &&
(threadMessages?.length > 0 || prompt.trim().length > 0) && (
<div className="flex-1 w-full flex justify-start px-2">
- <TokenCounter
- messages={threadMessages || []}
- additionalContextText={tokenCounterAdditionalContext}
- uploadedFiles={attachments
- .filter((a) => a.type === 'image' && a.dataUrl)
- .map((a) => ({
- name: a.name,
- type: a.mimeType || getFileTypeFromExtension(a.name),
- size: a.size || 0,
- base64: a.base64 || '',
- dataUrl: a.dataUrl!,
- }))}
- />
+ <TokenCounter messages={threadMessages || []} />
</div>
)}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 2d1c23012..02a9b61f0 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -27,6 +27,7 @@ import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator'
import { extractFilesFromPrompt, FileMetadata } from '@/lib/fileMetadata'
import { useMemo } from 'react'
import { Button } from '@/components/ui/button'
+import { PromptProgress } from '@/components/PromptProgress'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -243,6 +244,25 @@ export const MessageItem = memo(
partIndex: number
) => {
const isImage = part.mediaType?.startsWith('image/')
+ const isAudio =
+ part.mediaType === 'audio/wav' || part.mediaType === 'audio/mpeg'
+
+ if (isAudio && part.url) {
+ const justify =
+ message.role === 'user' ? 'justify-end' : 'justify-start'
+ return (
+ <div
+ key={`${message.id}-${partIndex}`}
+ className={`flex ${justify} w-full my-2`}
+ >
+ <audio
+ controls
+ src={part.url}
+ className="max-w-[80%] rounded-md"
+ />
+ </div>
+ )
+ }
if (message.role === 'user' && isImage && part.url) {
return (
@@ -294,7 +314,7 @@ export const MessageItem = memo(
<Tool
key={`${message.id}-${partIndex}`}
state={part.state}
- className="mb-2"
+ className="mb-1"
>
<ToolHeader
title={toolName}
@@ -470,9 +490,15 @@ export const MessageItem = memo(
{/* Render message parts */}
{renderedParts}
+ {isLastMessage &&
+ message.role === 'assistant' &&
+ (hasPendingToolCall || status === CHAT_STATUS.SUBMITTED) && (
+ <PromptProgress />
+ )}
+
{/* Message actions for user messages */}
{message.role === 'user' && !hideActions && (
- <div className="flex items-center justify-end gap-1 text-muted-foreground text-xs mt-4">
+ <div className="flex items-center justify-end gap-1 text-muted-foreground text-xs">
<span className="text-muted-foreground">
{formatDate(createdAt)}
</span>
@@ -496,7 +522,7 @@ export const MessageItem = memo(
{/* Message actions for assistant messages (non-tool) */}
{message.role === 'assistant' && (
- <div className="flex items-center gap-2 text-muted-foreground text-xs mt-1">
+ <div className="flex items-center gap-2 text-muted-foreground text-xs">
{!isStreaming && (
<span className="text-muted-foreground">
{formatDate(createdAt)}
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index 27cef5c8f..fa1436e2f 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -90,8 +90,7 @@ export function ModelSetting({
key === 'offload_mmproj' ||
key === 'batch_size' ||
key === 'cpu_moe' ||
- key === 'n_cpu_moe' ||
- key === 'reasoning'
+ key === 'n_cpu_moe'
) {
// Check if model is running before stopping it
serviceHub
@@ -106,6 +105,28 @@ export function ModelSetting({
}
}
+ const handleEngineSettingChange = (
+ key: string,
+ value: string | boolean | number
+ ) => {
+ if (!provider) return
+ const newSettings = provider.settings.map((s) =>
+ s.key === key
+ ? {
+ ...s,
+ controller_props: { ...s.controller_props, value },
+ }
+ : s
+ )
+ serviceHub.providers().updateSettings(provider.provider, newSettings)
+ updateProvider(provider.provider, { settings: newSettings })
+ }
+
+ const fitEnabled =
+ provider.settings?.find((s) => s.key === 'fit')?.controller_props?.value ===
+ true
+ const fitCtxSetting = provider.settings?.find((s) => s.key === 'fit_ctx')
+
return (
<Sheet>
<SheetTrigger asChild>
@@ -126,10 +147,36 @@ export function ModelSetting({
</SheetHeader>
<div className="px-4 space-y-8 pb-4">
- {Object.entries(model.settings || {})
+ {fitEnabled && fitCtxSetting && (
+ <div key="fit_ctx" className="space-y-2">
+ <div className="flex items-start justify-between gap-8">
+ <div className="mb-1 truncate">
+ <span title={fitCtxSetting.title} className="font-medium">
+ {fitCtxSetting.title}
+ </span>
+ </div>
+ <DynamicControllerSetting
+ key={fitCtxSetting.key}
+ title={fitCtxSetting.title}
+ description={fitCtxSetting.description}
+ controllerType={fitCtxSetting.controller_type}
+ controllerProps={fitCtxSetting.controller_props}
+ onChange={(newValue) =>
+ handleEngineSettingChange('fit_ctx', newValue)
+ }
+ />
+ </div>
+ <p className="text-muted-foreground leading-normal text-xs">
+ {fitCtxSetting.description}
+ </p>
+ </div>
+ )}
+ {(() => {
+ return Object.entries(model.settings || {})
.reduce<[string, unknown][]>((acc, entry) => {
if (entry[0] === 'auto_increase_ctx_len') return acc
if (entry[0] === 'reasoning') return acc
+ if (fitEnabled && entry[0] === 'ctx_len') return acc
if (entry[0] === 'ctx_len') {
const autoIncrease = Object.entries(model.settings || {}).find(
([k]) => k === 'auto_increase_ctx_len'
@@ -139,14 +186,6 @@ export function ModelSetting({
acc.push(entry)
return acc
}, [])
- .reduce<[string, unknown][]>((acc, entry) => {
- const reasoning = Object.entries(model.settings || {}).find(
- ([k]) => k === 'reasoning'
- )
- if (reasoning && acc.length === 0) acc.push(reasoning)
- acc.push(entry)
- return acc
- }, [])
.filter(([key]) => {
// MLX models only support context size setting
if (provider.provider === 'mlx') {
@@ -187,7 +226,8 @@ export function ModelSetting({
</p>
</div>
)
- })}
+ })
+ })()}
</div>
</SheetContent>
</Sheet>
diff --git a/web-app/src/containers/ModelSupportStatus.tsx b/web-app/src/containers/ModelSupportStatus.tsx
index fe57a2c4b..6b8d7930b 100644
--- a/web-app/src/containers/ModelSupportStatus.tsx
+++ b/web-app/src/containers/ModelSupportStatus.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from 'react'
+import { invoke } from '@tauri-apps/api/core'
import { cn } from '@/lib/utils'
import {
Tooltip,
@@ -16,6 +17,31 @@ interface ModelSupportStatusProps {
className?: string
}
+type CheckResult = {
+ status: 'RED' | 'YELLOW' | 'GREEN' | 'GREY' | null
+ effectiveCtx: number
+}
+
+const readTrainContext = async (
+ modelPath: string
+): Promise<number | undefined> => {
+ try {
+ const result = await invoke<{ metadata?: Record<string, string> }>(
+ 'plugin:llamacpp|read_gguf_metadata',
+ { path: modelPath }
+ )
+ const meta = result?.metadata
+ const arch = meta?.['general.architecture']
+ if (!arch) return undefined
+ const raw = meta?.[`${arch}.context_length`]
+ const parsed = raw ? parseInt(raw, 10) : NaN
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
+ } catch (e) {
+ console.error('Error reading GGUF context length:', e)
+ return undefined
+ }
+}
+
export const ModelSupportStatus = ({
modelId,
provider,
@@ -25,14 +51,12 @@ export const ModelSupportStatus = ({
const [modelSupportStatus, setModelSupportStatus] = useState<
'RED' | 'YELLOW' | 'GREEN' | 'LOADING' | null | 'GREY'
>(null)
+ const [effectiveCtx, setEffectiveCtx] = useState<number>(contextSize)
const serviceHub = useServiceHub()
// Helper function to check model support with proper path resolution
const checkModelSupportWithPath = useCallback(
- async (
- id: string,
- ctxSize: number
- ): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY' | null> => {
+ async (id: string, ctxSize: number): Promise<CheckResult> => {
try {
const janDataFolder = await getJanDataFolderPath()
@@ -45,47 +69,53 @@ export const ModelSupportStatus = ({
'model.gguf',
])
- // Check if the standard model.gguf file exists
+ let actualModelPath: string | null = null
if (await fs.existsSync(ggufModelPath)) {
- return await serviceHub.models().isModelSupported(ggufModelPath, ctxSize)
+ actualModelPath = ggufModelPath
+ } else {
+ // If model.gguf doesn't exist, try reading from model.yml (for imported models)
+ const modelConfigPath = await joinPath([
+ janDataFolder,
+ 'llamacpp',
+ 'models',
+ id,
+ 'model.yml',
+ ])
+
+ if (!(await fs.existsSync(modelConfigPath))) {
+ console.error(
+ `Neither model.gguf nor model.yml found for model: ${id}`
+ )
+ return { status: null, effectiveCtx: ctxSize }
+ }
+
+ const modelConfig = await serviceHub
+ .app()
+ .readYaml<{ model_path: string }>(
+ `llamacpp/models/${id}/model.yml`
+ )
+
+ actualModelPath =
+ modelConfig.model_path.startsWith('/') ||
+ modelConfig.model_path.match(/^[A-Za-z]:/)
+ ? modelConfig.model_path
+ : await joinPath([janDataFolder, modelConfig.model_path])
}
- // If model.gguf doesn't exist, try reading from model.yml (for imported models)
- const modelConfigPath = await joinPath([
- janDataFolder,
- 'llamacpp',
- 'models',
- id,
- 'model.yml',
- ])
-
- if (!(await fs.existsSync(modelConfigPath))) {
- console.error(
- `Neither model.gguf nor model.yml found for model: ${id}`
- )
- return null
- }
-
- // Read the model configuration to get the actual model path
- const modelConfig = await serviceHub.app().readYaml<{ model_path: string }>(
- `llamacpp/models/${id}/model.yml`
- )
-
- // Handle both absolute and relative paths
- const actualModelPath =
- modelConfig.model_path.startsWith('/') ||
- modelConfig.model_path.match(/^[A-Za-z]:/)
- ? modelConfig.model_path // absolute path, use as-is
- : await joinPath([janDataFolder, modelConfig.model_path]) // relative path, join with data folder
-
- return await serviceHub.models().isModelSupported(actualModelPath, ctxSize)
+ const trainCtx = await readTrainContext(actualModelPath)
+ const ctxForCheck = trainCtx
+ ? Math.min(ctxSize, trainCtx)
+ : ctxSize
+ const status = await serviceHub
+ .models()
+ .isModelSupported(actualModelPath, ctxForCheck)
+ return { status, effectiveCtx: trainCtx ?? ctxSize }
} catch (error) {
console.error(
'Error checking model support with path resolution:',
error
)
- // If path construction or model support check fails, assume not supported
- return null
+ return { status: null, effectiveCtx: ctxSize }
}
},
[serviceHub]
@@ -111,11 +141,11 @@ export const ModelSupportStatus = ({
const getStatusTooltip = (): string => {
switch (modelSupportStatus) {
case 'GREEN':
- return `Works Well on your device (ctx: ${contextSize})`
+ return `Works Well on your device (ctx: ${effectiveCtx})`
case 'YELLOW':
- return `Might work on your device (ctx: ${contextSize})`
+ return `Might work on your device (ctx: ${effectiveCtx})`
case 'RED':
- return `Doesn't work on your device (ctx: ${contextSize})`
+ return `Doesn't work on your device (ctx: ${effectiveCtx})`
case 'LOADING':
return 'Checking device compatibility...'
default:
@@ -130,11 +160,12 @@ export const ModelSupportStatus = ({
// Set loading state immediately
setModelSupportStatus('LOADING')
try {
- const supportStatus = await checkModelSupportWithPath(
+ const { status, effectiveCtx: ctx } = await checkModelSupportWithPath(
modelId,
contextSize
)
- setModelSupportStatus(supportStatus)
+ setEffectiveCtx(ctx)
+ setModelSupportStatus(status)
} catch (error) {
console.error('Error checking model support:', error)
setModelSupportStatus('RED')
diff --git a/web-app/src/containers/dialogs/DeleteModel.tsx b/web-app/src/containers/dialogs/DeleteModel.tsx
index 5c387c96b..0ce60224e 100644
--- a/web-app/src/containers/dialogs/DeleteModel.tsx
+++ b/web-app/src/containers/dialogs/DeleteModel.tsx
@@ -94,9 +94,9 @@ export const DialogDeleteModel = ({
return (
<Dialog>
- <DialogTrigger asChild>
- <Tooltip>
- <TooltipTrigger asChild>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DialogTrigger asChild>
<div
role="button"
tabIndex={0}
@@ -105,12 +105,12 @@ export const DialogDeleteModel = ({
>
<IconTrash size={18} className="text-muted-foreground" />
</div>
- </TooltipTrigger>
- <TooltipContent>
- <p>{t('providers:deleteModel.delete')}</p>
- </TooltipContent>
- </Tooltip>
- </DialogTrigger>
+ </DialogTrigger>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{t('providers:deleteModel.delete')}</p>
+ </TooltipContent>
+ </Tooltip>
<DialogContent>
<DialogHeader>
<DialogTitle>
diff --git a/web-app/src/containers/dialogs/ImportVisionModelDialog.tsx b/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx
similarity index 77%
rename from web-app/src/containers/dialogs/ImportVisionModelDialog.tsx
rename to web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx
index 2ab1c36f9..0c4dfbf7a 100644
--- a/web-app/src/containers/dialogs/ImportVisionModelDialog.tsx
+++ b/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx
@@ -13,26 +13,61 @@ import { useState, useEffect, useCallback } from 'react'
import { toast } from 'sonner'
import {
IconLoader2,
- IconEye,
+ IconSparkles,
+ IconPhoto,
+ IconMicrophone,
IconCheck,
IconAlertTriangle,
+ IconCodeCircle2,
} from '@tabler/icons-react'
-type ImportVisionModelDialogProps = {
+type DetectedModalities = { vision: boolean; audio: boolean }
+
+const EMBEDDING_GGUF_ARCHS = new Set([
+ 'bert',
+ 'nomic-bert',
+ 'nomic-bert-moe',
+ 'jina-bert-v2',
+ 'jina-bert-v3',
+ 'xlm-roberta',
+ 'mpnet',
+ 't5encoder',
+ 'gemma-embedding',
+ 'pangu-embedded',
+ 'llama-embed',
+])
+
+function detectEmbeddingFromMetadata(
+ meta: Record<string, string> | undefined
+): boolean {
+ if (!meta) return false
+ const arch = meta['general.architecture']
+ if (typeof arch !== 'string') return false
+ if (EMBEDDING_GGUF_ARCHS.has(arch)) return true
+ if (arch.toLowerCase().includes('embed')) return true
+ const poolingRaw = meta[`${arch}.pooling_type`]
+ if (typeof poolingRaw === 'string' && poolingRaw.length > 0) {
+ const n = Number(poolingRaw)
+ if (Number.isFinite(n) && n > 0) return true
+ }
+ return false
+}
+
+type ImportLlamacppModelDialogProps = {
provider: ModelProvider
trigger?: React.ReactNode
onSuccess?: (importedModelName?: string) => void
}
-export const ImportVisionModelDialog = ({
+export const ImportLlamacppModelDialog = ({
provider,
trigger,
onSuccess,
-}: ImportVisionModelDialogProps) => {
+}: ImportLlamacppModelDialogProps) => {
const serviceHub = useServiceHub()
const [open, setOpen] = useState(false)
const [importing, setImporting] = useState(false)
- const [isVisionModel, setIsVisionModel] = useState(false)
+ const [isMultimodal, setIsMultimodal] = useState(false)
const [modelFile, setModelFile] = useState<string | null>(null)
const [mmProjFile, setMmProjFile] = useState<string | null>(null)
const [modelName, setModelName] = useState('')
@@ -42,6 +77,9 @@ export const ImportVisionModelDialog = ({
string | null
>(null)
const [isValidatingMmproj, setIsValidatingMmproj] = useState(false)
+ const [detectedModalities, setDetectedModalities] =
+ useState<DetectedModalities | null>(null)
+ const [isEmbeddingModel, setIsEmbeddingModel] = useState(false)
const validateGgufFile = useCallback(
async (filePath: string, fileType: 'model' | 'mmproj'): Promise<void> => {
@@ -67,7 +105,18 @@ export const ImportVisionModelDialog = ({
setModelName(await serviceHub.path().basename(filePath))
- // Model files should NOT be clip
+ const embedding = detectEmbeddingFromMetadata(
+ result.metadata.metadata
+ )
+ setIsEmbeddingModel(embedding)
+ if (embedding) {
+ setIsMultimodal(false)
+ setMmProjFile(null)
+ setMmprojValidationError(null)
+ setIsValidatingMmproj(false)
+ setDetectedModalities(null)
+ }
+
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.'
@@ -97,19 +146,27 @@ export const ImportVisionModelDialog = ({
}
)
- // Check if architecture matches expected type
- const architecture = (
+ const meta = (
metadata as { metadata?: Record<string, string> }
- ).metadata?.['general.architecture']
+ ).metadata
+ const architecture = meta?.['general.architecture']
- // MMProj files MUST be clip
if (architecture !== 'clip') {
- const errorMessage = `This MMProj file has "${architecture}" architecture but should have "clip" architecture. MMProj files must be CLIP models for vision processing.`
+ const errorMessage = `This MMProj file has "${architecture}" architecture but should have "clip" architecture. MMProj files must be CLIP models for vision or audio processing.`
setMmprojValidationError(errorMessage)
+ setDetectedModalities(null)
console.error(
'Non-CLIP architecture detected in mmproj file:',
architecture
)
+ } else {
+ 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'])
+ setDetectedModalities(
+ vision || audio ? { vision, audio } : { vision: true, audio: false }
+ )
}
} catch (directError) {
console.error(
@@ -192,8 +249,8 @@ export const ImportVisionModelDialog = ({
return
}
- if (isVisionModel && !mmProjFile) {
- toast.error('Please select both model and MMPROJ files for vision models')
+ if (isMultimodal && !mmProjFile) {
+ toast.error('Please select both model and MMPROJ files for multimodal models')
return
}
@@ -217,7 +274,7 @@ export const ImportVisionModelDialog = ({
setImporting(true)
try {
- if (isVisionModel && mmProjFile) {
+ if (isMultimodal && mmProjFile) {
// Import vision model with both files - let backend calculate SHA256 and sizes
await serviceHub.models().pullModel(
modelName,
@@ -255,19 +312,20 @@ export const ImportVisionModelDialog = ({
setModelFile(null)
setMmProjFile(null)
setModelName('')
- setIsVisionModel(false)
+ setIsMultimodal(false)
setValidationError(null)
setIsValidating(false)
setMmprojValidationError(null)
setIsValidatingMmproj(false)
+ setDetectedModalities(null)
+ setIsEmbeddingModel(false)
}
- // Re-validate MMProj file when model name changes
useEffect(() => {
- if (mmProjFile && modelName && isVisionModel) {
+ if (mmProjFile && modelName && isMultimodal) {
validateMmprojFile(mmProjFile)
}
- }, [modelName, mmProjFile, isVisionModel, validateMmprojFile])
+ }, [modelName, mmProjFile, isMultimodal, validateMmprojFile])
const handleOpenChange = (newOpen: boolean) => {
if (!importing) {
@@ -291,36 +349,36 @@ export const ImportVisionModelDialog = ({
Import Model
</DialogTitle>
<DialogDescription>
- Import a GGUF model file to add it to your collection. Enable vision
- support for models that work with images.
+ Import a GGUF model file to add it to your collection. Enable
+ multimodal support to attach an mmproj for image or audio input.
+ Embedding models are detected automatically.
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
- {/* Vision Model Toggle Card */}
<div className="border rounded-lg p-4 space-y-3">
<div className="flex items-start space-x-3">
<div className="shrink-0 mt-0.5">
- <IconEye size={20} className="text-muted-foreground" />
+ <IconSparkles size={20} className="text-muted-foreground" />
</div>
<div className="flex-1">
- <h3 className="font-medium">
- Vision Model Support
- </h3>
+ <h3 className="font-medium">Multimodal Support</h3>
<p className="text-sm text-muted-foreground leading-normal">
- Enable if your model supports image understanding (requires
- MMPROJ file)
+ Enable if your model uses an mmproj for image or audio input.
+ Modalities are detected from the projector file.
</p>
</div>
<Switch
- id="vision-model"
- checked={isVisionModel}
+ id="multimodal"
+ checked={isMultimodal}
+ disabled={isEmbeddingModel}
onCheckedChange={(checked) => {
- setIsVisionModel(checked)
+ setIsMultimodal(checked)
if (!checked) {
setMmProjFile(null)
setMmprojValidationError(null)
setIsValidatingMmproj(false)
+ setDetectedModalities(null)
}
}}
className="mt-1"
@@ -422,6 +480,21 @@ export const ImportVisionModelDialog = ({
</div>
</div>
)}
+
+ {!isValidating && !validationError && isEmbeddingModel && (
+ <div className="border rounded-lg p-3 flex items-start gap-2">
+ <IconCodeCircle2 size={16} className="mt-0.5 shrink-0" />
+ <div>
+ <p className="text-sm font-medium">
+ Embedding model detected
+ </p>
+ <p className="text-xs text-muted-foreground mt-1">
+ This model will be imported for embeddings only.
+ Multimodal options are disabled.
+ </p>
+ </div>
+ </div>
+ )}
</div>
) : (
<Button
@@ -436,13 +509,12 @@ export const ImportVisionModelDialog = ({
)}
</div>
- {/* MMPROJ File Selection - only show if vision model is enabled */}
- {isVisionModel && (
+ {isMultimodal && (
<div className="border rounded-lg p-4 space-y-3">
<div className="flex items-center gap-2">
<h3 className="font-medium">MMPROJ File</h3>
<span className="text-xs bg-secondary px-2 py-1 rounded-sm">
- Required for Vision
+ Required for Multimodal
</span>
</div>
@@ -477,6 +549,27 @@ export const ImportVisionModelDialog = ({
Change
</Button>
</div>
+ {!isValidatingMmproj &&
+ !mmprojValidationError &&
+ detectedModalities && (
+ <div className="flex items-center gap-2 mt-3 pt-3 border-t">
+ <span className="text-xs text-muted-foreground">
+ Detected:
+ </span>
+ {detectedModalities.vision && (
+ <span className="inline-flex items-center gap-1 text-xs bg-secondary px-2 py-0.5 rounded-sm">
+ <IconPhoto size={12} />
+ Vision
+ </span>
+ )}
+ {detectedModalities.audio && (
+ <span className="inline-flex items-center gap-1 text-xs bg-secondary px-2 py-0.5 rounded-sm">
+ <IconMicrophone size={12} />
+ Audio
+ </span>
+ )}
+ </div>
+ )}
</div>
{/* MMProj Validation Error Display */}
@@ -546,7 +639,7 @@ export const ImportVisionModelDialog = ({
importing ||
!modelFile ||
!modelName ||
- (isVisionModel && !mmProjFile) ||
+ (isMultimodal && !mmProjFile) ||
validationError !== null ||
isValidating ||
mmprojValidationError !== null ||
@@ -554,11 +647,7 @@ export const ImportVisionModelDialog = ({
}
>
{importing && <IconLoader2 className="mr-2 size-4 animate-spin" />}
- {importing ? (
- 'Importing...'
- ) : (
- <>Import {isVisionModel ? 'Vision ' : ''}Model</>
- )}
+ {importing ? 'Importing...' : 'Import Model'}
</Button>
</div>
</DialogContent>
diff --git a/web-app/src/containers/dialogs/__tests__/ImportVisionModelDialog.test.tsx b/web-app/src/containers/dialogs/__tests__/ImportLlamacppModelDialog.test.tsx
similarity index 94%
rename from web-app/src/containers/dialogs/__tests__/ImportVisionModelDialog.test.tsx
rename to web-app/src/containers/dialogs/__tests__/ImportLlamacppModelDialog.test.tsx
index d7700c091..711cf2528 100644
--- a/web-app/src/containers/dialogs/__tests__/ImportVisionModelDialog.test.tsx
+++ b/web-app/src/containers/dialogs/__tests__/ImportLlamacppModelDialog.test.tsx
@@ -38,7 +38,7 @@ vi.mock('@tauri-apps/api/core', () => ({
invoke: hoisted.invoke,
}))
-import { ImportVisionModelDialog } from '../ImportVisionModelDialog'
+import { ImportLlamacppModelDialog } from '../ImportLlamacppModelDialog'
const provider = { models: [] } as unknown as any
@@ -46,7 +46,7 @@ const openDialog = () => {
fireEvent.click(screen.getByText('Open'))
}
-describe('ImportVisionModelDialog', () => {
+describe('ImportLlamacppModelDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
hoisted.validateGgufFile.mockResolvedValue({
@@ -60,7 +60,7 @@ describe('ImportVisionModelDialog', () => {
it('renders the trigger and opens the dialog content', () => {
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -72,7 +72,7 @@ describe('ImportVisionModelDialog', () => {
it('shows Select MMPROJ File when the vision switch is enabled', () => {
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -85,7 +85,7 @@ describe('ImportVisionModelDialog', () => {
it('toasts an error when Import is clicked with no model file selected', () => {
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -101,7 +101,7 @@ describe('ImportVisionModelDialog', () => {
hoisted.dialogOpen.mockResolvedValueOnce('/tmp/model.gguf')
hoisted.basename.mockReturnValueOnce('model.gguf')
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -124,7 +124,7 @@ describe('ImportVisionModelDialog', () => {
metadata: { metadata: { 'general.architecture': 'clip' } },
})
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -142,7 +142,7 @@ describe('ImportVisionModelDialog', () => {
models: [{ name: 'dup.gguf' }],
} as unknown as any
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={providerWithModel}
trigger={<button>Open</button>}
/>
@@ -171,7 +171,7 @@ describe('ImportVisionModelDialog', () => {
hoisted.pullModel.mockResolvedValueOnce(undefined)
const onSuccess = vi.fn()
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
onSuccess={onSuccess}
@@ -204,7 +204,7 @@ describe('ImportVisionModelDialog', () => {
hoisted.dialogOpen.mockResolvedValueOnce('/tmp/fail.gguf')
hoisted.pullModel.mockRejectedValueOnce(new Error('boom'))
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -228,7 +228,7 @@ describe('ImportVisionModelDialog', () => {
it('renders the MMPROJ file chip after selection', async () => {
hoisted.dialogOpen.mockResolvedValueOnce('/tmp/mmproj.gguf')
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -254,7 +254,7 @@ describe('ImportVisionModelDialog', () => {
metadata: { 'general.architecture': 'llama' },
})
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
@@ -269,7 +269,7 @@ describe('ImportVisionModelDialog', () => {
it('Cancel button closes the dialog', async () => {
render(
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
trigger={<button>Open</button>}
/>
diff --git a/web-app/src/hooks/__tests__/useModelProvider.test.ts b/web-app/src/hooks/__tests__/useModelProvider.test.ts
index 111f52177..aa9443afa 100644
--- a/web-app/src/hooks/__tests__/useModelProvider.test.ts
+++ b/web-app/src/hooks/__tests__/useModelProvider.test.ts
@@ -129,7 +129,7 @@ describe('useModelProvider - displayName functionality', () => {
expect(provider?.models[0].displayName).toBe('My Custom Model')
})
- it('should preserve user-configured capabilities when merging setProviders refresh', () => {
+ it('should preserve user-controlled capabilities but always pick up engine-owned ones (vision/audio/embeddings) on refresh', () => {
const { result } = renderHook(() => useModelProvider())
act(() => {
@@ -174,7 +174,7 @@ describe('useModelProvider - displayName functionality', () => {
})
const provider = result.current.getProviderByName('llamacpp')
- expect(provider?.models[0].capabilities).toEqual(['completion'])
+ expect(provider?.models[0].capabilities).toEqual(['completion', 'vision'])
expect(
(provider?.models[0] as { _userConfiguredCapabilities?: boolean })
._userConfiguredCapabilities
diff --git a/web-app/src/hooks/useDefaultEmbeddingModel.ts b/web-app/src/hooks/useDefaultEmbeddingModel.ts
new file mode 100644
index 000000000..8f147541f
--- /dev/null
+++ b/web-app/src/hooks/useDefaultEmbeddingModel.ts
@@ -0,0 +1,36 @@
+import { create } from 'zustand'
+import { persist, createJSONStorage } from 'zustand/middleware'
+import { localStorageKey } from '@/constants/localStorage'
+
+interface DefaultEmbeddingModelState {
+ defaultByProvider: Record<string, string>
+ setDefault: (provider: string, modelId: string) => void
+ clearDefault: (provider: string) => void
+ getDefault: (provider: string) => string | undefined
+}
+
+export const useDefaultEmbeddingModel = create<DefaultEmbeddingModelState>()(
+ persist(
+ (set, get) => ({
+ defaultByProvider: {},
+ setDefault: (provider, modelId) =>
+ set((state) => ({
+ defaultByProvider: {
+ ...state.defaultByProvider,
+ [provider]: modelId,
+ },
+ })),
+ clearDefault: (provider) =>
+ set((state) => {
+ const next = { ...state.defaultByProvider }
+ delete next[provider]
+ return { defaultByProvider: next }
+ }),
+ getDefault: (provider) => get().defaultByProvider[provider],
+ }),
+ {
+ name: localStorageKey.defaultEmbeddingModel,
+ storage: createJSONStorage(() => localStorage),
+ }
+ )
+)
diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.ts
index 4d93693cc..d6ac7dd5d 100644
--- a/web-app/src/hooks/useModelProvider.ts
+++ b/web-app/src/hooks/useModelProvider.ts
@@ -113,15 +113,17 @@ export const useModelProvider = create<ModelProviderState>()(
}
)?._userConfiguredCapabilities === true
- // When the user set tools/vision in Edit Model, honor that list on every
- // refresh from the engine; otherwise fresh engine data would re-add defaults.
+ const engineOwnedCaps = new Set(['vision', 'audio', 'embeddings'])
+ const engineCaps = model.capabilities || []
+ const existingCaps = existingModel?.capabilities || []
const mergedCapabilities = userConfiguredCapabilities
- ? [...(existingModel?.capabilities || [])]
+ ? [
+ ...existingCaps.filter((c) => !engineOwnedCaps.has(c)),
+ ...engineCaps.filter((c) => engineOwnedCaps.has(c)),
+ ]
: [
- ...(model.capabilities || []),
- ...(existingModel?.capabilities || []).filter(
- (cap) => !(model.capabilities || []).includes(cap)
- ),
+ ...engineCaps,
+ ...existingCaps.filter((c) => !engineCaps.includes(c)),
]
return {
...model,
diff --git a/web-app/src/hooks/useTokensCount.ts b/web-app/src/hooks/useTokensCount.ts
index 07d81ff58..49cc76611 100644
--- a/web-app/src/hooks/useTokensCount.ts
+++ b/web-app/src/hooks/useTokensCount.ts
@@ -1,287 +1,175 @@
-import { useCallback, useState, useRef, useEffect, useMemo } from 'react'
-import { ThreadMessage, ContentType } from '@janhq/core'
-import { useServiceHub } from './useServiceHub'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { ThreadMessage } from '@janhq/core'
+import { ExtensionManager } from '@/lib/extension'
import { useModelProvider } from './useModelProvider'
-import { usePrompt } from './usePrompt'
-import { removeReasoningContent } from '@/utils/reasoning'
+
+export interface ModelProps {
+ nCtx: number
+ totalSlots?: number
+ modelAlias?: string
+ isSleeping?: boolean
+}
export interface TokenCountData {
tokenCount: number
+ inputTokens?: number
+ outputTokens?: number
maxTokens?: number
percentage?: number
isNearLimit: boolean
loading: boolean
+ modelProps?: ModelProps
+ modelDisplayName?: string
+ fitEnabled: boolean
+ configuredCtxLen?: number
+ modalities?: { vision: boolean; audio: boolean }
error?: string
}
-type InlineFileContent = {
- name?: string
- content: string
+interface UsageMeta {
+ inputTokens?: number
+ outputTokens?: number
+ totalTokens?: number
}
-const getInlineFileContents = (
- metadata: ThreadMessage['metadata']
-): InlineFileContent[] => {
- const inlineFileContents = (
- metadata as { inline_file_contents?: unknown }
- )?.inline_file_contents
-
- if (!Array.isArray(inlineFileContents)) return []
-
- return inlineFileContents.filter((file): file is InlineFileContent => {
- if (!file || typeof file !== 'object') return false
- const { content, name } = file as { content?: unknown; name?: unknown }
-
- const hasContent = typeof content === 'string' && content.length > 0
- const hasValidName =
- typeof name === 'string' || typeof name === 'undefined'
-
- return hasContent && hasValidName
- })
+interface LlamacppExtensionLike {
+ getModelProps?: (modelId: string) => Promise<ModelProps | undefined>
}
-export const useTokensCount = (
- messages: ThreadMessage[] = [],
- uploadedFiles?: Array<{
- name: string
- type: string
- size: number
- base64: string
- dataUrl: string
- }>,
- additionalContextText?: string
-) => {
- const [tokenData, setTokenData] = useState<TokenCountData>({
- tokenCount: 0,
- loading: false,
- isNearLimit: false,
- })
-
- const debounceTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined)
- const latestCalculationRef = useRef<(() => Promise<void>) | null>(null)
- const requestIdRef = useRef(0)
- const isIncreasingContextSize = useRef<boolean>(false)
- const serviceHub = useServiceHub()
- const { selectedModel, selectedProvider } = useModelProvider()
- const { prompt } = usePrompt()
-
- // Create messages with current prompt for live calculation.
- // This mirrors the payload sent to token counting by appending the draft
- // user message (text plus any uploaded images) to the existing thread
- // history so the model sees the full context that will be submitted.
- const messagesWithPrompt = useMemo(() => {
- const result = [...messages]
- if (prompt.trim() || (uploadedFiles && uploadedFiles.length > 0)) {
- const content = []
-
- // Add text content if prompt exists
- if (prompt.trim()) {
- content.push({ type: ContentType.Text, text: { value: prompt } })
- }
-
- // Add image content for uploaded files
- if (uploadedFiles && uploadedFiles.length > 0) {
- uploadedFiles.forEach((file) => {
- content.push({
- type: ContentType.Image,
- image_url: {
- url: file.dataUrl,
- detail: 'high', // Default to high detail for token calculation
- },
- })
- })
- }
-
- if (content.length > 0) {
- result.push({
- id: 'temp-prompt',
- thread_id: '',
- role: 'user',
- content,
- created_at: Date.now(),
- } as ThreadMessage)
- }
- }
-
- if (additionalContextText?.trim()) {
- result.push({
- id: 'temp-runtime-context',
- thread_id: '',
- role: 'system',
- content: [
- {
- type: ContentType.Text,
- text: { value: additionalContextText.trim() },
- },
- ],
- created_at: Date.now(),
- } as ThreadMessage)
- }
-
- return result.map((e) => {
- // Pull inline file contents stored on the message metadata
- const inlineFileContents = getInlineFileContents(e.metadata)
-
- const buildInlineText = (base: string) => {
- if (!inlineFileContents.length) return base
- const formatted = inlineFileContents
- .map((f) => `File: ${f.name || 'attachment'}\n${f.content ?? ''}`)
- .join('\n\n')
- return base ? `${base}\n\n${formatted}` : formatted
- }
-
- return {
- ...e,
- content: e.content.map((c) => ({
- ...c,
- text:
- c.type === 'text'
- ? {
- value: removeReasoningContent(
- buildInlineText(c.text?.value ?? '.')
- ),
- annotations: [],
- }
- : c.text,
- })),
- }
- })
- }, [messages, prompt, uploadedFiles, additionalContextText])
-
- // Debounced calculation that includes current prompt
- const runTokenCalculation = useCallback(async () => {
- const requestId = ++requestIdRef.current
- const modelId = selectedModel?.id
-
- if (
- !modelId ||
- selectedProvider !== 'llamacpp' ||
- messagesWithPrompt.length === 0
- ) {
- if (requestId === requestIdRef.current) {
- setTokenData({
- tokenCount: 0,
- loading: false,
- isNearLimit: false,
- })
- }
- return
- }
-
- setTokenData((prev) => ({ ...prev, loading: true, error: undefined }))
-
- try {
- const tokenCount = await serviceHub
- .models()
- .getTokensCount(modelId, messagesWithPrompt)
-
- if (requestId !== requestIdRef.current) {
- return
- }
-
- const maxTokensValue =
- selectedModel?.settings?.ctx_len?.controller_props?.value
- const maxTokensNum =
- typeof maxTokensValue === 'string'
- ? parseInt(maxTokensValue)
- : typeof maxTokensValue === 'number'
- ? maxTokensValue
- : undefined
+const getLatestServerUsage = (messages: ThreadMessage[]): UsageMeta => {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const usage = (messages[i].metadata as { usage?: UsageMeta } | undefined)
+ ?.usage
+ if (usage && typeof usage.totalTokens === 'number' && usage.totalTokens > 0)
+ return usage
+ }
+ return {}
+}
- const percentage = maxTokensNum
- ? (tokenCount / maxTokensNum) * 100
- : undefined
- const isNearLimit = percentage ? percentage > 85 : false
+const getLlamacppExtension = (): LlamacppExtensionLike | undefined => {
+ const mgr = ExtensionManager.getInstance()
+ const candidates = [
+ mgr.getByName('@janhq/llamacpp-extension'),
+ mgr.getByName('llamacpp-extension'),
+ ]
+ for (const c of candidates) {
+ if (c && typeof (c as LlamacppExtensionLike).getModelProps === 'function')
+ return c as LlamacppExtensionLike
+ }
+ return mgr.listExtensions().find(
+ (ext) =>
+ typeof (ext as LlamacppExtensionLike).getModelProps === 'function'
+ ) as LlamacppExtensionLike | undefined
+}
- setTokenData({
- tokenCount,
- maxTokens: maxTokensNum,
- percentage,
- isNearLimit,
- loading: false,
- })
- } catch (error) {
- if (requestId !== requestIdRef.current) {
- return
- }
+const readSettingNumber = (v: unknown): number | undefined => {
+ if (typeof v === 'number' && Number.isFinite(v)) return v
+ if (typeof v === 'string') {
+ const n = parseInt(v, 10)
+ return Number.isFinite(n) ? n : undefined
+ }
+ return undefined
+}
- console.error('Failed to calculate tokens:', error)
- setTokenData((prev) => ({
- ...prev,
- loading: false,
- error:
- error instanceof Error ? error.message : 'Failed to calculate tokens',
- }))
- }
- }, [
- selectedModel?.id,
- selectedProvider,
- messagesWithPrompt,
- serviceHub,
- selectedModel?.settings?.ctx_len?.controller_props?.value,
- ])
+export const useTokensCount = (messages: ThreadMessage[] = []) => {
+ const { selectedModel, selectedProvider, getProviderByName } =
+ useModelProvider()
+ const [modelProps, setModelProps] = useState<ModelProps | undefined>(
+ undefined
+ )
+ const [loading, setLoading] = useState(false)
+ const reqId = useRef(0)
- useEffect(() => {
- latestCalculationRef.current = runTokenCalculation
- }, [runTokenCalculation])
+ const modelId =
+ selectedProvider === 'llamacpp' ? selectedModel?.id : undefined
- // Debounced effect that triggers when prompt or messages change
useEffect(() => {
- // Clear existing timeout
- if (debounceTimeoutRef.current) {
- clearTimeout(debounceTimeoutRef.current)
+ if (!modelId) {
+ setModelProps(undefined)
+ setLoading(false)
+ return
}
-
- // Skip calculation if we're currently increasing context size
- if (isIncreasingContextSize.current) {
+ const ext = getLlamacppExtension()
+ if (!ext?.getModelProps) {
+ setModelProps(undefined)
return
}
+ const id = ++reqId.current
+ setLoading(true)
+ ext
+ .getModelProps(modelId)
+ .then((props) => {
+ if (id !== reqId.current) return
+ setModelProps(props)
+ })
+ .catch(() => {
+ if (id !== reqId.current) return
+ setModelProps(undefined)
+ })
+ .finally(() => {
+ if (id !== reqId.current) return
+ setLoading(false)
+ })
+ }, [modelId, messages.length])
- // Only calculate if we have messages or a prompt
- if (
- messagesWithPrompt.length > 0 &&
- selectedProvider === 'llamacpp' &&
- selectedModel?.id
- ) {
- debounceTimeoutRef.current = setTimeout(() => {
- void latestCalculationRef.current?.()
- }, 500) // 500ms debounce to reduce repeated token calculations
- } else {
- // Reset immediately if no content
- requestIdRef.current += 1
- setTokenData({
+ const tokenData: TokenCountData = useMemo(() => {
+ if (selectedProvider !== 'llamacpp' || !modelId) {
+ return {
tokenCount: 0,
loading: false,
isNearLimit: false,
- })
+ fitEnabled: false,
+ }
+ }
+ const usage = getLatestServerUsage(messages)
+ const tokenCount = usage.totalTokens ?? 0
+ const maxTokens = modelProps?.nCtx
+ const percentage = maxTokens ? (tokenCount / maxTokens) * 100 : undefined
+ const isNearLimit = percentage ? percentage > 85 : false
+
+ const provider = getProviderByName('llamacpp')
+ const fitEnabled =
+ provider?.settings?.find((s) => s.key === 'fit')?.controller_props
+ ?.value === true
+ const configuredCtxLen = readSettingNumber(
+ selectedModel?.settings?.ctx_len?.controller_props?.value
+ )
+ const modelDisplayName =
+ modelProps?.modelAlias || selectedModel?.name || modelId
+ const caps = selectedModel?.capabilities ?? []
+ const modalities = {
+ vision: caps.includes('vision'),
+ audio: caps.includes('audio'),
}
- return () => {
- if (debounceTimeoutRef.current) {
- clearTimeout(debounceTimeoutRef.current)
- }
+ return {
+ tokenCount,
+ inputTokens: usage.inputTokens,
+ outputTokens: usage.outputTokens,
+ maxTokens,
+ percentage,
+ isNearLimit,
+ loading,
+ modelProps,
+ modelDisplayName,
+ fitEnabled,
+ configuredCtxLen,
+ modalities,
}
}, [
- prompt,
- messages.length,
- selectedModel?.id,
+ messages,
+ modelId,
selectedProvider,
- messagesWithPrompt.length,
- messagesWithPrompt,
+ modelProps,
+ loading,
+ getProviderByName,
+ selectedModel?.name,
+ selectedModel?.capabilities,
selectedModel?.settings?.ctx_len?.controller_props?.value,
])
- // Manual calculation function (for click events)
- const calculateTokens = useCallback(async () => {
- // Trigger the debounced calculation immediately
- if (debounceTimeoutRef.current) {
- clearTimeout(debounceTimeoutRef.current)
- }
- await latestCalculationRef.current?.()
- }, [])
-
return {
...tokenData,
- calculateTokens,
+ calculateTokens: async () => undefined,
}
}
diff --git a/web-app/src/lib/__tests__/audio-sentinel.test.ts b/web-app/src/lib/__tests__/audio-sentinel.test.ts
new file mode 100644
index 000000000..214e9a7ef
--- /dev/null
+++ b/web-app/src/lib/__tests__/audio-sentinel.test.ts
@@ -0,0 +1,95 @@
+import { describe, it, expect } from 'vitest'
+import {
+ encodeAudioSentinel,
+ hasAudioSentinel,
+ splitAudioSentinels,
+ parseAudioDataUrl,
+} from '../audio-sentinel'
+import { decodeAudioSentinelsInBody } from '../model-factory'
+
+describe('audio-sentinel', () => {
+ it('round-trips a single sentinel back to an input_audio part', () => {
+ const encoded = encodeAudioSentinel('mp3', 'QUFB')
+ expect(hasAudioSentinel(encoded)).toBe(true)
+ expect(splitAudioSentinels(encoded)).toEqual([
+ { type: 'input_audio', input_audio: { data: 'QUFB', format: 'mp3' } },
+ ])
+ })
+
+ it('preserves surrounding text and ordering', () => {
+ const encoded = `hello${encodeAudioSentinel('wav', 'WlpaWg==')}world`
+ expect(splitAudioSentinels(encoded)).toEqual([
+ { type: 'text', text: 'hello' },
+ { type: 'input_audio', input_audio: { data: 'WlpaWg==', format: 'wav' } },
+ { type: 'text', text: 'world' },
+ ])
+ })
+
+ it('returns null for plain text', () => {
+ expect(splitAudioSentinels('just a message')).toBeNull()
+ })
+
+ it('parses audio data URLs', () => {
+ expect(parseAudioDataUrl('data:audio/mpeg;base64,QUFB')).toEqual({ format: 'mp3', data: 'QUFB' })
+ expect(parseAudioDataUrl('data:audio/wav;base64,WlpaWg==')).toEqual({
+ format: 'wav',
+ data: 'WlpaWg==',
+ })
+ expect(parseAudioDataUrl('data:image/png;base64,XXXX')).toBeNull()
+ })
+
+ describe('decodeAudioSentinelsInBody', () => {
+ it('rewrites a bare-string user content to input_audio + text parts', () => {
+ const body = {
+ messages: [
+ {
+ role: 'user',
+ content: `transcribe: ${encodeAudioSentinel('mp3', 'QUFB')}`,
+ },
+ ],
+ }
+ decodeAudioSentinelsInBody(body)
+ expect(body.messages[0].content).toEqual([
+ { type: 'text', text: 'transcribe: ' },
+ { type: 'input_audio', input_audio: { data: 'QUFB', format: 'mp3' } },
+ ])
+ })
+
+ it('rewrites array content with a sentinel-bearing text part', () => {
+ const body = {
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'hi' },
+ { type: 'text', text: encodeAudioSentinel('wav', 'WlpaWg==') },
+ ],
+ },
+ ],
+ }
+ decodeAudioSentinelsInBody(body)
+ expect(body.messages[0].content).toEqual([
+ { type: 'text', text: 'hi' },
+ { type: 'input_audio', input_audio: { data: 'WlpaWg==', format: 'wav' } },
+ ])
+ })
+
+ it('leaves bodies without sentinels untouched', () => {
+ const body = {
+ messages: [{ role: 'user', content: 'hello world' }],
+ }
+ decodeAudioSentinelsInBody(body)
+ expect(body.messages[0].content).toBe('hello world')
+ })
+
+ it('ignores assistant messages even if they accidentally match', () => {
+ const body = {
+ messages: [
+ { role: 'assistant', content: encodeAudioSentinel('mp3', 'QUFB') },
+ ],
+ }
+ decodeAudioSentinelsInBody(body)
+ expect(body.messages[0].content).toBe(encodeAudioSentinel('mp3', 'QUFB'))
+ })
+ })
+})
diff --git a/web-app/src/lib/__tests__/completion.test.ts b/web-app/src/lib/__tests__/completion.test.ts
new file mode 100644
index 000000000..4cdff7799
--- /dev/null
+++ b/web-app/src/lib/__tests__/completion.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect } from 'vitest'
+import { ContentType } from '@janhq/core'
+import { newUserThreadContent } from '../completion'
+import type { Attachment } from '@/types/attachment'
+
+describe('newUserThreadContent — audio attachments', () => {
+ it('emits an input_audio content part for wav audio', () => {
+ const audio: Attachment = {
+ name: 'clip.wav',
+ type: 'audio',
+ base64: 'QUFB',
+ audioFormat: 'wav',
+ mimeType: 'audio/wav',
+ dataUrl: 'data:audio/wav;base64,QUFB',
+ size: 1024,
+ }
+ const msg = newUserThreadContent('t1', 'hello', [audio], 'm1')
+ const audioPart = msg.content.find(
+ (c) => c.type === ContentType.InputAudio
+ ) as any
+ expect(audioPart).toBeDefined()
+ expect(audioPart.input_audio).toEqual({ data: 'QUFB', format: 'wav' })
+ })
+
+ it('emits an input_audio content part for mp3 audio', () => {
+ const audio: Attachment = {
+ name: 'song.mp3',
+ type: 'audio',
+ base64: 'WlpaWg==',
+ audioFormat: 'mp3',
+ mimeType: 'audio/mpeg',
+ dataUrl: 'data:audio/mpeg;base64,WlpaWg==',
+ size: 2048,
+ }
+ const msg = newUserThreadContent('t1', 'listen', [audio])
+ const audioPart = msg.content.find(
+ (c) => c.type === ContentType.InputAudio
+ ) as any
+ expect(audioPart.input_audio).toEqual({ data: 'WlpaWg==', format: 'mp3' })
+ })
+
+ it('skips audio attachments missing base64 or format', () => {
+ const broken: Attachment = {
+ name: 'broken.wav',
+ type: 'audio',
+ audioFormat: 'wav',
+ mimeType: 'audio/wav',
+ size: 10,
+ }
+ const msg = newUserThreadContent('t1', 'hi', [broken])
+ expect(msg.content.some((c) => c.type === ContentType.InputAudio)).toBe(
+ false
+ )
+ })
+
+ it('coexists with text and image attachments', () => {
+ const image: Attachment = {
+ name: 'pic.png',
+ type: 'image',
+ base64: 'AAA',
+ mimeType: 'image/png',
+ dataUrl: 'data:image/png;base64,AAA',
+ size: 100,
+ }
+ const audio: Attachment = {
+ name: 'clip.wav',
+ type: 'audio',
+ base64: 'QUFB',
+ audioFormat: 'wav',
+ mimeType: 'audio/wav',
+ dataUrl: 'data:audio/wav;base64,QUFB',
+ size: 1024,
+ }
+ const msg = newUserThreadContent('t1', 'with both', [image, audio], 'm1')
+ const types = msg.content.map((c) => c.type)
+ expect(types).toContain(ContentType.Text)
+ expect(types).toContain(ContentType.Image)
+ expect(types).toContain(ContentType.InputAudio)
+ })
+})
diff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
index a2d7d37f7..db4369922 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { normalizeToolInputSchema } from '../custom-chat-transport'
+import {
+ buildLlamacppReasoningParams,
+ normalizeToolInputSchema,
+} from '../custom-chat-transport'
describe('normalizeToolInputSchema', () => {
it('adds empty properties for object schemas without properties', () => {
@@ -168,3 +171,48 @@ describe('normalizeToolInputSchema', () => {
})
})
})
+
+describe('buildLlamacppReasoningParams', () => {
+ it('returns empty object for non-llamacpp providers regardless of reasoning value', () => {
+ expect(buildLlamacppReasoningParams('openai', 'on')).toEqual({})
+ expect(buildLlamacppReasoningParams('anthropic', 'off')).toEqual({})
+ expect(buildLlamacppReasoningParams(null, 'on')).toEqual({})
+ expect(buildLlamacppReasoningParams(undefined, 'off')).toEqual({})
+ })
+
+ it('omits the kwarg for llamacpp when reasoning is auto or undefined', () => {
+ expect(buildLlamacppReasoningParams('llamacpp', 'auto')).toEqual({})
+ expect(buildLlamacppReasoningParams('llamacpp', undefined)).toEqual({})
+ })
+
+ it('emits chat_template_kwargs.enable_thinking=true for on', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'on')
+ expect(params).toEqual({
+ chat_template_kwargs: { enable_thinking: true },
+ })
+ })
+
+ it('emits chat_template_kwargs.enable_thinking=false for off', () => {
+ const params = buildLlamacppReasoningParams('llamacpp', 'off')
+ expect(params).toEqual({
+ chat_template_kwargs: { enable_thinking: false },
+ })
+ })
+
+ // Regression: llama-server's server-common.cpp:1056-1069 parses kwargs via
+ // `json_value(...).dump()` and rejects values that serialize to a quoted
+ // string ("invalid type for \"enable_thinking\" (expected boolean, got
+ // string)"). The value MUST be a JSON boolean.
+ it('emits enable_thinking as a JSON boolean, not a string', () => {
+ for (const r of ['on', 'off'] as const) {
+ const params = buildLlamacppReasoningParams('llamacpp', r)
+ const value = params.chat_template_kwargs?.enable_thinking
+ expect(typeof value).toBe('boolean')
+ expect(value).not.toBe('true')
+ expect(value).not.toBe('false')
+ // The exact serialization llama-server sees: JSON.stringify of the
+ // value must produce literal `true` / `false`, never quoted strings.
+ expect(JSON.stringify(value)).toMatch(/^(true|false)$/)
+ }
+ })
+})
diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.ts
index 8b9a35870..9f1e31ef2 100644
--- a/web-app/src/lib/__tests__/messages.test.ts
+++ b/web-app/src/lib/__tests__/messages.test.ts
@@ -82,6 +82,28 @@ describe('convertUIMessageToThreadMessage', () => {
expect(result.content[0].type).toBe(ContentType.Text)
})
+ it('converts wav audio file parts to input_audio', () => {
+ const msg = mkUI({
+ parts: [{ type: 'file', mediaType: 'audio/wav', url: 'data:audio/wav;base64,QUFB' } as any],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.content[0]).toMatchObject({
+ type: ContentType.InputAudio,
+ input_audio: { data: 'QUFB', format: 'wav' },
+ })
+ })
+
+ it('converts mp3 audio file parts to input_audio', () => {
+ const msg = mkUI({
+ parts: [{ type: 'file', mediaType: 'audio/mpeg', url: 'data:audio/mpeg;base64,WlpaWg==' } as any],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.content[0]).toMatchObject({
+ type: ContentType.InputAudio,
+ input_audio: { data: 'WlpaWg==', format: 'mp3' },
+ })
+ })
+
it('creates empty text when no content extracted', () => {
const result = convertUIMessageToThreadMessage(mkUI({ parts: [] }), 't1')
expect(result.content[0].text!.value).toBe('')
@@ -159,6 +181,28 @@ describe('convertThreadMessageToUIMessage', () => {
expect(result.parts).toContainEqual({ type: 'file', mediaType: 'image/jpeg', url: 'http://img.png' })
})
+ it('converts input_audio content to a file part with audio mediaType', () => {
+ const wav = convertThreadMessageToUIMessage(makeTm({
+ role: 'user',
+ content: [{ type: 'input_audio', input_audio: { data: 'QUFB', format: 'wav' } }],
+ }) as any)
+ expect(wav.parts).toContainEqual({
+ type: 'file',
+ mediaType: 'audio/wav',
+ url: 'data:audio/wav;base64,QUFB',
+ })
+
+ const mp3 = convertThreadMessageToUIMessage(makeTm({
+ role: 'user',
+ content: [{ type: 'input_audio', input_audio: { data: 'WlpaWg==', format: 'mp3' } }],
+ }) as any)
+ expect(mp3.parts).toContainEqual({
+ type: 'file',
+ mediaType: 'audio/mpeg',
+ url: 'data:audio/mpeg;base64,WlpaWg==',
+ })
+ })
+
it('converts tool_call content with and without output', () => {
const withOutput = convertThreadMessageToUIMessage(makeTm({
content: [{ type: 'tool_call', tool_call_id: 'tc-1', tool_name: 'search', input: { q: 'test' }, output: 'result' }],
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index 987e170e1..52f57957c 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -163,6 +163,15 @@ export const processAttachmentsForSend = async (
}
}
+ const audios = attachments.filter((a) => a.type === 'audio')
+ for (const aud of audios) {
+ processedAttachments.push({
+ ...aud,
+ processed: true,
+ processing: false,
+ })
+ }
+
const documents = attachments.filter((a) => a.type === 'document')
for (const doc of documents) {
try {
diff --git a/web-app/src/lib/audio-sentinel.ts b/web-app/src/lib/audio-sentinel.ts
new file mode 100644
index 000000000..13c9afa9c
Binary files /dev/null and b/web-app/src/lib/audio-sentinel.ts differ
diff --git a/web-app/src/lib/completion.ts b/web-app/src/lib/completion.ts
index fc500754a..ec4640728 100644
--- a/web-app/src/lib/completion.ts
+++ b/web-app/src/lib/completion.ts
@@ -23,8 +23,9 @@ export const newUserThreadContent = (
attachments?: Attachment[],
id?: string
): ThreadMessage => {
- // Separate images and documents
+ // Separate images, audio, and documents
const images = attachments?.filter((a) => a.type === 'image') || []
+ const audios = attachments?.filter((a) => a.type === 'audio') || []
const documents = attachments?.filter((a) => a.type === 'document') || []
const inlineDocuments = documents.filter(
@@ -68,6 +69,18 @@ export const newUserThreadContent = (
}
})
+ audios.forEach((aud) => {
+ if (aud.base64 && aud.audioFormat) {
+ contentParts.push({
+ type: ContentType.InputAudio,
+ input_audio: {
+ data: aud.base64,
+ format: aud.audioFormat,
+ },
+ } as any)
+ }
+ })
+
return {
type: 'text',
role: ChatCompletionRole.User,
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index e9aeab74f..801bfeefe 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -18,6 +18,8 @@ import { useAssistant } from '@/hooks/useAssistant'
import { useThreads } from '@/hooks/useThreads'
import { useAttachments } from '@/hooks/useAttachments'
import { useMCPServers } from '@/hooks/useMCPServers'
+import { useAppState } from '@/hooks/useAppState'
+import { invoke } from '@tauri-apps/api/core'
import { ExtensionManager } from '@/lib/extension'
import {
ExtensionTypeEnum,
@@ -32,6 +34,8 @@ import {
} from './context-manager'
import { mcpOrchestrator } from '@/lib/mcp-orchestrator'
import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'
+import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'
+import { extractFilesFromPrompt, type FileMetadata } from '@/lib/fileMetadata'
export type TokenUsageCallback = (
usage: LanguageModelUsage,
@@ -112,6 +116,26 @@ export function normalizeToolInputSchema(
}
/** Text from the most recent user message (for MCP server routing). */
+/**
+ * Build the per-request reasoning kwargs for llama-server's chat completions
+ * endpoint. The server parses `chat_template_kwargs.enable_thinking` via
+ * `json_value(...).dump()` (server-common.cpp:1056-1069) and rejects values
+ * that serialize to a quoted JSON string — so this must emit a JSON boolean
+ * (`true` / `false`), never the strings `"true"` / `"false"`. 'auto' omits
+ * the kwarg entirely so the server falls back to its --reasoning-budget
+ * default. The function is a no-op for non-llamacpp providers.
+ */
+export function buildLlamacppReasoningParams(
+ providerName: string | null | undefined,
+ reasoning: 'auto' | 'on' | 'off' | undefined
+): { chat_template_kwargs?: { enable_thinking: boolean } } {
+ if (providerName !== 'llamacpp') return {}
+ if (reasoning !== 'on' && reasoning !== 'off') return {}
+ return {
+ chat_template_kwargs: { enable_thinking: reasoning === 'on' },
+ }
+}
+
function extractLatestUserText(messages: UIMessage[]): string {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i]
@@ -457,14 +481,39 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const currentAssistant = useAssistant.getState().currentAssistant
const inferenceParams = currentAssistant?.parameters
+ const selectedModel = useModelProvider.getState().selectedModel
+ const reasoningParams = buildLlamacppReasoningParams(
+ effectiveProviderName,
+ selectedModel?.settings?.reasoning?.controller_props?.value as
+ | 'auto'
+ | 'on'
+ | 'off'
+ | undefined
+ )
+
+ if (providerId === 'llamacpp') {
+ try {
+ const loaded = await invoke<string[]>(
+ 'plugin:llamacpp|get_loaded_models'
+ )
+ if (!loaded.includes(modelId)) {
+ useAppState.getState().updateLoadingModel(true)
+ }
+ } catch {
+ // Ignore probe failures; the router will still load on demand
+ }
+ }
+
// Create the model before refreshing tools so the MCP orchestrator can run
// structured LLM routing when many servers are connected.
this.model = await ModelFactory.createModel(
modelId,
updatedProvider ?? provider,
- inferenceParams ?? {}
+ { ...(inferenceParams ?? {}), ...reasoningParams }
)
+ useAppState.getState().updateLoadingModel(false)
} catch (error) {
+ useAppState.getState().updateLoadingModel(false)
console.error('Failed to create model:', error)
throw new Error(
`Failed to create model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
@@ -478,7 +527,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// split it into separate messages so convertToModelMessages produces the
// tool_use / tool_result pairing that the Claude API requires.
// See: https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use#parallel-tool-use
- const messagesToConvert = (() => {
+ let messagesToConvert = (() => {
if (effectiveProviderName !== 'anthropic') {
return options.messages
}
@@ -526,6 +575,16 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const selectedModel = useModelProvider.getState().selectedModel
+ const { messages: strippedMessages, files: attachedFiles } =
+ this.extractFileMetadataForSystem(messagesToConvert)
+ messagesToConvert = strippedMessages
+ const filesAddendum = this.buildFilesSystemAddendum(attachedFiles)
+ const effectiveSystem = filesAddendum
+ ? this.systemMessage
+ ? `${this.systemMessage}\n\n${filesAddendum}`
+ : filesAddendum
+ : this.systemMessage
+
const maxOutputTokens: number | undefined = (() => {
const raw = inferenceParams.max_output_tokens ?? inferenceParams.max_tokens
if (raw === undefined || raw === null) return undefined
@@ -550,8 +609,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
autoCompact: !!autoCompact,
}
- const systemPromptTokens = this.systemMessage
- ? estimateTokens(this.systemMessage) + 4
+ const systemPromptTokens = effectiveSystem
+ ? estimateTokens(effectiveSystem) + 4
: 0
if (autoCompact && this.model) {
@@ -584,7 +643,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
const baseMessages = convertToModelMessages(
- this.mapUserInlineAttachments(effectiveMessages)
+ this.encodeAudioAttachments(this.mapUserInlineAttachments(effectiveMessages))
)
// If continuing a truncated response, append the partial assistant content as a
@@ -600,8 +659,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools
const shouldEnableTools = hasTools && modelSupportsTools
- // Track stream timing and token count for token speed calculation
let streamStartTime: number | undefined
+ useAppState.getState().updatePromptProgress(undefined)
const result = streamText({
model: this.model,
@@ -609,7 +668,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
abortSignal: options.abortSignal,
tools: shouldEnableTools ? this.tools : undefined,
toolChoice: shouldEnableTools ? 'auto' : undefined,
- system: this.systemMessage,
+ system: effectiveSystem,
...(maxOutputTokens !== undefined ? { maxTokens: maxOutputTokens } : {}),
})
@@ -671,6 +730,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return undefined
},
onError: (error) => {
+ useAppState.getState().updatePromptProgress(undefined)
+ useAppState.getState().updateLoadingModel(false)
const errorMessage = error == null
? 'Unknown error'
: typeof error === 'string'
@@ -682,7 +743,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return errorMessage
},
onFinish: ({ responseMessage }) => {
- // Call the token usage callback with usage data when stream completes
+ useAppState.getState().updatePromptProgress(undefined)
+ useAppState.getState().updateLoadingModel(false)
if (responseMessage) {
const metadata = responseMessage.metadata as
| Record<string, unknown>
@@ -716,11 +778,100 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return null
}
+ // Replace audio `file` parts on user messages with sentinel-bearing `text`
+ // parts. The `@ai-sdk/openai-compatible` provider rejects non-image file
+ // parts in its converter; the matching fetch wrapper in model-factory.ts
+ // decodes these sentinels back into OpenAI `input_audio` content parts on
+ // the outgoing wire, which llama-server's chat-completions endpoint accepts.
+ encodeAudioAttachments(messages: UIMessage[]): UIMessage[] {
+ return messages.map((message) => {
+ if (message.role !== 'user' || !Array.isArray(message.parts)) return message
+ let touched = false
+ const nextParts = message.parts.map((part) => {
+ if (
+ part?.type === 'file' &&
+ typeof (part as { mediaType?: string }).mediaType === 'string' &&
+ (part as { mediaType: string }).mediaType.startsWith('audio/') &&
+ typeof (part as { url?: string }).url === 'string'
+ ) {
+ const parsed = parseAudioDataUrl((part as { url: string }).url)
+ if (!parsed) return part
+ touched = true
+ return { type: 'text' as const, text: encodeAudioSentinel(parsed.format, parsed.data) }
+ }
+ return part
+ })
+ if (!touched) return message
+ return { ...message, parts: nextParts } as UIMessage
+ })
+ }
+
/**
* Map user messages to include inline attachments in the message parts
* @param messages
* @returns
*/
+ /**
+ * Strip persisted [ATTACHED_FILES] blocks from user message text and return
+ * the aggregated, deduped file metadata so it can be folded into the system
+ * prompt instead of the user turn. The stored ThreadMessages are untouched
+ * (UI still relies on the inline block for display); this only affects what
+ * is sent to the model.
+ */
+ extractFileMetadataForSystem(
+ messages: UIMessage[]
+ ): { messages: UIMessage[]; files: FileMetadata[] } {
+ const byId = new Map<string, FileMetadata>()
+ const next = messages.map((message) => {
+ if (message.role !== 'user' || !Array.isArray(message.parts)) return message
+ let touched = false
+ const parts = message.parts.map((part) => {
+ if (
+ part?.type === 'text' &&
+ typeof (part as { text?: string }).text === 'string' &&
+ (part as { text: string }).text.includes('[ATTACHED_FILES]')
+ ) {
+ const { files, cleanPrompt } = extractFilesFromPrompt(
+ (part as { text: string }).text
+ )
+ if (files.length === 0) return part
+ for (const f of files) {
+ if (!byId.has(f.id)) byId.set(f.id, f)
+ }
+ touched = true
+ return { ...part, text: cleanPrompt }
+ }
+ return part
+ })
+ if (!touched) return message
+ return { ...message, parts } as UIMessage
+ })
+ return { messages: next, files: Array.from(byId.values()) }
+ }
+
+ /**
+ * Format collected file metadata as a system-prompt addendum. The block is
+ * stable / parseable so models can reference file_ids when invoking RAG tools.
+ */
+ buildFilesSystemAddendum(files: FileMetadata[]): string {
+ if (files.length === 0) return ''
+ const lines = files.map((f) => {
+ const parts = [`file_id: ${f.id}`, `name: ${f.name}`]
+ if (f.type) parts.push(`type: ${f.type}`)
+ if (typeof f.size === 'number') parts.push(`size: ${f.size}`)
+ if (typeof f.chunkCount === 'number') parts.push(`chunks: ${f.chunkCount}`)
+ if (f.injectionMode) parts.push(`mode: ${f.injectionMode}`)
+ return `- ${parts.join(', ')}`
+ })
+ return [
+ 'The user has attached the following files to this conversation.',
+ 'Use the available retrieval tools with these file_ids when their contents are relevant.',
+ '[ATTACHED_FILES]',
+ ...lines,
+ '[/ATTACHED_FILES]',
+ ].join('\n')
+ }
+
mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {
return messages.map((message) => {
if (message.role === 'user') {
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index 1376734ca..c30205bfe 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -43,7 +43,6 @@ export function convertUIMessageToThreadMessage(
})
}
} else if (part.type === 'file' && part.mediaType) {
- // Handle file parts (images)
const mediaType = part.mediaType as string
if (mediaType?.startsWith('image/')) {
content.push({
@@ -53,6 +52,17 @@ export function convertUIMessageToThreadMessage(
detail: 'auto',
},
})
+ } else if (mediaType === 'audio/wav' || mediaType === 'audio/mpeg') {
+ const format = mediaType === 'audio/wav' ? 'wav' : 'mp3'
+ const url = part.url as string | undefined
+ const data =
+ typeof url === 'string' && url.startsWith('data:')
+ ? url.slice(url.indexOf(',') + 1)
+ : (url ?? '')
+ content.push({
+ type: ContentType.InputAudio,
+ input_audio: { data, format },
+ })
}
}
}
@@ -239,6 +249,14 @@ export function convertThreadMessageToUIMessage(
mediaType: 'image/jpeg',
url: content.image_url.url,
})
+ } else if (content.type === 'input_audio' && content.input_audio?.data) {
+ const fmt = content.input_audio.format
+ const mediaType = fmt === 'mp3' ? 'audio/mpeg' : 'audio/wav'
+ parts.push({
+ type: 'file',
+ mediaType,
+ url: `data:${mediaType};base64,${content.input_audio.data}`,
+ })
} else if (content.type === 'tool_call') {
// Handle tool call content items - direct conversion from flat structure
// Use AI SDK v5 UIToolInvocation format: toolCallId, state: 'output-available'/'input-available'
@@ -375,7 +393,6 @@ export function extractContentPartsFromUIMessage(message: UIMessage): ThreadCont
})
}
} else if (part.type === 'file' && part.mediaType) {
- // Handle file parts (images)
const mediaType = part.mediaType as string
if (mediaType?.startsWith('image/')) {
content.push({
@@ -385,6 +402,17 @@ export function extractContentPartsFromUIMessage(message: UIMessage): ThreadCont
detail: 'auto',
},
})
+ } else if (mediaType === 'audio/wav' || mediaType === 'audio/mpeg') {
+ const format = mediaType === 'audio/wav' ? 'wav' : 'mp3'
+ const url = part.url as string | undefined
+ const data =
+ typeof url === 'string' && url.startsWith('data:')
+ ? url.slice(url.indexOf(',') + 1)
+ : (url ?? '')
+ content.push({
+ type: 'input_audio' as ContentType.InputAudio,
+ input_audio: { data, format },
+ })
}
} else if (part.type.startsWith('tool-')) {
// Handle tool call parts - flatten structure to match parts format
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 00e8db251..4d7190c71 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -58,9 +58,11 @@ import { createXai } from '@ai-sdk/xai'
import { invoke } from '@tauri-apps/api/core'
import { SessionInfo } from '@janhq/core'
import { fetch as httpFetch } from '@tauri-apps/plugin-http'
+import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'
import { isPlatformTauri } from '@/lib/platform/utils'
import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'
import { LLAMACPP_ONLY_PARAM_KEYS } from '@/lib/predefinedParams'
+import { useAppState } from '@/hooks/useAppState'
/**
* Llama.cpp timings structure from the response
@@ -72,8 +74,16 @@ interface LlamaCppTimings {
prompt_per_second?: number
}
+interface LlamaCppPromptProgress {
+ total?: number
+ cache?: number
+ processed?: number
+ time_ms?: number
+}
+
interface LlamaCppChunk {
timings?: LlamaCppTimings
+ prompt_progress?: LlamaCppPromptProgress
}
/**
@@ -102,9 +112,25 @@ const providerMetadataExtractor: MetadataExtractor = {
return {
processChunk: (parsedChunk: unknown) => {
const chunk = parsedChunk as LlamaCppChunk
+ if (useAppState.getState().loadingModel) {
+ useAppState.getState().updateLoadingModel(false)
+ }
if (chunk?.timings) {
lastTimings = chunk.timings
}
+ const pp = chunk?.prompt_progress
+ if (
+ pp &&
+ typeof pp.total === 'number' &&
+ typeof pp.processed === 'number'
+ ) {
+ useAppState.getState().updatePromptProgress({
+ total: pp.total,
+ processed: pp.processed,
+ cache: pp.cache ?? 0,
+ time_ms: pp.time_ms ?? 0,
+ })
+ }
},
buildMetadata: () => {
if (lastTimings) {
@@ -171,13 +197,58 @@ function createCustomFetch(
normalised[targetKey] = value
}
- init = { ...init, body: JSON.stringify({ ...body, ...normalised }) }
+ const merged = { ...body, ...normalised }
+ if (keepLlamacppOnly && merged.stream === true) {
+ merged.return_progress = true
+ }
+ decodeAudioSentinelsInBody(merged)
+ init = { ...init, body: JSON.stringify(merged) }
}
return baseFetch(input, init)
}
}
+// Rewrites any sentinel-bearing text content (planted by
+// CustomChatTransport.encodeAudioAttachments) back into OpenAI `input_audio`
+// content parts. Mutates `body.messages` in place.
+export function decodeAudioSentinelsInBody(body: Record<string, unknown>): void {
+ const messages = body.messages
+ if (!Array.isArray(messages)) return
+ for (const msg of messages) {
+ if (!msg || typeof msg !== 'object') continue
+ const m = msg as { role?: string; content?: unknown }
+ if (m.role !== 'user') continue
+ if (typeof m.content === 'string') {
+ if (!hasAudioSentinel(m.content)) continue
+ const split = splitAudioSentinels(m.content)
+ if (split) m.content = split
+ continue
+ }
+ if (!Array.isArray(m.content)) continue
+ const next: unknown[] = []
+ let touched = false
+ for (const part of m.content) {
+ if (
+ part &&
+ typeof part === 'object' &&
+ (part as { type?: string }).type === 'text' &&
+ typeof (part as { text?: string }).text === 'string' &&
+ hasAudioSentinel((part as { text: string }).text)
+ ) {
+ const split = splitAudioSentinels((part as { text: string }).text)
+ if (split) {
+ next.push(...split)
+ touched = true
+ continue
+ }
+ }
+ next.push(part)
+ }
+ if (touched) m.content = next
+ }
+}
+
type ApiKeyHeaderMode = 'authorization-bearer' | 'x-api-key'
/** Retries with the next key when the upstream returns 401, 403, or 429. */
diff --git a/web-app/src/locales/en/providers.json b/web-app/src/locales/en/providers.json
index 9bad7e06e..4c58bc973 100644
--- a/web-app/src/locales/en/providers.json
+++ b/web-app/src/locales/en/providers.json
@@ -4,11 +4,17 @@
"noNewModels": "No new models found. All available models are already added.",
"refreshModelsFailed": "Failed to fetch models from {{provider}}. Please check your API key and base URL.",
"models": "Models",
+ "chatModels": "Chat Models",
+ "embeddingModels": "Embedding Models",
+ "embeddingModelsDesc": "Used for RAG and vector search. The selected model becomes the default when generating embeddings.",
+ "embeddingModelDefault": "Default",
+ "embeddingModelSetDefault": "Set as default embedding model",
+ "embeddingModelIsDefault": "Default embedding model",
"refreshing": "Refreshing...",
"refresh": "Refresh",
"import": "Import",
"imported": "Imported",
- "importedTooltip": "Imported from a local file. Deleting will remove the file from disk.",
+ "importedTooltip": "Imported from a local file. Removing it from Jan will not delete the file on disk.",
"importModelSuccess": "Model {{provider}} has been imported successfully.",
"importModelError": "Failed to import model:",
"stop": "Stop",
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 08e2fe4f0..aa6337608 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -10,7 +10,7 @@ import Capabilities from '@/containers/Capabilities'
import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'
import { RenderMarkdown } from '@/containers/RenderMarkdown'
import { DialogEditModel } from '@/containers/dialogs/EditModel'
-import { ImportVisionModelDialog } from '@/containers/dialogs/ImportVisionModelDialog'
+import { ImportLlamacppModelDialog } from '@/containers/dialogs/ImportLlamacppModelDialog'
import { ImportMlxModelDialog } from '@/containers/dialogs/ImportMlxModelDialog'
import { ModelSetting } from '@/containers/ModelSetting'
import { DialogDeleteModel } from '@/containers/dialogs/DeleteModel'
@@ -23,11 +23,14 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import {
+ IconCircleCheck,
+ IconCircle,
IconFolderPlus,
IconLoader,
IconRefresh,
IconUpload,
} from '@tabler/icons-react'
+import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'
import { toast } from 'sonner'
import { useCallback, useEffect, useState } from 'react'
import { predefinedProviders } from '@/constants/providers'
@@ -77,6 +80,54 @@ function ProviderDetail() {
const { providerName } = useParams({ from: Route.id })
const { getProviderByName, setProviders, updateProvider } = useModelProvider()
const provider = getProviderByName(providerName)
+ const isLlamacpp = provider?.provider === 'llamacpp'
+ const allModels = provider?.models ?? []
+ const embeddingModels = isLlamacpp
+ ? allModels.filter((m) => (m as any).embedding === true)
+ : []
+ const chatModels = isLlamacpp
+ ? allModels.filter((m) => (m as any).embedding !== true)
+ : allModels
+ const defaultEmbeddingModelId = useDefaultEmbeddingModel((s) =>
+ isLlamacpp ? s.getDefault('llamacpp') : undefined
+ )
+ const setDefaultEmbeddingModel = useDefaultEmbeddingModel((s) => s.setDefault)
+ const clearDefaultEmbeddingModel = useDefaultEmbeddingModel(
+ (s) => s.clearDefault
+ )
+
+ useEffect(() => {
+ if (!isLlamacpp) return
+ const hasMini = allModels.some(
+ (m) => m.id === 'sentence-transformer-mini'
+ )
+ if (
+ !defaultEmbeddingModelId &&
+ embeddingModels.length === 1 &&
+ !hasMini
+ ) {
+ setDefaultEmbeddingModel('llamacpp', embeddingModels[0].id)
+ return
+ }
+ if (
+ defaultEmbeddingModelId &&
+ embeddingModels.length > 0 &&
+ !embeddingModels.some((m) => m.id === defaultEmbeddingModelId)
+ ) {
+ clearDefaultEmbeddingModel('llamacpp')
+ return
+ }
+ if (defaultEmbeddingModelId && embeddingModels.length === 0) {
+ clearDefaultEmbeddingModel('llamacpp')
+ }
+ }, [
+ isLlamacpp,
+ defaultEmbeddingModelId,
+ embeddingModels,
+ allModels,
+ setDefaultEmbeddingModel,
+ clearDefaultEmbeddingModel,
+ ])
// Check if llamacpp/mlx provider needs backend configuration
const needsBackendConfig =
@@ -598,6 +649,13 @@ function ProviderDetail() {
return null
}
+ if (
+ provider?.provider === 'llamacpp' &&
+ setting.key === 'fit_ctx'
+ ) {
+ return null
+ }
+
// Use the DynamicController component
const actionComponent = (
<div className="mt-2">
@@ -1005,7 +1063,7 @@ function ProviderDetail() {
<DialogDeleteAllModels provider={provider} />
)}
{provider && provider.provider === 'llamacpp' && (
- <ImportVisionModelDialog
+ <ImportLlamacppModelDialog
provider={provider}
onSuccess={handleModelImportSuccess}
trigger={
@@ -1044,7 +1102,20 @@ function ProviderDetail() {
}
>
{provider?.models.length ? (
- provider?.models.map((model, modelIndex) => {
+ <>
+ {isLlamacpp && embeddingModels.length > 0 && chatModels.length > 0 && (
+ <div
+ role="separator"
+ aria-label={t('providers:chatModels')}
+ className="mt-1 mb-3 flex items-center gap-3"
+ >
+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
+ {t('providers:chatModels')}
+ </span>
+ <span className="h-0.5 flex-1 rounded-full bg-main-view-fg/15" />
+ </div>
+ )}
+ {(isLlamacpp ? chatModels : allModels).map((model, modelIndex) => {
const capabilities = model.capabilities || []
return (
<CardItem
@@ -1133,7 +1204,8 @@ function ProviderDetail() {
}
/>
)
- })
+ })}
+ </>
) : (
<div className="-mt-2">
<div className="flex items-center gap-2">
@@ -1170,6 +1242,105 @@ function ProviderDetail() {
}
/>
)}
+
+ {isLlamacpp && provider && embeddingModels.length > 0 && (
+ <>
+ <div
+ role="separator"
+ aria-label={t('providers:embeddingModels')}
+ className="mt-5 mb-3 flex items-center gap-3"
+ >
+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
+ {t('providers:embeddingModels')}
+ </span>
+ <span className="h-0.5 flex-1 rounded-full bg-main-view-fg/15" />
+ </div>
+ {embeddingModels.map((model, modelIndex) => {
+ const isDefault = defaultEmbeddingModelId === model.id
+ return (
+ <CardItem
+ key={`embedding-${modelIndex}`}
+ title={
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() =>
+ setDefaultEmbeddingModel(
+ 'llamacpp',
+ model.id
+ )
+ }
+ aria-label={
+ isDefault
+ ? t('providers:embeddingModelIsDefault')
+ : t('providers:embeddingModelSetDefault')
+ }
+ title={
+ isDefault
+ ? t('providers:embeddingModelIsDefault')
+ : t('providers:embeddingModelSetDefault')
+ }
+ className="size-6 flex items-center justify-center rounded transition-all hover:bg-main-view-fg/8"
+ >
+ {isDefault ? (
+ <IconCircleCheck
+ size={18}
+ className="text-muted-foreground"
+ />
+ ) : (
+ <IconCircle
+ size={18}
+ className="text-muted-foreground"
+ />
+ )}
+ </button>
+ <h1
+ className="font-medium line-clamp-1"
+ title={model.id}
+ >
+ {getModelDisplayName(model)}
+ </h1>
+ <Capabilities
+ capabilities={model.capabilities || []}
+ />
+ {isDefault && (
+ <span className="shrink-0 rounded-sm bg-main-view-fg/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
+ {t('providers:embeddingModelDefault')}
+ </span>
+ )}
+ {model.imported && (
+ <span
+ className="shrink-0 rounded-sm bg-main-view-fg/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground"
+ title={t('providers:importedTooltip')}
+ >
+ {t('providers:imported')}
+ </span>
+ )}
+ </div>
+ }
+ actions={
+ <div className="flex items-center gap-0.5">
+ <DialogEditModel
+ provider={provider}
+ modelId={model.id}
+ />
+ {model.settings && (
+ <ModelSetting
+ provider={provider}
+ model={model}
+ />
+ )}
+ <DialogDeleteModel
+ provider={provider}
+ modelId={model.id}
+ />
+ </div>
+ }
+ />
+ )
+ })}
+ </>
+ )}
</Card>
</div>
</div>
diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
index 417d0ba6f..e86ddec67 100644
--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx
@@ -213,8 +213,8 @@ vi.mock('@/containers/dialogs/EditModel', () => ({
DialogEditModel: ({ modelId }: any) => <div data-testid={`edit-${modelId}`} />,
}))
-vi.mock('@/containers/dialogs/ImportVisionModelDialog', () => ({
- ImportVisionModelDialog: ({ trigger }: any) => (
+vi.mock('@/containers/dialogs/ImportLlamacppModelDialog', () => ({
+ ImportLlamacppModelDialog: ({ trigger }: any) => (
<div data-testid="import-vision">{trigger}</div>
),
}))
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index ba5f2e4b4..abdbc2927 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -483,6 +483,11 @@ function ThreadDetail() {
reset: resetReasoningScroll,
} = useAutoScroll()
+ const lastIsAssistant = useMemo(() => {
+ const last = chatMessages[chatMessages.length - 1]
+ return !!last && last.role === 'assistant'
+ }, [chatMessages])
+
useEffect(() => {
if (status === 'streaming') {
resetReasoningScroll()
@@ -1114,7 +1119,9 @@ function ThreadDetail() {
{(pendingContinueMessage || isAutoIncreasingContext) && (
<Shimmer duration={1}>Growing the Mind...</Shimmer>
)}
- {status === CHAT_STATUS.SUBMITTED && <PromptProgress />}
+ {status === CHAT_STATUS.SUBMITTED && !lastIsAssistant && (
+ <PromptProgress />
+ )}
</div>
)}
{(error || contextLimitError) && !isAutoIncreasingContext && (
diff --git a/web-app/src/styles/markdown.css b/web-app/src/styles/markdown.css
index c63072081..97c5c0c63 100644
--- a/web-app/src/styles/markdown.css
+++ b/web-app/src/styles/markdown.css
@@ -51,6 +51,9 @@
p {
line-height: 1.6;
margin-bottom: 1em;
+ &:last-child {
+ margin-bottom: 0;
+ }
}
strong {
diff --git a/web-app/src/types/__tests__/attachment.test.ts b/web-app/src/types/__tests__/attachment.test.ts
index bf5794f18..cd88fd8d9 100644
--- a/web-app/src/types/__tests__/attachment.test.ts
+++ b/web-app/src/types/__tests__/attachment.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'
import {
createImageAttachment,
createDocumentAttachment,
+ createAudioAttachment,
} from '../attachment'
describe('createImageAttachment', () => {
@@ -37,7 +38,7 @@ describe('createDocumentAttachment', () => {
})
})
- it('passes through optional fileType, size, parseMode', () => {
+ it('passes through optional fileType, size, parseMode (doc)', () => {
const result = createDocumentAttachment({
name: 'a.docx',
path: '/a.docx',
@@ -51,3 +52,41 @@ describe('createDocumentAttachment', () => {
expect(result.type).toBe('document')
})
})
+
+describe('createAudioAttachment', () => {
+ it('returns an audio-typed attachment with wav format', () => {
+ const result = createAudioAttachment({
+ name: 'clip.wav',
+ base64: 'QkJC',
+ dataUrl: 'data:audio/wav;base64,QkJC',
+ mimeType: 'audio/wav',
+ audioFormat: 'wav',
+ size: 2048,
+ durationSec: 4.2,
+ })
+ expect(result).toEqual({
+ name: 'clip.wav',
+ base64: 'QkJC',
+ dataUrl: 'data:audio/wav;base64,QkJC',
+ mimeType: 'audio/wav',
+ audioFormat: 'wav',
+ size: 2048,
+ durationSec: 4.2,
+ type: 'audio',
+ })
+ })
+
+ it('supports mp3 format and omits durationSec when unknown', () => {
+ const result = createAudioAttachment({
+ name: 'song.mp3',
+ base64: 'YWFh',
+ dataUrl: 'data:audio/mpeg;base64,YWFh',
+ mimeType: 'audio/mpeg',
+ audioFormat: 'mp3',
+ size: 9001,
+ })
+ expect(result.type).toBe('audio')
+ expect(result.audioFormat).toBe('mp3')
+ expect(result.durationSec).toBeUndefined()
+ })
+})
diff --git a/web-app/src/types/attachment.ts b/web-app/src/types/attachment.ts
index 2ff38f17a..a7d02e665 100644
--- a/web-app/src/types/attachment.ts
+++ b/web-app/src/types/attachment.ts
@@ -1,9 +1,14 @@
/**
- * Unified attachment type for both images and documents
+ * Unified attachment type for images, documents, and audio
*/
export type Attachment = {
name: string
- type: 'image' | 'document'
+ type: 'image' | 'document' | 'audio'
+
+ /** For audio attachments: 'wav' or 'mp3' per llama.cpp mtmd support. */
+ audioFormat?: 'wav' | 'mp3'
+ /** Audio duration in seconds (decoded client-side for the chip preview). */
+ durationSec?: number
// Common fields
size?: number
@@ -45,6 +50,24 @@ export function createImageAttachment(data: {
}
}
+/**
+ * Helper to create audio attachment
+ */
+export function createAudioAttachment(data: {
+ name: string
+ base64: string
+ dataUrl: string
+ mimeType: string
+ audioFormat: 'wav' | 'mp3'
+ size: number
+ durationSec?: number
+}): Attachment {
+ return {
+ ...data,
+ type: 'audio',
+ }
+}
+
/**
* Helper to create document attachment
*/