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(rag): repair embeddings, stop chat-model reloads, and parse more PDFs (#8360)

Akarshan Biswas889c361e6563
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index c4131920e..0303a45f4 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -61,6 +61,7 @@ import {
readGgufMetadata,
isModelSupported,
unloadLlamaModel,
+ reloadRouterModels,
LlamacppConfig,
DownloadItem,
ModelConfig,
@@ -80,6 +81,12 @@ import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'
const EMBEDDING_CHECK_VERSION = 3
const MTP_CHECK_VERSION = 1
+// Upstream build that added the `GET /models?reload=1` diff/reconcile path
+// (llama.cpp #21848). At/above this, a preset change can be hot-applied without
+// restarting the router (unchanged models stay loaded); below it we must do a
+// full process restart.
+const RELOAD_MIN_BUILD = 9023
+
// 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,
@@ -732,6 +739,44 @@ export default class llamacpp_extension extends AIEngine {
)
}
+ /**
+ * Apply a preset change (model added/removed/renamed or a per-model setting)
+ * to the router. On a backend with the reload diff path (b9023+), regenerate
+ * `router.preset.ini` and hot-reload via `GET /models?reload=1` — models whose
+ * preset is unchanged stay loaded, so an embedder import or a settings write no
+ * longer cold-reloads the user's chat model. Falls back to a full restart when
+ * the router isn't running yet, the backend is too old, or the reload fails.
+ */
+ private async refreshRouterPreset(): Promise<void> {
+ if (!(await this.getRouterInfo())) {
+ await this.startRouter() // cold start
+ return
+ }
+
+ const versionBackend = this.config?.version_backend
+ const version = versionBackend?.split('/')[0]
+ const build = version ? parseBuildNumber(version) : null
+ if (build === null || build < RELOAD_MIN_BUILD) {
+ await this.startRouter() // backend predates live reload
+ return
+ }
+
+ const providerPath = await this.getProviderPath()
+ const janDataFolderPath = await getJanDataFolderPath()
+ const supportsMtp = build >= MTP_MIN_BUILD
+ await generatePreset(providerPath, janDataFolderPath, this.config, {
+ supportsMtp,
+ })
+
+ try {
+ await reloadRouterModels()
+ logger.info('Router preset hot-reloaded without restart')
+ } catch (e) {
+ logger.warn('Live router reload failed; falling back to restart:', e)
+ await this.startRouter()
+ }
+ }
+
/**
* Public accessor for downstream consumers. Returns `null` if the router
* hasn't been started successfully yet.
@@ -2327,7 +2372,7 @@ export default class llamacpp_extension extends AIEngine {
// The router's preset still references the old model id until we
// regenerate; without this a `POST /models/load <new-id>` would 404.
try {
- await this.startRouter()
+ await this.refreshRouterPreset()
} catch (e) {
logger.warn(`Router restart after model rename (${modelId} → ${model.id}) failed`, e)
}
@@ -2598,7 +2643,7 @@ export default class llamacpp_extension extends AIEngine {
}
try {
- await this.startRouter()
+ await this.refreshRouterPreset()
} catch (e) {
logger.warn(`Router refresh after import(${modelId}) failed:`, e)
}
@@ -3046,7 +3091,7 @@ export default class llamacpp_extension extends AIEngine {
await fs.rm(modelDir)
try {
- await this.startRouter()
+ await this.refreshRouterPreset()
} catch (e) {
logger.warn(`Router refresh after delete(${modelId}) failed:`, e)
}
@@ -3175,7 +3220,7 @@ export default class llamacpp_extension extends AIEngine {
await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
try {
- await this.startRouter()
+ await this.refreshRouterPreset()
} catch (e) {
logger.warn(`Failed to restart router after MTP update for ${modelId}`, e)
}
@@ -3230,7 +3275,7 @@ export default class llamacpp_extension extends AIEngine {
await invoke<void>('write_yaml', { data: cfg, savePath: configPath })
try {
- await this.startRouter()
+ await this.refreshRouterPreset()
} catch (e) {
logger.warn(
`Failed to restart router after model settings update for ${modelId}`,
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.ts
index c91acadef..6f9d7ec42 100644
--- a/extensions/llamacpp-extension/src/preset.test.ts
+++ b/extensions/llamacpp-extension/src/preset.test.ts
@@ -187,4 +187,52 @@ describe('generatePreset ctx-size default', () => {
const ini = writtenFiles['/p/router.preset.ini']
expect(ini).not.toContain('ctx-size = 8192')
})
+
+ it('honors an explicit ctx_size = 0 as native instead of the 8192 fallback', async () => {
+ setupModel('llama', {})
+ await generatePreset('/p', '/jan', { fit: false, ctx_size: 0 } as any, {
+ supportsMtp: false,
+ })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).toContain('ctx-size = 0')
+ expect(ini).not.toContain('ctx-size = 8192')
+ })
+
+ it('honors a per-model ctx_size = 0 override as native', async () => {
+ setupModel('llama', { ctx_size: 0 })
+ await generatePreset('/p', '/jan', { fit: false, ctx_size: 16384 } as any, {
+ supportsMtp: false,
+ })
+ const ini = writtenFiles['/p/router.preset.ini']
+ // [*] keeps the global, but the per-model section overrides to native.
+ expect(ini).toContain('ctx-size = 16384')
+ expect(ini).toContain('ctx-size = 0')
+ })
+})
+
+describe('generatePreset embedding ctx-size', () => {
+ it('pins embedders to native ctx-size = 0 so they do not inherit the global 8192', async () => {
+ setupModel('minilm', { embedding: true })
+ await generatePreset('/p', '/jan', { fit: false } as any, {
+ supportsMtp: false,
+ })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).toContain('embeddings = true')
+ // global [*] still emits 8192, but the embedder section overrides to native.
+ expect(ini).toContain('ctx-size = 8192')
+ expect(ini).toContain('ctx-size = 0')
+ })
+
+ it('keeps a positive per-model embedder ctx-size instead of forcing native', async () => {
+ setupModel('minilm', { embedding: true, ctx_size: 2048 })
+ await generatePreset('/p', '/jan', { fit: false } as any, {
+ supportsMtp: false,
+ })
+ const ini = writtenFiles['/p/router.preset.ini']
+ expect(ini).toContain('embeddings = true')
+ expect(ini).toContain('ctx-size = 2048')
+ // the embedder section must not additionally emit native 0.
+ const embedderSection = ini.slice(ini.indexOf('[minilm]'))
+ expect(embedderSection).not.toContain('ctx-size = 0')
+ })
})
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index dbeb256b8..64ecf14c2 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -144,13 +144,14 @@ export async function generatePreset(
lines.push(`fit-ctx = ${fitCtxNum}`)
}
// ctx-size: llama.cpp's own default loads the model's full trained context,
- // which can OOM on large-context models. Default to 8192 when the user hasn't
- // set a positive value. Skip entirely when auto-fit is enabled — fit owns
- // context sizing and an explicit ctx-size would override it.
+ // which can OOM on large-context models. Fall back to 8192 only when the
+ // value is unset; an explicit 0 is honored as "native" (load from model).
+ // Skip entirely when auto-fit is enabled — fit owns context sizing and an
+ // explicit ctx-size would override it.
const fitEnabled = config.fit !== false
if (!fitEnabled) {
const ctxSize =
- typeof config.ctx_size === 'number' && config.ctx_size > 0
+ typeof config.ctx_size === 'number' && Number.isFinite(config.ctx_size) && config.ctx_size >= 0
? config.ctx_size
: DEFAULT_CTX_SIZE
lines.push(`ctx-size = ${ctxSize}`)
@@ -345,12 +346,16 @@ export async function generatePreset(
// Per-model overrides — same default-skipping rules as the [*] block.
// ctx-size is skipped when auto-fit is on so fit can size the context.
+ // An explicit 0 overrides the global default with "native" (load from model).
+ let ctxEmitted = false
if (
!fitEnabled &&
typeof mc.ctx_size === 'number' &&
- mc.ctx_size > 0
+ Number.isFinite(mc.ctx_size) &&
+ mc.ctx_size >= 0
) {
lines.push(`ctx-size = ${mc.ctx_size}`)
+ ctxEmitted = true
}
if (typeof mc.n_gpu_layers === 'number' && mc.n_gpu_layers >= 0) {
lines.push(`n-gpu-layers = ${mc.n_gpu_layers}`)
@@ -471,6 +476,13 @@ export async function generatePreset(
if (mc.embedding === true) {
embeddingCount++
lines.push('embeddings = true')
+ // Embedders have a small trained context (e.g. MiniLM = 512). Without an
+ // explicit override they inherit the global [*] ctx-size (8192), which
+ // exceeds n_ctx_train and fails to load. Pin to native (0 = load from
+ // model) unless model.yml already set a positive per-model ctx-size.
+ if (!ctxEmitted) {
+ lines.push('ctx-size = 0')
+ }
const pooling =
typeof mc.pooling === 'string' && mc.pooling.length > 0
? mc.pooling
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index b963c5acb..bf392a595 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -106,7 +106,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
- "cpufeatures",
+ "cpufeatures 0.2.17",
]
[[package]]
@@ -519,6 +519,15 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block2"
version = "0.5.1"
@@ -749,6 +758,15 @@ dependencies = [
"toml 0.9.7",
]
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.2.40"
@@ -778,6 +796,12 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "cff-parser"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5810ca1a2b5870df2aab1c03e11c40c361ba51d6e3e361e56310f1cb3b4e087"
+
[[package]]
name = "cfg-expr"
version = "0.15.8"
@@ -800,6 +824,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+[[package]]
+name = "chacha20"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "chardetng"
version = "0.1.17"
@@ -1059,6 +1094,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc"
version = "3.3.0"
@@ -1188,7 +1232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
@@ -1515,6 +1559,15 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "ecb"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "ed25519"
version = "2.2.3"
@@ -2184,11 +2237,25 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
+ "r-efi 5.3.0",
"wasi 0.14.7+wasi-0.2.4",
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
+ "wasm-bindgen",
+]
+
[[package]]
name = "gimli"
version = "0.32.3"
@@ -2881,6 +2948,7 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
+ "block-padding",
"generic-array",
]
@@ -3230,19 +3298,28 @@ dependencies = [
[[package]]
name = "lopdf"
-version = "0.34.0"
+version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5c8ecfc6c72051981c0459f75ccc585e7ff67c70829560cda8e647882a9abff"
+checksum = "25aab26d99567469098e64a02f42679f8965c6401263eefa31d8f2dcc37a221c"
dependencies = [
+ "aes",
+ "bitflags 2.9.4",
+ "cbc",
+ "ecb",
"encoding_rs",
"flate2",
+ "getrandom 0.4.3",
"indexmap 2.11.4",
"itoa",
"log",
"md-5",
"nom",
+ "rand 0.10.1",
"rangemap",
- "time",
+ "sha2",
+ "stringprep",
+ "thiserror 2.0.17",
+ "ttf-parser",
"weezl",
]
@@ -3352,12 +3429,6 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
-[[package]]
-name = "minimal-lexical"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
-
[[package]]
name = "minisign-verify"
version = "0.2.4"
@@ -3480,12 +3551,11 @@ checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]]
name = "nom"
-version = "7.1.3"
+version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
- "minimal-lexical",
]
[[package]]
@@ -4125,13 +4195,15 @@ dependencies = [
[[package]]
name = "pdf-extract"
-version = "0.7.12"
+version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cbb3a5387b94b9053c1e69d8abfd4dd6dae7afda65a5c5279bc1f42ab39df575"
+checksum = "417e8fdc940f1d5bc62c5f89864c3a2255f74f69aa353c98509213d67df61e73"
dependencies = [
"adobe-cmap-parser",
+ "cff-parser",
"encoding_rs",
"euclid",
+ "log",
"lopdf",
"postscript",
"type1-encoding-parser",
@@ -4673,6 +4745,12 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
[[package]]
name = "radium"
version = "0.7.0"
@@ -4714,6 +4792,17 @@ dependencies = [
"rand_core 0.9.3",
]
+[[package]]
+name = "rand"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "rand_chacha"
version = "0.2.2"
@@ -4771,6 +4860,12 @@ dependencies = [
"getrandom 0.3.3",
]
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
[[package]]
name = "rand_hc"
version = "0.2.0"
@@ -5548,7 +5643,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -5559,7 +5654,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -7170,11 +7265,17 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+
[[package]]
name = "type1-encoding-parser"
-version = "0.1.0"
+version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3d6cc09e1a99c7e01f2afe4953789311a1c50baebbdac5b477ecf78e2e92a5b"
+checksum = "fa10c302f5a53b7ad27fd42a3996e23d096ba39b5b8dd6d9e683a05b01bee749"
dependencies = [
"pom",
]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index b24d9420e..dae33e625 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -11,6 +11,7 @@ const COMMANDS: &[&str] = &[
"force_kill_router_tree",
"force_stop_model",
"get_router_info",
+ "reload_router_models",
"router_slots_idle",
"get_devices",
"generate_api_key",
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 b7a800121..646ee0e7f 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -177,6 +177,14 @@ export async function routerSlotsIdle(modelId?: string): Promise<boolean> {
return await invoke('plugin:llamacpp|router_slots_idle', { modelId })
}
+/**
+ * Live-reload the router preset without restarting the process. Backend must
+ * support the reload diff path (upstream b9023+); gate on build at the caller.
+ */
+export async function reloadRouterModels(): Promise<void> {
+ return await invoke('plugin:llamacpp|reload_router_models')
+}
+
// GGUF commands
export async function readGgufMetadata(path: string): Promise<GgufMetadata> {
return await invoke('plugin:llamacpp|read_gguf_metadata', { path })
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
index 60450e76d..d903b14af 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md
@@ -13,6 +13,7 @@ Default permissions for the llamacpp plugin
- `allow-force-kill-router-tree`
- `allow-force-stop-model`
- `allow-get-router-info`
+- `allow-reload-router-models`
- `allow-router-slots-idle`
- `allow-get-devices`
- `allow-generate-api-key`
@@ -944,6 +945,32 @@ Denies the read_gguf_metadata command without any pre-configured scope.
<tr>
<td>
+`llamacpp:allow-reload-router-models`
+
+</td>
+<td>
+
+Enables the reload_router_models command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`llamacpp:deny-reload-router-models`
+
+</td>
+<td>
+
+Denies the reload_router_models command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`llamacpp:allow-remove-old-backend-versions`
</td>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
index b4d14858b..c9566121c 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml
@@ -13,6 +13,7 @@ permissions = [
"allow-force-kill-router-tree",
"allow-force-stop-model",
"allow-get-router-info",
+ "allow-reload-router-models",
"allow-router-slots-idle",
"allow-get-devices",
"allow-generate-api-key",
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 1e7fc997c..873ce65fc 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json
@@ -702,6 +702,18 @@
"const": "deny-read-gguf-metadata",
"markdownDescription": "Denies the read_gguf_metadata command without any pre-configured scope."
},
+ {
+ "description": "Enables the reload_router_models command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-reload-router-models",
+ "markdownDescription": "Enables the reload_router_models command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the reload_router_models command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-reload-router-models",
+ "markdownDescription": "Denies the reload_router_models command without any pre-configured scope."
+ },
{
"description": "Enables the remove_old_backend_versions command without any pre-configured scope.",
"type": "string",
@@ -811,10 +823,10 @@
"markdownDescription": "Denies the verify_backend_installation command without any pre-configured scope."
},
{
- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-force-stop-model`\n- `allow-get-router-info`\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": "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-force-stop-model`\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`",
"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-force-stop-model`\n- `allow-get-router-info`\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-force-stop-model`\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`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index 5eb09b9d4..6e6b463d7 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -530,6 +530,34 @@ pub async fn get_router_info<R: Runtime>(
}))
}
+/// Live-reload the router's preset (`GET /models?reload=1`) without restarting
+/// the process. The router diffs the regenerated `router.preset.ini` against the
+/// running set: models with unchanged presets stay loaded, only changed/removed
+/// ones are unloaded, and newly-added ones are registered. Requires a backend
+/// with the reload diff path (upstream b9023+); the TS caller gates on build.
+#[tauri::command]
+pub async fn reload_router_models<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+) -> Result<(), String> {
+ let (port, api_key, _pid) = router_endpoint(&app_handle).await?;
+ let client = http_client().await;
+ let url = format!("http://127.0.0.1:{}/models", port);
+ let resp = client
+ .get(&url)
+ .query(&[("reload", "1")])
+ .bearer_auth(&api_key)
+ .send()
+ .await
+ .map_err(|e| e.to_string())?;
+ if !resp.status().is_success() {
+ return Err(format!(
+ "router reload returned HTTP {}",
+ resp.status().as_u16()
+ ));
+ }
+ Ok(())
+}
+
/// 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/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 47bba47cc..3ef156bdd 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -32,6 +32,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
commands::force_kill_router_tree,
commands::force_stop_model,
commands::get_router_info,
+ commands::reload_router_models,
commands::router_slots_idle,
commands::get_devices,
commands::generate_api_key,
diff --git a/src-tauri/plugins/tauri-plugin-rag/Cargo.toml b/src-tauri/plugins/tauri-plugin-rag/Cargo.toml
index 9e232b536..dd07524b6 100644
--- a/src-tauri/plugins/tauri-plugin-rag/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-rag/Cargo.toml
@@ -17,7 +17,7 @@ serde_json = "1.0"
thiserror = "2.0"
tokio = { version = "1", features = ["full"] }
log = "0.4"
-pdf-extract = "0.7"
+pdf-extract = "0.12"
zip = "0.6"
quick-xml = { version = "0.31", features = ["serialize"] }
csv = "1.3"
diff --git a/web-app/src/containers/ProjectFiles.tsx b/web-app/src/containers/ProjectFiles.tsx
index 6afb1b95e..b67d9f599 100644
--- a/web-app/src/containers/ProjectFiles.tsx
+++ b/web-app/src/containers/ProjectFiles.tsx
@@ -72,6 +72,15 @@ function humanizeUploadError(
if (lower.includes('encrypted') || lower.includes('password')) {
return t('common:toast.uploadFailed.pdfEncrypted', { subject })
}
+ // pdf-extract hard-fails on PDF features it doesn't implement (e.g. a
+ // PostScript "unhandled function type" used for color/shading).
+ if (
+ lower.includes('function type') ||
+ lower.includes('not implemented') ||
+ lower.includes('unsupported')
+ ) {
+ return t('common:toast.uploadFailed.pdfUnsupportedFeature', { subject })
+ }
return t('common:toast.uploadFailed.pdfGeneric', { subject })
}
diff --git a/web-app/src/containers/__tests__/ProjectFiles.test.tsx b/web-app/src/containers/__tests__/ProjectFiles.test.tsx
index 8955b370f..6f27a78ba 100644
--- a/web-app/src/containers/__tests__/ProjectFiles.test.tsx
+++ b/web-app/src/containers/__tests__/ProjectFiles.test.tsx
@@ -53,6 +53,20 @@ vi.mock('@/hooks/useServiceHub', () => ({
}),
}))
+const uploadsHoisted = vi.hoisted(() => ({
+ ingestMock: vi.fn(),
+ progress: {} as Record<string, { current: number; total: number }>,
+}))
+const { ingestMock } = uploadsHoisted
+vi.mock('@/stores/project-uploads-store', () => ({
+ useProjectUploads: (selector: (s: unknown) => unknown) =>
+ selector({
+ progress: uploadsHoisted.progress,
+ completedTick: {},
+ ingest: uploadsHoisted.ingestMock,
+ }),
+}))
+
vi.mock('@/lib/extension', () => ({
ExtensionManager: {
getInstance: () => ({
@@ -61,12 +75,17 @@ vi.mock('@/lib/extension', () => ({
},
}))
+const coreHoisted = vi.hoisted(() => ({
+ fileStatMock: vi.fn(),
+ readdirSyncMock: vi.fn(),
+}))
+const { fileStatMock, readdirSyncMock } = coreHoisted
vi.mock('@janhq/core', () => ({
ExtensionTypeEnum: { VectorDB: 'vectordb' },
VectorDBExtension: class {},
fs: {
- fileStat: vi.fn().mockResolvedValue({ isDirectory: false, size: 100 }),
- readdirSync: vi.fn().mockResolvedValue([]),
+ fileStat: coreHoisted.fileStatMock,
+ readdirSync: coreHoisted.readdirSyncMock,
},
}))
@@ -97,6 +116,10 @@ describe('ProjectFiles', () => {
extMock.listAttachmentsForProject = listAttachmentsForProjectMock
extMock.deleteFileForProject = deleteFileForProjectMock
listAttachmentsForProjectMock.mockResolvedValue([])
+ fileStatMock.mockReset().mockResolvedValue({ isDirectory: false, size: 100 })
+ readdirSyncMock.mockReset().mockResolvedValue([])
+ ingestMock.mockReset()
+ uploadsHoisted.progress = {}
})
it('shows loader while files are loading', () => {
@@ -250,4 +273,149 @@ describe('ProjectFiles', () => {
fireEvent.drop(dropzone, { dataTransfer: { items: [], files: [] } })
await waitFor(() => expect(toastMock.info).toHaveBeenCalled())
})
+
+ // ---------- Upload flow: processFilePaths + ingest + humanizeUploadError ----------
+
+ async function clickUpload() {
+ render(<ProjectFiles projectId="p1" lng="en" />)
+ await waitFor(() =>
+ expect(screen.getByText('common:projects.processButton')).toBeInTheDocument()
+ )
+ fireEvent.click(screen.getByText('common:projects.processButton'))
+ }
+
+ const lastErrorDescription = () =>
+ (toastMock.error.mock.calls.at(-1)?.[1] as { description?: string })
+ ?.description
+
+ it('ingests a selected file and toasts success', async () => {
+ dialogOpenMock.mockResolvedValue(['/docs/report.pdf'])
+ ingestMock.mockImplementation(async (_pid, atts, _fn, opts) => {
+ expect(atts).toHaveLength(1)
+ expect(atts[0]).toMatchObject({ path: '/docs/report.pdf', fileType: 'pdf' })
+ opts.onSuccess()
+ })
+ await clickUpload()
+ await waitFor(() => expect(ingestMock).toHaveBeenCalledWith(
+ 'p1', expect.any(Array), expect.any(Function), expect.any(Object)
+ ))
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalled())
+ })
+
+ it.each([
+ [{ ParseError: 'PDF parsing failed unexpectedly: unhandled function type 4' }, 'pdfUnsupportedFeature'],
+ [{ ParseError: 'PDF parse error: invalid start value in xref table' }, 'pdfMalformedXref'],
+ [{ ParseError: 'PDF appears to be image-based or scanned' }, 'pdfScanned'],
+ [{ ParseError: 'PDF is encrypted, password required' }, 'pdfEncrypted'],
+ [{ UnsupportedFileType: 'odt' }, 'unsupportedType'],
+ [{ IoError: 'disk gone' }, 'ioError'],
+ [{ ParseError: 'totally weird failure' }, 'parseGeneric'],
+ ])(
+ 'maps RagError %j to uploadFailed.%s',
+ async (ragError, key) => {
+ dialogOpenMock.mockResolvedValue(['/docs/report.pdf'])
+ ingestMock.mockImplementation(async (_pid, _atts, _fn, opts) => {
+ opts.onError(ragError, 'report.pdf')
+ })
+ await clickUpload()
+ await waitFor(() => expect(toastMock.error).toHaveBeenCalled())
+ expect(lastErrorDescription()).toBe(`common:toast.uploadFailed.${key}`)
+ }
+ )
+
+ it('warns and skips unsupported file extensions without ingesting', async () => {
+ dialogOpenMock.mockResolvedValue(['/docs/archive.zzz'])
+ await clickUpload()
+ await waitFor(() => expect(toastMock.warning).toHaveBeenCalled())
+ expect(ingestMock).not.toHaveBeenCalled()
+ })
+
+ it('rejects files exceeding the max size without ingesting', async () => {
+ fileStatMock.mockResolvedValue({ isDirectory: false, size: 50 * 1024 * 1024 })
+ dialogOpenMock.mockResolvedValue(['/docs/huge.pdf'])
+ await clickUpload()
+ await waitFor(() =>
+ expect(toastMock.error).toHaveBeenCalledWith(
+ 'common:errors.fileTooLarge',
+ expect.any(Object)
+ )
+ )
+ expect(ingestMock).not.toHaveBeenCalled()
+ })
+
+ it('skips duplicates already attached to the project', async () => {
+ listAttachmentsForProjectMock.mockResolvedValue([
+ { id: 'd1', name: 'report.pdf', path: '/docs/report.pdf', chunk_count: 1 },
+ ])
+ dialogOpenMock.mockResolvedValue(['/docs/report.pdf'])
+ render(<ProjectFiles projectId="p1" lng="en" />)
+ await waitFor(() =>
+ expect(screen.getAllByText('report.pdf').length).toBeGreaterThan(0)
+ )
+ fireEvent.click(screen.getByText('common:projects.processButton'))
+ await waitFor(() => expect(toastMock.warning).toHaveBeenCalled())
+ expect(ingestMock).not.toHaveBeenCalled()
+ })
+
+ it('renders the upload progress bar while an ingest is in flight', async () => {
+ uploadsHoisted.progress = { p1: { current: 1, total: 3 } }
+ render(<ProjectFiles projectId="p1" lng="en" />)
+ await waitFor(() =>
+ expect(screen.getByText('common:projects.uploadingFiles')).toBeInTheDocument()
+ )
+ expect(screen.getByText('1 / 3')).toBeInTheDocument()
+ expect(screen.getByTestId('progress')).toHaveAttribute('data-value', String((1 / 3) * 100))
+ })
+
+ it('ingests files dropped with Tauri paths via dataTransfer.items', async () => {
+ ingestMock.mockImplementation(async (_pid, atts, _fn, opts) => {
+ expect(atts[0]).toMatchObject({ path: '/dropped/a.pdf', fileType: 'pdf' })
+ opts.onSuccess()
+ })
+ const { container } = render(<ProjectFiles projectId="p1" lng="en" />)
+ await waitFor(() =>
+ expect(screen.getByText('common:projects.filesDescription')).toBeInTheDocument()
+ )
+ const dropzone = container.querySelector('.border-dashed') as HTMLElement
+ const file = Object.assign(new File(['x'], 'a.pdf'), { path: '/dropped/a.pdf' })
+ fireEvent.drop(dropzone, {
+ dataTransfer: {
+ items: [{ kind: 'file', getAsFile: () => file }],
+ files: [],
+ },
+ })
+ await waitFor(() => expect(ingestMock).toHaveBeenCalled())
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalled())
+ })
+
+ it('falls back to dataTransfer.files when items are unavailable', async () => {
+ ingestMock.mockImplementation(async (_pid, atts, _fn, opts) => {
+ expect(atts[0]).toMatchObject({ path: '/web/b.pdf' })
+ opts.onSuccess()
+ })
+ const { container } = render(<ProjectFiles projectId="p1" lng="en" />)
+ await waitFor(() =>
+ expect(screen.getByText('common:projects.filesDescription')).toBeInTheDocument()
+ )
+ const dropzone = container.querySelector('.border-dashed') as HTMLElement
+ const file = Object.assign(new File(['x'], 'b.pdf'), { path: '/web/b.pdf' })
+ fireEvent.drop(dropzone, { dataTransfer: { files: [file] } })
+ await waitFor(() => expect(ingestMock).toHaveBeenCalled())
+ })
+
+ it('recursively gathers supported files from a dropped directory', async () => {
+ fileStatMock.mockImplementation(async (p: string) => ({
+ isDirectory: p === '/dir',
+ size: 100,
+ }))
+ readdirSyncMock.mockResolvedValue(['/dir/a.pdf', '/dir/skip.bin'])
+ dialogOpenMock.mockResolvedValue(['/dir'])
+ ingestMock.mockImplementation(async (_pid, atts, _fn, opts) => {
+ // only the supported .pdf survives the SUPPORTED_EXTENSIONS filter
+ expect(atts.map((a: { path: string }) => a.path)).toEqual(['/dir/a.pdf'])
+ opts.onSuccess()
+ })
+ await clickUpload()
+ await waitFor(() => expect(ingestMock).toHaveBeenCalled())
+ })
})
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 8c6b73895..1653243cf 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -482,6 +482,7 @@
"pdfMalformedXref": "{{subject}} has a malformed PDF cross-reference table and could not be parsed. Try opening it in a PDF viewer and re-saving it (File → Print → Save as PDF), then upload again.",
"pdfScanned": "{{subject}} appears to be a scanned or image-based PDF. OCR isn't supported yet — please upload a text-based PDF.",
"pdfEncrypted": "{{subject}} is password-protected. Remove the password and try again.",
+ "pdfUnsupportedFeature": "{{subject}} uses a PDF feature Jan can't parse yet (e.g. PostScript color/shading functions). Try re-saving it (File → Print → Save as PDF) to flatten it, then upload again.",
"pdfGeneric": "{{subject}} could not be parsed as a PDF. The file may be corrupted or uses an unsupported PDF feature.",
"fileTooLarge": "{{subject}} is too large. {{message}}.",
"unsupportedType": "File type \"{{type}}\" is not supported.",