Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(llamacpp): upgrade to 0.3.0, fix Windows MAX_PATH build, add grammar/template file paths (#8826)
Akarshan Biswas1c70d7288a58
diff --git a/README.md b/README.mdindex 58c04f815..f483578cf 100644--- a/README.md+++ b/README.md@@ -132,6 +132,26 @@ yarn buildyarn dev```+### Building on Windows++Run `make dev` from **Git Bash** (installed with Git for Windows) — make dispatches its recipes through `sh`, so a plain `cmd.exe` won't work.++You do **not** need a "Native Tools Command Prompt for VS 2022". The bundled llama.cpp engine builds with Ninja + `clang-cl`, and `clang-cl` locates the MSVC toolchain and Windows SDK on its own. What has to be installed (and on `PATH` for `ninja`/`clang-cl`/`cmake`):++- Visual Studio 2022 Build Tools (MSVC x64 workload + Windows SDK)+- LLVM (provides `clang-cl`)+- Ninja+- CMake+- CUDA Toolkit — only for `JAN_ENGINE_VARIANT=cuda12`/`cuda13` builds++Engine variants are picked with `JAN_ENGINE_VARIANT` (tokens: `cpu`, `vulkan`, `metal`, `cuda12`, `cuda13`, `hip`/`rocm`, joined by `-`), e.g.:++```bash+make dev JAN_ENGINE_VARIANT=cuda13+```++**"nvcc fatal : Could not open output file ...fattn-...cu.obj.d"** during `tauri-plugin-llamacpp(build)` means the build path crossed Windows' 260-character `MAX_PATH` limit — nvcc does not honor the long-path opt-in. The build script now detects this and automatically relocates the llama.cpp build tree to a short directory under `%LOCALAPPDATA%\jan-engine`. If you hit path-length errors anyway, set `JAN_ENGINE_BUILD_DIR` to a short path (e.g. `C:\jb`) or move the checkout closer to the drive root.+## System Requirements**Minimum specs for a decent experience:**diff --git a/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx b/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdxindex 9fba9395b..12f362a9c 100644--- a/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx+++ b/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx@@ -235,7 +235,7 @@ These settings are for fine-tuning model behavior and advanced use cases.| Setting | What It Does | Default Value | When to Change ||---------|-------------|---------------|----------------|| **Max Tokens to Predict** | Maximum tokens to generate | -1 (infinite) | Set a limit to prevent runaway generation |-| **Custom Jinja Chat Template** (per-model) | Override model's chat format | Empty | Only if model needs special formatting |+| **Custom Jinja Chat Template** (per-model) | Override model's chat format: a built-in template name, an inline Jinja body, or an absolute path to a `.jinja` file | Empty | Only if model needs special formatting || **Chat template options** (per-model) | Extra options the model's chat template accepts (sent as `chat_template_kwargs`, e.g. `enable_thinking`) | Empty | To toggle template features like reasoning or tool formatting per model |### RoPE (Rotary Position Embedding) Settings@@ -268,7 +268,7 @@ These settings are for fine-tuning model behavior and advanced use cases.| Setting | What It Does | Default Value | When to Change ||---------|-------------|---------------|----------------|-| **Grammar File** | Constrain output format | Empty | For structured output (JSON, code, etc.) |+| **Grammar** | Constrain output with a GBNF grammar: an inline grammar body or an absolute path to a `.gbnf` file | Empty | For structured output (JSON, code, etc.) || **JSON Schema File** | Enforce JSON structure | Empty | When you need specific JSON formats |## Troubleshooting Common Issuesdiff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 938b46b91..7a7fe353e 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -278,6 +278,11 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<coerce: (v) =>typeof v === 'string' && v.trim().length > 0 ? v : null,},+ grammar: {+ yamlKey: 'grammar',+ coerce: (v) =>+ typeof v === 'string' && v.trim().length > 0 ? v : null,+ },batch_size: {yamlKey: 'batch_size',coerce: (v) => {diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex bfc8196b8..8bdbe7877 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'const writtenFiles: Record<string, string> = {}const modelYamls: Record<string, unknown> = {}+const existingPaths = new Set<string>()vi.mock('@janhq/core', () => ({logger: {@@ -11,7 +12,10 @@ vi.mock('@janhq/core', () => ({error: vi.fn(),},fs: {- existsSync: vi.fn(async (p: string) => p === '/p/models' || p in modelYamls),+ existsSync: vi.fn(+ async (p: string) =>+ p === '/p/models' || p in modelYamls || existingPaths.has(p)+ ),mkdir: vi.fn(async () => undefined),readdirSync: vi.fn(async (dir: string) => {if (dir === '/p/models') {@@ -50,6 +54,7 @@ const CONFIG = {} as anybeforeEach(() => {for (const k of Object.keys(writtenFiles)) delete writtenFiles[k]for (const k of Object.keys(modelYamls)) delete modelYamls[k]+ existingPaths.clear()})function setupModel(id: string, yaml: Record<string, unknown>) {@@ -700,6 +705,56 @@ describe('generatePreset chat template', () => {await generatePreset('/p', '/jan', CONFIG)expect(writtenFiles['/p/router.preset.ini']).not.toContain('chat-template')})++ it('passes an absolute path to an existing file straight through', async () => {+ existingPaths.add('/home/u/templates/custom.jinja')+ setupModel('glm', { chat_template: '/home/u/templates/custom.jinja' })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('chat-template-file = /home/u/templates/custom.jinja')+ expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBeUndefined()+ })++ // A path that resolves to nothing is not silently trusted; it falls back to+ // the inline-body path so the value still reaches llama.cpp somehow.+ it('treats an absolute path to a missing file as an inline body', async () => {+ setupModel('glm', { chat_template: '/nope/custom.jinja' })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(+ '/nope/custom.jinja'+ )+ expect(writtenFiles['/p/router.preset.ini']).toContain(+ 'chat-template-file = /p/models/glm/chat_template.jinja'+ )+ })+})++// GBNF uses `#` for comments, so an inline grammar can never survive the ini;+// it always reaches llama.cpp as a file.+describe('generatePreset grammar', () => {+ it('writes an inline grammar to a file and points the preset at it', async () => {+ const grammar = '# yes/no only\nroot ::= "yes" | "no"'+ setupModel('glm', { grammar })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('grammar-file = /p/models/glm/grammar.gbnf')+ expect(writtenFiles['/p/models/glm/grammar.gbnf']).toBe(grammar)+ })++ it('passes an absolute path to an existing file straight through', async () => {+ existingPaths.add('/home/u/grammars/json.gbnf')+ setupModel('glm', { grammar: '/home/u/grammars/json.gbnf' })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('grammar-file = /home/u/grammars/json.gbnf')+ expect(writtenFiles['/p/models/glm/grammar.gbnf']).toBeUndefined()+ })++ it('emits nothing for a blank grammar', async () => {+ setupModel('glm', { grammar: ' ' })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('grammar')+ })})// The four draft flavours differ only in the `spec-type` value; a draft thatdiff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex d970e75b4..006728e78 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -21,6 +21,7 @@ import type { LlamacppConfig, ModelConfig } from '@janhq/tauri-plugin-llamacpp-a// `chat_template` that aren't yet in the strict typing.type ModelYaml = ModelConfig & {chat_template?: string+ grammar?: stringctx_size?: numbern_gpu_layers?: numberflash_attn?: string@@ -115,6 +116,25 @@ const DEFAULT_SPEC_TYPE = 'draft-mtp'*/const BUILTIN_TEMPLATE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/+// Absolute paths only: a relative one would resolve against llama.cpp's cwd,+// which is not something the user can predict. Covers POSIX, drive-letter and+// UNC forms.+const ABSOLUTE_PATH_RE = /^(?:\/|[A-Za-z]:[\\/]|\\\\)/++/**+ * When a setting value is an absolute path to an existing file, the preset+ * passes it through to the corresponding `*-file` flag instead of treating it+ * as an inline body.+ */+async function existingFilePath(value: string): Promise<string | null> {+ if (!ABSOLUTE_PATH_RE.test(value)) return null+ try {+ return (await fs.existsSync(value)) ? value : null+ } catch {+ return null+ }+}+function escapeIniValue(v: string): string {// INI values for llama-server are read as strings; trim surrounding whitespace// and strip stray newlines that would break parsing.@@ -479,13 +499,17 @@ export async function generatePreset(}// A template body cannot survive the ini: values have no line- // continuation, and `#`/`;` anywhere in one starts a comment. So only a- // built-in name goes inline; anything else is written beside model.yml and- // passed by path, which llama.cpp reads verbatim.+ // continuation, and `#`/`;` anywhere in one starts a comment. So an+ // absolute path to an existing file passes through as-is, a built-in name+ // goes inline, and anything else is written beside model.yml and passed by+ // path, which llama.cpp reads verbatim.const chatTemplate =typeof mc.chat_template === 'string' ? mc.chat_template.trim() : ''if (chatTemplate.length > 0) {- if (BUILTIN_TEMPLATE_NAME_RE.test(chatTemplate)) {+ const templateFile = await existingFilePath(chatTemplate)+ if (templateFile) {+ lines.push(`chat-template-file = ${escapeIniValue(templateFile)}`)+ } else if (BUILTIN_TEMPLATE_NAME_RE.test(chatTemplate)) {lines.push(`chat-template = ${chatTemplate}`)} else {const templatePath = await joinPath([@@ -498,6 +522,20 @@ export async function generatePreset(}}+ // GBNF uses `#` for comments and is usually multi-line, so an inline body+ // can never go through the ini; it always reaches llama.cpp as a file.+ const grammar = typeof mc.grammar === 'string' ? mc.grammar.trim() : ''+ if (grammar.length > 0) {+ const grammarFile = await existingFilePath(grammar)+ if (grammarFile) {+ lines.push(`grammar-file = ${escapeIniValue(grammarFile)}`)+ } else {+ const grammarPath = await joinPath([modelsDir, modelId, 'grammar.gbnf'])+ await fs.writeFileSync(grammarPath, grammar)+ lines.push(`grammar-file = ${escapeIniValue(grammarPath)}`)+ }+ }+// Per-model overrides -- same default-skipping rules as the [*] block.// An explicit 0 means "native" (load the model's own trained context).//diff --git a/src-tauri/.cargo/config.toml b/src-tauri/.cargo/config.tomlindex 1c702879f..da45e7bb2 100644--- a/src-tauri/.cargo/config.toml+++ b/src-tauri/.cargo/config.toml@@ -2,7 +2,6 @@# workaround needed to prevent `STATUS_ENTRYPOINT_NOT_FOUND` error in tests# see https://github.com/tauri-apps/tauri/pull/4383#issuecomment-1212221864__TAURI_WORKSPACE__ = "true"-ENABLE_SYSTEM_TRAY_ICON = "true"[target.aarch64-linux-android]linker = "aarch64-linux-android21-clang"diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex c2342ed85..fc19fbd75 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -3211,7 +3211,7 @@ dependencies = ["tokio","tower-service","tracing",- "windows-registry 0.6.1",+ "windows-registry 0.5.3",][[package]]@@ -4783,7 +4783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"dependencies = ["libc",- "windows-sys 0.61.2",+ "windows-sys 0.48.0",][[package]]@@ -7562,7 +7562,7 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.2.0"+version = "0.3.0"dependencies = ["base64 0.22.1","byteorder",@@ -9258,7 +9258,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.48.0",][[package]]diff --git a/src-tauri/build-utils/fetch-engine-source.sh b/src-tauri/build-utils/fetch-engine-source.shindex 84a721bc3..c6c31963a 100755--- a/src-tauri/build-utils/fetch-engine-source.sh+++ b/src-tauri/build-utils/fetch-engine-source.sh@@ -6,7 +6,7 @@# remember. `make clean` removes it.## The commit is verified after cloning because a git tag is mutable -- upstream-# could move b10582 and a --branch clone would silently hand us different+# could move the pinned tag and a --branch clone would silently hand us different# sources than build.rs claims, which is the one thing the pin exists to stop.## A script rather than a Makefile recipe so Windows gets the samediff --git a/src-tauri/build-utils/stage-engine.sh b/src-tauri/build-utils/stage-engine.shindex 2480b925b..1b07f053e 100755--- a/src-tauri/build-utils/stage-engine.sh+++ b/src-tauri/build-utils/stage-engine.sh@@ -44,10 +44,30 @@ mkdir -p "$DEST"install -m755 "$WORKER" "$DEST/jan-llama-worker$EXE"echo "stage-engine: staged jan-llama-worker$EXE"-# build.rs installs the ggml prefix under the build script's OUT_DIR. Take the-# newest match so a stale prefix from an earlier variant is never picked.-PREFIX="$(find "$TARGET_DIR/build" -maxdepth 3 -type d -name ggml-prefix -print0 2>/dev/null \- | xargs -0 -r ls -dt 2>/dev/null | head -1 || true)"+# Newest match only, so a stale artefact from an earlier variant is never+# picked.+newest() {+ find "$TARGET_DIR/build" -maxdepth 3 "$@" -print0 2>/dev/null \+ | xargs -0 -r ls -dt 2>/dev/null | head -1 || true+}++# build.rs normally installs the ggml prefix under the build script's OUT_DIR,+# but on Windows it relocates the cmake trees out of the target tree when+# OUT_DIR is too close to MAX_PATH. It records the root it chose in OUT_DIR.+PREFIX="$(newest -type d -name ggml-prefix)"+if [ -z "$PREFIX" ]; then+ MARKER="$(newest -type f -name engine-build-root.txt)"+ if [ -n "$MARKER" ]; then+ ROOT="$(tr -d '\r\n' < "$MARKER")"+ # The marker holds a native path; under Git Bash that is `C:\...`.+ if command -v cygpath >/dev/null 2>&1; then+ ROOT="$(cygpath -u "$ROOT")"+ fi+ if [ -d "$ROOT/ggml-prefix" ]; then+ PREFIX="$ROOT/ggml-prefix"+ fi+ fi+fiif [ -z "$PREFIX" ]; thenecho "stage-engine: no ggml-prefix found under $TARGET_DIR/build" >&2echo "stage-engine: was the worker built with an engine-* feature?" >&2diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lockindex 57fa66362..e71d5c34a 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock@@ -3421,7 +3421,7 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.2.0"+version = "0.3.0"dependencies = ["base64 0.22.1","byteorder",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlindex dab9f35c1..a207b832d 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml@@ -1,6 +1,6 @@[package]name = "tauri-plugin-llamacpp"-version = "0.2.0"+version = "0.3.0"authors = ["Jan <[email protected]>"]description = "Tauri plugin for managing Jan LlamaCpp server processes and model loading"license = "MIT"diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex b5ae1a219..5bdd49008 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -13,10 +13,10 @@// vendor/llama.cpp and with engine::PINNED_* on the Rust side; the shim// re-exports llama_version()/llama_build_number() so a mismatch is caught at// runtime instead of producing a silently wrong engine.-pub const LLAMA_CPP_TAG: &str = "b10582";-pub const LLAMA_CPP_BUILD_NUMBER: u32 = 10582;-pub const LLAMA_CPP_COMMIT: &str = "e85caa81ea2b65797396018c179b87ad61fa38ab";-pub const LLAMA_CPP_VERSION: &str = "0.2.0";+pub const LLAMA_CPP_TAG: &str = "b10621";+pub const LLAMA_CPP_BUILD_NUMBER: u32 = 10621;+pub const LLAMA_CPP_COMMIT: &str = "c1d0e7a004015f23bc0233470b747b596f29b264";+pub const LLAMA_CPP_VERSION: &str = "0.3.0";const COMMANDS: &[&str] = &[// Cleanup command@@ -186,6 +186,7 @@ mod engine {println!("cargo:rerun-if-env-changed=JAN_LLAMA_CPP_DIR");println!("cargo:rerun-if-env-changed=JAN_ENGINE_CUDA_ARCHS");println!("cargo:rerun-if-env-changed=JAN_ENGINE_BUILD_LOG");+ println!("cargo:rerun-if-env-changed=JAN_ENGINE_BUILD_DIR");// Headers are always needed: the shim is our code and is compiled// here even when the archives come prebuilt, so it cannot drift from@@ -209,8 +210,9 @@ mod engine {);(vec![lib], inc, dir.join("backends"))} else {- let ggml = build_ggml(&src);- let llama = build_llama(&src, &ggml);+ let root = build_root();+ let ggml = build_ggml(&src, &root);+ let llama = build_llama(&src, &ggml, &root);let mut dirs = ARCHIVE_DIRS.iter().map(|d| llama.join(d))@@ -237,6 +239,85 @@ mod engine {);}+ /// The deepest path a cmake build tree here creates, relative to the root+ /// the trees live under: nvcc's depfile for the longest-named CUDA+ /// template instance,+ /// `ggml-build/ggml/src/ggml-cuda/CMakeFiles/ggml-cuda.dir/Release/+ /// template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu.obj.d`.+ /// Measured with a margin for upstream adding a longer instance name.+ const DEEPEST_BUILD_PATH: usize = 150;++ /// Written into OUT_DIR with the (possibly relocated) build root, so+ /// packaging can find the ggml prefix without repeating the logic below.+ const BUILD_ROOT_MARKER: &str = "engine-build-root.txt";++ /// Windows' classic MAX_PATH. nvcc (and parts of MSVC) still open files+ /// through the 260-char-limited API even when the OS has long paths+ /// enabled, so the limit is real regardless of registry settings.+ const WINDOWS_MAX_PATH: usize = 260;++ /// Where the cmake build trees go. Normally OUT_DIR -- but on Windows a+ /// cargo OUT_DIR (`...\target\release\build\tauri-plugin-llamacpp-<hash>\+ /// out`) is easily 130+ chars, and nvcc then dies with "Could not open+ /// output file ...fattn-...cu.obj.d" because the depfile crosses MAX_PATH.+ /// When that would happen, the trees move to a short per-OUT_DIR directory+ /// under %LOCALAPPDATA% instead. `JAN_ENGINE_BUILD_DIR` overrides the+ /// location outright, on every platform. Relocated trees are not removed+ /// by `cargo clean`.+ fn build_root() -> PathBuf {+ let out = PathBuf::from(env::var("OUT_DIR").unwrap());+ let root = resolve_build_root(&out);+ // Packaging (build-utils/stage-engine.sh) collects the ggml runtime+ // from the build trees and cannot guess a relocated root, so record it.+ fs::write(+ out.join(BUILD_ROOT_MARKER),+ root.to_string_lossy().as_bytes(),+ )+ .expect("could not record the engine build root");+ root+ }++ fn resolve_build_root(out: &Path) -> PathBuf {+ if let Ok(dir) = env::var("JAN_ENGINE_BUILD_DIR") {+ let dir = dir.trim();+ if !dir.is_empty() {+ let root = PathBuf::from(dir).join(out_dir_key(out));+ fs::create_dir_all(&root).expect("could not create JAN_ENGINE_BUILD_DIR");+ return root;+ }+ }+ if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() != "windows" {+ return out.to_path_buf();+ }+ if out.as_os_str().len() + DEEPEST_BUILD_PATH < WINDOWS_MAX_PATH {+ return out.to_path_buf();+ }+ let base = env::var("LOCALAPPDATA")+ .map(PathBuf::from)+ .unwrap_or_else(|_| env::temp_dir());+ let root = base.join("jan-engine").join(out_dir_key(out));+ println!(+ "cargo:warning=OUT_DIR is too long for nvcc/cl on Windows \+ ({} chars); building llama.cpp under {} instead. Set \+ JAN_ENGINE_BUILD_DIR to choose the location.",+ out.as_os_str().len(),+ root.display()+ );+ fs::create_dir_all(&root).expect("could not create the short engine build dir");+ root+ }++ /// A stable short key for one OUT_DIR, so debug/release and per-feature+ /// builds relocated out of the target tree cannot share (and corrupt) one+ /// cmake cache. DefaultHasher::new() uses fixed keys, so the value is+ /// stable across runs.+ fn out_dir_key(out: &Path) -> String {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ out.hash(&mut h);+ format!("{:016x}", h.finish())+ }+/// Stage 1: ggml as shared libraries with runtime-loaded backend modules.////// Separate from stage 2 because `GGML_CPU_ALL_VARIANTS` requires@@ -249,11 +330,10 @@ mod engine {/// configuring ggml as the top-level project sets `GGML_STANDALONE=ON`,/// which then requires `tests/`, `examples/` and `ggml.pc.in` that the/// copy vendored inside llama.cpp does not ship.- fn build_ggml(src: &Path) -> PathBuf {- let out = PathBuf::from(env::var("OUT_DIR").unwrap());- let wrapper = out.join("ggml-project");- let build = out.join("ggml-build");- let prefix = out.join("ggml-prefix");+ fn build_ggml(src: &Path, root: &Path) -> PathBuf {+ let wrapper = root.join("ggml-project");+ let build = root.join("ggml-build");+ let prefix = root.join("ggml-prefix");fs::create_dir_all(&wrapper).expect("could not create the ggml wrapper dir");fs::write(wrapper.join("CMakeLists.txt"),@@ -278,7 +358,7 @@ mod engine {// MSVC-frontend compiler instead puts it back on /showIncludes, which// needs no such file -- and needs no vcvars either, since clang-cl// finds the MSVC headers and libraries by itself.- let host_toolchain = out.join("vulkan-shaders-gen-host.cmake");+ let host_toolchain = root.join("vulkan-shaders-gen-host.cmake");if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "windows" {fs::write(&host_toolchain,@@ -399,8 +479,8 @@ mod engine {}/// Stage 2: everything above ggml, statically, against stage 1's ggml.- fn build_llama(src: &Path, ggml_prefix: &Path) -> PathBuf {- let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join("llama-build");+ fn build_llama(src: &Path, ggml_prefix: &Path, root: &Path) -> PathBuf {+ let out = root.join("llama-build");discard_foreign_cache(&out, src);fs::create_dir_all(&out).expect("could not create the cmake build dir");diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/package.json b/src-tauri/plugins/tauri-plugin-llamacpp/package.jsonindex fa067be5a..738082879 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/package.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/package.json@@ -1,6 +1,6 @@{"name": "@janhq/tauri-plugin-llamacpp-api",- "version": "0.2.0",+ "version": "0.3.0","private": true,"description": "","type": "module",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.hindex 3af03f1bc..8520be171 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h@@ -96,8 +96,8 @@ void jan_llama_string_free(char * s);// The llama.cpp the shim was compiled against, for the pin assertion in// build.rs / engine::assert_pinned_version.-const char * jan_llama_version(void); // e.g. "0.2.0"-int jan_llama_build_number(void); // e.g. 10582+const char * jan_llama_version(void); // e.g. "0.3.0"+int jan_llama_build_number(void); // e.g. 10621const char * jan_llama_commit(void);#ifdef __cplusplusdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rsindex 47484e112..4f2db584d 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs@@ -212,9 +212,9 @@ mod tests {#[test]fn pin_constants_are_populated_from_build_rs() {- assert_eq!(PINNED_TAG, "b10582");- assert_eq!(PINNED_BUILD_NUMBER, "10582");- assert_eq!(PINNED_VERSION, "0.2.0");+ assert_eq!(PINNED_TAG, "b10621");+ assert_eq!(PINNED_BUILD_NUMBER, "10621");+ assert_eq!(PINNED_VERSION, "0.3.0");assert_eq!(PINNED_COMMIT.len(), 40, "commit should be a full sha");}diff --git a/src-tauri/src/core/server/commands.rs b/src-tauri/src/core/server/commands.rsindex c1dc76bcd..d0aef662d 100644--- a/src-tauri/src/core/server/commands.rs+++ b/src-tauri/src/core/server/commands.rs@@ -1,3 +1,4 @@+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use tauri::{AppHandle, Manager, Runtime, State};@@ -69,19 +70,41 @@ pub async fn start_server<R: Runtime>().await.map_err(|e| e.to_string())?;++ #[cfg(feature = "desktop")]+ crate::core::setup::show_tray(&app_handle);+Ok(actual_port)}#[tauri::command]-pub async fn stop_server(state: State<'_, AppState>) -> Result<(), String> {+pub async fn stop_server<R: Runtime>(+ app_handle: AppHandle<R>,+ state: State<'_, AppState>,+) -> Result<(), String> {let server_handle = state.server_handle.clone();proxy::stop_server(server_handle).await.map_err(|e| e.to_string())?;++ #[cfg(feature = "desktop")]+ crate::core::setup::remove_tray(&app_handle);+ #[cfg(not(feature = "desktop"))]+ let _ = app_handle;+Ok(())}+/// Whether closing the main window while the Local API Server runs should hide+/// the app to the tray instead of quitting (Windows/Linux only).+pub static SERVER_RUN_IN_BACKGROUND: AtomicBool = AtomicBool::new(true);++#[tauri::command]+pub fn set_server_run_in_background(enabled: bool) {+ SERVER_RUN_IN_BACKGROUND.store(enabled, Ordering::SeqCst);+}+#[tauri::command]pub async fn get_server_status(state: State<'_, AppState>) -> Result<bool, String> {let server_handle = state.server_handle.clone();diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 14b846799..841d44c83 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -246,12 +246,49 @@ pub fn setup_mcp<R: Runtime>(app: &App<R>) {}#[cfg(feature = "desktop")]-pub fn setup_tray(app: &App) -> tauri::Result<TrayIcon> {- let show_i = MenuItem::with_id(app.handle(), "open", "Open Jan", true, None::<&str>)?;- let quit_i = MenuItem::with_id(app.handle(), "quit", "Quit", true, None::<&str>)?;- let separator_i = PredefinedMenuItem::separator(app.handle())?;- let menu = Menu::with_items(app.handle(), &[&show_i, &separator_i, &quit_i])?;- TrayIconBuilder::with_id("tray")+pub const TRAY_ID: &str = "tray";++/// Tray icon forced on for the whole app lifetime at compile time; otherwise it+/// only exists while the Local API Server is running.+#[cfg(feature = "desktop")]+pub fn tray_always_visible() -> bool {+ option_env!("ENABLE_SYSTEM_TRAY_ICON").unwrap_or("false") == "true"+}++#[cfg(feature = "desktop")]+pub fn show_tray<R: Runtime>(app: &AppHandle<R>) {+ if app.tray_by_id(TRAY_ID).is_some() {+ return;+ }+ let handle = app.clone();+ // Tray creation must happen on the main thread (hard requirement on macOS).+ let _ = app.run_on_main_thread(move || {+ if handle.tray_by_id(TRAY_ID).is_none() {+ if let Err(e) = setup_tray(&handle) {+ log::error!("Failed to create tray icon: {e}");+ }+ }+ });+}++#[cfg(feature = "desktop")]+pub fn remove_tray<R: Runtime>(app: &AppHandle<R>) {+ if tray_always_visible() {+ return;+ }+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ let _ = handle.remove_tray_by_id(TRAY_ID);+ });+}++#[cfg(feature = "desktop")]+pub fn setup_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<TrayIcon<R>> {+ let show_i = MenuItem::with_id(app, "open", "Open Jan", true, None::<&str>)?;+ let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;+ let separator_i = PredefinedMenuItem::separator(app)?;+ let menu = Menu::with_items(app, &[&show_i, &separator_i, &quit_i])?;+ TrayIconBuilder::with_id(TRAY_ID).icon(app.default_window_icon().unwrap().clone()).menu(&menu).show_menu_on_left_click(false)diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e4f1e79a5..56893645f 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -83,6 +83,7 @@ macro_rules! invoke_commands_with_extras {core::server::commands::start_server,core::server::commands::stop_server,core::server::commands::get_server_status,+ core::server::commands::set_server_run_in_background,// Agent commandscore::agent::commands::agent_skill_list,core::agent::commands::agent_skill_read,@@ -370,9 +371,9 @@ pub fn run() {// Migration completed#[cfg(feature = "desktop")]- if option_env!("ENABLE_SYSTEM_TRAY_ICON").unwrap_or("false") == "true" {+ if setup::tray_always_visible() {log::info!("Enabling system tray icon");- let _ = setup::setup_tray(app);+ let _ = setup::setup_tray(app.handle());}#[cfg(all(feature = "deep-link", any(windows, target_os = "linux")))]@@ -422,12 +423,16 @@ pub fn run() {return;}// Windows/Linux: hide to tray only while the Local API Server is- // running; otherwise fall through to the normal quit-on-close.+ // running and the user opted into keeping it alive in the+ // background; otherwise fall through to the normal quit-on-close.// The llamacpp engine is not a reason to keep the app resident// (normal chat usage keeps it alive), so it gets torn down via// the ExitRequested path on quit.#[cfg(not(target_os = "macos"))]- if is_proxy_server_running(app) {+ if is_proxy_server_running(app)+ && core::server::commands::SERVER_RUN_IN_BACKGROUND+ .load(Ordering::SeqCst)+ {api.prevent_close();if let Some(window) = app.get_webview_window("main") {let _ = window.hide();diff --git a/web-app/src/hooks/useLlamacppDevices.ts b/web-app/src/hooks/useLlamacppDevices.tsindex 4ac2260b7..ca9924c4c 100644--- a/web-app/src/hooks/useLlamacppDevices.ts+++ b/web-app/src/hooks/useLlamacppDevices.ts@@ -13,6 +13,9 @@ interface LlamacppDevicesStore {clearError: () => voidsetDevices: (devices: (DeviceList & { activated: boolean })[]) => voidtoggleDevice: (deviceId: string) => void+ // Atomically set activation for several devices (e.g. one physical GPU+ // exposed by multiple backends) and persist the result once.+ setActivations: (updates: Record<string, boolean>) => Promise<void>}export const useLlamacppDevices = create<LlamacppDevicesStore>((set, get) => ({@@ -58,26 +61,29 @@ export const useLlamacppDevices = create<LlamacppDevicesStore>((set, get) => ({setDevices: (devices) => set({ devices }),toggleDevice: async (deviceId: string) => {- // Toggle device activation in the local state+ const device = get().devices.find((d) => d.id === deviceId)+ if (device) {+ await get().setActivations({ [deviceId]: !device.activated })+ }+ },++ setActivations: async (updates: Record<string, boolean>) => {set((state) => ({devices: state.devices.map((device) =>- device.id === deviceId- ? { ...device, activated: !device.activated }- : device+ updates[device.id] === undefined+ ? device+ : { ...device, activated: updates[device.id] }),}))- // Update llamacpp provider settingsconst { getProviderByName, updateProvider } = useModelProvider.getState()const llamacppProvider = getProviderByName('llamacpp')if (llamacppProvider) {- // Get activated devices after toggle- const activatedDeviceIds = get().devices- .filter((device) => device.activated)+ const deviceString = get()+ .devices.filter((device) => device.activated).map((device) => device.id)-- const deviceString = activatedDeviceIds.join(',')+ .join(',')const updatedSettings = llamacppProvider.settings.map((setting) => {if (setting.key === 'device') {@@ -98,5 +104,4 @@ export const useLlamacppDevices = create<LlamacppDevicesStore>((set, get) => ({})}},-}))diff --git a/web-app/src/hooks/useLocalApiServer.ts b/web-app/src/hooks/useLocalApiServer.tsindex 721c96e1d..01172effd 100644--- a/web-app/src/hooks/useLocalApiServer.ts+++ b/web-app/src/hooks/useLocalApiServer.ts@@ -7,6 +7,9 @@ type LocalApiServerState = {// Run local API server once app opensenableOnStartup: booleansetEnableOnStartup: (value: boolean) => void+ // Keep the app running in the tray when the window closes while the server is on+ runInBackground: boolean+ setRunInBackground: (value: boolean) => void// Default local model to auto-load when the server startsdefaultModelLocalApiServer: { model: string; provider: string } | nullsetDefaultModelLocalApiServer: (@@ -50,6 +53,8 @@ export const useLocalApiServer = create<LocalApiServerState>()((set) => ({enableOnStartup: false,setEnableOnStartup: (value) => set({ enableOnStartup: value }),+ runInBackground: true,+ setRunInBackground: (value) => set({ runInBackground: value }),defaultModelLocalApiServer: null,setDefaultModelLocalApiServer: (model) =>set({ defaultModelLocalApiServer: model }),@@ -88,7 +93,7 @@ export const useLocalApiServer = create<LocalApiServerState>()(name: localStorageKey.settingLocalApiServer,storage: createJSONStorage(() => backendStorage),skipHydration: true,- version: 3,+ version: 4,migrate: (persistedState: unknown, version: number) => {const state = persistedState as Partial<LocalApiServerState>if (version < 1) {@@ -103,6 +108,10 @@ export const useLocalApiServer = create<LocalApiServerState>()(// v2 -> v3: add server-side tool execution togglestate.enableServerToolExecution = false}+ if (version < 4) {+ // v3 -> v4: add run-in-background toggle (matches previous behavior)+ state.runInBackground = true+ }return state},}diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.tsindex afcef2a4d..6354a309e 100644--- a/web-app/src/hooks/useModelProvider.ts+++ b/web-app/src/hooks/useModelProvider.ts@@ -756,9 +756,28 @@ export const useModelProvider = create<ModelProviderState>()(})}+ if (version <= 17 && state?.providers) {+ // Grammar became a per-model setting; add the control to persisted+ // llamacpp models so the sidebar renders it.+ state.providers.forEach((provider) => {+ if (provider.provider !== 'llamacpp' || !provider.models) return+ provider.models.forEach((model) => {+ if (!model.settings) model.settings = {}+ if (!model.settings.grammar) {+ model.settings.grammar = {+ ...modelSettings.grammar,+ controller_props: {+ ...modelSettings.grammar.controller_props,+ },+ }+ }+ })+ })+ }+return state},- version: 17,+ version: 18,}))diff --git a/web-app/src/lib/predefined.ts b/web-app/src/lib/predefined.tsindex ae42c1e55..e760244c0 100644--- a/web-app/src/lib/predefined.ts+++ b/web-app/src/lib/predefined.ts@@ -127,12 +127,26 @@ export const modelSettings = {chatTemplate: {key: 'chat_template',title: 'Custom Jinja Chat template',- description: 'Custom Jinja chat_template to be used for the model',+ description:+ 'Custom Jinja chat_template for the model: a built-in template name, an inline template body, or an absolute path to a .jinja file',controller_type: 'textarea',controller_props: {value: '',placeholder:- 'e.g., {% for message in messages %}...{% endfor %} (default is read from GGUF)',+ 'e.g., {% for message in messages %}...{% endfor %} or /path/to/template.jinja (default is read from GGUF)',+ type: 'text',+ textAlign: 'right',+ },+ },+ grammar: {+ key: 'grammar',+ title: 'Grammar',+ description:+ 'GBNF grammar to constrain generations: an inline grammar body or an absolute path to a .gbnf file',+ controller_type: 'textarea',+ controller_props: {+ value: '',+ placeholder: 'e.g., root ::= "yes" | "no" or /path/to/grammar.gbnf',type: 'text',textAlign: 'right',},diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex cbb704c0f..04612e494 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -152,7 +152,18 @@"freeOf": "free of","driverVersion": "Driver Version","computeCapability": "Compute Capability",- "systemMonitor": "System Monitor"+ "systemMonitor": "System Monitor",+ "backendApi": "Backend API",+ "apiVersion": "API Version",+ "refresh": "Refresh",+ "detectingDevices": "Detecting GPUs...",+ "deviceListError": "Couldn't read GPU devices",+ "noDevicesDesc": "No GPUs are visible to the llama.cpp engine. Models will run on the CPU.",+ "gpuDisabled": "Disabled",+ "backendApiDesc": "How llama.cpp talks to this GPU",+ "backendSelectDesc": "Use this API for this GPU",+ "unifiedMemory": "Unified Memory",+ "unifiedMemoryDesc": "The GPU shares one memory pool with the CPU — models draw from the same memory as the rest of the system."},"httpsProxy": {"proxy": "Proxy",@@ -237,6 +248,8 @@"startupConfiguration": "Startup Configuration","runOnStartup": "Auto start","runOnStartupDesc": "Automatically start the Local API Server when the application launches.",+ "runInBackground": "Run in background",+ "runInBackgroundDesc": "Keep the server running in the system tray when the window is closed. When off, closing the window quits Jan and stops the server.","serverConfiguration": "Server Configuration","serverHost": "Server Host","serverHostDesc": "Network address for the server.",diff --git a/web-app/src/locales/en/system-monitor.json b/web-app/src/locales/en/system-monitor.jsonindex 7fa56678c..0a4eac040 100644--- a/web-app/src/locales/en/system-monitor.json+++ b/web-app/src/locales/en/system-monitor.json@@ -16,6 +16,8 @@"actions": "Actions","stop": "Stop","activeGpus": "Active GPUs",+ "gpus": "GPUs",+ "vram": "VRAM","noGpus": "No GPUs detected","noActiveGpus": "No active GPUs. All GPUs are currently disabled.","vramUsage": "VRAM Usage",diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsxindex 3f28585ee..9ee2745cc 100644--- a/web-app/src/providers/DataProvider.tsx+++ b/web-app/src/providers/DataProvider.tsx@@ -208,6 +208,7 @@ export function DataProvider() {lastServerModels,setLastServerModels,defaultModelLocalApiServer,+ runInBackground,} = useLocalApiServer()const setServerStatus = useAppState((state) => state.setServerStatus)@@ -399,6 +400,16 @@ export function DataProvider() {}}, [serviceHub, setProviders])+ // Keep the backend's hide-to-tray-on-close flag in sync with the setting+ useEffect(() => {+ serviceHub+ .app()+ .setServerRunInBackground(runInBackground)+ .catch((error) =>+ console.error('Failed to sync run-in-background setting:', error)+ )+ }, [serviceHub, runInBackground])+// Auto-start Local API Server on app startup if enableduseEffect(() => {if (enableOnStartup) {diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsxindex fe3675974..597e413b3 100644--- a/web-app/src/providers/__tests__/DataProvider.test.tsx+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx@@ -158,6 +158,7 @@ const hubState = vi.hoisted(() => ({getAssistants: vi.fn().mockResolvedValue([]),fetchThreads: vi.fn().mockResolvedValue([]),getServerStatus: vi.fn().mockResolvedValue(false),+ setServerRunInBackground: vi.fn().mockResolvedValue(undefined),startModel: vi.fn().mockResolvedValue(undefined),getActiveModels: vi.fn().mockResolvedValue([]),startServer: vi.fn().mockResolvedValue(1337),@@ -179,7 +180,10 @@ vi.mock('@/hooks/useServiceHub', () => {return Promise.resolve(hubState.unsubscribe)},}),- app: () => ({ getServerStatus: hubState.getServerStatus }),+ app: () => ({+ getServerStatus: hubState.getServerStatus,+ setServerRunInBackground: hubState.setServerRunInBackground,+ }),models: () => ({startModel: hubState.startModel,getActiveModels: hubState.getActiveModels,diff --git a/web-app/src/routes/__tests__/system-monitor.test.tsx b/web-app/src/routes/__tests__/system-monitor.test.tsxindex f3c609fea..5f12fdf59 100644--- a/web-app/src/routes/__tests__/system-monitor.test.tsx+++ b/web-app/src/routes/__tests__/system-monitor.test.tsx@@ -8,11 +8,10 @@ const h = vi.hoisted(() => ({hardwareData: {cpu: { name: 'Intel i9', arch: 'x86_64', core_count: 16 },total_memory: 32768,+ gpus: [] as any[],},- systemUsage: { cpu: 42.5, used_memory: 16384 },+ systemUsage: { cpu: 42.5, used_memory: 16384, gpus: [] as any[] },updateSystemUsage: vi.fn(),- fetchDevices: vi.fn(),- devices: [] as any[],getSystemUsage: vi.fn(),}))@@ -32,13 +31,6 @@ vi.mock('@/hooks/useHardware', () => ({}),}))-vi.mock('@/hooks/useLlamacppDevices', () => ({- useLlamacppDevices: () => ({- devices: h.devices,- fetchDevices: h.fetchDevices,- }),-}))-vi.mock('@/hooks/useServiceHub', () => ({useServiceHub: () => ({hardware: () => ({ getSystemUsage: h.getSystemUsage }),@@ -80,9 +72,9 @@ describe('SystemMonitor route', () => {h.hardwareData = {cpu: { name: 'Intel i9', arch: 'x86_64', core_count: 16 },total_memory: 32768,+ gpus: [],}- h.systemUsage = { cpu: 42.5, used_memory: 16384 }- h.devices = []+ h.systemUsage = { cpu: 42.5, used_memory: 16384, gpus: [] }h.getSystemUsage.mockResolvedValue({ cpu: 10, used_memory: 1 })})@@ -107,34 +99,51 @@ describe('SystemMonitor route', () => {expect(screen.getByText('50.00%')).toBeInTheDocument()})- it('calls fetchDevices on mount', () => {- renderComponent()- expect(h.fetchDevices).toHaveBeenCalled()- })-- it('shows noGpus message on non-mac when no devices', () => {+ it('shows noGpus message on non-mac when no GPUs reported', () => {renderComponent()expect(screen.getByText('system-monitor:noGpus')).toBeInTheDocument()- expect(screen.getByText('system-monitor:activeGpus')).toBeInTheDocument()+ expect(screen.getByText('system-monitor:gpus')).toBeInTheDocument()})- it('renders GPU device entries when devices present', () => {- h.devices = [- { id: 'gpu-0', name: 'RTX 4090', mem: 24576, free: 20480, activated: true },- { id: 'gpu-1', name: 'RTX 3060', mem: 12288, free: 10240, activated: false },+ it('renders GPUs from hardware data with backend and usage', () => {+ h.hardwareData.gpus = [+ {+ uuid: 'uuid-0',+ name: 'RTX 4090',+ total_memory: 24576,+ vendor: 'NVIDIA',+ driver_version: '560.35',+ nvidia_info: { index: 0, compute_capability: '8.9' },+ vulkan_info: { index: 0, api_version: '1.3' },+ },+ {+ uuid: 'uuid-1',+ name: 'Radeon RX 7800',+ total_memory: 16384,+ vendor: 'AMD',+ driver_version: '',+ nvidia_info: { index: -1, compute_capability: '' },+ vulkan_info: { index: 1, api_version: '1.3.290' },+ },+ ]+ h.systemUsage.gpus = [+ { uuid: 'uuid-0', used_memory: 6144, total_memory: 24576 },]renderComponent()expect(screen.getByText('RTX 4090')).toBeInTheDocument()- expect(screen.getByText('RTX 3060')).toBeInTheDocument()+ expect(screen.getByText('Radeon RX 7800')).toBeInTheDocument()+ expect(screen.getByText('CUDA')).toBeInTheDocument()+ expect(screen.getByText('Vulkan')).toBeInTheDocument()expect(screen.getByText('24576MB')).toBeInTheDocument()- expect(screen.getByText('20480MB')).toBeInTheDocument()- expect(screen.getByText('system-monitor:active')).toBeInTheDocument()+ expect(screen.getByText('560.35')).toBeInTheDocument()+ // 6144/24576 = 25%+ expect(screen.getByText('25.00%')).toBeInTheDocument()})it('hides GPU card on macOS', () => {;(globalThis as any).IS_MACOS = truerenderComponent()- expect(screen.queryByText('system-monitor:activeGpus')).not.toBeInTheDocument()+ expect(screen.queryByText('system-monitor:gpus')).not.toBeInTheDocument()})it('polls getSystemUsage every 5s and calls updateSystemUsage', async () => {diff --git a/web-app/src/routes/settings/__tests__/hardware.test.tsx b/web-app/src/routes/settings/__tests__/hardware.test.tsxindex bfa220be7..7c4f5ff5e 100644--- a/web-app/src/routes/settings/__tests__/hardware.test.tsx+++ b/web-app/src/routes/settings/__tests__/hardware.test.tsx@@ -59,13 +59,18 @@ vi.mock('@/hooks/useHardware', () => ({}),}))+const llamacpp = vi.hoisted(() => ({+ devices: [+ { id: 'gpu0', name: 'RTX 3080', mem: 10240, free: 8192, activated: true },+ ] as any[],+}))+vi.mock('@/hooks/useLlamacppDevices', () => ({useLlamacppDevices: () => ({- devices: [{ id: 'gpu0', name: 'RTX 3080', mem: 10240, free: 8192 }],+ devices: llamacpp.devices,loading: false,error: null,- activatedDevices: new Set(['gpu0']),- toggleDevice: vi.fn(),+ setActivations: vi.fn(),fetchDevices: vi.fn(),}),getState: () => ({ setActivatedDevices: vi.fn() }),@@ -99,7 +104,10 @@ vi.mock('@/constants/routes', () => ({}}))vi.mock('@/constants/windows', () => ({ windowKey: { systemMonitorWindow: 'monitor' } }))-vi.mock('@tabler/icons-react', () => ({ IconDeviceDesktopAnalytics: () => <div data-testid="icon" /> }))+vi.mock('@tabler/icons-react', () => ({+ IconDeviceDesktopAnalytics: () => <div data-testid="icon" />,+ IconRefresh: () => <div data-testid="icon-refresh" />,+}))// Mock the route structure properlyvi.mock('@tanstack/react-router', () => ({@@ -126,6 +134,9 @@ describe('Hardware Settings', () => {beforeEach(() => {vi.clearAllMocks()global.IS_MACOS = false+ llamacpp.devices = [+ { id: 'gpu0', name: 'RTX 3080', mem: 10240, free: 8192, activated: true },+ ]})it('renders hardware settings page', () => {@@ -171,18 +182,36 @@ describe('Hardware Settings', () => {render(<Component />)await waitFor(() => {- expect(screen.getByText('GPUs')).toBeInTheDocument()+ expect(screen.getByText('settings:hardware.gpus')).toBeInTheDocument()expect(screen.getByText('RTX 3080')).toBeInTheDocument()})})+ it('merges multi-backend devices into one card with a backend selector', async () => {+ llamacpp.devices = [+ { id: 'Vulkan0', name: 'RTX 3090', mem: 24824, free: 24240, activated: false },+ { id: 'CUDA0', name: 'RTX 3090', mem: 24127, free: 1259, activated: true },+ ]+ const Component = Route.component as React.ComponentType+ render(<Component />)++ await waitFor(() => {+ expect(screen.getAllByText('RTX 3090').length).toBe(1)+ expect(screen.getByText('CUDA')).toBeInTheDocument()+ expect(screen.getByText('Vulkan')).toBeInTheDocument()+ expect(screen.getAllByTestId('switch').length).toBe(1)+ })+ })+it('hides GPU devices on macOS', async () => {global.IS_MACOS = trueconst Component = Route.component as React.ComponentTyperender(<Component />)await waitFor(() => {- expect(screen.queryByText('GPUs')).not.toBeInTheDocument()+ expect(+ screen.queryByText('settings:hardware.gpus')+ ).not.toBeInTheDocument()})})})diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsxindex 13457771e..3f168f842 100644--- a/web-app/src/routes/settings/hardware.tsx+++ b/web-app/src/routes/settings/hardware.tsx@@ -6,12 +6,16 @@ import { Card, CardItem } from '@/containers/Card'import { Switch } from '@/components/ui/switch'import { Progress } from '@/components/ui/progress'import { useTranslation } from '@/i18n/react-i18next-compat'-import { useHardware } from '@/hooks/useHardware'+import { useHardware, type GPU } from '@/hooks/useHardware'import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'import { useEffect, useState } from 'react'-import { IconDeviceDesktopAnalytics } from '@tabler/icons-react'+import { IconDeviceDesktopAnalytics, IconRefresh } from '@tabler/icons-react'import { useServiceHub } from '@/hooks/useServiceHub'-import type { HardwareData, SystemUsage } from '@/services/hardware/types'+import type {+ DeviceList,+ HardwareData,+ SystemUsage,+} from '@/services/hardware/types'import { cn, formatMegaBytes } from '@/lib/utils'import { toNumber } from '@/utils/number'import { useModelProvider } from '@/hooks/useModelProvider'@@ -23,6 +27,318 @@ export const Route = createFileRoute(route.settings.hardware as any)({component: HardwareContent,})+const BACKEND_LABELS: Record<string, string> = {+ vulkan: 'Vulkan',+ cuda: 'CUDA',+ sycl: 'SYCL',+ hip: 'ROCm (HIP)',+ rocm: 'ROCm',+ opencl: 'OpenCL',+ metal: 'Metal',+ cpu: 'CPU',+}++function parseDeviceId(id: string): { backend: string; index: number } {+ const match = /^([A-Za-z]+?)(\d+)$/.exec(id ?? '')+ if (!match) return { backend: id ?? '', index: 0 }+ return { backend: match[1], index: Number(match[2]) }+}++function backendLabel(backend: string): string {+ return BACKEND_LABELS[backend.toLowerCase()] ?? backend.toUpperCase()+}++// Devices are joined to hardware-plugin GPUs by per-backend index, not by name:+// the same physical GPU appears at different indices under different backends.+function findGpuForDevice(+ backend: string,+ index: number,+ gpus: GPU[]+): GPU | undefined {+ const key = backend.toLowerCase()+ if (key === 'vulkan') {+ return gpus.find((gpu) => gpu.vulkan_info?.index === index)+ }+ if (key === 'cuda') {+ return gpus.find((gpu) => gpu.nvidia_info?.index === index)+ }+ return undefined+}++function BackendChip({ label, active }: { label: string; active: boolean }) {+ const { t } = useTranslation()+ return (+ <span+ title={t('settings:hardware.backendApiDesc')}+ className="inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-0.5 font-mono text-xs uppercase tracking-wider text-foreground"+ >+ <span+ className={cn(+ 'size-1.5 rounded-full',+ active ? 'bg-primary' : 'bg-muted-foreground/50'+ )}+ />+ {label}+ </span>+ )+}++function SpecChip({ children }: { children: React.ReactNode }) {+ return (+ <span className="rounded border border-border/60 bg-muted/40 px-1.5 py-0.5 font-mono text-xs text-muted-foreground">+ {children}+ </span>+ )+}++function UsageMeter({ percent }: { percent: number }) {+ const clamped = Math.min(100, Math.max(0, percent))+ return (+ <div className="flex items-center gap-3">+ <Progress value={clamped} className="h-1.5 w-32 border sm:w-40" />+ <span className="w-14 text-right font-mono text-xs tabular-nums text-foreground">+ {clamped.toFixed(1)}%+ </span>+ </div>+ )+}++type ActiveDevice = DeviceList & { activated: boolean }++interface GpuGroup {+ key: string+ name: string+ devices: ActiveDevice[]+}++const BACKEND_PRIORITY = [+ 'cuda',+ 'hip',+ 'rocm',+ 'sycl',+ 'metal',+ 'vulkan',+ 'opencl',+]++function backendPriority(backend: string): number {+ const index = BACKEND_PRIORITY.indexOf(backend.toLowerCase())+ return index === -1 ? BACKEND_PRIORITY.length : index+}++// llama.cpp lists one device per backend, so a single physical GPU can appear+// as both CUDA0 and Vulkan0. Group by name and pair same-name devices by their+// per-backend enumeration order.+function groupDevices(devices: ActiveDevice[]): GpuGroup[] {+ const byName = new Map<string, Map<string, ActiveDevice[]>>()+ for (const device of devices) {+ const { backend } = parseDeviceId(device.id)+ const backends = byName.get(device.name) ?? new Map()+ byName.set(device.name, backends)+ backends.set(backend, [...(backends.get(backend) ?? []), device])+ }++ const groups: GpuGroup[] = []+ for (const [name, backends] of byName) {+ const lists = [...backends.values()]+ for (const list of lists) {+ list.sort((a, b) => parseDeviceId(a.id).index - parseDeviceId(b.id).index)+ }+ const unitCount = Math.max(...lists.map((list) => list.length))+ for (let i = 0; i < unitCount; i++) {+ const unit = lists+ .map((list) => list[i])+ .filter((device): device is ActiveDevice => Boolean(device))+ .sort(+ (a, b) =>+ backendPriority(parseDeviceId(a.id).backend) -+ backendPriority(parseDeviceId(b.id).backend)+ )+ if (unit.length > 0) {+ groups.push({+ key: unit.map((device) => device.id).join('+'),+ name,+ devices: unit,+ })+ }+ }+ }+ return groups+}++// Activated device if any (units are priority-sorted), else the preferred one.+function selectedDevice(group: GpuGroup): ActiveDevice {+ return group.devices.find((device) => device.activated) ?? group.devices[0]+}++function GpuGroupCard({+ group,+ gpus,+ onToggle,+ onSelect,+}: {+ group: GpuGroup+ gpus: GPU[]+ onToggle: () => void+ onSelect: (deviceId: string) => void+}) {+ const { t } = useTranslation()+ const activated = group.devices.some((device) => device.activated)+ const device = selectedDevice(group)+ const { backend, index } = parseDeviceId(device.id)+ const gpuInfo = findGpuForDevice(backend, index, gpus)+ const used = Math.max(0, device.mem - device.free)+ const usedPercent = device.mem > 0 ? (used / device.mem) * 100 : 0++ const facts: { label: string; value: string }[] = [+ ...(gpuInfo?.driver_version+ ? [+ {+ label: t('settings:hardware.driverVersion'),+ value: gpuInfo.driver_version,+ },+ ]+ : []),+ ...(gpuInfo?.vulkan_info?.api_version+ ? [+ {+ label: t('settings:hardware.apiVersion'),+ value: gpuInfo.vulkan_info.api_version,+ },+ ]+ : []),+ ...(gpuInfo?.nvidia_info?.compute_capability+ ? [+ {+ label: t('settings:hardware.computeCapability'),+ value: gpuInfo.nvidia_info.compute_capability,+ },+ ]+ : []),+ ]++ return (+ <div+ className={cn(+ 'rounded-lg border border-border/60 p-4 transition-colors',+ activated ? 'border-l-2 border-l-primary' : 'bg-muted/20'+ )}+ >+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h2 className="truncate font-medium text-foreground">{group.name}</h2>+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">+ {group.devices.length > 1 ? (+ group.devices.map((groupDevice) => {+ const isSelected = groupDevice.id === device.id+ return (+ <button+ key={groupDevice.id}+ type="button"+ onClick={() => onSelect(groupDevice.id)}+ title={t('settings:hardware.backendSelectDesc')}+ className={cn(+ 'inline-flex cursor-pointer items-center gap-1.5 rounded-md border px-2 py-0.5 font-mono text-xs uppercase tracking-wider transition-colors',+ isSelected+ ? 'border-primary/60 text-foreground'+ : 'border-border text-muted-foreground hover:border-foreground/40 hover:text-foreground'+ )}+ >+ <span+ className={cn(+ 'size-1.5 rounded-full',+ isSelected && activated+ ? 'bg-primary'+ : 'bg-muted-foreground/50'+ )}+ />+ {backendLabel(parseDeviceId(groupDevice.id).backend)}+ </button>+ )+ })+ ) : (+ <BackendChip label={backendLabel(backend)} active={activated} />+ )}+ {!activated && (+ <span className="text-xs text-muted-foreground">+ {t('settings:hardware.gpuDisabled')}+ </span>+ )}+ </div>+ </div>+ <Switch checked={activated} onCheckedChange={onToggle} />+ </div>++ <div className={cn('mt-4', !activated && 'opacity-60')}>+ <div className="flex items-baseline justify-between gap-4 text-sm">+ <span className="text-muted-foreground">+ {t('settings:hardware.vram')}+ </span>+ <span className="font-mono text-xs tabular-nums text-foreground">+ {formatMegaBytes(device.free)} {t('settings:hardware.freeOf')}{' '}+ {formatMegaBytes(device.mem)}+ </span>+ </div>+ <Progress value={usedPercent} className="mt-1.5 h-1.5 w-full border" />+ {facts.length > 0 && (+ <dl className="mt-3 flex flex-wrap gap-x-6 gap-y-1">+ {facts.map((fact) => (+ <div key={fact.label} className="flex items-baseline gap-1.5">+ <dt className="text-xs text-muted-foreground">{fact.label}</dt>+ <dd className="font-mono text-xs tabular-nums text-foreground">+ {fact.value}+ </dd>+ </div>+ ))}+ </dl>+ )}+ </div>+ </div>+ )+}++// Apple Silicon: the hardware plugin enumerates GPUs via Vulkan/NVML only and+// llamacpp device listing is skipped on macOS, so the Metal GPU is synthesized+// from CPU + unified memory info.+function AppleSiliconGpuCard({+ name,+ totalMemory,+ usedMemory,+}: {+ name: string+ totalMemory: number+ usedMemory: number+}) {+ const { t } = useTranslation()+ const usedPercent = totalMemory > 0 ? (usedMemory / totalMemory) * 100 : 0++ return (+ <div className="rounded-lg border border-border/60 border-l-2 border-l-primary p-4">+ <div className="min-w-0">+ <h2 className="truncate font-medium text-foreground">{name}</h2>+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">+ <BackendChip label="Metal" active />+ </div>+ </div>+ <div className="mt-4">+ <div className="flex items-baseline justify-between gap-4 text-sm">+ <span className="text-muted-foreground">+ {t('settings:hardware.unifiedMemory')}+ </span>+ <span className="font-mono text-xs tabular-nums text-foreground">+ {formatMegaBytes(Math.max(0, totalMemory - usedMemory))}{' '}+ {t('settings:hardware.freeOf')} {formatMegaBytes(totalMemory)}+ </span>+ </div>+ <Progress value={usedPercent} className="mt-1.5 h-1.5 w-full border" />+ <p className="mt-3 text-xs text-muted-foreground">+ {t('settings:hardware.unifiedMemoryDesc')}+ </p>+ </div>+ </div>+ )+}+function HardwareContent() {const { t } = useTranslation()const [isLoading, setIsLoading] = useState(false)@@ -39,7 +355,6 @@ function HardwareContent() {const { providers } = useModelProvider()const llamacpp = providers.find((p) => p.provider === 'llamacpp')- // Llamacpp devices hookconst llamacppDevicesResult = useLlamacppDevices()// Use default values on macOS since llamacpp devices are not relevant@@ -47,24 +362,22 @@ function HardwareContent() {devices: llamacppDevices,loading: llamacppDevicesLoading,error: llamacppDevicesError,- toggleDevice,+ setActivations,fetchDevices,} = IS_MACOS? {devices: [],loading: false,error: null,- toggleDevice: () => {},+ setActivations: async () => {},fetchDevices: () => {},}: llamacppDevicesResult- // Fetch llamacpp devices when component mountsuseEffect(() => {fetchDevices()}, [fetchDevices])- // Fetch initial hardware info and system usageuseEffect(() => {setIsLoading(true)Promise.all([@@ -136,11 +449,52 @@ function HardwareContent() {}}+ const applyActivations = (updates: Record<string, boolean>) => {+ setActivations(updates)+ serviceHub.models().stopAllModels()+ serviceHub+ .models()+ .getActiveModels()+ .then((models) => setActiveModels(models || []))+ }++ const handleToggleGroup = (group: GpuGroup) => {+ const activated = group.devices.some((device) => device.activated)+ const updates: Record<string, boolean> = {}+ for (const device of group.devices) updates[device.id] = false+ if (!activated) updates[selectedDevice(group).id] = true+ applyActivations(updates)+ }++ const handleSelectBackend = (group: GpuGroup, deviceId: string) => {+ const updates: Record<string, boolean> = {}+ for (const device of group.devices) {+ updates[device.id] = device.id === deviceId+ }+ applyActivations(updates)+ }++ const gpus = hardwareData.gpus ?? []+ const isAppleSilicon =+ IS_MACOS && /^(arm64|aarch64)$/i.test(hardwareData.cpu?.arch ?? '')+ const memoryPercent =+ hardwareData.total_memory > 0+ ? toNumber(systemUsage.used_memory / hardwareData.total_memory) * 100+ : 0+ const cpuExtensions = hardwareData.cpu?.extensions ?? []+return (<div className="flex flex-col h-svh w-full"><HeaderPage>- <div className={cn("flex items-center justify-between w-full mr-2 pr-3", !IS_MACOS && "pr-30")}>- <span className='font-medium text-base font-studio'>{t('common:settings')}</span>+ <div+ className={cn(+ 'flex items-center justify-between w-full mr-2 pr-3',+ !IS_MACOS && 'pr-30'+ )}+ >+ <span className="font-medium text-base font-studio">+ {t('common:settings')}+ </span><Buttonvariant="outline"size="sm"@@ -163,7 +517,6 @@ function HardwareContent() {</div>) : (<div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- {/* OS Information */}<Card title={t('settings:hardware.os')}><CardItemtitle={t('settings:hardware.name')}@@ -183,7 +536,6 @@ function HardwareContent() {/></Card>- {/* CPU Information */}<Card title={t('settings:hardware.cpu')}><CardItemtitle={t('settings:hardware.model')}@@ -204,48 +556,45 @@ function HardwareContent() {<CardItemtitle={t('settings:hardware.cores')}actions={- <span className="text-foreground">+ <span className="text-foreground tabular-nums">{hardwareData.cpu?.core_count}</span>}/>- {hardwareData.cpu?.extensions?.join(', ').length > 0 && (+ {cpuExtensions.length > 0 && (<CardItemtitle={t('settings:hardware.instructions')}- column={hardwareData.cpu?.extensions.length > 6}+ column={cpuExtensions.length > 6}actions={- <span className="text-foreground wrap-break-word">- {hardwareData.cpu?.extensions?.join(', ')}- </span>+ <div className="flex flex-wrap gap-1 pt-1">+ {cpuExtensions.map((extension) => (+ <SpecChip key={extension}>{extension}</SpecChip>+ ))}+ </div>}/>)}<CardItemtitle={t('settings:hardware.usage')}actions={- <div className="flex items-center gap-2">- {systemUsage.cpu > 0 && (- <>- <Progress- value={systemUsage.cpu}- className="h-2 w-10 border"- />- <span className="text-foreground">- {systemUsage.cpu?.toFixed(2)}%- </span>- </>- )}- </div>+ systemUsage.cpu > 0 && (+ <UsageMeter percent={systemUsage.cpu} />+ )}/></Card>- {/* RAM Information */}- <Card title={t('settings:hardware.memory')}>+ <Card+ title={t(+ isAppleSilicon+ ? 'settings:hardware.unifiedMemory'+ : 'settings:hardware.memory'+ )}+ ><CardItemtitle={t('settings:hardware.totalRam')}actions={- <span className="text-foreground">+ <span className="text-foreground tabular-nums">{formatMegaBytes(hardwareData.total_memory)}</span>}@@ -253,7 +602,7 @@ function HardwareContent() {<CardItemtitle={t('settings:hardware.availableRam')}actions={- <span className="text-foreground">+ <span className="text-foreground tabular-nums">{formatMegaBytes(hardwareData.total_memory - systemUsage.used_memory)}@@ -263,112 +612,77 @@ function HardwareContent() {<CardItemtitle={t('settings:hardware.usage')}actions={- <div className="flex items-center gap-2">- {hardwareData.total_memory > 0 && (- <>- <Progress- value={- toNumber(- systemUsage.used_memory /- hardwareData.total_memory- ) * 100- }- className="h-2 w-10 border"- />- <span className="text-foreground">- {(- toNumber(- systemUsage.used_memory /- hardwareData.total_memory- ) * 100- ).toFixed(2)}- %- </span>- </>- )}- </div>+ hardwareData.total_memory > 0 && (+ <UsageMeter percent={memoryPercent} />+ )}/></Card>- {/* Llamacpp Devices Information */}+ {isAppleSilicon && (+ <Card title={t('settings:hardware.gpus')}>+ <AppleSiliconGpuCard+ name={hardwareData.cpu?.name || 'Apple Silicon'}+ totalMemory={hardwareData.total_memory}+ usedMemory={systemUsage.used_memory}+ />+ </Card>+ )}+{!IS_MACOS && llamacpp && (<Card- title="GPUs"+ title={t('settings:hardware.gpus')}header={- <div className="flex items-center justify-end mb-2">+ <div className="flex items-center justify-end -mt-10 mb-4"><Buttonvariant="ghost"size="sm"onClick={handleRefreshHardware}disabled={isLoading}+ className="flex items-center gap-1.5">- {isLoading ? '...' : 'Refresh'}+ <IconRefresh className="size-4 text-muted-foreground" />+ {t('settings:hardware.refresh')}</Button></div>}>{llamacppDevicesLoading ? (- <CardItem title="Loading devices..." actions={<></>} />+ <div className="text-muted-foreground text-sm">+ {t('settings:hardware.detectingDevices')}+ </div>) : llamacppDevicesError ? (- <CardItem- title="Error loading devices"- actions={- <span className="text-destructive text-sm">- {llamacppDevicesError}- </span>- }- />+ <div className="text-sm">+ <span className="text-destructive">+ {t('settings:hardware.deviceListError')}+ </span>+ <p className="mt-1 text-muted-foreground">+ {llamacppDevicesError}+ </p>+ </div>) : llamacppDevices.length > 0 ? (- llamacppDevices.map((device, index) => (- <Card key={index}>- <CardItem- title={device.name}- actions={- <div className="flex items-center gap-4">- {/* <div className="flex flex-col items-end gap-1">- <span className="text-foreground text-sm">- ID: {device.id}- </span>- <span className="text-foreground text-sm">- Memory: {formatMegaBytes(device.mem)} /{' '}- {formatMegaBytes(device.free)} free- </span>- </div> */}- <Switch- checked={device.activated}- onCheckedChange={() => {- toggleDevice(device.id)- serviceHub.models().stopAllModels()-- // Refresh active models after stopping- serviceHub- .models()- .getActiveModels()- .then((models) =>- setActiveModels(models || [])- )- }}- />- </div>+ <div className="flex flex-col gap-3">+ {groupDevices(llamacppDevices).map((group) => (+ <GpuGroupCard+ key={group.key}+ group={group}+ gpus={gpus}+ onToggle={() => handleToggleGroup(group)}+ onSelect={(deviceId) =>+ handleSelectBackend(group, deviceId)}/>- <div className="mt-3">- <CardItem- title={t('settings:hardware.vram')}- actions={- <span className="text-foreground">- {formatMegaBytes(device.free)}{' '}- {t('settings:hardware.freeOf')}{' '}- {formatMegaBytes(device.mem)}- </span>- }- />- </div>- </Card>- ))+ ))}+ </div>) : (- <CardItem title="No devices found" actions={<></>} />+ <div className="text-sm">+ <span className="text-foreground">+ {t('settings:hardware.noGpus')}+ </span>+ <p className="mt-1 text-muted-foreground">+ {t('settings:hardware.noDevicesDesc')}+ </p>+ </div>)}</Card>)}diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsxindex e3ad61612..e3529c2a3 100644--- a/web-app/src/routes/settings/local-api-server.tsx+++ b/web-app/src/routes/settings/local-api-server.tsx@@ -62,6 +62,8 @@ function LocalAPIServerContent() {setVerboseLogs,enableOnStartup,setEnableOnStartup,+ runInBackground,+ setRunInBackground,serverHost,serverPort,setServerPort,@@ -456,6 +458,20 @@ function LocalAPIServerContent() {/>}/>+ {!IS_MACOS && (+ <CardItem+ title={t('settings:localApiServer.runInBackground')}+ description={t(+ 'settings:localApiServer.runInBackgroundDesc'+ )}+ actions={+ <Switch+ checked={runInBackground}+ onCheckedChange={setRunInBackground}+ />+ }+ />+ )}<CardItemtitle={t('settings:localApiServer.defaultModel')}description={t('settings:localApiServer.defaultModelDesc')}diff --git a/web-app/src/routes/system-monitor.tsx b/web-app/src/routes/system-monitor.tsxindex 00073155d..79a29b543 100644--- a/web-app/src/routes/system-monitor.tsx+++ b/web-app/src/routes/system-monitor.tsx@@ -1,31 +1,33 @@/* eslint-disable @typescript-eslint/no-explicit-any */import { createFileRoute } from '@tanstack/react-router'import { useEffect } from 'react'-import { useHardware } from '@/hooks/useHardware'+import { useHardware, type GPU } from '@/hooks/useHardware'import { Progress } from '@/components/ui/progress'import { route } from '@/constants/routes'import { formatMegaBytes } from '@/lib/utils'import { IconDeviceDesktopAnalytics } from '@tabler/icons-react'import { useTranslation } from '@/i18n/react-i18next-compat'import { toNumber } from '@/utils/number'-import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'import { useServiceHub } from '@/hooks/useServiceHub'export const Route = createFileRoute(route.systemMonitor as any)({component: SystemMonitorContent,})+function gpuBackendLabel(gpu: GPU): string {+ if (gpu.nvidia_info?.compute_capability) return 'CUDA'+ if (gpu.vulkan_info?.api_version) return 'Vulkan'+ return gpu.vendor || 'GPU'+}+function SystemMonitorContent() {const { t } = useTranslation()const { hardwareData, systemUsage, updateSystemUsage } = useHardware()const serviceHub = useServiceHub()- const { devices: llamacppDevices, fetchDevices } = useLlamacppDevices()-- useEffect(() => {- // Fetch llamacpp devices- fetchDevices()- }, [updateSystemUsage, fetchDevices])+ // Extensions never load in this secondary window, so GPU data comes from+ // the hardware plugin (allowed by this window's capabilities), not llamacpp.+ const gpus = hardwareData.gpus ?? []// Poll system usage every 5 secondsuseEffect(() => {@@ -148,42 +150,68 @@ function SystemMonitorContent() {{!IS_MACOS && (<div className="bg-secondary/50 rounded-lg p-6 shadow-sm"><h2 className="text-base font-semibold mb-4">- {t('system-monitor:activeGpus')}+ {t('system-monitor:gpus')}</h2>- <div className="flex flex-col gap-2">- {llamacppDevices.length > 0 ? (- llamacppDevices.map((device) => (- <div key={device.id} className="flex flex-col gap-1">- <div className="flex justify-between items-center">- <span className="text-muted-foreground">- {device.name}- </span>- <span- className={`text-sm px-2 py-1 rounded-md ${- device.activated- ? 'bg-green-500/20 text-green-600 dark:text-green-400'- : 'hidden'- }`}- >- {device.activated- ? t('system-monitor:active')- : 'Inactive'}- </span>- </div>- <div className="flex justify-between items-center text-sm">- <span className="text-muted-foreground">VRAM:</span>- <span className="text-foreground">- {formatMegaBytes(device.mem)}- </span>- </div>- <div className="flex justify-between items-center text-sm">- <span className="text-muted-foreground">Free:</span>- <span className="text-foreground">- {formatMegaBytes(device.free)}- </span>+ <div className="flex flex-col gap-4">+ {gpus.length > 0 ? (+ gpus.map((gpu) => {+ const usage = systemUsage.gpus?.find(+ (u) => u.uuid === gpu.uuid+ )+ const total = usage?.total_memory || gpu.total_memory+ const used = usage?.used_memory ?? 0+ const usagePercent =+ total > 0 ? toNumber(used / total) * 100 : 0+ return (+ <div key={gpu.uuid} className="flex flex-col gap-2">+ <div className="flex justify-between items-center gap-2">+ <span+ className="text-foreground truncate"+ title={gpu.name}+ >+ {gpu.name}+ </span>+ <span className="shrink-0 rounded-md border border-border px-2 py-0.5 font-mono text-xs uppercase tracking-wider text-foreground">+ {gpuBackendLabel(gpu)}+ </span>+ </div>+ {gpu.driver_version && (+ <div className="flex justify-between items-center text-sm">+ <span className="text-muted-foreground">+ {t('system-monitor:driverVersion')}+ </span>+ <span className="text-foreground">+ {gpu.driver_version}+ </span>+ </div>+ )}+ <div className="flex justify-between items-center text-sm">+ <span className="text-muted-foreground">+ {t('system-monitor:vram')}+ </span>+ <span className="text-foreground">+ {formatMegaBytes(total)}+ </span>+ </div>+ {usage && (+ <div className="mt-1">+ <div className="flex justify-between items-center mb-2">+ <span className="text-muted-foreground">+ {t('system-monitor:vramUsage')}+ </span>+ <span className="text-foreground font-bold">+ {usagePercent.toFixed(2)}%+ </span>+ </div>+ <Progress+ value={usagePercent}+ className="h-3 w-full"+ />+ </div>+ )}</div>- </div>- ))+ )+ })) : (<div className="text-muted-foreground text-center py-4">{t('system-monitor:noGpus')}diff --git a/web-app/src/services/app/default.ts b/web-app/src/services/app/default.tsindex 40a8e15c5..b299a9e3e 100644--- a/web-app/src/services/app/default.ts+++ b/web-app/src/services/app/default.ts@@ -36,6 +36,11 @@ export class DefaultAppService implements AppService {return false}+ async setServerRunInBackground(enabled: boolean): Promise<void> {+ // No-op - tray/background behavior only exists in the desktop app+ void enabled+ }+async readYaml<T = unknown>(path: string): Promise<T> {console.log('readYaml called with path:', path)throw new Error('readYaml not implemented in default app service')diff --git a/web-app/src/services/app/tauri.ts b/web-app/src/services/app/tauri.tsindex c0c2deb13..560ac8010 100644--- a/web-app/src/services/app/tauri.ts+++ b/web-app/src/services/app/tauri.ts@@ -99,6 +99,10 @@ export class TauriAppService extends DefaultAppService {return await invoke<boolean>('get_server_status')}+ async setServerRunInBackground(enabled: boolean): Promise<void> {+ await invoke('set_server_run_in_background', { enabled })+ }+async readYaml<T = unknown>(path: string): Promise<T> {return await invoke<T>('read_yaml', { path })}diff --git a/web-app/src/services/app/types.ts b/web-app/src/services/app/types.tsindex 5185fee17..97eb21e27 100644--- a/web-app/src/services/app/types.ts+++ b/web-app/src/services/app/types.ts@@ -22,5 +22,6 @@ export interface AppService {getJanDataFolder(): Promise<string | undefined>relocateJanDataFolder(path: string): Promise<void>getServerStatus(): Promise<boolean>+ setServerRunInBackground(enabled: boolean): Promise<void>readYaml<T = unknown>(path: string): Promise<T>}