Skip to content

armgit / jan

Public Imported from GitHub
0

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

fix(llamacpp): atomic backend updates with rollback, and router crash recovery (#8547)

Akarshan Biswas59ca31f8b651
diff --git a/core/src/types/api/index.ts b/core/src/types/api/index.ts
index aa2075ca8..93a5f4631 100644
--- a/core/src/types/api/index.ts
+++ b/core/src/types/api/index.ts
@@ -67,6 +67,8 @@ export enum AppEvent {
onMainViewStateChange = 'onMainViewStateChange',
onBackendVerificationFailed = 'onBackendVerificationFailed',
+ onBackendRollback = 'onBackendRollback',
+ onBackendUpdateQueued = 'onBackendUpdateQueued',
}
export enum DownloadEvent {
diff --git a/core/src/types/setting/settingComponent.ts b/core/src/types/setting/settingComponent.ts
index 57b222d87..59f335010 100644
--- a/core/src/types/setting/settingComponent.ts
+++ b/core/src/types/setting/settingComponent.ts
@@ -37,7 +37,12 @@ export type InputType =
const InputActions = ['unobscure', 'copy'] as const
export type InputActionsTuple = typeof InputActions
export type InputAction = InputActionsTuple[number]
-export type DropdownOption = { name: string; value: string }
+export type DropdownOption = {
+ name: string
+ value: string
+ /** Backend versions only: already downloaded, so selecting it is a rollback. */
+ installed?: boolean
+}
export type InputComponentProps = {
placeholder: string
diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.ts
index e756d7ee7..939411b56 100644
--- a/extensions/llamacpp-extension/src/backend.ts
+++ b/extensions/llamacpp-extension/src/backend.ts
@@ -10,6 +10,8 @@ import {
listSupportedBackendsFromRust,
BackendVersion,
getSupportedFeaturesFromRust,
+ fetchBackendChecksums,
+ verifyFileSha512,
} from '@janhq/tauri-plugin-llamacpp-api'
/*
@@ -132,6 +134,55 @@ export async function verifyBackendInstallation(
)
}
+/**
+ * Check downloaded archives against the release's `checksum.yml` before they
+ * are unpacked.
+ *
+ * Fail-soft on a missing manifest or a missing entry, and deliberately so:
+ * releases published before the manifest existed -- and those whose entries
+ * predate the `-bin-` naming fix in janhq/llama.cpp db8b2fcd -- carry no usable
+ * digest, and refusing to install them would strand every older version, which
+ * is exactly what rollback depends on. A digest that IS present and does not
+ * match is a hard failure: the file is removed so a retry cannot reuse it.
+ */
+async function verifyDownloadedArchives(
+ savePaths: string[],
+ version: string,
+ source: 'github' | 'cdn',
+ proxyConfig: object | null
+): Promise<void> {
+ let checksums: Record<string, string> = {}
+ try {
+ checksums = await fetchBackendChecksums(version, source, proxyConfig)
+ } catch (e) {
+ logger.warn(`Could not load checksum.yml for ${version}:`, e)
+ return
+ }
+ if (!Object.keys(checksums).length) {
+ logger.warn(
+ `No usable checksums published for ${version}; skipping verification`
+ )
+ return
+ }
+
+ for (const savePath of savePaths) {
+ const name = savePath.split(/[\\/]/).pop() ?? ''
+ const expected = checksums[name]
+ if (!expected) {
+ logger.warn(`No checksum entry for ${name}; skipping verification`)
+ continue
+ }
+ if (await verifyFileSha512(savePath, expected)) {
+ logger.info(`Checksum verified for ${name}`)
+ continue
+ }
+ await fs.rm(savePath).catch(() => undefined)
+ throw new Error(
+ `Checksum mismatch for ${name}; the download was corrupt or tampered with`
+ )
+ }
+}
+
export async function downloadBackend(
backend: string,
version: string,
@@ -188,6 +239,13 @@ export async function downloadBackend(
return
}
+ await verifyDownloadedArchives(
+ itemsWithProxy.map((i) => i.save_path),
+ version,
+ source,
+ proxyConfig
+ )
+
for (const { save_path } of itemsWithProxy) {
// Official Windows HIP assets ship as .zip; everything else is .tar.gz.
if (save_path.endsWith('.tar.gz') || save_path.endsWith('.zip')) {
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index f5101baca..7fe6dee24 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -68,6 +68,8 @@ import {
isModelSupported,
unloadLlamaModel,
reloadRouterModels,
+ routerHealth,
+ adoptRouter,
LlamacppConfig,
DownloadItem,
ModelConfig,
@@ -95,6 +97,30 @@ const TEMPLATE_KWARGS_CHECK_VERSION = 1
// full process restart.
const RELOAD_MIN_BUILD = 9023
+// Superseded installs kept on disk so a rollback (or an offline downgrade)
+// does not require re-downloading a release that may since have been yanked.
+const BACKEND_VERSIONS_RETAINED = 2
+
+// Bounded so a long-lived install cannot grow the log without limit.
+const UPDATE_HISTORY_LIMIT = 50
+const UPDATE_HISTORY_FILENAME = 'update_history.json'
+
+type BackendUpdateRecord = {
+ timestamp: string
+ from: string
+ to: string
+ outcome: 'updated' | 'rolled-back' | 'rollback-failed' | 'failed'
+ durationMs: number
+ error?: string
+}
+
+/** Snapshot of an active backend choice, sufficient to restore it on rollback. */
+type BackendSelection = {
+ version: string
+ backend: string
+ storedType?: string
+}
+
// Provider settings that end up in `router.preset.ini` (`[*]` global section
// in preset.ts). Mutating any of these requires a router restart so the new
// preset is read; cosmetic / process-only keys (auto_update_engine, models_max,
@@ -370,11 +396,21 @@ export default class llamacpp_extension extends AIEngine {
private pendingDownloads: Map<string, Promise<void>> = new Map()
private isConfiguringBackends: boolean = false
private isUpdatingBackend: boolean = false
+ private currentUpdate: Promise<{
+ wasUpdated: boolean
+ newBackend: string
+ }> | null = null
+ private pendingUpdate: Promise<{
+ wasUpdated: boolean
+ newBackend: string
+ }> | null = null
+ private pendingTarget: string | null = null
private loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises
private unlistenValidationStarted?: () => void
private routerPort?: number
private routerApiKey?: string
+ private routerStartLock: Promise<void> | null = null
private userModelsMax: number = 1
private routerEmbeddingBonus: number = 0
private loadedChatOrder: string[] = []
@@ -457,13 +493,12 @@ export default class llamacpp_extension extends AIEngine {
// the UI unblocks; performLoad awaits it via ensureRouterReady().
//
// When a usable backend is already installed, start the router first so
- // inference is available without waiting on the network-bound update check,
- // then run configureBackends and restart the router only if the update
- // swapped the backend. On a fresh install (no backend yet) configureBackends
- // must run first to download one before the router can start.
+ // inference is available without waiting on the network-bound update check.
+ // A restart on the new binary is owned by updateBackend, which needs it to
+ // health-check the switch. On a fresh install (no backend yet)
+ // configureBackends must run first to download one before the router can start.
this.backgroundInit = (async () => {
if (await this.hasInstalledBackend()) {
- const before = this.config?.version_backend
try {
await this.startRouter()
} catch (e) {
@@ -474,19 +509,6 @@ export default class llamacpp_extension extends AIEngine {
} catch (e) {
logger.error('configureBackends failed during onLoad:', e)
}
- const after = this.config?.version_backend
- if (
- after &&
- after !== 'none' &&
- after.includes('/') &&
- after !== before
- ) {
- try {
- await this.startRouter()
- } catch (e) {
- logger.error('Router restart after backend update failed:', e)
- }
- }
} else {
try {
await this.configureBackends()
@@ -675,7 +697,25 @@ export default class llamacpp_extension extends AIEngine {
}
}
+ /**
+ * Serialized: two concurrent calls would each run the stop-then-spawn
+ * sequence below, and the second would kill the router the first had just
+ * brought up. A late caller gets the in-flight start rather than a restart.
+ */
private async startRouter(): Promise<void> {
+ const inflight = this.routerStartLock
+ if (inflight) {
+ logger.info('startRouter already in progress; awaiting the in-flight run')
+ await inflight.catch(() => undefined)
+ return
+ }
+ this.routerStartLock = this.runStartRouter().finally(() => {
+ this.routerStartLock = null
+ })
+ return this.routerStartLock
+ }
+
+ private async runStartRouter(): Promise<void> {
const versionBackend = this.config?.version_backend
if (
!versionBackend ||
@@ -711,13 +751,6 @@ export default class llamacpp_extension extends AIEngine {
)
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
@@ -738,8 +771,35 @@ export default class llamacpp_extension extends AIEngine {
modelsMax += embeddingSlotBonus
this.routerEmbeddingBonus = embeddingSlotBonus
- // Defensive: if a router is already running (hot reload / dev), stop it
- // first so start_router doesn't reject.
+ // Adoption runs before any stop, and is the only thing allowed to end an
+ // existing router here. It reuses a process whose backend, preset and
+ // models_max still match, and kills one whose config has moved on. A router
+ // can outlive the UI (crash, SIGKILL, power loss) since kill_on_drop never
+ // runs, so this both rescues orphans holding VRAM and makes a redundant
+ // call a no-op instead of a needless cold restart.
+ let adopted: Awaited<ReturnType<typeof adoptRouter>> = null
+ try {
+ adopted = await adoptRouter(
+ backendExe,
+ presetPath,
+ modelsMax,
+ this.apiSecret
+ )
+ } catch (e) {
+ logger.warn('Router adoption failed; starting a fresh router:', e)
+ }
+ if (adopted) {
+ this.routerPort = adopted.port
+ this.routerApiKey = adopted.api_key
+ logger.info(
+ `Reusing router on port ${adopted.port} (pid ${adopted.pid}); skipping spawn`
+ )
+ return
+ }
+
+ // Adoption found nothing to adopt, or declined a process it could not
+ // verify against the lock. A live router with no matching lock would make
+ // start_router reject, so clear it.
try {
const existing = await invoke<{ port: number; api_key: string } | null>(
'plugin:llamacpp|get_router_info'
@@ -751,6 +811,14 @@ export default class llamacpp_extension extends AIEngine {
/* ignore probe failures */
}
+ 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)
+
// --no-webui was renamed to --no-ui in upstream b9222. Keep the legacy
// flag for older backends; the deprecated form still works on newer ones
// but emits a warning, so prefer the new spelling when available.
@@ -758,11 +826,16 @@ export default class llamacpp_extension extends AIEngine {
const noUiFlag =
build !== null && build >= NO_UI_RENAME_BUILD ? '--no-ui' : '--no-webui'
+ // Beside app.log in the managed logs folder, where a bug report will look.
+ // The filename is derived from the port inside the plugin.
+ const logDir = await joinPath([janDataFolderPath, 'logs'])
+
const info = await invoke<{ port: number; api_key: string; pid: number }>(
'plugin:llamacpp|start_router',
{
backendExe,
presetPath,
+ logDir,
port,
apiKey,
modelsMax,
@@ -1164,12 +1237,22 @@ export default class llamacpp_extension extends AIEngine {
.value ?? ''
)
+ // Flag versions already on disk so the dropdown distinguishes a rollback
+ // (instant, works offline) from a download.
+ const installedVersions = new Set(
+ (await getLocalInstalledBackends().catch((e) => {
+ logger.warn('Could not list local backends for the version list:', e)
+ return [] as { version: string; backend: string }[]
+ })).map((b) => b.version)
+ )
+
const allVersions = Array.from(
new Set(version_backends.map((b) => b.version))
)
versionSetting.controllerProps.options = allVersions.map((v) => ({
value: v,
name: v,
+ installed: installedVersions.has(v),
}))
const allBackends = Array.from(
@@ -1459,17 +1542,49 @@ export default class llamacpp_extension extends AIEngine {
return result.backend_string
}
+ /**
+ * Serializes backend updates. A request arriving mid-update is queued rather
+ * than dropped, and only the newest queued target survives -- if a user
+ * clicks through three versions while a download runs, the first two are
+ * obsolete by the time they could run. All callers waiting on the queued slot
+ * receive the same result.
+ */
async updateBackend(
targetBackendString: string
): Promise<{ wasUpdated: boolean; newBackend: string }> {
- if (this.isUpdatingBackend) {
- logger.warn('Backend update already in progress, skipping new update request')
- // Treat concurrent update requests as a benign no-op and report that no new update
- // was performed, while still returning the current backend value.
- return { wasUpdated: false, newBackend: this.config.version_backend }
+ if (this.currentUpdate) {
+ this.pendingTarget = targetBackendString
+ logger.info(
+ `Backend update in progress; queued ${targetBackendString} (supersedes any earlier queued target)`
+ )
+ events.emit(AppEvent.onBackendUpdateQueued, {
+ target: targetBackendString,
+ })
+
+ this.pendingUpdate ??= this.currentUpdate
+ .catch(() => undefined)
+ .then(() => {
+ const next = this.pendingTarget as string
+ this.pendingTarget = null
+ this.pendingUpdate = null
+ return this.updateBackend(next)
+ })
+ return this.pendingUpdate
}
+ // `runUpdate` clears currentUpdate inside its own body, so a queued
+ // continuation chained onto it always observes an idle slot.
+ this.currentUpdate = this.runUpdate(targetBackendString)
+ return this.currentUpdate
+ }
+
+ private async runUpdate(
+ targetBackendString: string
+ ): Promise<{ wasUpdated: boolean; newBackend: string }> {
this.isUpdatingBackend = true
+ const startedAt = Date.now()
+ const from = this.config.version_backend
+ let previous: BackendSelection | undefined
try {
if (!targetBackendString)
@@ -1500,6 +1615,8 @@ export default class llamacpp_extension extends AIEngine {
`Updating backend to ${targetBackendString} (backend type: ${backend})`
)
+ previous = await this.captureBackendSelection()
+
// Download new backend using the original asset/backend name
await this.ensureBackendReady(backend, version)
@@ -1508,74 +1625,224 @@ export default class llamacpp_extension extends AIEngine {
await new Promise((resolve) => setTimeout(resolve, 1000))
}
- // Map backend type for stored preference only (not for download/config)
- const effectiveBackendType = await mapOldBackendToNew(backend)
- const currentStoredBackend = await this.getStoredBackendType()
-
- // Persist settings and stored preference before mutating in-memory config,
- // so that if any of these steps fail, config remains consistent.
+ await this.commitBackendSelection(version, backend)
- const settings = await this.getSettings()
- await this.updateSettings(
- settings.map((item) => {
- if (item.key === 'llamacpp_version') {
- item.controllerProps.value = version
- } else if (item.key === 'llamacpp_backend') {
- item.controllerProps.value = backend
- }
- return item
+ if (await this.restartRouterAndProbe()) {
+ logger.info(`Successfully updated to backend: ${targetBackendString}`)
+ await this.pruneOldBackendVersions(version, backend)
+ await this.recordUpdateHistory({
+ from,
+ to: targetBackendString,
+ outcome: 'updated',
+ durationMs: Date.now() - startedAt,
})
+ return { wasUpdated: true, newBackend: targetBackendString }
+ }
+
+ throw new Error(
+ `Router failed its health check on backend ${targetBackendString}`
)
+ } catch (error) {
+ logger.error('Backend update failed:', error)
+ const rollbackOutcome = await this.rollbackBackendSelection(previous)
+ await this.recordUpdateHistory({
+ from,
+ to: targetBackendString,
+ outcome:
+ rollbackOutcome === 'not-attempted' ? 'failed' : rollbackOutcome,
+ error: String(error),
+ durationMs: Date.now() - startedAt,
+ })
+ return { wasUpdated: false, newBackend: this.config.version_backend }
+ } finally {
+ this.isUpdatingBackend = false
+ this.currentUpdate = null
+ }
+ }
- if (currentStoredBackend !== effectiveBackendType) {
- await this.setStoredBackendType(effectiveBackendType)
- logger.info(
- `Updated stored backend type preference: ${effectiveBackendType}`
- )
- }
+ /**
+ * Every update outcome, newest first, for diagnosing a switch after the fact.
+ * Returns an empty list when nothing has been recorded yet.
+ */
+ async getBackendUpdateHistory(): Promise<BackendUpdateRecord[]> {
+ try {
+ const path = await joinPath([
+ await this.getProviderPath(),
+ UPDATE_HISTORY_FILENAME,
+ ])
+ if (!(await fs.existsSync(path))) return []
+ const parsed = JSON.parse(await fs.readFileSync(path, 'utf8'))
+ return Array.isArray(parsed) ? parsed : []
+ } catch (e) {
+ logger.warn('Could not read backend update history:', e)
+ return []
+ }
+ }
- this.config.llamacpp_version = version
- this.config.llamacpp_backend = backend
- this.recomposeVersionBackend()
- this.config.device = ''
+ /**
+ * Append one outcome to the update log. Never throws: losing a diagnostic
+ * record must not turn a working update into a failed one.
+ */
+ private async recordUpdateHistory(
+ record: Omit<BackendUpdateRecord, 'timestamp'>
+ ): Promise<void> {
+ try {
+ const path = await joinPath([
+ await this.getProviderPath(),
+ UPDATE_HISTORY_FILENAME,
+ ])
+ const history = await this.getBackendUpdateHistory()
+ history.unshift({ timestamp: new Date().toISOString(), ...record })
+ await fs.writeFileSync(
+ path,
+ JSON.stringify(history.slice(0, UPDATE_HISTORY_LIMIT), null, 2)
+ )
+ } catch (e) {
+ logger.warn('Could not record backend update history:', e)
+ }
+ }
- logger.info(`Successfully updated to backend: ${targetBackendString}`)
+ /**
+ * Prune superseded installs, keeping BACKEND_VERSIONS_RETAINED older ones as
+ * rollback targets. Runs only after the new backend has passed its health
+ * probe -- pruning earlier would delete the very copy a rollback needs.
+ * Best-effort: a full disk is worse than a failed update, but not by enough
+ * to undo a switch that already works.
+ */
+ private async pruneOldBackendVersions(
+ version: string,
+ backend: string
+ ): Promise<void> {
+ try {
+ const janDataFolderPath = await getJanDataFolderPath()
+ const backendsDir = await joinPath([
+ janDataFolderPath,
+ 'llamacpp',
+ 'backends',
+ ])
- if (events && typeof events.emit === 'function') {
- events.emit('settingsChanged', {
- key: 'llamacpp_version',
- value: version,
- })
- events.emit('settingsChanged', {
- key: 'llamacpp_backend',
- value: backend,
- })
+ if (IS_WINDOWS) {
+ await new Promise((resolve) => setTimeout(resolve, 500))
}
- // Clean up old versions — best-effort, don't fail the update if this errors
- try {
- const janDataFolderPath = await getJanDataFolderPath()
- const backendsDir = await joinPath([
- janDataFolderPath,
- 'llamacpp',
- 'backends',
- ])
+ const removed = await removeOldBackendVersions(
+ backendsDir,
+ version,
+ backend,
+ BACKEND_VERSIONS_RETAINED
+ )
+ if (removed.length) {
+ logger.info(`Pruned ${removed.length} superseded backend install(s)`)
+ }
+ } catch (cleanupError) {
+ logger.warn('Failed to remove old backend versions:', cleanupError)
+ }
+ }
+
+ private async captureBackendSelection(): Promise<BackendSelection> {
+ return {
+ version: this.config.llamacpp_version,
+ backend: this.config.llamacpp_backend,
+ storedType: (await this.getStoredBackendType()) || undefined,
+ }
+ }
+
+ /**
+ * Persist a backend choice across all three places it lives: the settings
+ * file, the stored type preference, and in-memory config. Settings are
+ * written before the in-memory mutation so a failure leaves config coherent.
+ */
+ private async commitBackendSelection(
+ version: string,
+ backend: string
+ ): Promise<void> {
+ const effectiveBackendType = await mapOldBackendToNew(backend)
+ const currentStoredBackend = await this.getStoredBackendType()
- if (IS_WINDOWS) {
- await new Promise((resolve) => setTimeout(resolve, 500))
+ const settings = await this.getSettings()
+ await this.updateSettings(
+ settings.map((item) => {
+ if (item.key === 'llamacpp_version') {
+ item.controllerProps.value = version
+ } else if (item.key === 'llamacpp_backend') {
+ item.controllerProps.value = backend
}
+ return item
+ })
+ )
- await removeOldBackendVersions(backendsDir, version, backend)
- } catch (cleanupError) {
- logger.warn('Failed to remove old backend versions:', cleanupError)
- }
+ if (currentStoredBackend !== effectiveBackendType) {
+ await this.setStoredBackendType(effectiveBackendType)
+ logger.info(
+ `Updated stored backend type preference: ${effectiveBackendType}`
+ )
+ }
- return { wasUpdated: true, newBackend: targetBackendString }
- } catch (error) {
- logger.error('Backend update failed:', error)
- return { wasUpdated: false, newBackend: this.config.version_backend }
- } finally {
- this.isUpdatingBackend = false
+ this.config.llamacpp_version = version
+ this.config.llamacpp_backend = backend
+ this.recomposeVersionBackend()
+ this.config.device = ''
+
+ if (events && typeof events.emit === 'function') {
+ events.emit('settingsChanged', { key: 'llamacpp_version', value: version })
+ events.emit('settingsChanged', { key: 'llamacpp_backend', value: backend })
+ }
+ }
+
+ /**
+ * Bring the router up on whatever backend config currently names and confirm
+ * it answers `/health`. A spawn that throws and a process that starts but
+ * can't serve are the same failure to the caller.
+ *
+ * This is the only gate on a backend switch. Static dependency analysis is
+ * deliberately not one: it is advisory on every other path and cannot be
+ * trusted to fail a switch (see verifyBackendInstallation).
+ */
+ private async restartRouterAndProbe(): Promise<boolean> {
+ try {
+ await this.startRouter()
+ } catch (e) {
+ logger.error('Router failed to start on updated backend:', e)
+ return false
+ }
+ return await routerHealth()
+ }
+
+ /**
+ * Restore the backend that was active before a failed update and bring its
+ * router back. Nothing to do when the update failed before the commit, or
+ * when there was no valid prior selection (first-run install).
+ */
+ private async rollbackBackendSelection(
+ previous: BackendSelection | undefined
+ ): Promise<'rolled-back' | 'rollback-failed' | 'not-attempted'> {
+ if (!previous?.version || !previous.backend) return 'not-attempted'
+ if (
+ this.config.llamacpp_version === previous.version &&
+ this.config.llamacpp_backend === previous.backend
+ ) {
+ return 'not-attempted'
+ }
+
+ const target = `${previous.version}/${previous.backend}`
+ logger.warn(`Rolling back to previous backend: ${target}`)
+ try {
+ await this.commitBackendSelection(previous.version, previous.backend)
+ if (previous.storedType) {
+ await this.setStoredBackendType(previous.storedType)
+ }
+ const healthy = await this.restartRouterAndProbe()
+ if (!healthy) {
+ logger.error(`Rollback target ${target} also failed its health check`)
+ }
+ events.emit(AppEvent.onBackendRollback, {
+ backend: previous.backend,
+ version: previous.version,
+ })
+ return healthy ? 'rolled-back' : 'rollback-failed'
+ } catch (e) {
+ logger.error(`Rollback to ${target} failed:`, e)
+ return 'rollback-failed'
}
}
@@ -1724,26 +1991,32 @@ export default class llamacpp_extension extends AIEngine {
this.unlistenValidationStarted()
}
- // Let any in-flight deferred startup finish so stop_router can't race a
- // concurrent startRouter and leave an orphaned process.
- if (this.backgroundInit) {
- await this.backgroundInit.catch(() => undefined)
- }
-
- try {
- await invoke('plugin:llamacpp|stop_router')
- } catch (e) {
- logger.warn('stop_router during onUnload failed (ignored):', e)
- }
+ // Deliberately does NOT stop the router. The router outlives any single
+ // extension instance: the app owns its lifetime and stops it on
+ // ExitRequested/Exit, and adoption reuses a survivor. An extension teardown
+ // is not an app exit -- React StrictMode and HMR both unload and immediately
+ // reload us, and awaiting backgroundInit here (as this used to) meant
+ // blocking until startRouter had adopted the router, then killing exactly
+ // the process it had just adopted.
this.routerPort = undefined
this.routerApiKey = undefined
}
onSettingUpdate<T>(key: string, value: T): void {
- if (key === 'llamacpp_version' || key === 'llamacpp_backend') {
- if (this.isUpdatingBackend) {
- return
- }
+ // configureBackends and updateBackend both persist settings themselves and
+ // own the router restart that follows, so every notification they trigger
+ // is an echo of their own write, and configureBackends writes the whole
+ // settings array rather than just the backend selection. This only
+ // suppresses echoes delivered while they are still running; a debounced
+ // restart outlives the flag. Reuse in startRouter, not this guard, is what
+ // keeps a late echo from respawning a healthy router.
+ const selfInflicted = this.isUpdatingBackend || this.isConfiguringBackends
+
+ if (
+ selfInflicted &&
+ (key === 'llamacpp_version' || key === 'llamacpp_backend')
+ ) {
+ return
}
this.config[key] = value
@@ -1831,6 +2104,7 @@ export default class llamacpp_extension extends AIEngine {
// A live router was started with the previous preset; without a restart
// the new value is invisible to inference. Debounced so a flurry of
// slider/dropdown updates collapses into one bounce.
+ if (selfInflicted) return
this.scheduleRouterRestart()
}
}
@@ -2868,7 +3142,8 @@ export default class llamacpp_extension extends AIEngine {
}
// Awaits the deferred startup, then makes one direct attempt if the router
- // still isn't up. Idempotent: startRouter stops any existing router first.
+ // still isn't up. Safe to call redundantly: startRouter reuses a router that
+ // already matches this config rather than respawning it.
private async ensureRouterReady(): Promise<void> {
if (this.backgroundInit) {
await this.backgroundInit.catch(() => undefined)
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index ca55f6be0..e3ecf2ef6 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -17,6 +17,12 @@ vi.mock('../backend', () => ({
listSupportedBackends: vi.fn(),
getBackendDir: vi.fn(),
getLocalInstalledBackends: vi.fn(),
+ fetchRemoteBackends: vi.fn(),
+ verifyBackendInstallation: vi.fn().mockResolvedValue({
+ verified: true,
+ missing_libraries: [],
+ resolved_libraries: [],
+ }),
}))
// Mock tauri-plugin-llamacpp-api (partial mock)
@@ -37,6 +43,8 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {
loadLlamaModel: vi.fn(),
unloadLlamaModel: vi.fn(),
reloadRouterModels: vi.fn(),
+ routerHealth: vi.fn().mockResolvedValue(true),
+ adoptRouter: vi.fn(),
}
})
@@ -47,8 +55,18 @@ vi.mock('../preset', async () => {
describe('llamacpp_extension', () => {
let extension: llamacpp_extension
- beforeEach(() => {
+ beforeEach(async () => {
vi.clearAllMocks()
+ // Re-armed per test: afterEach's restoreAllMocks strips implementations
+ // set in the vi.mock factories.
+ const { verifyBackendInstallation } = await import('../backend')
+ vi.mocked(verifyBackendInstallation).mockResolvedValue({
+ verified: true,
+ missing_libraries: [],
+ resolved_libraries: [],
+ })
+ const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(routerHealth).mockResolvedValue(true)
extension = new llamacpp_extension()
})
@@ -579,6 +597,7 @@ describe('llamacpp_extension', () => {
describe('isUpdatingBackend flag', () => {
it('should reset isUpdatingBackend to false after successful update', async () => {
extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
+ extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)
extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')
extension['setStoredBackendType'] = vi.fn()
extension['getSettings'] = vi.fn().mockResolvedValue([])
@@ -610,16 +629,138 @@ describe('llamacpp_extension', () => {
expect(result.wasUpdated).toBe(false)
})
- it('should return no-op when an update is already in progress', async () => {
- // Simulate an update already in progress
- extension['isUpdatingBackend'] = true
+ it('queues a concurrent request instead of dropping it', async () => {
+ extension['config'].llamacpp_version = 'v1.0.0'
+ extension['config'].llamacpp_backend = 'linux-avx2-x64'
+ extension['recomposeVersionBackend']()
+ extension['getStoredBackendType'] = vi
+ .fn()
+ .mockResolvedValue('linux-avx2-x64')
+ extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)
+ extension['getSettings'] = vi.fn().mockResolvedValue([])
+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+ extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)
+ extension['pruneOldBackendVersions'] = vi
+ .fn()
+ .mockResolvedValue(undefined)
+ extension['recordUpdateHistory'] = vi.fn().mockResolvedValue(undefined)
+ const { mapOldBackendToNew } = await import(
+ '@janhq/tauri-plugin-llamacpp-api'
+ )
+ vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)
- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
- expect(result.wasUpdated).toBe(false)
+ let releaseFirst: () => void = () => {}
+ const firstDownload = new Promise<void>((r) => {
+ releaseFirst = r
+ })
+ const ensureBackendReady = vi
+ .fn()
+ .mockImplementationOnce(() => firstDownload)
+ .mockResolvedValue(undefined)
+ extension['ensureBackendReady'] = ensureBackendReady
+
+ const first = extension.updateBackend('v2.0.0/linux-avx2-x64')
+ const queued = extension.updateBackend('v3.0.0/linux-avx2-x64')
+ releaseFirst()
+
+ const [firstResult, queuedResult] = await Promise.all([first, queued])
+
+ expect(firstResult.newBackend).toBe('v2.0.0/linux-avx2-x64')
+ // The queued request ran rather than being silently discarded.
+ expect(queuedResult.wasUpdated).toBe(true)
+ expect(queuedResult.newBackend).toBe('v3.0.0/linux-avx2-x64')
+ expect(ensureBackendReady).toHaveBeenCalledTimes(2)
+ })
+
+ it('coalesces queued requests so only the newest target runs', async () => {
+ extension['config'].llamacpp_version = 'v1.0.0'
+ extension['config'].llamacpp_backend = 'linux-avx2-x64'
+ extension['recomposeVersionBackend']()
+ extension['getStoredBackendType'] = vi
+ .fn()
+ .mockResolvedValue('linux-avx2-x64')
+ extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)
+ extension['getSettings'] = vi.fn().mockResolvedValue([])
+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+ extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)
+ extension['pruneOldBackendVersions'] = vi
+ .fn()
+ .mockResolvedValue(undefined)
+ extension['recordUpdateHistory'] = vi.fn().mockResolvedValue(undefined)
+ const { mapOldBackendToNew } = await import(
+ '@janhq/tauri-plugin-llamacpp-api'
+ )
+ vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)
+
+ let releaseFirst: () => void = () => {}
+ const firstDownload = new Promise<void>((r) => {
+ releaseFirst = r
+ })
+ const ensureBackendReady = vi
+ .fn()
+ .mockImplementationOnce(() => firstDownload)
+ .mockResolvedValue(undefined)
+ extension['ensureBackendReady'] = ensureBackendReady
+
+ const first = extension.updateBackend('v2.0.0/linux-avx2-x64')
+ const superseded = extension.updateBackend('v3.0.0/linux-avx2-x64')
+ const newest = extension.updateBackend('v4.0.0/linux-avx2-x64')
+ releaseFirst()
+
+ const results = await Promise.all([first, superseded, newest])
+
+ // v3 never runs: obsolete before it could start. Both waiters on the
+ // queued slot get the v4 result.
+ expect(ensureBackendReady).toHaveBeenCalledTimes(2)
+ expect(results[1].newBackend).toBe('v4.0.0/linux-avx2-x64')
+ expect(results[2].newBackend).toBe('v4.0.0/linux-avx2-x64')
+ expect(extension['config'].version_backend).toBe(
+ 'v4.0.0/linux-avx2-x64'
+ )
})
})
describe('onSettingUpdate guard', () => {
+ it('does not restart the router while configureBackends is persisting settings', async () => {
+ // configureBackends writes llamacpp_version/backend on every launch.
+ // Reacting to that would restart the router a second time, which at
+ // startup kills the router adoption just took over.
+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ extension['isConfiguringBackends'] = true
+
+ extension.onSettingUpdate('llamacpp_backend', 'linux-avx2-x64')
+ await new Promise((r) => setTimeout(r, 0))
+
+ expect(extension['ensureBackendReady']).not.toHaveBeenCalled()
+ expect(extension['startRouter']).not.toHaveBeenCalled()
+ })
+
+ it('does not schedule a preset restart for configureBackends own writes', async () => {
+ // configureBackends persists the entire settings array, so every
+ // preset-affecting key echoes back through here. Debouncing a restart
+ // off that echo is what killed the adopted router ~600ms into startup.
+ const scheduleRouterRestart = vi.fn()
+ extension['scheduleRouterRestart'] = scheduleRouterRestart
+ extension['isConfiguringBackends'] = true
+
+ extension.onSettingUpdate('ctx_size', 4096)
+
+ expect(scheduleRouterRestart).not.toHaveBeenCalled()
+ // The value is still applied; only the restart is suppressed.
+ expect(extension['config'].ctx_size).toBe(4096)
+ })
+
+ it('still schedules a preset restart for a genuine user edit', async () => {
+ const scheduleRouterRestart = vi.fn()
+ extension['scheduleRouterRestart'] = scheduleRouterRestart
+ extension['isConfiguringBackends'] = false
+
+ extension.onSettingUpdate('ctx_size', 8192)
+
+ expect(scheduleRouterRestart).toHaveBeenCalledTimes(1)
+ })
+
it('should skip ensureBackendReady in onSettingUpdate when updateBackend is in progress', async () => {
extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
@@ -637,6 +778,7 @@ describe('llamacpp_extension', () => {
describe('stored backend type', () => {
it('should store effectiveBackendType, not the full version/backend string', async () => {
extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
+ extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)
extension['getStoredBackendType'] = vi.fn().mockReturnValue('old-backend-type')
extension['setStoredBackendType'] = vi.fn()
extension['getSettings'] = vi.fn().mockResolvedValue([])
@@ -658,9 +800,182 @@ describe('llamacpp_extension', () => {
})
})
+ describe('atomicity', () => {
+ const armUpdate = async (extension: llamacpp_extension) => {
+ extension['config'].llamacpp_version = 'v1.0.0'
+ extension['config'].llamacpp_backend = 'linux-avx2-x64'
+ extension['recomposeVersionBackend']()
+ extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
+ extension['getStoredBackendType'] = vi.fn().mockResolvedValue('linux-avx2-x64')
+ extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)
+ extension['getSettings'] = vi.fn().mockResolvedValue([])
+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)
+ const { mapOldBackendToNew } = await import(
+ '@janhq/tauri-plugin-llamacpp-api'
+ )
+ vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)
+ }
+
+ it('restarts the router so the new binary actually serves', async () => {
+ await armUpdate(extension)
+ const startRouter = vi.fn().mockResolvedValue(undefined)
+ extension['startRouter'] = startRouter
+
+ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(startRouter).toHaveBeenCalledTimes(1)
+ expect(result.wasUpdated).toBe(true)
+ expect(result.newBackend).toBe('v2.0.0/linux-avx2-x64')
+ })
+
+ // Static dep analysis false-positives (libs dlopen'd at runtime, or
+ // resolved from paths the analyzer does not search but the spawn env
+ // does). A router that serves /health is proof the binary works,
+ // whatever lddtree concluded.
+ it('does not block a switch on a missing-library report', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const { verifyBackendInstallation } = await import('../backend')
+ vi.mocked(verifyBackendInstallation).mockResolvedValue({
+ verified: false,
+ missing_libraries: ['libcudart.so.12'],
+ resolved_libraries: [],
+ })
+
+ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(result.wasUpdated).toBe(true)
+ expect(extension['config'].version_backend).toBe(
+ 'v2.0.0/linux-avx2-x64'
+ )
+ })
+
+ it('rolls back when the router fails its health check', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(routerHealth).mockResolvedValue(false)
+
+ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(result.wasUpdated).toBe(false)
+ expect(extension['config'].llamacpp_version).toBe('v1.0.0')
+ // Once for the failed target, once bringing the old backend back up.
+ expect(extension['startRouter']).toHaveBeenCalledTimes(2)
+ })
+
+ it('rolls back when the router process refuses to start', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('spawn failed'))
+ .mockResolvedValue(undefined)
+
+ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(result.wasUpdated).toBe(false)
+ expect(extension['config'].version_backend).toBe(
+ 'v1.0.0/linux-avx2-x64'
+ )
+ })
+
+ it('prunes superseded installs only after the probe passes', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const { removeOldBackendVersions } = await import(
+ '@janhq/tauri-plugin-llamacpp-api'
+ )
+ vi.mocked(removeOldBackendVersions).mockResolvedValue([])
+ const { joinPath } = await import('@janhq/core')
+ vi.mocked(joinPath).mockResolvedValue('/jan/llamacpp/backends')
+
+ await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(removeOldBackendVersions).toHaveBeenCalledWith(
+ '/jan/llamacpp/backends',
+ 'v2.0.0',
+ 'linux-avx2-x64',
+ 2
+ )
+ })
+
+ it('keeps the rollback target on disk when the probe fails', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const { removeOldBackendVersions, routerHealth } = await import(
+ '@janhq/tauri-plugin-llamacpp-api'
+ )
+ vi.mocked(routerHealth).mockResolvedValue(false)
+
+ await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ // Pruning here would delete the version we just rolled back onto.
+ expect(removeOldBackendVersions).not.toHaveBeenCalled()
+ })
+
+ it('records the outcome of a failed switch as rolled-back when the rollback target is healthy', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const written: unknown[] = []
+ extension['recordUpdateHistory'] = vi.fn(async (r) => {
+ written.push(r)
+ })
+ const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(routerHealth)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+
+ await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(written).toHaveLength(1)
+ expect(written[0]).toMatchObject({
+ from: 'v1.0.0/linux-avx2-x64',
+ to: 'v2.0.0/linux-avx2-x64',
+ outcome: 'rolled-back',
+ })
+ })
+
+ it('records the outcome as rollback-failed when the rollback target also fails its health check', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ const written: unknown[] = []
+ extension['recordUpdateHistory'] = vi.fn(async (r) => {
+ written.push(r)
+ })
+ const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')
+ vi.mocked(routerHealth).mockResolvedValue(false)
+
+ await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(written).toHaveLength(1)
+ expect(written[0]).toMatchObject({
+ from: 'v1.0.0/linux-avx2-x64',
+ to: 'v2.0.0/linux-avx2-x64',
+ outcome: 'rollback-failed',
+ })
+ })
+
+ it('does not attempt a rollback when the download fails pre-commit', async () => {
+ await armUpdate(extension)
+ extension['startRouter'] = vi.fn().mockResolvedValue(undefined)
+ extension['ensureBackendReady'] = vi
+ .fn()
+ .mockRejectedValue(new Error('download failed'))
+
+ const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')
+
+ expect(result.wasUpdated).toBe(false)
+ expect(extension['startRouter']).not.toHaveBeenCalled()
+ expect(extension['config'].version_backend).toBe(
+ 'v1.0.0/linux-avx2-x64'
+ )
+ })
+ })
+
describe('trimming', () => {
it('should trim whitespace from version and backend before use', async () => {
extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)
+ extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)
extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')
extension['setStoredBackendType'] = vi.fn()
extension['getSettings'] = vi.fn().mockResolvedValue([])
@@ -987,3 +1302,214 @@ describe('bootstrapDefaultEmbedder', () => {
expect(setBackendSetting).not.toHaveBeenCalled()
})
})
+
+describe('router adoption after a UI crash', () => {
+ let extension: llamacpp_extension
+
+ const armStartRouter = async () => {
+ extension = new llamacpp_extension()
+ extension['config'] = {
+ version_backend: 'b9100/cpu',
+ models_max: 1,
+ } as never
+ extension['timeout'] = 600
+
+ const { generatePreset } = await import('../preset')
+ vi.mocked(generatePreset).mockResolvedValue({
+ path: '/jan/llamacpp/router.preset.ini',
+ embeddingCount: 0,
+ })
+ const { getJanDataFolderPath } = await import('@janhq/core')
+ vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')
+ vi.spyOn(extension, 'getProviderPath').mockResolvedValue('/jan/llamacpp')
+
+ const backendModule = await import('../backend')
+ vi.mocked(backendModule.getBackendExePath).mockResolvedValue(
+ '/backends/b9100/cpu/llama-server'
+ )
+ vi.spyOn(extension as never, 'getRandomPort' as never).mockResolvedValue(
+ 12345 as never
+ )
+ vi.spyOn(extension as never, 'generateApiKey' as never).mockResolvedValue(
+ 'derived-key' as never
+ )
+
+ const { invoke } = await import('@tauri-apps/api/core')
+ // get_router_info: nothing running in memory, which is the post-crash state.
+ vi.mocked(invoke).mockResolvedValue(null)
+
+ const { adoptRouter } = await import('@janhq/tauri-plugin-llamacpp-api')
+ return { adoptRouter: vi.mocked(adoptRouter), invoke: vi.mocked(invoke) }
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('reuses an adopted router instead of spawning a second one', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockResolvedValue({
+ port: 45678,
+ api_key: 'adopted-key',
+ pid: 999,
+ })
+
+ await extension['startRouter']()
+
+ expect(adoptRouter).toHaveBeenCalledTimes(1)
+ expect(extension['routerPort']).toBe(45678)
+ expect(extension['routerApiKey']).toBe('adopted-key')
+ expect(invoke).not.toHaveBeenCalledWith(
+ 'plugin:llamacpp|start_router',
+ expect.anything()
+ )
+ })
+
+ it('spawns a fresh router when there is nothing to adopt', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockResolvedValue(null)
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|start_router') {
+ return { port: 12345, api_key: 'fresh-key', pid: 111 }
+ }
+ return null
+ })
+
+ await extension['startRouter']()
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|start_router',
+ expect.anything()
+ )
+ expect(extension['routerPort']).toBe(12345)
+ })
+
+ it('falls back to spawning when adoption itself throws', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockRejectedValue(new Error('lock unreadable'))
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|start_router') {
+ return { port: 12345, api_key: 'fresh-key', pid: 111 }
+ }
+ return null
+ })
+
+ await extension['startRouter']()
+
+ expect(invoke).toHaveBeenCalledWith(
+ 'plugin:llamacpp|start_router',
+ expect.anything()
+ )
+ })
+
+ it('passes the effective models_max so an argv-only change is caught', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ extension['config'].models_max = 3 as never
+ adoptRouter.mockResolvedValue(null)
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|start_router') {
+ return { port: 12345, api_key: 'fresh-key', pid: 111 }
+ }
+ return null
+ })
+
+ await extension['startRouter']()
+
+ expect(adoptRouter).toHaveBeenCalledWith(
+ '/backends/b9100/cpu/llama-server',
+ '/jan/llamacpp/router.preset.ini',
+ 3,
+ expect.any(String)
+ )
+ })
+
+ it('never stops a router before trying to adopt it', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ const calls: string[] = []
+ adoptRouter.mockImplementation(async () => {
+ calls.push('adopt')
+ return { port: 45678, api_key: 'adopted-key', pid: 999 }
+ })
+ invoke.mockImplementation(async (cmd: string) => {
+ calls.push(cmd)
+ return null
+ })
+
+ await extension['startRouter']()
+
+ expect(calls[0]).toBe('adopt')
+ expect(calls).not.toContain('plugin:llamacpp|stop_router')
+ })
+
+ it('coalesces concurrent starts so the second cannot kill the first', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockResolvedValue(null)
+ let spawns = 0
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|start_router') {
+ spawns += 1
+ await new Promise((r) => setTimeout(r, 10))
+ return { port: 12345, api_key: 'fresh-key', pid: 111 }
+ }
+ return null
+ })
+
+ await Promise.all([extension['startRouter'](), extension['startRouter']()])
+
+ expect(spawns).toBe(1)
+ expect(invoke).not.toHaveBeenCalledWith('plugin:llamacpp|stop_router')
+ expect(extension['routerPort']).toBe(12345)
+ })
+
+ it('releases the lock so a later start can still run', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockResolvedValue(null)
+ invoke.mockImplementation(async (cmd: string) =>
+ cmd === 'plugin:llamacpp|start_router'
+ ? { port: 12345, api_key: 'fresh-key', pid: 111 }
+ : null
+ )
+
+ await extension['startRouter']()
+ await extension['startRouter']()
+
+ expect(adoptRouter).toHaveBeenCalledTimes(2)
+ expect(extension['routerStartLock']).toBeNull()
+ })
+
+ it('onUnload leaves the router running for the next instance to adopt', async () => {
+ const { invoke } = await armStartRouter()
+ extension['routerPort'] = 45678
+ extension['routerApiKey'] = 'adopted-key'
+ let adoptResolved = false
+ extension['backgroundInit'] = (async () => {
+ await new Promise((r) => setTimeout(r, 10))
+ adoptResolved = true
+ })()
+
+ await extension.onUnload()
+
+ expect(invoke).not.toHaveBeenCalledWith('plugin:llamacpp|stop_router')
+ // Must not block on the in-flight adoption either; that ordering is what
+ // pinned the kill to the moment adoption completed.
+ expect(adoptResolved).toBe(false)
+ expect(extension['routerPort']).toBeUndefined()
+ expect(extension['routerApiKey']).toBeUndefined()
+ })
+
+ it('releases the lock even when the spawn fails', async () => {
+ const { adoptRouter, invoke } = await armStartRouter()
+ adoptRouter.mockResolvedValue(null)
+ invoke.mockImplementation(async (cmd: string) => {
+ if (cmd === 'plugin:llamacpp|start_router') throw new Error('no port')
+ return null
+ })
+
+ await expect(extension['startRouter']()).rejects.toThrow('no port')
+ expect(extension['routerStartLock']).toBeNull()
+ })
+})
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index efeff2951..0d406c954 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -6890,6 +6890,7 @@ dependencies = [
"reqwest 0.12.23",
"serde",
"serde_json",
+ "serde_yaml",
"sha2",
"sysinfo",
"tauri",
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock
index 070239019..de96b347e 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock
@@ -2999,6 +2999,19 @@ dependencies = [
"syn 2.0.118",
]
+[[package]]
+name = "serde_yaml"
+version = "0.9.34+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap 2.14.0",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
[[package]]
name = "serialize-to-javascript"
version = "0.1.2"
@@ -3428,6 +3441,7 @@ dependencies = [
"reqwest 0.12.28",
"serde",
"serde_json",
+ "serde_yaml",
"sha2",
"sysinfo",
"tauri",
@@ -3954,6 +3968,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+[[package]]
+name = "unsafe-libyaml"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
[[package]]
name = "untrusted"
version = "0.9.0"
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
index d07b50954..177cf7ee9 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
@@ -26,6 +26,7 @@ thiserror = "2.0.12"
tokio = { version = "1", features = ["full"] }
tauri-plugin-hardware = { path = "../tauri-plugin-hardware" }
serde_json = "1.0.149"
+serde_yaml = "0.9.34"
futures-util = "0.3"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 78cd3d634..46ec34390 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -12,6 +12,8 @@ const COMMANDS: &[&str] = &[
"get_router_info",
"reload_router_models",
"router_slots_idle",
+ "router_health",
+ "adopt_router",
"get_devices",
"generate_api_key",
"is_process_running",
@@ -48,6 +50,8 @@ const COMMANDS: &[&str] = &[
"verify_backend_installation",
"fetch_remote_supported_backends",
"build_backend_download_items",
+ "fetch_backend_checksums",
+ "verify_file_sha512",
];
fn main() {
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index ae11f9b6c..eeb10bca2 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -186,6 +186,27 @@ export async function reloadRouterModels(): Promise<void> {
return await invoke('plugin:llamacpp|reload_router_models')
}
+export async function routerHealth(
+ port?: number,
+ apiKey?: string
+): Promise<boolean> {
+ return await invoke('plugin:llamacpp|router_health', { port, apiKey })
+}
+
+export async function adoptRouter(
+ backendExe: string,
+ presetPath: string,
+ modelsMax: number,
+ apiSecret: string
+): Promise<{ port: number; api_key: string; pid: number } | null> {
+ return await invoke('plugin:llamacpp|adopt_router', {
+ backendExe,
+ presetPath,
+ modelsMax,
+ apiSecret,
+ })
+}
+
// GGUF commands
export async function readGgufMetadata(path: string): Promise<GgufMetadata> {
return await invoke('plugin:llamacpp|read_gguf_metadata', { path })
@@ -338,15 +359,36 @@ export async function checkBackendForUpdates(
export async function removeOldBackendVersions(
backendsDir: string,
latestVersion: string,
- backendType: string
+ backendType: string,
+ keepPrevious: number
): Promise<string[]> {
return invoke('plugin:llamacpp|remove_old_backend_versions', {
backendsDir,
latestVersion,
backendType,
+ keepPrevious,
})
}
+export async function fetchBackendChecksums(
+ version: string,
+ source: 'github' | 'cdn',
+ proxy?: object | null
+): Promise<Record<string, string>> {
+ return invoke('plugin:llamacpp|fetch_backend_checksums', {
+ version,
+ source,
+ proxy,
+ })
+}
+
+export async function verifyFileSha512(
+ path: string,
+ expected: string
+): Promise<boolean> {
+ return invoke('plugin:llamacpp|verify_file_sha512', { path, expected })
+}
+
export async function validateBackendString(
backendString: string
): Promise<[string, string]> {
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 5dc556d09..b96ca3302 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -14,6 +14,8 @@ Default permissions for the llamacpp plugin
- `allow-get-router-info`
- `allow-reload-router-models`
- `allow-router-slots-idle`
+- `allow-router-health`
+- `allow-adopt-router`
- `allow-get-devices`
- `allow-generate-api-key`
- `allow-is-process-running`
@@ -47,6 +49,8 @@ Default permissions for the llamacpp plugin
- `allow-verify-backend-installation`
- `allow-fetch-remote-supported-backends`
- `allow-build-backend-download-items`
+- `allow-fetch-backend-checksums`
+- `allow-verify-file-sha512`
## Permission Table
@@ -57,6 +61,32 @@ Default permissions for the llamacpp plugin
</tr>
+<tr>
+<td>
+
+`llamacpp:allow-adopt-router`
+
+</td>
+<td>
+
+Enables the adopt_router command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-adopt-router`
+
+</td>
+<td>
+
+Denies the adopt_router command without any pre-configured scope.
+
+</td>
+</tr>
+
<tr>
<td>
@@ -242,6 +272,32 @@ Denies the estimate_kv_cache_size command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-fetch-backend-checksums`
+
+</td>
+<td>
+
+Enables the fetch_backend_checksums command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-fetch-backend-checksums`
+
+</td>
+<td>
+
+Denies the fetch_backend_checksums command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-fetch-remote-supported-backends`
</td>
@@ -970,6 +1026,32 @@ Denies the remove_old_backend_versions command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-router-health`
+
+</td>
+<td>
+
+Enables the router_health command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-router-health`
+
+</td>
+<td>
+
+Denies the router_health command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-router-slots-idle`
</td>
@@ -1172,6 +1254,32 @@ Enables the verify_backend_installation command without any pre-configured scope
Denies the verify_backend_installation command without any pre-configured scope.
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:allow-verify-file-sha512`
+
+</td>
+<td>
+
+Enables the verify_file_sha512 command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-verify-file-sha512`
+
+</td>
+<td>
+
+Denies the verify_file_sha512 command without any pre-configured scope.
+
</td>
</tr>
</table>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
index 08360a15e..0fb70ba92 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -14,6 +14,8 @@ permissions = [
"allow-get-router-info",
"allow-reload-router-models",
"allow-router-slots-idle",
+ "allow-router-health",
+ "allow-adopt-router",
"allow-get-devices",
"allow-generate-api-key",
"allow-is-process-running",
@@ -52,5 +54,7 @@ permissions = [
"allow-check-backend-installed",
"allow-verify-backend-installation",
"allow-fetch-remote-supported-backends",
- "allow-build-backend-download-items"
+ "allow-build-backend-download-items",
+ "allow-fetch-backend-checksums",
+ "allow-verify-file-sha512"
]
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 2724053cf..494ee500a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -294,6 +294,18 @@
"PermissionKind": {
"type": "string",
"oneOf": [
+ {
+ "description": "Enables the adopt_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-adopt-router",
+ "markdownDescription": "Enables the adopt_router command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the adopt_router command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-adopt-router",
+ "markdownDescription": "Denies the adopt_router command without any pre-configured scope."
+ },
{
"description": "Enables the build_backend_download_items command without any pre-configured scope.",
"type": "string",
@@ -378,6 +390,18 @@
"const": "deny-estimate-kv-cache-size",
"markdownDescription": "Denies the estimate_kv_cache_size command without any pre-configured scope."
},
+ {
+ "description": "Enables the fetch_backend_checksums command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-fetch-backend-checksums",
+ "markdownDescription": "Enables the fetch_backend_checksums command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the fetch_backend_checksums command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-fetch-backend-checksums",
+ "markdownDescription": "Denies the fetch_backend_checksums command without any pre-configured scope."
+ },
{
"description": "Enables the fetch_remote_supported_backends command without any pre-configured scope.",
"type": "string",
@@ -714,6 +738,18 @@
"const": "deny-remove-old-backend-versions",
"markdownDescription": "Denies the remove_old_backend_versions command without any pre-configured scope."
},
+ {
+ "description": "Enables the router_health command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-router-health",
+ "markdownDescription": "Enables the router_health command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the router_health command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-router-health",
+ "markdownDescription": "Denies the router_health command without any pre-configured scope."
+ },
{
"description": "Enables the router_slots_idle command without any pre-configured scope.",
"type": "string",
@@ -811,10 +847,22 @@
"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-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`",
+ "description": "Enables the verify_file_sha512 command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-verify-file-sha512",
+ "markdownDescription": "Enables the verify_file_sha512 command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the verify_file_sha512 command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-verify-file-sha512",
+ "markdownDescription": "Denies the verify_file_sha512 command without any pre-configured scope."
+ },
+ {
+ "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`"
+ "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
index ff3080486..5ec292ed8 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs
@@ -729,11 +729,19 @@ pub async fn check_backend_for_updates(
}
}
+/// Prune installs of `backend_type`, always keeping `latest_version` and the
+/// `keep_previous` newest versions below it. Those retained copies are what
+/// makes a rollback possible without a re-download, so this must never be run
+/// before a switch has proven itself.
+///
+/// Ordering is by parsed build number, not directory name: `b9100` must sort
+/// above `b982`, which a lexical compare gets backwards.
#[tauri::command]
pub async fn remove_old_backend_versions(
backends_dir: String,
latest_version: String,
backend_type: String,
+ keep_previous: usize,
) -> Result<Vec<String>, String> {
let mut removed_paths = Vec::new();
let backends_path = PathBuf::from(&backends_dir);
@@ -745,6 +753,7 @@ pub async fn remove_old_backend_versions(
let version_dirs = fs::read_dir(&backends_path)
.map_err(|e| format!("Failed to read backends directory: {}", e))?;
+ let mut candidates: Vec<(u32, String, PathBuf)> = Vec::new();
for version_entry in version_dirs {
let version_entry =
version_entry.map_err(|e| format!("Failed to read version entry: {}", e))?;
@@ -755,34 +764,58 @@ pub async fn remove_old_backend_versions(
None => continue,
};
- // Skip the latest version
if version_name == latest_version {
continue;
}
- // Check if this version has the specific backend type
let backend_type_path = version_path.join(&backend_type);
+ if !backend_type_path.exists() || !is_backend_installed(&backend_type_path) {
+ continue;
+ }
- if backend_type_path.exists() {
- // Verify it's actually installed before removing
- if is_backend_installed(&backend_type_path) {
- match fs::remove_dir_all(&backend_type_path) {
- Ok(_) => {
- log::info!(
- "Removed old version of {}: {}",
- backend_type,
- backend_type_path.display()
- );
- removed_paths.push(backend_type_path.to_string_lossy().to_string());
- }
- Err(e) => {
- log::warn!(
- "Failed to remove old backend version: {} - {}",
- backend_type_path.display(),
- e
- );
- }
- }
+ candidates.push((
+ parse_backend_version(version_name.clone()),
+ version_name,
+ backend_type_path,
+ ));
+ }
+
+ // Newest first, name as a tiebreaker so unparseable versions (all 0) are
+ // still pruned deterministically.
+ candidates.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));
+
+ if candidates.len() > keep_previous {
+ let retained: Vec<&str> = candidates
+ .iter()
+ .take(keep_previous)
+ .map(|(_, name, _)| name.as_str())
+ .collect();
+ log::info!(
+ "Pruning {} of {}: keeping active {} plus {:?}",
+ backend_type,
+ latest_version,
+ latest_version,
+ retained
+ );
+ }
+
+ for (_, version_name, path) in candidates.into_iter().skip(keep_previous) {
+ match fs::remove_dir_all(&path) {
+ Ok(_) => {
+ log::info!(
+ "Removed old version {} of {}: {}",
+ version_name,
+ backend_type,
+ path.display()
+ );
+ removed_paths.push(path.to_string_lossy().to_string());
+ }
+ Err(e) => {
+ log::warn!(
+ "Failed to remove old backend version: {} - {}",
+ path.display(),
+ e
+ );
}
}
}
@@ -1378,6 +1411,158 @@ mod tests {
use std::fs::File;
use std::io::Write;
+ fn install_backend(root: &Path, version: &str, backend: &str) {
+ let dir = root.join(version).join(backend);
+ std::fs::create_dir_all(&dir).unwrap();
+ let exe = if cfg!(target_os = "windows") {
+ "llama-server.exe"
+ } else {
+ "llama-server"
+ };
+ File::create(dir.join(exe)).unwrap();
+ }
+
+ fn versions_left(root: &Path, backend: &str) -> Vec<String> {
+ let mut v: Vec<String> = std::fs::read_dir(root)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().join(backend).exists())
+ .map(|e| e.file_name().to_string_lossy().to_string())
+ .collect();
+ v.sort();
+ v
+ }
+
+ #[tokio::test]
+ async fn retention_keeps_the_active_version_and_n_previous() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ for v in ["b900", "b1000", "b1100", "b1200"] {
+ install_backend(root, v, "cpu");
+ }
+
+ let removed = remove_old_backend_versions(
+ root.to_string_lossy().to_string(),
+ "b1200".into(),
+ "cpu".into(),
+ 2,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(removed.len(), 1);
+ assert_eq!(versions_left(root, "cpu"), vec!["b1000", "b1100", "b1200"]);
+ }
+
+ #[tokio::test]
+ async fn retention_orders_by_build_number_not_lexically() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ // Lexically "b982" > "b1100"; by build number it is older and must go.
+ for v in ["b982", "b1100", "b1200"] {
+ install_backend(root, v, "cpu");
+ }
+
+ remove_old_backend_versions(
+ root.to_string_lossy().to_string(),
+ "b1200".into(),
+ "cpu".into(),
+ 1,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(versions_left(root, "cpu"), vec!["b1100", "b1200"]);
+ }
+
+ #[tokio::test]
+ async fn retention_never_removes_the_active_version() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ install_backend(root, "b1000", "cpu");
+
+ let removed = remove_old_backend_versions(
+ root.to_string_lossy().to_string(),
+ "b1000".into(),
+ "cpu".into(),
+ 0,
+ )
+ .await
+ .unwrap();
+
+ assert!(removed.is_empty());
+ assert_eq!(versions_left(root, "cpu"), vec!["b1000"]);
+ }
+
+ #[tokio::test]
+ async fn retention_ignores_other_backend_types() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ install_backend(root, "b900", "cpu");
+ install_backend(root, "b900", "cuda");
+ install_backend(root, "b1000", "cpu");
+
+ remove_old_backend_versions(
+ root.to_string_lossy().to_string(),
+ "b1000".into(),
+ "cpu".into(),
+ 0,
+ )
+ .await
+ .unwrap();
+
+ // The cuda install under b900 survives; only its cpu sibling is pruned.
+ assert!(root.join("b900").join("cuda").exists());
+ assert!(!root.join("b900").join("cpu").exists());
+ }
+
+ #[test]
+ fn digest_normalization_tolerates_producer_quirks() {
+ // Windows CertUtil output: uppercase, BOM, folded whitespace.
+ assert_eq!(normalize_digest("\u{feff}AB\n cd \r\n"), "abcd");
+ assert_eq!(normalize_digest(" abcd "), "abcd");
+ assert_eq!(normalize_digest(""), "");
+ // Non-hex noise cannot smuggle itself into a digest.
+ assert_eq!(normalize_digest("zz12zz"), "12");
+ }
+
+ #[test]
+ fn checksum_manifest_parses_the_published_shape() {
+ let yaml = "version: b1234\nfiles:\n\
+ - url: llama-b1234-bin-linux-x64.tar.gz\n sha512: >-\n ABCD\n size: 10\n\
+ - url: cudart-llama-bin-linux-cu12.0-x64.tar.gz\n sha512: >-\n beef\n size: 20\n";
+ let m: ChecksumManifest = serde_yaml::from_str(yaml).unwrap();
+ assert_eq!(m.files.len(), 2);
+ assert_eq!(m.files[0].url, "llama-b1234-bin-linux-x64.tar.gz");
+ assert_eq!(normalize_digest(&m.files[0].sha512), "abcd");
+ }
+
+ #[tokio::test]
+ async fn sha512_verification_accepts_and_rejects() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("archive.tar.gz");
+ std::fs::write(&path, b"jan").unwrap();
+
+ let actual = {
+ use sha2::{Digest, Sha512};
+ let mut h = Sha512::new();
+ h.update(b"jan");
+ format!("{:x}", h.finalize())
+ };
+ let p = path.to_string_lossy().to_string();
+
+ assert!(verify_file_sha512(p.clone(), actual.to_uppercase())
+ .await
+ .unwrap());
+ assert!(!verify_file_sha512(p.clone(), "dead".repeat(32))
+ .await
+ .unwrap());
+ // No published digest means nothing to contradict.
+ assert!(verify_file_sha512(p.clone(), String::new()).await.unwrap());
+ // A malformed (too-short) digest is fail-soft, not a mismatch.
+ assert!(verify_file_sha512(p, "zz12zz".into()).await.unwrap());
+ }
+
// --- Tests for map_old_backend_to_new ---
#[test]
@@ -2207,3 +2392,119 @@ mod tests {
assert_ne!(github_items[0].url, cdn_items[0].url);
}
}
+
+// ============================================================================
+// Release checksum verification
+// ============================================================================
+
+#[derive(Deserialize)]
+struct ChecksumEntry {
+ url: String,
+ sha512: String,
+}
+
+#[derive(Deserialize)]
+struct ChecksumManifest {
+ files: Vec<ChecksumEntry>,
+}
+
+/// Normalize a digest as published. The Windows job produces it via `CertUtil`
+/// piped through `Out-File`, so it can arrive uppercase and carrying a BOM or
+/// UTF-16 padding; the YAML folded scalar (`>-`) can also fold in whitespace.
+/// Keeping only hex digits is the one rule that holds for every producer.
+fn normalize_digest(raw: &str) -> String {
+ raw.chars()
+ .filter(|c| c.is_ascii_hexdigit())
+ .flat_map(|c| c.to_lowercase())
+ .collect()
+}
+
+/// Fetch `checksum.yml` for a release and return `filename -> sha512`.
+///
+/// Returns an empty map rather than an error when the manifest is absent or
+/// unparseable: releases published before the manifest existed (and those
+/// whose entries predate the `-bin-` naming fix) must stay installable.
+#[tauri::command]
+pub async fn fetch_backend_checksums(
+ version: String,
+ source: String,
+ proxy: Option<ProxyConfig>,
+) -> Result<HashMap<String, String>, String> {
+ let url = if source == "cdn" {
+ format!(
+ "https://catalog.jan.ai/llama.cpp/releases/{}/checksum.yml",
+ version
+ )
+ } else {
+ format!(
+ "https://github.com/janhq/llama.cpp/releases/download/{}/checksum.yml",
+ version
+ )
+ };
+
+ let client = build_http_client(proxy.as_ref())?;
+ let resp = match client.get(&url).send().await {
+ Ok(r) if r.status().is_success() => r,
+ Ok(r) => {
+ log::warn!("checksum.yml for {} returned HTTP {}", version, r.status());
+ return Ok(HashMap::new());
+ }
+ Err(e) => {
+ log::warn!("Could not fetch checksum.yml for {}: {}", version, e);
+ return Ok(HashMap::new());
+ }
+ };
+
+ let body = match resp.text().await {
+ Ok(b) => b,
+ Err(e) => {
+ log::warn!("Could not read checksum.yml for {}: {}", version, e);
+ return Ok(HashMap::new());
+ }
+ };
+
+ match serde_yaml::from_str::<ChecksumManifest>(&body) {
+ Ok(m) => Ok(m
+ .files
+ .into_iter()
+ .map(|f| (f.url, normalize_digest(&f.sha512)))
+ .filter(|(_, digest)| !digest.is_empty())
+ .collect()),
+ Err(e) => {
+ log::warn!("Could not parse checksum.yml for {}: {}", version, e);
+ Ok(HashMap::new())
+ }
+ }
+}
+
+/// Streams the file so a multi-GB archive is never held in memory.
+#[tauri::command]
+pub async fn verify_file_sha512(path: String, expected: String) -> Result<bool, String> {
+ let expected = normalize_digest(&expected);
+ if expected.is_empty() {
+ return Ok(true);
+ }
+ if expected.len() != 128 {
+ log::warn!("Malformed SHA-512 digest (expected 128 hex chars, got {}), skipping verification", expected.len());
+ return Ok(true);
+ }
+
+ tokio::task::spawn_blocking(move || {
+ use sha2::{Digest, Sha512};
+ use std::io::Read;
+
+ let mut file = fs::File::open(&path).map_err(|e| format!("{}: {}", path, e))?;
+ let mut hasher = Sha512::new();
+ let mut buf = vec![0u8; 1024 * 1024];
+ loop {
+ let n = file.read(&mut buf).map_err(|e| format!("{}: {}", path, e))?;
+ if n == 0 {
+ break;
+ }
+ hasher.update(&buf[..n]);
+ }
+ Ok(format!("{:x}", hasher.finalize()) == expected)
+ })
+ .await
+ .map_err(|e| format!("Checksum task panicked: {}", e))?
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index af74f4971..f3ebf721d 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -32,6 +32,8 @@ async fn router_endpoint<R: Runtime>(
Ok((h.port, h.api_key.clone(), h.pid))
}
+const ROUTER_HEALTH_TIMEOUT_SECS: u64 = 5;
+
async fn http_client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(600))
@@ -812,6 +814,7 @@ pub async fn start_router<R: Runtime>(
app_handle: tauri::AppHandle<R>,
backend_exe: String,
preset_path: String,
+ log_dir: String,
port: u16,
api_key: String,
models_max: u32,
@@ -847,6 +850,7 @@ pub async fn start_router<R: Runtime>(
let handle = crate::router::start_router(
std::path::PathBuf::from(backend_exe),
std::path::PathBuf::from(preset_path),
+ std::path::PathBuf::from(log_dir),
port,
api_key,
models_max,
@@ -873,6 +877,62 @@ pub async fn start_router<R: Runtime>(
Ok(info)
}
+/// Reuse a router that outlived its UI, or kill it if it no longer matches.
+///
+/// Returns the adopted endpoint, or `None` when the caller should spawn a
+/// fresh router. `api_secret` is used to re-derive the router's key from the
+/// port recorded in the lock file, so the key never has to be persisted.
+#[tauri::command]
+pub async fn adopt_router<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ backend_exe: String,
+ preset_path: String,
+ models_max: u32,
+ api_secret: String,
+) -> Result<Option<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 preset_path = std::path::PathBuf::from(preset_path);
+ let backend_exe = std::path::PathBuf::from(backend_exe);
+
+ let Some(lock) = crate::router::read_lock(&preset_path) else {
+ return Ok(None);
+ };
+ let api_key = generate_api_key(format!("router{}", lock.port), api_secret)?;
+
+ match crate::router::try_adopt_router(&preset_path, &backend_exe, models_max, api_key).await {
+ crate::router::AdoptOutcome::Adopted(handle) => {
+ let handle = *handle;
+ let info = RouterInfo {
+ port: handle.port,
+ api_key: handle.api_key.clone(),
+ pid: handle.pid,
+ };
+ state
+ .router_pid
+ .store(handle.pid, std::sync::atomic::Ordering::SeqCst);
+ *guard = Some(handle);
+
+ // The SSE subscriber is a plain HTTP client, so it reattaches to an
+ // adopted router exactly as it would to one we spawned.
+ let watcher =
+ spawn_unload_watcher(app_handle.clone(), info.port, info.api_key.clone());
+ *state.unload_watcher.lock().await = Some(watcher);
+
+ Ok(Some(info))
+ }
+ crate::router::AdoptOutcome::NothingToAdopt => Ok(None),
+ crate::router::AdoptOutcome::Killed(reason) => {
+ log::info!("Router not adopted ({}); caller will spawn a fresh one", reason);
+ Ok(None)
+ }
+ }
+}
+
async fn stop_unload_watcher(state: &LlamacppState) {
if let Some(handle) = state.unload_watcher.lock().await.take() {
handle.abort();
@@ -933,9 +993,59 @@ pub async fn reload_router_models<R: Runtime>(
resp.status().as_u16()
));
}
+
+ // The process is now running the regenerated preset, so the hash recorded
+ // at spawn no longer describes it.
+ let state: State<Arc<LlamacppState>> = app_handle.state();
+ let preset_path = state
+ .router
+ .lock()
+ .await
+ .as_ref()
+ .map(|h| h.preset_path.clone());
+ if let Some(path) = preset_path {
+ crate::router::refresh_lock_preset_hash(&path);
+ }
Ok(())
}
+/// Probe `GET /health`. With `port`/`api_key` omitted, targets the router this
+/// process owns; supplying them probes an arbitrary endpoint (used to decide
+/// whether a router surviving a UI crash is adoptable). Never errors -- an
+/// unreachable or non-200 endpoint is simply not healthy.
+///
+/// The short timeout is deliberate: `http_client()`'s 600s budget is sized for
+/// inference, but a health gate must fail fast enough to roll back.
+#[tauri::command]
+pub async fn router_health<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ port: Option<u16>,
+ api_key: Option<String>,
+) -> Result<bool, String> {
+ let (port, api_key) = match (port, api_key) {
+ (Some(p), Some(k)) => (p, k),
+ _ => match router_endpoint(&app_handle).await {
+ Ok((p, k, _)) => (p, k),
+ Err(_) => return Ok(false),
+ },
+ };
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(ROUTER_HEALTH_TIMEOUT_SECS))
+ .build()
+ {
+ Ok(c) => c,
+ Err(_) => return Ok(false),
+ };
+ let url = format!("http://127.0.0.1:{}/health", port);
+ match client.get(&url).bearer_auth(&api_key).send().await {
+ Ok(resp) => Ok(resp.status().is_success()),
+ Err(e) => {
+ log::debug!("router health probe on port {} failed: {}", port, e);
+ Ok(false)
+ }
+ }
+}
+
/// Best-effort idle check; returns `Ok(true)` on any error so callers
/// never block on a transient `/slots` failure.
#[tauri::command]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs
index 1058e4ca9..82027700f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs
@@ -137,7 +137,7 @@ pub async fn is_model_supported(
.sum::<u64>(),
};
- log::info!("Total VRAM reported/calculated (in bytes): {}", &total_vram);
+ log::info!("Total VRAM reported/calculated (in bytes): {}", total_vram);
let usable_vram = total_vram.saturating_sub(RESERVE_BYTES);
@@ -146,11 +146,11 @@ pub async fn is_model_supported(
} else {
usable_vram
};
- log::info!("System RAM: {} bytes", &total_system_memory);
- log::info!("Total VRAM: {} bytes", &total_vram);
- log::info!("Usable total memory: {} bytes", &usable_total_memory);
- log::info!("Usable VRAM: {} bytes", &usable_vram);
- log::info!("Required: {} bytes", &total_required);
+ log::info!("System RAM: {} bytes", total_system_memory);
+ log::info!("Total VRAM: {} bytes", total_vram);
+ log::info!("Usable total memory: {} bytes", usable_total_memory);
+ log::info!("Usable VRAM: {} bytes", usable_vram);
+ log::info!("Required: {} bytes", total_required);
// Check if model fits in total memory at all (this is the hard limit)
if total_required > usable_total_memory {
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 83b19c45a..347510301 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -33,6 +33,10 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
commands::get_router_info,
commands::reload_router_models,
commands::router_slots_idle,
+ commands::router_health,
+ commands::adopt_router,
+ backend::fetch_backend_checksums,
+ backend::verify_file_sha512,
commands::get_devices,
commands::generate_api_key,
commands::ensure_session_ready,
@@ -69,3 +73,62 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
})
.build()
}
+
+#[cfg(test)]
+mod permission_tests {
+ /// A command reaches the frontend only if it is BOTH in `generate_handler!`
+ /// and in `build.rs`'s `COMMANDS` (which generates its permission). Missing
+ /// the latter compiles and tests clean, then fails at runtime with
+ /// "not allowed. Command not found" -- invisible to any suite that mocks
+ /// `invoke`. Keep the two lists in lockstep.
+ fn names_between<'a>(src: &'a str, start: &str, end: &str) -> Vec<&'a str> {
+ let body = src
+ .split_once(start)
+ .and_then(|(_, rest)| rest.split_once(end))
+ .map(|(body, _)| body)
+ .unwrap_or_else(|| panic!("could not locate {start} .. {end}"));
+ body.lines()
+ .map(|l| l.trim().trim_end_matches(',').trim_matches('"'))
+ .filter(|l| !l.is_empty() && !l.starts_with("//") && !l.starts_with('#'))
+ .map(|l| l.rsplit("::").next().unwrap_or(l))
+ .collect()
+ }
+
+ #[test]
+ fn every_registered_command_has_a_permission() {
+ let handlers = names_between(
+ include_str!("lib.rs"),
+ "tauri::generate_handler![",
+ "])",
+ );
+ let declared = names_between(include_str!("../build.rs"), "COMMANDS: &[&str] = &[", "];");
+
+ let missing: Vec<_> = handlers
+ .iter()
+ .filter(|c| !declared.contains(c))
+ .collect();
+ assert!(
+ missing.is_empty(),
+ "commands registered but absent from build.rs COMMANDS (they will \
+ fail at runtime as \"not allowed\"): {missing:?}"
+ );
+ }
+
+ #[test]
+ fn every_permission_is_in_the_default_set() {
+ let declared = names_between(include_str!("../build.rs"), "COMMANDS: &[&str] = &[", "];");
+ let default_toml = include_str!("../permissions/default.toml");
+
+ let missing: Vec<_> = declared
+ .iter()
+ .filter(|c| {
+ let permission = format!("allow-{}", c.replace('_', "-"));
+ !default_toml.contains(&permission)
+ })
+ .collect();
+ assert!(
+ missing.is_empty(),
+ "commands missing an allow-* entry in permissions/default.toml: {missing:?}"
+ );
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
index 0eec9abef..23c47b11f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
@@ -91,11 +91,349 @@ use jan_utils::{
};
/// A handle to a running router-mode `llama-server` process.
+///
+/// `child` is `None` for a router adopted after a UI crash: we inherit the
+/// process but not its pipes, so readiness parsing, the OOM/backend-error
+/// callback, and log streaming are unavailable until the next restart.
+/// Termination falls back to the PID-based path.
pub struct RouterHandle {
- pub child: Child,
+ pub child: Option<Child>,
pub port: u16,
pub api_key: String,
pub pid: u32,
+ /// Kept so the stop paths can clear the lock file that sits beside it.
+ pub preset_path: PathBuf,
+ /// This run's own log, removed on a deliberate stop.
+ pub log_path: PathBuf,
+}
+
+/// On-disk record of a spawned router, written next to the preset so a
+/// relaunched UI can find a process its in-memory state knows nothing about.
+///
+/// `start_time` is the pid-reuse guard: a recycled PID belongs to a process
+/// that started later, so a mismatch means our router is gone. `backend_exe`
+/// and `preset_hash` decide adoptability -- a router running a different
+/// binary or a stale preset is killed rather than adopted.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct RouterLock {
+ pub pid: u32,
+ pub port: u16,
+ pub start_time: u64,
+ pub backend_exe: String,
+ pub preset_hash: String,
+ /// An argv flag rather than a preset entry, so the preset hash cannot
+ /// catch a change to it.
+ pub models_max: u32,
+ /// So an adopted router can clean up the log it was actually started with.
+ #[serde(default)]
+ pub log_path: String,
+}
+
+pub const ROUTER_LOCK_FILENAME: &str = "router.lock.json";
+/// One log per router run, in the app's managed `logs/` folder beside
+/// `app.log`. It must stay a file of its own -- llama.cpp opens it with mode
+/// "w", so sharing `app.log` would truncate Jan's own log on every spawn.
+///
+/// The token is the port rather than the child's pid: `--log-file` has to be
+/// in argv before the process exists, and renaming afterwards is not an option
+/// because llama.cpp holds the handle open (which makes `rename` fail outright
+/// on Windows). The port is known at that point and matches the lock file, so
+/// a log is easy to tie back to a run. Ports are recycled across runs, so the
+/// newest log is chosen by mtime, never by name.
+pub const ROUTER_LOG_PREFIX: &str = "router-";
+pub const ROUTER_LOG_SUFFIX: &str = ".log";
+
+/// Cap for a log we retain after a crash. A run that never restarts cannot be
+/// truncated while its process holds the file open, so this applies only to
+/// logs left behind by a process that has already exited.
+const MAX_RETAINED_LOG_BYTES: u64 = 16 * 1024 * 1024;
+
+fn new_log_path(log_dir: &Path, port: u16) -> PathBuf {
+ log_dir.join(format!("{}{}{}", ROUTER_LOG_PREFIX, port, ROUTER_LOG_SUFFIX))
+}
+
+fn is_router_log(name: &str) -> bool {
+ name.starts_with(ROUTER_LOG_PREFIX) && name.ends_with(ROUTER_LOG_SUFFIX)
+}
+
+/// Called only when the router is shut down deliberately. A clean stop has
+/// nothing to diagnose, so this run's log goes; a crash never reaches here, so
+/// its log survives for the next session to inspect.
+///
+/// One log is always kept back -- the newest of whatever remains -- so repeated
+/// crashes cannot accumulate, and a user who exits cleanly after a crash still
+/// has the crash to look at.
+fn cleanup_logs(own_log: &Path) {
+ if let Err(e) = std::fs::remove_file(own_log) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ log::warn!("Could not remove router log {:?}: {}", own_log, e);
+ }
+ }
+
+ let Some(dir) = own_log.parent() else { return };
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return;
+ };
+
+ let mut logs: Vec<PathBuf> = entries
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| {
+ p.file_name()
+ .and_then(|n| n.to_str())
+ .map(is_router_log)
+ .unwrap_or(false)
+ })
+ .collect();
+
+ if logs.len() <= 1 {
+ if let Some(kept) = logs.pop() {
+ cap_retained_log(&kept);
+ }
+ return;
+ }
+
+ // By mtime, not name: a port-named log says nothing about when it ran, and
+ // ports are recycled.
+ logs.sort_by_key(|p| {
+ std::fs::metadata(p)
+ .and_then(|m| m.modified())
+ .unwrap_or(std::time::UNIX_EPOCH)
+ });
+ let kept = logs.pop();
+ for stale in logs {
+ if let Err(e) = std::fs::remove_file(&stale) {
+ log::warn!("Could not remove stale router log {:?}: {}", stale, e);
+ }
+ }
+ if let Some(kept) = kept {
+ log::info!("Retained router log from a previous run: {:?}", kept);
+ cap_retained_log(&kept);
+ }
+}
+
+/// Keep the tail: a crash signature is written just before the process dies,
+/// so the end is the part worth having.
+fn cap_retained_log(path: &Path) {
+ let Ok(meta) = std::fs::metadata(path) else {
+ return;
+ };
+ if meta.len() <= MAX_RETAINED_LOG_BYTES {
+ return;
+ }
+ let tmp = path.with_extension("log.tmp");
+ match keep_log_tail(path, &tmp, MAX_RETAINED_LOG_BYTES) {
+ Ok(()) => {
+ if let Err(e) = std::fs::rename(&tmp, path) {
+ log::warn!("Could not replace oversized router log: {}", e);
+ let _ = std::fs::remove_file(&tmp);
+ } else {
+ log::info!(
+ "Router log {:?} was {} bytes; kept the last {}",
+ path,
+ meta.len(),
+ MAX_RETAINED_LOG_BYTES
+ );
+ }
+ }
+ Err(e) => log::warn!("Could not cap oversized router log: {}", e),
+ }
+}
+
+fn keep_log_tail(src: &Path, dst: &Path, bytes: u64) -> std::io::Result<()> {
+ use std::io::{Read, Seek, SeekFrom, Write};
+
+ let mut input = std::fs::File::open(src)?;
+ let len = input.metadata()?.len();
+ input.seek(SeekFrom::Start(len.saturating_sub(bytes)))?;
+
+ let mut output = std::fs::File::create(dst)?;
+ let mut buf = vec![0u8; 1024 * 1024];
+ loop {
+ let n = input.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ output.write_all(&buf[..n])?;
+ }
+ output.flush()
+}
+
+fn lock_path_for(preset_path: &Path) -> PathBuf {
+ preset_path
+ .parent()
+ .unwrap_or_else(|| Path::new("."))
+ .join(ROUTER_LOCK_FILENAME)
+}
+
+pub fn hash_preset(preset_path: &Path) -> String {
+ match std::fs::read(preset_path) {
+ Ok(bytes) => {
+ use sha2::{Digest, Sha256};
+ let mut hasher = Sha256::new();
+ hasher.update(&bytes);
+ format!("{:x}", hasher.finalize())
+ }
+ Err(e) => {
+ log::warn!("hash_preset: cannot read {:?}: {}", preset_path, e);
+ String::new()
+ }
+ }
+}
+
+fn process_start_time(pid: u32) -> Option<u64> {
+ let mut sys = System::new();
+ sys.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid)]), true);
+ sys.process(Pid::from_u32(pid)).map(|p| p.start_time())
+}
+
+fn write_lock(preset_path: &Path, lock: &RouterLock) {
+ let path = lock_path_for(preset_path);
+ match serde_json::to_vec_pretty(lock) {
+ Ok(bytes) => {
+ if let Err(e) = std::fs::write(&path, bytes) {
+ log::warn!("Failed to write router lock {:?}: {}", path, e);
+ }
+ }
+ Err(e) => log::warn!("Failed to serialize router lock: {}", e),
+ }
+}
+
+pub fn remove_lock(preset_path: &Path) {
+ let path = lock_path_for(preset_path);
+ if let Err(e) = std::fs::remove_file(&path) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ log::warn!("Failed to remove router lock {:?}: {}", path, e);
+ }
+ }
+}
+
+pub fn read_lock(preset_path: &Path) -> Option<RouterLock> {
+ let path = lock_path_for(preset_path);
+ let bytes = std::fs::read(&path).ok()?;
+ match serde_json::from_slice::<RouterLock>(&bytes) {
+ Ok(l) => Some(l),
+ Err(e) => {
+ log::warn!("Discarding unreadable router lock {:?}: {}", path, e);
+ let _ = std::fs::remove_file(&path);
+ None
+ }
+ }
+}
+
+/// Re-record the preset hash for a router that hot-reloaded its preset.
+///
+/// A live reload (`GET /models?reload=1`) applies a new preset without
+/// respawning, so the hash captured at spawn goes stale while the running
+/// process is in fact up to date. Left alone, the next adoption attempt would
+/// read that stale hash, conclude the preset changed, and kill a healthy
+/// router.
+pub fn refresh_lock_preset_hash(preset_path: &Path) {
+ let Some(mut lock) = read_lock(preset_path) else {
+ return;
+ };
+ let hash = hash_preset(preset_path);
+ if lock.preset_hash == hash {
+ return;
+ }
+ lock.preset_hash = hash;
+ write_lock(preset_path, &lock);
+ log::debug!("Router lock preset hash refreshed after a live reload");
+}
+
+/// Outcome of inspecting a router that outlived its UI.
+pub enum AdoptOutcome {
+ /// Same binary, same preset, answering `/health` -- reuse it.
+ Adopted(Box<RouterHandle>),
+ /// Nothing usable was running (no lock, dead PID, or PID reused).
+ NothingToAdopt,
+ /// A router was running but could not be reused; it has been killed and
+ /// the caller should spawn a fresh one.
+ Killed(&'static str),
+}
+
+/// Decide what to do with a router recorded in the lock file. Never spawns.
+///
+/// The health probe is what makes adoption safe: a process that is alive but
+/// wedged is killed rather than inherited.
+pub async fn try_adopt_router(
+ preset_path: &Path,
+ backend_exe: &Path,
+ models_max: u32,
+ api_key: String,
+) -> AdoptOutcome {
+ let Some(lock) = read_lock(preset_path) else {
+ return AdoptOutcome::NothingToAdopt;
+ };
+
+ let Some(start_time) = process_start_time(lock.pid) else {
+ log::info!("Router lock pid {} is not running; discarding", lock.pid);
+ remove_lock(preset_path);
+ return AdoptOutcome::NothingToAdopt;
+ };
+ if start_time != lock.start_time {
+ log::info!(
+ "Router lock pid {} was reused (start_time {} != {}); discarding",
+ lock.pid,
+ start_time,
+ lock.start_time
+ );
+ remove_lock(preset_path);
+ return AdoptOutcome::NothingToAdopt;
+ }
+
+ let kill = |reason: &'static str| {
+ log::info!(
+ "Killing unadoptable router pid {} ({}); a fresh one will be spawned",
+ lock.pid,
+ reason
+ );
+ force_kill_router_tree_by_pid(lock.pid);
+ remove_lock(preset_path);
+ AdoptOutcome::Killed(reason)
+ };
+
+ if lock.backend_exe != backend_exe.to_string_lossy() {
+ return kill("backend changed");
+ }
+ if lock.preset_hash != hash_preset(preset_path) {
+ return kill("preset changed");
+ }
+ if lock.models_max != models_max {
+ return kill("models_max changed");
+ }
+
+ if !probe_health(lock.port, &api_key).await {
+ return kill("failed health check");
+ }
+
+ log::info!(
+ "Adopted router pid {} on port {} (no stdout/stderr pipes; logs unavailable until restart)",
+ lock.pid,
+ lock.port
+ );
+ AdoptOutcome::Adopted(Box::new(RouterHandle {
+ child: None,
+ port: lock.port,
+ api_key,
+ pid: lock.pid,
+ preset_path: preset_path.to_path_buf(),
+ log_path: PathBuf::from(&lock.log_path),
+ }))
+}
+
+async fn probe_health(port: u16, api_key: &str) -> bool {
+ let Ok(client) = reqwest::Client::builder()
+ .timeout(Duration::from_secs(5))
+ .build()
+ else {
+ return false;
+ };
+ let url = format!("http://127.0.0.1:{}/health", port);
+ matches!(
+ client.get(&url).bearer_auth(api_key).send().await,
+ Ok(r) if r.status().is_success()
+ )
}
/// Build the argv for router mode. Pure / unit-testable.
@@ -115,6 +453,7 @@ pub fn router_args(
preset_path: &Path,
port: u16,
models_max: u32,
+ log_path: Option<&Path>,
default_args: &[String],
) -> Vec<String> {
let mut args: Vec<String> = vec![
@@ -127,6 +466,13 @@ pub fn router_args(
"--port".to_string(),
port.to_string(),
];
+ // Written in addition to stdout/stderr, not instead of them, so the pipe
+ // readers below are unaffected. This is the only diagnostic an adopted
+ // router leaves behind, since adoption inherits no pipes.
+ if let Some(path) = log_path {
+ args.push("--log-file".to_string());
+ args.push(path.to_string_lossy().to_string());
+ }
// Web-UI disable flag (`--no-webui` pre-b9222, `--no-ui` from b9222) is
// appended by the TS caller via `default_args` because the spelling
// depends on the backend build number.
@@ -150,6 +496,7 @@ fn with_api_key_env(mut envs: HashMap<String, String>, api_key: &str) -> HashMap
pub async fn start_router(
backend_exe: PathBuf,
preset_path: PathBuf,
+ log_dir: PathBuf,
port: u16,
api_key: String,
models_max: u32,
@@ -169,7 +516,11 @@ pub async fn start_router(
// `router_args`'s doc comment).
let envs = with_api_key_env(envs, &api_key);
- let args = router_args(&preset_path, port, models_max, &default_args);
+ if let Err(e) = std::fs::create_dir_all(&log_dir) {
+ log::warn!("Could not create router log directory {:?}: {}", log_dir, e);
+ }
+ let log_path = new_log_path(&log_dir, port);
+ let args = router_args(&preset_path, port, models_max, Some(&log_path), &default_args);
log::info!("Router argv: {:?}", args);
// Resolve readiness timeout (seconds). Match existing convention by
@@ -367,11 +718,27 @@ pub async fn start_router(
}
let pid = child.id().unwrap_or(0);
+ write_lock(
+ &preset_path,
+ &RouterLock {
+ pid,
+ port,
+ // A PID we just spawned but cannot find is not worth recording:
+ // without a start_time the reuse guard cannot fire.
+ start_time: process_start_time(pid).unwrap_or(0),
+ backend_exe: backend_exe.to_string_lossy().to_string(),
+ preset_hash: hash_preset(&preset_path),
+ models_max,
+ log_path: log_path.to_string_lossy().to_string(),
+ },
+ );
Ok(RouterHandle {
- child,
+ child: Some(child),
port,
api_key,
pid,
+ preset_path,
+ log_path,
})
}
@@ -403,7 +770,7 @@ pub async fn try_graceful_stop_router(
Ok(c) => c,
Err(e) => {
log::warn!("try_graceful_stop_router: failed to build http client: {}; terminating directly", e);
- terminate_router_process(&mut handle.child).await;
+ terminate_router_process(&mut handle).await;
return Ok(());
}
};
@@ -415,7 +782,7 @@ pub async fn try_graceful_stop_router(
"try_graceful_stop_router: GET /models failed ({}); router likely already down, terminating",
e
);
- terminate_router_process(&mut handle.child).await;
+ terminate_router_process(&mut handle).await;
return Ok(());
}
};
@@ -477,7 +844,7 @@ pub async fn try_graceful_stop_router(
tokio::time::sleep(Duration::from_millis(150).min(remaining)).await;
}
- terminate_router_process(&mut handle.child).await;
+ terminate_router_process(&mut handle).await;
Ok(())
}
@@ -566,7 +933,15 @@ async fn list_processing_models(
busy
}
-async fn terminate_router_process(child: &mut Child) {
+/// Terminate the router, using the owned `Child` when we have one and falling
+/// back to a PID-based tree kill for an adopted process.
+async fn terminate_router_process(handle: &mut RouterHandle) {
+ remove_lock(&handle.preset_path);
+ cleanup_logs(&handle.log_path);
+ let Some(child) = handle.child.as_mut() else {
+ force_kill_router_tree_by_pid(handle.pid);
+ return;
+ };
#[cfg(unix)]
{
crate::process::graceful_terminate_process(child).await;
@@ -612,6 +987,8 @@ pub fn force_kill_router_tree_by_pid(router_pid: u32) {
/// Router is killed before children so it can't spawn new ones mid-sweep.
pub async fn force_kill_router_tree(mut handle: RouterHandle) {
+ remove_lock(&handle.preset_path);
+ cleanup_logs(&handle.log_path);
let router_pid = handle.pid;
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
@@ -642,7 +1019,9 @@ pub async fn force_kill_router_tree(mut handle: RouterHandle) {
}
}
- let _ = handle.child.wait().await;
+ if let Some(child) = handle.child.as_mut() {
+ let _ = child.wait().await;
+ }
}
#[cfg(test)]
@@ -650,10 +1029,292 @@ mod tests {
use super::*;
use std::path::PathBuf;
+ fn preset_in(dir: &Path, body: &str) -> PathBuf {
+ let p = dir.join("router.preset.ini");
+ std::fs::write(&p, body).unwrap();
+ p
+ }
+
+ fn lock_for(preset: &Path, pid: u32, models_max: u32) -> RouterLock {
+ RouterLock {
+ pid,
+ port: 1337,
+ start_time: process_start_time(pid).unwrap_or(0),
+ backend_exe: "/backends/llama-server".to_string(),
+ preset_hash: hash_preset(preset),
+ models_max,
+ log_path: String::new(),
+ }
+ }
+
+ #[test]
+ fn lock_roundtrips_next_to_the_preset() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ let lock = lock_for(&preset, 4242, 2);
+
+ write_lock(&preset, &lock);
+ assert!(dir.path().join(ROUTER_LOCK_FILENAME).exists());
+
+ let read = read_lock(&preset).expect("lock should be readable");
+ assert_eq!(read.pid, 4242);
+ assert_eq!(read.port, 1337);
+ assert_eq!(read.models_max, 2);
+
+ remove_lock(&preset);
+ assert!(read_lock(&preset).is_none());
+ }
+
+ #[test]
+ fn corrupt_lock_is_discarded_not_returned() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ std::fs::write(dir.path().join(ROUTER_LOCK_FILENAME), b"{not json").unwrap();
+
+ assert!(read_lock(&preset).is_none());
+ // A lock we cannot parse must not survive to be retried forever.
+ assert!(!dir.path().join(ROUTER_LOCK_FILENAME).exists());
+ }
+
+ #[test]
+ fn removing_an_absent_lock_is_not_an_error() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ remove_lock(&preset);
+ remove_lock(&preset);
+ }
+
+ #[test]
+ fn preset_hash_tracks_content() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");
+ let before = hash_preset(&preset);
+
+ std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();
+ assert_ne!(before, hash_preset(&preset));
+
+ std::fs::write(&preset, "[*]\nctx_size=4096\n").unwrap();
+ assert_eq!(before, hash_preset(&preset));
+ }
+
+ #[test]
+ fn missing_preset_hashes_empty_rather_than_panicking() {
+ let dir = tempfile::tempdir().unwrap();
+ assert_eq!(hash_preset(&dir.path().join("absent.ini")), "");
+ }
+
+ #[test]
+ fn refreshing_the_lock_hash_survives_a_hot_reload() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");
+ write_lock(&preset, &lock_for(&preset, 4242, 1));
+
+ // A live reload rewrites the preset without respawning.
+ std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();
+ assert_ne!(read_lock(&preset).unwrap().preset_hash, hash_preset(&preset));
+
+ refresh_lock_preset_hash(&preset);
+
+ let lock = read_lock(&preset).unwrap();
+ assert_eq!(lock.preset_hash, hash_preset(&preset));
+ // Everything else about the run is untouched.
+ assert_eq!(lock.pid, 4242);
+ assert_eq!(lock.port, 1337);
+ }
+
+ // Uses a throwaway child rather than our own pid: reaching the health
+ // probe means reaching the kill branch, and force_kill_router_tree_by_pid
+ // would take the test runner with it.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_hot_reloaded_router_is_still_adoptable() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");
+
+ let mut child = std::process::Command::new("sleep")
+ .arg("30")
+ .spawn()
+ .expect("spawn a stand-in process");
+ let mut lock = lock_for(&preset, child.id(), 1);
+ lock.backend_exe = "/backends/llama-server".to_string();
+ write_lock(&preset, &lock);
+
+ std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();
+ refresh_lock_preset_hash(&preset);
+
+ // Reaches the health probe rather than being killed for a stale hash.
+ // Nothing listens on the recorded port, so it fails there instead.
+ let outcome = try_adopt_router(
+ &preset,
+ Path::new("/backends/llama-server"),
+ 1,
+ "k".into(),
+ )
+ .await;
+ let _ = child.wait();
+ assert!(
+ matches!(outcome, AdoptOutcome::Killed("failed health check")),
+ "should not be killed for a preset change after the hash is refreshed"
+ );
+ }
+
+ #[tokio::test]
+ async fn no_lock_means_nothing_to_adopt() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ let outcome = try_adopt_router(
+ &preset,
+ Path::new("/backends/llama-server"),
+ 1,
+ "k".into(),
+ )
+ .await;
+ assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));
+ }
+
+ #[tokio::test]
+ async fn dead_pid_discards_the_lock() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ // Never-valid PID: no process can match, so this exercises the
+ // liveness check without depending on a real one.
+ let mut lock = lock_for(&preset, u32::MAX, 1);
+ lock.start_time = 1;
+ write_lock(&preset, &lock);
+
+ let outcome = try_adopt_router(
+ &preset,
+ Path::new("/backends/llama-server"),
+ 1,
+ "k".into(),
+ )
+ .await;
+ assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));
+ assert!(read_lock(&preset).is_none());
+ }
+
+ #[tokio::test]
+ async fn pid_reuse_is_caught_by_start_time() {
+ let dir = tempfile::tempdir().unwrap();
+ let preset = preset_in(dir.path(), "[*]\n");
+ let mut lock = lock_for(&preset, std::process::id(), 1);
+ // Our own PID is alive, but this start_time cannot be ours.
+ lock.start_time = lock.start_time.wrapping_add(9999);
+ write_lock(&preset, &lock);
+
+ let outcome = try_adopt_router(
+ &preset,
+ Path::new("/backends/llama-server"),
+ 1,
+ "k".into(),
+ )
+ .await;
+ assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));
+ assert!(read_lock(&preset).is_none());
+ }
+
+ #[test]
+ fn router_args_adds_log_file_only_when_asked() {
+ let preset = PathBuf::from("/tmp/router.preset.ini");
+ assert!(!router_args(&preset, 1337, 1, None, &[])
+ .iter()
+ .any(|a| a == "--log-file"));
+
+ let args = router_args(&preset, 1337, 1, Some(Path::new("/tmp/r.log")), &[]);
+ let i = args.iter().position(|a| a == "--log-file").unwrap();
+ assert_eq!(args[i + 1], "/tmp/r.log");
+ }
+
+ #[test]
+ fn router_log_never_shares_the_app_log_file() {
+ // llama.cpp opens the log with mode "w"; sharing app.log would
+ // truncate Jan's own log on every spawn.
+ let path = new_log_path(Path::new("/logs"), 1337);
+ assert_eq!(path.file_name().unwrap(), "router-1337.log");
+ assert_ne!(path.file_name().unwrap(), "app.log");
+ }
+
+ fn write_log(dir: &Path, port: u16, body: &[u8]) -> PathBuf {
+ let p = new_log_path(dir, port);
+ std::fs::write(&p, body).unwrap();
+ p
+ }
+
+ #[test]
+ fn a_clean_stop_removes_its_own_log() {
+ let dir = tempfile::tempdir().unwrap();
+ let own = write_log(dir.path(), 1337, b"clean run");
+
+ cleanup_logs(&own);
+
+ assert!(!own.exists());
+ }
+
+ #[test]
+ fn a_crashed_run_leaves_its_log_for_the_next_clean_stop() {
+ let dir = tempfile::tempdir().unwrap();
+ // The crashed run never reached cleanup, so its log is still here.
+ let crashed = write_log(dir.path(), 4242, b"CUDA error: out of memory");
+ let own = write_log(dir.path(), 1337, b"clean run");
+
+ cleanup_logs(&own);
+
+ assert!(!own.exists());
+ assert!(crashed.exists(), "crash evidence must survive a clean stop");
+ }
+
+ #[test]
+ fn repeated_crashes_keep_only_the_most_recent_log() {
+ let dir = tempfile::tempdir().unwrap();
+ let old = write_log(dir.path(), 1111, b"first crash");
+ let newer = write_log(dir.path(), 2222, b"second crash");
+ // Ports say nothing about ordering, so age is taken from mtime.
+ let long_ago = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
+ let f = std::fs::File::options().write(true).open(&old).unwrap();
+ f.set_times(std::fs::FileTimes::new().set_modified(long_ago))
+ .unwrap();
+ drop(f);
+
+ let own = write_log(dir.path(), 3333, b"clean run");
+ cleanup_logs(&own);
+
+ assert!(!own.exists());
+ assert!(!old.exists(), "the older crash log should be swept");
+ assert!(newer.exists(), "the newest crash log is kept");
+ }
+
+ #[test]
+ fn a_retained_oversized_log_is_capped_to_its_tail() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut body = vec![b'x'; (MAX_RETAINED_LOG_BYTES + 4096) as usize];
+ body.extend_from_slice(b"CUDA error: out of memory");
+ let crashed = write_log(dir.path(), 4242, &body);
+ let own = write_log(dir.path(), 1337, b"clean run");
+
+ cleanup_logs(&own);
+
+ let kept = std::fs::read(&crashed).unwrap();
+ assert_eq!(kept.len() as u64, MAX_RETAINED_LOG_BYTES);
+ // The crash signature is at the end, so the tail is what must survive.
+ assert!(kept.ends_with(b"CUDA error: out of memory"));
+ }
+
+ #[test]
+ fn cleanup_ignores_files_that_are_not_router_logs() {
+ let dir = tempfile::tempdir().unwrap();
+ let app_log = dir.path().join("app.log");
+ std::fs::write(&app_log, b"jan's own log").unwrap();
+ let own = write_log(dir.path(), 1337, b"clean run");
+
+ cleanup_logs(&own);
+
+ assert_eq!(std::fs::read(&app_log).unwrap(), b"jan's own log");
+ }
+
#[test]
fn router_args_contains_required_flags() {
let preset = PathBuf::from("/tmp/preset.ini");
- let args = router_args(&preset, 1337, 4, &[]);
+ let args = router_args(&preset, 1337, 4, None, &[]);
// Required flags present
let joined = args.join(" ");
@@ -723,7 +1384,7 @@ mod tests {
// visible to any other process on the machine (ps/Task Manager) and
// gets logged verbatim at startup.
let preset = PathBuf::from("/tmp/preset.ini");
- let args = router_args(&preset, 1337, 4, &[]);
+ let args = router_args(&preset, 1337, 4, None, &[]);
assert!(!args.iter().any(|a| a == "--api-key"));
assert!(!args.join(" ").to_lowercase().contains("api-key"));
}
@@ -732,7 +1393,7 @@ mod tests {
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, 2, &extras);
+ let args = router_args(&preset, 8080, 2, None, &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();
@@ -743,7 +1404,7 @@ mod tests {
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, 0, &[]);
+ let args = router_args(&preset, 8080, 0, None, &[]);
let joined = args.join(" ");
assert!(joined.contains("--models-max 0"));
}
diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rs
index a89ba5d0d..156690549 100644
--- a/src-tauri/src/bin/jan-cli.rs
+++ b/src-tauri/src/bin/jan-cli.rs
@@ -1031,9 +1031,12 @@ async fn ensure_router_and_load(
.entry("LLAMA_ARG_TIMEOUT".to_string())
.or_insert_with(|| timeout.to_string());
+ let log_dir = cli_get_data_folder().join("logs");
+
let handle = llamacpp_router::start_router(
std::path::PathBuf::from(bin_path),
preset_path,
+ log_dir,
port,
router_api_key,
0,
diff --git a/web-app/src/containers/BackendUpdateHistory.tsx b/web-app/src/containers/BackendUpdateHistory.tsx
new file mode 100644
index 000000000..1c1ffd3b6
--- /dev/null
+++ b/web-app/src/containers/BackendUpdateHistory.tsx
@@ -0,0 +1,120 @@
+import { useCallback, useEffect, useState } from 'react'
+import { ExtensionManager } from '@/lib/extension'
+import { Button } from '@/components/ui/button'
+import { useTranslation } from '@/i18n'
+import { cn } from '@/lib/utils'
+
+export type BackendUpdateRecord = {
+ timestamp: string
+ from: string
+ to: string
+ outcome: 'updated' | 'rolled-back' | 'rollback-failed' | 'failed'
+ durationMs: number
+ error?: string
+}
+
+type HistoryProvider = {
+ getBackendUpdateHistory: () => Promise<BackendUpdateRecord[]>
+}
+
+function getHistoryProvider(): HistoryProvider | null {
+ const extension = ExtensionManager.getInstance().getByName(
+ 'llamacpp-extension'
+ )
+ return extension && 'getBackendUpdateHistory' in extension
+ ? (extension as unknown as HistoryProvider)
+ : null
+}
+
+const OUTCOME_LABELS: Record<BackendUpdateRecord['outcome'], string> = {
+ updated: 'providers:backendHistoryUpdated',
+ 'rolled-back': 'providers:backendHistoryRolledBack',
+ 'rollback-failed': 'providers:backendHistoryRollbackFailed',
+ failed: 'providers:backendHistoryFailed',
+}
+
+export function BackendUpdateHistory() {
+ const { t } = useTranslation()
+ const [expanded, setExpanded] = useState(false)
+ const [records, setRecords] = useState<BackendUpdateRecord[] | null>(null)
+
+ const load = useCallback(async () => {
+ const provider = getHistoryProvider()
+ if (!provider) {
+ setRecords([])
+ return
+ }
+ try {
+ setRecords(await provider.getBackendUpdateHistory())
+ } catch {
+ setRecords([])
+ }
+ }, [])
+
+ useEffect(() => {
+ if (expanded) void load()
+ }, [expanded, load])
+
+ return (
+ <div className="mt-2 w-full">
+ <Button
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-muted-foreground"
+ onClick={() => setExpanded((v) => !v)}
+ >
+ {expanded
+ ? t('providers:backendHistoryHide')
+ : t('providers:backendHistoryShow')}
+ </Button>
+
+ {expanded && (
+ <div className="mt-2 max-h-60 overflow-y-auto rounded-md border border-border">
+ {records === null && (
+ <p className="p-3 text-sm text-muted-foreground">
+ {t('providers:backendHistoryLoading')}
+ </p>
+ )}
+ {records?.length === 0 && (
+ <p className="p-3 text-sm text-muted-foreground">
+ {t('providers:backendHistoryEmpty')}
+ </p>
+ )}
+ {records?.map((record, index) => (
+ <div
+ key={`${record.timestamp}-${index}`}
+ className="border-b border-border p-3 text-sm last:border-b-0"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-medium">
+ {record.from || t('providers:backendHistoryNone')} &rarr;{' '}
+ {record.to}
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 text-xs',
+ record.outcome === 'updated'
+ ? 'text-muted-foreground'
+ : 'text-destructive'
+ )}
+ >
+ {t(OUTCOME_LABELS[record.outcome])}
+ </span>
+ </div>
+ <div className="mt-1 text-xs text-muted-foreground">
+ {new Date(record.timestamp).toLocaleString()}
+ {' · '}
+ {Math.round(record.durationMs / 1000)}s
+ </div>
+ {record.error && (
+ <p className="mt-1 break-words text-xs text-destructive">
+ {record.error}
+ </p>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsx b/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsx
new file mode 100644
index 000000000..953e2bf3e
--- /dev/null
+++ b/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsx
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BackendUpdateHistory } from '../BackendUpdateHistory'
+
+const hoisted = vi.hoisted(() => ({
+ extension: null as Record<string, unknown> | null,
+}))
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: () => ({
+ getByName: () => hoisted.extension,
+ }),
+ },
+}))
+
+vi.mock('@/i18n', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+describe('BackendUpdateHistory', () => {
+ beforeEach(() => {
+ hoisted.extension = null
+ })
+
+ it('only loads the history once expanded', async () => {
+ const getBackendUpdateHistory = vi.fn().mockResolvedValue([])
+ hoisted.extension = { getBackendUpdateHistory }
+
+ render(<BackendUpdateHistory />)
+ expect(getBackendUpdateHistory).not.toHaveBeenCalled()
+
+ await userEvent.click(screen.getByRole('button'))
+
+ await waitFor(() => expect(getBackendUpdateHistory).toHaveBeenCalledTimes(1))
+ expect(
+ screen.getByText('providers:backendHistoryEmpty')
+ ).toBeInTheDocument()
+ })
+
+ it('renders each record with its outcome and error', async () => {
+ hoisted.extension = {
+ getBackendUpdateHistory: vi.fn().mockResolvedValue([
+ {
+ timestamp: '2026-07-28T10:00:00.000Z',
+ from: 'b1000/cpu',
+ to: 'b1100/cpu',
+ outcome: 'rolled-back',
+ durationMs: 4000,
+ error: 'Router failed its health check',
+ },
+ ]),
+ }
+
+ render(<BackendUpdateHistory />)
+ await userEvent.click(screen.getByRole('button'))
+
+ await waitFor(() =>
+ expect(screen.getByText(/b1000\/cpu/)).toBeInTheDocument()
+ )
+ expect(
+ screen.getByText('providers:backendHistoryRolledBack')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText('Router failed its health check')
+ ).toBeInTheDocument()
+ })
+
+ it('degrades to an empty list when the extension is unavailable', async () => {
+ hoisted.extension = null
+
+ render(<BackendUpdateHistory />)
+ await userEvent.click(screen.getByRole('button'))
+
+ await waitFor(() =>
+ expect(
+ screen.getByText('providers:backendHistoryEmpty')
+ ).toBeInTheDocument()
+ )
+ })
+})
diff --git a/web-app/src/containers/dynamicControllerSetting/DropdownControl.tsx b/web-app/src/containers/dynamicControllerSetting/DropdownControl.tsx
index f8691e292..6e09c7388 100644
--- a/web-app/src/containers/dynamicControllerSetting/DropdownControl.tsx
+++ b/web-app/src/containers/dynamicControllerSetting/DropdownControl.tsx
@@ -8,11 +8,18 @@ import {
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { ChevronsUpDown } from 'lucide-react'
+import { useTranslation } from '@/i18n'
// Dropdown component
type DropdownControlProps = {
value: string
- options?: Array<{ value: number | string; name: string }>
+ options?: Array<{
+ value: number | string
+ name: string
+ /** Present on backend versions: already on disk, so selecting it is a
+ * rollback rather than a download. */
+ installed?: boolean
+ }>
recommended?: string
onChange: (value: number | string) => void
}
@@ -22,6 +29,7 @@ export function DropdownControl({
options = [],
onChange,
}: DropdownControlProps) {
+ const { t } = useTranslation()
const isSelected =
options.find((option) => option.value === value)?.name || value
@@ -57,6 +65,11 @@ export function DropdownControl({
)}
>
<span>{option.name}</span>
+ {option.installed && (
+ <span className="ml-2 shrink-0 text-xs text-muted-foreground">
+ {t('providers:backendInstalled')}
+ </span>
+ )}
</DropdownMenuItem>
))}
</DropdownMenuContent>
diff --git a/web-app/src/locales/en/providers.json b/web-app/src/locales/en/providers.json
index 53f92320a..8639ef6e4 100644
--- a/web-app/src/locales/en/providers.json
+++ b/web-app/src/locales/en/providers.json
@@ -6,6 +6,16 @@
"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",
+ "backendInstalled": "Installed",
+ "backendHistoryShow": "Show update history",
+ "backendHistoryHide": "Hide update history",
+ "backendHistoryLoading": "Loading update history...",
+ "backendHistoryEmpty": "No backend updates recorded yet.",
+ "backendHistoryNone": "none",
+ "backendHistoryUpdated": "Updated",
+ "backendHistoryRolledBack": "Rolled back",
+ "backendHistoryRollbackFailed": "Rollback failed",
+ "backendHistoryFailed": "Failed",
"chatModels": "Chat Models",
"embeddingModels": "Embedding Models",
"embeddingModelsDesc": "Used for RAG and vector search. The selected model becomes the default when generating embeddings.",
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 25668e44d..51c88e92e 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -18,6 +18,7 @@ import { DialogDeleteAllModels } from '@/containers/dialogs/DeleteAllModels'
import { FavoriteModelAction } from '@/containers/FavoriteModelAction'
import { route } from '@/constants/routes'
import DeleteProvider from '@/containers/dialogs/DeleteProvider'
+import { BackendUpdateHistory } from '@/containers/BackendUpdateHistory'
import { useServiceHub } from '@/hooks/useServiceHub'
import { Button } from '@/components/ui/button'
import { SecretInput } from '@/components/ui/secret-input'
@@ -1047,6 +1048,7 @@ function ProviderDetail() {
</span>
</Button>
)}
+ <BackendUpdateHistory />
</div>
)}
</>