Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(llamacpp): refactor llama.cpp integration with worker process and session caching (#8762)
Akarshan Biswas87fc8e526dc1
diff --git a/.github/actions/setup-engine-toolchain/action.yml b/.github/actions/setup-engine-toolchain/action.ymlnew file mode 100644index 000000000..afa5630c4--- /dev/null+++ b/.github/actions/setup-engine-toolchain/action.yml@@ -0,0 +1,110 @@+name: Setup engine toolchain+description: >+ Selects a JAN_ENGINE_VARIANT and asserts the runner can build it. The engine+ jobs run on self-hosted runners whose images carry cmake, ccache and the+ vendor toolkits, so this installs nothing for them -- it points ccache at the+ runner's persistent cache and fails fast when the image cannot produce the+ variant it was handed. The one exception is the Vulkan SDK, which the+ GitHub-hosted images the desktop builds default to do not carry.++inputs:+ variant:+ description: >+ JAN_ENGINE_VARIANT to build: a `-` joined backend list, e.g. vulkan,+ cuda13-vulkan, rocm-vulkan, metal or cpu.+ required: true+ ccache-max:+ description: >+ ccache size limit. 25G rather than the 5G default because CUDA objects are+ large and a smaller cache thrashes instead of rolling over.+ required: false+ default: '25G'++runs:+ using: composite+ steps:+ - name: Select the engine variant+ shell: bash+ run: echo "JAN_ENGINE_VARIANT=${{ inputs.variant }}" >> "$GITHUB_ENV"++ # The cache lives outside the workspace, which is re-cloned per run. Nothing+ # is saved or restored through actions/cache: the runner's disk persists, so+ # a hit costs no upload and survives across workflows.+ - name: Point ccache at the runner's persistent cache+ shell: bash+ run: |+ if [ "$RUNNER_OS" = "Windows" ]; then+ echo "CCACHE_DIR=${LOCALAPPDATA}\\ccache" >> "$GITHUB_ENV"+ else+ echo "CCACHE_DIR=${HOME}/.ccache" >> "$GITHUB_ENV"+ fi+ echo "CCACHE_MAXSIZE=${{ inputs.ccache-max }}" >> "$GITHUB_ENV"++ # No GitHub-hosted image ships a Vulkan shader compiler, and the desktop+ # templates default to the vulkan variant on one. Guarded on glslc rather+ # than on the runner label so a self-hosted image that carries the SDK does+ # no apt or installer work at all.+ - name: Provision the Vulkan SDK+ if: contains(format('-{0}-', inputs.variant), '-vulkan-')+ shell: bash+ run: |+ if command -v glslc >/dev/null 2>&1; then+ echo "engine toolchain: glslc already on the image"+ exit 0+ fi+ case "$RUNNER_OS" in+ Linux)+ # LunarG rather than the distro packages: jammy ships Vulkan headers+ # 1.3.204, older than the extensions ggml-vulkan compiles against.+ codename=$(. /etc/os-release && echo "$VERSION_CODENAME")+ wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc \+ | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc >/dev/null+ sudo wget -qO "/etc/apt/sources.list.d/lunarg-vulkan-$codename.list" \+ "https://packages.lunarg.com/vulkan/lunarg-vulkan-$codename.list"+ sudo apt-get update+ sudo apt-get install -y vulkan-sdk+ ;;+ Windows)+ curl -fL -o "$RUNNER_TEMP/vulkan-sdk.exe" \+ https://sdk.lunarg.com/sdk/download/latest/windows/vulkan_sdk.exe+ "$RUNNER_TEMP/vulkan-sdk.exe" --root 'C:\VulkanSDK' \+ --accept-licenses --default-answer --confirm-command install+ echo 'VULKAN_SDK=C:\VulkanSDK' >> "$GITHUB_ENV"+ echo 'C:\VulkanSDK\Bin' >> "$GITHUB_PATH"+ ;;+ *)+ echo "error: no Vulkan SDK provisioning for $RUNNER_OS" >&2+ exit 1+ ;;+ esac++ # Windows builds the engine the way upstream llama.cpp builds this exact+ # configuration: Ninja plus its own clang toolchain file. No developer+ # environment is set up for it -- clang locates the MSVC headers and+ # libraries itself, which an earlier run demonstrated by compiling all of+ # ggml without one. The image carries LLVM; ninja is not dependable.+ - name: Provision the Windows engine toolchain+ if: runner.os == 'Windows'+ shell: bash+ run: |+ if command -v ninja >/dev/null 2>&1; then+ echo "engine toolchain: ninja already on the image"+ else+ choco install ninja -y --no-progress+ echo "C:\ProgramData\chocolatey\bin" >> "$GITHUB_PATH"+ fi+ if command -v clang >/dev/null 2>&1; then+ echo "engine toolchain: clang already on the image"+ elif [ -x "/c/Program Files/LLVM/bin/clang.exe" ]; then+ echo "C:\Program Files\LLVM\bin" >> "$GITHUB_PATH"+ else+ choco install llvm -y --no-progress+ echo "C:\Program Files\LLVM\bin" >> "$GITHUB_PATH"+ fi+++ # Asserts the image, not the steps above: a mis-provisioned runner fails+ # here in seconds instead of five minutes into `make build`.+ - name: Verify the toolchain+ shell: bash+ run: make check-engine-toolchaindiff --git a/.github/workflows/engine-build.yml b/.github/workflows/engine-build.ymlnew file mode 100644index 000000000..89f41999f--- /dev/null+++ b/.github/workflows/engine-build.yml@@ -0,0 +1,186 @@+name: Engine Build+on:+ workflow_dispatch:+ push:+ tags:+ - 'v*'+ pull_request:+ branches:+ - dev+ paths:+ - .github/workflows/engine-build.yml+ - .github/actions/setup-engine-toolchain/action.yml+ - Makefile+ - src-tauri/build-utils/*engine*.sh+ - src-tauri/plugins/tauri-plugin-llamacpp/build.rs+ - src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml+ - src-tauri/plugins/tauri-plugin-llamacpp/src/engine/**+ - src-tauri/plugins/tauri-plugin-llamacpp/shim/**+ - src-tauri/plugins/tauri-plugin-llamacpp/src/bin/**++concurrency:+ group: engine-build-${{ github.ref }}+ cancel-in-progress: true++env:+ CARGO_TERM_COLOR: always++jobs:+ # rust-check.yml compiles this plugin with default features, which leave the+ # engine OFF -- so nothing there links llama.cpp, and a broken shim or build.rs+ # would first surface in a nightly desktop build. A PR gets the one cheapest+ # variant that still links the shim; the full per-vendor matrix is for a tag or+ # a manual run, where the wall clock of a CUDA plus HIP build is affordable.+ variants:+ name: Select variants+ runs-on: ubuntu-latest+ outputs:+ include: ${{ steps.select.outputs.include }}+ steps:+ - id: select+ shell: bash+ run: |+ pr='[+ {"name":"linux-x64-vulkan","variant":"vulkan","runs-on":"ubuntu-22-04"}+ ]'+ full='[+ {"name":"linux-x64-cuda13","variant":"cuda13-vulkan","runs-on":"ubuntu-22-04-cuda-13-0"},+ {"name":"linux-x64-cuda12","variant":"cuda12-vulkan","runs-on":"ubuntu-22-04-cuda-12-4"},+ {"name":"linux-x64-rocm","variant":"rocm-vulkan","runs-on":"ubuntu-22-04","rocm":true},+ {"name":"windows-x64-cuda13","variant":"cuda13-vulkan","runs-on":"windows-cuda-13-0"},+ {"name":"windows-x64-cuda12","variant":"cuda12-vulkan","runs-on":"windows-cuda-12-0"},+ {"name":"macos-arm64-metal","variant":"metal","runs-on":"macos-selfhosted-14-arm64"}+ ]'+ # Not in `full`, and each for a reason rather than an oversight:+ # linux-arm64-cuda13 no arm64 CUDA runner in the pool yet (sbsa+ # works, the label does not exist)+ # linux-arm64-vulkan same pool gap; nothing self-hosted is arm64+ # windows-arm64-vulkan windows-11-arm has no engine toolchain image+ # windows-x64-rocm no Windows HIP SDK image; ROCm on Windows is+ # an installer run, not an apt line+ if [ "${{ github.event_name }}" = "pull_request" ]; then+ echo "include=$(echo "$pr" | jq -c .)" >> "$GITHUB_OUTPUT"+ else+ echo "include=$(echo "$full" | jq -c .)" >> "$GITHUB_OUTPUT"+ fi++ worker:+ name: jan-llama-worker (${{ matrix.name }})+ needs: variants+ # Fork PRs must not reach this job: every runner label in the matrix is+ # self-hosted and persistent, and the job compiles `build.rs`, `shim/**`+ # and `engine/**` from the PR tip, then runs `sudo apt-get install`. A+ # build script is arbitrary code execution by construction, so a fork PR+ # touching this workflow's paths filter would get root on a box that later+ # hosts tag-time release builds. Same guard as+ # jan-tauri-build-nightly.yaml; `workflow_dispatch` and tag pushes are+ # unaffected because they are not `pull_request` events.+ if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository+ runs-on: ${{ matrix.runs-on }}+ strategy:+ fail-fast: false+ matrix:+ include: ${{ fromJson(needs.variants.outputs.include) }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6++ - uses: dtolnay/rust-toolchain@stable++ # The plugin depends on tauri, so building its binary needs the GUI+ # headers even though the worker itself has no window. Idempotent, and+ # a no-op on an image that already carries them.+ - name: Install Tauri dependencies+ if: runner.os == 'Linux'+ run: |+ sudo apt-get update+ sudo apt-get install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev++ # The CUDA images carry their own toolkit; no image in the pool carries+ # ROCm, so the one HIP job provisions it, guarded so a reprovisioned image+ # skips the apt work entirely. Mirrors llama.cpp's own menlo-build.yml.+ - name: Provision ROCm+ if: matrix.rocm && runner.os == 'Linux'+ run: |+ if command -v hipcc >/dev/null 2>&1; then+ echo "hipcc already on the image"+ else+ sudo mkdir --parents --mode=0755 /etc/apt/keyrings+ wget -qO- https://repo.radeon.com/rocm/rocm.gpg.key \+ | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg >/dev/null+ echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/${ROCM_VERSION} jammy main" \+ | sudo tee /etc/apt/sources.list.d/rocm.list+ printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' \+ | sudo tee /etc/apt/preferences.d/rocm-pin-600+ sudo apt-get update+ sudo apt-get install -y rocm-hip-sdk rocwmma-dev+ fi+ echo "HIPCXX=$(hipconfig -l)/clang" >> "$GITHUB_ENV"+ echo "HIP_PATH=$(hipconfig -R)" >> "$GITHUB_ENV"+ echo "/opt/rocm/bin" >> "$GITHUB_PATH"+ env:+ ROCM_VERSION: '7.2.1'++ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ matrix.variant }}++ - name: Build and stage the engine+ run: make build-engine++ # The only place the engine-gated code is type-checked at all. Every+ # suite under tests/ is `#![cfg(feature = "engine")]`, and both+ # rust-check.yml and `cargo test --lib` run with the feature off, so all+ # three currently report "0 passed; ok" -- three green suites that assert+ # nothing, over the whole FFI boundary in sys.rs. `--no-run` compiles+ # them without needing a model: the runtime half still wants+ # JAN_TEST_GGUF, but a suite that no longer builds now fails here instead+ # of passing vacuously. Cheap because `make build-engine` above already+ # built llama.cpp into the same target dir with the same features.+ - name: Compile the engine-gated test suites+ run: make check-engine-tests++ # --version proves the worker starts and resolves libggml through the+ # rpath; --list-devices additionally exercises the shim and the pinned+ # llama.cpp assert. Device enumeration is best-effort because a headless+ # runner has no ICD to report, and a CUDA runner may have no GPU at all.+ - name: Smoke-test the worker+ shell: bash+ run: |+ bin=src-tauri/resources/bin/jan-llama-worker+ if [ "$RUNNER_OS" = "Windows" ]; then+ bin="$bin.exe"+ fi+ ls -l src-tauri/resources/bin+ "./$bin" --version+ "./$bin" --list-devices || true++ # The bundle is universal but the engine build is host-arch, so name the+ # slice that is actually covered instead of shipping the gap silently.+ - name: Report the engine's architecture coverage+ if: runner.os == 'macOS'+ shell: bash+ run: |+ archs=$(lipo -archs src-tauri/resources/bin/jan-llama-worker)+ echo "jan-llama-worker: $archs"+ for want in x86_64 arm64; do+ case " $archs " in+ *" $want "*) ;;+ *) echo "::warning::jan-llama-worker has no $want slice, so local inference will not start on $want Macs" ;;+ esac+ done++ - name: Upload the engine+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: jan-llama-worker-${{ matrix.name }}+ path: src-tauri/resources/bin+ if-no-files-found: error++ - name: Upload the engine build log+ if: failure()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: engine-build-log-${{ matrix.name }}+ path: src-tauri/target/engine-build.log+ if-no-files-found: ignorediff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.ymlindex 6d6ea5765..55ef971e1 100644--- a/.github/workflows/jan-linter-and-test.yml+++ b/.github/workflows/jan-linter-and-test.yml@@ -90,20 +90,11 @@ jobs:- name: Install cargo-llvm-covuses: taiki-e/install-action@9e57365e36de1e26dea5145e57d471261468d9f7 # cargo-llvm-cov+ # The same script the coverage job uses. It stubs the engine worker and a+ # libggml* too, which the bundle config now requires and this inline copy+ # did not.- name: Create Tauri resource stubs for CI- run: |- TRIPLE=$(rustc -vV | awk '/^host:/ { print $2 }')- mkdir -p src-tauri/resources/bin src-tauri/resources/pre-install src-tauri/icons- touch src-tauri/resources/pre-install/.gitkeep- touch src-tauri/resources/LICENSE- touch src-tauri/resources/bin/jan-cli- for bin in uv bun; do- touch "src-tauri/resources/bin/${bin}-${TRIPLE}"- done- # Icons are gitignored; generate_context!() requires them at compile time- for icon in 32x32.png 128x128.png [email protected] icon.icns icon.ico; do- [ -f "src-tauri/icons/$icon" ] || cp src-tauri/icons/icon.png "src-tauri/icons/$icon"- done+ run: ./scripts/stub-tauri-resources.sh- name: Run Rust test coveragerun: |diff --git a/.github/workflows/template-tauri-build-linux-x64-external.yml b/.github/workflows/template-tauri-build-linux-x64-external.ymlindex fe92b746a..2c6c03948 100644--- a/.github/workflows/template-tauri-build-linux-x64-external.yml+++ b/.github/workflows/template-tauri-build-linux-x64-external.yml@@ -20,9 +20,25 @@ on:type: booleandefault: falsedescription: 'If true, builds both .deb and .appimage but disables auto-updater'+ runner:+ required: false+ type: string+ default: 'ubuntu-22.04'+ description: >+ Label of the runner to build on. A self-hosted label is what carries+ the engine toolchain; the default keeps the GitHub-hosted image, which+ only has enough for the vulkan variant.+ engine_variant:+ required: false+ type: string+ default: 'vulkan'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker: a `-` joined+ backend list, e.g. vulkan, cuda13-vulkan, rocm-vulkan. One CUDA major+ per bundle, so cuda12 and cuda13 are separate builds.jobs:build-linux-x64-external:- runs-on: ubuntu-22.04+ runs-on: ${{ inputs.runner }}steps:- name: Getting the repouses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6@@ -66,6 +82,15 @@ jobs:sudo apt updatesudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev libfuse2 libappindicator3-dev+ # `make build` compiles jan-llama-worker, which the deb and the AppImage+ # both bundle. The default variant is vulkan because it covers AMD, Intel+ # and NVIDIA through one driver-provided backend; a cuda or rocm variant+ # needs a caller-supplied runner that carries that toolkit.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Update app versionrun: |echo "Version: ${{ inputs.new_version }}"diff --git a/.github/workflows/template-tauri-build-linux-x64-flatpak.yml b/.github/workflows/template-tauri-build-linux-x64-flatpak.ymlindex f5857f647..ee0563409 100644--- a/.github/workflows/template-tauri-build-linux-x64-flatpak.yml+++ b/.github/workflows/template-tauri-build-linux-x64-flatpak.yml@@ -29,6 +29,22 @@ on:type: booleandefault: falsedescription: 'If true, builds both .deb and .appimage but disables auto-updater'+ runner:+ required: false+ type: string+ default: 'ubuntu-22.04'+ description: >+ Label of the runner to build on. A self-hosted label is what carries+ the engine toolchain; the default keeps the GitHub-hosted image, which+ only has enough for the vulkan variant.+ engine_variant:+ required: false+ type: string+ default: 'vulkan'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker: a `-` joined+ backend list, e.g. vulkan, cuda13-vulkan, rocm-vulkan. One CUDA major+ per bundle, so cuda12 and cuda13 are separate builds.secrets:DELTA_AWS_S3_BUCKET_NAME:required: false@@ -44,7 +60,7 @@ on:required: falsejobs:build-linux-x64:- runs-on: ubuntu-22.04+ runs-on: ${{ inputs.runner }}permissions:contents: writesteps:@@ -84,6 +100,14 @@ jobs:sudo apt updatesudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev libfuse2 libappindicator3-dev+ # `make build` compiles jan-llama-worker into the deb this job produces.+ # Vulkan is also the only backend Flathub's own builders can produce, so+ # the two Linux paths ship the same engine.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Update app version base public_providerrun: |echo "Version: ${{ inputs.new_version }}"diff --git a/.github/workflows/template-tauri-build-linux-x64.yml b/.github/workflows/template-tauri-build-linux-x64.ymlindex 0851bdb1e..538514b6f 100644--- a/.github/workflows/template-tauri-build-linux-x64.yml+++ b/.github/workflows/template-tauri-build-linux-x64.yml@@ -33,6 +33,22 @@ on:type: booleandefault: falsedescription: 'If true, builds both .deb and .appimage but disables auto-updater'+ runner:+ required: false+ type: string+ default: 'ubuntu-22.04'+ description: >+ Label of the runner to build on. A self-hosted label is what carries+ the engine toolchain; the default keeps the GitHub-hosted image, which+ only has enough for the vulkan variant.+ engine_variant:+ required: false+ type: string+ default: 'vulkan'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker: a `-` joined+ backend list, e.g. vulkan, cuda13-vulkan, rocm-vulkan. One CUDA major+ per bundle, so cuda12 and cuda13 are separate builds.secrets:DELTA_AWS_S3_BUCKET_NAME:required: false@@ -55,7 +71,7 @@ on:value: ${{ jobs.build-linux-x64.outputs.APPIMAGE_FILE_NAME }}jobs:build-linux-x64:- runs-on: ubuntu-22.04+ runs-on: ${{ inputs.runner }}outputs:DEB_SIG: ${{ steps.packageinfo.outputs.DEB_SIG }}APPIMAGE_SIG: ${{ steps.packageinfo.outputs.APPIMAGE_SIG }}@@ -105,6 +121,15 @@ jobs:sudo apt updatesudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev libfuse2 libappindicator3-dev+ # `make build` compiles jan-llama-worker, which the deb and the AppImage+ # both bundle. The default variant is vulkan because it covers AMD, Intel+ # and NVIDIA through one driver-provided backend; a cuda or rocm variant+ # needs a caller-supplied runner that carries that toolkit.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Update app version base public_providerrun: |echo "Version: ${{ inputs.new_version }}"@@ -203,6 +228,37 @@ jobs:TAURI_TRAY: libappindicator3# Publish app+ # tauri reports a linuxdeploy failure as `failed to run linuxdeploy` and+ # discards its output, so ask the tool itself. `--version` alone separates+ # the two candidates: a tool that cannot run at all is an AppImage that+ # could not mount, anything else is the AppDir it was handed.+ - name: Diagnose the AppImage bundler+ if: failure()+ run: |+ tool=$(ls .cache/tauri/linuxdeploy-*-x86_64.AppImage 2>/dev/null | head -1)+ [ -n "$tool" ] || { echo "linuxdeploy was never downloaded"; exit 0; }+ echo "--- does linuxdeploy run at all?"+ "$tool" --version || echo "it does not: an AppImage that cannot mount is the usual reason"+ appdir=$(ls -d src-tauri/target/release/bundle/appimage/*.AppDir 2>/dev/null | head -1)+ [ -n "$appdir" ] || { echo "no AppDir left behind; the build failed before bundling"; exit 0; }+ echo "--- engine binaries tauri staged into the AppDir"+ find "$appdir" \( -name '*.so*' -o -name 'jan-llama-worker' \) | head -40+ echo "--- linuxdeploy over that AppDir"+ "$tool" --appdir "$appdir" || true+ env:+ APPIMAGE_EXTRACT_AND_RUN: '1'++ # The engine build is fifteen minutes of cmake whose output cargo only+ # surfaces as a tail. When it fails, the whole log is the artifact worth+ # having.+ - name: Upload the engine build log+ if: failure()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: engine-build-log-linux-x64+ path: src-tauri/target/engine-build.log+ if-no-files-found: ignore+## Artifacts, for dev and test- name: Upload Artifactif: inputs.public_provider != 'github'diff --git a/.github/workflows/template-tauri-build-macos-external.yml b/.github/workflows/template-tauri-build-macos-external.ymlindex efd291d22..3ef151856 100644--- a/.github/workflows/template-tauri-build-macos-external.yml+++ b/.github/workflows/template-tauri-build-macos-external.yml@@ -15,9 +15,24 @@ on:type: stringdefault: 'nightly'description: 'The channel to use for this job'+ runner:+ required: false+ type: string+ default: 'macos-latest'+ description: >+ Label of the runner to build on. A self-hosted arm64 label is what+ carries the engine toolchain; the default keeps the GitHub-hosted+ image, where Xcode alone is enough for the metal variant.+ engine_variant:+ required: false+ type: string+ default: 'metal'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker. Metal is the only+ backend worth shipping on macOS.jobs:build-macos-external:- runs-on: macos-latest+ runs-on: ${{ inputs.runner }}steps:- name: Getting the repouses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6@@ -104,6 +119,14 @@ jobs:yarn --versionyarn config set -H enableImmutableInstalls false+ # `make build` compiles jan-llama-worker, which the dmg bundles. Metal is+ # the only backend worth shipping on macOS, and it needs nothing beyond+ # Xcode.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Build apprun: |make build@@ -111,6 +134,20 @@ jobs:NODE_OPTIONS: "--max-old-space-size=4196"APP_PATH: '.'+ # The bundle is universal but the engine build is host-arch, so name the+ # slice that is actually covered instead of shipping the gap silently.+ - name: Report the engine's architecture coverage+ shell: bash+ run: |+ archs=$(lipo -archs src-tauri/resources/bin/jan-llama-worker)+ echo "jan-llama-worker: $archs"+ for want in x86_64 arm64; do+ case " $archs " in+ *" $want "*) ;;+ *) echo "::warning::jan-llama-worker has no $want slice, so local inference will not start on $want Macs" ;;+ esac+ done+- name: Upload Artifactuses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:diff --git a/.github/workflows/template-tauri-build-macos.yml b/.github/workflows/template-tauri-build-macos.ymlindex cb497798a..887db6652 100644--- a/.github/workflows/template-tauri-build-macos.yml+++ b/.github/workflows/template-tauri-build-macos.yml@@ -28,6 +28,21 @@ on:type: stringdefault: 'nightly'description: 'The channel to use for this job'+ runner:+ required: false+ type: string+ default: 'macos-latest'+ description: >+ Label of the runner to build on. A self-hosted arm64 label is what+ carries the engine toolchain; the default keeps the GitHub-hosted+ image, where Xcode alone is enough for the metal variant.+ engine_variant:+ required: false+ type: string+ default: 'metal'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker. Metal is the only+ backend worth shipping on macOS.secrets:DELTA_AWS_S3_BUCKET_NAME:required: false@@ -63,7 +78,7 @@ on:jobs:build-macos:- runs-on: macos-latest+ runs-on: ${{ inputs.runner }}outputs:MAC_UNIVERSAL_SIG: ${{ steps.metadata.outputs.MAC_UNIVERSAL_SIG }}FILE_NAME: ${{ steps.metadata.outputs.FILE_NAME }}@@ -180,11 +195,21 @@ jobs:yarn --versionyarn config set -H enableImmutableInstalls false+ # `make build` compiles jan-llama-worker, which the dmg bundles. Metal is+ # the only backend worth shipping on macOS, and it needs nothing beyond+ # Xcode, so this runs on the GitHub-hosted image unless a caller says+ # otherwise.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Build apprun: |make buildenv:NODE_OPTIONS: "--max-old-space-size=4196"+ JAN_ENGINE_REQUIRE_SIGNING: '1'GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}APP_PATH: '.'POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}@@ -198,6 +223,62 @@ jobs:TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}+ # The engine build is fifteen minutes of cmake whose output cargo only+ # surfaces as a tail. When it fails, the whole log is the artifact worth+ # having.+ - name: Upload the engine build log+ if: failure()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: engine-build-log-macos+ path: src-tauri/target/engine-build.log+ if-no-files-found: ignore++ # The bundle is universal but the engine build is host-arch, so name the+ # slice that is actually covered instead of shipping the gap silently.+ - name: Report the engine's architecture coverage+ shell: bash+ run: |+ archs=$(lipo -archs src-tauri/resources/bin/jan-llama-worker)+ echo "jan-llama-worker: $archs"+ for want in x86_64 arm64; do+ case " $archs " in+ *" $want "*) ;;+ *) echo "::warning::jan-llama-worker has no $want slice, so local inference will not start on $want Macs" ;;+ esac+ done++ # Tauri signs the .app and notarizes the dmg, but nothing in that path+ # would notice an unsigned nested binary until a user's Gatekeeper did.+ - name: Verify the signed and notarized bundle+ shell: bash+ run: |+ bundle=$(find src-tauri/target/universal-apple-darwin/release/bundle/macos -maxdepth 1 -name '*.app' | head -1)+ echo "Verifying $bundle"+ codesign --verify --deep --strict --verbose=2 "$bundle"+ worker=$(find "$bundle/Contents/Resources" -name jan-llama-worker | head -1)+ if [ -z "$worker" ]; then+ echo "error: no jan-llama-worker inside $bundle" >&2+ exit 1+ fi+ codesign --verify --strict "$worker"++ # tauri notarizes and staples the .app, then builds the dmg around it,+ # so the dmg carries no ticket of its own -- requiring one there+ # failed a build whose app was notarized and Accepted. Either side+ # having a ticket proves the submission happened; neither does not.+ dmg=$(find src-tauri/target/universal-apple-darwin/release/bundle/dmg -maxdepth 1 -name '*.dmg' | head -1)+ if xcrun stapler validate "$bundle"; then+ echo "the .app carries its notarization ticket"+ elif [ -n "$dmg" ] && xcrun stapler validate "$dmg"; then+ echo "the .dmg carries its notarization ticket"+ else+ echo "error: neither the .app nor the dmg has a stapled ticket" >&2+ exit 1+ fi+ # What Gatekeeper actually runs against the app the user launches.+ spctl --assess --type exec --verbose=2 "$bundle"+# Publish app## Artifacts, for dev and testdiff --git a/.github/workflows/template-tauri-build-windows-x64-external.yml b/.github/workflows/template-tauri-build-windows-x64-external.ymlindex 1a18c83f1..4b05207f5 100644--- a/.github/workflows/template-tauri-build-windows-x64-external.yml+++ b/.github/workflows/template-tauri-build-windows-x64-external.yml@@ -15,9 +15,25 @@ on:type: stringdefault: 'nightly'description: 'The channel to use for this job'+ runner:+ required: false+ type: string+ default: 'windows-latest'+ description: >+ Label of the runner to build on. A self-hosted label is what carries+ the engine toolchain; the default keeps the GitHub-hosted image, which+ only has enough for the vulkan variant.+ engine_variant:+ required: false+ type: string+ default: 'vulkan'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker: a `-` joined+ backend list, e.g. vulkan, cuda13-vulkan, rocm-vulkan. One CUDA major+ per bundle, so cuda12 and cuda13 are separate builds.jobs:build-windows-x64-external:- runs-on: windows-latest+ runs-on: ${{ inputs.runner }}steps:- name: Getting the repouses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6@@ -156,6 +172,14 @@ jobs:yarn --versionyarn config set -H enableImmutableInstalls false+ # `make build` compiles jan-llama-worker, which the NSIS and MSI bundles+ # both carry. Vulkan covers AMD, Intel and NVIDIA here through one+ # driver-provided backend; a CUDA variant needs a toolkit on the runner.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Build appshell: bashrun: |diff --git a/.github/workflows/template-tauri-build-windows-x64.yml b/.github/workflows/template-tauri-build-windows-x64.ymlindex 7e10accf1..2bd494b1b 100644--- a/.github/workflows/template-tauri-build-windows-x64.yml+++ b/.github/workflows/template-tauri-build-windows-x64.yml@@ -28,6 +28,26 @@ on:type: stringdefault: 'nightly'description: 'The channel to use for this job'+ runner:+ required: false+ type: string+ default: 'windows-2025'+ description: >+ Label of the runner to build on. A self-hosted label is what carries+ the engine toolchain; the default keeps a GitHub-hosted image, which+ has enough for the vulkan variant. Pinned rather than+ `windows-latest` for reproducibility only -- it does not choose a+ Visual Studio version: this label resolves to `windows-2025-vs2026`+ too, which is why the engine build asks for Ninja rather than trying+ to make the Visual Studio generator work.+ engine_variant:+ required: false+ type: string+ default: 'vulkan'+ description: >+ JAN_ENGINE_VARIANT for the bundled jan-llama-worker: a `-` joined+ backend list, e.g. vulkan, cuda13-vulkan, rocm-vulkan. One CUDA major+ per bundle, so cuda12 and cuda13 are separate builds.secrets:DELTA_AWS_S3_BUCKET_NAME:required: false@@ -63,7 +83,7 @@ on:jobs:build-windows-x64:- runs-on: windows-latest+ runs-on: ${{ inputs.runner }}outputs:WIN_SIG: ${{ steps.metadata.outputs.WIN_SIG }}FILE_NAME: ${{ steps.metadata.outputs.FILE_NAME }}@@ -224,12 +244,22 @@ jobs:yarn --versionyarn config set -H enableImmutableInstalls false+ # `make build` compiles jan-llama-worker, which the NSIS and MSI bundles+ # both carry. The default variant is vulkan, which covers AMD, Intel and+ # NVIDIA through one driver-provided backend; a cuda variant needs a+ # caller-supplied runner that carries the toolkit.+ - name: Set up the llama.cpp engine toolchain+ uses: ./.github/actions/setup-engine-toolchain+ with:+ variant: ${{ inputs.engine_variant }}+- name: Build appshell: bashrun: |make buildenv:AZURE_KEY_VAULT_URI: ${{ secrets.AZURE_KEY_VAULT_URI }}+ JAN_ENGINE_REQUIRE_SIGNING: '1'AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}@@ -245,6 +275,17 @@ jobs:TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}+ # The engine build is fifteen minutes of cmake whose output cargo only+ # surfaces as a tail. When it fails, the whole log is the artifact worth+ # having.+ - name: Upload the engine build log+ if: failure()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: engine-build-log-windows-x64+ path: src-tauri/target/engine-build.log+ if-no-files-found: ignore+- name: Upload NSIS Installer Artifactuses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:diff --git a/.gitignore b/.gitignoreindex 4c2741869..77e721941 100644--- a/.gitignore+++ b/.gitignore@@ -72,3 +72,7 @@ llm-docs.claude/agents.claudeCLAUDE.md++# Vendored llama.cpp: a shallow clone of the pinned tag, fetched by+# `make engine-source`. Never committed -- the pin lives in build.rs.+src-tauri/plugins/tauri-plugin-llamacpp/vendor/diff --git a/Makefile b/Makefileindex 03843b4f2..7c32a39fc 100644--- a/Makefile+++ b/Makefile@@ -13,7 +13,18 @@ elseDETECTED_OS := $(shell uname -s)endif+# On Windows make runs recipes through cmd.exe -- unless an sh.exe is on PATH,+# which is every Git Bash and MSYS invocation, CI included. The two share no+# spelling for mkdir or for a one-off environment variable, and the OS alone+# cannot tell them apart, so the shell make picked is what the Windows-only+# recipes have to branch on.ifeq ($(OS),Windows_NT)+ RECIPE_SHELL_IS_CMD := $(if $(filter sh sh.exe bash bash.exe,$(notdir $(SHELL))),,yes)+else+ RECIPE_SHELL_IS_CMD :=+endif++ifeq ($(RECIPE_SHELL_IS_CMD),yes)MKDIR = if not exist "$(1)" mkdir "$(1)"elseMKDIR = mkdir -p $(1)@@ -65,8 +76,9 @@ install-ios-rust-targets:dev: install-and-buildyarn download:bin- make build-mlx-server-if-exists- make build-cli-dev+ $(MAKE) build-mlx-server-if-exists+ $(MAKE) build-cli-dev+ $(MAKE) build-engine-dev-if-possibleyarn dev# Web application targets@@ -141,8 +153,8 @@ test-rust:test: test-prepare install-rust-targetsyarn build:mlx-server- make build-cli- make test-rust+ $(MAKE) build-cli+ $(MAKE) test-rust# Placeholders for the binaries test-ci no longer builds. Each platform's# tauri.<os>.conf.json declares these under bundle.resources, and@@ -150,21 +162,35 @@ test: test-prepare install-rust-targets# but it only checks existence, and no test executes them. Guarded with -e so# we never clobber a real local build or churn the cargo:rerun-if-changed# stamps these paths emit.+#+# The PowerShell arm is for cmd.exe only. CI runs make from a bash step, where+# sh expands `$f`/`$p` to nothing before PowerShell ever sees them; the `-`+# prefix then swallowed the syntax error and the stubs were silently never+# created, so the app's build script failed on a missing resource instead.stub-resources:-ifeq ($(DETECTED_OS),Windows)- -powershell -Command "New-Item -ItemType Directory -Force -Path src-tauri/resources/bin | Out-Null; if (-not (Test-Path 'src-tauri/resources/bin/jan-cli.exe')) { New-Item -ItemType File -Path 'src-tauri/resources/bin/jan-cli.exe' | Out-Null }"+ifeq ($(RECIPE_SHELL_IS_CMD),yes)+ -powershell -Command "New-Item -ItemType Directory -Force -Path src-tauri/resources/bin | Out-Null; foreach ($$f in @('jan-cli.exe','jan-llama-worker.exe','ggml-base.dll')) { $$p = Join-Path 'src-tauri/resources/bin' $$f; if (-not (Test-Path $$p)) { New-Item -ItemType File -Path $$p | Out-Null } }"+else ifeq ($(DETECTED_OS),Windows)+ @mkdir -p src-tauri/resources/bin+ @[ -e src-tauri/resources/bin/jan-cli.exe ] || touch src-tauri/resources/bin/jan-cli.exe+ @[ -e src-tauri/resources/bin/jan-llama-worker.exe ] || touch src-tauri/resources/bin/jan-llama-worker.exe+ @ls src-tauri/resources/bin/ggml*.dll >/dev/null 2>&1 || touch src-tauri/resources/bin/ggml-base.dllelse ifeq ($(DETECTED_OS),Darwin)@mkdir -p src-tauri/resources/bin@[ -e src-tauri/resources/bin/jan-cli ] || touch src-tauri/resources/bin/jan-cli@[ -e src-tauri/resources/bin/mlx-server ] || touch src-tauri/resources/bin/mlx-server@[ -e src-tauri/resources/bin/mlx-swift_Cmlx.bundle ] || mkdir -p src-tauri/resources/bin/mlx-swift_Cmlx.bundle+ @[ -e src-tauri/resources/bin/jan-llama-worker ] || touch src-tauri/resources/bin/jan-llama-worker+ @ls src-tauri/resources/bin/libggml*.dylib >/dev/null 2>&1 || touch src-tauri/resources/bin/libggml-base.dylibelse@mkdir -p src-tauri/resources/bin@[ -e src-tauri/resources/bin/jan-cli ] || touch src-tauri/resources/bin/jan-cli+ @[ -e src-tauri/resources/bin/jan-llama-worker ] || touch src-tauri/resources/bin/jan-llama-worker+ @ls src-tauri/resources/bin/libggml*.so* >/dev/null 2>&1 || touch src-tauri/resources/bin/libggml-base.soendiftest-ci: test-prepare stub-resources- make test-rust+ $(MAKE) test-rust# Cheap compile guard for the CLI feature set, covering what test-ci no longer# builds. `make build` still builds the real binary on every platform.@@ -262,6 +288,246 @@ elsecp src-tauri/target/release/jan-cli src-tauri/resources/bin/jan-cliendif+# ---------------------------------------------------------------------------+# llama.cpp engine worker+#+# JAN_ENGINE_VARIANT picks the GPU backends compiled into the worker. Vulkan is+# in every variant, not just the default: it is the fallback when the CUDA or+# ROCm runtime turns out to be missing or too old on the user's machine, and+# ggml chooses between the registered backends at runtime.+#+# The CPU backend is always multi-versioned (GGML_CPU_ALL_VARIANTS), so every+# variant ships the full set of x86-64/ARM microarchitecture modules and ggml+# scores them at load time. That is what "common CPUs" means here.+#+# The variant is a `-` separated list of backends, so a shipping build names+# every backend it carries and one worker covers the machine it lands on:+#+# vulkan (default) vulkan+# cuda13 cuda + vulkan (needs CUDA 13 toolkit on PATH)+# cuda12 cuda + vulkan (needs CUDA 12 toolkit on PATH)+# rocm hip + vulkan (needs ROCm/HIP)+# cuda13-hip-vulkan all three (needs the CUDA and the HIP toolkit)+#+# cuda12 and cuda13 cannot be combined: the CUDA major is whichever nvcc is on+# PATH, one toolkit per configure, and both emit libggml-cuda.so.+#+# CUDA 12 vs 13 is not a cmake flag -- it is whichever nvcc is found, and+# llama.cpp adapts CMAKE_CUDA_ARCHITECTURES to it on its own (ggml-cuda's+# CMakeLists only adds the 50/61/70 virtual archs below CUDA 13). They are still+# separate variants because the resulting binaries cover different GPUs, so+# check-engine-toolchain asserts the toolkit matches the variant name rather+# than letting a cuda13 build ship labelled cuda12.+COMMA := ,+SPACE := $(subst ,, )+JAN_ENGINE_VARIANT ?= vulkan++# Shipping builds pair Vulkan with CUDA/ROCm so the app still offloads when the+# vendor runtime turns out to be missing or too old. That needs the Vulkan SDK,+# which a developer with only a CUDA toolkit has no reason to install, so it can+# be dropped locally. Never drop it for a release: the fallback is the point.+JAN_ENGINE_VULKAN_FALLBACK ?= 1++# Overrides the GPU architectures a CUDA build targets. Empty means upstream's+# own list, which covers discrete desktop/datacenter parts (75/80/86/89/90, plus+# 50/61/70 below CUDA 13) but has NO Jetson entry -- Orin is sm_87 and Xavier+# sm_72. Set it for an ARM/Jetson target, or to trim a build to one known GPU:+# make build-engine JAN_ENGINE_VARIANT=cuda13 JAN_ENGINE_CUDA_ARCHS=87+# make build-engine JAN_ENGINE_VARIANT=cuda13 JAN_ENGINE_CUDA_ARCHS=86-real+JAN_ENGINE_CUDA_ARCHS ?=+export JAN_ENGINE_CUDA_ARCHS++# One token to one cargo feature. `engine` alone is the CPU-only worker, and it+# is implied by every other feature, so `cpu` maps to it and the GPU tokens do+# not have to name it.+ENGINE_TOKENS := $(subst -, ,$(JAN_ENGINE_VARIANT))+ENGINE_FEATURE_cpu := engine+ENGINE_FEATURE_vulkan := engine-vulkan+ENGINE_FEATURE_metal := engine-metal+ENGINE_FEATURE_cuda12 := engine-cuda+ENGINE_FEATURE_cuda13 := engine-cuda+ENGINE_FEATURE_hip := engine-hip+ENGINE_FEATURE_rocm := engine-hip++ENGINE_UNKNOWN_TOKENS := $(strip $(foreach t,$(ENGINE_TOKENS),$(if $(ENGINE_FEATURE_$(t)),,$(t))))+ifneq ($(ENGINE_UNKNOWN_TOKENS),)+ $(error Unknown JAN_ENGINE_VARIANT '$(JAN_ENGINE_VARIANT)': no backend named '$(ENGINE_UNKNOWN_TOKENS)'. Tokens are cpu, vulkan, metal, cuda12, cuda13, hip/rocm, joined by '-')+endif+ifneq ($(word 2,$(filter cuda12 cuda13,$(ENGINE_TOKENS))),)+ $(error JAN_ENGINE_VARIANT '$(JAN_ENGINE_VARIANT)' names more than one CUDA major, which one build cannot carry)+endif++# The fallback adds vulkan whenever a vendor runtime is in play and the variant+# did not already ask for it. $(sort) dedupes, so naming vulkan twice is+# harmless and the feature list is deterministic.+ENGINE_VENDOR_FEATURES := $(filter engine-cuda engine-hip,$(foreach t,$(ENGINE_TOKENS),$(ENGINE_FEATURE_$(t))))+ENGINE_FEATURE_LIST := $(sort $(foreach t,$(ENGINE_TOKENS),$(ENGINE_FEATURE_$(t))) \+ $(if $(ENGINE_VENDOR_FEATURES),$(if $(filter 1,$(JAN_ENGINE_VULKAN_FALLBACK)),engine-vulkan,),))+ENGINE_FEATURES := $(subst $(SPACE),$(COMMA),$(ENGINE_FEATURE_LIST))++ENGINE_PLUGIN_DIR := src-tauri/plugins/tauri-plugin-llamacpp+ENGINE_BIN_DIR := src-tauri/resources/bin++# cmake and nvcc output goes here, and is tailed live while cargo runs -- cargo+# captures a build script's output and only shows it on failure, so without this+# a fifteen-minute engine build prints nothing and looks hung. Kept afterwards+# as the artifact to attach to a build report.+ENGINE_BUILD_LOG := $(CURDIR)/src-tauri/target/engine-build.log+export JAN_ENGINE_BUILD_LOG := $(ENGINE_BUILD_LOG)++# Parallelism for the engine build only.+#+# `make -j2` alone does NOT reach cmake: build.rs reads NUM_JOBS, which *cargo*+# sets from its own parallelism, and cargo ignores make's jobserver for that+# purpose -- it defaults to num_cpus. So `make -j2` silently built 8-wide and+# passed cmake -j8. Translating make's own -j into CARGO_BUILD_JOBS makes the+# flag mean what it says.+#+# Scoped to the engine rather than exported globally, because an 8-way nvcc+# build is the memory spike worth limiting; throttling the 1,200-crate app build+# to match would just make everything slower.+#+# JAN_ENGINE_JOBS overrides both, for limiting the engine without touching the+# rest of the tree:+# make build-engine JAN_ENGINE_VARIANT=cuda13 JAN_ENGINE_JOBS=2+#+# A bare `make -j` (unlimited) yields an empty value and falls through to+# cargo's default, which is the right reading of "no limit".+# Deferred (`=`, not `:=`) on purpose: make puts -j into MAKEFLAGS only when it+# runs a recipe, not while parsing the makefile, so a simple assignment reads an+# empty value and the limit is silently lost -- the exact failure this is meant+# to fix. `--jobserver-auth=...` does not match `-j%` (it starts `--`).+MAKE_J = $(strip $(patsubst -j%,%,$(filter -j%,$(MAKEFLAGS))))+JAN_ENGINE_JOBS ?= $(MAKE_J)+ENGINE_CARGO_JOBS = $(if $(JAN_ENGINE_JOBS),CARGO_BUILD_JOBS=$(JAN_ENGINE_JOBS),)+# cmd.exe has no `VAR=value command` prefix, so the same limit is set with `set`+# there. The Windows recipes still run under sh when one is on PATH, where the+# prefix form is the only one that works.+ENGINE_CARGO_JOBS_WIN = $(if $(RECIPE_SHELL_IS_CMD),$(if $(JAN_ENGINE_JOBS),set CARGO_BUILD_JOBS=$(JAN_ENGINE_JOBS)&&,),$(ENGINE_CARGO_JOBS))++# cargo also finds the jobserver in MAKEFLAGS and tries to join it, but a recipe+# line make did not mark recursive never inherits its file descriptors, so cargo+# warns and falls back on every build. An empty CARGO_MAKEFLAGS takes precedence+# over MAKEFLAGS and reads as "no jobserver", which is the truth here:+# parallelism reaches cargo as CARGO_BUILD_JOBS above, and build.rs sizes+# cmake -j from the NUM_JOBS cargo derives from it.+export CARGO_MAKEFLAGS :=++# Streams the build log while $(1) runs, then stops the tail either way. Unix+# only -- the Windows recipes run cargo straight, so cmake output there arrives+# in cargo's own failure dump rather than live.+# `tail -F` tolerates the file not existing yet; the trap covers a cargo failure+# and a Ctrl-C so no reader is left behind.+define with_engine_log+ @mkdir -p $(dir $(ENGINE_BUILD_LOG))+ @: > $(ENGINE_BUILD_LOG)+ @tail -F -n +1 $(ENGINE_BUILD_LOG) 2>/dev/null | sed 's/^/[engine] /' & \+ tail_pid=$$!; \+ trap 'kill $$tail_pid 2>/dev/null || true' EXIT INT TERM; \+ $(1); \+ rc=$$?; \+ sleep 1; \+ kill $$tail_pid 2>/dev/null || true; \+ exit $$rc+endef++# `make dev` must not require a GPU toolchain: a contributor working on the UI+# has no reason to install the Vulkan SDK or CUDA, so the default variant skips+# rather than blocks.+#+# But a variant asked for *explicitly* is a request, not a default -- silently+# skipping it would leave someone waiting for an engine that was never built.+# `origin` distinguishes the two: `file` means the `?=` default below, anything+# else means the caller named it.+ENGINE_VARIANT_EXPLICIT := $(if $(filter-out file,$(origin JAN_ENGINE_VARIANT)),yes,)++build-engine-dev-if-possible:+ifeq ($(DETECTED_OS),Windows)+ @echo "Building the llama.cpp engine (skipped if the toolchain is incomplete)"+ -$(MAKE) build-engine-dev+else+ @if out=$$($(MAKE) --no-print-directory check-engine-toolchain 2>&1); then \+ $(MAKE) --no-print-directory build-engine-dev; \+ elif [ -n "$(ENGINE_VARIANT_EXPLICIT)" ]; then \+ echo "$$out" >&2; \+ echo "" >&2; \+ echo "You asked for JAN_ENGINE_VARIANT=$(JAN_ENGINE_VARIANT) explicitly, so this is a" >&2; \+ echo "hard failure rather than a skip. Note that PATH changes must be in the" >&2; \+ echo "same shell as make, e.g.:" >&2; \+ echo " PATH=/usr/local/cuda-13/bin:\$$PATH make dev JAN_ENGINE_VARIANT=$(JAN_ENGINE_VARIANT)$(if $(filter 1,$(JAN_ENGINE_VULKAN_FALLBACK)), JAN_ENGINE_VULKAN_FALLBACK=0,)" >&2; \+ exit 1; \+ else \+ echo "=============================================================="; \+ echo "Skipping the llama.cpp engine -- toolchain incomplete:"; \+ echo "$$out" | sed 's/^/ /'; \+ echo ""; \+ echo "Local models will not run. Cloud providers are unaffected."; \+ echo "To build one, name a variant you have the toolchain for:"; \+ echo " make build-engine-dev JAN_ENGINE_VARIANT=cpu"; \+ echo "=============================================================="; \+ fi+endif++# The vendored llama.cpp. The pin itself lives in build.rs and is read by+# fetch-engine-source.sh, so there is exactly one source of truth for it.+ENGINE_SRC_DIR := $(ENGINE_PLUGIN_DIR)/vendor/llama.cpp++engine-source:+ bash src-tauri/build-utils/fetch-engine-source.sh++# Drops the vendored clone. A `clean` prerequisite rather than part of its+# recipe so it runs *before* clean's `find . -name build -type d` sweeps the+# tree -- otherwise those walk the whole llama.cpp checkout on the way to+# deleting it.+clean-engine-source:+ifeq ($(DETECTED_OS),Windows)+ -powershell -Command "if (Test-Path '$(ENGINE_SRC_DIR)') { Remove-Item -Recurse -Force '$(ENGINE_SRC_DIR)' }"+else+ rm -rf $(ENGINE_SRC_DIR)+endif++check-engine-toolchain:+ bash src-tauri/build-utils/check-engine-toolchain.sh $(JAN_ENGINE_VARIANT) $(ENGINE_FEATURES)++# Release worker plus the ggml runtime it loads.+build-engine: engine-source check-engine-toolchain+ @echo "Building llama.cpp engine worker (variant: $(JAN_ENGINE_VARIANT), features: $(ENGINE_FEATURES), jobs: $(if $(JAN_ENGINE_JOBS),$(JAN_ENGINE_JOBS),all cores))"+ $(call MKDIR,'$(ENGINE_BIN_DIR)')+ifeq ($(DETECTED_OS),Windows)+ cd $(ENGINE_PLUGIN_DIR) && $(ENGINE_CARGO_JOBS_WIN) cargo build --release --features $(ENGINE_FEATURES) --bin jan-llama-worker+ bash src-tauri/build-utils/stage-engine.sh release+else+ $(call with_engine_log,cd $(ENGINE_PLUGIN_DIR) && $(ENGINE_CARGO_JOBS) cargo build --release --features $(ENGINE_FEATURES) --bin jan-llama-worker)+ bash src-tauri/build-utils/stage-engine.sh release+endif+ bash src-tauri/build-utils/sign-engine.sh++# Type-checks and links the engine-gated test suites without running them.+#+# Every suite under tests/ is `#![cfg(feature = "engine")]`, and both+# rust-check.yml and a plain `cargo test --lib` run with the feature off, so all+# three report "0 passed; ok" -- green suites that assert nothing, over the whole+# FFI boundary. `--no-run` is the part that needs no model: the runtime half+# still wants JAN_TEST_GGUF, but a suite that stops compiling now fails loudly+# instead of passing vacuously. Depends on the same toolchain check as+# build-engine, and reuses ENGINE_FEATURES so it cannot drift from what the+# worker is built with.+check-engine-tests: engine-source check-engine-toolchain+ @echo "Compiling engine test suites (variant: $(JAN_ENGINE_VARIANT), features: $(ENGINE_FEATURES))"+ cd $(ENGINE_PLUGIN_DIR) && cargo test --features $(ENGINE_FEATURES) --no-run++# Debug worker for local dev. Same staging, so `make dev` behaves like a bundle.+build-engine-dev: engine-source check-engine-toolchain+ @echo "Building llama.cpp engine worker (dev, variant: $(JAN_ENGINE_VARIANT), jobs: $(if $(JAN_ENGINE_JOBS),$(JAN_ENGINE_JOBS),all cores))"+ $(call MKDIR,'$(ENGINE_BIN_DIR)')+ifeq ($(DETECTED_OS),Windows)+ cd $(ENGINE_PLUGIN_DIR) && $(ENGINE_CARGO_JOBS_WIN) cargo build --features $(ENGINE_FEATURES) --bin jan-llama-worker+ bash src-tauri/build-utils/stage-engine.sh debug+else+ $(call with_engine_log,cd $(ENGINE_PLUGIN_DIR) && $(ENGINE_CARGO_JOBS) cargo build --features $(ENGINE_FEATURES) --bin jan-llama-worker)+ bash src-tauri/build-utils/stage-engine.sh debug+endif+# Debug build for local dev (faster, native arch only)build-cli-dev:$(call MKDIR,'src-tauri/resources/bin')@@ -274,9 +540,10 @@ endif# Buildbuild: install-and-build install-rust-targets+ $(MAKE) build-engineyarn build-clean:+clean: clean-engine-sourceifeq ($(DETECTED_OS),Windows)-powershell -Command "Get-ChildItem -Path . -Include node_modules, .next, dist, build, out, .turbo, .yarn -Recurse -Directory | Remove-Item -Recurse -Force"-powershell -Command "Get-ChildItem -Path . -Include package-lock.json, tsconfig.tsbuildinfo -Recurse -File | Remove-Item -Recurse -Force"diff --git a/core/src/browser/extensions/engines/AIEngine.test.ts b/core/src/browser/extensions/engines/AIEngine.test.tsindex 192143376..7d8bc4626 100644--- a/core/src/browser/extensions/engines/AIEngine.test.ts+++ b/core/src/browser/extensions/engines/AIEngine.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, vi } from 'vitest'-import { AIEngine } from './AIEngine'+import { AIEngine, isEmbeddingEngine } from './AIEngine'import { events } from '../../events'import { ModelEvent, Model } from '../../../types'@@ -84,3 +84,30 @@ describe('AIEngine', () => {expect(result).toEqual([])})})++describe('isEmbeddingEngine', () => {+ const full = {+ embed: async () => ({ data: [] }),+ getEmbeddingContextSize: async () => 512,+ countEmbeddingTokens: async () => [1],+ }++ it('accepts an engine implementing all three members', () => {+ expect(isEmbeddingEngine(full)).toBe(true)+ })++ // A partially implemented engine used to pass the callers' `if (!llm?.embed)`+ // check and then throw on the first getEmbeddingContextSize call.+ it('rejects an engine missing any member', () => {+ for (const key of Object.keys(full)) {+ const partial: Record<string, unknown> = { ...full }+ delete partial[key]+ expect(isEmbeddingEngine(partial), key).toBe(false)+ }+ })++ it('rejects absent engines', () => {+ expect(isEmbeddingEngine(undefined)).toBe(false)+ expect(isEmbeddingEngine(null)).toBe(false)+ })+})diff --git a/core/src/browser/extensions/engines/AIEngine.ts b/core/src/browser/extensions/engines/AIEngine.tsindex d47d6de58..a1a294e0c 100644--- a/core/src/browser/extensions/engines/AIEngine.ts+++ b/core/src/browser/extensions/engines/AIEngine.ts@@ -215,6 +215,13 @@ export interface chatOptions {// Output for /chat will be Promise<ChatCompletion> for non-streaming// or Promise<AsyncIterable<ChatCompletionChunk>> for streaming+/**+ * A speculative-decoding draft flavour, matching llama.cpp's `--spec-type`+ * values minus their `draft-` prefix (common/speculative.cpp). `dspark` is+ * `dflash` plus a Markov head.+ */+export type SpecDraftKind = 'mtp' | 'eagle3' | 'dflash' | 'dspark'+// 7. /importexport interface ImportOptions {modelPath: string@@ -223,8 +230,11 @@ export interface ImportOptions {modelSize?: numbermmprojSha256?: stringmmprojSize?: number- // Optional MTP draft gguf (speculative decoding companion) downloaded with the model.- mtpPath?: string+ // Optional speculative-decoding draft gguf downloaded alongside the model,+ // plus which flavour the catalog named it as. The kind is a hint only: the+ // draft's own `general.architecture` decides, since it is authoritative.+ specDraftPath?: string+ specDraftKind?: SpecDraftKind// Additional files to download for MLX modelsfiles?: Array<{url: string@@ -240,6 +250,79 @@ export interface importResult {error?: string}+export interface EmbeddingData {+ embedding: number[]+ index: number+ object?: string+}++export interface EmbeddingResponse {+ data: EmbeddingData[]+ model?: string+ object?: string+ usage?: {+ prompt_tokens: number+ total_tokens: number+ }+}++/**+ * Embedding support an engine may add on top of `AIEngine`.+ *+ * Kept off `AIEngine` because most engines cannot embed. It is an interface+ * rather than optional members so the RAG and vector-db extensions -- which+ * reach the embedding engine by name across the extension boundary -- narrow+ * with `isEmbeddingEngine` instead of casting to a structural type each+ * declares for itself. Three copies of that cast had already drifted apart.+ */+export interface EmbeddingEngine {+ /** Embeds each text, in input order. */+ embed(texts: string[]): Promise<EmbeddingResponse>++ /**+ * The embedding model's context window in tokens, or undefined when no+ * embedding model is available to ask.+ */+ getEmbeddingContextSize(): Promise<number | undefined>++ /** Token counts from the embedding model's own tokenizer, in input order. */+ countEmbeddingTokens(texts: string[]): Promise<number[]>+}++function hasMethod(engine: unknown, name: keyof EmbeddingEngine): boolean {+ return (+ !!engine &&+ typeof engine === 'object' &&+ typeof (engine as Record<string, unknown>)[name] === 'function'+ )+}++/**+ * Narrows to an engine that can produce embeddings.+ *+ * Deliberately weaker than `isEmbeddingEngine`: producing a vector needs no+ * tokenizer, so an engine that can embed but cannot count tokens is usable+ * here and must not be turned away.+ */+export function canEmbed(engine: unknown): engine is AIEngine & Pick<EmbeddingEngine, 'embed'> {+ return hasMethod(engine, 'embed')+}++/**+ * Narrows to an engine implementing the whole embedding contract, including the+ * tokenizer queries that context-aware chunking needs.+ *+ * Checks each method rather than the object as a whole so a partially+ * implemented engine is rejected here instead of throwing on first use.+ */+export function isEmbeddingEngine(engine: unknown): engine is AIEngine & EmbeddingEngine {+ return (+ canEmbed(engine) &&+ hasMethod(engine, 'getEmbeddingContextSize') &&+ hasMethod(engine, 'countEmbeddingTokens')+ )+}+/*** Base AIEngine* Applicable to all AI Enginesdiff --git a/core/src/browser/extensions/engines/embedding.test.ts b/core/src/browser/extensions/engines/embedding.test.tsnew file mode 100644index 000000000..8654832f2--- /dev/null+++ b/core/src/browser/extensions/engines/embedding.test.ts@@ -0,0 +1,82 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { getEmbeddingEngine, embedTexts, EMBEDDING_ENGINE_EXTENSION } from './embedding'++function withExtension(ext: unknown) {+ globalThis.core = { extensionManager: { getByName: vi.fn().mockReturnValue(ext) } }+}++const engine = {+ embed: vi.fn(),+ getEmbeddingContextSize: vi.fn(),+ countEmbeddingTokens: vi.fn(),+}++describe('getEmbeddingEngine', () => {+ beforeEach(() => vi.clearAllMocks())++ it('looks the engine up by extension name', () => {+ withExtension(engine)+ expect(getEmbeddingEngine()).toBe(engine)+ expect(globalThis.core.extensionManager.getByName).toHaveBeenCalledWith(+ EMBEDDING_ENGINE_EXTENSION+ )+ })++ it('returns undefined when the extension is absent', () => {+ withExtension(undefined)+ expect(getEmbeddingEngine()).toBeUndefined()+ })++ it('returns undefined when the extension cannot embed', () => {+ withExtension({ embed: () => {} })+ expect(getEmbeddingEngine()).toBeUndefined()+ })++ // Producing a vector needs no tokenizer, so embedTexts must accept an engine+ // that getEmbeddingEngine rejects for lacking the token-counting queries.+ it('is stricter than embedTexts about the tokenizer queries', async () => {+ withExtension({ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [7], index: 0 }] }) })+ expect(getEmbeddingEngine()).toBeUndefined()+ await expect(embedTexts(['a'])).resolves.toEqual([[7]])+ })++ it('survives a missing extension manager', () => {+ globalThis.core = undefined+ expect(getEmbeddingEngine()).toBeUndefined()+ })+})++describe('embedTexts', () => {+ beforeEach(() => vi.clearAllMocks())++ // The response is keyed by `index`, so a provider returning them out of+ // order must not shift every vector onto the wrong text.+ it('scatters vectors back by index, not by response order', async () => {+ withExtension(engine)+ engine.embed.mockResolvedValue({+ data: [+ { embedding: [3], index: 2 },+ { embedding: [1], index: 0 },+ { embedding: [2], index: 1 },+ ],+ })+ await expect(embedTexts(['a', 'b', 'c'])).resolves.toEqual([[1], [2], [3]])+ })++ it('short-circuits on an empty input without touching the engine', async () => {+ withExtension(engine)+ await expect(embedTexts([])).resolves.toEqual([])+ expect(engine.embed).not.toHaveBeenCalled()+ })++ it('throws when no embedding engine is available', async () => {+ withExtension(undefined)+ await expect(embedTexts(['a'])).rejects.toThrow('llamacpp extension not available')+ })++ it('tolerates a response with no data', async () => {+ withExtension(engine)+ engine.embed.mockResolvedValue({})+ await expect(embedTexts(['a'])).resolves.toEqual([undefined])+ })+})diff --git a/core/src/browser/extensions/engines/embedding.ts b/core/src/browser/extensions/engines/embedding.tsnew file mode 100644index 000000000..992547cf8--- /dev/null+++ b/core/src/browser/extensions/engines/embedding.ts@@ -0,0 +1,47 @@+import { AIEngine, EmbeddingEngine, canEmbed, isEmbeddingEngine } from './AIEngine'++/**+ * The only embedding-capable engine that ships today. Named here rather than in+ * each consumer because the RAG and vector-db extensions both reached for it by+ * string literal, so a rename had three places to miss.+ */+export const EMBEDDING_ENGINE_EXTENSION = '@janhq/llamacpp-extension'++function lookup(extensionName: string): unknown {+ return globalThis.core?.extensionManager?.getByName(extensionName)+}++/**+ * Looks up the embedding engine, requiring the full contract including the+ * tokenizer queries.+ *+ * @returns the engine, or undefined when it is absent or only partly+ * implemented -- callers that merely want a vector should use `embedTexts`,+ * which asks for less.+ */+export function getEmbeddingEngine(+ extensionName: string = EMBEDDING_ENGINE_EXTENSION+): (AIEngine & EmbeddingEngine) | undefined {+ const engine = lookup(extensionName)+ return isEmbeddingEngine(engine) ? engine : undefined+}++/**+ * Embeds `texts` and returns the vectors positionally.+ *+ * The response is keyed by `index` rather than ordered, so the result is+ * scattered back into place; a caller that trusted response order would+ * silently mismatch vectors to chunks.+ */+export async function embedTexts(texts: string[]): Promise<number[][]> {+ if (!texts.length) return []+ const engine = lookup(EMBEDDING_ENGINE_EXTENSION)+ if (!canEmbed(engine)) throw new Error('llamacpp extension not available')++ const res = await engine.embed(texts)+ const out: number[][] = new Array(texts.length)+ for (const item of res?.data ?? []) {+ out[item.index] = item.embedding+ }+ return out+}diff --git a/core/src/browser/extensions/engines/index.ts b/core/src/browser/extensions/engines/index.tsindex 34ef45afd..aeb14c85f 100644--- a/core/src/browser/extensions/engines/index.ts+++ b/core/src/browser/extensions/engines/index.ts@@ -3,3 +3,4 @@ export * from './OAIEngine'export * from './LocalOAIEngine'export * from './RemoteOAIEngine'export * from './EngineManager'+export * from './embedding'diff --git a/core/src/browser/fs.test.ts b/core/src/browser/fs.test.tsindex 136d0145d..e8fd0e306 100644--- a/core/src/browser/fs.test.ts+++ b/core/src/browser/fs.test.ts@@ -17,6 +17,9 @@ describe('fs module', () => {copyFile: vi.fn(),getGgufFiles: vi.fn(),fileStat: vi.fn(),+ readYaml: vi.fn(),+ writeYaml: vi.fn(),+ decompress: vi.fn(),},}})@@ -94,4 +97,30 @@ describe('fs module', () => {await fs.fileStat(path)expect(globalThis.core.api.fileStat).toHaveBeenCalledWith({ args: path })})++ it('should call readYaml with a named path argument', async () => {+ await fs.readYaml('models/foo/model.yml')+ expect(globalThis.core.api.readYaml).toHaveBeenCalledWith({+ path: 'models/foo/model.yml',+ })+ })++ // The Rust command is `write_yaml(data, save_path)`, so the argument object+ // must carry both keys even though the wrapper takes the path first.+ it('should call writeYaml with data and savePath', async () => {+ const data = { model_path: 'a.gguf' }+ await fs.writeYaml('models/foo/model.yml', data)+ expect(globalThis.core.api.writeYaml).toHaveBeenCalledWith({+ data,+ savePath: 'models/foo/model.yml',+ })+ })++ it('should call decompress with path and outputDir', async () => {+ await fs.decompress('/tmp/a.tar.gz', '/out')+ expect(globalThis.core.api.decompress).toHaveBeenCalledWith({+ path: '/tmp/a.tar.gz',+ outputDir: '/out',+ })+ })})diff --git a/core/src/browser/fs.ts b/core/src/browser/fs.tsindex 42d43ca65..44e4b4f9b 100644--- a/core/src/browser/fs.ts+++ b/core/src/browser/fs.ts@@ -89,6 +89,35 @@ const getGgufFiles: (paths: string[]) => Promise<any> = (paths) =>const fileStat: (path: string) => Promise<FileStat | undefined> = (path) =>globalThis.core.api?.fileStat({ args: path })+/**+ * Reads a YAML file and returns it parsed.+ *+ * The Rust side (`core::filesystem::commands::read_yaml`) resolves the path+ * within the Jan data folder, so a path escaping it is rejected there.+ *+ * @param path - The path to the YAML file.+ */+const readYaml: <T = unknown>(path: string) => Promise<T> = (path) =>+ globalThis.core.api?.readYaml({ path })++/**+ * Serializes `data` as YAML to `savePath`.+ *+ * @param savePath - Destination path, resolved within the Jan data folder.+ * @param data - The value to serialize.+ */+const writeYaml: (savePath: string, data: unknown) => Promise<void> = (savePath, data) =>+ globalThis.core.api?.writeYaml({ data, savePath })++/**+ * Unpacks an archive into `outputDir`.+ *+ * @param path - The archive to unpack.+ * @param outputDir - Destination directory, resolved within the Jan data folder.+ */+const decompress: (path: string, outputDir: string) => Promise<void> = (path, outputDir) =>+ globalThis.core.api?.decompress({ path, outputDir })+// TODO: Export `dummy` fs functions automatically// Currently adding these manuallyexport const fs = {@@ -105,4 +134,7 @@ export const fs = {fileStat,writeBlob,getGgufFiles,+ readYaml,+ writeYaml,+ decompress,}diff --git a/core/src/browser/index.ts b/core/src/browser/index.tsindex 1ae6029b7..b9ee292c4 100644--- a/core/src/browser/index.ts+++ b/core/src/browser/index.ts@@ -16,6 +16,12 @@ export * from './events'*/export * from './fs'+/**+ * Export app settings module.+ * @module+ */+export * from './settings'+/*** Export Extension module.* @modulediff --git a/core/src/browser/models/utils.test.ts b/core/src/browser/models/utils.test.tsindex 5600a28be..35ac47ffe 100644--- a/core/src/browser/models/utils.test.ts+++ b/core/src/browser/models/utils.test.ts@@ -95,7 +95,10 @@ describe('validationRules', () => {expect(validationRules.ngl(12)).toBe(true)expect(validationRules.ngl(1)).toBe(true)expect(validationRules.ngl(0)).toBe(true)- expect(validationRules.ngl(-1)).toBe(false)+ // -1 is auto (VRAM-aware) and -2 offloads all layers; both are valid.+ expect(validationRules.ngl(-1)).toBe(true)+ expect(validationRules.ngl(-2)).toBe(true)+ expect(validationRules.ngl(-3)).toBe(false)expect(validationRules.ngl('12')).toBe(false)})@@ -156,7 +159,9 @@ describe('validationRules', () => {it('should validate repeat_last_n correctly', () => {expect(validationRules.repeat_last_n(5)).toBe(true)- expect(validationRules.repeat_last_n(-5)).toBe(true)+ // Rejected: llama.cpp throws on a negative window rather than clamping,+ // so persisting one aborts the model load and 400s every request.+ expect(validationRules.repeat_last_n(-5)).toBe(false)expect(validationRules.repeat_last_n(0)).toBe(true)expect(validationRules.repeat_last_n(1.5)).toBe(true)expect(validationRules.repeat_last_n('5')).toBe(false)diff --git a/core/src/browser/models/utils.ts b/core/src/browser/models/utils.tsindex c11bed4c7..4b0b79aed 100644--- a/core/src/browser/models/utils.ts+++ b/core/src/browser/models/utils.ts@@ -15,12 +15,14 @@ export const validationRules: { [key: string]: (value: any) => boolean } = {stop: (value: any) => Array.isArray(value) && value.every((v) => typeof v === 'string'),frequency_penalty: (value: any) => typeof value === 'number' && value >= -2 && value <= 2,presence_penalty: (value: any) => typeof value === 'number' && value >= -2 && value <= 2,- repeat_last_n: (value: any) => typeof value === 'number',+ // Upstream throws on a negative window rather than clamping it.+ repeat_last_n: (value: any) => typeof value === 'number' && value >= 0,repeat_penalty: (value: any) => typeof value === 'number',min_p: (value: any) => typeof value === 'number',ctx_len: (value: any) => Number.isInteger(value) && value >= 0,- ngl: (value: any) => Number.isInteger(value) && value >= 0,+ // -1 is auto (VRAM-aware) and -2 or below means all layers.+ ngl: (value: any) => Number.isInteger(value) && value >= -2,embedding: (value: any) => typeof value === 'boolean',n_parallel: (value: any) => Number.isInteger(value) && value >= 0,cpu_threads: (value: any) => Number.isInteger(value) && value >= 0,diff --git a/core/src/browser/settings.test.ts b/core/src/browser/settings.test.tsnew file mode 100644index 000000000..317f8f5f3--- /dev/null+++ b/core/src/browser/settings.test.ts@@ -0,0 +1,40 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { appSettings } from './settings'++describe('appSettings', () => {+ beforeEach(() => {+ globalThis.core = {+ api: {+ settingsGet: vi.fn(),+ settingsSet: vi.fn(),+ settingsRemove: vi.fn(),+ },+ }+ })++ it('passes the key through to settingsGet', async () => {+ globalThis.core.api.settingsGet.mockResolvedValue('vulkan')+ await expect(appSettings.get('backend')).resolves.toBe('vulkan')+ expect(globalThis.core.api.settingsGet).toHaveBeenCalledWith({ key: 'backend' })+ })++ // The Rust command returns Option<String>, which serializes to null; callers+ // distinguish "unset" from "empty", so undefined must not leak through.+ it('normalizes a missing key to null', async () => {+ globalThis.core.api.settingsGet.mockResolvedValue(undefined)+ await expect(appSettings.get('absent')).resolves.toBeNull()+ })++ it('passes key and value through to settingsSet', async () => {+ await appSettings.set('backend', 'cuda-12')+ expect(globalThis.core.api.settingsSet).toHaveBeenCalledWith({+ key: 'backend',+ value: 'cuda-12',+ })+ })++ it('passes the key through to settingsRemove', async () => {+ await appSettings.remove('backend')+ expect(globalThis.core.api.settingsRemove).toHaveBeenCalledWith({ key: 'backend' })+ })+})diff --git a/core/src/browser/settings.ts b/core/src/browser/settings.tsnew file mode 100644index 000000000..a909cb7e6--- /dev/null+++ b/core/src/browser/settings.ts@@ -0,0 +1,28 @@+/**+ * Typed access to the Rust settings store (`core::app::settings_store`), which+ * persists to `<jan_data>/settings.json`.+ *+ * Named `appSettings` rather than `settings` to keep it distinct from+ * `BaseExtension`'s per-extension setting descriptors, which are unrelated.+ */++/**+ * Reads a persisted setting.+ * @returns the stored string, or null when the key is unset.+ */+const get: (key: string) => Promise<string | null> = async (key) =>+ (await globalThis.core.api?.settingsGet({ key })) ?? null++/**+ * Persists a setting. Values are stored as strings; callers serialize.+ */+const set: (key: string, value: string) => Promise<void> = (key, value) =>+ globalThis.core.api?.settingsSet({ key, value })++/**+ * Removes a setting. Removing an absent key is not an error.+ */+const remove: (key: string) => Promise<void> = (key) =>+ globalThis.core.api?.settingsRemove({ key })++export const appSettings = { get, set, remove }diff --git a/core/src/types/api/index.ts b/core/src/types/api/index.tsindex 93a5f4631..c9c2bc3af 100644--- a/core/src/types/api/index.ts+++ b/core/src/types/api/index.ts@@ -50,6 +50,9 @@ export enum AppRoute {baseName = 'baseName',log = 'log',showToast = 'showToast',+ settingsGet = 'settingsGet',+ settingsSet = 'settingsSet',+ settingsRemove = 'settingsRemove',}export enum AppEvent {@@ -99,6 +102,9 @@ export enum FileSystemRoute {mkdir = 'mkdir',readFileSync = 'readFileSync',writeFileSync = 'writeFileSync',+ readYaml = 'readYaml',+ writeYaml = 'writeYaml',+ decompress = 'decompress',}export enum FileManagerRoute {copyFile = 'copyFile',diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.jsonindex 260e0228f..d5a326ce3 100644--- a/extensions/llamacpp-extension/settings.json+++ b/extensions/llamacpp-extension/settings.json@@ -1,26 +1,4 @@[- {- "key": "llamacpp_version",- "title": "Version",- "description": "llama.cpp release version",- "controllerType": "dropdown",- "controllerProps": {- "value": "none",- "options": [],- "recommended": ""- }- },- {- "key": "llamacpp_backend",- "title": "Backend",- "description": "Hardware backend for llama.cpp (CUDA, HIP/ROCm, Vulkan, CPU, etc.)",- "controllerType": "dropdown",- "controllerProps": {- "value": "none",- "options": [],- "recommended": ""- }- },{"key": "llamacpp_env","title": "Environmental variables",@@ -33,34 +11,13 @@"textAlign": "right"}},- {- "key": "check_for_updates",- "title": "Check for updates",- "description": "Fetch the remote llama.cpp release list. Required for the version dropdown to show releases beyond what's installed locally, and for update notifications.",- "controllerType": "checkbox",- "controllerProps": { "value": true }- },- {- "key": "auto_update_engine",- "title": "Auto update engine",- "description": "Automatically download and switch to the latest llamacpp engine when available. Requires \"Check for updates\" to be on.",- "controllerType": "checkbox",- "controllerProps": { "value": true }- },- {- "key": "verify_backend_deps",- "title": "Verify backend dependencies",- "description": "Check that GPU backend shared libraries (CUDA, Vulkan, etc.) resolve on startup and warn if any are missing.",- "controllerType": "checkbox",- "controllerProps": { "value": true }- },{"key": "models_max","title": "Max Concurrently Loaded Models","description": "Maximum number of models the router will keep loaded at once. 0 = unlimited.","controllerType": "input","controllerProps": {- "value": "1",+ "value": 1,"placeholder": "e.g 1","type": "number","textAlign": "right"@@ -72,7 +29,7 @@"description": "Llamacpp connection and load timeout in seconds","controllerType": "input","controllerProps": {- "value": "600",+ "value": 600,"placeholder": "e.g 600","type": "number","textAlign": "right"@@ -156,6 +113,18 @@"textAlign": "right"}},+ {+ "key": "batch_size",+ "title": "Batch Size",+ "description": "Logical maximum batch size for processing prompts.",+ "controllerType": "input",+ "controllerProps": {+ "value": 2048,+ "placeholder": "2048",+ "type": "number",+ "textAlign": "right"+ }+ },{"key": "ubatch_size","title": "uBatch Size",@@ -168,10 +137,31 @@"textAlign": "right"}},+ {+ "key": "n_cpu_moe",+ "title": "MoE Layers on CPU",+ "description": "Keep the Mixture-of-Experts weights of the first N layers in CPU memory. Lets a large MoE model fit in limited VRAM. 0 disables it.",+ "controllerType": "input",+ "controllerProps": {+ "value": 0,+ "placeholder": "0",+ "type": "number",+ "textAlign": "right"+ }+ },+ {+ "key": "no_kv_offload",+ "title": "Disable KV Cache Offload",+ "description": "Keep the KV cache in system RAM instead of GPU memory. Useful when VRAM is scarce, at the cost of speed.",+ "controllerType": "checkbox",+ "controllerProps": {+ "value": false+ }+ },{"key": "device","title": "Devices for Offload",- "description": "Comma-separated list of devices to use for offloading (e.g., 'CUDA0', 'CUDA0,CUDA1'). Leave empty to use default/CPU only.",+ "description": "Comma-separated accelerators to offload to, named as in the detected hardware list. Leave empty to use every available accelerator, or set \"none\" to disable offload entirely.","controllerType": "input","controllerProps": {"value": "",@@ -187,9 +177,22 @@"controllerProps": {"value": "layer","options": [- { "value": "none", "name": "None" },- { "value": "layer", "name": "Layer" },- { "value": "row", "name": "Row" }+ {+ "value": "none",+ "name": "None"+ },+ {+ "value": "layer",+ "name": "Layer"+ },+ {+ "value": "row",+ "name": "Row"+ },+ {+ "value": "tensor",+ "name": "Tensor (experimental)"+ }]}},@@ -205,6 +208,26 @@"textAlign": "right"}},+ {+ "key": "tensor_split",+ "title": "Tensor Split",+ "description": "Comma-separated proportions for splitting the model across devices, e.g. \"3,1\". Leave empty for an even split.",+ "controllerType": "input",+ "controllerProps": {+ "value": "",+ "placeholder": "3,1",+ "type": "text"+ }+ },+ {+ "key": "no_op_offload",+ "title": "Disable Op Offload",+ "description": "Keep host tensor operations on the CPU instead of offloading them to the accelerator.",+ "controllerType": "checkbox",+ "controllerProps": {+ "value": false+ }+ },{"key": "flash_attn","title": "Flash Attention",@@ -213,9 +236,18 @@"controllerProps": {"value": "auto","options": [- { "value": "auto", "name": "Auto" },- { "value": "on", "name": "On" },- { "value": "off", "name": "Off" }+ {+ "value": "auto",+ "name": "Auto"+ },+ {+ "value": "on",+ "name": "On"+ },+ {+ "value": "off",+ "name": "Off"+ }]}},@@ -235,10 +267,10 @@{"key": "cont_batching","title": "Continuous Batching",- "description": "Enable continuous batching (a.k.a dynamic batching) for concurrent requests.",+ "description": "Enable continuous batching (a.k.a dynamic batching) for concurrent requests. Enabled by default, matching llama.cpp.","controllerType": "checkbox","controllerProps": {- "value": false+ "value": true}},{@@ -253,7 +285,7 @@{"key": "mlock","title": "MLock",- "description": "Force system to keep model in RAM, preventing swapping/compression.",+ "description": "Lock the model in RAM so it is never swapped out. Combined with \"Disable mmap\" this loads the weights without mmap and then locks them.","controllerType": "checkbox","controllerProps": {"value": false@@ -267,15 +299,42 @@"controllerProps": {"value": "f16","options": [- { "value": "f32", "name": "f32" },- { "value": "f16", "name": "f16" },- { "value": "bf16", "name": "bf16" },- { "value": "q8_0", "name": "q8_0" },- { "value": "q4_0", "name": "q4_0" },- { "value": "q4_1", "name": "q4_1" },- { "value": "iq4_nl", "name": "iq4_nl" },- { "value": "q5_0", "name": "q5_0" },- { "value": "q5_1", "name": "q5_1" }+ {+ "value": "f32",+ "name": "f32"+ },+ {+ "value": "f16",+ "name": "f16"+ },+ {+ "value": "bf16",+ "name": "bf16"+ },+ {+ "value": "q8_0",+ "name": "q8_0"+ },+ {+ "value": "q4_0",+ "name": "q4_0"+ },+ {+ "value": "q4_1",+ "name": "q4_1"+ },+ {+ "value": "iq4_nl",+ "name": "iq4_nl"+ },+ {+ "value": "q5_0",+ "name": "q5_0"+ },+ {+ "value": "q5_1",+ "name": "q5_1"+ }]}},@@ -287,46 +346,72 @@"controllerProps": {"value": "f16","options": [- { "value": "f32", "name": "f32" },- { "value": "f16", "name": "f16" },- { "value": "bf16", "name": "bf16" },- { "value": "q8_0", "name": "q8_0" },- { "value": "q4_0", "name": "q4_0" },- { "value": "q4_1", "name": "q4_1" },- { "value": "iq4_nl", "name": "iq4_nl" },- { "value": "q5_0", "name": "q5_0" },- { "value": "q5_1", "name": "q5_1" }+ {+ "value": "f32",+ "name": "f32"+ },+ {+ "value": "f16",+ "name": "f16"+ },+ {+ "value": "bf16",+ "name": "bf16"+ },+ {+ "value": "q8_0",+ "name": "q8_0"+ },+ {+ "value": "q4_0",+ "name": "q4_0"+ },+ {+ "value": "q4_1",+ "name": "q4_1"+ },+ {+ "value": "iq4_nl",+ "name": "iq4_nl"+ },+ {+ "value": "q5_0",+ "name": "q5_0"+ },+ {+ "value": "q5_1",+ "name": "q5_1"+ }]}},{"key": "rope_scaling","title": "RoPE Scaling Method",- "description": "RoPE frequency scaling method.",+ "description": "RoPE frequency scaling method. \"Model default\" leaves it to the model; \"None\" explicitly disables scaling.","controllerType": "dropdown","controllerProps": {- "value": "none",+ "value": "auto","options": [- { "value": "none", "name": "None" },- { "value": "linear", "name": "Linear" },- { "value": "yarn", "name": "YaRN" }+ {+ "value": "auto",+ "name": "Model default"+ },+ {+ "value": "none",+ "name": "None"+ },+ {+ "value": "linear",+ "name": "Linear"+ },+ {+ "value": "yarn",+ "name": "YaRN"+ }]}},- {- "key": "rope_scale",- "title": "RoPE Scale Factor",- "description": "RoPE context scaling factor.",- "controllerType": "input",- "controllerProps": {- "value": 1.0,- "placeholder": "1.0",- "type": "number",- "textAlign": "right",- "min": 0,- "step": 0.01- }- },{"key": "rope_freq_base","title": "RoPE Frequency Base",@@ -342,11 +427,11 @@{"key": "rope_freq_scale","title": "RoPE Frequency Scale Factor",- "description": "RoPE frequency scaling factor.",+ "description": "RoPE frequency scaling factor. 0 loads the value from the model; 1 forces no scaling.","controllerType": "input","controllerProps": {- "value": 1.0,- "placeholder": "1.0",+ "value": 0,+ "placeholder": "0","type": "number","textAlign": "right","min": 0,@@ -356,11 +441,32 @@{"key": "cache_ram","title": "Prompt Cache RAM (MiB)",- "description": "Maximum prompt cache size in MiB. -1 = unlimited, 0 = disabled.",+ "description": "Prompt cache size in MiB (default: 8192). -1 is unlimited, 0 disables it.","controllerType": "input","controllerProps": {- "value": -1,- "placeholder": "-1",+ "value": 8192,+ "placeholder": "8192",+ "type": "number",+ "textAlign": "right"+ }+ },+ {+ "key": "persist_thread_cache",+ "title": "Remember Conversations Between Sessions",+ "description": "Keep each conversation's prompt cache on disk so reopening it does not re-read the whole conversation. Restored only when the model, its settings and the llama.cpp build all match what saved it.",+ "controllerType": "checkbox",+ "controllerProps": {+ "value": true+ }+ },+ {+ "key": "thread_cache_size",+ "title": "Conversation Cache Disk Limit (MiB)",+ "description": "Disk budget for saved conversation caches (default: 8192). The oldest are dropped first once it is reached. One long conversation can take hundreds of MiB.",+ "controllerType": "input",+ "controllerProps": {+ "value": 8192,+ "placeholder": "8192","type": "number","textAlign": "right"}@@ -378,6 +484,30 @@"min": 0}},+ {+ "key": "ctx_checkpoints",+ "title": "Context Checkpoints",+ "description": "Maximum context checkpoints kept per slot, which let a shifted context be restored instead of reprocessed.",+ "controllerType": "input",+ "controllerProps": {+ "value": 32,+ "placeholder": "32",+ "type": "number",+ "textAlign": "right"+ }+ },+ {+ "key": "checkpoint_min_step",+ "title": "Checkpoint Minimum Step",+ "description": "Minimum number of tokens between context checkpoints.",+ "controllerType": "input",+ "controllerProps": {+ "value": 8192,+ "placeholder": "8192",+ "type": "number",+ "textAlign": "right"+ }+ },{"key": "swa_full","title": "Full SWA Cache",@@ -395,9 +525,18 @@"controllerProps": {"value": "auto","options": [- { "value": "auto", "name": "Auto" },- { "value": "on", "name": "On" },- { "value": "off", "name": "Off" }+ {+ "value": "auto",+ "name": "Auto"+ },+ {+ "value": "on",+ "name": "On"+ },+ {+ "value": "off",+ "name": "Off"+ }]}},diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.tsdeleted file mode 100644index 0bc9086a3..000000000--- a/extensions/llamacpp-extension/src/backend.ts+++ /dev/null@@ -1,286 +0,0 @@-import { getJanDataFolderPath, fs, joinPath, events, logger } from '@janhq/core'-import { invoke } from '@tauri-apps/api/core'-import { getProxyConfig } from './util'-import { dirname } from '@tauri-apps/api/path'-import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'-import {- getLocalInstalledBackendsInternal,- normalizeFeatures,- determineSupportedBackends,- listSupportedBackendsFromRust,- BackendVersion,- getSupportedFeaturesFromRust,- fetchBackendChecksums,- verifyFileSha512,- probeBackendLoad,- type LoadProbeResult,-} from '@janhq/tauri-plugin-llamacpp-api'--/*- * Reads currently installed backends in janDataFolderPath- *- */-export async function getLocalInstalledBackends(): Promise<- { version: string; backend: string }[]-> {- const janDataFolderPath = await getJanDataFolderPath()- const backendDir = await joinPath([- janDataFolderPath,- 'llamacpp',- 'backends',- ])- return await getLocalInstalledBackendsInternal(backendDir)-}--// folder structure-// <Jan's data folder>/llamacpp/backends/<backend_version>/<backend_type>--// what should be available to the user for selection?-/**- * Hardware-supported backends published by upstream. Excludes- * locally-installed-only entries, so the "recommended backend" calculation- * isn't biased by user side-loads.- */-export async function fetchRemoteBackends(): Promise<BackendVersion[]> {- const sysInfo = await getSystemInfo()- const rawFeatures = await getSupportedFeaturesFromRust(- sysInfo.os_type,- sysInfo.cpu.extensions,- sysInfo.gpus- )- const features = normalizeFeatures(rawFeatures)- const supportedBackends = await determineSupportedBackends(- sysInfo.os_type,- sysInfo.cpu.arch,- features- )-- try {- return await invoke<BackendVersion[]>(- 'plugin:llamacpp|fetch_remote_supported_backends',- { supportedBackends, proxy: await getProxyConfig() }- )- } catch (e) {- logger.debug(- `Not able to get remote backends, Jan might be offline or network problem: ${String(e)}`- )- return []- }-}--export async function listSupportedBackends(- checkRemote: boolean = true-): Promise<BackendVersion[]> {- const remoteBackendVersions = checkRemote ? await fetchRemoteBackends() : []- const localBackendVersions = await getLocalInstalledBackends()- return listSupportedBackendsFromRust(remoteBackendVersions, localBackendVersions)-}--export async function getBackendDir(- backend: string,- version: string-): Promise<string> {- const janDataFolder = await getJanDataFolderPath()- return invoke<string>('plugin:llamacpp|get_backend_dir', {- backend,- version,- janDataFolder,- })-}--export async function getBackendExePath(- backend: string,- version: string-): Promise<string> {- const janDataFolder = await getJanDataFolderPath()- return invoke<string>('plugin:llamacpp|get_backend_exe_path', {- backend,- version,- janDataFolder,- isWindows: IS_WINDOWS,- })-}--export async function isBackendInstalled(- backend: string,- version: string-): Promise<boolean> {- const janDataFolder = await getJanDataFolderPath()- return invoke<boolean>('plugin:llamacpp|check_backend_installed', {- backend,- version,- janDataFolder,- isWindows: IS_WINDOWS,- })-}--export type BackendVerificationResult = {- verified: boolean- missing_libraries: string[]- resolved_libraries: string[]-}--/**- * Loads the backend's GPU library the way llama-server would, to recover the- * reason it cannot. A release build of ggml discards that error and silently- * falls back to CPU, so this is the only way to name the missing dependency.- */-export async function probeBackendGpuLibraries(- backend: string,- version: string-): Promise<LoadProbeResult> {- const janDataFolder = await getJanDataFolderPath()- return probeBackendLoad(backend, version, janDataFolder, IS_WINDOWS)-}--export async function verifyBackendInstallation(- backend: string,- version: string-): Promise<BackendVerificationResult> {- const janDataFolder = await getJanDataFolderPath()- return invoke<BackendVerificationResult>(- 'plugin:llamacpp|verify_backend_installation',- {- backend,- version,- janDataFolder,- isWindows: IS_WINDOWS,- }- )-}--/**- * Check downloaded archives against the release's `checksum.yml` before they- * are unpacked.- *- * Fail-soft on a missing manifest or a missing entry, and deliberately so:- * releases published before the manifest existed -- and those whose entries- * predate the `-bin-` naming fix in janhq/llama.cpp db8b2fcd -- carry no usable- * digest, and refusing to install them would strand every older version, which- * is exactly what rollback depends on. A digest that IS present and does not- * match is a hard failure: the file is removed so a retry cannot reuse it.- */-async function verifyDownloadedArchives(- savePaths: string[],- version: string,- source: 'github' | 'cdn',- proxyConfig: object | null-): Promise<void> {- let checksums: Record<string, string> = {}- try {- checksums = await fetchBackendChecksums(version, source, proxyConfig)- } catch (e) {- logger.warn(`Could not load checksum.yml for ${version}:`, e)- return- }- if (!Object.keys(checksums).length) {- logger.warn(- `No usable checksums published for ${version}; skipping verification`- )- return- }-- for (const savePath of savePaths) {- const name = savePath.split(/[\\/]/).pop() ?? ''- const expected = checksums[name]- if (!expected) {- logger.warn(`No checksum entry for ${name}; skipping verification`)- continue- }- if (await verifyFileSha512(savePath, expected)) {- logger.info(`Checksum verified for ${name}`)- continue- }- await fs.rm(savePath).catch(() => undefined)- throw new Error(- `Checksum mismatch for ${name}; the download was corrupt or tampered with`- )- }-}--export async function downloadBackend(- backend: string,- version: string,- source: 'github' | 'cdn' = 'github'-): Promise<void> {- const janDataFolderPath = await getJanDataFolderPath()- const sysInfo = await getSystemInfo()- const proxyConfig = await getProxyConfig()-- const downloadItems: Array<{- url: string- save_path: string- model_id: string- proxy?: object- }> = await invoke('plugin:llamacpp|build_backend_download_items', {- backend,- version,- source,- janDataFolder: janDataFolderPath,- osType: sysInfo.os_type,- })-- // Attach proxy config to each item- const itemsWithProxy = downloadItems.map((item) => ({- ...item,- proxy: proxyConfig,- }))-- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )- const taskId = `llamacpp-${version}-${backend}`.replace(/\./g, '-')- const downloadType = 'Engine'-- logger.info(- `Downloading backend ${backend} version ${version} from ${source}: ${JSON.stringify(itemsWithProxy)}`- )-- let downloadCompleted = false- try {- const onProgress = (transferred: number, total: number) => {- events.emit('onFileDownloadUpdate', {- modelId: taskId,- percent: transferred / total,- size: { transferred, total },- downloadType,- })- downloadCompleted = transferred === total- }- await downloadManager.downloadFiles(itemsWithProxy, taskId, onProgress)-- if (!downloadCompleted) {- events.emit('onFileDownloadStopped', { modelId: taskId, downloadType })- return- }-- await verifyDownloadedArchives(- itemsWithProxy.map((i) => i.save_path),- version,- source,- proxyConfig- )-- for (const { save_path } of itemsWithProxy) {- // Official Windows HIP assets ship as .zip; everything else is .tar.gz.- if (save_path.endsWith('.tar.gz') || save_path.endsWith('.zip')) {- const parentDir = await dirname(save_path)- await invoke('decompress', { path: save_path, outputDir: parentDir })- await fs.rm(save_path)- }- }-- events.emit('onFileDownloadSuccess', { modelId: taskId, downloadType })- } catch (error) {- if (- source === 'github' &&- error?.toString() !== 'Error: Download cancelled'- ) {- logger.warn(`GitHub download failed, falling back to CDN:`, error)- return await downloadBackend(backend, version, 'cdn')- }- logger.error(`Failed to download backend ${backend}: `, error)- events.emit('onFileDownloadError', { modelId: taskId, downloadType })- throw error- }-}diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 8b68107c5..938b46b91 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -8,6 +8,7 @@import {AIEngine,+ type EmbeddingEngine,getJanDataFolderPath,fs,joinPath,@@ -17,6 +18,7 @@ import {chatCompletion,chatCompletionChunk,ImportOptions,+ type SpecDraftKind,chatCompletionRequest,events,AppEvent,@@ -33,17 +35,6 @@ import {} from './settings-store'import { listen } from '@tauri-apps/api/event'-import {- listSupportedBackends,- fetchRemoteBackends,- downloadBackend,- isBackendInstalled,- verifyBackendInstallation,- getBackendExePath,- getBackendDir,- getLocalInstalledBackends,- probeBackendGpuLibraries,-} from './backend'import { invoke } from '@tauri-apps/api/core'import {getProxyConfig,@@ -51,17 +42,21 @@ import {mergeEmbedResponses,detectEmbeddingFromGgufMeta,detectMtpLayersFromGgufMeta,+ resolveSpecDraftKind,detectTemplateKwargsFromChatTemplate,getDefaultEmbeddingModelId,setDefaultEmbeddingModelId,type EmbedBatchResult,} from './util'-import { generatePreset, MTP_MIN_BUILD } from './preset'import {- backendImpliesGpu,+ generatePreset,+ threadCacheDir,+ DEFAULT_EMBEDDING_UBATCH,+} from './preset'+import {evaluateEmbeddingVector,evaluateGpuOffload,- isBackendConfigured,+ backendFromDeviceIds,type EmbeddingVectorProblem,type GpuOffloadCheck,type ReadinessStatus,@@ -73,13 +68,21 @@ import {} from './backend-settings'import { basename } from '@tauri-apps/api/path'import {+ asI32,loadLlamaModel,readGgufMetadata,+ findGgufTensors,isModelSupported,unloadLlamaModel,- reloadRouterModels,- routerHealth,- adoptRouter,+ startEngine,+ eraseThreadSlotState,+ getEngineInfo as pluginGetEngineInfo,+ reloadEngineModels,+ engineDevices,+ generateApiKey as pluginGenerateApiKey,+ findSessionByModel as pluginFindSessionByModel,+ ensureSessionReady as pluginEnsureSessionReady,+ getLoadedModels as pluginGetLoadedModels,LlamacppConfig,DownloadItem,ModelConfig,@@ -87,60 +90,25 @@ import {EmbeddingResponse,ModelProps,DeviceList,- mapOldBackendToNew,- findLatestVersionForBackend,- prioritizeBackends,- checkBackendForUpdates,- removeOldBackendVersions,- shouldMigrateBackend,- handleSettingUpdate,} from '@janhq/tauri-plugin-llamacpp-api'import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'const EMBEDDING_CHECK_VERSION = 3const MTP_CHECK_VERSION = 1-const TEMPLATE_KWARGS_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--// Superseded installs kept on disk so a rollback (or an offline downgrade)-// does not require re-downloading a release that may since have been yanked.-const BACKEND_VERSIONS_RETAINED = 2--// Bounded so a long-lived install cannot grow the log without limit.-const UPDATE_HISTORY_LIMIT = 50-const UPDATE_HISTORY_FILENAME = 'update_history.json'--type BackendUpdateRecord = {- timestamp: string- from: string- to: string- outcome: 'updated' | 'rolled-back' | 'rollback-failed' | 'failed'- durationMs: number- error?: string-}-/** Snapshot of an active backend choice, sufficient to restore it on rollback. */-type BackendSelection = {- version: string- backend: string- storedType?: string-}+// The tensor that marks a DSpark draft: it is a DFlash one plus this Markov+// head (common/speculative.cpp, llama-arch.cpp LLM_TENSOR_DSPARK_MARKOV_W1).+const MARKOV_HEAD_TENSOR = 'markov_w1.weight'+const TEMPLATE_KWARGS_CHECK_VERSION = 1// 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,-// timeout, llamacpp_env, version_backend) are handled separately or not at all.+// in preset.ts). Mutating any of these needs the preset reloaded so the new+// value is read; cosmetic / process-only keys (models_max, timeout,+// llamacpp_env) are handled separately or not at all.const PRESET_AFFECTING_KEYS = new Set<string>(['fit','fit_target','fit_ctx',- 'ctx_size',- 'n_gpu_layers','flash_attn','cache_type_k','cache_type_v',@@ -149,22 +117,33 @@ const PRESET_AFFECTING_KEYS = new Set<string>(['threads','threads_batch','n_predict',+ 'batch_size','ubatch_size',+ 'n_cpu_moe',+ 'no_kv_offload','device','split_mode','main_gpu','no_mmap','mlock','rope_scaling',- 'rope_scale','rope_freq_base','rope_freq_scale','ctx_shift','cache_ram',+ // persist_thread_cache decides whether slot-save-path is emitted at all;+ // thread_cache_size is not a preset key but rides the same reload, which+ // carries it to the worker (see reload_engine_models).+ 'persist_thread_cache',+ 'thread_cache_size','cache_reuse','swa_full','keep','kv_unified',+ 'tensor_split',+ 'no_op_offload',+ 'ctx_checkpoints',+ 'checkpoint_min_step',])@@ -174,15 +153,6 @@ const PRESET_AFFECTING_KEYS = new Set<string>([* It also subscribes to events emitted by the @janhq/core package and handles new message requests.*/-/**- * Parse the build number from a llama.cpp version string like "b6325".- * Returns the numeric portion, or null if the format doesn't match.- */-function parseBuildNumber(version: string): number | null {- const match = version.match(/^b(\d+)$/)- return match ? parseInt(match[1], 10) : null-}-type YamlSettingValue = string | number | boolean | nulltype PersistedProviderSetting = {@@ -197,7 +167,6 @@ type PersistedModelState = {}const MODEL_PROVIDER_STORE_KEY = 'model-provider'-const INTERFACE_SETTINGS_STORE_KEY = 'setting-appearance'const EMBEDDER_BOOTSTRAP_KEY = 'llamacpp-embedder-bootstrapped'/** Set once the user has agreed to the first-run download. */const SETUP_CONSENT_KEY = 'llamacpp-first-run-setup-started'@@ -205,7 +174,17 @@ const FALLBACK_EMBEDDING_MODEL_ID = 'sentence-transformer-mini'const FALLBACK_EMBEDDING_MODEL_URL ='https://huggingface.co/second-state/All-MiniLM-L6-v2-Embedding-GGUF/resolve/main/all-MiniLM-L6-v2-ggml-model-f16.gguf?download=true'const LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY =- 'llamacpp_model_yaml_backfill_v1'+ 'llamacpp_model_yaml_backfill_v2'++/// The GPU-layers value the old UI shipped as its default. v1 of the backfill+/// copied it into every model.yml, which pins offload to 100 layers and defeats+/// llama.cpp's own -1 (auto, VRAM-aware) -- an OOM on a small GPU. v2 removes it+/// again. A user who deliberately chose exactly 100 loses that choice, which is+/// the right trade: 100 was never a considered value, it was the default.+const LEGACY_NGL_DEFAULT = 100++/// Matches the `timeout` default in settings.json.+const DEFAULT_TIMEOUT = 600// Short and non-empty: enough to exercise tokenize plus pooling without making// setup wait on a long prompt.@@ -258,7 +237,18 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<top_k: { yamlKey: 'top_k', coerce: coerceIntSetting },top_p: { yamlKey: 'top_p', coerce: coerceFloatSetting },min_p: { yamlKey: 'min_p', coerce: coerceFloatSetting },- repeat_last_n: { yamlKey: 'repeat_last_n', coerce: coerceIntSetting },+ // Not coerceIntSetting: upstream throws on a negative window on both the+ // preset path and the per-request path, so a legacy -1 from the old+ // "-1 = full context" UI has to be dropped, not passed through. Omitting the+ // key lets upstream's own default (64) apply.+ repeat_last_n: {+ yamlKey: 'repeat_last_n',+ coerce: (v) => {+ if (v === '' || v == null) return null+ const n = typeof v === 'number' ? v : Number(v)+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null+ },+ },repeat_penalty: { yamlKey: 'repeat_penalty', coerce: coerceFloatSetting },presence_penalty: { yamlKey: 'presence_penalty', coerce: coerceFloatSetting },frequency_penalty: {@@ -278,7 +268,9 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<coerce: (v) => {if (v === '' || v == null) return nullconst n = typeof v === 'number' ? v : Number(v)- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null+ // -1 is auto (VRAM-aware) and -2 or below means all layers, so the floor+ // is -2 rather than 0.+ return Number.isFinite(n) && n >= -2 ? Math.floor(n) : null},},chat_template: {@@ -346,22 +338,6 @@ async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {}}-// Interface settings persist to the Rust settings store (settings.json), not-// webview localStorage — see web-app/src/lib/backendStorage.ts. The value is-// the Zustand-persisted blob `{ state: {...} }`. Defaults to true (feature on).-async function readAutoGenerateTitleSetting(): Promise<boolean> {- try {- const raw = await getBackendSetting(INTERFACE_SETTINGS_STORE_KEY)- if (!raw) return true- const parsed = JSON.parse(raw)- const value = parsed?.state?.autoGenerateTitle- return typeof value === 'boolean' ? value : true- } catch (error) {- logger.warn('Failed to read autoGenerateTitle setting:', error)- return true- }-}-/*** Breadth-first search of `rootDir` for the directory directly containing* a file named `serverName`. Returns the absolute path of that directory,@@ -418,7 +394,7 @@ async function findLlamaServerDir(// - lib/// - e.g. libcudart.so.12-export default class llamacpp_extension extends AIEngine {+export default class llamacpp_extension extends AIEngine implements EmbeddingEngine {provider: string = 'llamacpp'timeout: number = 600llamacpp_env: string = ''@@ -431,29 +407,28 @@ export default class llamacpp_extension extends AIEngine {/** Keyed by modelId; two imports of one model would cancel each other. */private pendingImports: Map<string, Promise<void>> = new Map()private embedderBootstrapError?: string- private isConfiguringBackends: boolean = false- private isUpdatingBackend: boolean = false- private currentUpdate: Promise<{- wasUpdated: boolean- newBackend: string- }> | null = null- private pendingUpdate: Promise<{- wasUpdated: boolean- newBackend: string- }> | null = null- private pendingTarget: string | null = null+ /**+ * True while the fallback embedder is being fetched.+ *+ * The old readiness gate keyed off "no backend selected yet", which happened+ * to cover this window on a fresh install. The engine ships with the app now,+ * so that proxy is gone and this is the direct signal -- without it, a normal+ * first-run download is reported as a failed embedding check.+ */+ private embedderBootstrapping = falseprivate loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promisesprivate unlistenValidationStarted?: () => void- private routerPort?: number- private routerApiKey?: string- private routerStartLock: Promise<void> | null = null+ private enginePort?: number+ private engineApiKey?: string+ private presetPath?: string+ private engineStartLock: Promise<void> | null = nullprivate userModelsMax: number = 1- private routerEmbeddingBonus: number = 0+ private engineEmbeddingBonus: number = 0private loadedChatOrder: string[] = []- // Backend discovery + router spawn run off the onLoad critical path; awaited- // via ensureRouterReady() before any model load so inference never races it.+ // The engine worker spawn runs off the onLoad critical path; awaited via+ // ensureEngineReady() before any model load so inference never races it.private backgroundInit?: Promise<void>/** Single-flight provisioning run; see ensureProvisioned(). */private provisioning?: Promise<void>@@ -463,35 +438,12 @@ export default class llamacpp_extension extends AIEngine {await this.migrateLocalStorageToFile()- let settings = structuredClone(SETTINGS) // Clone to modify settings definition before registration-- // Migration: legacy `version_backend` (single composite string) → split- // into `llamacpp_version` + `llamacpp_backend`. Read from localStorage- // before registerSettings overwrites the persisted set.- try {- const prior = await this.getSettings()- const legacy = prior.find((s) => s.key === 'version_backend')- const legacyValue = legacy?.controllerProps?.value- if (- typeof legacyValue === 'string' &&- legacyValue.includes('/') &&- legacyValue !== 'none'- ) {- const [v, b] = legacyValue.split('/')- if (v && b) {- const vSetting = settings.find((s) => s.key === 'llamacpp_version')- const bSetting = settings.find((s) => s.key === 'llamacpp_backend')- if (vSetting) vSetting.controllerProps.value = v- if (bSetting) bSetting.controllerProps.value = b- logger.info(- `Migrated legacy version_backend '${legacyValue}' → version='${v}', backend='${b}'`- )- }- }- } catch (e) {- logger.warn('version_backend migration check failed (ignored):', e)- }-+ // The engine is bundled at a pinned version, so there is no backend or+ // version to migrate or select. `registerSettings` drops the keys that no+ // longer exist in SETTINGS (llamacpp_version, llamacpp_backend,+ // check_for_updates, auto_update_engine, verify_backend_deps) from the+ // persisted set on its own.+ const settings = structuredClone(SETTINGS)await this.registerSettings(settings)let loadedConfig: any = {}@@ -504,7 +456,6 @@ export default class llamacpp_extension extends AIEngine {)}this.config = loadedConfig as LlamacppConfig- this.recomposeVersionBackend()// Auto-fit is disabled by default on all platforms; ctx-size owns context// sizing. Force off for users a prior build left with fit enabled.@@ -512,7 +463,7 @@ export default class llamacpp_extension extends AIEngine {await this.migrateAutoUnloadToModelsMax()- this.timeout = this.config.timeout+ this.timeout = asI32(this.config.timeout, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUTthis.llamacpp_env = this.config.llamacpp_env// This sets the base directory where model files for this provider are stored.@@ -528,27 +479,12 @@ export default class llamacpp_extension extends AIEngine {events.emit(DownloadEvent.onModelValidationStarted, event.payload)})- // Defer the slow, fail-soft startup (network + subprocess) off onLoad so- // the UI unblocks; performLoad awaits it via ensureRouterReady().- //- // When a usable backend is already installed, start the router first so- // inference is available without waiting on the network-bound update check.- // A restart on the new binary is owned by updateBackend, which needs it to- // health-check the switch. On a fresh install (no backend yet)- // configureBackends must run first to download one before the router can start.- // A first run downloads a backend and an embedding model -- hundreds of- // megabytes. That is not started behind the user's back: the setup screen- // asks first and then calls startFirstRunSetup(). An install that already- // has a backend has nothing to ask about, so it provisions as before, and- // any later attempt to use a local model provisions on demand through- // ensureRouterReady().- if ((await this.hasInstalledBackend()) || (await this.hasSetupConsent())) {- this.backgroundInit = this.ensureProvisioned()- } else {- logger.info(- 'Deferring first-run provisioning until the setup screen asks for it.'- )- }+ // Deferred off onLoad so the UI unblocks; performLoad awaits it via+ // ensureEngineReady(). The engine is bundled with the app now, so there is+ // no backend catalog fetch and no hundreds-of-megabytes download to ask+ // consent for -- only the fallback embedder, which bootstrapDefaultEmbedder+ // still gates on setup consent.+ this.backgroundInit = this.ensureProvisioned()}private async hasSetupConsent(): Promise<boolean> {@@ -576,42 +512,21 @@ export default class llamacpp_extension extends AIEngine {}/**- * Downloads/selects a backend, starts the router, then installs the fallback- * embedder. Single-flight: startup, the setup screen and the first model load- * can all ask for it, and only one run happens.+ * Starts the engine, then installs the fallback embedder. Single-flight:+ * startup, the setup screen and the first model load can all ask for it, and+ * only one run happens.*- * When a usable backend is already installed the router starts first so- * inference is available without waiting on the network-bound update check.- * A restart on the new binary is owned by updateBackend, which needs it to- * health-check the switch. On a fresh install configureBackends must run first- * to download one before the router can start.+ * There is no backend selection step any more -- the engine is linked into+ * the shipped worker at a pinned version, so the ordering dance between+ * "download a backend first" and "start first for availability" is gone.*/private ensureProvisioned(): Promise<void> {this.provisioning ??= (async () => {- if (await this.hasInstalledBackend()) {- try {- await this.startRouter()- } catch (e) {- logger.error('Router failed to start during provisioning:', e)- this.reportMissingLibrariesFromError(e)- }- try {- await this.configureBackends()- } catch (e) {- logger.error('configureBackends failed during provisioning:', e)- }- } else {- try {- await this.configureBackends()- } catch (e) {- logger.error('configureBackends failed during provisioning:', e)- }- try {- await this.startRouter()- } catch (e) {- logger.error('Router failed to start during provisioning:', e)- this.reportMissingLibrariesFromError(e)- }+ try {+ await this.startEngine()+ } catch (e) {+ logger.error('Engine failed to start during provisioning:', e)+ this.reportMissingLibrariesFromError(e)}await this.bootstrapDefaultEmbedder()})()@@ -632,6 +547,9 @@ export default class llamacpp_extension extends AIEngine {try {if (await getBackendSetting(EMBEDDER_BOOTSTRAP_KEY)) returnif (!(await this.hasEmbedderInstalled())) {+ // Set only around the actual fetch, and only when there is one to do:+ // an install that is already present must not flash a pending state.+ this.embedderBootstrapping = trueawait this.import(FALLBACK_EMBEDDING_MODEL_ID, {modelPath: FALLBACK_EMBEDDING_MODEL_URL,})@@ -655,6 +573,10 @@ export default class llamacpp_extension extends AIEngine {'Fallback embedder bootstrap failed (will import on demand):',e)+ } finally {+ // In `finally` so a thrown import cannot leave the checklist reporting+ // "downloading" for the rest of the session.+ this.embedderBootstrapping = false}}@@ -664,9 +586,15 @@ export default class llamacpp_extension extends AIEngine {}/**- * A launch failure that names unresolvable libraries carries the same- * actionable information as a failed static verification, so it raises the- * same dependency dialog instead of surfacing a generic process error.+ * Why the startup embedder install failed, for setup to report. Undefined+ * when it succeeded or has not run; the import is retried on demand, so this+ * is advisory rather than terminal.+ */+ /**+ * A launch failure that names unresolvable libraries is the one dependency+ * problem a bundled engine still has: the GPU driver runtime (CUDA, Vulkan)+ * lives on the user's machine, not in the app. Raises the same dependency+ * dialog the old pre-flight backend verification did.*/private reportMissingLibrariesFromError(error: unknown): void {const err = error as { code?: string; missing_libraries?: unknown }@@ -679,19 +607,19 @@ export default class llamacpp_extension extends AIEngine {: []if (libs.length === 0) return- const [version, backend] = (this.config?.version_backend ?? '').split('/')+ // The engine is bundled, so there is no selected variant to name. The+ // unresolved library itself identifies the runtime that is missing, and+ // getBackendDisplayName matches on exactly these substrings.+ const joined = libs.join(' ').toLowerCase()+ const backend = ['cuda', 'vulkan', 'hip', 'metal'].find((b) =>+ joined.includes(b)+ )events.emit(AppEvent.onBackendVerificationFailed, {backend: backend ?? '',- version: version ?? '',missingLibraries: libs,})}- /**- * Why the startup embedder install failed, for setup to report. Undefined- * when it succeeded or has not run; the import is retried on demand, so this- * is advisory rather than terminal.- */getEmbedderBootstrapError(): string | undefined {return this.embedderBootstrapError}@@ -702,10 +630,9 @@ export default class llamacpp_extension extends AIEngine {* reports the problem and lets the user continue.*/async verifyEmbeddingModel(): Promise<EmbeddingModelReport> {- // The router cannot start before a backend is selected, and the embedder is- // installed after that. Probing during that window would block on the whole- // backend download and then report a failure that is really an absence.- if (!isBackendConfigured(this.config?.version_backend)) {+ // Downloading it is not a defect. Probing mid-download would fail on a+ // model that is simply not there yet and report a warning for it.+ if (this.embedderBootstrapping) {return { status: 'ok', pending: true }}@@ -734,86 +661,22 @@ export default class llamacpp_extension extends AIEngine {}}- /**- * Names the GPU libraries the loader cannot resolve, and raises the same- * dependency dialog a failed static verification does. Empty when the probe- * found nothing or could not run, so callers fall back to the symptom-level- * verdict rather than reporting a cause that was never established.- */- private async probeMissingGpuLibraries(backend: string): Promise<string[]> {- const [version] = (this.config?.version_backend ?? '').split('/')- if (!version || !backend) return []-- try {- const result = await probeBackendGpuLibraries(backend, version)- if (result.inconclusive) return []-- // Built by reduce rather than flatMap: this extension declares an ES2018- // lib, where flatMap is not available.- const seen = new Set<string>()- for (const failure of result.failures) {- for (const lib of failure.missing_libraries ?? []) seen.add(lib)- }- const missing = Array.from(seen)- if (missing.length > 0) {- logger.warn(- `Backend ${backend} cannot load its GPU library; missing: ${missing.join(', ')}`- )- events.emit(AppEvent.onBackendVerificationFailed, {- backend,- version,- missingLibraries: missing,- })- }- return missing- } catch (e) {- logger.warn('Backend load probe failed:', e)- return []- }- }-/*** Detects a GPU backend that runs entirely on the CPU. Such a router starts* cleanly and reports healthy, so this comparison against the engine's own* device list is the only signal that offload never happened.*/async verifyGpuOffload(): Promise<GpuOffloadReport> {- // No backend chosen yet means the engine is still setting itself up. An- // empty name would otherwise read as "a CPU-only build", which is how a- // CUDA install came to be reported as leaving the GPU idle.- if (!isBackendConfigured(this.config?.version_backend)) {- return {- status: 'ok',- backend: '',- gpuExpected: false,- engineDeviceCount: 0,- pending: true,- }- }-- const backend = (this.config?.version_backend ?? '').split('/')[1] ?? ''-- // A CPU build cannot offload, so skip the --list-devices subprocess rather- // than spend a 30s-timeout spawn confirming a known answer.- if (!backendImpliesGpu(backend)) {- return {- status: 'ok',- backend,- gpuExpected: false,- engineDeviceCount: 0,- }- }-- let engineDeviceCount: number+ let devices: DeviceList[]try {- engineDeviceCount = (await this.getDevices()).length+ devices = await this.getDevices()} catch (e) {// Without a device list there is no basis for a reason code, and guessing// one would point the user at the wrong fix.return {status: 'warning',- backend,- gpuExpected: backendImpliesGpu(backend),+ backend: '',+ gpuExpected: false,engineDeviceCount: 0,error: e instanceof Error ? e.message : String(e),}@@ -826,41 +689,12 @@ export default class llamacpp_extension extends AIEngine {logger.warn('Hardware GPU probe failed during setup verification:', e)}- // Zero devices on a GPU build means the library never loaded. ggml discards- // that loader error in a release build, so ask the loader directly to name- // the dependency instead of reporting only the symptom.- if (engineDeviceCount === 0) {- const missing = await this.probeMissingGpuLibraries(backend)- if (missing.length > 0) {- return {- status: 'warning',- backend,- gpuExpected: true,- engineDeviceCount: 0,- reason: 'missingLibrary',- missingLibraries: missing,- }- }- }-return {- backend,- ...evaluateGpuOffload({ backend, engineDeviceCount, hardwareGpuCount }),- }- }-- // True when config.version_backend names a backend that's already downloaded,- // so the router can spawn without waiting on configureBackends.- private async hasInstalledBackend(): Promise<boolean> {- const vb = this.config?.version_backend- if (!vb || vb === 'none' || !vb.includes('/')) return false- const [version, backend] = vb.split('/')- if (!version || !backend) return false- try {- return await isBackendInstalled(backend, version)- } catch (e) {- logger.warn('isBackendInstalled probe failed during onLoad:', e)- return false+ backend: backendFromDeviceIds(devices.map((d) => d.id)),+ ...evaluateGpuOffload({+ engineDeviceCount: devices.length,+ hardwareGpuCount,+ }),}}@@ -965,252 +799,178 @@ export default class llamacpp_extension extends AIEngine {}}- private async persistRecommended(- key: string,- value: string- ): Promise<void> {- const settings = await readSettingsFile()- const entry = settings.find((s) => s.key === key)- if (!entry) return- const cp = entry.controllerProps as { recommended?: string }- if (cp.recommended === value) return- cp.recommended = value- await writeSettingsFile(settings)- }-- private recomposeVersionBackend(): void {- const v = this.config?.llamacpp_version- const b = this.config?.llamacpp_backend- if (v && b && v !== 'none' && b !== 'none') {- this.config.version_backend = `${v}/${b}`- } else if (!this.config.version_backend) {- this.config.version_backend = ''- }- }-/*** Serialized: two concurrent calls would each run the stop-then-spawn- * sequence below, and the second would kill the router the first had just- * brought up. A late caller gets the in-flight start rather than a restart.+ * sequence, and the second would kill the worker the first had just brought+ * up. A late caller gets the in-flight start rather than a restart.*/- private async startRouter(): Promise<void> {- const inflight = this.routerStartLock+ private async startEngine(): Promise<void> {+ const inflight = this.engineStartLockif (inflight) {- logger.info('startRouter already in progress; awaiting the in-flight run')+ logger.info('startEngine already in progress; awaiting the in-flight run')await inflight.catch(() => undefined)return}- this.routerStartLock = this.runStartRouter().finally(() => {- this.routerStartLock = null+ this.engineStartLock = this.runStartEngine().finally(() => {+ this.engineStartLock = null})- return this.routerStartLock+ return this.engineStartLock}- private async runStartRouter(): Promise<void> {- const versionBackend = this.config?.version_backend- if (!isBackendConfigured(versionBackend)) {- logger.info(- `Router will start once backend is configured (version_backend: ${- versionBackend || 'unset'- }).`- )- return- }-- const [version, backend] = (versionBackend as string).split('/')-+ private async runStartEngine(): Promise<void> {const providerPath = await this.getProviderPath()const janDataFolderPath = await getJanDataFolderPath()- const build = parseBuildNumber(version)- const supportsMtp = build !== null && build >= MTP_MIN_BUILDconst { path: presetPath, embeddingCount } = await generatePreset(providerPath,janDataFolderPath,- this.config,- {- supportsMtp,- reservedBackgroundSlots: (await readAutoGenerateTitleSetting()) ? 1 : 0,- }+ this.config)- const backendExe = await getBackendExePath(backend, version)-- const rawMax = (this.config as any).models_max- let modelsMax = 1- if (typeof rawMax === 'number') modelsMax = rawMax- else if (typeof rawMax === 'string' && rawMax.trim().length > 0) {- const n = parseInt(rawMax, 10)- if (!Number.isNaN(n) && n >= 0) modelsMax = n- }- // Reserve a single extra slot when any embedder is installed, so loading- // an embedder doesn't evict the user's chat model. Only one embedding is- // ever loaded at a time (RAG calls load() once per request), so the bonus- // is +1 regardless of how many embedders are installed. 0 (unlimited)- // stays unlimited.- const userModelsMax = modelsMax- this.userModelsMax = userModelsMax- const embeddingSlotBonus =- modelsMax > 0 && embeddingCount > 0 ? 1 : 0- modelsMax += embeddingSlotBonus- this.routerEmbeddingBonus = embeddingSlotBonus-- // Adoption runs before any stop, and is the only thing allowed to end an- // existing router here. It reuses a process whose backend, preset and- // models_max still match, and kills one whose config has moved on. A router- // can outlive the UI (crash, SIGKILL, power loss) since kill_on_drop never- // runs, so this both rescues orphans holding VRAM and makes a redundant- // call a no-op instead of a needless cold restart.- let adopted: Awaited<ReturnType<typeof adoptRouter>> = null- try {- adopted = await adoptRouter(- backendExe,- presetPath,- modelsMax,- this.apiSecret- )- } catch (e) {- logger.warn('Router adoption failed; starting a fresh router:', e)- }- if (adopted) {- this.routerPort = adopted.port- this.routerApiKey = adopted.api_key- logger.info(- `Reusing router on port ${adopted.port} (pid ${adopted.pid}); skipping spawn`- )- return- }-- // Adoption found nothing to adopt, or declined a process it could not- // verify against the lock. A live router with no matching lock would make- // start_router reject, so clear it.- try {- const existing = await invoke<{ port: number; api_key: string } | null>(- 'plugin:llamacpp|get_router_info'- )- if (existing) {- await invoke('plugin:llamacpp|stop_router').catch(() => undefined)- }- } catch {- /* ignore probe failures */- }-- const port = await this.getRandomPort()- const apiKey = await this.generateApiKey('router', String(port))+ const modelsMax = this.resolveModelsMax(embeddingCount)+ // Idempotent in the plugin: a second start returns the running worker+ // rather than orphaning it, so a redundant call is a no-op instead of a+ // cold restart. That is also why there is no adoption dance here: the+ // worker exits on stdin EOF, which the OS delivers when this process dies+ // by any means -- including SIGKILL, where kill_on_drop never runs -- so+ // there is nothing to adopt or reap. Not because a child dies with its+ // parent; it does not, it gets reparented.const envs: Record<string, string> = {}- envs['LLAMA_API_KEY'] = apiKeyenvs['LLAMA_ARG_TIMEOUT'] = String(this.timeout)if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)- // --no-webui was renamed to --no-ui in upstream b9222. Keep the legacy- // flag for older backends; the deprecated form still works on newer ones- // but emits a warning, so prefer the new spelling when available.- const NO_UI_RENAME_BUILD = 9222- const noUiFlag =- build !== null && build >= NO_UI_RENAME_BUILD ? '--no-ui' : '--no-webui'-- // Beside app.log in the managed logs folder, where a bug report will look.- // The filename is derived from the port inside the plugin.- const logDir = await joinPath([janDataFolderPath, 'logs'])-- const info = await invoke<{ port: number; api_key: string; pid: number }>(- 'plugin:llamacpp|start_router',- {- backendExe,- presetPath,- logDir,- port,- apiKey,- modelsMax,- defaultArgs: [noUiFlag],- envs,- }+ const info = await startEngine(+ presetPath,+ modelsMax,+ this.resolveThreadCacheBudget(),+ envs)-- this.routerPort = info.port- this.routerApiKey = info.api_key+ this.enginePort = info.port+ this.engineApiKey = info.api_key+ this.presetPath = presetPathlogger.info(- `Router started on port ${info.port} (pid ${info.pid}, models_max=${modelsMax} [user=${userModelsMax}, +${embeddingSlotBonus} embedding, ${embeddingCount} installed], preset=${presetPath})`+ `Engine worker started on port ${info.port} (pid ${info.pid}, models_max=${modelsMax}, ${info.models.length} models registered, preset=${presetPath})`)}/**- * 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.+ * Drops a thread's saved prompt cache, for a thread the user deleted.+ *+ * Best-effort by design: the cache is invisible to the user and the store+ * prunes by size anyway, so failing here must not make deleting a thread+ * fail. Returns how many states were dropped.*/- private async refreshRouterPreset(): Promise<void> {- if (!(await this.getRouterInfo())) {- await this.startRouter() // cold start- return+ async forgetThreadCache(threadId: string): Promise<number> {+ try {+ return await eraseThreadSlotState({+ threadId,+ cacheDir: threadCacheDir(await this.getProviderPath()),+ })+ } catch (e) {+ logger.warn(`could not drop the saved cache for thread ${threadId}: ${e}`)+ return 0+ }+ }++ /**+ * The disk budget for saved thread caches, in MiB.+ *+ * 0 is the off switch on the worker side, so the toggle and the size collapse+ * into one number: a disabled feature and a zero budget are the same thing,+ * and keeping them separate would let the worker create a directory it would+ * never write to.+ */+ private resolveThreadCacheBudget(): number {+ if (this.config.persist_thread_cache === false) return 0+ const raw = Number(this.config.thread_cache_size)+ if (!Number.isFinite(raw) || raw <= 0) return 0+ return Math.floor(raw)+ }++ /**+ * `models_max` including the embedding slot bonus.+ *+ * Reserves one extra slot when any embedder is installed so loading it does+ * not evict the user's chat model. Only one embedding model is ever resident+ * (RAG calls load() once per request), so the bonus is +1 regardless of how+ * many are installed. 0 (unlimited) stays unlimited.+ */+ private resolveModelsMax(embeddingCount: number): number {+ const raw = (this.config as { models_max?: unknown }).models_max+ let modelsMax = 1+ if (typeof raw === 'number') modelsMax = raw+ else if (typeof raw === 'string' && raw.trim().length > 0) {+ const n = parseInt(raw, 10)+ if (!Number.isNaN(n) && n >= 0) modelsMax = n}+ this.userModelsMax = modelsMax+ const bonus = modelsMax > 0 && embeddingCount > 0 ? 1 : 0+ this.engineEmbeddingBonus = bonus+ return modelsMax + bonus+ }- 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+ /**+ * Apply a preset change (model added/removed/renamed or a per-model setting)+ * to the running worker. Models whose preset section is unchanged stay+ * loaded, so an embedder import or a settings write no longer cold-reloads+ * the model the user is talking to.+ *+ * Unlike the router this also resizes `models_max`, so a change in the+ * embedding slot bonus no longer needs a restart either -- which was the one+ * remaining case that evicted a live chat model.+ */+ private async refreshEnginePreset(): Promise<void> {+ if (!(await this.getEngineInfo())) {+ await this.startEngine() // cold startreturn}const providerPath = await this.getProviderPath()const janDataFolderPath = await getJanDataFolderPath()- const supportsMtp = build >= MTP_MIN_BUILD- const { embeddingCount } = await generatePreset(+ const { path: presetPath, embeddingCount } = await generatePreset(providerPath,janDataFolderPath,- this.config,- {- supportsMtp,- reservedBackgroundSlots: (await readAutoGenerateTitleSetting()) ? 1 : 0,- }+ this.config)+ this.presetPath = presetPath- // models_max is fixed at router spawn; a live reload can't grow it. If an- // embedder appeared (e.g. sentence-transformer-mini imported on demand) or- // the last one was removed, restart so the +1 embedding slot is applied —- // otherwise chat and embedding models evict each other on every RAG call.- const requiredBonus =- this.userModelsMax > 0 && embeddingCount > 0 ? 1 : 0- if (requiredBonus !== this.routerEmbeddingBonus) {+ try {+ const report = await reloadEngineModels(+ presetPath,+ this.resolveModelsMax(embeddingCount),+ this.resolveThreadCacheBudget()+ )logger.info(- `Embedding slot bonus changed (${this.routerEmbeddingBonus} -> ${requiredBonus}); restarting router to resize models_max`+ `Engine preset reloaded: +${report.added.length} ~${report.changed.length} -${report.removed.length}, ${report.kept.length} kept loaded`)- await this.startRouter()- return- }-- 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()+ logger.warn('Live engine reload failed; falling back to restart:', e)+ await this.startEngine()}}/**- * Public accessor for downstream consumers. Returns `null` if the router- * hasn't been started successfully yet.+ * Public accessor for downstream consumers. Returns `null` if the engine+ * worker hasn't started successfully yet.*/- async getRouterInfo(): Promise<{ port: number; apiKey: string } | null> {- if (this.routerPort != null && this.routerApiKey) {- return { port: this.routerPort, apiKey: this.routerApiKey }- }+ async getEngineInfo(): Promise<{ port: number; apiKey: string } | null> {+ // Deliberately not answered from the cached port: get_engine_info is the+ // one place a worker that died is noticed -- it reaps the handle and+ // reports nothing running -- and every caller here uses this as the+ // liveness probe before deciding whether to respawn. Answering from+ // enginePort would keep handing out a closed port for the rest of the+ // session, which is exactly the crash the worker process exists to survive.try {- const info = await invoke<- { port: number; api_key: string; pid: number } | null- >('plugin:llamacpp|get_router_info')+ const info = await pluginGetEngineInfo()if (info) {- this.routerPort = info.port- this.routerApiKey = info.api_key+ this.enginePort = info.port+ this.engineApiKey = info.api_keyreturn { port: info.port, apiKey: info.api_key }}+ this.enginePort = undefined+ this.engineApiKey = undefined} catch (e) {- logger.warn('get_router_info failed:', e)+ logger.warn('get_engine_info failed:', e)}return null}@@ -1230,10 +990,10 @@ export default class llamacpp_extension extends AIEngine {})| undefined> {- const router = await this.getRouterInfo()- if (!router || !modelId) return undefined- // Router runs with models_autoload=true, so `/props?model=X` against an- // unloaded model would trigger a load. Gate on the loaded-set first.+ const engine = await this.getEngineInfo()+ if (!engine || !modelId) return undefined+ // A request naming an unloaded model loads it on demand, so `/props` alone+ // would trigger a load. Gate on the loaded-set first.try {const loaded = await this.getLoadedModels()if (!loaded.includes(modelId)) return undefined@@ -1241,9 +1001,9 @@ export default class llamacpp_extension extends AIEngine {return undefined}try {- const url = `http://127.0.0.1:${router.port}/props?model=${encodeURIComponent(modelId)}`+ const url = `http://127.0.0.1:${engine.port}/props?model=${encodeURIComponent(modelId)}`const res = await fetch(url, {- headers: { Authorization: `Bearer ${router.apiKey}` },+ headers: { Authorization: `Bearer ${engine.apiKey}` },})if (!res.ok) return undefinedconst json = (await res.json()) as {@@ -1316,943 +1076,142 @@ export default class llamacpp_extension extends AIEngine {)}} catch (e) {- logger.warn('migrateAutoUnloadToModelsMax failed:', e)- return- }-- await setBackendSetting(MIGRATION_KEY, '1')- }-- private async getStoredBackendType(): Promise<string | null> {- return getBackendSetting('llama_cpp_backend_type')- }-- private async setStoredBackendType(backendType: string): Promise<void> {- await setBackendSetting('llama_cpp_backend_type', backendType)- logger.info(`Stored backend type preference: ${backendType}`)- }-- private async clearStoredBackendType(): Promise<void> {- await removeBackendSetting('llama_cpp_backend_type')- logger.info('Cleared stored backend type preference')- }-- private async migrateFitOff(): Promise<void> {- const MIGRATION_KEY = 'llamacpp_fit_off_v1'- if (await getBackendSetting(MIGRATION_KEY)) return-- if (this.config.fit === true) {- const settings = await this.getSettings()- await this.updateSettings(- settings.map((item) => {- if (item.key === 'fit') {- item.controllerProps.value = false- }- return item- })- )- this.config.fit = false- logger.info('Migrated fit setting: disabled')- }-- await setBackendSetting(MIGRATION_KEY, '1')- }-- private async migratePersistedModelSettingsToYaml(): Promise<void> {- if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return-- const persistedModels = await readPersistedLlamacppModels()- if (persistedModels.length === 0) {- await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')- return- }-- const providerPath = await this.getProviderPath()-- for (const persistedModel of persistedModels) {- const modelId =- typeof persistedModel.id === 'string' ? persistedModel.id : undefined- if (!modelId || !persistedModel.settings) continue-- const configPath = await joinPath([- providerPath,- 'models',- modelId,- 'model.yml',- ])- if (!(await fs.existsSync(configPath))) continue-- const cfg = (await invoke<ModelConfig>('read_yaml', {- path: configPath,- })) as ModelConfig & Record<string, unknown>-- let touched = false- for (const [sidebarKey, persistedSetting] of Object.entries(- persistedModel.settings- )) {- const mapping = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]- if (!mapping) continue-- if (mapping.yamlKey in cfg) continue-- const next = mapping.coerce(persistedSetting?.controller_props?.value)- if (next === null) continue-- ;(cfg as Record<string, unknown>)[mapping.yamlKey] = next- touched = true- }-- if (touched) {- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })- }- }-- await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')- }-- async configureBackends(): Promise<void> {- if (this.isConfiguringBackends) {- logger.info(- 'configureBackends already in progress, skipping duplicate call'- )- return- }-- this.isConfiguringBackends = true-- try {- let version_backends: { version: string; backend: string }[] = []-- try {- version_backends = await listSupportedBackends(- this.config.check_for_updates !== false- )- if (version_backends.length === 0) {- throw new Error(- 'No supported backend binaries found for this system. Backend selection and auto-update will be unavailable.'- )- } else {- version_backends.sort((a, b) => b.version.localeCompare(a.version))- }- } catch (error) {- throw new Error(- `Failed to fetch supported backends: ${- error instanceof Error ? error.message : error- }`- )- }-- // Get stored backend preference- const storedBackendType = await this.getStoredBackendType()- let bestAvailableBackendString = ''-- // "Recommended" is computed against upstream releases only — a- // user-side-loaded backend (Install from File) must not bias the- // suggestion. If we have no remote data (check_for_updates off or- // offline), there is no honest recommendation to surface.- const remoteOnly =- this.config.check_for_updates !== false- ? await fetchRemoteBackends()- : []- bestAvailableBackendString =- remoteOnly.length > 0- ? await this.determineBestBackend(remoteOnly)- : ''-- if (storedBackendType) {- // Delegate migration check to Rust- const migrationTarget = await shouldMigrateBackend(- storedBackendType,- version_backends- )-- if (migrationTarget) {- logger.info(- `Migrating stored backend type preference from old '${storedBackendType}' to new common type: '${migrationTarget}'`- )- await this.setStoredBackendType(migrationTarget)- }-- const effectiveStoredBackendType = migrationTarget || storedBackendType-- // Use the effective (migrated) type to find the latest version- const preferredBackendString = await findLatestVersionForBackend(- version_backends,- effectiveStoredBackendType- )-- if (preferredBackendString) {- // Override bestAvailableBackendString with the user preference- // The returned string from Rust is "version/backend"- bestAvailableBackendString = preferredBackendString- logger.info(- `Using stored backend preference: ${bestAvailableBackendString}`- )- } else {- logger.warn(- `Stored backend type '${effectiveStoredBackendType}' not available, falling back to best backend`- )- // Clear the invalid stored preference- await this.clearStoredBackendType()- // bestAvailableBackendString remains as the priority one calculated earlier- }- }-- let settings = structuredClone(SETTINGS)- const versionSetting = settings.find((s) => s.key === 'llamacpp_version')- const backendSetting = settings.find((s) => s.key === 'llamacpp_backend')- if (!versionSetting || !backendSetting) {- throw new Error(- 'Critical settings "llamacpp_version" / "llamacpp_backend" not found.'- )- }-- // Read prior persisted values (may have been pre-populated by the- // legacy-migration pass in onLoad, or carry user-edited values from a- // prior session).- const priorPersisted = await this.getSettings()- const priorVersion = String(- priorPersisted.find((s) => s.key === 'llamacpp_version')?.controllerProps- .value ?? ''- )- const priorBackend = String(- priorPersisted.find((s) => s.key === 'llamacpp_backend')?.controllerProps- .value ?? ''- )-- // Flag versions already on disk so the dropdown distinguishes a rollback- // (instant, works offline) from a download.- const installedVersions = new Set(- (await getLocalInstalledBackends().catch((e) => {- logger.warn('Could not list local backends for the version list:', e)- return [] as { version: string; backend: string }[]- })).map((b) => b.version)- )-- const allVersions = Array.from(- new Set(version_backends.map((b) => b.version))- )- versionSetting.controllerProps.options = allVersions.map((v) => ({- value: v,- name: v,- installed: installedVersions.has(v),- }))-- const allBackends = Array.from(- new Set(version_backends.map((b) => b.backend))- )- backendSetting.controllerProps.options = allBackends.map((b) => ({- value: b,- name: b,- }))-- const [bestVersion, bestBackend] =- bestAvailableBackendString.split('/')- if (bestVersion) versionSetting.controllerProps.recommended = bestVersion- if (bestBackend) backendSetting.controllerProps.recommended = bestBackend-- // Decide initial UI values. Priority: valid prior selection → best-available.- let initialVersion = bestVersion || ''- let initialBackend = bestBackend || ''- if (- priorVersion &&- priorBackend &&- priorVersion !== 'none' &&- priorBackend !== 'none'- ) {- const normalizedBackend = await mapOldBackendToNew(priorBackend)- const composed = `${priorVersion}/${normalizedBackend}`- if (- version_backends.some(- (e) => `${e.version}/${e.backend}` === composed- )- ) {- initialVersion = priorVersion- initialBackend = normalizedBackend- const currentStoredBackend = await this.getStoredBackendType()- if (currentStoredBackend !== normalizedBackend) {- await this.setStoredBackendType(normalizedBackend)- logger.info(- `Stored backend type preference from saved setting: ${normalizedBackend}`- )- }- }- } else if (bestBackend) {- const currentStoredBackend = await this.getStoredBackendType()- if (currentStoredBackend !== bestBackend) {- await this.setStoredBackendType(bestBackend)- logger.info(- `Stored backend type preference from best available: ${bestBackend}`- )- }- }-- versionSetting.controllerProps.value = initialVersion- backendSetting.controllerProps.value = initialBackend- logger.info(- `Initial UI defaults: llamacpp_version='${initialVersion}', llamacpp_backend='${initialBackend}'`- )-- // Must await — registerSettings is async; without await, the- // persistRecommended writes below race with its merge+write and lose.- await this.registerSettings(settings)-- // core's registerSettings preserves the previous `recommended` over the- // new one (see extension.ts:142-148). Force-write afterward so a stale- // recommendation from a prior session can't outlive a fresh compute.- await this.persistRecommended('llamacpp_version', bestVersion || '')- await this.persistRecommended('llamacpp_backend', bestBackend || '')-- let effectiveBackendString = this.config.version_backend- let backendWasDownloaded = false-- // Handle fresh installation case where version_backend might be 'none' or invalid- if (- (!effectiveBackendString ||- effectiveBackendString === 'none' ||- !effectiveBackendString.includes('/') ||- // If the selected backend is not in the list of supported backends- // Need to reset too- !version_backends.some(- (e) => `${e.version}/${e.backend}` === effectiveBackendString- )) &&- // Ensure we have a valid best available backend- bestAvailableBackendString- ) {- effectiveBackendString = bestAvailableBackendString- logger.info(- `Fresh installation or invalid backend detected, using: ${effectiveBackendString}`- )-- const [newV, newB] = effectiveBackendString.split('/')- this.config.llamacpp_version = newV- this.config.llamacpp_backend = newB- this.recomposeVersionBackend()-- const updatedSettings = await this.getSettings()- await this.updateSettings(- updatedSettings.map((item) => {- if (item.key === 'llamacpp_version') {- item.controllerProps.value = newV- } else if (item.key === 'llamacpp_backend') {- item.controllerProps.value = newB- }- return item- })- )- logger.info(`Updated UI settings to show: ${effectiveBackendString}`)-- if (events && typeof events.emit === 'function') {- events.emit('settingsChanged', {- key: 'llamacpp_version',- value: newV,- })- events.emit('settingsChanged', {- key: 'llamacpp_backend',- value: newB,- })- }- }-- // Download and install the backend if not already present- if (effectiveBackendString) {- const [version, backend] = effectiveBackendString.split('/')- if (version && backend) {- const isInstalled = await isBackendInstalled(backend, version)- if (!isInstalled) {- logger.info(`Installing initial backend: ${effectiveBackendString}`)- await this.ensureBackendReady(backend, version)- backendWasDownloaded = true- logger.info(- `Successfully installed initial backend: ${effectiveBackendString}`- )- }- }- }-- if (this.config.auto_update_engine && this.config.check_for_updates) {- const updateResult = await this.handleAutoUpdate(- bestAvailableBackendString- )- if (updateResult.wasUpdated) {- effectiveBackendString = updateResult.newBackend- backendWasDownloaded = true- }- }-- if (!backendWasDownloaded && effectiveBackendString) {- await this.ensureFinalBackendInstallation(effectiveBackendString)- }-- // Run dependency verification once after the backend is confirmed- // installed. This covers both fresh downloads and pre-existing installs,- // and runs only once per app startup via the isConfiguringBackends guard.- if (effectiveBackendString && this.config.verify_backend_deps !== false) {- // effectiveBackendString is expected to be "<version>/<backend>" (e.g.- // "b4589/linux-cuda-12"). Any other shape silently skips verification.- const [version, backend] = effectiveBackendString.split('/')- if (version && backend) {- // Advisory and fail-soft — defer to browser idle so it yields to the- // router (already up by now) and the UI instead of running inline.- const verify = () => void this.verifyBackendDeps(backend, version)- if (typeof window.requestIdleCallback === 'function')- window.requestIdleCallback(verify, { timeout: 3000 })- else setTimeout(verify, 0)- }- }- } finally {- this.isConfiguringBackends = false- }- }-- /*- * Narrow refresh of the `version_backend` setting's options dropdown.- *- * Re-scans installed + remote backends and rewrites- * `controllerProps.options` on the persisted setting without re-running- * the heavy `configureBackends` flow (no autoupdate, no initial- * download, no dep verification). The user's current selection is- * preserved unless it disappeared from the list.- *- * Used by the manual "Install from file" flow so the just-extracted- * backend shows up in the dropdown immediately.- */- async refreshBackendOptions(): Promise<void> {- let version_backends: { version: string; backend: string }[] = []- try {- version_backends = await listSupportedBackends(- this.config.check_for_updates !== false- )- } catch (e) {- logger.error(- `refreshBackendOptions: failed to list supported backends: ${String(e)}`- )- return- }- if (version_backends.length === 0) {- logger.warn('refreshBackendOptions: no supported backends found')- return- }- version_backends.sort((a, b) => b.version.localeCompare(a.version))-- const settings = await this.getSettings()- const versionSetting = settings.find((s) => s.key === 'llamacpp_version')- const backendSetting = settings.find((s) => s.key === 'llamacpp_backend')- if (!versionSetting || !backendSetting) {- logger.error(- 'refreshBackendOptions: llamacpp_version/llamacpp_backend not found in persisted settings'- )- return- }-- const allVersions = Array.from(- new Set(version_backends.map((b) => b.version))- )- const allBackends = Array.from(- new Set(version_backends.map((b) => b.backend))- )- ;(versionSetting.controllerProps as DropdownComponentProps).options =- allVersions.map((v) => ({- value: v,- name: v,- }))- ;(backendSetting.controllerProps as DropdownComponentProps).options =- allBackends.map((b) => ({- value: b,- name: b,- }))-- const currentV = String(versionSetting.controllerProps.value ?? '')- const currentB = String(backendSetting.controllerProps.value ?? '')- const composedStillPresent =- currentV &&- currentB &&- version_backends.some(- (e) => e.version === currentV && e.backend === currentB- )- if (!composedStillPresent) {- const best = await this.determineBestBackend(version_backends)- const [bv, bb] = best.split('/')- if (bv && bb) {- versionSetting.controllerProps.value = bv- backendSetting.controllerProps.value = bb- this.config.llamacpp_version = bv- this.config.llamacpp_backend = bb- this.recomposeVersionBackend()- }- }-- await this.registerSettings(settings)-- if (events && typeof events.emit === 'function') {- events.emit('settingsChanged', {- key: 'llamacpp_version',- value: versionSetting.controllerProps.value,- })- events.emit('settingsChanged', {- key: 'llamacpp_backend',- value: backendSetting.controllerProps.value,- })- }- }-- private async determineBestBackend(- version_backends: { version: string; backend: string }[]- ): Promise<string> {- if (version_backends.length === 0) return ''-- // Check GPU memory availability via system info- let hasEnoughGpuMemory = false- try {- const sysInfo = await getSystemInfo()- for (const gpuInfo of sysInfo.gpus) {- if (gpuInfo.total_memory >= 6 * 1024) {- hasEnoughGpuMemory = true- break- }- }- } catch (error) {- logger.warn('Failed to get system info for GPU memory check:', error)- // Default to false if we can't determine GPU memory- hasEnoughGpuMemory = false- }-- // Use Rust logic to prioritize backends- const result = await prioritizeBackends(- version_backends,- hasEnoughGpuMemory- )- return result.backend_string- }-- /**- * Serializes backend updates. A request arriving mid-update is queued rather- * than dropped, and only the newest queued target survives -- if a user- * clicks through three versions while a download runs, the first two are- * obsolete by the time they could run. All callers waiting on the queued slot- * receive the same result.- */- async updateBackend(- targetBackendString: string- ): Promise<{ wasUpdated: boolean; newBackend: string }> {- if (this.currentUpdate) {- this.pendingTarget = targetBackendString- logger.info(- `Backend update in progress; queued ${targetBackendString} (supersedes any earlier queued target)`- )- events.emit(AppEvent.onBackendUpdateQueued, {- target: targetBackendString,- })-- this.pendingUpdate ??= this.currentUpdate- .catch(() => undefined)- .then(() => {- const next = this.pendingTarget as string- this.pendingTarget = null- this.pendingUpdate = null- return this.updateBackend(next)- })- return this.pendingUpdate- }-- // `runUpdate` clears currentUpdate inside its own body, so a queued- // continuation chained onto it always observes an idle slot.- this.currentUpdate = this.runUpdate(targetBackendString)- return this.currentUpdate- }-- private async runUpdate(- targetBackendString: string- ): Promise<{ wasUpdated: boolean; newBackend: string }> {- this.isUpdatingBackend = true- const startedAt = Date.now()- const from = this.config.version_backend- let previous: BackendSelection | undefined-- try {- if (!targetBackendString)- throw new Error(- `Invalid backend string: ${targetBackendString} supplied to update function`- )-- const backendParts = targetBackendString.split('/')-- if (- backendParts.length !== 2 ||- !backendParts[0]?.trim() ||- !backendParts[1]?.trim()- ) {- throw new Error(- `Invalid backend string format: "${targetBackendString}". Expected "version/backend".`- )- }-- const [rawVersion, rawBackend] = backendParts- const version = rawVersion.trim()- const backend = rawBackend.trim()-- // Normalize the target backend string to use trimmed values- targetBackendString = `${version}/${backend}`-- logger.info(- `Updating backend to ${targetBackendString} (backend type: ${backend})`- )-- previous = await this.captureBackendSelection()-- // Download new backend using the original asset/backend name- await this.ensureBackendReady(backend, version)-- // Add delay on Windows- if (IS_WINDOWS) {- await new Promise((resolve) => setTimeout(resolve, 1000))- }-- await this.commitBackendSelection(version, backend)-- if (await this.restartRouterAndProbe()) {- logger.info(`Successfully updated to backend: ${targetBackendString}`)- await this.pruneOldBackendVersions(version, backend)- await this.recordUpdateHistory({- from,- to: targetBackendString,- outcome: 'updated',- durationMs: Date.now() - startedAt,- })- return { wasUpdated: true, newBackend: targetBackendString }- }-- throw new Error(- `Router failed its health check on backend ${targetBackendString}`- )- } catch (error) {- logger.error('Backend update failed:', error)- const rollbackOutcome = await this.rollbackBackendSelection(previous)- await this.recordUpdateHistory({- from,- to: targetBackendString,- outcome:- rollbackOutcome === 'not-attempted' ? 'failed' : rollbackOutcome,- error: String(error),- durationMs: Date.now() - startedAt,- })- return { wasUpdated: false, newBackend: this.config.version_backend }- } finally {- this.isUpdatingBackend = false- this.currentUpdate = null- }- }-- /**- * Every update outcome, newest first, for diagnosing a switch after the fact.- * Returns an empty list when nothing has been recorded yet.- */- async getBackendUpdateHistory(): Promise<BackendUpdateRecord[]> {- try {- const path = await joinPath([- await this.getProviderPath(),- UPDATE_HISTORY_FILENAME,- ])- if (!(await fs.existsSync(path))) return []- const parsed = JSON.parse(await fs.readFileSync(path, 'utf8'))- return Array.isArray(parsed) ? parsed : []- } catch (e) {- logger.warn('Could not read backend update history:', e)- return []- }- }-- /**- * Append one outcome to the update log. Never throws: losing a diagnostic- * record must not turn a working update into a failed one.- */- private async recordUpdateHistory(- record: Omit<BackendUpdateRecord, 'timestamp'>- ): Promise<void> {- try {- const path = await joinPath([- await this.getProviderPath(),- UPDATE_HISTORY_FILENAME,- ])- const history = await this.getBackendUpdateHistory()- history.unshift({ timestamp: new Date().toISOString(), ...record })- await fs.writeFileSync(- path,- JSON.stringify(history.slice(0, UPDATE_HISTORY_LIMIT), null, 2)- )- } catch (e) {- logger.warn('Could not record backend update history:', e)- }- }-- /**- * Prune superseded installs, keeping BACKEND_VERSIONS_RETAINED older ones as- * rollback targets. Runs only after the new backend has passed its health- * probe -- pruning earlier would delete the very copy a rollback needs.- * Best-effort: a full disk is worse than a failed update, but not by enough- * to undo a switch that already works.- */- private async pruneOldBackendVersions(- version: string,- backend: string- ): Promise<void> {- try {- const janDataFolderPath = await getJanDataFolderPath()- const backendsDir = await joinPath([- janDataFolderPath,- 'llamacpp',- 'backends',- ])-- if (IS_WINDOWS) {- await new Promise((resolve) => setTimeout(resolve, 500))- }-- const removed = await removeOldBackendVersions(- backendsDir,- version,- backend,- BACKEND_VERSIONS_RETAINED- )- if (removed.length) {- logger.info(`Pruned ${removed.length} superseded backend install(s)`)- }- } catch (cleanupError) {- logger.warn('Failed to remove old backend versions:', cleanupError)- }- }-- private async captureBackendSelection(): Promise<BackendSelection> {- return {- version: this.config.llamacpp_version,- backend: this.config.llamacpp_backend,- storedType: (await this.getStoredBackendType()) || undefined,- }- }-- /**- * Persist a backend choice across all three places it lives: the settings- * file, the stored type preference, and in-memory config. Settings are- * written before the in-memory mutation so a failure leaves config coherent.- */- private async commitBackendSelection(- version: string,- backend: string- ): Promise<void> {- const effectiveBackendType = await mapOldBackendToNew(backend)- const currentStoredBackend = await this.getStoredBackendType()-- const settings = await this.getSettings()- await this.updateSettings(- settings.map((item) => {- if (item.key === 'llamacpp_version') {- item.controllerProps.value = version- } else if (item.key === 'llamacpp_backend') {- item.controllerProps.value = backend- }- return item- })- )-- if (currentStoredBackend !== effectiveBackendType) {- await this.setStoredBackendType(effectiveBackendType)- logger.info(- `Updated stored backend type preference: ${effectiveBackendType}`- )- }-- this.config.llamacpp_version = version- this.config.llamacpp_backend = backend- this.recomposeVersionBackend()- this.config.device = ''-- if (events && typeof events.emit === 'function') {- events.emit('settingsChanged', { key: 'llamacpp_version', value: version })- events.emit('settingsChanged', { key: 'llamacpp_backend', value: backend })- }- }-- /**- * Bring the router up on whatever backend config currently names and confirm- * it answers `/health`. A spawn that throws and a process that starts but- * can't serve are the same failure to the caller.- *- * This is the only gate on a backend switch. Static dependency analysis is- * deliberately not one: it is advisory on every other path and cannot be- * trusted to fail a switch (see verifyBackendInstallation).- */- private async restartRouterAndProbe(): Promise<boolean> {- try {- await this.startRouter()- } catch (e) {- logger.error('Router failed to start on updated backend:', e)- return false+ logger.warn('migrateAutoUnloadToModelsMax failed:', e)+ return}- return await routerHealth()++ await setBackendSetting(MIGRATION_KEY, '1')}- /**- * Restore the backend that was active before a failed update and bring its- * router back. Nothing to do when the update failed before the commit, or- * when there was no valid prior selection (first-run install).- */- private async rollbackBackendSelection(- previous: BackendSelection | undefined- ): Promise<'rolled-back' | 'rollback-failed' | 'not-attempted'> {- if (!previous?.version || !previous.backend) return 'not-attempted'- if (- this.config.llamacpp_version === previous.version &&- this.config.llamacpp_backend === previous.backend- ) {- return 'not-attempted'- }+ private async migrateFitOff(): Promise<void> {+ const MIGRATION_KEY = 'llamacpp_fit_off_v1'+ if (await getBackendSetting(MIGRATION_KEY)) return- const target = `${previous.version}/${previous.backend}`- logger.warn(`Rolling back to previous backend: ${target}`)- try {- await this.commitBackendSelection(previous.version, previous.backend)- if (previous.storedType) {- await this.setStoredBackendType(previous.storedType)- }- const healthy = await this.restartRouterAndProbe()- if (!healthy) {- logger.error(`Rollback target ${target} also failed its health check`)- }- events.emit(AppEvent.onBackendRollback, {- backend: previous.backend,- version: previous.version,- })- return healthy ? 'rolled-back' : 'rollback-failed'- } catch (e) {- logger.error(`Rollback to ${target} failed:`, e)- return 'rollback-failed'+ if (this.config.fit === true) {+ const settings = await this.getSettings()+ await this.updateSettings(+ settings.map((item) => {+ if (item.key === 'fit') {+ item.controllerProps.value = false+ }+ return item+ })+ )+ this.config.fit = false+ logger.info('Migrated fit setting: disabled')}++ await setBackendSetting(MIGRATION_KEY, '1')}- private async handleAutoUpdate(- bestAvailableBackendString: string- ): Promise<{ wasUpdated: boolean; newBackend: string }> {- logger.info(- `Auto-update engine is enabled. Current backend: ${this.config.version_backend}. Best available: ${bestAvailableBackendString}`- )+ private async migratePersistedModelSettingsToYaml(): Promise<void> {+ if (await getBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY)) return- if (!bestAvailableBackendString) {- logger.warn(- 'Auto-update enabled, but no best available backend determined'- )- return { wasUpdated: false, newBackend: this.config.version_backend }- }+ const persistedModels = await readPersistedLlamacppModels()+ const providerPath = await this.getProviderPath()- // If version_backend is empty, invalid, or 'none', use the best available backend- if (- !this.config.version_backend ||- this.config.version_backend === '' ||- this.config.version_backend === 'none' ||- !this.config.version_backend.includes('/')- ) {- logger.info(- 'No valid backend currently selected, using best available backend'- )+ // v1's n_gpu_layers stamp lives in model.yml, not in the persisted+ // settings, so it has to be swept even when nothing is persisted.+ await this.stripLegacyNglFromModelYaml(providerPath)- return await this.updateBackend(bestAvailableBackendString)+ if (persistedModels.length === 0) {+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')+ return}- // Use Rust checkBackendForUpdates logic implicitly here by using the helpers- const version_backends = await listSupportedBackends(true)- const checkResult = await checkBackendForUpdates(- this.config.version_backend,- version_backends- )+ for (const persistedModel of persistedModels) {+ const modelId =+ typeof persistedModel.id === 'string' ? persistedModel.id : undefined+ if (!modelId || !persistedModel.settings) continue- if (checkResult.update_needed && checkResult.target_backend) {- logger.info(- `Auto-updating to new version: ${checkResult.new_version} (${checkResult.target_backend})`- )- return await this.updateBackend(checkResult.target_backend)- }+ const configPath = await joinPath([+ providerPath,+ 'models',+ modelId,+ 'model.yml',+ ])+ if (!(await fs.existsSync(configPath))) continue- // If no update needed, check if we need to fall back (e.g. current backend not supported anymore)- // The Rust check_backend_for_updates handles finding the latest version for current type.- // If it returns no target_backend, it means current type is not found.- if (!checkResult.target_backend) {- const [currentVersion, currentBackend] =- this.config.version_backend.split('/')- const currentEffectiveType = await mapOldBackendToNew(currentBackend)- const bestEffectiveType = await mapOldBackendToNew(- bestAvailableBackendString.split('/')[1]- )+ const cfg = (await invoke<ModelConfig>('read_yaml', {+ path: configPath,+ })) as ModelConfig & Record<string, unknown>++ let touched = false- if (currentEffectiveType !== bestEffectiveType) {+ // Undo v1's n_gpu_layers stamp so upstream's auto offload applies again.+ if (cfg.n_gpu_layers === LEGACY_NGL_DEFAULT) {+ delete (cfg as Record<string, unknown>).n_gpu_layers+ touched = truelogger.info(- `Current backend type ${currentEffectiveType} not available, falling back to best available: ${bestAvailableBackendString}`+ `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${modelId}; GPU offload is auto again`)- return await this.updateBackend(bestAvailableBackendString)}- }- return { wasUpdated: false, newBackend: this.config.version_backend }- }+ for (const [sidebarKey, persistedSetting] of Object.entries(+ persistedModel.settings+ )) {+ const mapping = MODEL_SETTINGS_YAML_MAPPING[sidebarKey]+ if (!mapping) continue- async checkBackendForUpdates(): Promise<{- updateNeeded: boolean- newVersion: string- targetBackend?: string- }> {- try {- const version_backends = await listSupportedBackends(true)- const result = await checkBackendForUpdates(- this.config.version_backend,- version_backends- )+ if (mapping.yamlKey in cfg) continue- return {- updateNeeded: result.update_needed,- newVersion: result.new_version,- targetBackend: result.target_backend,+ const value = persistedSetting?.controller_props?.value+ // Never re-copy the legacy default; that is what v1 did.+ if (sidebarKey === 'ngl' && Number(value) === LEGACY_NGL_DEFAULT) {+ continue+ }++ const next = mapping.coerce(value)+ if (next === null) continue++ ;(cfg as Record<string, unknown>)[mapping.yamlKey] = next+ touched = true}- } catch (e) {- logger.warn('Failed to check for updates via Rust command:', e)- return { updateNeeded: false, newVersion: '0' }- }- }- private async ensureFinalBackendInstallation(- backendString: string- ): Promise<void> {- if (!backendString) {- logger.warn('No backend specified for final installation check')- return+ if (touched) {+ await invoke<void>('write_yaml', { data: cfg, savePath: configPath })+ }}- const [selectedVersion, selectedBackend] = backendString- .split('/')- .map((part) => part?.trim())+ await setBackendSetting(LLAMACPP_MODEL_SETTINGS_BACKFILL_KEY, '1')+ }++ /**+ * Removes v1's `n_gpu_layers: 100` stamp from every model.yml.+ *+ * Separate from the settings backfill because the stamp is in the yaml even+ * for models that no longer appear in the persisted provider settings, so+ * iterating the persisted list would miss them.+ */+ private async stripLegacyNglFromModelYaml(providerPath: string): Promise<void> {+ const modelsDir = await joinPath([providerPath, 'models'])+ if (!(await fs.existsSync(modelsDir))) return- if (!selectedVersion || !selectedBackend) {- logger.warn(`Invalid backend format: ${backendString}`)+ let entries: string[] = []+ try {+ entries = await fs.readdirSync(modelsDir)+ } catch (e) {+ logger.warn('Could not list models while sweeping legacy ngl:', e)return}- try {- const isInstalled = await isBackendInstalled(- selectedBackend,- selectedVersion- )- if (!isInstalled) {- logger.info(`Final check: Installing backend ${backendString}`)- await this.ensureBackendReady(selectedBackend, selectedVersion)- logger.info(`Successfully installed backend: ${backendString}`)- } else {+ for (const entry of entries) {+ const configPath = await joinPath([entry, 'model.yml'])+ try {+ if (!(await fs.existsSync(configPath))) continue+ // Read as a bag rather than ModelConfig: that type covers the+ // plugin's own fields, not every per-model key the sidebar writes.+ const cfg = await fs.readYaml<Record<string, unknown>>(configPath)+ if (cfg?.n_gpu_layers !== LEGACY_NGL_DEFAULT) continue+ delete cfg.n_gpu_layers+ await fs.writeYaml(configPath, cfg)logger.info(- `Final check: Backend ${backendString} is already installed`+ `Removed legacy n_gpu_layers=${LEGACY_NGL_DEFAULT} from ${configPath}`)+ } catch (e) {+ // Per-model isolation: one unreadable yaml must not block the sweep.+ logger.warn(`Legacy ngl sweep skipped ${configPath}:`, e)}- } catch (error) {- logger.error(- `Failed to ensure backend ${backendString} installation:`,- error- )- throw error // Re-throw as this is critical}}@@ -2274,140 +1233,52 @@ export default class llamacpp_extension extends AIEngine {this.unlistenValidationStarted()}- // Deliberately does NOT stop the router. The router outlives any single+ // Deliberately does NOT stop the engine worker. It outlives any single// extension instance: the app owns its lifetime and stops it on- // ExitRequested/Exit, and adoption reuses a survivor. An extension teardown- // is not an app exit -- React StrictMode and HMR both unload and immediately- // reload us, and awaiting backgroundInit here (as this used to) meant- // blocking until startRouter had adopted the router, then killing exactly- // the process it had just adopted.- this.routerPort = undefined- this.routerApiKey = undefined+ // ExitRequested/Exit. An extension teardown is not an app exit -- React+ // StrictMode and HMR both unload and immediately reload us, and awaiting+ // backgroundInit here (as this used to) meant blocking until the worker was+ // up, then killing exactly the process it had just started.+ this.enginePort = undefined+ this.engineApiKey = undefined}onSettingUpdate<T>(key: string, value: T): void {- // configureBackends and updateBackend both persist settings themselves and- // own the router restart that follows, so every notification they trigger- // is an echo of their own write, and configureBackends writes the whole- // settings array rather than just the backend selection. This only- // suppresses echoes delivered while they are still running; a debounced- // restart outlives the flag. Reuse in startRouter, not this guard, is what- // keeps a late echo from respawning a healthy router.- const selfInflicted = this.isUpdatingBackend || this.isConfiguringBackends-- if (- selfInflicted &&- (key === 'llamacpp_version' || key === 'llamacpp_backend')- ) {- return- }-this.config[key] = value- if (key === 'llamacpp_version' || key === 'llamacpp_backend') {- ;(async () => {- try {- let v = this.config.llamacpp_version- let b = this.config.llamacpp_backend- if (!v || !b || v === 'none' || b === 'none') return-- // Validate (v, b) combination exists; if not, auto-resolve the- // backend to the best one available for the chosen version.- const supported = await listSupportedBackends(- this.config.check_for_updates !== false- )- const combos = new Set(- supported.map((e) => `${e.version}/${e.backend}`)- )- if (!combos.has(`${v}/${b}`)) {- const candidates = supported.filter((e) => e.version === v)- if (candidates.length === 0) {- logger.warn(- `No backends available for version '${v}'; ignoring update.`- )- return- }- const best = await this.determineBestBackend(candidates)- const [, bb] = best.split('/')- if (!bb) return- b = bb- this.config.llamacpp_backend = bb- const settings = await this.getSettings()- await this.updateSettings(- settings.map((item) => {- if (item.key === 'llamacpp_backend') {- item.controllerProps.value = bb- }- return item- })- )- if (events && typeof events.emit === 'function') {- events.emit('settingsChanged', {- key: 'llamacpp_backend',- value: bb,- })- }- }-- this.recomposeVersionBackend()- const composite = this.config.version_backend- const currentStored =- (await this.getStoredBackendType()) || undefined- const result = await handleSettingUpdate(- 'version_backend',- composite,- currentStored- )-- if (result.backend_type_updated && result.effective_backend_type) {- await this.setStoredBackendType(result.effective_backend_type)- logger.info(- `Updated backend type preference to: ${result.effective_backend_type}`- )- }-- if (result.version && result.backend) {- this.config.device = ''- await this.ensureBackendReady(result.backend, result.version)- try {- await this.startRouter()- } catch (e) {- logger.warn('Router restart after backend update failed:', e)- }- }- } catch (e) {- logger.error('Error in onSettingUpdate async block:', e)- }- })()- } else if (key === 'llamacpp_env') {+ if (key === 'llamacpp_env') {this.llamacpp_env = value as string} else if (key === 'timeout') {- this.timeout = value as number+ // Clamped through the plugin's own coercion: the field is a text input, so+ // clearing it yields '' and a bare cast produced NaN. 0 or negative would+ // make the request timeout fire immediately and abort every stream.+ this.timeout = asI32(value, DEFAULT_TIMEOUT) || DEFAULT_TIMEOUT+ } else if (key === 'models_max') {+ // Not a `[*]` preset key, so it is deliberately absent from+ // PRESET_AFFECTING_KEYS -- but the worker still has to be told, or+ // "Max Concurrently Loaded Models" only ever updated this.config.+ this.schedulePresetRefresh()} else if (PRESET_AFFECTING_KEYS.has(key)) {- // A live router was started with the previous preset; without a restart- // the new value is invisible to inference. Debounced so a flurry of- // slider/dropdown updates collapses into one bounce.- if (selfInflicted) return- this.scheduleRouterRestart()+ // The running worker was started with the previous preset; without a+ // reload the new value is invisible to inference. Debounced so a flurry+ // of slider/dropdown updates collapses into one bounce.+ this.schedulePresetRefresh()}}- private routerRestartTimer: ReturnType<typeof setTimeout> | null = null- private scheduleRouterRestart(): void {- if (this.routerRestartTimer) clearTimeout(this.routerRestartTimer)- this.routerRestartTimer = setTimeout(() => {- this.routerRestartTimer = null- this.startRouter().catch((e) =>- logger.warn('Router restart after settings update failed:', e)+ private presetRefreshTimer: ReturnType<typeof setTimeout> | null = null+ private schedulePresetRefresh(): void {+ if (this.presetRefreshTimer) clearTimeout(this.presetRefreshTimer)+ this.presetRefreshTimer = setTimeout(() => {+ this.presetRefreshTimer = null+ this.refreshEnginePreset().catch((e) =>+ logger.warn('Preset refresh after settings update failed:', e))}, 600)}private async generateApiKey(modelId: string, port: string): Promise<string> {- const hash = await invoke<string>('plugin:llamacpp|generate_api_key', {- modelId: modelId + port,- apiSecret: this.apiSecret,- })+ const hash = await pluginGenerateApiKey(modelId + port, this.apiSecret)return hash}@@ -2832,173 +1703,6 @@ export default class llamacpp_extension extends AIEngine {await setBackendSetting('cortex_models_migrated', 'true')}- /*- * Manually installs a supported backend archive- *- */- async installBackend(path: string): Promise<void> {- const platformName = IS_WINDOWS ? 'win' : 'linux'-- // Match prefix (optional), llama, main (optional), version (b####-hash),- // optional cudart-llama, bin, backend details- // Examples:- // - k_llama-main-b4314-09c61e1-bin-win-cuda-12.8-x64-avx2.zip- // - ik_llama-main-b4314-09c61e1-cudart-llama-bin-win-cuda-12.8-x64-avx512.zip- // - llama-b7037-bin-win-cuda-12.4-x64.zip (legacy format)- const re =- /^(.+?[-_])?llama(?:-main)?-(b\d+(?:-[a-f0-9]+)?)(?:-cudart-llama)?-bin-(.+?)\.(?:tar\.gz|zip)$/-- const archiveName = await basename(path)- logger.info(`Installing backend from path: ${path}`)-- if (- !(await fs.existsSync(path)) ||- (!path.endsWith('tar.gz') && !path.endsWith('zip'))- ) {- logger.error(`Invalid path or file ${path}`)- throw new Error(`Invalid path or file ${path}`)- }-- const match = re.exec(archiveName)-- if (!match) {- throw new Error(- `Failed to parse archive name: ${archiveName}. Expected format: [Optional prefix-]llama-<version>-bin-<backend>.(tar.gz|zip)`- )- }-- const [, prefix, version, backend] = match-- if (!version || !backend) {- throw new Error(`Invalid backend archive name: ${archiveName}`)- }-- // Include prefix in the backend identifier if present- const backendIdentifier = prefix ? `${prefix}${backend}` : backend-- logger.info(- `Detected prefix: ${prefix || 'none'}, version: ${version}, backend: ${backendIdentifier}`- )-- const backendDir = await getBackendDir(backendIdentifier, version)-- try {- await invoke('decompress', { path: path, outputDir: backendDir })- } catch (e) {- logger.error(`Failed to install: ${String(e)}`)- throw new Error(`Failed to decompress archive: ${String(e)}`)- }-- const serverName =- platformName === 'win' ? 'llama-server.exe' : 'llama-server'- const expectedBinDir = await joinPath([backendDir, 'build', 'bin'])- const expectedBinPath = await joinPath([expectedBinDir, serverName])-- // Normalize varying archive layouts to `build/bin/`: Jan tarballs already- // ship it; upstream Linux tarballs nest under `llama-bXXXX/`; upstream- // Windows zips are flat with the binary + DLLs at the root.- if (!(await fs.existsSync(expectedBinPath))) {- const foundDir = await findLlamaServerDir(backendDir, serverName)- if (!foundDir) {- await fs.rm(backendDir)- throw new Error(- 'Not a supported backend archive! Missing llama-server binary.'- )- }- if (foundDir !== expectedBinDir) {- const staging = `${backendDir}.staging`- try {- // Move the binary's dir into build/bin in one rename to keep relative- // symlinks intact (libggml.so → .so.0 → .so.0.10.0). A flat-root- // archive can't rename into its own subtree, so stage to a sibling.- if (foundDir === backendDir) {- await fs.mv(backendDir, staging)- await fs.mkdir(await joinPath([backendDir, 'build']))- await fs.mv(staging, expectedBinDir)- } else {- await fs.mkdir(await joinPath([backendDir, 'build']))- await fs.mv(foundDir, expectedBinDir)- }- } catch (e) {- if (await fs.existsSync(staging)) await fs.rm(staging)- if (await fs.existsSync(backendDir)) await fs.rm(backendDir)- throw new Error(`Failed to normalize backend layout: ${String(e)}`)- }- }- }-- if (!(await fs.existsSync(expectedBinPath))) {- await fs.rm(backendDir)- throw new Error(- 'Not a supported backend archive! Missing llama-server binary.'- )- }-- try {- await this.refreshBackendOptions()- logger.info(- `Backend ${backendIdentifier}/${version} installed and UI refreshed`- )- } catch (e) {- logger.error('Backend installed but failed to refresh UI', e)- throw new Error(- `Backend installed but failed to refresh UI: ${String(e)}`- )- }- }-- /**- * Install the supplementary CUDA runtime DLLs that upstream ships separately- * (`cudart-llama-bin-<backend>.zip`) into every installed backend of that- * type, so llama-server can resolve cublas/cudart at launch.- */- async installCudaRuntime(path: string): Promise<void> {- if (- !(await fs.existsSync(path)) ||- (!path.endsWith('tar.gz') && !path.endsWith('zip'))- ) {- throw new Error(`Invalid path or file ${path}`)- }-- const archiveName = await basename(path)- const match = /^cudart-llama-bin-(.+?)\.(?:tar\.gz|zip)$/.exec(archiveName)- if (!match || !match[1]) {- throw new Error(- `Not a CUDA runtime archive: ${archiveName}. Expected cudart-llama-bin-<backend>.(zip|tar.gz)`- )- }- const backendType = match[1]-- const targets = (await getLocalInstalledBackends()).filter(- (b) => b.backend === backendType- )- if (targets.length === 0) {- throw new Error(- `No installed "${backendType}" backend found. Install that backend first, then add the CUDA runtime.`- )- }-- let installed = 0- for (const t of targets) {- const binDir = await joinPath([- await getBackendDir(t.backend, t.version),- 'build',- 'bin',- ])- if (!(await fs.existsSync(binDir))) continue- await invoke('decompress', { path, outputDir: binDir })- installed++- }- if (installed === 0) {- throw new Error(- `Found ${backendType} backend(s) but none had a build/bin directory to install into.`- )- }- logger.info(- `CUDA runtime installed into ${installed} ${backendType} backend(s)`- )- }-/*** Update a model with new information.* @param modelId@@ -3044,7 +1748,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.refreshRouterPreset()+ await this.refreshEnginePreset()} catch (e) {logger.warn(`Router restart after model rename (${modelId} → ${model.id}) failed`, e)}@@ -3141,9 +1845,11 @@ export default class llamacpp_extension extends AIEngine {let mmprojPath = opts.mmprojPath? await maybeDownload(opts.mmprojPath, 'mmproj.gguf'): undefined- // MTP draft companion (speculative decoding); paired with the main model.- let mtpModelPath = opts.mtpPath- ? await maybeDownload(opts.mtpPath, 'mtp.gguf')+ // Speculative-decoding draft companion; paired with the main model. The+ // file name stays `mtp.gguf` for every flavour: it is the local name of+ // the paired draft, and changing it would orphan existing installs.+ let draftModelPath = opts.specDraftPath+ ? await maybeDownload(opts.specDraftPath, 'mtp.gguf'): undefinedif (downloadItems.length > 0) {@@ -3227,6 +1933,7 @@ export default class llamacpp_extension extends AIEngine {const fullModelPath = await joinPath([janDataFolderPath, modelPath])let isEmbedding = falselet mtpLayers = 0+ let specKind: SpecDraftKind = 'mtp'let templateKwargs: TemplateKwarg[] = []let resolvedName: string | undefined@@ -3260,12 +1967,26 @@ export default class llamacpp_extension extends AIEngine {)}- // Validate MTP draft and read its head count (the main gguf usually- // lacks nextn_predict_layers when MTP ships as a separate file).- if (mtpModelPath) {- const fullMtpPath = await joinPath([janDataFolderPath, mtpModelPath])- const mtpMetadata = await readGgufMetadata(fullMtpPath)- const draftLayers = detectMtpLayersFromGgufMeta(mtpMetadata.metadata)+ // Validate the draft, decide which spec type it implements, and read+ // its head count (the main gguf usually lacks nextn_predict_layers when+ // MTP ships as a separate file).+ if (draftModelPath) {+ const fullDraftPath = await joinPath([janDataFolderPath, draftModelPath])+ const draftMetadata = await readGgufMetadata(fullDraftPath)+ // Only asked for a DFlash-architecture draft, since that is the one+ // case a tensor decides (DSpark = DFlash + Markov head).+ const hasMarkovHead =+ draftMetadata.metadata?.['general.architecture'] === 'dflash'+ ? (await findGgufTensors(fullDraftPath, [MARKOV_HEAD_TENSOR]))+ .length > 0+ : undefined+ specKind = resolveSpecDraftKind(draftMetadata.metadata, {+ hasMarkovHead,+ hint: opts.specDraftKind,+ })+ const draftLayers = detectMtpLayersFromGgufMeta(draftMetadata.metadata)+ // Only an MTP head reports nextn layers; the other flavours have none,+ // and the count is what makes the settings panel offer the toggle.mtpLayers = draftLayers > 0 ? draftLayers : Math.max(mtpLayers, 1)}} catch (error) {@@ -3284,9 +2005,9 @@ export default class llamacpp_extension extends AIEngine {await fs.fileStat(await joinPath([janDataFolderPath, mmprojPath]))).size}- if (mtpModelPath) {+ if (draftModelPath) {size_bytes += (- await fs.fileStat(await joinPath([janDataFolderPath, mtpModelPath]))+ await fs.fileStat(await joinPath([janDataFolderPath, draftModelPath]))).size}@@ -3311,9 +2032,16 @@ export default class llamacpp_extension extends AIEngine {mtp_check_v: MTP_CHECK_VERSION,template_kwargs: templateKwargs,template_kwargs_check_v: TEMPLATE_KWARGS_CHECK_VERSION,- // A separate draft gguf is downloaded only to be used — enable MTP by- // default. Embedded-MTP models keep MTP opt-in (no flag written here).- ...(mtpModelPath ? { mtp_model_path: mtpModelPath, mtp: true } : {}),+ // A separate draft gguf is downloaded only to be used, so enable it by+ // default. Embedded-MTP models stay opt-in (no flag written here) and+ // need no spec_type: their flavour is always draft-mtp.+ ...(draftModelPath+ ? {+ mtp_model_path: draftModelPath,+ mtp: true,+ spec_type: `draft-${specKind}`,+ }+ : {}),...(isEmbedding? { pooling: 'mean', ubatch_size: 2048, batch_size: 2048 }: {}),@@ -3343,7 +2071,7 @@ export default class llamacpp_extension extends AIEngine {}try {- await this.refreshRouterPreset()+ await this.refreshEnginePreset()} catch (e) {logger.warn(`Router refresh after import(${modelId}) failed:`, e)}@@ -3446,15 +2174,13 @@ export default class llamacpp_extension extends AIEngine {}}- // Awaits the deferred startup, then makes one direct attempt if the router- // still isn't up. Safe to call redundantly: startRouter reuses a router that- // already matches this config rather than respawning it.- private async ensureRouterReady(): Promise<void> {- // Provisions if the setup screen never got the chance to ask, so skipping- // setup and later loading a local model still works.+ // Awaits the deferred startup, then makes one direct attempt if the worker+ // still isn't up. Safe to call redundantly: start_engine returns the running+ // worker rather than spawning a second one.+ private async ensureEngineReady(): Promise<void> {await this.ensureProvisioned().catch(() => undefined)- if (!(await this.getRouterInfo())) {- await this.startRouter()+ if (!(await this.getEngineInfo())) {+ await this.startEngine()}}@@ -3462,11 +2188,10 @@ export default class llamacpp_extension extends AIEngine {modelId: string,isEmbedding: boolean = false): Promise<SessionInfo> {- await this.ensureRouterReady()- const router = await this.getRouterInfo()- if (!router) {+ await this.ensureEngineReady()+ if (!(await this.getEngineInfo())) {throw new Error(- 'llama.cpp router is not running. Please restart the app.'+ 'The llama.cpp engine is not running. Please restart the app.')}@@ -3563,64 +2288,6 @@ export default class llamacpp_extension extends AIEngine {return `${this.provider}/${modelId.replace(/\./g, '-')}`}- private async verifyBackendDeps(backend: string, version: string): Promise<void> {- const backendKey = `${version}/${backend}`- try {- const verification = await verifyBackendInstallation(backend, version)- if (verification.verified) {- logger.info(- `Backend ${backendKey} dependency verification passed (${verification.resolved_libraries.length} libraries resolved)`- )- } else {- logger.warn(- `Backend ${backendKey} is missing libraries: ${verification.missing_libraries.join(', ')}`- )- events.emit(AppEvent.onBackendVerificationFailed, {- backend,- version,- missingLibraries: verification.missing_libraries,- })- }- } catch (verifyErr) {- // Intentionally non-fatal: verification is advisory only. A BinaryNotFound- // error here means the exe disappeared between install and startup — the- // backend will fail naturally when first used, which is surfaced elsewhere.- logger.warn(`Backend ${backendKey} dependency verification failed: ${verifyErr}`)- }- }-- private async ensureBackendReady(- backend: string,- version: string- ): Promise<void> {- const backendKey = `${version}/${backend}`-- // Check if backend is already installed- const isInstalled = await isBackendInstalled(backend, version)- if (isInstalled) {- return- }-- // Check if download is already in progress- if (this.pendingDownloads.has(backendKey)) {- logger.info(- `Backend ${backendKey} download already in progress, waiting...`- )- await this.pendingDownloads.get(backendKey)- return- }-- // Start new download- logger.info(`Backend ${backendKey} not installed, downloading...`)- const downloadPromise = downloadBackend(backend, version).finally(() => {- this.pendingDownloads.delete(backendKey)- })-- this.pendingDownloads.set(backendKey, downloadPromise)- await downloadPromise- logger.info(`Backend ${backendKey} download completed`)- }-private async *handleStreamingResponse(url: string,headers: HeadersInit,@@ -3720,10 +2387,7 @@ export default class llamacpp_extension extends AIEngine {modelId: string): Promise<SessionInfo | null> {try {- return await invoke<SessionInfo | null>(- 'plugin:llamacpp|find_session_by_model',- { modelId }- )+ return await pluginFindSessionByModel(modelId)} catch (e) {logger.error(e)throw new Error(String(e))@@ -3731,10 +2395,7 @@ export default class llamacpp_extension extends AIEngine {}private async ensureHealthySession(modelId: string): Promise<SessionInfo> {- return invoke<SessionInfo>('plugin:llamacpp|ensure_session_ready', {- modelId,- isEmbedding: false,- })+ return pluginEnsureSessionReady(modelId, false)}override async chat(@@ -3799,7 +2460,7 @@ export default class llamacpp_extension extends AIEngine {await fs.rm(modelDir)try {- await this.refreshRouterPreset()+ await this.refreshEnginePreset()} catch (e) {logger.warn(`Router refresh after delete(${modelId}) failed:`, e)}@@ -3807,9 +2468,7 @@ export default class llamacpp_extension extends AIEngine {override async getLoadedModels(): Promise<string[]> {try {- let models: string[] = await invoke<string[]>(- 'plugin:llamacpp|get_loaded_models'- )+ let models: string[] = await pluginGetLoadedModels()return models} catch (e) {logger.error(e)@@ -3928,7 +2587,7 @@ export default class llamacpp_extension extends AIEngine {await invoke<void>('write_yaml', { data: cfg, savePath: configPath })try {- await this.refreshRouterPreset()+ await this.refreshEnginePreset()} catch (e) {logger.warn(`Failed to restart router after MTP update for ${modelId}`, e)}@@ -3983,7 +2642,7 @@ export default class llamacpp_extension extends AIEngine {await invoke<void>('write_yaml', { data: cfg, savePath: configPath })try {- await this.refreshRouterPreset()+ await this.refreshEnginePreset()} catch (e) {logger.warn(`Failed to restart router after model settings update for ${modelId}`,@@ -3993,27 +2652,12 @@ export default class llamacpp_extension extends AIEngine {}async getDevices(): Promise<DeviceList[]> {- const cfg = this.config- const [version, backend] = cfg.version_backend.split('/')- if (!version || !backend) {- throw new Error(- 'Backend setup was not successful. Please restart the app in a stable internet connection.'- )- }// set envsconst envs: Record<string, string> = {}if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env)- // Ensure backend is downloaded and ready before proceeding- await this.ensureBackendReady(backend, version)- logger.info('Calling Tauri command getDevices with arg --list-devices')- const backendPath = await getBackendExePath(backend, version)-try {- const dList = await invoke<DeviceList[]>('plugin:llamacpp|get_devices', {- backendPath,- envs,- })+ const dList = await engineDevices(envs)// On Linux with AMD GPUs, llama.cpp via Vulkan may report UMA (shared) memory as device-local.// For clearer UX, override with dedicated VRAM from the hardware plugin when available.try {@@ -4179,14 +2823,33 @@ export default class llamacpp_extension extends AIEngine {return counts}+ /**+ * Token budget for one embedding request.+ *+ * Deliberately not the engine-wide `ubatch_size`: preset.ts pins every+ * embedding model's section to its own ubatch (DEFAULT_EMBEDDING_UBATCH) and+ * to `ctx-size = 0`, so the real ceiling is the embedder's own trained+ * context -- 512 on MiniLM. llama.cpp rejects a batch wider than either with+ * no retry path, so the budget is the smaller of the two.+ */+ private async embedBatchBudget(sInfo: SessionInfo): Promise<number> {+ let budget = DEFAULT_EMBEDDING_UBATCH+ try {+ const props = await this.getModelProps(sInfo.model_id)+ const nCtx = props?.nCtx+ if (typeof nCtx === 'number' && nCtx > 0) {+ budget = Math.min(budget, nCtx)+ }+ } catch (e) {+ // Without /props the pinned ubatch is still a valid ceiling.+ logger.warn('Could not read embedder context size; using the pinned ubatch:', e)+ }+ return budget+ }+async embed(text: string[]): Promise<EmbeddingResponse> {const sInfo = await this.ensureEmbeddingModelLoaded()-- const ubatchSize =- (this.config?.ubatch_size && this.config.ubatch_size > 0- ? this.config.ubatch_size- : 512) || 512- const batches = buildEmbedBatches(text, ubatchSize)+ const batches = buildEmbedBatches(text, await this.embedBatchBudget(sInfo))const attemptRequest = async (session: SessionInfo,diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex 28790ee37..e05ad1e1a 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -43,7 +43,7 @@ vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn(async (_cmd: string, args: { path: string }) => modelYamls[args.path]),}))-import { generatePreset } from './preset'+import { generatePreset, threadCacheDir } from './preset'const CONFIG = {} as any@@ -68,7 +68,7 @@ describe('generatePreset MTP emission', () => {spec_draft_n_min: 0,spec_draft_p_min: 0.8,})- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('spec-type = draft-mtp')expect(ini).toContain('spec-draft-n-max = 8')@@ -76,24 +76,16 @@ describe('generatePreset MTP emission', () => {expect(ini).toContain('spec-draft-p-min = 0.8')})- it('omits MTP lines when backend does not support MTP', async () => {- setupModel('glm', { mtp: true, mtp_layers: 1, spec_draft_n_max: 8 })- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: false })- const ini = writtenFiles['/p/router.preset.ini']- expect(ini).not.toContain('spec-type')- expect(ini).not.toContain('spec-draft')- })-it('omits MTP lines when model has no MTP heads (mtp_layers = 0)', async () => {setupModel('llama', { mtp: true, mtp_layers: 0 })- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('spec-type')})it('omits MTP lines when mtp flag is off even if heads exist', async () => {setupModel('glm', { mtp: false, mtp_layers: 1 })- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('spec-type')})@@ -104,7 +96,7 @@ describe('generatePreset MTP emission', () => {mtp_layers: 0,mtp_model_path: 'models/gemma/mtp.gguf',})- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('spec-type = draft-mtp')expect(ini).toContain('spec-draft-model = /jan/models/gemma/mtp.gguf')@@ -112,30 +104,34 @@ describe('generatePreset MTP emission', () => {it('does not emit spec-draft-model for embedded MTP (no draft path)', async () => {setupModel('glm', { mtp: true, mtp_layers: 1 })- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('spec-type = draft-mtp')expect(ini).not.toContain('spec-draft-model')})- it('emits per-model sampling defaults with CLI-style INI keys', async () => {+ // Values are chosen to differ from llama.cpp's defaults: an equal value is+ // deliberately skipped now, since emitting one suppresses the GGUF's own+ // sampling recommendations. The two penalties set no such bit and are always+ // emitted, so their defaults are fine here.+ it('emits per-model sampling values with CLI-style INI keys', async () => {setupModel('s', {temperature: 0,- top_k: 40,+ top_k: 20,top_p: 0.9,- min_p: 0.05,- repeat_last_n: 64,+ min_p: 0.1,+ repeat_last_n: 128,repeat_penalty: 1.1,presence_penalty: 0.5,frequency_penalty: 0.25,})- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: false })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('temperature = 0')- expect(ini).toContain('top-k = 40')+ expect(ini).toContain('top-k = 20')expect(ini).toContain('top-p = 0.9')- expect(ini).toContain('min-p = 0.05')- expect(ini).toContain('repeat-last-n = 64')+ expect(ini).toContain('min-p = 0.1')+ expect(ini).toContain('repeat-last-n = 128')expect(ini).toContain('repeat-penalty = 1.1')expect(ini).toContain('presence-penalty = 0.5')expect(ini).toContain('frequency-penalty = 0.25')@@ -143,7 +139,7 @@ describe('generatePreset MTP emission', () => {it('omits sampling keys that are absent or non-numeric', async () => {setupModel('s', { temperature: 0.7 })- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: false })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('temperature = 0.7')expect(ini).not.toContain('top-p')@@ -157,7 +153,7 @@ describe('generatePreset MTP emission', () => {spec_draft_n_max: -5,spec_draft_p_min: 1.5,})- await generatePreset('/p', '/jan', CONFIG, { supportsMtp: true })+ await generatePreset('/p', '/jan', CONFIG)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('spec-type = draft-mtp')expect(ini).not.toContain('spec-draft-n-max')@@ -169,7 +165,6 @@ describe('generatePreset parallel reservation', () => {it('adds one reserved background slot on top of the global parallel value', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1 } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('parallel = 2')@@ -177,22 +172,32 @@ describe('generatePreset parallel reservation', () => {it('adds one reserved background slot on top of a per-model parallel override', async () => {setupModel('llama', { parallel: 3 })- await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })+ await generatePreset('/p', '/jan', {} as any)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('parallel = 4')})it('omits parallel when unset, leaving llama.cpp auto-default untouched', async () => {setupModel('llama', {})- await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })+ await generatePreset('/p', '/jan', {} as any)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).not.toContain('parallel =')+ })++ // 0 is the setting's "let llama.cpp decide": omitting the key is what the+ // engine resolves to its own auto default (4 slots, unified KV), so a+ // reserved background slot must not be added on top of nothing.+ it('omits parallel when the setting is an explicit 0', async () => {+ setupModel('llama', {})+ await generatePreset('/p', '/jan', { parallel: 0 } as any)const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('parallel =')+ expect(ini).not.toContain('kv-unified')})it('reserves no extra slot when reservedBackgroundSlots is 0 (global)', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1 } as any, {- supportsMtp: false,reservedBackgroundSlots: 0,})const ini = writtenFiles['/p/router.preset.ini']@@ -202,19 +207,38 @@ describe('generatePreset parallel reservation', () => {it('reserves no extra slot when reservedBackgroundSlots is 0 (per-model)', async () => {setupModel('llama', { parallel: 3 })await generatePreset('/p', '/jan', {} as any, {- supportsMtp: false,reservedBackgroundSlots: 0,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('parallel = 3')})++ // The frontend pins background work to a fixed slot index 1+ // (BACKGROUND_SLOT_ID), and upstream wraps an out-of-range id_slot modulo the+ // slot count rather than rejecting it. So the reservation has to be+ // unconditional: every emitted `parallel` must be at least 2, or the pin+ // silently lands back on the chat slot 0.+ it('reserves the background slot by default, so slot 1 always exists', async () => {+ setupModel('llama', {})+ await generatePreset('/p', '/jan', { parallel: 1 } as any)+ expect(writtenFiles['/p/router.preset.ini']).toContain('parallel = 2')+ })++ it('reserves it in the per-model section too, which overrides [*]', async () => {+ setupModel('llama', { parallel: 1 })+ await generatePreset('/p', '/jan', { parallel: 4 } as any)+ const ini = writtenFiles['/p/router.preset.ini']+ // The provider-level value is what the old pin was computed from; the+ // section's own value is what llama.cpp actually applies.+ expect(ini).toContain('parallel = 5')+ expect(ini).toContain('parallel = 2')+ })})describe('generatePreset kv-unified', () => {it('enables unified KV on auto when an explicit parallel is emitted', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1 } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('parallel = 2')@@ -223,14 +247,14 @@ describe('generatePreset kv-unified', () => {it('enables unified KV on auto when only a per-model parallel is emitted', async () => {setupModel('llama', { parallel: 3 })- await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })+ await generatePreset('/p', '/jan', {} as any)const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('kv-unified = true')})it('omits kv-unified on auto when no explicit parallel is emitted', async () => {setupModel('llama', {})- await generatePreset('/p', '/jan', {} as any, { supportsMtp: false })+ await generatePreset('/p', '/jan', {} as any)const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('kv-unified')})@@ -238,7 +262,6 @@ describe('generatePreset kv-unified', () => {it('respects an explicit off even when parallel is emitted', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { parallel: 1, kv_unified: 'off' } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('kv-unified = false')@@ -247,7 +270,6 @@ describe('generatePreset kv-unified', () => {it('respects an explicit on when no parallel is emitted', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { kv_unified: 'on' } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('kv-unified = true')@@ -258,76 +280,52 @@ describe('generatePreset ctx-size default', () => {it('emits ctx-size = 8192 in [*] when fit is off and no ctx_size is set', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { fit: false } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('ctx-size = 8192')})- it('uses the user ctx_size over the default', async () => {- setupModel('llama', {})- await generatePreset('/p', '/jan', { fit: false, ctx_size: 16384 } as any, {- supportsMtp: false,+ // There is no engine-level ctx_size setting: the [*] value is purely an OOM+ // guard, and a user's choice belongs to the per-model ctx_len.+ it('uses the per-model ctx_size over the [*] guard', async () => {+ setupModel('llama', { ctx_size: 16384 })+ await generatePreset('/p', '/jan', { fit: false } as any, {})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('ctx-size = 16384')- expect(ini).not.toContain('ctx-size = 8192')})it('omits ctx-size when auto-fit is enabled', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { fit: true } as any, {- supportsMtp: false,- })- 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,+ await generatePreset('/p', '/jan', { fit: false } as any, {})const ini = writtenFiles['/p/router.preset.ini']- // [*] keeps the global, but the per-model section overrides to native.- expect(ini).toContain('ctx-size = 16384')+ // [*] keeps the guard, but the per-model section overrides it to native.+ expect(ini).toContain('ctx-size = 8192')expect(ini).toContain('ctx-size = 0')})})describe('generatePreset n-gpu-layers under fit', () => {- it('emits global n-gpu-layers when fit is off', async () => {- setupModel('llama', {})- await generatePreset('/p', '/jan', { fit: false, n_gpu_layers: 20 } as any, {- supportsMtp: false,- })- const ini = writtenFiles['/p/router.preset.ini']- expect(ini).toContain('n-gpu-layers = 20')- })-- it('omits global n-gpu-layers when auto-fit is enabled so fit owns offload', async () => {+ // There is no engine-level n_gpu_layers setting either; offload is per-model.+ it('never emits an engine-level n-gpu-layers', async () => {setupModel('llama', {})- await generatePreset('/p', '/jan', { fit: true, n_gpu_layers: 20 } as any, {- supportsMtp: false,+ await generatePreset('/p', '/jan', { fit: false } as any, {})- const ini = writtenFiles['/p/router.preset.ini']- expect(ini).not.toContain('n-gpu-layers')+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('n-gpu-layers')})it('emits per-model n-gpu-layers when fit is off', async () => {setupModel('llama', { n_gpu_layers: 33 })await generatePreset('/p', '/jan', { fit: false } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('n-gpu-layers = 33')@@ -336,7 +334,6 @@ describe('generatePreset n-gpu-layers under fit', () => {it('omits per-model n-gpu-layers when auto-fit is enabled', async () => {setupModel('llama', { n_gpu_layers: 33 })await generatePreset('/p', '/jan', { fit: true } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('n-gpu-layers')@@ -347,7 +344,6 @@ describe('generatePreset context-shift', () => {it('emits context-shift = true when ctx_shift is enabled', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { ctx_shift: true } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).toContain('context-shift = true')@@ -356,7 +352,6 @@ describe('generatePreset context-shift', () => {it('omits context-shift when disabled, matching llama.cpp own default', async () => {setupModel('llama', {})await generatePreset('/p', '/jan', { ctx_shift: false } as any, {- supportsMtp: false,})const ini = writtenFiles['/p/router.preset.ini']expect(ini).not.toContain('context-shift')@@ -367,7 +362,6 @@ 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')@@ -379,7 +373,6 @@ describe('generatePreset embedding ctx-size', () => {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')@@ -389,3 +382,376 @@ describe('generatePreset embedding ctx-size', () => {expect(embedderSection).not.toContain('ctx-size = 0')})})++describe('generatePreset global engine options', () => {+ const globalSection = () => {+ const ini = writtenFiles['/p/router.preset.ini']+ const end = ini.indexOf('\n[', ini.indexOf('[*]') + 1)+ return end === -1 ? ini : ini.slice(0, end)+ }++ // Only non-defaults are emitted, so the preset stays intent-revealing.+ it('omits every option left at its llama.cpp default', async () => {+ await generatePreset('/p', '/jan', {+ batch_size: 2048,+ ubatch_size: 512,+ n_cpu_moe: 0,+ no_kv_offload: false,+ } as any)+ const g = globalSection()+ expect(g).not.toContain('batch-size')+ expect(g).not.toContain('n-cpu-moe')+ expect(g).not.toContain('kv-offload')+ })++ it('emits batch-size when it differs from the 2048 default', async () => {+ await generatePreset('/p', '/jan', { batch_size: 4096 } as any, {+ })+ expect(globalSection()).toContain('batch-size = 4096')+ })++ // ubatch-size was exposed without its logical counterpart, so a user could+ // set the physical batch but not the logical one it must not exceed.+ it('emits batch-size and ubatch-size independently', async () => {+ await generatePreset('/p', '/jan', {+ batch_size: 1024,+ ubatch_size: 256,+ } as any)+ const g = globalSection()+ expect(g).toContain('batch-size = 1024')+ expect(g).toContain('ubatch-size = 256')+ })++ it('emits n-cpu-moe only when at least one layer is pinned to the host', async () => {+ await generatePreset('/p', '/jan', { n_cpu_moe: 12 } as any, {+ })+ expect(globalSection()).toContain('n-cpu-moe = 12')+ })++ it('floors a fractional n-cpu-moe rather than emitting a non-integer', async () => {+ await generatePreset('/p', '/jan', { n_cpu_moe: 3.7 } as any, {+ })+ expect(globalSection()).toContain('n-cpu-moe = 3')+ })++ // Spelled as the negated half of llama.cpp's kv-offload pair; common_preset+ // inverts it, so `true` here really does disable offloading.+ it('emits no-kv-offload only when offloading is disabled', async () => {+ await generatePreset('/p', '/jan', { no_kv_offload: true } as any, {+ })+ expect(globalSection()).toContain('no-kv-offload = true')+ })+})++describe('generatePreset upstream-default skipping', () => {+ const globalSection = () => {+ const ini = writtenFiles['/p/router.preset.ini']+ const end = ini.indexOf('\n[', ini.indexOf('[*]') + 1)+ return end === -1 ? ini : ini.slice(0, end)+ }+ const modelSection = (id: string) => {+ const ini = writtenFiles['/p/router.preset.ini']+ const start = ini.indexOf(`[${id}]`)+ const end = ini.indexOf('\n[', start + 1)+ return end === -1 ? ini.slice(start) : ini.slice(start, end)+ }++ // Passing any of these sets a bit that suppresses the GGUF's own+ // general.sampling.* recommendations, so an identical-looking default+ // silently overrode what the model asked for.+ it('omits sampling values equal to llama.cpp defaults', async () => {+ setupModel('m', {+ temperature: 0.8,+ top_k: 40,+ top_p: 0.95,+ min_p: 0.05,+ repeat_last_n: 64,+ repeat_penalty: 1.0,+ })+ await generatePreset('/p', '/jan', {} as any)+ const sec = modelSection('m')+ for (const k of ['temperature', 'top-k', 'top-p', 'min-p', 'repeat-last-n', 'repeat-penalty']) {+ expect(sec, k).not.toContain(`${k} = `)+ }+ })++ it('still emits a sampling value that differs from the default', async () => {+ setupModel('m', { temperature: 0.6, top_k: 20 })+ await generatePreset('/p', '/jan', {} as any)+ const sec = modelSection('m')+ expect(sec).toContain('temperature = 0.6')+ expect(sec).toContain('top-k = 20')+ })++ // temperature 0 is greedy decoding, an explicit choice, not a default.+ it('emits temperature = 0', async () => {+ setupModel('m', { temperature: 0 })+ await generatePreset('/p', '/jan', {} as any)+ expect(modelSection('m')).toContain('temperature = 0')+ })++ // Upstream throws on a negative window rather than clamping, which aborts+ // the load; the old UI documented -1 as "full context".+ it('omits a negative repeat-last-n', async () => {+ setupModel('m', { repeat_last_n: -1 })+ await generatePreset('/p', '/jan', {} as any)+ expect(modelSection('m')).not.toContain('repeat-last-n')+ })++ // Upstream's fit leaves a user-set context alone, so gating this on fit was+ // why "Increase Context Size" did nothing while Fit was on.+ it('emits per-model ctx-size even when fit is enabled', async () => {+ setupModel('m', { ctx_size: 16384 })+ await generatePreset('/p', '/jan', { fit: true } as any)+ expect(modelSection('m')).toContain('ctx-size = 16384')+ })++ it('emits n-gpu-layers for auto (-1) and all (-2) but not below', async () => {+ setupModel('a', { n_gpu_layers: -1 })+ await generatePreset('/p', '/jan', { fit: false } as any)+ expect(modelSection('a')).toContain('n-gpu-layers = -1')++ setupModel('b', { n_gpu_layers: -2 })+ await generatePreset('/p', '/jan', { fit: false } as any)+ expect(modelSection('b')).toContain('n-gpu-layers = -2')++ setupModel('c', { n_gpu_layers: -3 })+ await generatePreset('/p', '/jan', { fit: false } as any)+ expect(modelSection('c')).not.toContain('n-gpu-layers')+ })++ // mlock and no_mmap are two deprecated aliases for one upstream field, so+ // emitting both left load_mode at NONE and silently dropped mlock.+ it('derives a single load-mode and never emits mlock or no-mmap', async () => {+ const cases: Array<[boolean, boolean, string | null]> = [+ [false, false, null],+ [false, true, 'load-mode = none'],+ [true, false, 'load-mode = mmap+mlock'],+ [true, true, 'load-mode = mlock'],+ ]+ for (const [mlock, no_mmap, expected] of cases) {+ await generatePreset('/p', '/jan', { mlock, no_mmap } as any, {+ })+ const g = globalSection()+ expect(g, `mlock=${mlock} no_mmap=${no_mmap}`).not.toMatch(/^mlock = /m)+ expect(g).not.toMatch(/^no-mmap = /m)+ if (expected) expect(g).toContain(expected)+ else expect(g).not.toContain('load-mode')+ }+ })++ // Upstream's default is UNSPECIFIED, so treating 'none' as the default made+ // an explicit "disable scaling" impossible to express.+ it('emits rope-scaling for none but not for auto', async () => {+ await generatePreset('/p', '/jan', { rope_scaling: 'none' } as any, {+ })+ expect(globalSection()).toContain('rope-scaling = none')++ await generatePreset('/p', '/jan', { rope_scaling: 'auto' } as any, {+ })+ expect(globalSection()).not.toContain('rope-scaling')+ })++ // 1.0 is an explicit "force no scaling", not the default (which is 0).+ it('emits rope-freq-scale = 1 and omits it at 0', async () => {+ await generatePreset('/p', '/jan', { rope_freq_scale: 1 } as any, {+ })+ expect(globalSection()).toContain('rope-freq-scale = 1')++ await generatePreset('/p', '/jan', { rope_freq_scale: 0 } as any, {+ })+ expect(globalSection()).not.toContain('rope-freq-scale')+ })++ it('omits cache-ram at the upstream default and emits an explicit -1', async () => {+ await generatePreset('/p', '/jan', { cache_ram: 8192 } as any, {+ })+ expect(globalSection()).not.toContain('cache-ram')++ await generatePreset('/p', '/jan', { cache_ram: -1 } as any, {+ })+ expect(globalSection()).toContain('cache-ram = -1')+ })++ it('names a slot-save-path even when conversation persistence is off', async () => {+ // Absent by default in llama.cpp, and naming it is what enables the slot+ // save/restore routes at all -- so the default (unset) must still emit it.+ await generatePreset('/p', '/jan', {} as any)+ expect(globalSection()).toContain(+ `slot-save-path = ${threadCacheDir('/p')}`+ )++ // Off, the worker still needs the directory: it prunes what an earlier+ // session left there and erases a deleted thread's state out of it. The+ // zero budget is what stops it writing.+ await generatePreset('/p', '/jan', { persist_thread_cache: false } as any, {+ })+ expect(globalSection()).toContain(+ `slot-save-path = ${threadCacheDir('/p')}`+ )+ })++ it('puts the thread cache under the provider directory, not a temp dir', async () => {+ // A cache the user paid prefill time for has to survive a reboot, which is+ // the entire point of persisting it.+ expect(threadCacheDir('/p')).toBe('/p/thread-cache')+ })++ it('omits cont-batching when enabled and emits it only when turned off', async () => {+ await generatePreset('/p', '/jan', { cont_batching: true } as any, {+ })+ expect(globalSection()).not.toContain('cont-batching')++ await generatePreset('/p', '/jan', { cont_batching: false } as any, {+ })+ expect(globalSection()).toContain('cont-batching = false')+ })++ it('emits the newly exposed offload and checkpoint options only when set', async () => {+ await generatePreset('/p', '/jan', {} as any)+ let g = globalSection()+ expect(g).not.toContain('tensor-split')+ expect(g).not.toContain('no-op-offload')+ expect(g).not.toContain('ctx-checkpoints')+ expect(g).not.toContain('checkpoint-min-step')++ await generatePreset(+ '/p',+ '/jan',+ {+ tensor_split: ' 3,1 ',+ no_op_offload: true,+ ctx_checkpoints: 8,+ checkpoint_min_step: 4096,+ } as any,+ )+ g = globalSection()+ expect(g).toContain('tensor-split = 3,1')+ expect(g).toContain('no-op-offload = true')+ expect(g).toContain('ctx-checkpoints = 8')+ expect(g).toContain('checkpoint-min-step = 4096')+ })++ it('omits the checkpoint options at their upstream defaults', async () => {+ await generatePreset(+ '/p',+ '/jan',+ { ctx_checkpoints: 32, checkpoint_min_step: 8192 } as any,+ )+ const g = globalSection()+ expect(g).not.toContain('ctx-checkpoints')+ expect(g).not.toContain('checkpoint-min-step')+ })++ // Upstream documents 0 as "no minimum" and only rejects negatives+ // (common/arg.cpp), and settings.json puts no `min` on the field, so 0 is+ // reachable from the UI and has to reach the preset.+ it('emits an explicit checkpoint-min-step of 0, which means no minimum', async () => {+ await generatePreset(+ '/p',+ '/jan',+ { ctx_checkpoints: 0, checkpoint_min_step: 0 } as any,+ )+ const g = globalSection()+ expect(g).toContain('checkpoint-min-step = 0')+ expect(g).toContain('ctx-checkpoints = 0')+ })+})++// The ini value grammar ends a value at `#` or `;` and has no line+// continuation, so an inline template is truncated or flattened. Anything that+// is not a plain built-in name goes to a file instead.+describe('generatePreset chat template', () => {+ it('writes a multi-line template to a file and points the preset at it', async () => {+ const template = "{%- if x %}\n<|im_start|>\n{%- endif %}"+ setupModel('glm', { chat_template: template })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain(+ 'chat-template-file = /p/models/glm/chat_template.jinja'+ )+ expect(ini).not.toContain('chat-template =')+ expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(template)+ })++ it('preserves a template containing a comment marker verbatim', async () => {+ const template = "{# a comment #}{{ '#1' }}; done"+ setupModel('glm', { chat_template: template })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBe(template)+ expect(writtenFiles['/p/router.preset.ini']).toContain(+ 'chat-template-file = /p/models/glm/chat_template.jinja'+ )+ })++ // A built-in name is not a template body, and --chat-template-file would+ // try to read it as a path.+ it('keeps a built-in template name inline', async () => {+ setupModel('glm', { chat_template: 'chatml' })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('chat-template = chatml')+ expect(ini).not.toContain('chat-template-file')+ expect(writtenFiles['/p/models/glm/chat_template.jinja']).toBeUndefined()+ })++ it('emits nothing for a blank template', async () => {+ setupModel('glm', { chat_template: ' ' })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('chat-template')+ })+})++// The four draft flavours differ only in the `spec-type` value; a draft that+// cannot implement the type it is given fails the load with an unrelated+// message, so the type recorded at import is what must be emitted.+describe('generatePreset spec type', () => {+ it('emits the recorded spec type for a dflash draft', async () => {+ setupModel('dsv4', {+ mtp: true,+ mtp_layers: 1,+ mtp_model_path: 'models/dsv4/mtp.gguf',+ spec_type: 'draft-dflash',+ })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('spec-type = draft-dflash')+ expect(ini).toContain('spec-draft-model = /jan/models/dsv4/mtp.gguf')+ expect(ini).not.toContain('draft-mtp')+ })++ it('emits draft-dspark when that is what was detected', async () => {+ setupModel('dsv4', {+ mtp: true,+ mtp_layers: 1,+ mtp_model_path: 'models/dsv4/mtp.gguf',+ spec_type: 'draft-dspark',+ })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).toContain(+ 'spec-type = draft-dspark'+ )+ })++ // Models imported before the type was recorded, and every embedded-MTP+ // model, carry no spec_type.+ it('falls back to draft-mtp when no type was recorded', async () => {+ setupModel('glm', { mtp: true, mtp_layers: 1 })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).toContain(+ 'spec-type = draft-mtp'+ )+ })++ it('ignores a spec type that is not one llama.cpp accepts', async () => {+ setupModel('glm', {+ mtp: true,+ mtp_layers: 1,+ spec_type: 'draft-nonsense',+ })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).toContain(+ 'spec-type = draft-mtp'+ )+ })+})diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex 7fa0bf8ae..673cf1ed1 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -1,11 +1,16 @@/**- * @file Generates the llama-server router preset INI from per-model `model.yml`- * files under `<providerPath>/models/<modelId>/model.yml`.+ * @file Generates `router.preset.ini` from the per-model `model.yml` files under+ * `<providerPath>/models/<modelId>/model.yml`.*- * Phase 2 keeps the preset minimal — model path, mmproj, chat-template,- * load-on-startup=false. A small `[*]` global section pulls a couple of- * conservative defaults from `LlamacppConfig`. Per-model setting fidelity- * is deferred to Phase 3.+ * The file has a `[*]` section of engine-wide defaults, then one `[<modelId>]`+ * section per model. Only values that differ from llama.cpp's own defaults are+ * written, so the preset stays intent-revealing and a setting left alone keeps+ * whatever upstream (or the GGUF) decided. `load-on-startup = false` is the one+ * unconditional line.+ *+ * An ini key is the CLI flag with its leading dashes removed, resolved by+ * `common/preset.cpp` `get_map_key_opt`. Defaults quoted below are from+ * `common/common.h` at the pinned build.*/import { fs, joinPath } from '@janhq/core'@@ -29,6 +34,7 @@ type ModelYaml = ModelConfig & {mtp_layers?: numbermtp?: booleanmtp_model_path?: string+ spec_type?: stringtemperature?: numbertop_k?: numbertop_p?: number@@ -50,17 +56,65 @@ type ModelYaml = ModelConfig & {// One extra llama-server slot beyond the user-visible "Parallel Sequences"// count, reserved for background requests (e.g. thread auto-titling) that// must never be able to evict the user's own chat KV cache from its slot.-// Hidden from the setting's UI value; see reservedSlotId in thread-title-summarizer.ts.+// Hidden from the setting's UI value.+//+// Added unconditionally, and that is load-bearing. The emitted `parallel` is+// therefore always 2 or more, which is what lets the frontend pin background+// work to a fixed BACKGROUND_SLOT_ID (web-app/src/constants/models.ts) instead+// of computing an index here that the two sides then have to keep in sync.+// Upstream wraps an out-of-range id_slot modulo the slot count rather than+// rejecting it, so any such desync is silent: the background request lands back+// on the chat slot and overwrites the cache it was meant to protect.export const RESERVED_BACKGROUND_SLOTS = 1-export const MTP_MIN_BUILD = 9193+/**+ * The ubatch every embedding model's preset section is pinned to.+ *+ * Exported because `embed()` has to budget its batches against the *embedder's*+ * ubatch, not the engine-wide setting: llama.cpp rejects a batch wider than+ * n_ubatch outright, with no retry path.+ */+export const DEFAULT_EMBEDDING_UBATCH = 2048-const DEFAULT_EMBEDDING_UBATCH = 2048+/**+ * Where each thread's saved KV cache lives.+ *+ * Under the provider directory rather than a temp dir: it is a cache the user+ * paid prefill time for and expects to survive a reboot, which is the whole+ * point. Shared verbatim with the Rust side, which llama.cpp joins file names+ * onto, so the two must not compute it differently -- this function is the one+ * definition.+ */+export function threadCacheDir(providerPath: string): string {+ return `${providerPath}/thread-cache`+}// Fallback context size when the user hasn't set one, to avoid loading a// model's full trained context (which can OOM on large-context models).const DEFAULT_CTX_SIZE = 8192+/**+ * The `--spec-type` values llama.cpp accepts for a draft model+ * (common/speculative.cpp). A model.yml records one at import; anything else+ * -- an older install with no record, or a value we do not recognise -- falls+ * back to MTP, which is what every embedded-head model is.+ */+const SPEC_TYPES = new Set([+ 'draft-mtp',+ 'draft-eagle3',+ 'draft-dflash',+ 'draft-dspark',+])+const DEFAULT_SPEC_TYPE = 'draft-mtp'++/**+ * A built-in template name (`chatml`, `llama3`, ...) as opposed to a template+ * body. `--chat-template` takes either, but `--chat-template-file` reads its+ * value as a path, so the two have to be told apart. Any real jinja carries+ * `{`, whitespace or a newline, none of which match here.+ */+const BUILTIN_TEMPLATE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/+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.@@ -76,11 +130,12 @@ export async function generatePreset(providerPath: string,janDataFolderPath: string,config: LlamacppConfig,- opts: { supportsMtp?: boolean; reservedBackgroundSlots?: number } = {}+ opts: { reservedBackgroundSlots?: number } = {}): Promise<{ path: string; embeddingCount: number }> {- const supportsMtp = opts.supportsMtp === true- // Reserved background slot count (thread auto-titling). Disabling that- // feature drops it to 0 so no extra parallel slot is provisioned.+ // Overridable for tests only. Production callers take the default: gating it+ // on the auto-title setting made the reservation appear and disappear behind+ // a toggle that regenerates no preset, so the frontend's pin outlived the+ // slot it named.const reservedBackgroundSlots =typeof opts.reservedBackgroundSlots === 'number'? opts.reservedBackgroundSlots@@ -159,27 +214,15 @@ 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. 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.+ // which can OOM on a large-context model, so a conservative cap stands in.+ // There is no engine-level context setting to read here -- per-model+ // `ctx_len` owns that -- so this is purely the guard.+ //+ // Skipped when auto-fit is on: emitting it would make n_ctx non-zero for+ // every model and stop fit from reducing context to make a model fit.const fitEnabled = config.fit !== falseif (!fitEnabled) {- const ctxSize =- 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}`)- }- // n-gpu-layers default = 0 / auto; emit any non-negative explicit value.- // Skip when auto-fit is on: an explicit n-gpu-layers makes fit abort its- // layer-offload computation (llama.cpp common/fit.cpp), so fit owns ngl too.- if (- !fitEnabled &&- typeof config.n_gpu_layers === 'number' &&- config.n_gpu_layers >= 0- ) {- lines.push(`n-gpu-layers = ${config.n_gpu_layers}`)+ lines.push(`ctx-size = ${DEFAULT_CTX_SIZE}`)}// flash-attn default = 'auto'; explicit on/off only.if (@@ -242,6 +285,15 @@ export async function generatePreset() {lines.push(`n-predict = ${Math.floor(config.n_predict)}`)}+ // batch-size default = 2048 (common.h: n_batch)+ if (+ typeof config.batch_size === 'number' &&+ Number.isFinite(config.batch_size) &&+ config.batch_size > 0 &&+ config.batch_size !== 2048+ ) {+ lines.push(`batch-size = ${Math.floor(config.batch_size)}`)+ }// ubatch-size default = 512if (typeof config.ubatch_size === 'number' &&@@ -251,6 +303,50 @@ export async function generatePreset() {lines.push(`ubatch-size = ${Math.floor(config.ubatch_size)}`)}+ // n-cpu-moe default = 0 (no MoE weights pinned to the host)+ if (+ typeof config.n_cpu_moe === 'number' &&+ Number.isFinite(config.n_cpu_moe) &&+ config.n_cpu_moe > 0+ ) {+ lines.push(`n-cpu-moe = ${Math.floor(config.n_cpu_moe)}`)+ }+ // no-kv-offload default = false (the cache is offloaded). Spelled negatively+ // to match llama.cpp's own flag and the existing no_mmap setting.+ // common_preset's parse_bool_arg recognises `no-kv-offload` as the negated+ // half of the kv-offload pair (arg.cpp:2403-2410) and inverts it, so `true`+ // here does disable offloading.+ if (config.no_kv_offload === true) {+ lines.push('no-kv-offload = true')+ }+ // tensor-split default = empty (even split across devices).+ if (+ typeof config.tensor_split === 'string' &&+ config.tensor_split.trim().length > 0+ ) {+ lines.push(`tensor-split = ${escapeIniValue(config.tensor_split.trim())}`)+ }+ // no-op-offload default = false (host tensor ops are offloaded).+ if (config.no_op_offload === true) {+ lines.push('no-op-offload = true')+ }+ // ctx-checkpoints default = 32, checkpoint-min-step default = 8192.+ if (+ typeof config.ctx_checkpoints === 'number' &&+ Number.isFinite(config.ctx_checkpoints) &&+ config.ctx_checkpoints >= 0 &&+ config.ctx_checkpoints !== 32+ ) {+ lines.push(`ctx-checkpoints = ${Math.floor(config.ctx_checkpoints)}`)+ }+ if (+ typeof config.checkpoint_min_step === 'number' &&+ Number.isFinite(config.checkpoint_min_step) &&+ config.checkpoint_min_step >= 0 &&+ config.checkpoint_min_step !== 8192+ ) {+ lines.push(`checkpoint-min-step = ${Math.floor(config.checkpoint_min_step)}`)+ }// device default = empty (auto-pick)if (typeof config.device === 'string' && config.device.trim().length > 0) {lines.push(`device = ${escapeIniValue(config.device)}`)@@ -271,31 +367,31 @@ export async function generatePreset() {lines.push(`main-gpu = ${Math.floor(config.main_gpu)}`)}- // no-mmap / mlock default = false- if (config.no_mmap === true) {- lines.push('no-mmap = true')- }- if (config.mlock === true) {- lines.push('mlock = true')- }- // rope-scaling default = 'none'+ // `--mlock` and `--no-mmap` are both deprecated aliases that write the single+ // params.load_mode field (arg.cpp:2658-2702), so emitting both left load_mode+ // at NONE and silently dropped mlock -- and mmap+mlock was unreachable.+ // Deriving the one key it actually wants fixes both.+ const wantsMlock = config.mlock === true+ const wantsNoMmap = config.no_mmap === true+ if (wantsMlock || wantsNoMmap) {+ const loadMode = wantsMlock+ ? wantsNoMmap+ ? 'mlock'+ : 'mmap+mlock'+ : 'none'+ lines.push(`load-mode = ${loadMode}`)+ }+ // rope-scaling default is UNSPECIFIED (let the model decide), not 'none'.+ // Treating 'none' as the default made "None" -- an explicit request to+ // disable scaling -- impossible to express.if (typeof config.rope_scaling === 'string' &&config.rope_scaling.length > 0 &&- config.rope_scaling !== 'none'+ config.rope_scaling !== 'auto') {lines.push(`rope-scaling = ${escapeIniValue(config.rope_scaling)}`)}- // rope-scale / rope-freq-scale default = 1.0 (identity / no scaling);// rope-freq-base default = 0 (loaded from model).- if (- typeof config.rope_scale === 'number' &&- Number.isFinite(config.rope_scale) &&- config.rope_scale > 0 &&- config.rope_scale !== 1- ) {- lines.push(`rope-scale = ${config.rope_scale}`)- }if (typeof config.rope_freq_base === 'number' &&Number.isFinite(config.rope_freq_base) &&@@ -303,11 +399,13 @@ export async function generatePreset() {lines.push(`rope-freq-base = ${config.rope_freq_base}`)}+ // rope-freq-scale default = 0 (loaded from model). 1.0 is not the default: it+ // is an explicit "force no scaling", so it must still be emitted. `rope_scale`+ // is gone -- it was a second spelling of this same upstream field (as 1/N).if (typeof config.rope_freq_scale === 'number' &&Number.isFinite(config.rope_freq_scale) &&- config.rope_freq_scale > 0 &&- config.rope_freq_scale !== 1+ config.rope_freq_scale > 0) {lines.push(`rope-freq-scale = ${config.rope_freq_scale}`)}@@ -323,6 +421,12 @@ export async function generatePreset() {lines.push(`cache-ram = ${Math.floor(config.cache_ram)}`)}+ // slot-save-path has no default: naming it is what enables llama.cpp's slot+ // save/restore routes at all. Emitted even with the feature off, so the worker+ // knows which directory to keep clear and can still erase a deleted thread's+ // state; the *budget* is what decides whether anything is written. The C++ arg+ // handler throws if the directory is missing -- the worker creates it first.+ lines.push(`slot-save-path = ${escapeIniValue(threadCacheDir(providerPath))}`)// cache-reuse default = 0 (disabled)if (typeof config.cache_reuse === 'number' &&@@ -374,16 +478,35 @@ export async function generatePreset(lines.push(`mmproj = ${escapeIniValue(mmprojAbs)}`)}- if (mc.chat_template && mc.chat_template.trim().length > 0) {- lines.push(`chat-template = ${escapeIniValue(mc.chat_template)}`)+ // 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.+ const chatTemplate =+ typeof mc.chat_template === 'string' ? mc.chat_template.trim() : ''+ if (chatTemplate.length > 0) {+ if (BUILTIN_TEMPLATE_NAME_RE.test(chatTemplate)) {+ lines.push(`chat-template = ${chatTemplate}`)+ } else {+ const templatePath = await joinPath([+ modelsDir,+ modelId,+ 'chat_template.jinja',+ ])+ await fs.writeFileSync(templatePath, chatTemplate)+ lines.push(`chat-template-file = ${escapeIniValue(templatePath)}`)+ }}- // 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).+ // Per-model overrides -- same default-skipping rules as the [*] block.+ // An explicit 0 means "native" (load the model's own trained context).+ //+ // Emitted even with auto-fit on, unlike n-gpu-layers below: upstream's fit+ // explicitly leaves a user-set context alone (common/fit.cpp: "context size+ // set by user -> no change") and only bails on an explicit n_gpu_layers. The+ // old gate is why "Increase Context Size" did nothing while Fit was on.let ctxEmitted = falseif (- !fitEnabled &&typeof mc.ctx_size === 'number' &&Number.isFinite(mc.ctx_size) &&mc.ctx_size >= 0@@ -391,11 +514,13 @@ export async function generatePreset(lines.push(`ctx-size = ${mc.ctx_size}`)ctxEmitted = true}- // Skipped when auto-fit is on so fit computes GPU offload (see [*] above).+ // Skipped when auto-fit is on: an explicit n-gpu-layers makes fit abort its+ // layer-offload computation. -1 is auto and -2 or below means all layers,+ // so the floor is -2 rather than 0.if (!fitEnabled &&typeof mc.n_gpu_layers === 'number' &&- mc.n_gpu_layers >= 0+ mc.n_gpu_layers >= -2) {lines.push(`n-gpu-layers = ${mc.n_gpu_layers}`)}@@ -460,13 +585,17 @@ export async function generatePreset(}// MTP either lives in the main gguf (mtp_layers > 0) or ships as a separate- // draft gguf (mtp_model_path), which is passed to llama-server as the draft.+ // draft gguf (mtp_model_path), which is passed to the engine as the draft.const hasMtpModel =typeof mc.mtp_model_path === 'string' && mc.mtp_model_path.length > 0const hasMtpLayers =typeof mc.mtp_layers === 'number' && mc.mtp_layers > 0- if (mc.mtp === true && supportsMtp && (hasMtpLayers || hasMtpModel)) {- lines.push('spec-type = draft-mtp')+ if (mc.mtp === true && (hasMtpLayers || hasMtpModel)) {+ const specType =+ typeof mc.spec_type === 'string' && SPEC_TYPES.has(mc.spec_type)+ ? mc.spec_type+ : DEFAULT_SPEC_TYPE+ lines.push(`spec-type = ${specType}`)if (hasMtpModel) {const mtpAbs = await joinPath([janDataFolderPath, mc.mtp_model_path!])lines.push(`spec-draft-model = ${escapeIniValue(mtpAbs)}`)@@ -496,21 +625,31 @@ export async function generatePreset(// defaults for every request to the model (chat and external API clients);// a per-request JSON field still overrides them. INI keys are the CLI// long-form names minus dashes.- const samplingIniKeys: Array<[keyof ModelYaml, string]> = [- ['temperature', 'temperature'],- ['top_k', 'top-k'],- ['top_p', 'top-p'],- ['min_p', 'min-p'],- ['repeat_last_n', 'repeat-last-n'],- ['repeat_penalty', 'repeat-penalty'],- ['presence_penalty', 'presence-penalty'],- ['frequency_penalty', 'frequency-penalty'],+ //+ // Skipping a value equal to llama.cpp's default is not just tidiness here:+ // passing any of the first six sets a `user_sampling_config` bit that+ // suppresses the GGUF's own `general.sampling.*` recommendations, so writing+ // an identical-looking default silently overrode what the model asked for.+ // `null` means "no default, always emit" -- the two penalties set no bit.+ const samplingIniKeys: Array<[keyof ModelYaml, string, number | null]> = [+ ['temperature', 'temperature', 0.8],+ ['top_k', 'top-k', 40],+ ['top_p', 'top-p', 0.95],+ ['min_p', 'min-p', 0.05],+ ['repeat_last_n', 'repeat-last-n', 64],+ ['repeat_penalty', 'repeat-penalty', 1.0],+ ['presence_penalty', 'presence-penalty', null],+ ['frequency_penalty', 'frequency-penalty', null],]- for (const [yamlKey, iniKey] of samplingIniKeys) {+ for (const [yamlKey, iniKey, upstreamDefault] of samplingIniKeys) {const v = mc[yamlKey]- if (typeof v === 'number' && Number.isFinite(v)) {- lines.push(`${iniKey} = ${v}`)- }+ if (typeof v !== 'number' || !Number.isFinite(v)) continue+ if (upstreamDefault !== null && v === upstreamDefault) continue+ // Upstream throws on a negative window rather than clamping, which aborts+ // the load; a legacy -1 from the old "-1 = full context" UI must not reach+ // the preset.+ if (iniKey === 'repeat-last-n' && v < 0) continue+ lines.push(`${iniKey} = ${v}`)}if (mc.embedding === true) {diff --git a/extensions/llamacpp-extension/src/readiness.test.ts b/extensions/llamacpp-extension/src/readiness.test.tsindex 13e59a60d..f7b28bb09 100644--- a/extensions/llamacpp-extension/src/readiness.test.ts+++ b/extensions/llamacpp-extension/src/readiness.test.ts@@ -1,53 +1,39 @@import { describe, it, expect } from 'vitest'import {- backendImpliesGpu,- isBackendConfigured,+ backendFromDeviceIds,evaluateGpuOffload,evaluateEmbeddingVector,} from './readiness'-describe('backendImpliesGpu', () => {- it('recognizes every GPU variant Jan ships', () => {- for (const backend of [- 'linux-cuda-12-common_cpus-x64',- 'linux-cuda-11-common_cpus-x64',- 'win-cuda-13-common_cpus-x64',- 'linux-vulkan-common_cpus-x64',- 'linux-hip-common_cpus-x64',- ]) {- expect(backendImpliesGpu(backend), backend).toBe(true)- }+describe('backendFromDeviceIds', () => {+ // The backend is read off the device the engine actually enumerated, which+ // is what makes it trustworthy: a configured name never proved the runtime+ // had loaded.+ it('strips the device index to name the backend', () => {+ expect(backendFromDeviceIds(['CUDA0'])).toBe('cuda')+ expect(backendFromDeviceIds(['Vulkan0'])).toBe('vulkan')+ expect(backendFromDeviceIds(['Metal0'])).toBe('metal')+ expect(backendFromDeviceIds(['ROCm1'])).toBe('rocm')})- it('does not flag CPU variants', () => {- for (const backend of [- 'linux-common_cpus-x64',- 'win-common_cpus-x64',- 'win-arm64',- 'linux-noavx-x64',- 'linux-avx2-x64',- ]) {- expect(backendImpliesGpu(backend), backend).toBe(false)- }+ it('uses the first device when several are present', () => {+ expect(backendFromDeviceIds(['CUDA0', 'CUDA1'])).toBe('cuda')})- // Metal is implicit on Apple Silicon and always available, so a macOS build- // must not be reported as a GPU variant that failed to find a device.- it('does not flag macOS builds', () => {- expect(backendImpliesGpu('macos-arm64')).toBe(false)- expect(backendImpliesGpu('macos-x64')).toBe(false)+ it('is empty when no device was enumerated', () => {+ expect(backendFromDeviceIds([])).toBe('')+ expect(backendFromDeviceIds(['', ' '])).toBe('')})- it('tolerates an empty or missing backend id', () => {- expect(backendImpliesGpu('')).toBe(false)- expect(backendImpliesGpu(undefined as unknown as string)).toBe(false)+ // A multi-digit index must not eat part of the name.+ it('only strips trailing digits', () => {+ expect(backendFromDeviceIds(['Vulkan10'])).toBe('vulkan')})})describe('evaluateGpuOffload', () => {- it('passes a CPU backend without looking at devices', () => {+ it('passes a machine with no GPU without expecting offload', () => {const result = evaluateGpuOffload({- backend: 'linux-common_cpus-x64',engineDeviceCount: 0,hardwareGpuCount: 0,})@@ -56,9 +42,8 @@ describe('evaluateGpuOffload', () => {expect(result.reason).toBeUndefined()})- it('passes a GPU backend that the engine can actually use', () => {+ it('passes a GPU the engine can actually use', () => {const result = evaluateGpuOffload({- backend: 'linux-cuda-12-common_cpus-x64',engineDeviceCount: 1,hardwareGpuCount: 1,})@@ -66,22 +51,11 @@ describe('evaluateGpuOffload', () => {expect(result.gpuExpected).toBe(true)})- // The machine has no GPU at all: the wrong variant was installed.- it('warns when a GPU backend finds no devices and no GPU hardware exists', () => {- const result = evaluateGpuOffload({- backend: 'linux-cuda-12-common_cpus-x64',- engineDeviceCount: 0,- hardwareGpuCount: 0,- })- expect(result.status).toBe('warning')- expect(result.reason).toBe('noGpuHardware')- })-- // A GPU exists but the engine cannot reach it, which is a driver/runtime- // problem and needs different advice than "you have no GPU".- it('distinguishes a present GPU the engine cannot reach', () => {+ // The one failure worth reporting now that the engine ships with the app: a+ // GPU is present but the engine cannot reach it, which is a driver or runtime+ // problem. There is no longer a "wrong variant installed" case.+ it('warns when a present GPU is invisible to the engine', () => {const result = evaluateGpuOffload({- backend: 'linux-cuda-12-common_cpus-x64',engineDeviceCount: 0,hardwareGpuCount: 1,})@@ -91,15 +65,13 @@ describe('evaluateGpuOffload', () => {it('reports the engine device count it based the verdict on', () => {expect(- evaluateGpuOffload({- backend: 'linux-cuda-12-common_cpus-x64',- engineDeviceCount: 2,- hardwareGpuCount: 2,- }).engineDeviceCount+ evaluateGpuOffload({ engineDeviceCount: 2, hardwareGpuCount: 2 })+ .engineDeviceCount).toBe(2)})})+describe('evaluateEmbeddingVector', () => {it('accepts a healthy vector and reports its dimension', () => {const result = evaluateEmbeddingVector([0.1, -0.2, 0.3])@@ -144,24 +116,3 @@ describe('evaluateEmbeddingVector', () => {expect(result.dimension).toBe(3)})})--describe('isBackendConfigured', () => {- it('accepts a well-formed version/backend pair', () => {- expect(isBackendConfigured('b6099/linux-cuda-12-common_cpus-x64')).toBe(true)- })-- // A fresh install sits in these states through a catalog fetch and a backend- // download; treating them as "configured" is what made a probe report a- // defect instead of an absence.- it('rejects the fresh-install placeholders', () => {- for (const value of ['', ' ', 'none', undefined, null]) {- expect(isBackendConfigured(value), String(value)).toBe(false)- }- })-- it('rejects a malformed pair', () => {- for (const value of ['b6099', 'b6099/', '/linux-cuda', '/']) {- expect(isBackendConfigured(value), value).toBe(false)- }- })-})diff --git a/extensions/llamacpp-extension/src/readiness.ts b/extensions/llamacpp-extension/src/readiness.tsindex f0967b132..c04f48292 100644--- a/extensions/llamacpp-extension/src/readiness.ts+++ b/extensions/llamacpp-extension/src/readiness.ts@@ -6,16 +6,15 @@export type ReadinessStatus = 'ok' | 'warning'/**- * `noGpuHardware` means a GPU build is installed on a machine with no GPU.* `runtimeUnreachable` means a GPU exists but the engine cannot see it, which- * points at the driver or runtime rather than the variant choice.- * `missingLibrary` is the same symptom with the cause established: the loader- * named a dependency it could not resolve.+ * points at the driver or runtime. `missingLibrary` is the same symptom with the+ * cause established: the loader named a dependency it could not resolve.+ *+ * `noGpuHardware` is gone: it meant "a GPU build on a machine with no GPU",+ * which the bundled engine cannot be in -- no GPU means no GPU expected, which+ * is simply `ok`.*/-export type GpuOffloadReason =- | 'noGpuHardware'- | 'runtimeUnreachable'- | 'missingLibrary'+export type GpuOffloadReason = 'runtimeUnreachable' | 'missingLibrary'export interface GpuOffloadCheck {status: ReadinessStatus@@ -26,21 +25,6 @@ export interface GpuOffloadCheck {missingLibraries?: string[]}-/**- * Whether a backend has been selected. Nothing downstream of the router can be- * probed until it has: on a fresh install this stays false through a catalog- * fetch and a backend download, so a probe answered during that window reports- * an absence of setup rather than a defect.- */-export function isBackendConfigured(- versionBackend: string | undefined | null-): boolean {- const value = (versionBackend ?? '').trim()- if (value === '' || value === 'none' || !value.includes('/')) return false- const [version, backend] = value.split('/')- return Boolean(version && backend)-}-export type EmbeddingVectorProblem =| 'missing'| 'empty'@@ -53,29 +37,34 @@ export interface EmbeddingVectorCheck {problem?: EmbeddingVectorProblem}-// Substrings of a backend variant id that mean layers are meant to run on a-// GPU. Metal is excluded: it is implicit on Apple Silicon and always present,-// so a macOS build can never be "a GPU build that found no GPU".-const GPU_BACKEND_MARKERS = ['cuda', 'vulkan', 'hip']--export function backendImpliesGpu(backend: string): boolean {- const lower = (backend ?? '').toLowerCase()- return GPU_BACKEND_MARKERS.some((marker) => lower.includes(marker))+/**+ * The backend a device id came from, e.g. `Vulkan0` -> `vulkan`.+ *+ * Observed rather than declared: with the engine bundled at a pinned version+ * there is no backend *setting* to read, and the device the engine actually+ * enumerated is a stronger signal than a configured name ever was -- a+ * configured `cuda` told us nothing about whether CUDA loaded.+ */+export function backendFromDeviceIds(deviceIds: string[]): string {+ const first = deviceIds.find((id) => id.trim() !== '')+ if (!first) return ''+ return first.trim().replace(/\d+$/, '').toLowerCase()}/**- * A GPU backend that starts cleanly but sees no devices falls back to CPU- * silently: llama.cpp's layer fit puts everything on the host and the router- * still reports healthy. Comparing the engine's own device list against the- * variant is the only way to catch it.+ * A GPU present in hardware but absent from the engine's device list means+ * layers silently run on the host: llama.cpp's layer fit puts everything on the+ * CPU and the engine still reports healthy. Comparing the two counts is the+ * only signal that offload never happened.*/export function evaluateGpuOffload(input: {- backend: stringengineDeviceCount: numberhardwareGpuCount: number}): GpuOffloadCheck {- const { backend, engineDeviceCount, hardwareGpuCount } = input- const gpuExpected = backendImpliesGpu(backend)+ const { engineDeviceCount, hardwareGpuCount } = input+ // "Expected" is now a property of the machine, not of a chosen build: the+ // shipped engine offloads wherever it can.+ const gpuExpected = hardwareGpuCount > 0if (!gpuExpected || engineDeviceCount > 0) {return { status: 'ok', gpuExpected, engineDeviceCount }@@ -85,7 +74,7 @@ export function evaluateGpuOffload(input: {status: 'warning',gpuExpected,engineDeviceCount,- reason: hardwareGpuCount > 0 ? 'runtimeUnreachable' : 'noGpuHardware',+ reason: 'runtimeUnreachable',}}diff --git a/extensions/llamacpp-extension/src/test/backend.test.ts b/extensions/llamacpp-extension/src/test/backend.test.tsdeleted file mode 100644index d793d333e..000000000--- a/extensions/llamacpp-extension/src/test/backend.test.ts+++ /dev/null@@ -1,594 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'-import {- getBackendDir,- getBackendExePath,- isBackendInstalled,- downloadBackend,- verifyBackendInstallation,- fetchRemoteBackends,-} from '../backend'-import { getSystemInfo } from '@janhq/tauri-plugin-hardware-api'-import { fs, getJanDataFolderPath, events } from '@janhq/core'-import { invoke } from '@tauri-apps/api/core'-import { dirname } from '@tauri-apps/api/path'--// Mock constants-const MOCK_JAN_PATH_STRING = '/path/to/jan'--// Mock the core dependencies-vi.mock('@janhq/core', () => ({- logger: {- debug: vi.fn(),- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- },- getJanDataFolderPath: vi.fn().mockResolvedValue('/path/to/jan'),- fs: {- existsSync: vi.fn(),- readdirSync: vi.fn().mockResolvedValue([]),- rm: vi.fn().mockResolvedValue(undefined),- },- joinPath: vi.fn(async (paths: string[]) => paths.join('/')),- events: {- emit: vi.fn(),- },-}))-vi.mock('@tauri-apps/api/core', () => ({- invoke: vi.fn(),-}))-vi.mock('@janhq/tauri-plugin-hardware-api', () => ({- getSystemInfo: vi.fn(),-}))-vi.mock('../util', () => ({- getProxyConfig: vi.fn().mockResolvedValue({ enabled: false }),- basenameNoExt: vi.fn((name: string) => name.replace(/\.tar\.gz$/, '')),-}))-vi.mock('@tauri-apps/api/path', () => ({- dirname: vi.fn(async (path: string) => path.split('/').slice(0, -1).join('/')),- basename: vi.fn(async (path: string) => path.split('/').pop()),-}))-vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {- const actual = await vi.importActual<- typeof import('@janhq/tauri-plugin-llamacpp-api')- >('@janhq/tauri-plugin-llamacpp-api')-- return {- ...actual,- getSupportedFeaturesFromRust: vi.fn().mockResolvedValue({}),- normalizeFeatures: vi.fn().mockReturnValue({}),- determineSupportedBackends: vi- .fn()- .mockResolvedValue(['linux-vulkan-x64']),- }-})--// Mock IS_WINDOWS and window.core global for environment setup-vi.stubGlobal('IS_WINDOWS', false)-vi.stubGlobal('window', {- core: {- extensionManager: {- getByName: vi.fn(),- },- },-})--// Setup global mock for `window.core.extensionManager.getByName` and the download manager-const mockDownloadManager = {- downloadFiles: vi.fn().mockImplementation((items, taskId, onProgress) => {- // Simulate successful download- if (onProgress) onProgress(100, 100)- return Promise.resolve()- }),-}-vi.mocked(window.core.extensionManager.getByName).mockReturnValue(- mockDownloadManager-)--describe('Backend functions', () => {- beforeEach(async () => {- vi.clearAllMocks()- vi.mocked(getJanDataFolderPath).mockResolvedValue(MOCK_JAN_PATH_STRING)-- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'linux',- cpu: {- arch: 'x86_64',- extensions: [],- },- gpus: [],- } as any)-- vi.mocked(window.core.extensionManager.getByName).mockReturnValue(- mockDownloadManager- )- vi.mocked(mockDownloadManager.downloadFiles).mockClear()- // Re-apply after clearAllMocks wipes return values- const { getProxyConfig } = await import('../util')- vi.mocked(getProxyConfig).mockResolvedValue({ enabled: false } as any)- })-- afterEach(() => {- vi.restoreAllMocks()- })-- describe('getBackendDir', () => {- it('should call invoke with correct params and return the path', async () => {- const expectedDir = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/linux-avx2-x64`- vi.mocked(invoke).mockResolvedValueOnce(expectedDir)-- const dir = await getBackendDir('linux-avx2-x64', 'v1.2.3')-- expect(invoke).toHaveBeenCalledWith('plugin:llamacpp|get_backend_dir', {- backend: 'linux-avx2-x64',- version: 'v1.2.3',- janDataFolder: MOCK_JAN_PATH_STRING,- })- expect(dir).toBe(expectedDir)- })-- it('should call invoke with correct params for new common backend name', async () => {- const expectedDir = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v2.0.0/win-common_cpus-x64`- vi.mocked(invoke).mockResolvedValueOnce(expectedDir)-- const dir = await getBackendDir('win-common_cpus-x64', 'v2.0.0')-- expect(invoke).toHaveBeenCalledWith('plugin:llamacpp|get_backend_dir', {- backend: 'win-common_cpus-x64',- version: 'v2.0.0',- janDataFolder: MOCK_JAN_PATH_STRING,- })- expect(dir).toBe(expectedDir)- })- })-- describe('getBackendExePath', () => {- it('should call invoke with correct params including isWindows', async () => {- vi.stubGlobal('IS_WINDOWS', false)- const expectedExe = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/linux-avx2-x64/llama-server`- vi.mocked(invoke).mockResolvedValueOnce(expectedExe)-- const exePath = await getBackendExePath('linux-avx2-x64', 'v1.2.3')-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|get_backend_exe_path',- {- backend: 'linux-avx2-x64',- version: 'v1.2.3',- janDataFolder: MOCK_JAN_PATH_STRING,- isWindows: false,- }- )- expect(exePath).toBe(expectedExe)- })-- it('should pass isWindows=true on Windows', async () => {- vi.stubGlobal('IS_WINDOWS', true)- const expectedExe = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.2.3/win-avx2-x64/llama-server.exe`- vi.mocked(invoke).mockResolvedValueOnce(expectedExe)-- const exePath = await getBackendExePath('win-avx2-x64', 'v1.2.3')-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|get_backend_exe_path',- {- backend: 'win-avx2-x64',- version: 'v1.2.3',- janDataFolder: MOCK_JAN_PATH_STRING,- isWindows: true,- }- )- expect(exePath).toBe(expectedExe)- })- })-- describe('isBackendInstalled', () => {- it('should call invoke with correct params and return true when installed', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(invoke).mockResolvedValueOnce(true)-- const result = await isBackendInstalled('win-avx2-x64', 'v1.0.0')-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|check_backend_installed',- {- backend: 'win-avx2-x64',- version: 'v1.0.0',- janDataFolder: MOCK_JAN_PATH_STRING,- isWindows: false,- }- )- expect(result).toBe(true)- })-- it('should return false when backend is not installed', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(invoke).mockResolvedValueOnce(false)-- const result = await isBackendInstalled('win-avx2-x64', 'v1.0.0')-- expect(result).toBe(false)- })- })-- describe('verifyBackendInstallation', () => {- it('should invoke verify_backend_installation with correct params on Linux', async () => {- vi.stubGlobal('IS_WINDOWS', false)- const mockResult = {- verified: true,- missing_libraries: [],- resolved_libraries: ['libvulkan.so.1', 'libstdc++.so.6'],- }- vi.mocked(invoke).mockResolvedValueOnce(mockResult)-- const result = await verifyBackendInstallation(- 'linux-vulkan-common_cpus-x64',- 'b8795'- )-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|verify_backend_installation',- {- backend: 'linux-vulkan-common_cpus-x64',- version: 'b8795',- janDataFolder: MOCK_JAN_PATH_STRING,- isWindows: false,- }- )- expect(result.verified).toBe(true)- expect(result.missing_libraries).toHaveLength(0)- expect(result.resolved_libraries).toHaveLength(2)- })-- it('should return verified=false with missing library list when deps are absent', async () => {- vi.stubGlobal('IS_WINDOWS', false)- const mockResult = {- verified: false,- missing_libraries: ['libvulkan.so.1', 'libcuda.so.1'],- resolved_libraries: ['libstdc++.so.6'],- }- vi.mocked(invoke).mockResolvedValueOnce(mockResult)-- const result = await verifyBackendInstallation(- 'linux-vulkan-common_cpus-x64',- 'b8795'- )-- expect(result.verified).toBe(false)- expect(result.missing_libraries).toEqual(['libvulkan.so.1', 'libcuda.so.1'])- })-- it('should pass isWindows=true on Windows', async () => {- vi.stubGlobal('IS_WINDOWS', true)- const mockResult = {- verified: true,- missing_libraries: [],- resolved_libraries: ['KERNEL32.dll'],- }- vi.mocked(invoke).mockResolvedValueOnce(mockResult)-- await verifyBackendInstallation('win-common_cpus-x64', 'b8795')-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|verify_backend_installation',- expect.objectContaining({ isWindows: true })- )- })-- it('should propagate invoke errors', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(invoke).mockRejectedValueOnce(- new Error('BINARY_NOT_FOUND')- )-- await expect(- verifyBackendInstallation('linux-common_cpus-x64', 'b8795')- ).rejects.toThrow('BINARY_NOT_FOUND')- })- })-- describe('downloadBackend', () => {- beforeEach(() => {- vi.mocked(mockDownloadManager.downloadFiles).mockClear()- vi.mocked(mockDownloadManager.downloadFiles).mockImplementation(- (items, taskId, onProgress) => {- if (onProgress) onProgress(100, 100)- return Promise.resolve()- }- )- })-- it('should call build_backend_download_items and pass items with proxy to downloadFiles', async () => {- vi.stubGlobal('IS_WINDOWS', false)- const taskId = 'llamacpp-v1-0-0-linux-avx2-x64'- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz`,- model_id: taskId,- },- ]-- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- await downloadBackend('linux-avx2-x64', 'v1.0.0')-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|build_backend_download_items',- {- backend: 'linux-avx2-x64',- version: 'v1.0.0',- source: 'github',- janDataFolder: MOCK_JAN_PATH_STRING,- osType: 'linux',- }- )-- const downloadItems =- vi.mocked(mockDownloadManager.downloadFiles).mock.calls[0][0]- expect(downloadItems.length).toBe(1)- expect(downloadItems[0].url).toContain('linux-avx2-x64.tar.gz')- expect(downloadItems[0].proxy).toBeDefined()- })-- it('should include cudart for cuda-12-common_cpus if Rust returns two items', async () => {- vi.stubGlobal('IS_WINDOWS', true)- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'windows',- cpu: { arch: 'x86_64', extensions: [] },- gpus: [- {- driver_version: '530.41',- nvidia_info: { compute_capability: '8.6' },- },- ],- } as any)-- const taskId = 'llamacpp-v1-0-0-win-cuda-12-common_cpus-x64'- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-win-cuda-12-common_cpus-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/backend.tar.gz`,- model_id: taskId,- },- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/cudart-llama-bin-win-cu12.0-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/build/bin/cuda12.tar.gz`,- model_id: taskId,- },- ]-- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- await downloadBackend('win-cuda-12-common_cpus-x64', 'v1.0.0')-- const downloadItems =- vi.mocked(mockDownloadManager.downloadFiles).mock.calls[0][0]- expect(downloadItems.length).toBe(2)- expect(downloadItems[0].url).toContain('win-cuda-12-common_cpus-x64.tar.gz')- expect(downloadItems[0].save_path).toBe(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/backend.tar.gz`- )- expect(downloadItems[1].url).toContain('cudart-llama-bin-win-cu12.0-x64.tar.gz')- expect(downloadItems[1].save_path).toBe(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-cuda-12-common_cpus-x64/build/bin/cuda12.tar.gz`- )- expect(downloadItems[0].proxy).toBeDefined()- expect(downloadItems[1].proxy).toBeDefined()- })-- it('should include cudart for old cuda-cu11.7 if Rust returns two items', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'linux',- cpu: { arch: 'x86_64', extensions: [] },- gpus: [- {- driver_version: '452.39',- nvidia_info: { compute_capability: '7.0' },- },- ],- } as any)-- const taskId = 'llamacpp-v1-0-0-linux-avx2-cuda-cu11-7-x64'- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-cuda-cu11.7-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/backend.tar.gz`,- model_id: taskId,- },- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/cudart-llama-bin-linux-cu11.7-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/build/bin/cuda11.tar.gz`,- model_id: taskId,- },- ]-- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- await downloadBackend('linux-avx2-cuda-cu11.7-x64', 'v1.0.0')-- const downloadItems =- vi.mocked(mockDownloadManager.downloadFiles).mock.calls[0][0]- expect(downloadItems.length).toBe(2)- expect(downloadItems[0].url).toContain('linux-avx2-cuda-cu11.7-x64.tar.gz')- expect(downloadItems[0].save_path).toBe(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/backend.tar.gz`- )- expect(downloadItems[1].url).toContain('cudart-llama-bin-linux-cu11.7-x64.tar.gz')- expect(downloadItems[1].save_path).toBe(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-cuda-cu11.7-x64/build/bin/cuda11.tar.gz`- )- })-- it('should include cudart for cuda-13 if Rust returns two items', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'linux',- cpu: { arch: 'x86_64', extensions: [] },- gpus: [- {- driver_version: '560.00',- nvidia_info: { compute_capability: '12.0' },- },- ],- } as any)-- const taskId = 'llamacpp-v1-0-0-linux-cuda-13-common_cpus-x64'- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-cuda-13-common_cpus-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-cuda-13-common_cpus-x64/backend.tar.gz`,- model_id: taskId,- },- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/cudart-llama-bin-linux-cu13.0-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-cuda-13-common_cpus-x64/build/bin/cuda13.tar.gz`,- model_id: taskId,- },- ]-- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- await downloadBackend('linux-cuda-13-common_cpus-x64', 'v1.0.0')-- const downloadItems =- vi.mocked(mockDownloadManager.downloadFiles).mock.calls[0][0]- expect(downloadItems.length).toBe(2)- expect(downloadItems[1].url).toContain(- 'cudart-llama-bin-linux-cu13.0-x64.tar.gz'- )- expect(downloadItems[1].save_path).toBe(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-cuda-13-common_cpus-x64/build/bin/cuda13.tar.gz`- )- })-- it('should correctly call decompress for .tar.gz files and use dirname for outputDir', async () => {- vi.stubGlobal('IS_WINDOWS', true)- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'windows',- cpu: { arch: 'x86_64', extensions: [] },- gpus: [],- } as any)-- const taskId = 'llamacpp-v1-0-0-win-avx2-x64'- const backendTarPath = `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64/backend.tar.gz`- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-win-avx2-x64.tar.gz',- save_path: backendTarPath,- model_id: taskId,- },- ]-- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- vi.mocked(dirname).mockResolvedValue(- `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`- )-- await downloadBackend('win-avx2-x64', 'v1.0.0')-- expect(invoke).toHaveBeenCalledWith('decompress', {- path: backendTarPath,- outputDir: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/win-avx2-x64`,- })- })-- it('should fall back to CDN when GitHub download fails', async () => {- vi.stubGlobal('IS_WINDOWS', false)- vi.mocked(getSystemInfo).mockResolvedValue({- os_type: 'linux',- cpu: { arch: 'x86_64', extensions: [] },- gpus: [],- } as any)-- const taskId = 'llamacpp-v1-0-0-linux-avx2-x64'- const mockItems = [- {- url: 'https://github.com/janhq/llama.cpp/releases/download/v1.0.0/llama-v1.0.0-bin-linux-avx2-x64.tar.gz',- save_path: `${MOCK_JAN_PATH_STRING}/llamacpp/backends/v1.0.0/linux-avx2-x64/backend.tar.gz`,- model_id: taskId,- },- ]-- // invoke always returns items (both github and cdn calls)- vi.mocked(invoke).mockImplementation(async (command: string) => {- if (command === 'plugin:llamacpp|build_backend_download_items')- return mockItems- if (command === 'decompress') return undefined- return undefined- })-- // First downloadFiles call (github) throws; second (cdn) succeeds- vi.mocked(mockDownloadManager.downloadFiles)- .mockRejectedValueOnce(new Error('Network error'))- .mockImplementation((items, _taskId, onProgress) => {- if (onProgress) onProgress(100, 100)- return Promise.resolve()- })-- await downloadBackend('linux-avx2-x64', 'v1.0.0')-- // Should have been called twice (github + cdn fallback)- expect(mockDownloadManager.downloadFiles).toHaveBeenCalledTimes(2)- // Second call should use cdn source- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|build_backend_download_items',- expect.objectContaining({ source: 'cdn' })- )- })- })-- describe('fetchRemoteBackends', () => {- it('returns the upstream-released backends from the plugin invoke', async () => {- const remote = [- { version: 'b9300', backend: 'linux-vulkan-common_cpus-x64' },- { version: 'b9222', backend: 'linux-vulkan-common_cpus-x64' },- ]- vi.mocked(invoke).mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|fetch_remote_supported_backends')- return remote as any- return undefined as any- })-- const result = await fetchRemoteBackends()- expect(result).toEqual(remote)- })-- it('returns [] when the remote fetch fails (offline)', async () => {- vi.mocked(invoke).mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|fetch_remote_supported_backends')- throw new Error('offline')- return undefined as any- })- const result = await fetchRemoteBackends()- expect(result).toEqual([])- })- })-})diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex 1de04aeb0..4f6affab0 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -1,7 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'-import { normalizeLlamacppConfig } from '@janhq/tauri-plugin-llamacpp-api'import { getBackendSetting, setBackendSetting } from '../backend-settings'vi.mock('../backend-settings')@@ -9,23 +8,6 @@ vi.mock('../backend-settings')// Mock fetch globallyglobal.fetch = vi.fn()-// Mock backend functions-vi.mock('../backend', () => ({- isBackendInstalled: vi.fn(),- getBackendExePath: vi.fn(),- downloadBackend: vi.fn(),- listSupportedBackends: vi.fn(),- getBackendDir: vi.fn(),- getLocalInstalledBackends: vi.fn(),- fetchRemoteBackends: vi.fn(),- verifyBackendInstallation: vi.fn().mockResolvedValue({- verified: true,- missing_libraries: [],- resolved_libraries: [],- }),- probeBackendGpuLibraries: vi.fn(),-}))-// Mock tauri-plugin-llamacpp-api (partial mock)vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {const actual = await vi.importActual<@@ -43,9 +25,22 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {}),loadLlamaModel: vi.fn(),unloadLlamaModel: vi.fn(),- reloadRouterModels: vi.fn(),- routerHealth: vi.fn().mockResolvedValue(true),- adoptRouter: vi.fn(),+ startEngine: vi.fn().mockResolvedValue({+ port: 39271,+ api_key: 'k',+ pid: 1234,+ models: [],+ }),+ stopEngine: vi.fn(),+ getEngineInfo: vi.fn(),+ reloadEngineModels: vi.fn().mockResolvedValue({+ added: [],+ changed: [],+ removed: [],+ kept: [],+ models_max: 1,+ }),+ engineDevices: vi.fn().mockResolvedValue([]),}})@@ -60,14 +55,21 @@ describe('llamacpp_extension', () => {vi.clearAllMocks()// Re-armed per test: afterEach's restoreAllMocks strips implementations// set in the vi.mock factories.- const { verifyBackendInstallation } = await import('../backend')- vi.mocked(verifyBackendInstallation).mockResolvedValue({- verified: true,- missing_libraries: [],- resolved_libraries: [],+ const { startEngine, getEngineInfo } = await import(+ '@janhq/tauri-plugin-llamacpp-api'+ )+ vi.mocked(startEngine).mockResolvedValue({+ port: 39271,+ api_key: 'k',+ pid: 1234,+ models: [],+ })+ vi.mocked(getEngineInfo).mockResolvedValue({+ port: 39271,+ api_key: 'k',+ pid: 1234,+ models: [],})- const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(routerHealth).mockResolvedValue(true)extension = new llamacpp_extension()})@@ -85,6 +87,42 @@ describe('llamacpp_extension', () => {})})+ describe('resolveThreadCacheBudget', () => {+ const budget = (cfg: Record<string, unknown>): number => {+ // `config` is populated by onLoad, which is not run here.+ ;(extension as any).config = { ...((extension as any).config ?? {}), ...cfg }+ return (extension as any).resolveThreadCacheBudget()+ }++ it('reports the configured size when persistence is on', () => {+ expect(+ budget({ persist_thread_cache: true, thread_cache_size: 4096 })+ ).toBe(4096)+ })++ // 0 is the worker's off switch, so the toggle and the size collapse into+ // one number rather than being forwarded separately.+ it('reports 0 when the toggle is off, whatever the size says', () => {+ expect(+ budget({ persist_thread_cache: false, thread_cache_size: 4096 })+ ).toBe(0)+ })++ it('treats an unusable size as off rather than passing it through', () => {+ for (const thread_cache_size of [0, -1, NaN, undefined, 'lots']) {+ expect(+ budget({ persist_thread_cache: true, thread_cache_size })+ ).toBe(0)+ }+ })++ it('truncates a fractional size, since the flag is an integer of MiB', () => {+ expect(+ budget({ persist_thread_cache: true, thread_cache_size: 2048.7 })+ ).toBe(2048)+ })+ })+describe('getProviderPath', () => {it('should return correct provider path', async () => {const { getJanDataFolderPath, joinPath } = await import('@janhq/core')@@ -241,10 +279,6 @@ describe('llamacpp_extension', () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')const { invoke } = await import('@tauri-apps/api/core')- const backendModule = await import('../backend')- vi.mocked(backendModule.isBackendInstalled).mockResolvedValue(true)- vi.mocked(backendModule.getBackendExePath).mockResolvedValue('/path/to/backend/executable')-vi.mocked(fs.existsSync).mockResolvedValue(true)extension['config'] = {@@ -532,642 +566,80 @@ describe('llamacpp_extension', () => {})})- describe('updateBackend', () => {- beforeEach(() => {- vi.stubGlobal('IS_WINDOWS', false)- extension['config'] = {- version_backend: 'v1.0.0/linux-avx2-x64',- device: '',- } as any- })-- afterEach(() => {- vi.unstubAllGlobals()- })-- describe('validation', () => {- it('should reject empty targetBackendString', async () => {- const result = await extension.updateBackend('')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })-- it('should reject targetBackendString with no slash', async () => {- const result = await extension.updateBackend('v1.2.3')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })-- it('should reject targetBackendString with trailing slash', async () => {- const result = await extension.updateBackend('v1.2.3/')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })-- it('should reject targetBackendString with leading slash', async () => {- const result = await extension.updateBackend('/linux-avx2-x64')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })-- it('should reject targetBackendString with extra segments', async () => {- const result = await extension.updateBackend('v1/backend/extra')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })-- it('should reject targetBackendString with whitespace-only parts', async () => {- const result = await extension.updateBackend(' / ')- expect(result).toEqual({- wasUpdated: false,- newBackend: 'v1.0.0/linux-avx2-x64',- })- })- })-- describe('isUpdatingBackend flag', () => {- it('should reset isUpdatingBackend to false after successful update', async () => {- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)- extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)- extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')- extension['setStoredBackendType'] = vi.fn()- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)-- const { getJanDataFolderPath, joinPath } = await import('@janhq/core')- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')-- const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')- vi.mocked(removeOldBackendVersions).mockResolvedValue([])-- expect(extension['isUpdatingBackend']).toBe(false)-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(extension['isUpdatingBackend']).toBe(false)- })-- it('should reset isUpdatingBackend to false after failed update', async () => {- extension['ensureBackendReady'] = vi.fn().mockRejectedValue(new Error('download failed'))-- expect(extension['isUpdatingBackend']).toBe(false)-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(extension['isUpdatingBackend']).toBe(false)- expect(result.wasUpdated).toBe(false)- })-- it('queues a concurrent request instead of dropping it', async () => {- extension['config'].llamacpp_version = 'v1.0.0'- extension['config'].llamacpp_backend = 'linux-avx2-x64'- extension['recomposeVersionBackend']()- extension['getStoredBackendType'] = vi- .fn()- .mockResolvedValue('linux-avx2-x64')- extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)- extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)- extension['pruneOldBackendVersions'] = vi- .fn()- .mockResolvedValue(undefined)- extension['recordUpdateHistory'] = vi.fn().mockResolvedValue(undefined)- const { mapOldBackendToNew } = await import(- '@janhq/tauri-plugin-llamacpp-api'- )- vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)-- let releaseFirst: () => void = () => {}- const firstDownload = new Promise<void>((r) => {- releaseFirst = r- })- const ensureBackendReady = vi- .fn()- .mockImplementationOnce(() => firstDownload)- .mockResolvedValue(undefined)- extension['ensureBackendReady'] = ensureBackendReady-- const first = extension.updateBackend('v2.0.0/linux-avx2-x64')- const queued = extension.updateBackend('v3.0.0/linux-avx2-x64')- releaseFirst()-- const [firstResult, queuedResult] = await Promise.all([first, queued])-- expect(firstResult.newBackend).toBe('v2.0.0/linux-avx2-x64')- // The queued request ran rather than being silently discarded.- expect(queuedResult.wasUpdated).toBe(true)- expect(queuedResult.newBackend).toBe('v3.0.0/linux-avx2-x64')- expect(ensureBackendReady).toHaveBeenCalledTimes(2)- })-- it('coalesces queued requests so only the newest target runs', async () => {- extension['config'].llamacpp_version = 'v1.0.0'- extension['config'].llamacpp_backend = 'linux-avx2-x64'- extension['recomposeVersionBackend']()- extension['getStoredBackendType'] = vi- .fn()- .mockResolvedValue('linux-avx2-x64')- extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)- extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)- extension['pruneOldBackendVersions'] = vi- .fn()- .mockResolvedValue(undefined)- extension['recordUpdateHistory'] = vi.fn().mockResolvedValue(undefined)- const { mapOldBackendToNew } = await import(- '@janhq/tauri-plugin-llamacpp-api'- )- vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)-- let releaseFirst: () => void = () => {}- const firstDownload = new Promise<void>((r) => {- releaseFirst = r- })- const ensureBackendReady = vi- .fn()- .mockImplementationOnce(() => firstDownload)- .mockResolvedValue(undefined)- extension['ensureBackendReady'] = ensureBackendReady-- const first = extension.updateBackend('v2.0.0/linux-avx2-x64')- const superseded = extension.updateBackend('v3.0.0/linux-avx2-x64')- const newest = extension.updateBackend('v4.0.0/linux-avx2-x64')- releaseFirst()-- const results = await Promise.all([first, superseded, newest])-- // v3 never runs: obsolete before it could start. Both waiters on the- // queued slot get the v4 result.- expect(ensureBackendReady).toHaveBeenCalledTimes(2)- expect(results[1].newBackend).toBe('v4.0.0/linux-avx2-x64')- expect(results[2].newBackend).toBe('v4.0.0/linux-avx2-x64')- expect(extension['config'].version_backend).toBe(- 'v4.0.0/linux-avx2-x64'- )- })- })-- describe('onSettingUpdate guard', () => {- it('does not restart the router while configureBackends is persisting settings', async () => {- // configureBackends writes llamacpp_version/backend on every launch.- // Reacting to that would restart the router a second time, which at- // startup kills the router adoption just took over.- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- extension['isConfiguringBackends'] = true-- extension.onSettingUpdate('llamacpp_backend', 'linux-avx2-x64')- await new Promise((r) => setTimeout(r, 0))-- expect(extension['ensureBackendReady']).not.toHaveBeenCalled()- expect(extension['startRouter']).not.toHaveBeenCalled()- })-- it('does not schedule a preset restart for configureBackends own writes', async () => {- // configureBackends persists the entire settings array, so every- // preset-affecting key echoes back through here. Debouncing a restart- // off that echo is what killed the adopted router ~600ms into startup.- const scheduleRouterRestart = vi.fn()- extension['scheduleRouterRestart'] = scheduleRouterRestart- extension['isConfiguringBackends'] = true-- extension.onSettingUpdate('ctx_size', 4096)-- expect(scheduleRouterRestart).not.toHaveBeenCalled()- // The value is still applied; only the restart is suppressed.- expect(extension['config'].ctx_size).toBe(4096)- })-- it('still schedules a preset restart for a genuine user edit', async () => {- const scheduleRouterRestart = vi.fn()- extension['scheduleRouterRestart'] = scheduleRouterRestart- extension['isConfiguringBackends'] = false-- extension.onSettingUpdate('ctx_size', 8192)-- expect(scheduleRouterRestart).toHaveBeenCalledTimes(1)- })-- it('should skip ensureBackendReady in onSettingUpdate when updateBackend is in progress', async () => {- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)-- // Simulate updateBackend in progress- extension['isUpdatingBackend'] = true-- // Call onSettingUpdate while updateBackend is "running"- extension.onSettingUpdate('llamacpp_backend', 'linux-avx2-x64')-- // ensureBackendReady should NOT have been called from onSettingUpdate- expect(extension['ensureBackendReady']).not.toHaveBeenCalled()- })- })-- describe('stored backend type', () => {- it('should store effectiveBackendType, not the full version/backend string', async () => {- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)- extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)- extension['getStoredBackendType'] = vi.fn().mockReturnValue('old-backend-type')- extension['setStoredBackendType'] = vi.fn()- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)-- const { getJanDataFolderPath, joinPath } = await import('@janhq/core')- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')-- const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')- vi.mocked(removeOldBackendVersions).mockResolvedValue([])-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- // setStoredBackendType should be called with the backend type only, not "version/backend"- const storedValue = vi.mocked(extension['setStoredBackendType']).mock.calls[0]?.[0]- expect(storedValue).not.toContain('/')- })- })-- describe('atomicity', () => {- const armUpdate = async (extension: llamacpp_extension) => {- extension['config'].llamacpp_version = 'v1.0.0'- extension['config'].llamacpp_backend = 'linux-avx2-x64'- extension['recomposeVersionBackend']()- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)- extension['getStoredBackendType'] = vi.fn().mockResolvedValue('linux-avx2-x64')- extension['setStoredBackendType'] = vi.fn().mockResolvedValue(undefined)- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)- const { mapOldBackendToNew } = await import(- '@janhq/tauri-plugin-llamacpp-api'- )- vi.mocked(mapOldBackendToNew).mockImplementation(async (b) => b)- }-- it('restarts the router so the new binary actually serves', async () => {- await armUpdate(extension)- const startRouter = vi.fn().mockResolvedValue(undefined)- extension['startRouter'] = startRouter-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(startRouter).toHaveBeenCalledTimes(1)- expect(result.wasUpdated).toBe(true)- expect(result.newBackend).toBe('v2.0.0/linux-avx2-x64')- })-- // Static dep analysis false-positives (libs dlopen'd at runtime, or- // resolved from paths the analyzer does not search but the spawn env- // does). A router that serves /health is proof the binary works,- // whatever lddtree concluded.- it('does not block a switch on a missing-library report', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const { verifyBackendInstallation } = await import('../backend')- vi.mocked(verifyBackendInstallation).mockResolvedValue({- verified: false,- missing_libraries: ['libcudart.so.12'],- resolved_libraries: [],- })-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(result.wasUpdated).toBe(true)- expect(extension['config'].version_backend).toBe(- 'v2.0.0/linux-avx2-x64'- )- })-- it('rolls back when the router fails its health check', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(routerHealth).mockResolvedValue(false)-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(result.wasUpdated).toBe(false)- expect(extension['config'].llamacpp_version).toBe('v1.0.0')- // Once for the failed target, once bringing the old backend back up.- expect(extension['startRouter']).toHaveBeenCalledTimes(2)- })-- it('rolls back when the router process refuses to start', async () => {- await armUpdate(extension)- extension['startRouter'] = vi- .fn()- .mockRejectedValueOnce(new Error('spawn failed'))- .mockResolvedValue(undefined)-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(result.wasUpdated).toBe(false)- expect(extension['config'].version_backend).toBe(- 'v1.0.0/linux-avx2-x64'- )- })-- it('prunes superseded installs only after the probe passes', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const { removeOldBackendVersions } = await import(- '@janhq/tauri-plugin-llamacpp-api'- )- vi.mocked(removeOldBackendVersions).mockResolvedValue([])- const { joinPath } = await import('@janhq/core')- vi.mocked(joinPath).mockResolvedValue('/jan/llamacpp/backends')-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(removeOldBackendVersions).toHaveBeenCalledWith(- '/jan/llamacpp/backends',- 'v2.0.0',- 'linux-avx2-x64',- 2- )- })-- it('keeps the rollback target on disk when the probe fails', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const { removeOldBackendVersions, routerHealth } = await import(- '@janhq/tauri-plugin-llamacpp-api'- )- vi.mocked(routerHealth).mockResolvedValue(false)-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- // Pruning here would delete the version we just rolled back onto.- expect(removeOldBackendVersions).not.toHaveBeenCalled()- })-- it('records the outcome of a failed switch as rolled-back when the rollback target is healthy', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const written: unknown[] = []- extension['recordUpdateHistory'] = vi.fn(async (r) => {- written.push(r)- })- const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(routerHealth)- .mockResolvedValueOnce(false)- .mockResolvedValueOnce(true)-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(written).toHaveLength(1)- expect(written[0]).toMatchObject({- from: 'v1.0.0/linux-avx2-x64',- to: 'v2.0.0/linux-avx2-x64',- outcome: 'rolled-back',- })- })-- it('records the outcome as rollback-failed when the rollback target also fails its health check', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- const written: unknown[] = []- extension['recordUpdateHistory'] = vi.fn(async (r) => {- written.push(r)- })- const { routerHealth } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(routerHealth).mockResolvedValue(false)-- await extension.updateBackend('v2.0.0/linux-avx2-x64')-- expect(written).toHaveLength(1)- expect(written[0]).toMatchObject({- from: 'v1.0.0/linux-avx2-x64',- to: 'v2.0.0/linux-avx2-x64',- outcome: 'rollback-failed',- })- })-- it('does not attempt a rollback when the download fails pre-commit', async () => {- await armUpdate(extension)- extension['startRouter'] = vi.fn().mockResolvedValue(undefined)- extension['ensureBackendReady'] = vi- .fn()- .mockRejectedValue(new Error('download failed'))-- const result = await extension.updateBackend('v2.0.0/linux-avx2-x64')+})- expect(result.wasUpdated).toBe(false)- expect(extension['startRouter']).not.toHaveBeenCalled()- expect(extension['config'].version_backend).toBe(- 'v1.0.0/linux-avx2-x64'- )- })- })+// The worker is a separate process precisely so a GGML_ASSERT or an OOM kill+// costs the model rather than the app, which only pays off if Jan notices the+// death and respawns. get_engine_info is where that is noticed.+describe('a dead worker is noticed rather than cached', () => {+ let extension: llamacpp_extension- describe('trimming', () => {- it('should trim whitespace from version and backend before use', async () => {- extension['ensureBackendReady'] = vi.fn().mockResolvedValue(undefined)- extension['restartRouterAndProbe'] = vi.fn().mockResolvedValue(true)- extension['getStoredBackendType'] = vi.fn().mockReturnValue('linux-avx2-x64')- extension['setStoredBackendType'] = vi.fn()- extension['getSettings'] = vi.fn().mockResolvedValue([])- extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)-- const { getJanDataFolderPath, joinPath } = await import('@janhq/core')- vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')- vi.mocked(joinPath).mockResolvedValue('/path/to/jan/llamacpp/backends')-- const { mapOldBackendToNew, removeOldBackendVersions } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(mapOldBackendToNew).mockResolvedValue('linux-avx2-x64')- vi.mocked(removeOldBackendVersions).mockResolvedValue([])-- await extension.updateBackend(' v2.0.0 / linux-avx2-x64 ')-- // ensureBackendReady should receive trimmed values- expect(extension['ensureBackendReady']).toHaveBeenCalledWith(- 'linux-avx2-x64',- 'v2.0.0'- )- })- })+ beforeEach(async () => {+ vi.clearAllMocks()+ extension = new llamacpp_extension()})- describe('installCudaRuntime', () => {- it('should reject a path that does not exist', async () => {- const { fs } = await import('@janhq/core')- vi.mocked(fs.existsSync).mockResolvedValue(false)-- await expect(- extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda.zip')- ).rejects.toThrow('Invalid path or file')- })-- it('should reject a file with an unsupported extension', async () => {- const { fs } = await import('@janhq/core')- vi.mocked(fs.existsSync).mockResolvedValue(true)-- await expect(- extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda.rar')- ).rejects.toThrow('Invalid path or file')- })-- it('should reject an archive that is not a CUDA runtime archive', async () => {- const { fs } = await import('@janhq/core')- const { basename } = await import('@tauri-apps/api/path')- vi.mocked(fs.existsSync).mockResolvedValue(true)- vi.mocked(basename).mockResolvedValue('llama-b9193-bin-win-cuda.zip')-- await expect(- extension.installCudaRuntime('/tmp/llama-b9193-bin-win-cuda.zip')- ).rejects.toThrow('Not a CUDA runtime archive')- })-- it('should throw when no matching backend is installed', async () => {- const { fs } = await import('@janhq/core')- const { basename } = await import('@tauri-apps/api/path')- const backendModule = await import('../backend')- vi.mocked(fs.existsSync).mockResolvedValue(true)- vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')- vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([- { backend: 'win-cpu-x64', version: 'v1.0.0' },- ])-- await expect(- extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda-12.4.zip')- ).rejects.toThrow('No installed "win-cuda-12.4" backend found')+ it('re-asks the command even after a successful answer', async () => {+ const { getEngineInfo } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(getEngineInfo).mockResolvedValue({+ port: 39271,+ api_key: 'k',+ pid: 1234,+ models: [],})-- it('should throw when matching backends lack a build/bin directory', async () => {- const { fs, joinPath } = await import('@janhq/core')- const { basename } = await import('@tauri-apps/api/path')- const { invoke } = await import('@tauri-apps/api/core')- const backendModule = await import('../backend')-- vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')- vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([- { backend: 'win-cuda-12.4', version: 'v1.0.0' },- ])- vi.mocked(backendModule.getBackendDir).mockResolvedValue(- '/path/to/jan/llamacpp/backends/v1.0.0/win-cuda-12.4'- )- vi.mocked(joinPath).mockImplementation((paths) =>- Promise.resolve(paths.join('/'))- )- // archive path exists, build/bin dir does not- vi.mocked(fs.existsSync)- .mockResolvedValueOnce(true)- .mockResolvedValue(false)-- await expect(- extension.installCudaRuntime('/tmp/cudart-llama-bin-win-cuda-12.4.zip')- ).rejects.toThrow('none had a build/bin directory')- expect(invoke).not.toHaveBeenCalledWith('decompress', expect.anything())+ expect(await extension.getEngineInfo()).toEqual({+ port: 39271,+ apiKey: 'k',})- it('should decompress into every matching backend build/bin', async () => {- const { fs, joinPath } = await import('@janhq/core')- const { basename } = await import('@tauri-apps/api/path')- const { invoke } = await import('@tauri-apps/api/core')- const backendModule = await import('../backend')-- vi.mocked(basename).mockResolvedValue('cudart-llama-bin-win-cuda-12.4.zip')- vi.mocked(backendModule.getLocalInstalledBackends).mockResolvedValue([- { backend: 'win-cuda-12.4', version: 'v1.0.0' },- { backend: 'win-cuda-12.4', version: 'v2.0.0' },- { backend: 'win-cpu-x64', version: 'v1.0.0' },- ])- vi.mocked(backendModule.getBackendDir).mockImplementation(- (backend, version) =>- Promise.resolve(- `/path/to/jan/llamacpp/backends/${version}/${backend}`- )- )- vi.mocked(joinPath).mockImplementation((paths) =>- Promise.resolve(paths.join('/'))- )- vi.mocked(fs.existsSync).mockResolvedValue(true)- vi.mocked(invoke).mockResolvedValue(undefined)-- await extension.installCudaRuntime(- '/tmp/cudart-llama-bin-win-cuda-12.4.zip'- )-- // Only the two win-cuda-12.4 backends, not the cpu one.- const decompressCalls = vi- .mocked(invoke)- .mock.calls.filter(([cmd]) => cmd === 'decompress')- expect(decompressCalls).toHaveLength(2)- expect(invoke).toHaveBeenCalledWith('decompress', {- path: '/tmp/cudart-llama-bin-win-cuda-12.4.zip',- outputDir:- '/path/to/jan/llamacpp/backends/v1.0.0/win-cuda-12.4/build/bin',- })- expect(invoke).toHaveBeenCalledWith('decompress', {- path: '/tmp/cudart-llama-bin-win-cuda-12.4.zip',- outputDir:- '/path/to/jan/llamacpp/backends/v2.0.0/win-cuda-12.4/build/bin',- })- })+ // The worker died: the command reaps the handle and reports nothing.+ vi.mocked(getEngineInfo).mockResolvedValue(null as never)+ expect(await extension.getEngineInfo()).toBeNull()+ expect(vi.mocked(getEngineInfo)).toHaveBeenCalledTimes(2)})-})--describe('normalizeLlamacppConfig', () => {- describe('parallel field', () => {- it('should default parallel to 1 when undefined', () => {- const result = normalizeLlamacppConfig({})- expect(result.parallel).toBe(1)- })-- it('should default parallel to 1 when null', () => {- const result = normalizeLlamacppConfig({ parallel: null })- expect(result.parallel).toBe(1)- })-- it('should default parallel to 1 when empty string', () => {- const result = normalizeLlamacppConfig({ parallel: '' })- expect(result.parallel).toBe(1)- })-- it('should parse parallel as a number', () => {- const result = normalizeLlamacppConfig({ parallel: 4 })- expect(result.parallel).toBe(4)- })- it('should parse parallel from a string number', () => {- const result = normalizeLlamacppConfig({ parallel: '2' })- expect(result.parallel).toBe(2)+ it('respawns instead of handing out the closed port', async () => {+ const { getEngineInfo } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(getEngineInfo).mockResolvedValue({+ port: 39271,+ api_key: 'k',+ pid: 1234,+ models: [],})+ await extension.getEngineInfo()- it('should allow parallel of 0 (disables the flag)', () => {- const result = normalizeLlamacppConfig({ parallel: 0 })- expect(result.parallel).toBe(0)- })+ vi.mocked(getEngineInfo).mockResolvedValue(null as never)+ vi.spyOn(extension as never, 'ensureProvisioned' as never).mockResolvedValue(+ undefined as never+ )+ const spawn = vi+ .spyOn(extension as never, 'startEngine' as never)+ .mockResolvedValue(undefined as never)+ await extension['ensureEngineReady']()+ expect(spawn).toHaveBeenCalled()})})-describe('refreshRouterPreset embedding slot reservation', () => {++describe('refreshEnginePreset embedding slot reservation', () => {let extension: llamacpp_extension- const setupRunningRouter = (opts: {+ const setupRunningEngine = (opts: {userModelsMax: number- routerEmbeddingBonus: numberembeddingCount: number}) => {extension = new llamacpp_extension()- extension['routerPort'] = 12345- extension['routerApiKey'] = 'key'- extension['config'] = { version_backend: 'b9100/cpu' } as never- extension['userModelsMax'] = opts.userModelsMax- extension['routerEmbeddingBonus'] = opts.routerEmbeddingBonus+ extension['config'] = { models_max: opts.userModelsMax } as neverreturn (async () => {+ // A running worker is what get_engine_info reports, not what the+ // extension last cached: that command is where a worker that died is+ // noticed, so getEngineInfo() always asks it.+ const { getEngineInfo } = await import('@janhq/tauri-plugin-llamacpp-api')+ vi.mocked(getEngineInfo).mockResolvedValue({+ port: 12345,+ api_key: 'key',+ pid: 1234,+ models: [],+ })const { generatePreset } = await import('../preset')vi.mocked(generatePreset).mockResolvedValue({path: '/p/router.preset.ini',@@ -1176,14 +648,20 @@ describe('refreshRouterPreset embedding slot reservation', () => {const { getJanDataFolderPath } = await import('@janhq/core')vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')vi.spyOn(extension, 'getProviderPath').mockResolvedValue('/jan/llamacpp')- const startRouter = vi- .spyOn(extension as never, 'startRouter' as never)+ const startEngine = vi+ .spyOn(extension as never, 'startEngine' as never).mockResolvedValue(undefined as never)- const { reloadRouterModels } = await import(+ const { reloadEngineModels } = await import('@janhq/tauri-plugin-llamacpp-api')- vi.mocked(reloadRouterModels).mockResolvedValue(undefined as never)- return { startRouter, reloadRouterModels: vi.mocked(reloadRouterModels) }+ vi.mocked(reloadEngineModels).mockResolvedValue({+ added: [],+ changed: [],+ removed: [],+ kept: [],+ models_max: 1,+ })+ return { startEngine, reloadEngineModels: vi.mocked(reloadEngineModels) }})()}@@ -1191,48 +669,58 @@ describe('refreshRouterPreset embedding slot reservation', () => {vi.clearAllMocks()})- it('restarts the router when an embedder appears after start (bonus 0 -> 1)', async () => {- const { startRouter, reloadRouterModels } = await setupRunningRouter({+ // The router fixed models_max at spawn, so this case had to cold-restart and+ // evict the model the user was talking to. The worker resizes in place.+ it('reloads rather than restarting when an embedder appears', async () => {+ const { startEngine, reloadEngineModels } = await setupRunningEngine({userModelsMax: 1,- routerEmbeddingBonus: 0,embeddingCount: 1,})- await extension['refreshRouterPreset']()- expect(startRouter).toHaveBeenCalledTimes(1)- expect(reloadRouterModels).not.toHaveBeenCalled()+ await extension['refreshEnginePreset']()+ expect(startEngine).not.toHaveBeenCalled()+ expect(reloadEngineModels).toHaveBeenCalledWith(+ '/p/router.preset.ini',+ 2,+ expect.any(Number)+ )})- it('live-reloads when the embedding bonus is unchanged', async () => {- const { startRouter, reloadRouterModels } = await setupRunningRouter({+ it('reloads when the embedding bonus is unchanged', async () => {+ const { startEngine, reloadEngineModels } = await setupRunningEngine({userModelsMax: 1,- routerEmbeddingBonus: 1,- embeddingCount: 1,+ embeddingCount: 0,})- await extension['refreshRouterPreset']()- expect(startRouter).not.toHaveBeenCalled()- expect(reloadRouterModels).toHaveBeenCalledTimes(1)+ await extension['refreshEnginePreset']()+ expect(startEngine).not.toHaveBeenCalled()+ expect(reloadEngineModels).toHaveBeenCalledWith(+ '/p/router.preset.ini',+ 1,+ expect.any(Number)+ )})- it('restarts when the last embedder is removed (bonus 1 -> 0)', async () => {- const { startRouter, reloadRouterModels } = await setupRunningRouter({- userModelsMax: 1,- routerEmbeddingBonus: 1,- embeddingCount: 0,+ // 0 means unlimited, so the +1 bonus must not turn it into a cap of 1.+ it('keeps models_max unlimited rather than adding the bonus to it', async () => {+ const { reloadEngineModels } = await setupRunningEngine({+ userModelsMax: 0,+ embeddingCount: 1,})- await extension['refreshRouterPreset']()- expect(startRouter).toHaveBeenCalledTimes(1)- expect(reloadRouterModels).not.toHaveBeenCalled()+ await extension['refreshEnginePreset']()+ expect(reloadEngineModels).toHaveBeenCalledWith(+ '/p/router.preset.ini',+ 0,+ expect.any(Number)+ )})- it('does not restart when models_max is unlimited (0)', async () => {- const { startRouter, reloadRouterModels } = await setupRunningRouter({- userModelsMax: 0,- routerEmbeddingBonus: 0,+ it('falls back to a restart when the live reload fails', async () => {+ const { startEngine, reloadEngineModels } = await setupRunningEngine({+ userModelsMax: 1,embeddingCount: 1,})- await extension['refreshRouterPreset']()- expect(startRouter).not.toHaveBeenCalled()- expect(reloadRouterModels).toHaveBeenCalledTimes(1)+ reloadEngineModels.mockRejectedValue(new Error('worker gone'))+ await extension['refreshEnginePreset']()+ expect(startEngine).toHaveBeenCalledTimes(1)})})@@ -1310,217 +798,6 @@ describe('bootstrapDefaultEmbedder', () => {})})-describe('router adoption after a UI crash', () => {- let extension: llamacpp_extension-- const armStartRouter = async () => {- extension = new llamacpp_extension()- extension['config'] = {- version_backend: 'b9100/cpu',- models_max: 1,- } as never- extension['timeout'] = 600-- const { generatePreset } = await import('../preset')- vi.mocked(generatePreset).mockResolvedValue({- path: '/jan/llamacpp/router.preset.ini',- embeddingCount: 0,- })- const { getJanDataFolderPath } = await import('@janhq/core')- vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')- vi.spyOn(extension, 'getProviderPath').mockResolvedValue('/jan/llamacpp')-- const backendModule = await import('../backend')- vi.mocked(backendModule.getBackendExePath).mockResolvedValue(- '/backends/b9100/cpu/llama-server'- )- vi.spyOn(extension as never, 'getRandomPort' as never).mockResolvedValue(- 12345 as never- )- vi.spyOn(extension as never, 'generateApiKey' as never).mockResolvedValue(- 'derived-key' as never- )-- const { invoke } = await import('@tauri-apps/api/core')- // get_router_info: nothing running in memory, which is the post-crash state.- vi.mocked(invoke).mockResolvedValue(null)-- const { adoptRouter } = await import('@janhq/tauri-plugin-llamacpp-api')- return { adoptRouter: vi.mocked(adoptRouter), invoke: vi.mocked(invoke) }- }-- beforeEach(() => {- vi.clearAllMocks()- })-- afterEach(() => {- vi.restoreAllMocks()- })-- it('reuses an adopted router instead of spawning a second one', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockResolvedValue({- port: 45678,- api_key: 'adopted-key',- pid: 999,- })-- await extension['startRouter']()-- expect(adoptRouter).toHaveBeenCalledTimes(1)- expect(extension['routerPort']).toBe(45678)- expect(extension['routerApiKey']).toBe('adopted-key')- expect(invoke).not.toHaveBeenCalledWith(- 'plugin:llamacpp|start_router',- expect.anything()- )- })-- it('spawns a fresh router when there is nothing to adopt', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockResolvedValue(null)- invoke.mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|start_router') {- return { port: 12345, api_key: 'fresh-key', pid: 111 }- }- return null- })-- await extension['startRouter']()-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|start_router',- expect.anything()- )- expect(extension['routerPort']).toBe(12345)- })-- it('falls back to spawning when adoption itself throws', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockRejectedValue(new Error('lock unreadable'))- invoke.mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|start_router') {- return { port: 12345, api_key: 'fresh-key', pid: 111 }- }- return null- })-- await extension['startRouter']()-- expect(invoke).toHaveBeenCalledWith(- 'plugin:llamacpp|start_router',- expect.anything()- )- })-- it('passes the effective models_max so an argv-only change is caught', async () => {- const { adoptRouter, invoke } = await armStartRouter()- extension['config'].models_max = 3 as never- adoptRouter.mockResolvedValue(null)- invoke.mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|start_router') {- return { port: 12345, api_key: 'fresh-key', pid: 111 }- }- return null- })-- await extension['startRouter']()-- expect(adoptRouter).toHaveBeenCalledWith(- '/backends/b9100/cpu/llama-server',- '/jan/llamacpp/router.preset.ini',- 3,- expect.any(String)- )- })-- it('never stops a router before trying to adopt it', async () => {- const { adoptRouter, invoke } = await armStartRouter()- const calls: string[] = []- adoptRouter.mockImplementation(async () => {- calls.push('adopt')- return { port: 45678, api_key: 'adopted-key', pid: 999 }- })- invoke.mockImplementation(async (cmd: string) => {- calls.push(cmd)- return null- })-- await extension['startRouter']()-- expect(calls[0]).toBe('adopt')- expect(calls).not.toContain('plugin:llamacpp|stop_router')- })-- it('coalesces concurrent starts so the second cannot kill the first', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockResolvedValue(null)- let spawns = 0- invoke.mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|start_router') {- spawns += 1- await new Promise((r) => setTimeout(r, 10))- return { port: 12345, api_key: 'fresh-key', pid: 111 }- }- return null- })-- await Promise.all([extension['startRouter'](), extension['startRouter']()])-- expect(spawns).toBe(1)- expect(invoke).not.toHaveBeenCalledWith('plugin:llamacpp|stop_router')- expect(extension['routerPort']).toBe(12345)- })-- it('releases the lock so a later start can still run', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockResolvedValue(null)- invoke.mockImplementation(async (cmd: string) =>- cmd === 'plugin:llamacpp|start_router'- ? { port: 12345, api_key: 'fresh-key', pid: 111 }- : null- )-- await extension['startRouter']()- await extension['startRouter']()-- expect(adoptRouter).toHaveBeenCalledTimes(2)- expect(extension['routerStartLock']).toBeNull()- })-- it('onUnload leaves the router running for the next instance to adopt', async () => {- const { invoke } = await armStartRouter()- extension['routerPort'] = 45678- extension['routerApiKey'] = 'adopted-key'- let adoptResolved = false- extension['backgroundInit'] = (async () => {- await new Promise((r) => setTimeout(r, 10))- adoptResolved = true- })()-- await extension.onUnload()-- expect(invoke).not.toHaveBeenCalledWith('plugin:llamacpp|stop_router')- // Must not block on the in-flight adoption either; that ordering is what- // pinned the kill to the moment adoption completed.- expect(adoptResolved).toBe(false)- expect(extension['routerPort']).toBeUndefined()- expect(extension['routerApiKey']).toBeUndefined()- })-- it('releases the lock even when the spawn fails', async () => {- const { adoptRouter, invoke } = await armStartRouter()- adoptRouter.mockResolvedValue(null)- invoke.mockImplementation(async (cmd: string) => {- if (cmd === 'plugin:llamacpp|start_router') throw new Error('no port')- return null- })-- await expect(extension['startRouter']()).rejects.toThrow('no port')- expect(extension['routerStartLock']).toBeNull()- })-})-describe('verifyEmbeddingModel', () => {let extension: llamacpp_extension@@ -1543,17 +820,6 @@ describe('verifyEmbeddingModel', () => {.spyOn(extension, 'embed').mockResolvedValue({ data: [{ embedding, index: 0 }] } as never)- it('reports pending instead of probing before a backend is configured', async () => {- extension['config'] = { version_backend: '' } as never- const embed = armEmbed([0.1])-- const result = await extension.verifyEmbeddingModel()-- expect(result.pending).toBe(true)- expect(result.status).toBe('ok')- expect(embed).not.toHaveBeenCalled()- })-// The startup install failing is the specific, actionable cause; the load// error it produces downstream is not.it('prefers the bootstrap error over the downstream load error', async () => {@@ -1632,13 +898,9 @@ describe('verifyEmbeddingModel', () => {describe('verifyGpuOffload', () => {let extension: llamacpp_extension- const arm = async (- backend: string,- devices: unknown[],- gpus: unknown[] | undefined- ) => {+ const arm = async (devices: unknown[], gpus: unknown[] | undefined) => {extension = new llamacpp_extension()- extension['config'] = { version_backend: `b9145/${backend}` } as never+ extension['config'] = {} as nevervi.spyOn(extension, 'getDevices').mockResolvedValue(devices as never)const { getSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')vi.mocked(getSystemInfo).mockResolvedValue(@@ -1650,94 +912,58 @@ describe('verifyGpuOffload', () => {vi.clearAllMocks()})- // A fresh install has no backend until a catalog fetch and a download finish.- // Reporting that as a CPU build made a CUDA install look like it left the GPU- // idle, and probing anyway would have blocked on the whole download.- it('reports pending while no backend is configured', async () => {- for (const versionBackend of ['', 'none', 'b9145', undefined]) {- extension = new llamacpp_extension()- extension['config'] = { version_backend: versionBackend } as never- const getDevices = vi.spyOn(extension, 'getDevices')-- const result = await extension.verifyGpuOffload()-- expect(result.pending, String(versionBackend)).toBe(true)- expect(result.status).toBe('ok')- expect(result.backend).toBe('')- expect(getDevices).not.toHaveBeenCalled()- }+ // The backend is now read off the device the engine enumerated rather than a+ // setting, so it reports what actually loaded instead of what was chosen.+ it('names the backend from the enumerated device', async () => {+ await arm([{ id: 'CUDA0', name: 'RTX 4090', mem: 24576, free: 24000 }], [{}])+ const result = await extension.verifyGpuOffload()+ expect(result.status).toBe('ok')+ expect(result.backend).toBe('cuda')+ expect(result.gpuExpected).toBe(true)+ expect(result.engineDeviceCount).toBe(1)})- it('does not report pending once a backend is configured', async () => {- await arm('linux-cuda-12-common_cpus-x64', [{ id: '0' }], [{ uuid: 'a' }])-- expect((await extension.verifyGpuOffload()).pending).toBeUndefined()+ // Metal is implicit on Apple Silicon; it enumerates as a device like any+ // other, so it no longer needs a special case upstream of this.+ it('names metal from an Apple device', async () => {+ await arm([{ id: 'Metal0', name: 'M3 Pro', mem: 1, free: 1 }], [{}])+ expect((await extension.verifyGpuOffload()).backend).toBe('metal')})- it('passes a CUDA backend with a visible device', async () => {- await arm('linux-cuda-12-common_cpus-x64', [{ id: '0' }], [{ uuid: 'a' }])-+ it('passes a machine with no GPU at all', async () => {+ await arm([], [])const result = await extension.verifyGpuOffload()-expect(result.status).toBe('ok')- expect(result.backend).toBe('linux-cuda-12-common_cpus-x64')+ expect(result.gpuExpected).toBe(false)+ expect(result.backend).toBe('')+ expect(result.reason).toBeUndefined()})- // The silent CPU-fallback case: the router is healthy, so nothing else notices.- it('warns when a CUDA backend sees no devices but a GPU exists', async () => {- await arm('linux-cuda-12-common_cpus-x64', [], [{ uuid: 'a' }])-+ // The one actionable failure: the GPU is there but the engine cannot see it.+ it('warns when a present GPU is invisible to the engine', async () => {+ await arm([], [{}])const result = await extension.verifyGpuOffload()-expect(result.status).toBe('warning')expect(result.reason).toBe('runtimeUnreachable')})- it('warns differently when the machine has no GPU at all', async () => {- await arm('linux-cuda-12-common_cpus-x64', [], [])-- const result = await extension.verifyGpuOffload()-- expect(result.reason).toBe('noGpuHardware')- })-- // getDevices spawns `llama-server --list-devices` with a 30s timeout, so a- // CPU build must not pay for a probe whose answer is already known.- it('passes a CPU backend without spawning the device probe', async () => {- await arm('linux-common_cpus-x64', [], [])- const getDevices = vi.spyOn(extension, 'getDevices')-+ it('survives hardware detection returning nothing', async () => {+ await arm([], undefined)const result = await extension.verifyGpuOffload()-expect(result.status).toBe('ok')expect(result.gpuExpected).toBe(false)- expect(getDevices).not.toHaveBeenCalled()})- // A throwing device probe means we do not know why; claiming "no GPU" would- // send the user to buy hardware they already have.- it('does not guess a reason when the device probe fails', async () => {+ // Without a device list there is no basis for a reason code, so the raw cause+ // is reported rather than a guess between "no GPU" and "unreachable GPU".+ it('reports the raw error when the device probe throws', async () => {extension = new llamacpp_extension()- extension['config'] = {- version_backend: 'b9145/linux-cuda-12-common_cpus-x64',- } as never- vi.spyOn(extension, 'getDevices').mockRejectedValue(- new Error('libcudart.so.12: cannot open shared object file')- )-+ extension['config'] = {} as never+ vi.spyOn(extension, 'getDevices').mockRejectedValue(new Error('no worker'))const result = await extension.verifyGpuOffload()-expect(result.status).toBe('warning')+ expect(result.error).toContain('no worker')expect(result.reason).toBeUndefined()- expect(result.error).toContain('libcudart.so.12')- })-- it('survives hardware detection returning nothing', async () => {- await arm('linux-cuda-12-common_cpus-x64', [], undefined)-- const result = await extension.verifyGpuOffload()-- expect(result.reason).toBe('noGpuHardware')})})@@ -1828,19 +1054,46 @@ describe('reportMissingLibrariesFromError', () => {missing_libraries: ['libcudart.so.12'],})+ // There is no selected variant to name any more, so the backend is+ // inferred from the library that failed to resolve.expect(await emitted()).toHaveBeenCalledWith('onBackendVerificationFailed',{- backend: 'linux-cuda-12-common_cpus-x64',- version: 'b9145',+ backend: 'cuda',missingLibraries: ['libcudart.so.12'],})})+ it('infers vulkan from a vulkan loader failure', async () => {+ extension['reportMissingLibrariesFromError']({+ code: 'MISSING_SHARED_LIBRARY',+ missing_libraries: ['libvulkan.so.1'],+ })++ expect(await emitted()).toHaveBeenCalledWith(+ 'onBackendVerificationFailed',+ { backend: 'vulkan', missingLibraries: ['libvulkan.so.1'] }+ )+ })++ // An unrecognised library still raises the dialog: the library name is the+ // actionable part, and withholding it would leave the user with nothing.+ it('still reports a library it cannot attribute to a backend', async () => {+ extension['reportMissingLibrariesFromError']({+ code: 'MISSING_SHARED_LIBRARY',+ missing_libraries: ['libsomething.so.3'],+ })++ expect(await emitted()).toHaveBeenCalledWith(+ 'onBackendVerificationFailed',+ { backend: '', missingLibraries: ['libsomething.so.3'] }+ )+ })+it('ignores unrelated launch failures', async () => {extension['reportMissingLibrariesFromError']({- code: 'LLAMA_CPP_PROCESS_ERROR',+ code: 'MODEL_LOAD_FAILED',details: 'something else',})@@ -1864,135 +1117,6 @@ describe('reportMissingLibrariesFromError', () => {})})-describe('verifyGpuOffload missing-library probe', () => {- let extension: llamacpp_extension-- const arm = async (- devices: unknown[],- probe: unknown,- gpus: unknown[] = [{ uuid: 'a' }]- ) => {- extension = new llamacpp_extension()- extension['config'] = {- version_backend: 'b9145/linux-cuda-12-common_cpus-x64',- } as never- vi.spyOn(extension, 'getDevices').mockResolvedValue(devices as never)- const { getSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')- vi.mocked(getSystemInfo).mockResolvedValue({ gpus } as never)- const { probeBackendGpuLibraries } = await import('../backend')- if (probe instanceof Error) {- vi.mocked(probeBackendGpuLibraries).mockRejectedValue(probe)- } else {- vi.mocked(probeBackendGpuLibraries).mockResolvedValue(probe as never)- }- }-- beforeEach(() => {- vi.clearAllMocks()- })-- // ggml discards the loader error in a release build, so the probe is the only- // way to name the dependency.- it('names the missing library when a GPU backend sees no devices', async () => {- await arm([], {- loaded: [],- inconclusive: false,- failures: [- {- library: 'libggml-cuda.so',- error: 'libnccl.so.2: cannot open shared object file',- missing_libraries: ['libnccl.so.2'],- },- ],- })-- const result = await extension.verifyGpuOffload()-- expect(result.status).toBe('warning')- expect(result.reason).toBe('missingLibrary')- expect(result.missingLibraries).toEqual(['libnccl.so.2'])- })-- it('raises the dependency dialog with the probed libraries', async () => {- await arm([], {- loaded: [],- inconclusive: false,- failures: [- {- library: 'libggml-cuda.so',- error: 'boom',- missing_libraries: ['libnccl.so.2', 'libcublas.so.12'],- },- ],- })-- await extension.verifyGpuOffload()-- const { events } = await import('@janhq/core')- expect(vi.mocked(events.emit)).toHaveBeenCalledWith(- 'onBackendVerificationFailed',- {- backend: 'linux-cuda-12-common_cpus-x64',- version: 'b9145',- missingLibraries: ['libnccl.so.2', 'libcublas.so.12'],- }- )- })-- it('deduplicates libraries reported by several failures', async () => {- await arm([], {- loaded: [],- inconclusive: false,- failures: [- { library: 'a.so', error: 'x', missing_libraries: ['libnccl.so.2'] },- { library: 'b.so', error: 'y', missing_libraries: ['libnccl.so.2'] },- ],- })-- const result = await extension.verifyGpuOffload()-- expect(result.missingLibraries).toEqual(['libnccl.so.2'])- })-- // An inconclusive probe establishes no cause, so the symptom-level verdict- // must stand rather than a fabricated one.- it('falls back to the symptom verdict when the probe is inconclusive', async () => {- await arm([], { loaded: [], failures: [], inconclusive: true })-- const result = await extension.verifyGpuOffload()-- expect(result.reason).toBe('runtimeUnreachable')- expect(result.missingLibraries).toBeUndefined()- })-- it('falls back when the probe finds no failures', async () => {- await arm([], { loaded: ['libggml-cuda.so'], failures: [], inconclusive: false })-- const result = await extension.verifyGpuOffload()-- expect(result.reason).toBe('runtimeUnreachable')- })-- it('survives the probe throwing', async () => {- await arm([], new Error('probe exploded'))-- const result = await extension.verifyGpuOffload()-- expect(result.reason).toBe('runtimeUnreachable')- })-- // A working GPU must never pay for the probe.- it('does not probe when devices are present', async () => {- await arm([{ id: '0' }], { loaded: [], failures: [], inconclusive: false })-- const result = await extension.verifyGpuOffload()-- const { probeBackendGpuLibraries } = await import('../backend')- expect(vi.mocked(probeBackendGpuLibraries)).not.toHaveBeenCalled()- expect(result.status).toBe('ok')- })-})-describe('createDownloadTaskId', () => {let extension: llamacpp_extension@@ -2104,85 +1228,45 @@ describe('import deduplication', () => {})})-describe('first-run provisioning gate', () => {+describe('embedding readiness during the first-run fetch', () => {let extension: llamacpp_extensionbeforeEach(() => {vi.clearAllMocks()extension = new llamacpp_extension()- })-- const armProvisioningSpies = () => ({- configure: vi- .spyOn(extension as never, 'configureBackends')- .mockResolvedValue(undefined as never),- router: vi- .spyOn(extension as never, 'startRouter')- .mockResolvedValue(undefined as never),- embedder: vi- .spyOn(extension as never, 'bootstrapDefaultEmbedder')- .mockResolvedValue(undefined as never),- })-- // A first run downloads hundreds of megabytes; the setup screen asks first.- it('sets the consent flag and provisions when the setup screen asks', async () => {- const spies = armProvisioningSpies()-- await extension.startFirstRunSetup()-- expect(setBackendSetting).toHaveBeenCalledWith(- 'llamacpp-first-run-setup-started',- 'true'+ extension['config'] = {} as never+ })++ // The old gate keyed off "no backend selected yet", which happened to cover+ // this window. With the engine bundled that proxy is gone, so a normal+ // first-run download was being reported as a failed embedding check --+ // a warning on the onboarding checklist for nothing being wrong.+ it('reports pending while the embedder is downloading, not a warning', async () => {+ extension['embedderBootstrapping'] = true+ const load = vi.spyOn(+ extension as never,+ 'ensureEmbeddingModelLoaded' as never)- expect(spies.configure).toHaveBeenCalled()- expect(spies.embedder).toHaveBeenCalled()- })-- it('provisions only once however many callers ask', async () => {- const spies = armProvisioningSpies()-- await Promise.all([- extension.startFirstRunSetup(),- extension.startFirstRunSetup(),- extension['ensureProvisioned'](),- ])-- expect(spies.configure).toHaveBeenCalledTimes(1)- expect(spies.embedder).toHaveBeenCalledTimes(1)- })- // Skipping setup and later loading a local model still has to work.- it('provisions on demand when the router is needed', async () => {- const spies = armProvisioningSpies()- vi.spyOn(extension as never, 'getRouterInfo').mockResolvedValue({- port: 1234,- } as never)+ const report = await extension.verifyEmbeddingModel()- await extension['ensureRouterReady']()-- expect(spies.configure).toHaveBeenCalledTimes(1)+ expect(report.status).toBe('ok')+ expect(report.pending).toBe(true)+ // Probing mid-download would fail on a model that is simply not there yet.+ expect(load).not.toHaveBeenCalled()})- it('still provisions when the persisted flag cannot be written', async () => {- const spies = armProvisioningSpies()- vi.mocked(setBackendSetting).mockRejectedValueOnce(new Error('disk full'))-- await extension.startFirstRunSetup()+ it('reports a real failure once the fetch is done', async () => {+ extension['embedderBootstrapping'] = false+ vi.spyOn(+ extension as never,+ 'ensureEmbeddingModelLoaded' as never+ ).mockRejectedValue(new Error('no embedder') as never)- expect(spies.configure).toHaveBeenCalled()- })+ const report = await extension.verifyEmbeddingModel()- it('treats an unreadable consent flag as not consented', async () => {- vi.mocked(getBackendSetting).mockRejectedValue(new Error('unreadable'))-- expect(await extension['hasSetupConsent']()).toBe(false)- })-- it('reads consent from the persisted flag', async () => {- vi.mocked(getBackendSetting).mockResolvedValue('true')- expect(await extension['hasSetupConsent']()).toBe(true)-- vi.mocked(getBackendSetting).mockResolvedValue(null)- expect(await extension['hasSetupConsent']()).toBe(false)+ expect(report.status).toBe('warning')+ expect(report.pending).toBeUndefined()+ expect(report.error).toContain('no embedder')})})diff --git a/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.ts b/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.tsnew file mode 100644index 000000000..873e88d98--- /dev/null+++ b/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.ts@@ -0,0 +1,70 @@+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join } from 'node:path'++// Enforces the project rule that `invoke` for the llamacpp plugin lives only in+// the plugin's guest-js layer. A raw `invoke('plugin:llamacpp|...')` elsewhere+// bypasses the typed wrapper, so the arg shape is unchecked -- which is how+// getDevices shipped sending a `libraryPath` the command does not take while+// omitting the `envs` it requires.+const REPO_ROOT = join(__dirname, '..', '..', '..', '..')+const GUEST_JS = join(+ REPO_ROOT,+ 'src-tauri',+ 'plugins',+ 'tauri-plugin-llamacpp',+ 'guest-js'+)+const SEARCH_DIRS = [+ join(REPO_ROOT, 'web-app', 'src'),+ join(REPO_ROOT, 'core', 'src'),+ join(REPO_ROOT, 'extensions'),+ join(REPO_ROOT, 'src-tauri', 'plugins'),+]+const SKIP_DIRS = new Set(['node_modules', 'dist', 'dist-js', 'target', 'build'])+const RAW_INVOKE = /['"]plugin:llamacpp\|/++function collect(dir: string): string[] {+ const out: string[] = []+ let entries: string[]+ try {+ entries = readdirSync(dir)+ } catch {+ return out+ }+ for (const entry of entries) {+ const full = join(dir, entry)+ if (statSync(full).isDirectory()) {+ if (SKIP_DIRS.has(entry)) continue+ // The guest-js layer is where these calls belong.+ if (full === GUEST_JS) continue+ out.push(...collect(full))+ continue+ }+ if (!/\.(ts|tsx)$/.test(entry)) continue+ // Test files legitimately assert on the wire-level command name.+ if (/\.test\.tsx?$/.test(entry)) continue+ out.push(full)+ }+ return out+}++describe('invoke for plugin:llamacpp stays in guest-js', () => {+ it('has no raw plugin:llamacpp invoke in production source', () => {+ const offenders: string[] = []+ for (const dir of SEARCH_DIRS) {+ for (const file of collect(dir)) {+ readFileSync(file, 'utf8')+ .split('\n')+ .forEach((line, i) => {+ if (RAW_INVOKE.test(line)) {+ offenders.push(+ `${file.slice(REPO_ROOT.length + 1)}:${i + 1}: ${line.trim()}`+ )+ }+ })+ }+ }+ expect(offenders, offenders.join('\n')).toEqual([])+ })+})diff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.tsindex 4f79a94e2..82890653b 100644--- a/extensions/llamacpp-extension/src/util.test.ts+++ b/extensions/llamacpp-extension/src/util.test.ts@@ -3,6 +3,7 @@ import { logger } from '@janhq/core'import {buildEmbedBatches,detectMtpLayersFromGgufMeta,+ resolveSpecDraftKind,detectTemplateKwargsFromChatTemplate,estimateTokensFromText,getProxyConfig,@@ -673,3 +674,70 @@ describe('detectTemplateKwargsFromChatTemplate', () => {])})})++describe('resolveSpecDraftKind', () => {+ // general.architecture is what llama.cpp itself keys on: `eagle3` and+ // `dflash` are distinct architectures, and anything else carrying draft+ // weights is an MTP head.+ it('reads eagle3 straight off the architecture', () => {+ expect(resolveSpecDraftKind({ 'general.architecture': 'eagle3' })).toBe(+ 'eagle3'+ )+ })++ it('reads dflash off the architecture', () => {+ expect(resolveSpecDraftKind({ 'general.architecture': 'dflash' })).toBe(+ 'dflash'+ )+ })++ // DSpark shares the dflash architecture and is told apart by its Markov+ // head, which is a tensor rather than a metadata key.+ it('separates dspark from dflash by the markov head', () => {+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'dflash' }, {+ hasMarkovHead: true,+ })+ ).toBe('dspark')+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'dflash' }, {+ hasMarkovHead: false,+ })+ ).toBe('dflash')+ })++ // The tensor is the evidence; the catalog's file naming is only a fallback+ // for when it could not be read.+ it('trusts the markov head over the file naming', () => {+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'dflash' }, {+ hasMarkovHead: false,+ hint: 'dspark',+ })+ ).toBe('dflash')+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'dflash' }, {+ hint: 'dspark',+ })+ ).toBe('dspark')+ })++ it('treats any other architecture as an MTP head', () => {+ expect(resolveSpecDraftKind({ 'general.architecture': 'deepseek2' })).toBe(+ 'mtp'+ )+ expect(resolveSpecDraftKind({})).toBe('mtp')+ expect(resolveSpecDraftKind(undefined)).toBe('mtp')+ })++ // The architecture wins: a misnamed file must not select a type the draft+ // cannot implement, which fails the load with an unrelated message.+ it('ignores a hint the architecture contradicts', () => {+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'glm4moe' }, { hint: 'dflash' })+ ).toBe('mtp')+ expect(+ resolveSpecDraftKind({ 'general.architecture': 'dflash' }, { hint: 'mtp' })+ ).toBe('dflash')+ })+})diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex 684ed1ec3..37a12ef11 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -1,30 +1,11 @@import { logger } from '@janhq/core'+import type { SpecDraftKind } from '@janhq/core'import type {TemplateKwarg,TemplateKwargType,} from '@janhq/tauri-plugin-llamacpp-api'import { getBackendSetting, setBackendSetting } from './backend-settings'-// File path utilities-export function basenameNoExt(filePath: string): string {- const VALID_EXTENSIONS = [".tar.gz", ".zip"];-- // handle VALID extensions first- for (const ext of VALID_EXTENSIONS) {- if (filePath.toLowerCase().endsWith(ext)) {- return filePath.slice(0, -ext.length);- }- }-- // fallback: remove only the last extension- const lastDotIndex = filePath.lastIndexOf('.');- if (lastDotIndex > 0) {- return filePath.slice(0, lastDotIndex);- }-- return filePath;-}-// Zustand proxy state structureinterface ProxyState {proxyEnabled: boolean@@ -172,7 +153,7 @@ export type EmbedBatchResult = {const DEFAULT_CHARS_PER_TOKEN = 3const UBATCH_SAFETY_MARGIN = 0.5-export const EMBEDDING_GGUF_ARCHS = new Set([+const EMBEDDING_GGUF_ARCHS = new Set(['bert','nomic-bert','nomic-bert-moe',@@ -183,10 +164,6 @@ export const EMBEDDING_GGUF_ARCHS = new Set(['t5encoder',])-export function isEmbeddingArchitecture(arch: unknown): boolean {- return typeof arch === 'string' && EMBEDDING_GGUF_ARCHS.has(arch)-}-export function detectEmbeddingFromGgufMeta(meta: Record<string, unknown> | undefined): boolean {@@ -205,6 +182,28 @@ export function detectEmbeddingFromGgufMeta(return Number.isFinite(n) && n > 0}+/**+ * Which speculative-decoding flavour a draft gguf implements.+ *+ * `general.architecture` is authoritative -- llama.cpp registers `eagle3` and+ * `dflash` as their own architectures (llama-arch.cpp), and a draft with any+ * other architecture is an MTP head. DSpark is DFlash plus a Markov head, so+ * only `hasMarkovHead` separates those two; `hint` (the catalog's file naming)+ * is the fallback for when the tensor could not be read at all.+ */+export function resolveSpecDraftKind(+ meta: Record<string, unknown> | undefined,+ opts: { hasMarkovHead?: boolean; hint?: SpecDraftKind } = {}+): SpecDraftKind {+ const arch = meta?.['general.architecture']+ if (arch === 'eagle3') return 'eagle3'+ if (arch === 'dflash') {+ const isDspark = opts.hasMarkovHead ?? opts.hint === 'dspark'+ return isDspark ? 'dspark' : 'dflash'+ }+ return 'mtp'+}+export function detectMtpLayersFromGgufMeta(meta: Record<string, unknown> | undefined): number {diff --git a/extensions/llamacpp-extension/vitest.config.ts b/extensions/llamacpp-extension/vitest.config.tsindex 7acffe40c..8fb151a62 100644--- a/extensions/llamacpp-extension/vitest.config.ts+++ b/extensions/llamacpp-extension/vitest.config.ts@@ -1,9 +1,27 @@import { defineConfig } from 'vitest/config'+import { fileURLToPath } from 'node:url'++const resolveHere = (p: string) => fileURLToPath(new URL(p, import.meta.url))export default defineConfig({test: {globals: true,environment: 'jsdom',setupFiles: ['./src/test/setup.ts'],+ alias: {+ // Resolve the plugin to its guest-js source rather than the built+ // package: Node resolution picks dist-js/index.cjs, so the tests ran+ // against whatever was last built and could not observe the wrappers.+ '@janhq/tauri-plugin-llamacpp-api': resolveHere(+ '../../src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts'+ ),+ // The plugin carries its own @tauri-apps/api install, so aliasing+ // guest-js in would otherwise give it a second module instance that+ // `vi.mock('@tauri-apps/api/core')` never intercepts -- the real invoke+ // would run and die on a missing window.__TAURI_INTERNALS__.+ '@tauri-apps/api/core': resolveHere(+ './node_modules/@tauri-apps/api/core.js'+ ),+ },},-})\ No newline at end of file+})diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.tsindex c9c59fc02..d2352e93b 100644--- a/extensions/mlx-extension/src/index.ts+++ b/extensions/mlx-extension/src/index.ts@@ -32,7 +32,11 @@ import {unloadMlxModel,MlxConfig,} from '@janhq/tauri-plugin-mlx-api'-import { readGgufMetadata, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'+import {+ readGgufMetadata,+ generateApiKey,+ ModelConfig,+} from '@janhq/tauri-plugin-llamacpp-api'// Error message constantconst OUT_OF_CONTEXT_SIZE = 'the request exceeds the available context size.'@@ -107,10 +111,7 @@ export default class mlx_extension extends AIEngine {private async generateApiKey(modelId: string, port: string): Promise<string> {// Reuse the llamacpp plugin's API key generation- const hash = await invoke<string>('plugin:llamacpp|generate_api_key', {- modelId: modelId + port,- apiSecret: this.apiSecret,- })+ const hash = await generateApiKey(modelId + port, this.apiSecret)return hash}diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.tsindex cff4ff5fc..893b6c4b9 100644--- a/extensions/rag-extension/src/index.ts+++ b/extensions/rag-extension/src/index.ts@@ -6,7 +6,7 @@ import {VectorDBExtension,type AttachmentInput,type SettingComponentProps,- AIEngine,+ embedTexts,type AttachmentFileInfo,logger,} from '@janhq/core'@@ -232,7 +232,7 @@ export default class RagExtension extends RAGExtension {}}- const queryEmb = (await this.embedTexts([query]))?.[0]+ const queryEmb = (await embedTexts([query]))?.[0]if (!queryEmb) {return {error: 'Failed to compute embeddings',@@ -530,25 +530,7 @@ export default class RagExtension extends RAGExtension {async embed(texts: string[]): Promise<number[][]> {if (!texts || texts.length === 0) return []- return this.embedTexts(texts)+ return embedTexts(texts)}- // Locally implement embedding logic (previously in embeddings-extension)- private async embedTexts(texts: string[]): Promise<number[][]> {- const llm = window.core?.extensionManager.getByName(- '@janhq/llamacpp-extension'- ) as AIEngine & {- embed?: (- texts: string[]- ) => Promise<{ data: Array<{ embedding: number[]; index: number }> }>- }- if (!llm?.embed) throw new Error('llamacpp extension not available')- const res = await llm.embed(texts)- const data: Array<{ embedding: number[]; index: number }> = res?.data || []- const out: number[][] = new Array(texts.length)- for (const item of data) {- out[item.index] = item.embedding- }- return out- }}diff --git a/extensions/rag-extension/src/test/setup.ts b/extensions/rag-extension/src/test/setup.tsindex 51dce354b..27eb3ec49 100644--- a/extensions/rag-extension/src/test/setup.ts+++ b/extensions/rag-extension/src/test/setup.ts@@ -7,16 +7,25 @@ Object.defineProperty(globalThis, 'SETTINGS', {configurable: true,})-// window.core.extensionManager is the bridge RagExtension resolves dependencies through.-Object.defineProperty(globalThis, 'window', {- value: {- core: {- extensionManager: {- get: vi.fn(),- getByName: vi.fn(),- },- },+// window.core.extensionManager is the bridge RagExtension resolves dependencies+// through. `@janhq/core` reads `globalThis.core`, so both names must reach the+// same object -- in the browser they are the same object, and a setup that set+// only one made the core helpers silently see no extensions.+const core = {+ extensionManager: {+ get: vi.fn(),+ getByName: vi.fn(),},+}++Object.defineProperty(globalThis, 'window', {+ value: { core },+ writable: true,+ configurable: true,+})++Object.defineProperty(globalThis, 'core', {+ value: core,writable: true,configurable: true,})@@ -29,7 +38,11 @@ vi.mock('@janhq/tauri-plugin-rag-api', () => ({parseDocument: vi.fn(),}))-vi.mock('@janhq/core', () => {+// The embedding helpers are taken from the real module rather than stubbed:+// they are the shared implementation this extension delegates to, so stubbing+// them would leave the delegation untested on both sides.+vi.mock('@janhq/core', async () => {+ const actual = await vi.importActual<typeof import('@janhq/core')>('@janhq/core')class BaseExtension {registerSettings = vi.fn().mockResolvedValue(undefined)getSetting = vi.fn(async (_key: string, defaultValue: unknown) => defaultValue)@@ -37,9 +50,11 @@ vi.mock('@janhq/core', () => {}class RAGExtension extends BaseExtension {}return {+ embedTexts: actual.embedTexts,+ getEmbeddingEngine: actual.getEmbeddingEngine,+ isEmbeddingEngine: actual.isEmbeddingEngine,RAGExtension,BaseExtension,- AIEngine: class {},RAG_INTERNAL_SERVER: 'rag-internal',ExtensionTypeEnum: {RAG: 'RAG',diff --git a/extensions/vector-db-extension/src/index.test.ts b/extensions/vector-db-extension/src/index.test.tsindex 94c6d8fa5..edc386fc9 100644--- a/extensions/vector-db-extension/src/index.test.ts+++ b/extensions/vector-db-extension/src/index.test.ts@@ -75,35 +75,6 @@ describe('collection naming', () => {})})-describe('embedTexts', () => {- it('throws when no embedding engine is available', async () => {- getByName.mockReturnValue(undefined)- await expect((ext as any).embedTexts(['a'])).rejects.toThrow('llamacpp extension not available')- })-- it('reorders embeddings by their reported index', async () => {- getByName.mockReturnValue(- makeEngine({- embed: vi.fn().mockResolvedValue({- data: [- { embedding: [2], index: 1 },- { embedding: [1], index: 0 },- ],- }),- })- )- const out = await (ext as any).embedTexts(['a', 'b'])- expect(out).toEqual([[1], [2]])- })-- it('returns sparse array when embed omits data', async () => {- getByName.mockReturnValue(makeEngine({ embed: vi.fn().mockResolvedValue({}) }))- const out = await (ext as any).embedTexts(['a', 'b'])- expect(out).toHaveLength(2)- expect(out[0]).toBeUndefined()- })-})-describe('chunk sizing against embedding context', () => {it('clampToEmbeddingContext returns original size when engine lacks ctx accessor', async () => {getByName.mockReturnValue(makeEngine({ getEmbeddingContextSize: undefined }))diff --git a/extensions/vector-db-extension/src/index.ts b/extensions/vector-db-extension/src/index.tsindex de85c190e..2d95fee01 100644--- a/extensions/vector-db-extension/src/index.ts+++ b/extensions/vector-db-extension/src/index.ts@@ -1,4 +1,4 @@-import { VectorDBExtension, type SearchMode, type VectorDBStatus, type VectorChunkInput, type VectorSearchResult, type AttachmentFileInfo, type VectorDBFileInput, type VectorDBIngestOptions, AIEngine } from '@janhq/core'+import { VectorDBExtension, type SearchMode, type VectorDBStatus, type VectorChunkInput, type VectorSearchResult, type AttachmentFileInfo, type VectorDBFileInput, type VectorDBIngestOptions, type EmbeddingEngine, getEmbeddingEngine, embedTexts } from '@janhq/core'import * as vecdb from '@janhq/tauri-plugin-vector-db-api'import * as ragApi from '@janhq/tauri-plugin-rag-api'@@ -92,7 +92,7 @@ export default class VectorDBExt extends VectorDBExtension {// Get embeddings to determine dimension - use a default if no chunkslet dimension = 0if (chunks.length > 0) {- const embeddings = await this.embedTexts(chunks)+ const embeddings = await embedTexts(chunks)dimension = embeddings[0]?.length || 0}@@ -113,7 +113,7 @@ export default class VectorDBExt extends VectorDBExtension {}// Re-embed if we got dimension from createCollection- const embeddings = await this.embedTexts(chunks)+ const embeddings = await embedTexts(chunks)const finalDimension = embeddings[0]?.length || 0if (finalDimension <= 0) throw new Error('Embedding dimension not available')@@ -164,8 +164,8 @@ export default class VectorDBExt extends VectorDBExtension {* most chunks fit on the first try (cheap, but only an estimate).*/private async clampToEmbeddingContext(chunkSize: number, chunkOverlap: number): Promise<number> {- const llm = this.getEmbeddingEngine()- if (!llm?.getEmbeddingContextSize) return chunkSize+ const llm = getEmbeddingEngine()+ if (!llm) return chunkSizeconst ctxSize = await this.probeEmbeddingContextSize(llm)if (!ctxSize || ctxSize <= 0) return chunkSizeconst safeMaxChars = Math.floor(@@ -183,8 +183,8 @@ export default class VectorDBExt extends VectorDBExtension {* so ingestion can never hit exceed_context_size_error.*/private async ensureChunksFitEmbeddingContext(chunks: string[]): Promise<string[]> {- const llm = this.getEmbeddingEngine()- if (!llm?.getEmbeddingContextSize || !llm?.countEmbeddingTokens) return chunks+ const llm = getEmbeddingEngine()+ if (!llm) return chunksconst ctxSize = await this.probeEmbeddingContextSize(llm)if (!ctxSize || ctxSize <= 0) return chunksconst budget = Math.max(1, ctxSize - EMBEDDING_CONTEXT_SAFETY_TOKENS)@@ -202,11 +202,11 @@ export default class VectorDBExt extends VectorDBExtension {* oversized chunks through and surface later as a confusing HTTP 400* (exceed_context_size_error), so fail ingestion with the real cause.*/- private async probeEmbeddingContextSize(llm: {- getEmbeddingContextSize?: () => Promise<number | undefined>- }): Promise<number | undefined> {+ private async probeEmbeddingContextSize(+ llm: EmbeddingEngine+ ): Promise<number | undefined> {try {- return await llm.getEmbeddingContextSize!()+ return await llm.getEmbeddingContextSize()} catch (e) {throw new Error(`Failed to determine embedding context size: ${e instanceof Error ? e.message : String(e)}`@@ -217,7 +217,7 @@ export default class VectorDBExt extends VectorDBExtension {private async splitChunkToFit(text: string,budget: number,- llm: { countEmbeddingTokens: (texts: string[]) => Promise<number[]> }+ llm: EmbeddingEngine): Promise<string[]> {if (!text) return []let count: number@@ -236,27 +236,6 @@ export default class VectorDBExt extends VectorDBExtension {]}- private getEmbeddingEngine() {- return window.core?.extensionManager.getByName('@janhq/llamacpp-extension') as AIEngine & {- embed?: (texts: string[]) => Promise<{ data: Array<{ embedding: number[]; index: number }> }>- getEmbeddingContextSize?: () => Promise<number | undefined>- countEmbeddingTokens?: (texts: string[]) => Promise<number[]>- }- }-- private async embedTexts(texts: string[]): Promise<number[][]> {- const llm = this.getEmbeddingEngine()- if (!llm?.embed) throw new Error('llamacpp extension not available')-- const res = await llm.embed(texts)- const data: Array<{ embedding: number[]; index: number }> = res?.data || []- const out: number[][] = new Array(texts.length)- for (const item of data) {- out[item.index] = item.embedding- }- return out- }-async ingestFile(threadId: string, file: VectorDBFileInput, opts: VectorDBIngestOptions): Promise<AttachmentFileInfo> {// Check for duplicate file (same name + path)const existingFiles = await vecdb.listAttachments(this.collectionForThread(threadId)).catch(() => [])@@ -271,7 +250,7 @@ export default class VectorDBExt extends VectorDBExtension {const fi = await vecdb.createFile(this.collectionForThread(threadId), file)return fi}- const embeddings = await this.embedTexts(chunks)+ const embeddings = await embedTexts(chunks)const dimension = embeddings[0]?.length || 0if (dimension <= 0) throw new Error('Embedding dimension not available')await this.createCollection(threadId, dimension)diff --git a/extensions/vector-db-extension/src/test/setup.ts b/extensions/vector-db-extension/src/test/setup.tsindex 76121d834..2b8737910 100644--- a/extensions/vector-db-extension/src/test/setup.ts+++ b/extensions/vector-db-extension/src/test/setup.ts@@ -18,19 +18,33 @@ vi.mock('@janhq/tauri-plugin-rag-api', () => ({parseDocument: vi.fn().mockResolvedValue(''),}))-vi.mock('@janhq/core', () => ({- VectorDBExtension: class {},- AIEngine: class {},-}))+// The embedding helpers are taken from the real module rather than stubbed:+// they are the shared implementation this extension delegates to, so stubbing+// them would leave the delegation untested on both sides.+vi.mock('@janhq/core', async () => {+ const actual = await vi.importActual<typeof import('@janhq/core')>('@janhq/core')+ return {+ VectorDBExtension: class {},+ embedTexts: actual.embedTexts,+ getEmbeddingEngine: actual.getEmbeddingEngine,+ isEmbeddingEngine: actual.isEmbeddingEngine,+ }+})const getByName = vi.fn()+// `@janhq/core` reads `globalThis.core`; the extension code reads `window.core`.+// They are the same object in the browser, so both names point at one here.+const core = { extensionManager: { getByName } }+Object.defineProperty(globalThis, 'window', {- value: {- core: {- extensionManager: { getByName },- },- },+ value: { core },+ writable: true,+ configurable: true,+})++Object.defineProperty(globalThis, 'core', {+ value: core,writable: true,configurable: true,})diff --git a/scripts/stub-tauri-resources.sh b/scripts/stub-tauri-resources.shindex ac7022e6e..f869b9c41 100755--- a/scripts/stub-tauri-resources.sh+++ b/scripts/stub-tauri-resources.sh@@ -18,6 +18,16 @@ for bin in uv bun; dostub="src-tauri/resources/bin/${bin}-${TRIPLE}"[ -f "$stub" ] || touch "$stub"done+# The engine worker and the ggml runtime beside it. `libggml*` is a glob in the+# bundle config, and a glob that matches nothing is an error (GlobPathNotFound),+# not an empty set -- so one stub library is required, not optional.+case "$(uname -s)" in+ Darwin) EXE=""; LIB="libggml-base.dylib" ;;+ MINGW* | MSYS* | CYGWIN*) EXE=".exe"; LIB="ggml-base.dll" ;;+ *) EXE=""; LIB="libggml-base.so" ;;+esac+[ -f "src-tauri/resources/bin/jan-llama-worker${EXE}" ] || touch "src-tauri/resources/bin/jan-llama-worker${EXE}"+ls src-tauri/resources/bin/*ggml*."${LIB##*.}"* >/dev/null 2>&1 || touch "src-tauri/resources/bin/$LIB"# Icons are gitignored; generate_context!() requires them at compile timefor icon in 32x32.png 128x128.png [email protected] icon.icns icon.ico; do[ -f "src-tauri/icons/$icon" ] || cp src-tauri/icons/icon.png "src-tauri/icons/$icon"diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 3478b316b..e0960a791 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -6876,30 +6876,31 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.8.3"+version = "0.2.0"dependencies = ["base64 0.22.1","byteorder",+ "bytes",+ "cc","futures-util","hmac",+ "http-body-util",+ "hyper",+ "hyper-util","jan-utils","lddtree",- "libloading 0.8.9","log","nix 0.30.1","rand 0.8.5","reqwest 0.12.23","serde","serde_json",- "serde_yaml","sha2",- "sysinfo","tauri","tauri-plugin","tauri-plugin-hardware","thiserror 2.0.17","tokio",- "walkdir",][[package]]diff --git a/src-tauri/build-utils/buildAppImage.sh b/src-tauri/build-utils/buildAppImage.shindex dea03c0b9..d81bed384 100755--- a/src-tauri/build-utils/buildAppImage.sh+++ b/src-tauri/build-utils/buildAppImage.sh@@ -2,21 +2,23 @@APPIMAGETOOL="./.cache/build-tools/appimagetool"RELEASE_CHANNEL=${RELEASE_CHANNEL:-"stable"}+# appimagetool is itself an AppImage, so it mounts itself through FUSE, which+# the hosted runners no longer provide. This runs outside shim-linuxdeploy.sh,+# so it needs its own copy of the fallback.+export APPIMAGE_EXTRACT_AND_RUN=1+mkdir -p ./.cache/build-toolswget https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage -O "${APPIMAGETOOL}" || { echo "Failed to download appimagetool."; exit 1; }chmod +x "${APPIMAGETOOL}"if [ "${RELEASE_CHANNEL}" != "stable" ]; thenAPP_DIR=./src-tauri/target/release/bundle/appimage/Jan-${RELEASE_CHANNEL}.AppDir- LIB_DIR=$APP_DIR/usr/lib/Jan-${RELEASE_CHANNEL}/binarieselseAPP_DIR=./src-tauri/target/release/bundle/appimage/Jan.AppDir- LIB_DIR=$APP_DIR/usr/lib/Jan/binariesfi# bundle additional resources in the AppDir without pulling in their dependenciescp ./src-tauri/resources/bin/bun $APP_DIR/usr/bin/bun-mkdir -p $LIB_DIR/engines# remove appimage generated by tauri buildAPP_IMAGE=./src-tauri/target/release/bundle/appimage/$(ls ./src-tauri/target/release/bundle/appimage/ | grep AppImage | head -1)diff --git a/src-tauri/build-utils/check-engine-toolchain.sh b/src-tauri/build-utils/check-engine-toolchain.shnew file mode 100755index 000000000..0eeb87f95--- /dev/null+++ b/src-tauri/build-utils/check-engine-toolchain.sh@@ -0,0 +1,96 @@+#!/usr/bin/env bash+# Fails fast when the toolchain on PATH cannot produce the requested variant.+# Without this, building `cuda12` on a CUDA 13 host silently yields a cuda13+# artifact under the cuda12 name -- which then crashes on the Pascal cards the+# cuda12 build exists to support.+#+# Takes the variant and the resolved cargo feature list, both decided by the+# Makefile. A script rather than a recipe so Windows checks the same things:+# make there runs recipes through cmd.exe, which has no `command -v`.+set -uo pipefail++VARIANT="${1:?usage: check-engine-toolchain.sh <variant> <features>}"+FEATURES="${2-}"++# The variant is a `-` separated backend list, so each toolkit is asked for by+# the token that needs it rather than by the whole name.+TOKENS=" ${VARIANT//-/ } "+has_token() { case "$TOKENS" in *" $1 "*) return 0 ;; *) return 1 ;; esac; }++want=""+for token in $TOKENS; do+ case "$token" in+ cuda*) want="${token#cuda}" ;;+ esac+done+if [ -n "$want" ]; then+ command -v nvcc >/dev/null 2>&1 || {+ echo "error: JAN_ENGINE_VARIANT=$VARIANT needs nvcc on PATH" >&2+ exit 1+ }+ got=$(nvcc --version | sed -n 's/.*release \([0-9]*\)\..*/\1/p' | head -1)+ if [ "$got" != "$want" ]; then+ echo "error: JAN_ENGINE_VARIANT=$VARIANT but nvcc reports CUDA $got" >&2+ echo " point PATH/CUDA_HOME at a CUDA $want toolkit, or build the cuda$got variant" >&2+ exit 1+ fi+ echo "engine toolchain: CUDA $got matches $VARIANT"+fi++if has_token hip || has_token rocm; then+ command -v hipcc >/dev/null 2>&1 || {+ echo "error: JAN_ENGINE_VARIANT=$VARIANT needs hipcc on PATH (install ROCm)" >&2+ exit 1+ }+ echo "engine toolchain: hipcc found"+fi++command -v cmake >/dev/null 2>&1 || {+ echo "error: building the engine needs cmake on PATH" >&2+ exit 1+}++# Windows only, and both are upstream llama.cpp's own recipe for this build:+# Ninja because ggml's vulkan-shaders-gen ExternalProject cannot identify a+# compiler when nested inside MSBuild, and clang because ggml's per-CPU-variant+# flags (-mavxvnni and friends) live in its GNU-driver branch.+case "$(uname -s)" in+MINGW* | MSYS* | CYGWIN*)+ command -v ninja >/dev/null 2>&1 || {+ echo "error: the engine build needs ninja on PATH on Windows" >&2+ echo " (the Visual Studio generator cannot build vulkan-shaders-gen)" >&2+ exit 1+ }+ command -v clang >/dev/null 2>&1 || {+ echo "error: the engine build needs clang on PATH on Windows (install LLVM)" >&2+ exit 1+ }+ command -v cl >/dev/null 2>&1 || {+ echo "warning: cl is not on PATH; run from a Visual Studio developer prompt" >&2+ echo " if the build cannot find the MSVC headers and libraries." >&2+ }+ echo "engine toolchain: ninja and clang found"+ ;;+esac++if command -v ccache >/dev/null 2>&1; then+ max=$(ccache -s 2>/dev/null | awk -F': *' '/[Mm]ax cache size/ {print $2; exit}')+ echo "engine toolchain: ccache found${max:+ (max $max)}"+elif command -v sccache >/dev/null 2>&1; then+ echo "engine toolchain: sccache found"+else+ echo "warning: no ccache/sccache -- every engine rebuild recompiles from scratch." >&2+ echo " A CUDA rebuild is tens of minutes without it, a couple with it:" >&2+ echo " sudo apt install ccache && ccache -M 25G" >&2+ echo " (25G because CUDA objects are large; the default 5G thrashes.)" >&2+fi++case ",$FEATURES," in+*,engine-vulkan,*)+ command -v glslc >/dev/null 2>&1 || command -v glslangValidator >/dev/null 2>&1 || {+ echo "error: the vulkan backend needs the Vulkan SDK (glslc) on PATH" >&2+ exit 1+ }+ echo "engine toolchain: Vulkan shader compiler found"+ ;;+esacdiff --git a/src-tauri/build-utils/fetch-engine-source.sh b/src-tauri/build-utils/fetch-engine-source.shnew file mode 100755index 000000000..84a721bc3--- /dev/null+++ b/src-tauri/build-utils/fetch-engine-source.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+# Shallow-clones the pinned llama.cpp into the plugin's vendor directory.+#+# Not a submodule: we never modify this tree and pin an exact commit, so a+# submodule only adds gitlink churn and a step every contributor has to+# 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+# 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 same+# implementation: make there runs recipes through cmd.exe, which cannot read+# this shell.+set -euo pipefail++PLUGIN_DIR="src-tauri/plugins/tauri-plugin-llamacpp"+SRC_DIR="$PLUGIN_DIR/vendor/llama.cpp"+SRC_URL="https://github.com/ggml-org/llama.cpp.git"++if [ -n "${JAN_LLAMA_CPP_DIR:-}" ]; then+ echo "engine source: using JAN_LLAMA_CPP_DIR=$JAN_LLAMA_CPP_DIR (skipping the vendored clone)"+ exit 0+fi++pin() { sed -n "s/^pub const $1: &str = \"\(.*\)\";/\1/p" "$PLUGIN_DIR/build.rs"; }+TAG=$(pin LLAMA_CPP_TAG)+COMMIT=$(pin LLAMA_CPP_COMMIT)+if [ -z "$TAG" ] || [ -z "$COMMIT" ]; then+ echo "error: could not read the llama.cpp pin out of $PLUGIN_DIR/build.rs" >&2+ exit 1+fi++if [ ! -f "$SRC_DIR/CMakeLists.txt" ]; then+ echo "Cloning llama.cpp $TAG (shallow)..."+ rm -rf "$SRC_DIR"+ git clone --depth 1 --branch "$TAG" "$SRC_URL" "$SRC_DIR" || {+ echo "error: could not clone $SRC_URL at tag $TAG" >&2+ exit 1+ }+fi++got=$(git -C "$SRC_DIR" rev-parse HEAD)+if [ "$got" != "$COMMIT" ]; then+ echo "error: $SRC_DIR is at $got but build.rs pins $COMMIT." >&2+ echo " The tag $TAG may have moved upstream, or the tree is stale." >&2+ echo " Delete it and re-run, or point JAN_LLAMA_CPP_DIR at a checkout." >&2+ exit 1+fi+echo "engine source: llama.cpp $TAG at $got"diff --git a/src-tauri/build-utils/shim-linuxdeploy.sh b/src-tauri/build-utils/shim-linuxdeploy.shindex 359ccd5ba..df820fb18 100755--- a/src-tauri/build-utils/shim-linuxdeploy.sh+++ b/src-tauri/build-utils/shim-linuxdeploy.sh@@ -27,4 +27,10 @@ firm -f "$SYMLINK"ln -s "$LINUXDEPLOY" "$SYMLINK"+# linuxdeploy, its plugins and appimagetool are all AppImages, which mount+# themselves through FUSE and fail with no output at all where it is missing --+# and the GitHub-hosted images no longer ship libfuse2. Extracting instead is+# the documented fallback and costs a little disk on a host that has FUSE.+export APPIMAGE_EXTRACT_AND_RUN=1+"$@"\ No newline at end of filediff --git a/src-tauri/build-utils/sign-engine.sh b/src-tauri/build-utils/sign-engine.shnew file mode 100755index 000000000..9b6870900--- /dev/null+++ b/src-tauri/build-utils/sign-engine.sh@@ -0,0 +1,65 @@+#!/usr/bin/env bash+# Signs the staged engine worker and the ggml libraries beside it.+#+# Tauri signs the app binary and the installers it produces, not the contents of+# `resources/`, so nothing else in the build signs these. On macOS that is fatal:+# notarization rejects a bundle containing an unsigned mach-o. On Windows it is+# not fatal but the installer then carries unsigned executable code, which is+# what AV heuristics and DLL-signature policies flag.+#+# JAN_ENGINE_REQUIRE_SIGNING=1 turns a missing identity or tool into an error.+# Release CI sets it; a developer build leaves it unset and is only warned, since+# an unsigned local worker runs fine.+set -uo pipefail++DEST="src-tauri/resources/bin"++give_up() {+ if [ "${JAN_ENGINE_REQUIRE_SIGNING:-0}" = "1" ]; then+ echo "error: $1" >&2+ echo " JAN_ENGINE_REQUIRE_SIGNING=1, so the engine must be signed." >&2+ exit 1+ fi+ echo "warning: $1" >&2+ echo " Skipping engine code signing." >&2+ exit 0+}++case "$(uname -s)" in+Darwin)+ identity=$(security find-identity -v -p codesigning 2>/dev/null \+ | grep "Developer ID Application" | head -1 | sed 's/.*"\(.*\)".*/\1/')+ [ -n "$identity" ] || give_up "no 'Developer ID Application' identity in the keychain."+ echo "Signing the engine with: $identity"+ signed=0+ # The backend modules are `.so` even on macOS (CMake MODULE libraries), and+ # ggml dlopens them without checking a signature, so leaving them out here+ # fails notarization rather than anything at run time.+ for target in "$DEST/jan-llama-worker" "$DEST"/libggml*.dylib "$DEST"/libggml*.so; do+ [ -f "$target" ] || continue+ # cmake stages the soname chain as symlinks. codesign follows them, so+ # signing every name would sign the same file three times.+ [ -L "$target" ] && continue+ codesign --force --options runtime --timestamp --sign "$identity" "$target" || exit 1+ codesign --verify --strict "$target" || exit 1+ signed=$((signed + 1))+ done+ [ "$signed" -gt 0 ] || give_up "no engine binaries in $DEST to sign."+ echo "Signed and verified $signed engine binaries"+ ;;+MINGW* | MSYS* | CYGWIN*)+ [ -n "${AZURE_KEY_VAULT_URI:-}" ] || give_up "AZURE_KEY_VAULT_URI is unset, so there is no certificate to sign with."+ command -v AzureSignTool >/dev/null 2>&1 \+ || give_up "AzureSignTool is not on PATH (dotnet tool install --global AzureSignTool)."+ signed=0+ # sign.ps1 is the same script tauri's signCommand runs, so the installer and+ # the binaries inside it are signed by one implementation.+ for target in "$DEST/jan-llama-worker.exe" "$DEST"/ggml*.dll; do+ [ -f "$target" ] || continue+ powershell -ExecutionPolicy Bypass -File src-tauri/sign.ps1 "$target" || exit 1+ signed=$((signed + 1))+ done+ [ "$signed" -gt 0 ] || give_up "no engine binaries in $DEST to sign."+ echo "Signed $signed engine binaries"+ ;;+esacdiff --git a/src-tauri/build-utils/stage-engine.sh b/src-tauri/build-utils/stage-engine.shnew file mode 100755index 000000000..2480b925b--- /dev/null+++ b/src-tauri/build-utils/stage-engine.sh@@ -0,0 +1,101 @@+#!/usr/bin/env bash+# Stages the llama.cpp engine worker and the ggml runtime it needs into+# src-tauri/resources/bin, which is what tauri.<os>.conf.json bundles.+#+# The ggml compute backends are MODULE libraries loaded by name at runtime, and+# ggml resolves them against the *executable's own directory*+# (ggml/src/ggml-backend-reg.cpp: search paths are GGML_BACKEND_DIR, then the+# exe dir, then the cwd). So they have to sit next to jan-llama-worker, not+# merely somewhere in the bundle. libggml/libggml-base are ordinary shared+# libraries found via the rpath ($ORIGIN / @loader_path) build.rs emits, which+# resolves to the same directory.+set -euo pipefail++# Positional first: cmd.exe has no `VAR=value command` prefix, so the Windows+# recipes pass the profile as an argument. The env var stays for callers that+# already set it.+PROFILE="${1:-${JAN_ENGINE_PROFILE:-release}}"+PLUGIN_DIR="src-tauri/plugins/tauri-plugin-llamacpp"+TARGET_DIR="${CARGO_TARGET_DIR:-$PLUGIN_DIR/target}/$PROFILE"+DEST="src-tauri/resources/bin"++# Two extensions, not one. The core libraries (libggml, libggml-base) are+# SHARED, but under GGML_BACKEND_DL every compute backend is a CMake MODULE+# library -- and CMake gives a MODULE the `.so` suffix on macOS too, which is+# also the only extension ggml's own loader looks for there+# (ggml/src/ggml-backend-reg.cpp: backend_filename_extension() is `.dll` on+# Windows and `.so` everywhere else, with no __APPLE__ case). Staging only+# `.dylib` on Darwin therefore ships the two core libraries and not one single+# backend, so Metal and every CPU variant go missing silently -- the loader runs+# with silent=true under NDEBUG.+case "$(uname -s)" in+ MINGW*|MSYS*|CYGWIN*) EXE=".exe"; LIBEXT="dll"; MODEXT="dll" ;;+ Darwin) EXE=""; LIBEXT="dylib"; MODEXT="so" ;;+ *) EXE=""; LIBEXT="so"; MODEXT="so" ;;+esac++WORKER="$TARGET_DIR/jan-llama-worker$EXE"+if [ ! -f "$WORKER" ]; then+ echo "stage-engine: $WORKER not found; run the cargo build first" >&2+ exit 1+fi++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)"+if [ -z "$PREFIX" ]; then+ echo "stage-engine: no ggml-prefix found under $TARGET_DIR/build" >&2+ echo "stage-engine: was the worker built with an engine-* feature?" >&2+ exit 1+fi++# Backend modules live in bin/, the core libraries in lib/ (see build.rs).+#+# Only Darwin has two distinct extensions; elsewhere a second glob over the same+# suffix would list every file twice.+exts=("$LIBEXT")+[ "$MODEXT" = "$LIBEXT" ] || exts+=("$MODEXT")++srcs=()+for ext in "${exts[@]}"; do+ srcs+=("$PREFIX"/bin/*."$ext"* "$PREFIX"/lib/libggml*."$ext"*)+done++# cp -P, not install: cmake ships libggml.so -> .so.0 -> .so.0.21.0 as symlinks,+# and `install` dereferences them, writing three full copies of every core+# library. Preserving the links keeps the soname chain the loader expects and+# stops the bundle carrying the same bytes three times.+staged=0+modules=0+for src in "${srcs[@]}"; do+ [ -e "$src" ] || [ -L "$src" ] || continue+ name="$(basename "$src")"+ cp -Pf "$src" "$DEST/$name"+ [ -L "$src" ] || chmod 644 "$DEST/$name"+ staged=$((staged + 1))+ case "$name" in+ libggml.*|libggml-base.*|ggml.dll|ggml-base.dll) ;;+ *) modules=$((modules + 1)) ;;+ esac+done++if [ "$staged" -eq 0 ]; then+ echo "stage-engine: found $PREFIX but no ggml libraries in it" >&2+ exit 1+fi++# Asserted, not merely printed: the two core libraries alone make `staged`+# non-zero, so a run that staged no backend module at all would otherwise pass+# the check above and ship an app with no compute backend to load.+if [ "$modules" -eq 0 ]; then+ echo "stage-engine: staged $staged ggml libraries but no backend module" >&2+ echo "stage-engine: expected *.$MODEXT MODULE libraries in $PREFIX/bin" >&2+ exit 1+fi++echo "stage-engine: staged $staged ggml libraries ($modules backend modules) into $DEST"diff --git a/src-tauri/capabilities/system-monitor-window.json b/src-tauri/capabilities/system-monitor-window.jsonindex cec43f8d8..dbd736250 100644--- a/src-tauri/capabilities/system-monitor-window.json+++ b/src-tauri/capabilities/system-monitor-window.json@@ -16,7 +16,6 @@"core:window:allow-set-focus","hardware:allow-get-system-info","hardware:allow-get-system-usage",- "llamacpp:allow-get-devices","llamacpp:allow-read-gguf-metadata","deep-link:allow-get-current",{diff --git a/src-tauri/plugins/package.json b/src-tauri/plugins/package.jsonindex df9dec545..6d55d4710 100644--- a/src-tauri/plugins/package.json+++ b/src-tauri/plugins/package.json@@ -2,7 +2,8 @@"private": true,"workspaces": {"packages": [- "**"+ "**",+ "!**/vendor/**"]},"installConfig": {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lockindex b40d708f8..57fa66362 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock@@ -1288,6 +1288,12 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]name = "hyper"version = "1.10.1"@@ -1302,6 +1308,7 @@ dependencies = ["http","http-body","httparse",+ "httpdate","itoa","pin-project-lite","smallvec",@@ -2999,19 +3006,6 @@ dependencies = ["syn 2.0.118",]-[[package]]-name = "serde_yaml"-version = "0.9.34+deprecated"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"-dependencies = [- "indexmap 2.14.0",- "itoa",- "ryu",- "serde",- "unsafe-libyaml",-]-[[package]]name = "serialize-to-javascript"version = "0.1.2"@@ -3427,31 +3421,32 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.8.3"+version = "0.2.0"dependencies = ["base64 0.22.1","byteorder",+ "bytes",+ "cc","futures-util","hmac",+ "http-body-util",+ "hyper",+ "hyper-util","jan-utils","lddtree",- "libloading 0.8.9","log","nix","rand 0.8.6","reqwest 0.12.28","serde","serde_json",- "serde_yaml","sha2",- "sysinfo","tauri","tauri-plugin","tauri-plugin-hardware","tempfile","thiserror 2.0.18","tokio",- "walkdir",][[package]]@@ -3969,12 +3964,6 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"-[[package]]-name = "unsafe-libyaml"-version = "0.2.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"-[[package]]name = "untrusted"version = "0.9.0"diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlindex d0e2408ab..dab9f35c1 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.8.3"+version = "0.2.0"authors = ["Jan <[email protected]>"]description = "Tauri plugin for managing Jan LlamaCpp server processes and model loading"license = "MIT"@@ -15,22 +15,24 @@ base64 = "0.22.1"byteorder = "1.5.0"hmac = "0.12.1"jan-utils = { path = "../../utils" }-# Cross-platform dlopen/LoadLibrary with error strings, for the out-of-process-# backend load probe. Already present in the lockfile via other crates.-libloading = "0.8"-walkdir = "2"log = "0.4"+# Bearer tokens for the worker. The OS assigns the port, so the key cannot be+# derived from it; it is drawn from the OS CSPRNG instead.rand = "0.8"serde = { version = "1.0", features = ["derive"] }sha2 = "0.10.9"-sysinfo = "0.34.2"tauri = { version = "2.5.0", default-features = false, features = [] }thiserror = "2.0.12"tokio = { version = "1", features = ["full"] }tauri-plugin-hardware = { path = "../tauri-plugin-hardware" }serde_json = "1.0.149"-serde_yaml = "0.9.34"futures-util = "0.3"+# The loopback OpenAI-compatible surface. Same versions the app crate already+# uses, so the workspace resolves one copy.+hyper = { version = "1", features = ["server", "http1"] }+hyper-util = { version = "0.1", features = ["tokio"] }+http-body-util = "0.1"+bytes = "1"[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]reqwest = { version = "0.12", features = ["json", "blocking", "stream", "native-tls"] }@@ -46,8 +48,36 @@ reqwest = { version = "0.12", features = ["json", "blocking", "stream", "rustls-[target.'cfg(unix)'.dependencies]nix = { version = "=0.30.1", features = ["signal", "process"] }+# The supervised worker. `required-features` keeps it out of the default build,+# where there is no compiled llama.cpp to link against.+[[bin]]+name = "jan-llama-worker"+path = "src/bin/jan-llama-worker.rs"+required-features = ["engine"]++[features]+default = []+# Compiles and statically links llama.cpp (libllama + libcommon ++# server-context) plus the C shim. OFF by default: this crate is a+# non-optional dependency of the app crate, so enabling it unconditionally+# would put cmake and a C++ toolchain on the critical path of every+# `cargo check`, including the CLI-only job that never runs inference.+engine = []+# GPU backends. Each implies `engine`; they are separate build artifacts+# because each needs its own toolchain (nvcc per CUDA major, the Vulkan SDK,+# ROCm) and CUDA 12 and 13 cannot come from one compile.+engine-cuda = ["engine"]+engine-vulkan = ["engine"]+engine-hip = ["engine"]+engine-metal = ["engine"]+[dev-dependencies]tempfile = "3.0"+serde_json = "1.0.149"+reqwest = { version = "0.12", features = ["json"] }[build-dependencies]tauri-plugin = { version = "2.3.1", features = ["build"] }+# Pure-Rust and cheap when unused; it only shells out to a compiler if the+# `engine` feature actually asks for the native build.+cc = "1"diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 22792d86f..b5ae1a219 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -1,61 +1,772 @@+//! Permission generation, plus the optional native llama.cpp engine build.+//!+//! The engine is behind the `engine` feature and OFF by default, deliberately:+//! this crate is a non-optional dependency of the app crate, so a `build.rs`+//! that always ran cmake would put a C++ toolchain on the critical path of+//! every `cargo check` -- including the CLI-only job, which never runs+//! inference. Enable it for real desktop builds.++// The pinned llama.cpp. `make engine-source` reads TAG and COMMIT straight out+// of this file and shallow-clones that tag, verifying HEAD against COMMIT -- a+// git tag is mutable, so the commit is what actually pins the build. Vendored+// at+// 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";+const COMMANDS: &[&str] = &[// Cleanup command"cleanup_llama_processes",- // LlamaCpp server commands+ // Model lifecycle, served by the engine worker over loopback HTTP"load_llama_model","unload_llama_model",- // Router-mode commands (Phase 1)- "start_router",- "stop_router",- "try_graceful_stop_router",- "force_kill_router_tree",- "get_router_info",- "reload_router_models",- "router_slots_idle",- "router_health",- "adopt_router",- "get_devices","generate_api_key",- "is_process_running","ensure_session_ready",- "get_random_port","find_session_by_model","get_loaded_models",- "get_all_sessions",- "get_session_by_model",+ // The in-process engine worker, which replaced the spawned router and the+ // downloaded backend it used to run+ "start_engine",+ "stop_engine",+ "get_engine_info",+ "reload_engine_models",+ "engine_devices",+ "force_stop_engine",+ "engine_slots_idle",+ "erase_thread_slot_state",// GGUF commands"read_gguf_metadata",- "estimate_kv_cache_size",- "get_model_size",+ "find_gguf_tensors","is_model_supported",- // backend management- "map_old_backend_to_new",- "get_local_installed_backends",- "list_supported_backends",- "determine_supported_backends",- "get_supported_features",- "is_cuda_installed",- "find_latest_version_for_backend",- "prioritize_backends",- "parse_backend_version",- "check_backend_for_updates",- "remove_old_backend_versions",- "validate_backend_string",- "should_migrate_backend",- "handle_setting_update",- // Backend path & download commands- "get_backend_dir",- "get_backend_exe_path",- "check_backend_installed",- "verify_backend_installation",- "fetch_remote_supported_backends",- "build_backend_download_items",- "fetch_backend_checksums",- "verify_file_sha512",- // Backend GPU library load probe- "probe_backend_load",];fn main() {tauri_plugin::Builder::new(COMMANDS).build();++ println!("cargo:rustc-env=JAN_LLAMA_CPP_TAG={LLAMA_CPP_TAG}");+ println!("cargo:rustc-env=JAN_LLAMA_CPP_BUILD_NUMBER={LLAMA_CPP_BUILD_NUMBER}");+ println!("cargo:rustc-env=JAN_LLAMA_CPP_COMMIT={LLAMA_CPP_COMMIT}");+ println!("cargo:rustc-env=JAN_LLAMA_CPP_VERSION={LLAMA_CPP_VERSION}");++ // Features reach a build script only as CARGO_FEATURE_* env vars -- a+ // `#[cfg(feature = ...)]` here would silently never fire.+ if std::env::var_os("CARGO_FEATURE_ENGINE").is_some() {+ engine::build();+ }+}++mod engine {+ use std::path::{Path, PathBuf};+ use std::{env, fs, process::Command};++ use super::{LLAMA_CPP_BUILD_NUMBER, LLAMA_CPP_COMMIT, LLAMA_CPP_TAG};++ /// Static archives from stage 2, in the order the linker group needs them+ /// declared. server-context <-> llama-common <-> mtmd have circular+ /// references, so on GNU ld they go inside one --start-group rather than+ /// being ordered by hand. No ggml here: stage 1 builds it shared.+ const ARCHIVES: &[&str] = &[+ "jan_llama_shim",+ "server-context",+ "llama-common",+ "llama-common-base",+ "mtmd",+ "llama",+ "cpp-httplib",+ "vendor-hash",+ ];++ /// Windows needs a generator that is not Visual Studio, and a compiler+ /// named in the environment rather than found by one.+ ///+ /// ggml builds `vulkan-shaders-gen` as an `ExternalProject`, which+ /// reconfigures itself with the parent's generator *and nothing else* --+ /// verified from a generated `-cfgcmd.txt`, whose whole command line is the+ /// cache args the caller listed plus `-G<parent generator>`. Under the+ /// Visual Studio generator that child configure runs inside MSBuild, where+ /// it cannot identify a compiler at all ("The C compiler identification is+ /// unknown", then "No CMAKE_C_COMPILER could be found") and the engine+ /// build dies. Ninja keeps both configures flat and non-recursive, and+ /// `CC`/`CXX` reach the child because it inherits this environment -- the+ /// one channel ExternalProject cannot strip. clang-cl rather than cl+ /// because it locates the MSVC toolchain and Windows SDK itself, so no+ /// developer prompt is needed, while staying an MSVC-ABI, MSVC-naming+ /// compiler: the archives here link into a Rust `*-pc-windows-msvc` binary,+ /// which a GNU-driver clang would break by emitting `libllama.a`.+ fn windows_generator(cmd: &mut Command, src: &Path) {+ if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() != "windows" {+ return;+ }+ if !on_path("ninja") {+ println!(+ "cargo:warning=ninja is not on PATH, so cmake will pick the Visual Studio \+ generator, whose nested vulkan-shaders-gen configure cannot find a compiler"+ );+ return;+ }+ cmd.args(["-G", WINDOWS_GENERATOR]);+ cmd.arg(format!(+ "-DCMAKE_TOOLCHAIN_FILE={}",+ cmake_path(&src.join("cmake/x64-windows-llvm.cmake"))+ ));+ }++ /// cmake takes forward slashes on every platform and treats a backslash as+ /// an escape in some contexts, so paths handed to `-D` go through here.+ fn cmake_path(p: &Path) -> String {+ p.display().to_string().replace('\\', "/")+ }++ fn on_path(exe: &str) -> bool {+ let Some(path) = env::var_os("PATH") else {+ return false;+ };+ env::split_paths(&path)+ .any(|dir| dir.join(exe).is_file() || dir.join(format!("{exe}.exe")).is_file())+ }++ /// upstream llama.cpp's own Windows recipe for this exact configuration+ /// (`GGML_BACKEND_DL` plus `GGML_CPU_ALL_VARIANTS`), down to the generator+ /// and toolchain file, and it is what its release job runs on this very+ /// image -- its ccache key says `windows-2025-vs2026`.+ ///+ /// Both halves are load-bearing. Ninja keeps the vulkan-shaders-gen+ /// ExternalProject out of MSBuild, which cannot identify a compiler when+ /// nested. The toolchain file sets `CMAKE_SYSTEM_NAME`, which makes+ /// `CMAKE_CROSSCOMPILING` true, which is what makes ggml generate a host+ /// toolchain and *pass it to that child* -- the only channel by which the+ /// child gets a compiler at all, since ExternalProject forwards nothing but+ /// the generator. It also selects clang's GNU driver, whose branch in+ /// ggml-cpu/CMakeLists.txt carries the per-variant `-mavxvnni` flags; the+ /// MSVC branch beside it only defines `__AVXVNNI__` and adds no flag, so+ /// clang-cl refused `_mm256_dpbusd_avx_epi32` in the alderlake variant.+ /// Artifact naming stays MSVC (`ggml.lib`, no `lib` prefix) because that+ /// follows the target, not the driver, which is what lets these archives+ /// link into a Rust `*-pc-windows-msvc` binary.+ const WINDOWS_GENERATOR: &str = "Ninja Multi-Config";++ /// The cmake configuration. Named on every build and install step, not+ /// just at configure time: a multi-config generator (Visual Studio, which+ /// is cmake's default on Windows) ignores CMAKE_BUILD_TYPE entirely and+ /// silently builds Debug, which links the non-redistributable debug CRT.+ /// The single-config generators accept the flag and ignore it.+ const CONFIG: &str = "Release";++ /// Where each archive lands under the stage 2 cmake build tree.+ const ARCHIVE_DIRS: &[&str] = &[+ "src",+ "common",+ "tools/server",+ "tools/mtmd",+ "vendor/cpp-httplib",+ "vendor/hash",+ ];++ /// ggml, linked as shared libraries from stage 1. The compute backends are+ /// *not* here: they are `MODULE` libraries loaded by name at runtime.+ const SHARED_LIBS: &[&str] = &["ggml", "ggml-base"];++ /// GPU backends, as (cargo feature, ggml cmake flag). These belong to+ /// stage 1 because they are ggml backend modules.+ const GPU_BACKENDS: &[(&str, &str)] = &[+ ("engine-cuda", "-DGGML_CUDA=ON"),+ ("engine-vulkan", "-DGGML_VULKAN=ON"),+ ("engine-hip", "-DGGML_HIP=ON"),+ ("engine-metal", "-DGGML_METAL=ON"),+ ];++ pub fn build() {+ println!("cargo:rerun-if-changed=shim/jan_llama_shim.cpp");+ println!("cargo:rerun-if-changed=shim/jan_llama_shim.h");+ println!("cargo:rerun-if-env-changed=JAN_LLAMA_PREBUILT_DIR");+ 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");++ // Headers are always needed: the shim is our code and is compiled+ // here even when the archives come prebuilt, so it cannot drift from+ // the crate.+ let src = source_dir();++ // Prebuilt path: a matrix job compiled both stages once and published+ // them, so the app build only links. No network, no cmake, no nvcc.+ // Layout is `lib/` (stage 2 .a plus stage 1 ggml shared libs),+ // `include/` (llama.cpp's *generated* headers, e.g. build-info.h) and+ // `backends/` (the runtime-loaded ggml modules).+ let (mut search_dirs, generated_include, backend_dir) =+ if let Ok(dir) = env::var("JAN_LLAMA_PREBUILT_DIR") {+ let dir = PathBuf::from(dir);+ let lib = dir.join("lib");+ let inc = dir.join("include");+ assert!(+ lib.is_dir() && inc.is_dir(),+ "JAN_LLAMA_PREBUILT_DIR={} must contain lib/ and include/",+ dir.display()+ );+ (vec![lib], inc, dir.join("backends"))+ } else {+ let ggml = build_ggml(&src);+ let llama = build_llama(&src, &ggml);+ let mut dirs = ARCHIVE_DIRS+ .iter()+ .map(|d| llama.join(d))+ .collect::<Vec<_>>();+ // Visual Studio writes each target under its config; the+ // single-config generators write it where cmake was pointed.+ if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "windows" {+ dirs.extend(ARCHIVE_DIRS.iter().map(|d| llama.join(d).join(CONFIG)));+ }+ dirs.push(ggml.join("lib"));+ (dirs, llama, ggml.join("bin"))+ };++ search_dirs.push(compile_shim(&src, &generated_include));+ emit_link_flags(&search_dirs);++ // ggml resolves backend modules against the *executable's* directory+ // (ggml-backend-reg.cpp:492), which is where packaging puts them. A+ // `cargo run`/`cargo test` binary has no such neighbours, so the worker+ // falls back to this path via GGML_BACKEND_PATH.+ println!(+ "cargo:rustc-env=JAN_GGML_BACKEND_DIR={}",+ backend_dir.display()+ );+ }++ /// Stage 1: ggml as shared libraries with runtime-loaded backend modules.+ ///+ /// Separate from stage 2 because `GGML_CPU_ALL_VARIANTS` requires+ /// `GGML_BACKEND_DL`, which requires `BUILD_SHARED_LIBS`+ /// (ggml/src/CMakeLists.txt:188-190 and :485-487, both hard errors) --+ /// while we still want a *static* libllama/libcommon/server-context. Two+ /// configures is the only way to have both.+ ///+ /// Driven through a generated wrapper project rather than `-S <src>/ggml`:+ /// 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");+ fs::create_dir_all(&wrapper).expect("could not create the ggml wrapper dir");+ fs::write(+ wrapper.join("CMakeLists.txt"),+ "cmake_minimum_required(VERSION 3.14)\n\+ project(jan_ggml C CXX ASM)\n\+ add_subdirectory(${JAN_GGML_SRC} ggml)\n",+ )+ .expect("could not write the ggml wrapper project");++ // The wrapper is regenerated each run, so its own path never changes;+ // what changes is JAN_GGML_SRC inside it. A cache holding a different+ // value would silently keep building the old tree, so key off that.+ discard_stale_ggml_cache(&build, &src.join("ggml"));++ // ggml builds vulkan-shaders-gen as an ExternalProject and, when+ // cross-compiling -- which the Windows toolchain file makes true --+ // hands it a host toolchain. Left to itself it runs `find_program(NAMES+ // cl gcc clang)`, and with no developer environment there is no `cl`,+ // so it settles on the GNU-driver clang: cmake then asks for a GNU+ // depfile, whose directory Ninja Multi-Config has not created, and the+ // child dies on `opening dependency file ...obj.d`. Naming an+ // 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");+ if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "windows" {+ fs::write(+ &host_toolchain,+ "set(CMAKE_BUILD_TYPE Release)\n\+ set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n\+ set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER)\n\+ set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER)\n\+ set(CMAKE_C_COMPILER clang-cl)\n\+ set(CMAKE_CXX_COMPILER clang-cl)\n",+ )+ .expect("could not write the shader-generator host toolchain");+ }++ let mut cfg = Command::new("cmake");+ windows_generator(&mut cfg, src);+ cfg.arg("-S").arg(&wrapper).arg("-B").arg(&build);+ cfg.arg(format!(+ "-DJAN_GGML_SRC={}",+ src.join("ggml").display()+ ));+ cfg.arg(format!("-DCMAKE_INSTALL_PREFIX={}", prefix.display()));+ cfg.args([+ "-DCMAKE_BUILD_TYPE=Release",+ "-DCMAKE_POSITION_INDEPENDENT_CODE=ON",+ "-DBUILD_SHARED_LIBS=ON",+ "-DGGML_BACKEND_DL=ON",+ // Deterministic across machines: the per-microarchitecture choice+ // is made at runtime by ggml_backend_score, not at compile time.+ "-DGGML_NATIVE=OFF",+ // Upstream defaults are GGML_OPENMP=ON with GGML_OPENMP_FETCH=OFF,+ // and that pair links OpenMP into ggml-base and every CPU variant+ // while installing no runtime: the sole `install(FILES+ // ${GGML_OPENMP_RUNTIME})` rule sits inside the FETCH branch. On+ // Windows that shipped a hard import on a libomp.dll we never+ // staged, so every CPU backend failed to load on a machine without+ // LLVM -- silently, since release loading is silent=true. CI missed+ // it because the toolchain action puts LLVM's own libomp.dll on+ // PATH. FETCH=ON would fix it by downloading an LLVM installer and+ // extracting it with 7-Zip at configure time, which trades a silent+ // runtime break for a network dependency in the build; dropping+ // OpenMP costs some CPU threading throughput and nothing else.+ // Passed explicitly so a future upstream default cannot flip it+ // back unnoticed.+ "-DGGML_OPENMP=OFF",+ // Default is already ON, but passed explicitly so a value cached by+ // an earlier configure cannot silently disable caching -- the+ // difference on a CUDA rebuild is minutes versus tens of minutes.+ // ggml picks up ccache or sccache, whichever it finds.+ "-DGGML_CCACHE=ON",+ ]);+ // Every ggml library is staged into one directory, so each can find+ // its siblings from its own location. cmake otherwise strips the rpath+ // on install ("Set non-toolchain portion of runtime path to ''"),+ // leaving each backend module declaring a bare `libggml-base.so.0` that+ // nothing can resolve on its own: at runtime the worker has already+ // loaded it, but AppImage bundling reads these files cold and fails the+ // whole build on `Could not find dependency: libggml-base.so.0`.+ //+ // ELF only. macOS resolves this today through the worker's own+ // @loader_path and is left alone.+ if !matches!(+ env::var("CARGO_CFG_TARGET_OS").unwrap_or_default().as_str(),+ "macos" | "ios" | "windows"+ ) {+ cfg.arg("-DCMAKE_INSTALL_RPATH=$ORIGIN");+ }+ if host_toolchain.is_file() {+ cfg.arg(format!(+ "-DGGML_VULKAN_SHADERS_GEN_TOOLCHAIN={}",+ cmake_path(&host_toolchain)+ ));+ }+ if cpu_all_variants_supported() {+ cfg.arg("-DGGML_CPU_ALL_VARIANTS=ON");+ }+ for (feature, flag) in GPU_BACKENDS {+ if feature_enabled(feature) {+ cfg.arg(flag);+ }+ }+ // Upstream picks CMAKE_CUDA_ARCHITECTURES itself, but only when it is+ // undefined, and its default list (75/80/86/89/90, plus 50/61/70 below+ // CUDA 13 and 120a from 12.8) covers discrete desktop and datacenter+ // parts only. It has no Jetson entry: Orin is sm_87 and Xavier sm_72,+ // neither of which is in that list, and on CUDA 13 the lowest virtual+ // arch is 75, which cannot JIT down to 72. So an ARM/Jetson build needs+ // to say what it targets -- and trimming to a single known arch is also+ // how you cut a CUDA worker's size for a fixed fleet.+ if let Ok(archs) = env::var("JAN_ENGINE_CUDA_ARCHS") {+ let archs = archs.trim();+ if !archs.is_empty() {+ println!("cargo:rerun-if-env-changed=JAN_ENGINE_CUDA_ARCHS");+ cfg.arg(format!("-DCMAKE_CUDA_ARCHITECTURES={archs}"));+ }+ }+ if feature_enabled("engine-cuda") {+ // NCCL is multi-GPU collective communication for distributed+ // inference. It is found opportunistically and defaults ON+ // (ggml/CMakeLists.txt:210), which would make the shipped+ // ggml-cuda module depend on whatever libnccl the build host+ // happened to have.+ cfg.arg("-DGGML_CUDA_NCCL=OFF");+ }+ run(&mut cfg, "cmake configure (ggml)");++ let mut bld = Command::new("cmake");+ bld.arg("--build").arg(&build).args(["--config", CONFIG]);+ if let Ok(jobs) = env::var("NUM_JOBS") {+ bld.arg("-j").arg(jobs);+ }+ run(&mut bld, "cmake build (ggml)");++ let mut inst = Command::new("cmake");+ inst.arg("--install").arg(&build).args(["--config", CONFIG]);+ run(&mut inst, "cmake install (ggml)");++ prefix+ }++ /// 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");+ discard_foreign_cache(&out, src);+ fs::create_dir_all(&out).expect("could not create the cmake build dir");++ let mut cfg = Command::new("cmake");+ windows_generator(&mut cfg, src);+ cfg.arg("-S").arg(src).arg("-B").arg(&out);+ cfg.arg(format!(+ "-DCMAKE_PREFIX_PATH={}",+ ggml_prefix.display()+ ));+ cfg.args([+ "-DCMAKE_BUILD_TYPE=Release",+ "-DCMAKE_POSITION_INDEPENDENT_CODE=ON",+ // Static: libllama/libcommon/server-context link into our binary.+ // server-context is declared STATIC upstream regardless+ // (tools/server/CMakeLists.txt:5-7), but libllama and libcommon+ // follow this flag.+ "-DBUILD_SHARED_LIBS=OFF",+ // Use stage 1's ggml instead of building a second, static one+ // (CMakeLists.txt:204-208 -> find_package(ggml REQUIRED)).+ "-DLLAMA_USE_SYSTEM_GGML=ON",+ "-DLLAMA_BUILD_TESTS=OFF",+ "-DLLAMA_BUILD_EXAMPLES=OFF",+ "-DLLAMA_BUILD_APP=OFF",+ "-DLLAMA_BUILD_SERVER=ON",+ "-DLLAMA_BUILD_TOOLS=ON",+ "-DLLAMA_BUILD_COMMON=ON",+ // We drive server_routes directly, so the bundled web UI is dead+ // weight -- and LLAMA_USE_PREBUILT_UI would fetch from HuggingFace+ // during configure.+ "-DLLAMA_BUILD_UI=OFF",+ "-DLLAMA_USE_PREBUILT_UI=OFF",+ // Router mode is the only consumer of subprocess spawning, and we+ // replace router mode with an in-process registry.+ "-DLLAMA_SUBPROCESS=OFF",+ // mtmd's video path fork/execs ffmpeg.+ "-DMTMD_VIDEO=OFF",+ // cpp-httplib's TLS, which only serves llama.cpp's own HTTPS model+ // downloads -- Jan fetches models in Rust and the worker listens on+ // loopback. On by default, and it puts OpenSSL symbols in an+ // archive nothing links an OpenSSL into: on Linux they resolve by+ // accident against the one reqwest already pulls in, on macOS,+ // where reqwest uses Security.framework, the link fails outright.+ "-DLLAMA_OPENSSL=OFF",+ "-DGGML_NATIVE=OFF",+ // Stage 1 owns the ggml libraries, but this tree still evaluates+ // ggml's option set, so the value is pinned on both sides rather+ // than left to depend on which branch runs here.+ "-DGGML_OPENMP=OFF",+ "-DLLAMA_BUILD_IS_DEV=OFF",+ ]);+ cfg.arg(format!("-DLLAMA_BUILD_NUMBER={LLAMA_CPP_BUILD_NUMBER}"));+ cfg.arg(format!("-DLLAMA_BUILD_COMMIT={LLAMA_CPP_COMMIT}"));+ run(&mut cfg, "cmake configure (llama)");++ let mut bld = Command::new("cmake");+ bld.arg("--build")+ .arg(&out)+ .args(["--config", CONFIG])+ .arg("--target")+ .arg("server-context");+ if let Ok(jobs) = env::var("NUM_JOBS") {+ bld.arg("-j").arg(jobs);+ }+ run(&mut bld, "cmake build (llama)");++ out+ }++ /// Removes a cmake build tree whose cache was generated from a different+ /// source directory.+ ///+ /// The build dir is keyed only by OUT_DIR, so switching between the+ /// vendored clone and a `JAN_LLAMA_CPP_DIR` checkout leaves a cache+ /// pointing at the old tree, and cmake then hard-fails with "does not match+ /// the source used to generate cache". Wiping is safe: everything in there+ /// is derived.+ /// A build tree carries the generator it was configured with, and cmake+ /// refuses to reuse it under another one. Switching to Ninja on Windows+ /// would otherwise hard-fail on any tree an earlier Visual Studio configure+ /// left behind, which is every local Windows checkout built before that+ /// change.+ fn discard_other_generator(build_dir: &Path) {+ if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() != "windows" {+ return;+ }+ let Ok(text) = fs::read_to_string(build_dir.join("CMakeCache.txt")) else {+ return;+ };+ let Some(cached) = text+ .lines()+ .find_map(|l| l.strip_prefix("CMAKE_GENERATOR:INTERNAL="))+ .map(str::trim)+ else {+ return;+ };+ let want = if on_path("ninja") { WINDOWS_GENERATOR } else { return };+ if cached != want {+ println!(+ "cargo:warning=cmake generator changed ({cached} -> {want}); discarding the cache"+ );+ let _ = fs::remove_dir_all(build_dir);+ }+ }++ fn discard_foreign_cache(build_dir: &Path, src: &Path) {+ discard_other_generator(build_dir);+ let cache = build_dir.join("CMakeCache.txt");+ let Ok(text) = fs::read_to_string(&cache) else {+ return;+ };+ let home = text+ .lines()+ .find_map(|l| l.strip_prefix("CMAKE_HOME_DIRECTORY:INTERNAL="))+ .map(str::trim);+ let Some(home) = home else { return };++ // Compare canonically: OUT_DIR paths and the source can both contain+ // symlinks, and a spurious mismatch would rebuild llama.cpp every time.+ let same = fs::canonicalize(home)+ .ok()+ .zip(fs::canonicalize(src).ok())+ .map(|(a, b)| a == b)+ .unwrap_or(false);+ if !same {+ println!(+ "cargo:warning=llama.cpp source changed ({home} -> {}); discarding the cmake cache",+ src.display()+ );+ let _ = fs::remove_dir_all(build_dir);+ }+ }++ /// Same idea as `discard_foreign_cache`, but stage 1's cache home is the+ /// generated wrapper (whose path is stable), so the value that identifies+ /// the source is the cached `JAN_GGML_SRC`.+ fn discard_stale_ggml_cache(build_dir: &Path, ggml_src: &Path) {+ discard_other_generator(build_dir);+ let cache = build_dir.join("CMakeCache.txt");+ let Ok(text) = fs::read_to_string(&cache) else {+ return;+ };+ let cached = text+ .lines()+ .find_map(|l| l.split_once("JAN_GGML_SRC:").and_then(|(_, r)| r.split_once('=')))+ .map(|(_, v)| v.trim().to_string());+ let Some(cached) = cached else { return };++ let same = fs::canonicalize(&cached)+ .ok()+ .zip(fs::canonicalize(ggml_src).ok())+ .map(|(a, b)| a == b)+ .unwrap_or(false);+ if !same {+ println!(+ "cargo:warning=ggml source changed ({cached} -> {}); discarding the cmake cache",+ ggml_src.display()+ );+ let _ = fs::remove_dir_all(build_dir);+ }+ }++ fn feature_enabled(feature: &str) -> bool {+ env::var_os(format!(+ "CARGO_FEATURE_{}",+ feature.to_uppercase().replace('-', "_")+ ))+ .is_some()+ }++ /// `GGML_CPU_ALL_VARIANTS` hard-errors on architectures it has no variant+ /// table for (ggml/src/CMakeLists.txt:581), so it is opt-in per arch rather+ /// than unconditional.+ fn cpu_all_variants_supported() -> bool {+ matches!(+ env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default().as_str(),+ "x86_64" | "aarch64" | "riscv64"+ )+ }++ /// `JAN_LLAMA_CPP_DIR` overrides the vendored clone, which is what a+ /// llama.cpp contributor working against a local tree wants.+ fn source_dir() -> PathBuf {+ if let Ok(dir) = env::var("JAN_LLAMA_CPP_DIR") {+ return PathBuf::from(dir);+ }+ let vendored = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("vendor/llama.cpp");+ assert!(+ vendored.join("CMakeLists.txt").is_file(),+ "vendor/llama.cpp is empty -- run `make engine-source` to \+ shallow-clone {LLAMA_CPP_TAG}, or point JAN_LLAMA_CPP_DIR at an \+ existing checkout. (Looked in {})",+ vendored.display()+ );+ vendored+ }++ /// The shim is compiled with `cc` rather than added to llama.cpp's cmake+ /// tree so the vendored source stays untouched and bisectable.+ /// `generated_include` is where llama.cpp's generated headers live: the+ /// cmake build dir normally, or the prebuilt bundle's include/.+ fn compile_shim(src: &Path, generated_include: &Path) -> PathBuf {+ let mut cc = cc::Build::new();+ cc.cpp(true)+ .std("c++17")+ .file("shim/jan_llama_shim.cpp")+ .include("shim")+ .include(src.join("include"))+ .include(src.join("ggml/include"))+ .include(src.join("common"))+ .include(src.join("tools/server"))+ .include(src.join("tools/mtmd"))+ .include(src.join("vendor"))+ .include(src.join("vendor/nlohmann"))+ .include(generated_include)+ .include(generated_include.join("common"));+ cc.compile("jan_llama_shim");+ PathBuf::from(env::var("OUT_DIR").unwrap())+ }++ fn emit_link_flags(dirs: &[PathBuf]) {+ for d in dirs {+ println!("cargo:rustc-link-search=native={}", d.display());+ }+ let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ let gnu_ld = !matches!(target_os.as_str(), "macos" | "ios" | "windows");++ if gnu_ld {+ // One group: the archives reference each other cyclically.+ println!("cargo:rustc-link-arg=-Wl,--start-group");+ for a in ARCHIVES {+ println!("cargo:rustc-link-arg=-l{a}");+ }+ println!("cargo:rustc-link-arg=-Wl,--end-group");+ } else {+ // ld64 and link.exe re-scan archives until no undefined symbol is+ // left, so they resolve the cycle themselves and reject the group+ // flags outright.+ for a in ARCHIVES {+ println!("cargo:rustc-link-lib=static={a}");+ }+ }++ // ggml is shared now, so it links normally rather than into the group.+ for l in SHARED_LIBS {+ println!("cargo:rustc-link-lib=dylib={l}");+ }++ match target_os.as_str() {+ "macos" | "ios" => {+ println!("cargo:rustc-link-lib=dylib=c++");+ for fw in ["Accelerate", "Foundation", "Metal", "MetalKit"] {+ println!("cargo:rustc-link-lib=framework={fw}");+ }+ // Shipped beside the binary; @loader_path keeps the bundle+ // relocatable, which an absolute build path would not.+ println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path");+ }+ // Windows has no rpath: the loader searches the .exe's own+ // directory first, which is where packaging puts the DLLs.+ "windows" => {}+ _ => {+ for l in ["stdc++", "m", "pthread", "dl", "gomp"] {+ println!("cargo:rustc-link-lib=dylib={l}");+ }+ println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN");+ }+ }++ // The build-tree ggml, so `cargo test` and `cargo run` link and run+ // without a copy step. Packaging overrides this by placing the real+ // libraries next to the executable, which $ORIGIN/@loader_path finds+ // first. Windows has no rpath at all.+ if target_os != "windows" {+ for d in dirs {+ println!("cargo:rustc-link-arg=-Wl,-rpath,{}", d.display());+ }+ }+ }++ /// Runs a build step, streaming its output to `JAN_ENGINE_BUILD_LOG` when set.+ ///+ /// Cargo captures a build script's stdout and stderr and only surfaces them+ /// if the script fails, so a cmake/nvcc run that takes fifteen minutes+ /// prints nothing at all -- the build looks hung. Writing to a path the+ /// caller chose lets the Makefile `tail -F` it for live progress.+ ///+ /// On failure the tail is echoed through `println!` so the reason still+ /// reaches cargo's own error output, which is the one place a developer is+ /// guaranteed to look.+ fn run(cmd: &mut Command, what: &str) {+ let log_path = env::var_os("JAN_ENGINE_BUILD_LOG").map(PathBuf::from);++ // The directory is the caller's to name and need not exist yet -- the+ // Makefile points this at src-tauri/target, which the plugin's own+ // cargo build never creates. A log that cannot be opened costs progress+ // reporting, not the build, so fall back to inheriting stdio.+ let log = log_path.as_ref().and_then(|path| {+ if let Some(dir) = path.parent() {+ let _ = fs::create_dir_all(dir);+ }+ fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)+ .map_err(|e| {+ println!(+ "cargo:warning=could not open {} for the build log: {e}",+ path.display()+ );+ })+ .ok()+ });++ let status = match log {+ Some(file) => {+ let err = file+ .try_clone()+ .expect("could not duplicate the build log handle");+ cmd.stdout(file).stderr(err).status()+ }+ None => cmd.status(),+ }+ .unwrap_or_else(|e| panic!("{what} could not start ({e}); is cmake installed?"));++ if status.success() {+ return;+ }+ if let Some(path) = &log_path {+ let text = fs::read_to_string(path).unwrap_or_default();+ // MSBuild interleaves the output of parallel targets, so the cause+ // is usually nowhere near the end the way it is under make.+ let errors = last_matching(&text, "error", 40);+ if !errors.is_empty() {+ eprintln!("--- error lines from {} ---", path.display());+ for line in errors {+ eprintln!("{line}");+ }+ }+ eprintln!("--- tail of {} ---", path.display());+ for line in tail(&text, 60) {+ eprintln!("{line}");+ }+ }+ panic!("{what} failed with {status}");+ }++ /// The last `n` lines, for a failure message.+ fn tail(text: &str, n: usize) -> Vec<String> {+ let lines: Vec<&str> = text.lines().collect();+ lines[lines.len().saturating_sub(n)..]+ .iter()+ .map(|s| s.to_string())+ .collect()+ }++ /// The last `n` lines containing `needle`, case-insensitively. A cmake log+ /// is small next to what it took to produce, so this reads all of it.+ fn last_matching(text: &str, needle: &str, n: usize) -> Vec<String> {+ let mut hits: Vec<String> = text+ .lines()+ .filter(|l| l.to_ascii_lowercase().contains(needle))+ .map(|s| s.to_string())+ .collect();+ let drop = hits.len().saturating_sub(n);+ hits.drain(..drop);+ hits+ }}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.tsindex e5384f21f..5b93cc0d3 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts@@ -1,18 +1,11 @@import { invoke } from '@tauri-apps/api/core'import {SessionInfo,- DeviceInfo,+ DeviceList,UnloadResult,+ ReloadReport,+ EngineInfo,GgufMetadata,- LlamacppConfig,- BackendVersion,- BackendFeatures,- SupportedFeatures,- GpuInfo,- BestBackendResult,- UpdateCheckResult,- SettingUpdateResult,- LoadProbeResult,} from './types'// Helpers@@ -25,102 +18,18 @@ function asNumber(v: any, defaultValue = 0): number {const I32_MAX = 2147483647const I32_MIN = -2147483648-function asI32(v: any, defaultValue = 0): number {+/**+ * Coerces to a value llama.cpp's int32 args accept, clamping rather than+ * overflowing. Exported because the extension needs the same clamp for+ * `timeout`, and a second hand-rolled one would drift.+ */+export function asI32(v: any, defaultValue = 0): number {const n = Math.trunc(asNumber(v, defaultValue))if (n > I32_MAX) return I32_MAXif (n < I32_MIN) return I32_MINreturn n}-function asBool(v: any, defaultValue = false): boolean {- if (v === '' || v === null || v === undefined) return defaultValue- return v === true || v === 'true' || v === 1 || v === '1'-}--function asString(v: any, defaultValue = ''): string {- if (v === '' || v === null || v === undefined) return defaultValue- return String(v)-}--export function normalizeLlamacppConfig(config: any): LlamacppConfig {- const llamacpp_version = asString(config.llamacpp_version)- const llamacpp_backend = asString(config.llamacpp_backend)- const composedVersionBackend =- llamacpp_version && llamacpp_backend- ? `${llamacpp_version}/${llamacpp_backend}`- : asString(config.version_backend)- return {- llamacpp_version,- llamacpp_backend,- version_backend: composedVersionBackend,- auto_update_engine: asBool(config.auto_update_engine),- check_for_updates:- config.check_for_updates === undefined ||- config.check_for_updates === null- ? true- : asBool(config.check_for_updates),- verify_backend_deps:- config.verify_backend_deps === undefined || config.verify_backend_deps === null- ? true- : asBool(config.verify_backend_deps),- auto_unload: asBool(config.auto_unload),- models_max:- typeof config.models_max === 'number'- ? config.models_max- : asI32(config.models_max, 1),- timeout: asI32(config.timeout, 600),-- llamacpp_env: asString(config.llamacpp_env),- fit: asBool(config.fit),- fit_target: asString(config.fit_target),- fit_ctx: asString(config.fit_ctx),- chat_template: asString(config.chat_template),-- n_gpu_layers: asI32(config.n_gpu_layers),- offload_mmproj: asBool(config.offload_mmproj),- cpu_moe: asBool(config.cpu_moe),- n_cpu_moe: asI32(config.n_cpu_moe),-- override_tensor_buffer_t: asString(config.override_tensor_buffer_t),-- ctx_size: asI32(config.ctx_size),- threads: asI32(config.threads),- threads_batch: asI32(config.threads_batch),- n_predict: asI32(config.n_predict),- batch_size: asI32(config.batch_size),- ubatch_size: asI32(config.ubatch_size),-- device: asString(config.device),- split_mode: asString(config.split_mode),- main_gpu: asI32(config.main_gpu),-- flash_attn: asString(config.flash_attn),- cont_batching: asBool(config.cont_batching),-- no_mmap: asBool(config.no_mmap),- mlock: asBool(config.mlock),- no_kv_offload: asBool(config.no_kv_offload),-- cache_type_k: asString(config.cache_type_k),- cache_type_v: asString(config.cache_type_v),-- rope_scaling: asString(config.rope_scaling),- rope_scale: asNumber(config.rope_scale, 1.0),- rope_freq_base: asNumber(config.rope_freq_base, 0.0),- rope_freq_scale: asNumber(config.rope_freq_scale, 1.0),-- ctx_shift: asBool(config.ctx_shift),- parallel: asI32(config.parallel, 1),-- reasoning: asString(config.reasoning, 'auto'),- cache_ram: asI32(config.cache_ram, -1),- cache_reuse: asI32(config.cache_reuse, 0),- swa_full: asBool(config.swa_full),- keep: asI32(config.keep, 0),- kv_unified: asString(config.kv_unified, 'auto'),- }-}-export async function loadLlamaModel(modelId: string,isEmbedding: boolean = false@@ -147,30 +56,11 @@ export async function ensureSessionReady(export async function getDevices(backendPath: string,- libraryPath?: string-): Promise<DeviceInfo[]> {+ envs: Record<string, string> = {}+): Promise<DeviceList[]> {return await invoke('plugin:llamacpp|get_devices', {backendPath,- libraryPath,- })-}--/**- * Loads the backend's GPU library the way llama-server would, to recover the- * reason it cannot. A release build of ggml discards that error and silently- * falls back to CPU, so this is the only way to name the missing dependency.- */-export async function probeBackendLoad(- backend: string,- version: string,- janDataFolder: string,- isWindows: boolean-): Promise<LoadProbeResult> {- return await invoke('plugin:llamacpp|probe_backend_load', {- backend,- version,- janDataFolder,- isWindows,+ envs,})}@@ -194,247 +84,141 @@ export async function getLoadedModels(): Promise<string[]> {return await invoke('plugin:llamacpp|get_loaded_models')}-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.+ * Starts the supervised in-process engine worker. Replaces `startRouter`: no+ * downloaded backend binary, and the port is OS-assigned then reported back+ * rather than guessed.*/-export async function reloadRouterModels(): Promise<void> {- return await invoke('plugin:llamacpp|reload_router_models')-}--export async function routerHealth(- port?: number,- apiKey?: string-): Promise<boolean> {- return await invoke('plugin:llamacpp|router_health', { port, apiKey })-}--export async function adoptRouter(- backendExe: string,+/**+ * `slotCacheMib` caps the directory holding each thread's KV cache, which lets+ * a conversation resume without re-reading its prompt. 0 turns that off; a+ * single saved conversation runs to hundreds of MiB, so it is a budget rather+ * than a boolean.+ */+export async function startEngine(presetPath: string,modelsMax: number,- apiSecret: string-): Promise<{ port: number; api_key: string; pid: number } | null> {- return await invoke('plugin:llamacpp|adopt_router', {- backendExe,+ slotCacheMib: number = 0,+ envs: Record<string, string> = {}+): Promise<EngineInfo> {+ return await invoke('plugin:llamacpp|start_engine', {presetPath,modelsMax,- apiSecret,- })-}--// GGUF commands-export async function readGgufMetadata(path: string): Promise<GgufMetadata> {- return await invoke('plugin:llamacpp|read_gguf_metadata', { path })-}--export async function estimateKVCacheSize(- meta: Record<string, string>,- ctxSize?: number-): Promise<{ size: number; per_token_size: number }> {- return await invoke('plugin:llamacpp|estimate_kv_cache_size', {- meta,- ctxSize,+ slotCacheMib: asI32(slotCacheMib),+ envs,})}-export async function getModelSize(path: string): Promise<number> {- return await invoke('plugin:llamacpp|get_model_size', { path })-}--export async function isModelSupported(- path: string,- ctxSize?: number-): Promise<'RED' | 'YELLOW' | 'GREEN'> {- return await invoke('plugin:llamacpp|is_model_supported', {- path,- ctxSize,- })+export async function stopEngine(): Promise<void> {+ return await invoke('plugin:llamacpp|stop_engine')}-// Cleanup commands-export async function cleanupLlamaProcesses(): Promise<void> {- return await invoke('plugin:llamacpp|cleanup_llama_processes')+/** Null when no worker is running, including after one died. */+export async function getEngineInfo(): Promise<EngineInfo | null> {+ return await invoke('plugin:llamacpp|get_engine_info')}-// backend functions--/*- * Helper function to map an old backend type string to its new, common equivalent.- * This is used for migrating stored user preferences.+/**+ * The devices the shipped engine can offload to.+ *+ * Replaces the `getDevices(backendPath, envs)` shell-out to a downloaded+ * `llama-server --list-devices`: there is no downloaded binary any more, and+ * the engine is statically linked into the worker.*/-export async function mapOldBackendToNew(oldBackend: string): Promise<string> {- return await invoke<string>('plugin:llamacpp|map_old_backend_to_new', { oldBackend })-}--export async function getLocalInstalledBackendsInternal(- backendsDir: string-): Promise<{ version: string; backend: string }[]> {- return await invoke<{ version: string; backend: string }[]>(- 'plugin:llamacpp|get_local_installed_backends',- {- backendsDir,- }- )-}--export function normalizeFeatures(features: any): BackendFeatures {- return {- cuda11: features.cuda11 || false,- cuda12: features.cuda12 || false,- cuda13: features.cuda13 || false,- vulkan: features.vulkan || false,- hip: features.hip || false,- }-}--export async function determineSupportedBackends(- osType: string,- arch: string,- features: BackendFeatures-): Promise<string[]> {- return invoke<string[]>('plugin:llamacpp|determine_supported_backends', {- osType,- arch,- features,- })-}--export async function listSupportedBackendsFromRust(- remoteBackendVersions: BackendVersion[],- localBackendVersions: BackendVersion[]-): Promise<BackendVersion[]> {- return invoke<BackendVersion[]>('plugin:llamacpp|list_supported_backends', {- remoteBackendVersions,- localBackendVersions,- })+export async function engineDevices(+ envs: Record<string, string> = {}+): Promise<DeviceList[]> {+ return await invoke('plugin:llamacpp|engine_devices', { envs })}-export async function getSupportedFeaturesFromRust(- osType: string,- cpuExtensions: string[],- gpus: GpuInfo[]-): Promise<SupportedFeatures> {- return invoke<SupportedFeatures>('plugin:llamacpp|get_supported_features', {- osType,- cpuExtensions,- gpus,- })+/**+ * Applies a regenerated preset to the running worker without restarting it.+ *+ * `modelsMax` is optional; omitting it keeps the worker's current value. Unlike+ * the router, the worker can be resized, so the embedding slot bonus changing+ * no longer forces a cold restart.+ */+/**+ * Kills the worker without waiting for it to unwind. Backs the force-quit the+ * busy-on-exit dialog offers; use `stopEngine` everywhere else.+ */+export async function forceStopEngine(): Promise<void> {+ return await invoke('plugin:llamacpp|force_stop_engine')}-export async function isCudaInstalledFromRust(- backendDir: string,- version: string,- osType: string,- janDataFolderPath: string-): Promise<boolean> {- return invoke<boolean>('plugin:llamacpp|is_cuda_installed', {- backendDir,- version,- osType,- janDataFolderPath,- })+/**+ * True when nothing is generating, so the model can be reconfigured or+ * unloaded. Omit `modelId` to ask about the whole worker.+ */+export async function engineSlotsIdle(modelId?: string): Promise<boolean> {+ return await invoke('plugin:llamacpp|engine_slots_idle', { modelId })}-export async function findLatestVersionForBackend(- versionBackends: BackendVersion[],- backendType: string-): Promise<string | null> {- return invoke('plugin:llamacpp|find_latest_version_for_backend', {- versionBackends,- backendType,+/**+ * Drops saved KV cache: a thread's (under every model it was used with), or a+ * whole model's. Returns how many were dropped.+ *+ * `cacheDir` is the preset's `slot-save-path`. With no worker running the erase+ * is done on disk instead, so deleting a thread reclaims its cache whether or+ * not a model happens to be loaded; without the directory there is nowhere to+ * look and the answer is 0.+ */+export async function eraseThreadSlotState(args: {+ threadId?: string+ modelId?: string+ cacheDir?: string+}): Promise<number> {+ return await invoke('plugin:llamacpp|erase_thread_slot_state', {+ threadId: args.threadId,+ modelId: args.modelId,+ cacheDir: args.cacheDir,})}-export async function prioritizeBackends(- versionBackends: BackendVersion[],- hasEnoughGpuMemory: boolean-): Promise<BestBackendResult> {- return invoke('plugin:llamacpp|prioritize_backends', {- versionBackends,- hasEnoughGpuMemory,+export async function reloadEngineModels(+ presetPath: string,+ modelsMax?: number,+ slotCacheMib?: number+): Promise<ReloadReport> {+ return await invoke('plugin:llamacpp|reload_engine_models', {+ presetPath,+ modelsMax,+ slotCacheMib:+ slotCacheMib === undefined ? undefined : asI32(slotCacheMib),})}-export async function parseBackendVersion(- versionString: string-): Promise<number> {- return invoke('plugin:llamacpp|parse_backend_version', { versionString })-}--export async function checkBackendForUpdates(- currentBackendString: string,- versionBackends: BackendVersion[]-): Promise<UpdateCheckResult> {- return invoke('plugin:llamacpp|check_backend_for_updates', {- currentBackendString,- versionBackends,- })+// GGUF commands+export async function readGgufMetadata(path: string): Promise<GgufMetadata> {+ return await invoke('plugin:llamacpp|read_gguf_metadata', { path })}-export async function removeOldBackendVersions(- backendsDir: string,- latestVersion: string,- backendType: string,- keepPrevious: number+/**+ * Which of `names` exist as tensors in a gguf. Exact names, mirroring+ * llama.cpp's `gguf_find_tensor`: the facts worth knowing are yes/no ones+ * (`markov_w1.weight` marks a DSpark draft), and listing every tensor of a+ * large model to answer one would be far more data than the answer.+ */+export async function findGgufTensors(+ path: string,+ names: string[]): Promise<string[]> {- return invoke('plugin:llamacpp|remove_old_backend_versions', {- backendsDir,- latestVersion,- backendType,- keepPrevious,- })-}--export async function fetchBackendChecksums(- version: string,- source: 'github' | 'cdn',- proxy?: object | null-): Promise<Record<string, string>> {- return invoke('plugin:llamacpp|fetch_backend_checksums', {- version,- source,- proxy,- })+ return await invoke('plugin:llamacpp|find_gguf_tensors', { path, names })}-export async function verifyFileSha512(+export async function isModelSupported(path: string,- expected: string-): Promise<boolean> {- return invoke('plugin:llamacpp|verify_file_sha512', { path, expected })-}--export async function validateBackendString(- backendString: string-): Promise<[string, string]> {- return invoke('plugin:llamacpp|validate_backend_string', { backendString })-}--export async function shouldMigrateBackend(- storedBackendType: string,- versionBackends: BackendVersion[]-): Promise<string | null> {- return invoke('plugin:llamacpp|should_migrate_backend', {- storedBackendType,- versionBackends,+ ctxSize?: number+): Promise<'RED' | 'YELLOW' | 'GREEN'> {+ return await invoke('plugin:llamacpp|is_model_supported', {+ path,+ ctxSize,})}-export async function handleSettingUpdate(- key: string,- value: string,- currentStoredBackend?: string-): Promise<SettingUpdateResult> {- return invoke('plugin:llamacpp|handle_setting_update', {- key,- value,- currentStoredBackend,- })+// Cleanup commands+export async function cleanupLlamaProcesses(): Promise<void> {+ return await invoke('plugin:llamacpp|cleanup_llama_processes')}export * from './types'diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex 2de81a72e..423dd71f6 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -12,10 +12,26 @@ export interface UnloadResult {error?: string}-export interface DeviceInfo {- id: string- name: string- memory: number+/** Mirrors `engine::commands::EngineInfo`. */+export interface EngineInfo {+ port: number+ api_key: string+ pid: number+ /** Model ids the worker registered from the preset. */+ models: string[]+}++/**+ * Mirrors `engine::commands::ReloadReport`. Every model in the preset appears+ * in exactly one list, so an empty `changed`/`removed` proves the reload left+ * the models the user was using alone.+ */+export interface ReloadReport {+ added: string[]+ changed: string[]+ removed: string[]+ kept: string[]+ models_max: number}export interface ModelProps {@@ -31,65 +47,56 @@ export interface GgufMetadata {metadata: Record<string, string>}-// llama.cpp settings+/**+ * The engine-level (provider-wide) settings, mirroring+ * `extensions/llamacpp-extension/settings.json` exactly.+ *+ * Kept in lockstep on purpose: `this.config` is built only from those keys, so a+ * field declared here with no settings.json entry is permanently `undefined` --+ * which is how two dead `[*]` preset branches (`ctx_size`, `n_gpu_layers`) came+ * to typecheck. Per-model settings are a different type (`ModelConfig`).+ */export type LlamacppConfig = {- llamacpp_version: string- llamacpp_backend: string- /** Composed from llamacpp_version + llamacpp_backend as `${version}/${backend}`. Not user-settable. */- version_backend: string- auto_update_engine: boolean- check_for_updates: boolean- verify_backend_deps: boolean- auto_unload: boolean+ llamacpp_env: stringmodels_max: string | numbertimeout: number- llamacpp_env: stringfit: booleanfit_target: stringfit_ctx: string- chat_template: string- n_gpu_layers: number- offload_mmproj: boolean- cpu_moe: boolean- n_cpu_moe: number- override_tensor_buffer_t: string- ctx_size: numberthreads: numberthreads_batch: number+ ctx_shift: booleann_predict: numberbatch_size: numberubatch_size: number+ n_cpu_moe: number+ no_kv_offload: booleandevice: stringsplit_mode: stringmain_gpu: number+ tensor_split: string+ no_op_offload: booleanflash_attn: string+ parallel: numbercont_batching: booleanno_mmap: booleanmlock: boolean- no_kv_offload: booleancache_type_k: stringcache_type_v: stringrope_scaling: string- rope_scale: numberrope_freq_base: numberrope_freq_scale: number- ctx_shift: boolean- parallel: number- reasoning: stringcache_ram: number+ /** Keep each thread's prompt cache on disk across sessions. */+ persist_thread_cache: boolean+ /** Disk budget for the above, in MiB. */+ thread_cache_size: numbercache_reuse: number+ ctx_checkpoints: number+ checkpoint_min_step: numberswa_full: boolean- keep: numberkv_unified: string-}--export type ModelPlan = {- gpuLayers: number- maxContextLength: number- noOffloadKVCache: boolean- offloadMmproj?: boolean- batchSize: number- mode: 'GPU' | 'Hybrid' | 'CPU' | 'Unsupported'+ keep: number}export interface DownloadItem {@@ -146,81 +153,3 @@ export interface DeviceList {free: number}-export interface SystemMemory {- totalVRAM: number- totalRAM: number- totalMemory: number-}--// backend types-export type BackendVersion = { version: string; backend: string }--export type BackendFeatures = {- cuda11: boolean- cuda12: boolean- cuda13: boolean- vulkan: boolean- hip: boolean-}--export type SupportedFeatures = {- avx: boolean- avx2: boolean- avx512: boolean- cuda11: boolean- cuda12: boolean- cuda13: boolean- vulkan: boolean-}-export type NvidiaInfo = {- compute_capability: string-}--export type VulkanInfo = {- api_version: string-}--export type GpuInfo = {- driver_version: string- nvidia_info?: NvidiaInfo | null- vulkan_info?: VulkanInfo | null-}--export interface BestBackendResult {- backend_string: string- version: string- backend_type: string-}--export interface UpdateCheckResult {- update_needed: boolean- new_version: string- target_backend?: string-}--export interface SettingUpdateResult {- backend_type_updated: boolean- effective_backend_type?: string- needs_backend_installation: boolean- version?: string- backend?: string-}--/** One ggml GPU library that failed to load, with the cause. */-export interface LoadProbeFailure {- library: string- /** Raw loader message. */- error: string- /** Names parsed out of `error`, for install advice. */- missing_libraries: string[]-}--export interface LoadProbeResult {- loaded: string[]- failures: LoadProbeFailure[]- /**- * The probe could not run, so an empty `failures` list must not be read as a- * healthy backend.- */- inconclusive: boolean-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/package.json b/src-tauri/plugins/tauri-plugin-llamacpp/package.jsonindex e4c3f9fe4..fa067be5a 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.8.3",+ "version": "0.2.0","private": true,"description": "","type": "module",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.tomldeleted file mode 100644index 3ba12c524..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/check_backend_for_updates.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-check-backend-for-updates"-description = "Enables the check_backend_for_updates command without any pre-configured scope."-commands.allow = ["check_backend_for_updates"]--[[permission]]-identifier = "deny-check-backend-for-updates"-description = "Denies the check_backend_for_updates command without any pre-configured scope."-commands.deny = ["check_backend_for_updates"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.tomldeleted file mode 100644index b01878f61..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/determine_supported_backends.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-determine-supported-backends"-description = "Enables the determine_supported_backends command without any pre-configured scope."-commands.allow = ["determine_supported_backends"]--[[permission]]-identifier = "deny-determine-supported-backends"-description = "Denies the determine_supported_backends command without any pre-configured scope."-commands.deny = ["determine_supported_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/estimate_kv_cache_size.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/estimate_kv_cache_size.tomldeleted file mode 100644index 39d419214..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/estimate_kv_cache_size.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-estimate-kv-cache-size"-description = "Enables the estimate_kv_cache_size command without any pre-configured scope."-commands.allow = ["estimate_kv_cache_size"]--[[permission]]-identifier = "deny-estimate-kv-cache-size"-description = "Denies the estimate_kv_cache_size command without any pre-configured scope."-commands.deny = ["estimate_kv_cache_size"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.tomldeleted file mode 100644index 22d0afbd9..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/find_latest_version_for_backend.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-find-latest-version-for-backend"-description = "Enables the find_latest_version_for_backend command without any pre-configured scope."-commands.allow = ["find_latest_version_for_backend"]--[[permission]]-identifier = "deny-find-latest-version-for-backend"-description = "Denies the find_latest_version_for_backend command without any pre-configured scope."-commands.deny = ["find_latest_version_for_backend"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_all_sessions.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_all_sessions.tomldeleted file mode 100644index 1d9de5517..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_all_sessions.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-all-sessions"-description = "Enables the get_all_sessions command without any pre-configured scope."-commands.allow = ["get_all_sessions"]--[[permission]]-identifier = "deny-get-all-sessions"-description = "Denies the get_all_sessions command without any pre-configured scope."-commands.deny = ["get_all_sessions"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_devices.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_devices.tomldeleted file mode 100644index c5aa86e9f..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_devices.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-devices"-description = "Enables the get_devices command without any pre-configured scope."-commands.allow = ["get_devices"]--[[permission]]-identifier = "deny-get-devices"-description = "Denies the get_devices command without any pre-configured scope."-commands.deny = ["get_devices"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.tomldeleted file mode 100644index ac1e5c94e..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_local_installed_backends.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-local-installed-backends"-description = "Enables the get_local_installed_backends command without any pre-configured scope."-commands.allow = ["get_local_installed_backends"]--[[permission]]-identifier = "deny-get-local-installed-backends"-description = "Denies the get_local_installed_backends command without any pre-configured scope."-commands.deny = ["get_local_installed_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_model_size.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_model_size.tomldeleted file mode 100644index 7ba81c38e..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_model_size.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-model-size"-description = "Enables the get_model_size command without any pre-configured scope."-commands.allow = ["get_model_size"]--[[permission]]-identifier = "deny-get-model-size"-description = "Denies the get_model_size command without any pre-configured scope."-commands.deny = ["get_model_size"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_random_port.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_random_port.tomldeleted file mode 100644index ba0ba01b8..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_random_port.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-random-port"-description = "Enables the get_random_port command without any pre-configured scope."-commands.allow = ["get_random_port"]--[[permission]]-identifier = "deny-get-random-port"-description = "Denies the get_random_port command without any pre-configured scope."-commands.deny = ["get_random_port"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_session_by_model.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_session_by_model.tomldeleted file mode 100644index bed88faa9..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_session_by_model.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-session-by-model"-description = "Enables the get_session_by_model command without any pre-configured scope."-commands.allow = ["get_session_by_model"]--[[permission]]-identifier = "deny-get-session-by-model"-description = "Denies the get_session_by_model command without any pre-configured scope."-commands.deny = ["get_session_by_model"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.tomldeleted file mode 100644index 3d3e8dbd5..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/get_supported_features.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-supported-features"-description = "Enables the get_supported_features command without any pre-configured scope."-commands.allow = ["get_supported_features"]--[[permission]]-identifier = "deny-get-supported-features"-description = "Denies the get_supported_features command without any pre-configured scope."-commands.deny = ["get_supported_features"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.tomldeleted file mode 100644index 13ba58e8f..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/handle_setting_update.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-handle-setting-update"-description = "Enables the handle_setting_update command without any pre-configured scope."-commands.allow = ["handle_setting_update"]--[[permission]]-identifier = "deny-handle-setting-update"-description = "Denies the handle_setting_update command without any pre-configured scope."-commands.deny = ["handle_setting_update"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.tomldeleted file mode 100644index f5016fc33..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_cuda_installed.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-is-cuda-installed"-description = "Enables the is_cuda_installed command without any pre-configured scope."-commands.allow = ["is_cuda_installed"]--[[permission]]-identifier = "deny-is-cuda-installed"-description = "Denies the is_cuda_installed command without any pre-configured scope."-commands.deny = ["is_cuda_installed"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_process_running.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_process_running.tomldeleted file mode 100644index 71fcc5812..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/is_process_running.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-is-process-running"-description = "Enables the is_process_running command without any pre-configured scope."-commands.allow = ["is_process_running"]--[[permission]]-identifier = "deny-is-process-running"-description = "Denies the is_process_running command without any pre-configured scope."-commands.deny = ["is_process_running"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.tomldeleted file mode 100644index efafa5d74..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/list_supported_backends.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-list-supported-backends"-description = "Enables the list_supported_backends command without any pre-configured scope."-commands.allow = ["list_supported_backends"]--[[permission]]-identifier = "deny-list-supported-backends"-description = "Denies the list_supported_backends command without any pre-configured scope."-commands.deny = ["list_supported_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.tomldeleted file mode 100644index 0734db38c..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/map_old_backend_to_new.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-map-old-backend-to-new"-description = "Enables the map_old_backend_to_new command without any pre-configured scope."-commands.allow = ["map_old_backend_to_new"]--[[permission]]-identifier = "deny-map-old-backend-to-new"-description = "Denies the map_old_backend_to_new command without any pre-configured scope."-commands.deny = ["map_old_backend_to_new"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.tomldeleted file mode 100644index 20431da62..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/parse_backend_version.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-parse-backend-version"-description = "Enables the parse_backend_version command without any pre-configured scope."-commands.allow = ["parse_backend_version"]--[[permission]]-identifier = "deny-parse-backend-version"-description = "Denies the parse_backend_version command without any pre-configured scope."-commands.deny = ["parse_backend_version"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.tomldeleted file mode 100644index 01ebe0883..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/prioritize_backends.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-prioritize-backends"-description = "Enables the prioritize_backends command without any pre-configured scope."-commands.allow = ["prioritize_backends"]--[[permission]]-identifier = "deny-prioritize-backends"-description = "Denies the prioritize_backends command without any pre-configured scope."-commands.deny = ["prioritize_backends"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.tomldeleted file mode 100644index 18ce48706..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/remove_old_backend_versions.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-remove-old-backend-versions"-description = "Enables the remove_old_backend_versions command without any pre-configured scope."-commands.allow = ["remove_old_backend_versions"]--[[permission]]-identifier = "deny-remove-old-backend-versions"-description = "Denies the remove_old_backend_versions command without any pre-configured scope."-commands.deny = ["remove_old_backend_versions"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.tomldeleted file mode 100644index 2b590c390..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/should_migrate_backend.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-should-migrate-backend"-description = "Enables the should_migrate_backend command without any pre-configured scope."-commands.allow = ["should_migrate_backend"]--[[permission]]-identifier = "deny-should-migrate-backend"-description = "Denies the should_migrate_backend command without any pre-configured scope."-commands.deny = ["should_migrate_backend"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.tomldeleted file mode 100644index f2327ceb7..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/commands/validate_backend_string.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-validate-backend-string"-description = "Enables the validate_backend_string command without any pre-configured scope."-commands.allow = ["validate_backend_string"]--[[permission]]-identifier = "deny-validate-backend-string"-description = "Denies the validate_backend_string command without any pre-configured scope."-commands.deny = ["validate_backend_string"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.mdindex 5fea63fb4..a5d7e4e1d 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md@@ -7,51 +7,21 @@ Default permissions for the llamacpp plugin- `allow-cleanup-llama-processes`- `allow-load-llama-model`- `allow-unload-llama-model`-- `allow-start-router`-- `allow-stop-router`-- `allow-try-graceful-stop-router`-- `allow-force-kill-router-tree`-- `allow-get-router-info`-- `allow-reload-router-models`-- `allow-router-slots-idle`-- `allow-router-health`-- `allow-adopt-router`-- `allow-get-devices`- `allow-generate-api-key`-- `allow-is-process-running`- `allow-ensure-session-ready`-- `allow-get-random-port`- `allow-find-session-by-model`- `allow-get-loaded-models`-- `allow-get-all-sessions`-- `allow-get-session-by-model`+- `allow-start-engine`+- `allow-stop-engine`+- `allow-get-engine-info`+- `allow-reload-engine-models`+- `allow-engine-devices`+- `allow-force-stop-engine`+- `allow-engine-slots-idle`+- `allow-erase-thread-slot-state`- `allow-read-gguf-metadata`-- `allow-estimate-kv-cache-size`-- `allow-get-model-size`+- `allow-find-gguf-tensors`- `allow-is-model-supported`-- `allow-map-old-backend-to-new`-- `allow-get-local-installed-backends`-- `allow-list-supported-backends`-- `allow-determine-supported-backends`-- `allow-get-supported-features`-- `allow-is-cuda-installed`-- `allow-find-latest-version-for-backend`-- `allow-prioritize-backends`-- `allow-parse-backend-version`-- `allow-check-backend-for-updates`-- `allow-remove-old-backend-versions`-- `allow-validate-backend-string`-- `allow-should-migrate-backend`-- `allow-handle-setting-update`-- `allow-get-backend-dir`-- `allow-get-backend-exe-path`-- `allow-check-backend-installed`-- `allow-verify-backend-installation`-- `allow-fetch-remote-supported-backends`-- `allow-build-backend-download-items`-- `allow-fetch-backend-checksums`-- `allow-verify-file-sha512`-- `allow-probe-backend-load`## Permission Table@@ -62,110 +32,6 @@ Default permissions for the llamacpp plugin</tr>-<tr>-<td>--`llamacpp:allow-adopt-router`--</td>-<td>--Enables the adopt_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-adopt-router`--</td>-<td>--Denies the adopt_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-build-backend-download-items`--</td>-<td>--Enables the build_backend_download_items command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-build-backend-download-items`--</td>-<td>--Denies the build_backend_download_items command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-check-backend-for-updates`--</td>-<td>--Enables the check_backend_for_updates command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-check-backend-for-updates`--</td>-<td>--Denies the check_backend_for_updates command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-check-backend-installed`--</td>-<td>--Enables the check_backend_installed command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-check-backend-installed`--</td>-<td>--Denies the check_backend_installed command without any pre-configured scope.--</td>-</tr>-<tr><td>@@ -195,38 +61,12 @@ Denies the cleanup_llama_processes command without any pre-configured scope.<tr><td>-`llamacpp:allow-determine-supported-backends`--</td>-<td>--Enables the determine_supported_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-determine-supported-backends`--</td>-<td>--Denies the determine_supported_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-ensure-session-ready`+`llamacpp:allow-engine-devices`</td><td>-Enables the ensure_session_ready command without any pre-configured scope.+Enables the engine_devices command without any pre-configured scope.</td></tr>@@ -234,12 +74,12 @@ Enables the ensure_session_ready command without any pre-configured scope.<tr><td>-`llamacpp:deny-ensure-session-ready`+`llamacpp:deny-engine-devices`</td><td>-Denies the ensure_session_ready command without any pre-configured scope.+Denies the engine_devices command without any pre-configured scope.</td></tr>@@ -247,12 +87,12 @@ Denies the ensure_session_ready command without any pre-configured scope.<tr><td>-`llamacpp:allow-estimate-kv-cache-size`+`llamacpp:allow-engine-slots-idle`</td><td>-Enables the estimate_kv_cache_size command without any pre-configured scope.+Enables the engine_slots_idle command without any pre-configured scope.</td></tr>@@ -260,12 +100,12 @@ Enables the estimate_kv_cache_size command without any pre-configured scope.<tr><td>-`llamacpp:deny-estimate-kv-cache-size`+`llamacpp:deny-engine-slots-idle`</td><td>-Denies the estimate_kv_cache_size command without any pre-configured scope.+Denies the engine_slots_idle command without any pre-configured scope.</td></tr>@@ -273,12 +113,12 @@ Denies the estimate_kv_cache_size command without any pre-configured scope.<tr><td>-`llamacpp:allow-fetch-backend-checksums`+`llamacpp:allow-ensure-session-ready`</td><td>-Enables the fetch_backend_checksums command without any pre-configured scope.+Enables the ensure_session_ready command without any pre-configured scope.</td></tr>@@ -286,12 +126,12 @@ Enables the fetch_backend_checksums command without any pre-configured scope.<tr><td>-`llamacpp:deny-fetch-backend-checksums`+`llamacpp:deny-ensure-session-ready`</td><td>-Denies the fetch_backend_checksums command without any pre-configured scope.+Denies the ensure_session_ready command without any pre-configured scope.</td></tr>@@ -299,12 +139,12 @@ Denies the fetch_backend_checksums command without any pre-configured scope.<tr><td>-`llamacpp:allow-fetch-remote-supported-backends`+`llamacpp:allow-erase-thread-slot-state`</td><td>-Enables the fetch_remote_supported_backends command without any pre-configured scope.+Enables the erase_thread_slot_state command without any pre-configured scope.</td></tr>@@ -312,12 +152,12 @@ Enables the fetch_remote_supported_backends command without any pre-configured s<tr><td>-`llamacpp:deny-fetch-remote-supported-backends`+`llamacpp:deny-erase-thread-slot-state`</td><td>-Denies the fetch_remote_supported_backends command without any pre-configured scope.+Denies the erase_thread_slot_state command without any pre-configured scope.</td></tr>@@ -325,12 +165,12 @@ Denies the fetch_remote_supported_backends command without any pre-configured sc<tr><td>-`llamacpp:allow-find-latest-version-for-backend`+`llamacpp:allow-find-gguf-tensors`</td><td>-Enables the find_latest_version_for_backend command without any pre-configured scope.+Enables the find_gguf_tensors command without any pre-configured scope.</td></tr>@@ -338,12 +178,12 @@ Enables the find_latest_version_for_backend command without any pre-configured s<tr><td>-`llamacpp:deny-find-latest-version-for-backend`+`llamacpp:deny-find-gguf-tensors`</td><td>-Denies the find_latest_version_for_backend command without any pre-configured scope.+Denies the find_gguf_tensors command without any pre-configured scope.</td></tr>@@ -377,12 +217,12 @@ Denies the find_session_by_model command without any pre-configured scope.<tr><td>-`llamacpp:allow-force-kill-router-tree`+`llamacpp:allow-force-stop-engine`</td><td>-Enables the force_kill_router_tree command without any pre-configured scope.+Enables the force_stop_engine command without any pre-configured scope.</td></tr>@@ -390,12 +230,12 @@ Enables the force_kill_router_tree command without any pre-configured scope.<tr><td>-`llamacpp:deny-force-kill-router-tree`+`llamacpp:deny-force-stop-engine`</td><td>-Denies the force_kill_router_tree command without any pre-configured scope.+Denies the force_stop_engine command without any pre-configured scope.</td></tr>@@ -429,90 +269,12 @@ Denies the generate_api_key command without any pre-configured scope.<tr><td>-`llamacpp:allow-get-all-sessions`--</td>-<td>--Enables the get_all_sessions command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-get-all-sessions`--</td>-<td>--Denies the get_all_sessions command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-get-backend-dir`--</td>-<td>--Enables the get_backend_dir command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-get-backend-dir`--</td>-<td>--Denies the get_backend_dir command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-get-backend-exe-path`--</td>-<td>--Enables the get_backend_exe_path command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-get-backend-exe-path`--</td>-<td>--Denies the get_backend_exe_path command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-get-devices`+`llamacpp:allow-get-engine-info`</td><td>-Enables the get_devices command without any pre-configured scope.+Enables the get_engine_info command without any pre-configured scope.</td></tr>@@ -520,12 +282,12 @@ Enables the get_devices command without any pre-configured scope.<tr><td>-`llamacpp:deny-get-devices`+`llamacpp:deny-get-engine-info`</td><td>-Denies the get_devices command without any pre-configured scope.+Denies the get_engine_info command without any pre-configured scope.</td></tr>@@ -559,64 +321,12 @@ Denies the get_loaded_models command without any pre-configured scope.<tr><td>-`llamacpp:allow-get-local-installed-backends`--</td>-<td>--Enables the get_local_installed_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-get-local-installed-backends`--</td>-<td>--Denies the get_local_installed_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-get-model-size`--</td>-<td>--Enables the get_model_size command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-get-model-size`--</td>-<td>--Denies the get_model_size command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-get-random-port`+`llamacpp:allow-is-model-supported`</td><td>-Enables the get_random_port command without any pre-configured scope.+Enables the is_model_supported command without any pre-configured scope.</td></tr>@@ -624,12 +334,12 @@ Enables the get_random_port command without any pre-configured scope.<tr><td>-`llamacpp:deny-get-random-port`+`llamacpp:deny-is-model-supported`</td><td>-Denies the get_random_port command without any pre-configured scope.+Denies the is_model_supported command without any pre-configured scope.</td></tr>@@ -637,12 +347,12 @@ Denies the get_random_port command without any pre-configured scope.<tr><td>-`llamacpp:allow-get-router-info`+`llamacpp:allow-load-llama-model`</td><td>-Enables the get_router_info command without any pre-configured scope.+Enables the load_llama_model command without any pre-configured scope.</td></tr>@@ -650,12 +360,12 @@ Enables the get_router_info command without any pre-configured scope.<tr><td>-`llamacpp:deny-get-router-info`+`llamacpp:deny-load-llama-model`</td><td>-Denies the get_router_info command without any pre-configured scope.+Denies the load_llama_model command without any pre-configured scope.</td></tr>@@ -663,12 +373,12 @@ Denies the get_router_info command without any pre-configured scope.<tr><td>-`llamacpp:allow-get-session-by-model`+`llamacpp:allow-read-gguf-metadata`</td><td>-Enables the get_session_by_model command without any pre-configured scope.+Enables the read_gguf_metadata command without any pre-configured scope.</td></tr>@@ -676,12 +386,12 @@ Enables the get_session_by_model command without any pre-configured scope.<tr><td>-`llamacpp:deny-get-session-by-model`+`llamacpp:deny-read-gguf-metadata`</td><td>-Denies the get_session_by_model command without any pre-configured scope.+Denies the read_gguf_metadata command without any pre-configured scope.</td></tr>@@ -689,12 +399,12 @@ Denies the get_session_by_model command without any pre-configured scope.<tr><td>-`llamacpp:allow-get-supported-features`+`llamacpp:allow-reload-engine-models`</td><td>-Enables the get_supported_features command without any pre-configured scope.+Enables the reload_engine_models command without any pre-configured scope.</td></tr>@@ -702,12 +412,12 @@ Enables the get_supported_features command without any pre-configured scope.<tr><td>-`llamacpp:deny-get-supported-features`+`llamacpp:deny-reload-engine-models`</td><td>-Denies the get_supported_features command without any pre-configured scope.+Denies the reload_engine_models command without any pre-configured scope.</td></tr>@@ -715,12 +425,12 @@ Denies the get_supported_features command without any pre-configured scope.<tr><td>-`llamacpp:allow-handle-setting-update`+`llamacpp:allow-start-engine`</td><td>-Enables the handle_setting_update command without any pre-configured scope.+Enables the start_engine command without any pre-configured scope.</td></tr>@@ -728,12 +438,12 @@ Enables the handle_setting_update command without any pre-configured scope.<tr><td>-`llamacpp:deny-handle-setting-update`+`llamacpp:deny-start-engine`</td><td>-Denies the handle_setting_update command without any pre-configured scope.+Denies the start_engine command without any pre-configured scope.</td></tr>@@ -741,12 +451,12 @@ Denies the handle_setting_update command without any pre-configured scope.<tr><td>-`llamacpp:allow-is-cuda-installed`+`llamacpp:allow-stop-engine`</td><td>-Enables the is_cuda_installed command without any pre-configured scope.+Enables the stop_engine command without any pre-configured scope.</td></tr>@@ -754,12 +464,12 @@ Enables the is_cuda_installed command without any pre-configured scope.<tr><td>-`llamacpp:deny-is-cuda-installed`+`llamacpp:deny-stop-engine`</td><td>-Denies the is_cuda_installed command without any pre-configured scope.+Denies the stop_engine command without any pre-configured scope.</td></tr>@@ -767,12 +477,12 @@ Denies the is_cuda_installed command without any pre-configured scope.<tr><td>-`llamacpp:allow-is-model-supported`+`llamacpp:allow-unload-llama-model`</td><td>-Enables the is_model_supported command without any pre-configured scope.+Enables the unload_llama_model command without any pre-configured scope.</td></tr>@@ -780,533 +490,13 @@ Enables the is_model_supported command without any pre-configured scope.<tr><td>-`llamacpp:deny-is-model-supported`--</td>-<td>--Denies the is_model_supported command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-is-process-running`--</td>-<td>--Enables the is_process_running command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-is-process-running`--</td>-<td>--Denies the is_process_running command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-list-supported-backends`--</td>-<td>--Enables the list_supported_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-list-supported-backends`--</td>-<td>--Denies the list_supported_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-load-llama-model`--</td>-<td>--Enables the load_llama_model command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-load-llama-model`--</td>-<td>--Denies the load_llama_model command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-map-old-backend-to-new`--</td>-<td>--Enables the map_old_backend_to_new command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-map-old-backend-to-new`--</td>-<td>--Denies the map_old_backend_to_new command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-parse-backend-version`--</td>-<td>--Enables the parse_backend_version command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-parse-backend-version`--</td>-<td>--Denies the parse_backend_version command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-prioritize-backends`--</td>-<td>--Enables the prioritize_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-prioritize-backends`--</td>-<td>--Denies the prioritize_backends command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-probe-backend-load`--</td>-<td>--Enables the probe_backend_load command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-probe-backend-load`--</td>-<td>--Denies the probe_backend_load command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-read-gguf-metadata`--</td>-<td>--Enables the read_gguf_metadata command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-read-gguf-metadata`--</td>-<td>--Denies the read_gguf_metadata command without any pre-configured scope.--</td>-</tr>--<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>-<td>--Enables the remove_old_backend_versions command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-remove-old-backend-versions`--</td>-<td>--Denies the remove_old_backend_versions command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-router-health`--</td>-<td>--Enables the router_health command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-router-health`--</td>-<td>--Denies the router_health command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-router-slots-idle`--</td>-<td>--Enables the router_slots_idle command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-router-slots-idle`--</td>-<td>--Denies the router_slots_idle command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-should-migrate-backend`--</td>-<td>--Enables the should_migrate_backend command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-should-migrate-backend`--</td>-<td>--Denies the should_migrate_backend command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-start-router`--</td>-<td>--Enables the start_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-start-router`--</td>-<td>--Denies the start_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-stop-router`--</td>-<td>--Enables the stop_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-stop-router`--</td>-<td>--Denies the stop_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-try-graceful-stop-router`--</td>-<td>--Enables the try_graceful_stop_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-try-graceful-stop-router`--</td>-<td>--Denies the try_graceful_stop_router command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-unload-llama-model`--</td>-<td>--Enables the unload_llama_model command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-unload-llama-model`+`llamacpp:deny-unload-llama-model`</td><td>Denies the unload_llama_model command without any pre-configured scope.-</td>-</tr>--<tr>-<td>--`llamacpp:allow-validate-backend-string`--</td>-<td>--Enables the validate_backend_string command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-validate-backend-string`--</td>-<td>--Denies the validate_backend_string command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-verify-backend-installation`--</td>-<td>--Enables the verify_backend_installation command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-verify-backend-installation`--</td>-<td>--Denies the verify_backend_installation command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:allow-verify-file-sha512`--</td>-<td>--Enables the verify_file_sha512 command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`llamacpp:deny-verify-file-sha512`--</td>-<td>--Denies the verify_file_sha512 command without any pre-configured scope.-</td></tr></table>diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.tomlindex 9cfeb8d78..0585e75d9 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/default.toml@@ -1,63 +1,29 @@[default]description = "Default permissions for the llamacpp plugin"permissions = [- # Cleanup commands+ # Cleanup"allow-cleanup-llama-processes",- # LlamaCpp server commands+ # Model lifecycle, served by the engine worker over loopback HTTP"allow-load-llama-model","allow-unload-llama-model",- "allow-start-router",- "allow-stop-router",- "allow-try-graceful-stop-router",- "allow-force-kill-router-tree",- "allow-get-router-info",- "allow-reload-router-models",- "allow-router-slots-idle",- "allow-router-health",- "allow-adopt-router",- "allow-get-devices","allow-generate-api-key",- "allow-is-process-running","allow-ensure-session-ready",- "allow-get-random-port","allow-find-session-by-model","allow-get-loaded-models",- "allow-get-all-sessions",- "allow-get-session-by-model",- # GGUF commands+ # The in-process engine worker+ "allow-start-engine",+ "allow-stop-engine",+ "allow-get-engine-info",+ "allow-reload-engine-models",+ "allow-engine-devices",+ "allow-force-stop-engine",+ "allow-engine-slots-idle",+ "allow-erase-thread-slot-state",++ # GGUF"allow-read-gguf-metadata",- "allow-estimate-kv-cache-size",- "allow-get-model-size",+ "allow-find-gguf-tensors","allow-is-model-supported",-- # Backend management commands- "allow-map-old-backend-to-new",- "allow-get-local-installed-backends",- "allow-list-supported-backends",- "allow-determine-supported-backends",- "allow-get-supported-features",- "allow-is-cuda-installed",- "allow-find-latest-version-for-backend",- "allow-prioritize-backends",- "allow-parse-backend-version",- "allow-check-backend-for-updates",- "allow-remove-old-backend-versions",- "allow-validate-backend-string",- "allow-should-migrate-backend",- "allow-handle-setting-update",-- # Backend path & download commands- "allow-get-backend-dir",- "allow-get-backend-exe-path",- "allow-check-backend-installed",- "allow-verify-backend-installation",- "allow-fetch-remote-supported-backends",- "allow-build-backend-download-items",- "allow-fetch-backend-checksums",- "allow-verify-file-sha512",-- # Backend GPU library load probe- "allow-probe-backend-load"]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.jsonindex bda297a75..d46852336 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json@@ -294,54 +294,6 @@"PermissionKind": {"type": "string","oneOf": [- {- "description": "Enables the adopt_router command without any pre-configured scope.",- "type": "string",- "const": "allow-adopt-router",- "markdownDescription": "Enables the adopt_router command without any pre-configured scope."- },- {- "description": "Denies the adopt_router command without any pre-configured scope.",- "type": "string",- "const": "deny-adopt-router",- "markdownDescription": "Denies the adopt_router command without any pre-configured scope."- },- {- "description": "Enables the build_backend_download_items command without any pre-configured scope.",- "type": "string",- "const": "allow-build-backend-download-items",- "markdownDescription": "Enables the build_backend_download_items command without any pre-configured scope."- },- {- "description": "Denies the build_backend_download_items command without any pre-configured scope.",- "type": "string",- "const": "deny-build-backend-download-items",- "markdownDescription": "Denies the build_backend_download_items command without any pre-configured scope."- },- {- "description": "Enables the check_backend_for_updates command without any pre-configured scope.",- "type": "string",- "const": "allow-check-backend-for-updates",- "markdownDescription": "Enables the check_backend_for_updates command without any pre-configured scope."- },- {- "description": "Denies the check_backend_for_updates command without any pre-configured scope.",- "type": "string",- "const": "deny-check-backend-for-updates",- "markdownDescription": "Denies the check_backend_for_updates command without any pre-configured scope."- },- {- "description": "Enables the check_backend_installed command without any pre-configured scope.",- "type": "string",- "const": "allow-check-backend-installed",- "markdownDescription": "Enables the check_backend_installed command without any pre-configured scope."- },- {- "description": "Denies the check_backend_installed command without any pre-configured scope.",- "type": "string",- "const": "deny-check-backend-installed",- "markdownDescription": "Denies the check_backend_installed command without any pre-configured scope."- },{"description": "Enables the cleanup_llama_processes command without any pre-configured scope.","type": "string",@@ -355,76 +307,64 @@"markdownDescription": "Denies the cleanup_llama_processes command without any pre-configured scope."},{- "description": "Enables the determine_supported_backends command without any pre-configured scope.",+ "description": "Enables the engine_devices command without any pre-configured scope.","type": "string",- "const": "allow-determine-supported-backends",- "markdownDescription": "Enables the determine_supported_backends command without any pre-configured scope."+ "const": "allow-engine-devices",+ "markdownDescription": "Enables the engine_devices command without any pre-configured scope."},{- "description": "Denies the determine_supported_backends command without any pre-configured scope.",+ "description": "Denies the engine_devices command without any pre-configured scope.","type": "string",- "const": "deny-determine-supported-backends",- "markdownDescription": "Denies the determine_supported_backends command without any pre-configured scope."+ "const": "deny-engine-devices",+ "markdownDescription": "Denies the engine_devices command without any pre-configured scope."},{- "description": "Enables the ensure_session_ready command without any pre-configured scope.",- "type": "string",- "const": "allow-ensure-session-ready",- "markdownDescription": "Enables the ensure_session_ready command without any pre-configured scope."- },- {- "description": "Denies the ensure_session_ready command without any pre-configured scope.",- "type": "string",- "const": "deny-ensure-session-ready",- "markdownDescription": "Denies the ensure_session_ready command without any pre-configured scope."- },- {- "description": "Enables the estimate_kv_cache_size command without any pre-configured scope.",+ "description": "Enables the engine_slots_idle command without any pre-configured scope.","type": "string",- "const": "allow-estimate-kv-cache-size",- "markdownDescription": "Enables the estimate_kv_cache_size command without any pre-configured scope."+ "const": "allow-engine-slots-idle",+ "markdownDescription": "Enables the engine_slots_idle command without any pre-configured scope."},{- "description": "Denies the estimate_kv_cache_size command without any pre-configured scope.",+ "description": "Denies the engine_slots_idle command without any pre-configured scope.","type": "string",- "const": "deny-estimate-kv-cache-size",- "markdownDescription": "Denies the estimate_kv_cache_size command without any pre-configured scope."+ "const": "deny-engine-slots-idle",+ "markdownDescription": "Denies the engine_slots_idle command without any pre-configured scope."},{- "description": "Enables the fetch_backend_checksums command without any pre-configured scope.",+ "description": "Enables the ensure_session_ready command without any pre-configured scope.","type": "string",- "const": "allow-fetch-backend-checksums",- "markdownDescription": "Enables the fetch_backend_checksums command without any pre-configured scope."+ "const": "allow-ensure-session-ready",+ "markdownDescription": "Enables the ensure_session_ready command without any pre-configured scope."},{- "description": "Denies the fetch_backend_checksums command without any pre-configured scope.",+ "description": "Denies the ensure_session_ready command without any pre-configured scope.","type": "string",- "const": "deny-fetch-backend-checksums",- "markdownDescription": "Denies the fetch_backend_checksums command without any pre-configured scope."+ "const": "deny-ensure-session-ready",+ "markdownDescription": "Denies the ensure_session_ready command without any pre-configured scope."},{- "description": "Enables the fetch_remote_supported_backends command without any pre-configured scope.",+ "description": "Enables the erase_thread_slot_state command without any pre-configured scope.","type": "string",- "const": "allow-fetch-remote-supported-backends",- "markdownDescription": "Enables the fetch_remote_supported_backends command without any pre-configured scope."+ "const": "allow-erase-thread-slot-state",+ "markdownDescription": "Enables the erase_thread_slot_state command without any pre-configured scope."},{- "description": "Denies the fetch_remote_supported_backends command without any pre-configured scope.",+ "description": "Denies the erase_thread_slot_state command without any pre-configured scope.","type": "string",- "const": "deny-fetch-remote-supported-backends",- "markdownDescription": "Denies the fetch_remote_supported_backends command without any pre-configured scope."+ "const": "deny-erase-thread-slot-state",+ "markdownDescription": "Denies the erase_thread_slot_state command without any pre-configured scope."},{- "description": "Enables the find_latest_version_for_backend command without any pre-configured scope.",+ "description": "Enables the find_gguf_tensors command without any pre-configured scope.","type": "string",- "const": "allow-find-latest-version-for-backend",- "markdownDescription": "Enables the find_latest_version_for_backend command without any pre-configured scope."+ "const": "allow-find-gguf-tensors",+ "markdownDescription": "Enables the find_gguf_tensors command without any pre-configured scope."},{- "description": "Denies the find_latest_version_for_backend command without any pre-configured scope.",+ "description": "Denies the find_gguf_tensors command without any pre-configured scope.","type": "string",- "const": "deny-find-latest-version-for-backend",- "markdownDescription": "Denies the find_latest_version_for_backend command without any pre-configured scope."+ "const": "deny-find-gguf-tensors",+ "markdownDescription": "Denies the find_gguf_tensors command without any pre-configured scope."},{"description": "Enables the find_session_by_model command without any pre-configured scope.",@@ -439,16 +379,16 @@"markdownDescription": "Denies the find_session_by_model command without any pre-configured scope."},{- "description": "Enables the force_kill_router_tree command without any pre-configured scope.",+ "description": "Enables the force_stop_engine command without any pre-configured scope.","type": "string",- "const": "allow-force-kill-router-tree",- "markdownDescription": "Enables the force_kill_router_tree command without any pre-configured scope."+ "const": "allow-force-stop-engine",+ "markdownDescription": "Enables the force_stop_engine command without any pre-configured scope."},{- "description": "Denies the force_kill_router_tree command without any pre-configured scope.",+ "description": "Denies the force_stop_engine command without any pre-configured scope.","type": "string",- "const": "deny-force-kill-router-tree",- "markdownDescription": "Denies the force_kill_router_tree command without any pre-configured scope."+ "const": "deny-force-stop-engine",+ "markdownDescription": "Denies the force_stop_engine command without any pre-configured scope."},{"description": "Enables the generate_api_key command without any pre-configured scope.",@@ -463,52 +403,16 @@"markdownDescription": "Denies the generate_api_key command without any pre-configured scope."},{- "description": "Enables the get_all_sessions command without any pre-configured scope.",- "type": "string",- "const": "allow-get-all-sessions",- "markdownDescription": "Enables the get_all_sessions command without any pre-configured scope."- },- {- "description": "Denies the get_all_sessions command without any pre-configured scope.",- "type": "string",- "const": "deny-get-all-sessions",- "markdownDescription": "Denies the get_all_sessions command without any pre-configured scope."- },- {- "description": "Enables the get_backend_dir command without any pre-configured scope.",+ "description": "Enables the get_engine_info command without any pre-configured scope.","type": "string",- "const": "allow-get-backend-dir",- "markdownDescription": "Enables the get_backend_dir command without any pre-configured scope."+ "const": "allow-get-engine-info",+ "markdownDescription": "Enables the get_engine_info command without any pre-configured scope."},{- "description": "Denies the get_backend_dir command without any pre-configured scope.",+ "description": "Denies the get_engine_info command without any pre-configured scope.","type": "string",- "const": "deny-get-backend-dir",- "markdownDescription": "Denies the get_backend_dir command without any pre-configured scope."- },- {- "description": "Enables the get_backend_exe_path command without any pre-configured scope.",- "type": "string",- "const": "allow-get-backend-exe-path",- "markdownDescription": "Enables the get_backend_exe_path command without any pre-configured scope."- },- {- "description": "Denies the get_backend_exe_path command without any pre-configured scope.",- "type": "string",- "const": "deny-get-backend-exe-path",- "markdownDescription": "Denies the get_backend_exe_path command without any pre-configured scope."- },- {- "description": "Enables the get_devices command without any pre-configured scope.",- "type": "string",- "const": "allow-get-devices",- "markdownDescription": "Enables the get_devices command without any pre-configured scope."- },- {- "description": "Denies the get_devices command without any pre-configured scope.",- "type": "string",- "const": "deny-get-devices",- "markdownDescription": "Denies the get_devices command without any pre-configured scope."+ "const": "deny-get-engine-info",+ "markdownDescription": "Denies the get_engine_info command without any pre-configured scope."},{"description": "Enables the get_loaded_models command without any pre-configured scope.",@@ -522,102 +426,6 @@"const": "deny-get-loaded-models","markdownDescription": "Denies the get_loaded_models command without any pre-configured scope."},- {- "description": "Enables the get_local_installed_backends command without any pre-configured scope.",- "type": "string",- "const": "allow-get-local-installed-backends",- "markdownDescription": "Enables the get_local_installed_backends command without any pre-configured scope."- },- {- "description": "Denies the get_local_installed_backends command without any pre-configured scope.",- "type": "string",- "const": "deny-get-local-installed-backends",- "markdownDescription": "Denies the get_local_installed_backends command without any pre-configured scope."- },- {- "description": "Enables the get_model_size command without any pre-configured scope.",- "type": "string",- "const": "allow-get-model-size",- "markdownDescription": "Enables the get_model_size command without any pre-configured scope."- },- {- "description": "Denies the get_model_size command without any pre-configured scope.",- "type": "string",- "const": "deny-get-model-size",- "markdownDescription": "Denies the get_model_size command without any pre-configured scope."- },- {- "description": "Enables the get_random_port command without any pre-configured scope.",- "type": "string",- "const": "allow-get-random-port",- "markdownDescription": "Enables the get_random_port command without any pre-configured scope."- },- {- "description": "Denies the get_random_port command without any pre-configured scope.",- "type": "string",- "const": "deny-get-random-port",- "markdownDescription": "Denies the get_random_port command without any pre-configured scope."- },- {- "description": "Enables the get_router_info command without any pre-configured scope.",- "type": "string",- "const": "allow-get-router-info",- "markdownDescription": "Enables the get_router_info command without any pre-configured scope."- },- {- "description": "Denies the get_router_info command without any pre-configured scope.",- "type": "string",- "const": "deny-get-router-info",- "markdownDescription": "Denies the get_router_info command without any pre-configured scope."- },- {- "description": "Enables the get_session_by_model command without any pre-configured scope.",- "type": "string",- "const": "allow-get-session-by-model",- "markdownDescription": "Enables the get_session_by_model command without any pre-configured scope."- },- {- "description": "Denies the get_session_by_model command without any pre-configured scope.",- "type": "string",- "const": "deny-get-session-by-model",- "markdownDescription": "Denies the get_session_by_model command without any pre-configured scope."- },- {- "description": "Enables the get_supported_features command without any pre-configured scope.",- "type": "string",- "const": "allow-get-supported-features",- "markdownDescription": "Enables the get_supported_features command without any pre-configured scope."- },- {- "description": "Denies the get_supported_features command without any pre-configured scope.",- "type": "string",- "const": "deny-get-supported-features",- "markdownDescription": "Denies the get_supported_features command without any pre-configured scope."- },- {- "description": "Enables the handle_setting_update command without any pre-configured scope.",- "type": "string",- "const": "allow-handle-setting-update",- "markdownDescription": "Enables the handle_setting_update command without any pre-configured scope."- },- {- "description": "Denies the handle_setting_update command without any pre-configured scope.",- "type": "string",- "const": "deny-handle-setting-update",- "markdownDescription": "Denies the handle_setting_update command without any pre-configured scope."- },- {- "description": "Enables the is_cuda_installed command without any pre-configured scope.",- "type": "string",- "const": "allow-is-cuda-installed",- "markdownDescription": "Enables the is_cuda_installed command without any pre-configured scope."- },- {- "description": "Denies the is_cuda_installed command without any pre-configured scope.",- "type": "string",- "const": "deny-is-cuda-installed",- "markdownDescription": "Denies the is_cuda_installed command without any pre-configured scope."- },{"description": "Enables the is_model_supported command without any pre-configured scope.","type": "string",@@ -630,30 +438,6 @@"const": "deny-is-model-supported","markdownDescription": "Denies the is_model_supported command without any pre-configured scope."},- {- "description": "Enables the is_process_running command without any pre-configured scope.",- "type": "string",- "const": "allow-is-process-running",- "markdownDescription": "Enables the is_process_running command without any pre-configured scope."- },- {- "description": "Denies the is_process_running command without any pre-configured scope.",- "type": "string",- "const": "deny-is-process-running",- "markdownDescription": "Denies the is_process_running command without any pre-configured scope."- },- {- "description": "Enables the list_supported_backends command without any pre-configured scope.",- "type": "string",- "const": "allow-list-supported-backends",- "markdownDescription": "Enables the list_supported_backends command without any pre-configured scope."- },- {- "description": "Denies the list_supported_backends command without any pre-configured scope.",- "type": "string",- "const": "deny-list-supported-backends",- "markdownDescription": "Denies the list_supported_backends command without any pre-configured scope."- },{"description": "Enables the load_llama_model command without any pre-configured scope.","type": "string",@@ -666,54 +450,6 @@"const": "deny-load-llama-model","markdownDescription": "Denies the load_llama_model command without any pre-configured scope."},- {- "description": "Enables the map_old_backend_to_new command without any pre-configured scope.",- "type": "string",- "const": "allow-map-old-backend-to-new",- "markdownDescription": "Enables the map_old_backend_to_new command without any pre-configured scope."- },- {- "description": "Denies the map_old_backend_to_new command without any pre-configured scope.",- "type": "string",- "const": "deny-map-old-backend-to-new",- "markdownDescription": "Denies the map_old_backend_to_new command without any pre-configured scope."- },- {- "description": "Enables the parse_backend_version command without any pre-configured scope.",- "type": "string",- "const": "allow-parse-backend-version",- "markdownDescription": "Enables the parse_backend_version command without any pre-configured scope."- },- {- "description": "Denies the parse_backend_version command without any pre-configured scope.",- "type": "string",- "const": "deny-parse-backend-version",- "markdownDescription": "Denies the parse_backend_version command without any pre-configured scope."- },- {- "description": "Enables the prioritize_backends command without any pre-configured scope.",- "type": "string",- "const": "allow-prioritize-backends",- "markdownDescription": "Enables the prioritize_backends command without any pre-configured scope."- },- {- "description": "Denies the prioritize_backends command without any pre-configured scope.",- "type": "string",- "const": "deny-prioritize-backends",- "markdownDescription": "Denies the prioritize_backends command without any pre-configured scope."- },- {- "description": "Enables the probe_backend_load command without any pre-configured scope.",- "type": "string",- "const": "allow-probe-backend-load",- "markdownDescription": "Enables the probe_backend_load command without any pre-configured scope."- },- {- "description": "Denies the probe_backend_load command without any pre-configured scope.",- "type": "string",- "const": "deny-probe-backend-load",- "markdownDescription": "Denies the probe_backend_load command without any pre-configured scope."- },{"description": "Enables the read_gguf_metadata command without any pre-configured scope.","type": "string",@@ -727,100 +463,40 @@"markdownDescription": "Denies the read_gguf_metadata command without any pre-configured scope."},{- "description": "Enables the reload_router_models command without any pre-configured scope.",+ "description": "Enables the reload_engine_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."+ "const": "allow-reload-engine-models",+ "markdownDescription": "Enables the reload_engine_models command without any pre-configured scope."},{- "description": "Denies the reload_router_models command without any pre-configured scope.",+ "description": "Denies the reload_engine_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."+ "const": "deny-reload-engine-models",+ "markdownDescription": "Denies the reload_engine_models command without any pre-configured scope."},{- "description": "Enables the remove_old_backend_versions command without any pre-configured scope.",+ "description": "Enables the start_engine command without any pre-configured scope.","type": "string",- "const": "allow-remove-old-backend-versions",- "markdownDescription": "Enables the remove_old_backend_versions command without any pre-configured scope."+ "const": "allow-start-engine",+ "markdownDescription": "Enables the start_engine command without any pre-configured scope."},{- "description": "Denies the remove_old_backend_versions command without any pre-configured scope.",+ "description": "Denies the start_engine command without any pre-configured scope.","type": "string",- "const": "deny-remove-old-backend-versions",- "markdownDescription": "Denies the remove_old_backend_versions command without any pre-configured scope."+ "const": "deny-start-engine",+ "markdownDescription": "Denies the start_engine command without any pre-configured scope."},{- "description": "Enables the router_health command without any pre-configured scope.",+ "description": "Enables the stop_engine command without any pre-configured scope.","type": "string",- "const": "allow-router-health",- "markdownDescription": "Enables the router_health command without any pre-configured scope."+ "const": "allow-stop-engine",+ "markdownDescription": "Enables the stop_engine command without any pre-configured scope."},{- "description": "Denies the router_health command without any pre-configured scope.",+ "description": "Denies the stop_engine command without any pre-configured scope.","type": "string",- "const": "deny-router-health",- "markdownDescription": "Denies the router_health command without any pre-configured scope."- },- {- "description": "Enables the router_slots_idle command without any pre-configured scope.",- "type": "string",- "const": "allow-router-slots-idle",- "markdownDescription": "Enables the router_slots_idle command without any pre-configured scope."- },- {- "description": "Denies the router_slots_idle command without any pre-configured scope.",- "type": "string",- "const": "deny-router-slots-idle",- "markdownDescription": "Denies the router_slots_idle command without any pre-configured scope."- },- {- "description": "Enables the should_migrate_backend command without any pre-configured scope.",- "type": "string",- "const": "allow-should-migrate-backend",- "markdownDescription": "Enables the should_migrate_backend command without any pre-configured scope."- },- {- "description": "Denies the should_migrate_backend command without any pre-configured scope.",- "type": "string",- "const": "deny-should-migrate-backend",- "markdownDescription": "Denies the should_migrate_backend command without any pre-configured scope."- },- {- "description": "Enables the start_router command without any pre-configured scope.",- "type": "string",- "const": "allow-start-router",- "markdownDescription": "Enables the start_router command without any pre-configured scope."- },- {- "description": "Denies the start_router command without any pre-configured scope.",- "type": "string",- "const": "deny-start-router",- "markdownDescription": "Denies the start_router command without any pre-configured scope."- },- {- "description": "Enables the stop_router command without any pre-configured scope.",- "type": "string",- "const": "allow-stop-router",- "markdownDescription": "Enables the stop_router command without any pre-configured scope."- },- {- "description": "Denies the stop_router command without any pre-configured scope.",- "type": "string",- "const": "deny-stop-router",- "markdownDescription": "Denies the stop_router command without any pre-configured scope."- },- {- "description": "Enables the try_graceful_stop_router command without any pre-configured scope.",- "type": "string",- "const": "allow-try-graceful-stop-router",- "markdownDescription": "Enables the try_graceful_stop_router command without any pre-configured scope."- },- {- "description": "Denies the try_graceful_stop_router command without any pre-configured scope.",- "type": "string",- "const": "deny-try-graceful-stop-router",- "markdownDescription": "Denies the try_graceful_stop_router command without any pre-configured scope."+ "const": "deny-stop-engine",+ "markdownDescription": "Denies the stop_engine command without any pre-configured scope."},{"description": "Enables the unload_llama_model command without any pre-configured scope.",@@ -835,46 +511,10 @@"markdownDescription": "Denies the unload_llama_model command without any pre-configured scope."},{- "description": "Enables the validate_backend_string command without any pre-configured scope.",- "type": "string",- "const": "allow-validate-backend-string",- "markdownDescription": "Enables the validate_backend_string command without any pre-configured scope."- },- {- "description": "Denies the validate_backend_string command without any pre-configured scope.",- "type": "string",- "const": "deny-validate-backend-string",- "markdownDescription": "Denies the validate_backend_string command without any pre-configured scope."- },- {- "description": "Enables the verify_backend_installation command without any pre-configured scope.",- "type": "string",- "const": "allow-verify-backend-installation",- "markdownDescription": "Enables the verify_backend_installation command without any pre-configured scope."- },- {- "description": "Denies the verify_backend_installation command without any pre-configured scope.",- "type": "string",- "const": "deny-verify-backend-installation",- "markdownDescription": "Denies the verify_backend_installation command without any pre-configured scope."- },- {- "description": "Enables the verify_file_sha512 command without any pre-configured scope.",- "type": "string",- "const": "allow-verify-file-sha512",- "markdownDescription": "Enables the verify_file_sha512 command without any pre-configured scope."- },- {- "description": "Denies the verify_file_sha512 command without any pre-configured scope.",- "type": "string",- "const": "deny-verify-file-sha512",- "markdownDescription": "Denies the verify_file_sha512 command without any pre-configured scope."- },- {- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`\n- `allow-probe-backend-load`",+ "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-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`","type": "string","const": "default",- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-start-router`\n- `allow-stop-router`\n- `allow-try-graceful-stop-router`\n- `allow-force-kill-router-tree`\n- `allow-get-router-info`\n- `allow-reload-router-models`\n- `allow-router-slots-idle`\n- `allow-router-health`\n- `allow-adopt-router`\n- `allow-get-devices`\n- `allow-generate-api-key`\n- `allow-is-process-running`\n- `allow-ensure-session-ready`\n- `allow-get-random-port`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-get-all-sessions`\n- `allow-get-session-by-model`\n- `allow-read-gguf-metadata`\n- `allow-estimate-kv-cache-size`\n- `allow-get-model-size`\n- `allow-is-model-supported`\n- `allow-map-old-backend-to-new`\n- `allow-get-local-installed-backends`\n- `allow-list-supported-backends`\n- `allow-determine-supported-backends`\n- `allow-get-supported-features`\n- `allow-is-cuda-installed`\n- `allow-find-latest-version-for-backend`\n- `allow-prioritize-backends`\n- `allow-parse-backend-version`\n- `allow-check-backend-for-updates`\n- `allow-remove-old-backend-versions`\n- `allow-validate-backend-string`\n- `allow-should-migrate-backend`\n- `allow-handle-setting-update`\n- `allow-get-backend-dir`\n- `allow-get-backend-exe-path`\n- `allow-check-backend-installed`\n- `allow-verify-backend-installation`\n- `allow-fetch-remote-supported-backends`\n- `allow-build-backend-download-items`\n- `allow-fetch-backend-checksums`\n- `allow-verify-file-sha512`\n- `allow-probe-backend-load`"+ "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-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`"}]}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cppnew file mode 100644index 000000000..896e95f4b--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp@@ -0,0 +1,700 @@+#include "jan_llama_shim.h"++#include "server-context.h"+#include "server-common.h"+#include "server-http.h"++#include "arg.h"+#include "preset.h"+#include "common.h"+#include "log.h"+#include "build-info.h"+#include "llama.h"+#include "ggml-backend.h"++#include <atomic>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <exception>+#include <functional>+#include <map>+#include <memory>+#include <mutex>+#include <string>+#include <vector>+#include <chrono>+#include <thread>+#include <unordered_map>++struct jan_llama_engine;++namespace {++/// Mirrors upstream's `ex_wrapper` (tools/server/server.cpp), which every route+/// is registered behind. `build_table` captures the *unwrapped* handler members,+/// so the two things that wrapper does have to be done here instead: map+/// `std::invalid_argument` to 400 rather than 500, and build the body with the+/// JSON library. Upstream's own messages quote the offending field+/// (`response_format type must be one of "text" or "json_object"`), and a+/// nlohmann parse error echoes the caller's bytes, so concatenating `e.what()`+/// into a string literal produced unparseable JSON and let a client inject+/// quotes into the response.+server_http_res_ptr error_response(const std::string & message, error_type type) {+ auto res = std::make_unique<server_http_res>();+ res->status = 500;+ try {+ json error_data = format_error_response(message, type);+ res->status = json_value(error_data, "code", 500);+ res->data = safe_json_to_str({{ "error", error_data }});+ } catch (const std::exception & e) {+ LOG_ERR("failed to format an error response: %s | for: %s\n", e.what(), message.c_str());+ res->data = R"({"error":{"message":"internal server error","type":"server_error","code":500}})";+ }+ return res;+}++void set_err(char * err, size_t err_len, const std::string & msg) {+ if (err == nullptr || err_len == 0) {+ return;+ }+ const size_t n = std::min(msg.size(), err_len - 1);+ std::memcpy(err, msg.data(), n);+ err[n] = '\0';+}++jan_llama_engine * finish_start(std::unique_ptr<jan_llama_engine> engine,+ char * err, size_t err_len);++// `server_context::load_model` returns a bool and puts the reason -- a CUDA+// OOM, an unsupported arch, a missing backend -- only in the log, so a caller+// that reports the bool alone cannot tell those apart. These collect+// ERROR-level lines while a load runs so `set_err` can carry the cause.+//+// The first lines are kept rather than the last: the cause comes first+// (`cudaMalloc failed: out of memory`) and everything after it is fallout, and+// keeping the head also stops an unrelated error from a model already serving+// in this process from evicting it.+constexpr size_t LOG_CAPTURE_MAX_LINES = 8;++std::mutex g_capture_mu;+std::vector<std::string> g_captured;+bool g_capturing = false;++void capture_log_callback(ggml_log_level level, const char * text, void * user_data) {+ if (level == GGML_LOG_LEVEL_ERROR && text != nullptr) {+ std::lock_guard<std::mutex> lock(g_capture_mu);+ if (g_capturing && g_captured.size() < LOG_CAPTURE_MAX_LINES) {+ std::string line(text);+ while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) {+ line.pop_back();+ }+ if (!line.empty()) {+ g_captured.push_back(std::move(line));+ }+ }+ }+ common_log_default_callback(level, text, user_data);+}++// Scoped so every exit from the load -- including a throw -- stops capturing.+struct log_capture {+ log_capture() {+ std::lock_guard<std::mutex> lock(g_capture_mu);+ g_captured.clear();+ g_capturing = true;+ }++ ~log_capture() { finish(""); }++ std::string message(const std::string & summary) { return finish(summary); }++private:+ std::string finish(const std::string & summary) {+ std::lock_guard<std::mutex> lock(g_capture_mu);+ g_capturing = false;+ std::string out = summary;+ for (const auto & line : g_captured) {+ out += "; ";+ out += line;+ }+ g_captured.clear();+ return out;+ }+};++// Device descriptions are vendor strings and have carried backslashes and+// quotes; emitting them raw would produce JSON the Rust side cannot parse.+std::string json_quote(const char * raw) {+ std::string out = "\"";+ for (const char * p = raw == nullptr ? "" : raw; *p != '\0'; ++p) {+ const unsigned char c = static_cast<unsigned char>(*p);+ switch (c) {+ case '"': out += "\\\""; break;+ case '\\': out += "\\\\"; break;+ case '\n': out += "\\n"; break;+ case '\r': out += "\\r"; break;+ case '\t': out += "\\t"; break;+ default:+ if (c < 0x20) {+ char esc[7];+ std::snprintf(esc, sizeof(esc), "\\u%04x", c);+ out += esc;+ } else {+ out += static_cast<char>(c);+ }+ }+ }+ out += '"';+ return out;+}++// llama.cpp reads slot actions from the query string, so the shim has to hand+// it a param map. Percent-decoding is included because a value is not+// guaranteed to be url-safe -- ours are ints and fixed keywords, but a caller+// with a filename would silently get the escaped form otherwise.+int hex_value(unsigned char c) {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+}++std::string url_decode(const std::string & in) {+ std::string out;+ out.reserve(in.size());+ for (size_t i = 0; i < in.size(); ++i) {+ if (in[i] == '+') {+ out += ' ';+ continue;+ }+ if (in[i] == '%' && i + 2 < in.size()) {+ const int hi = hex_value(static_cast<unsigned char>(in[i + 1]));+ const int lo = hex_value(static_cast<unsigned char>(in[i + 2]));+ if (hi >= 0 && lo >= 0) {+ out += static_cast<char>(hi * 16 + lo);+ i += 2;+ continue;+ }+ }+ out += in[i];+ }+ return out;+}++std::map<std::string, std::string> parse_query(const char * query) {+ std::map<std::string, std::string> out;+ if (query == nullptr) {+ return out;+ }+ std::string q(query);+ size_t pos = 0;+ while (pos < q.size()) {+ const size_t amp = q.find('&', pos);+ const std::string pair = q.substr(pos, amp == std::string::npos ? std::string::npos : amp - pos);+ pos = amp == std::string::npos ? q.size() : amp + 1;+ if (pair.empty()) {+ continue;+ }+ const size_t eq = pair.find('=');+ if (eq == std::string::npos) {+ out[url_decode(pair)] = "";+ } else {+ out[url_decode(pair.substr(0, eq))] = url_decode(pair.substr(eq + 1));+ }+ }+ return out;+}++} // namespace++struct jan_llama_engine {+ common_params params;+ server_context ctx;+ jan_llama_state_cb on_state = nullptr;+ void * state_ud = nullptr;+ std::unique_ptr<server_routes> routes;+ std::thread loop;+ std::atomic<bool> running{false};+ // Set once start_loop() has returned, i.e. the loop is provably finished.+ // stop() polls this because server_queue::start_loop sets `running = true`+ // at its top (server-queue.cpp:279): a terminate() that lands before the+ // loop thread reaches that line is erased, and the loop then blocks+ // forever. Re-issuing terminate() until the thread exits is the only+ // ordering-independent fix.+ std::atomic<bool> loop_done{false};++ std::unordered_map<std::string, server_http_context::handler_t *> table;++ void build_table() {+ auto & r = *routes;+ table = {+ {"get_health", &r.get_health},+ {"get_metrics", &r.get_metrics},+ {"get_slots", &r.get_slots},+ {"post_slots", &r.post_slots},+ {"get_props", &r.get_props},+ {"post_props", &r.post_props},+ {"post_infill", &r.post_infill},+ {"post_completions", &r.post_completions},+ {"post_completions_oai", &r.post_completions_oai},+ {"post_chat_completions", &r.post_chat_completions},+ {"post_chat_completions_tok", &r.post_chat_completions_tok},+ {"post_control", &r.post_control},+ {"post_responses_oai", &r.post_responses_oai},+ {"post_apply_template", &r.post_apply_template},+ {"get_models", &r.get_models},+ {"post_tokenize", &r.post_tokenize},+ {"post_detokenize", &r.post_detokenize},+ {"post_embeddings", &r.post_embeddings},+ {"post_embeddings_oai", &r.post_embeddings_oai},+ {"post_rerank", &r.post_rerank},+ {"get_lora_adapters", &r.get_lora_adapters},+ {"post_lora_adapters", &r.post_lora_adapters},+ };+ }+};++// server-context.cpp:4188 does `res->set_req(&req)`, and server_res_spipe keeps+// that pointer for the life of the stream -- so the request, and the+// std::function its `should_stop` member references, must outlive the response.+// Declaration order here is the destruction order that guarantees it.+struct jan_llama_response {+ std::atomic<bool> cancel{false};+ std::function<bool()> should_stop;+ std::unique_ptr<server_http_req> req;+ server_http_res_ptr res;++ std::string chunk; // owns the buffer handed back across the ABI+ bool drained = false; // next() reported the last chunk+ bool completed = false; // on_complete() has run++ void finish() {+ if (res && !completed) {+ res->on_complete();+ completed = true;+ }+ }++ ~jan_llama_response() {+ finish();+ }+};++jan_llama_engine * jan_llama_engine_start(const char * const * argv,+ int argc,+ jan_llama_state_cb on_state,+ void * user_data,+ char * err,+ size_t err_len) {+ try {+ auto engine = std::make_unique<jan_llama_engine>();+ engine->on_state = on_state;+ engine->state_ud = user_data;++ // common_params_parse wants char**; it does not retain the pointers.+ std::vector<std::string> owned;+ owned.reserve(argc);+ for (int i = 0; i < argc; i++) {+ owned.emplace_back(argv[i] ? argv[i] : "");+ }+ std::vector<char *> raw;+ raw.reserve(argc);+ for (auto & s : owned) {+ raw.push_back(const_cast<char *>(s.c_str()));+ }++ if (!common_params_parse(argc, raw.data(), engine->params, LLAMA_EXAMPLE_SERVER)) {+ set_err(err, err_len, "failed to parse server arguments");+ return nullptr;+ }++ return finish_start(std::move(engine), err, err_len);+ } catch (const std::exception & e) {+ set_err(err, err_len, e.what());+ return nullptr;+ } catch (...) {+ set_err(err, err_len, "unknown exception while starting the engine");+ return nullptr;+ }+}++jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_path,+ const char * preset_name,+ jan_llama_state_cb on_state,+ void * user_data,+ char * err,+ size_t err_len) {+ try {+ if (ini_path == nullptr || preset_name == nullptr) {+ set_err(err, err_len, "ini_path and preset_name are required");+ return nullptr;+ }+ auto engine = std::make_unique<jan_llama_engine>();+ engine->on_state = on_state;+ engine->state_ud = user_data;++ common_preset_context pctx(LLAMA_EXAMPLE_SERVER);+ // The ini is shared with the router, which owns keys like+ // load-on-startup that are not common_params options.+ pctx.ignore_unknown_keys = true;++ // apply_to_params only writes the keys the ini names, so the base has+ // to be the example's own defaults rather than a default-constructed+ // common_params -- otherwise the per-example values+ // common_params_parser_init sets (for SERVER, n_parallel = -1 = auto)+ // are silently dropped and an unset key means something different here+ // than it does on the command line. pctx already built them.+ engine->params = pctx.default_params;++ common_preset global;+ common_presets presets = pctx.load_from_ini(ini_path, global);++ auto it = presets.find(preset_name);+ if (it == presets.end()) {+ set_err(err, err_len, std::string("no such preset: ") + preset_name);+ return nullptr;+ }++ // [*] first, then the named section overrides it.+ global.apply_to_params(engine->params);+ it->second.apply_to_params(engine->params);++ // common_params_parse does this at arg.cpp:892-896; apply_to_params does+ // not. Without it n_threads stays 0 and ggml_threadpool_new_impl+ // memsets a zero-length array -> SIGSEGV. The router never hits this+ // because it forwards keys to a child that re-parses them.+ postprocess_cpu_params(engine->params.cpuparams, nullptr);+ postprocess_cpu_params(engine->params.cpuparams_batch, &engine->params.cpuparams);+ postprocess_cpu_params(engine->params.speculative.draft.cpuparams,+ &engine->params.cpuparams);+ postprocess_cpu_params(engine->params.speculative.draft.cpuparams_batch,+ &engine->params.cpuparams_batch);++ // Same omission, arg.cpp:946-954: common_params_fit needs spare slots+ // to write its overrides into and throws "did not provide buffer to+ // set tensor_buft_overrides" without them, so auto-fit silently gave+ // up and the load then asked for more VRAM than the device had.+ const size_t ntbo = llama_max_tensor_buft_overrides();+ while (engine->params.tensor_buft_overrides.size() < ntbo) {+ engine->params.tensor_buft_overrides.push_back({nullptr, nullptr});+ }+ if (!engine->params.speculative.draft.tensor_buft_overrides.empty()) {+ engine->params.speculative.draft.tensor_buft_overrides.push_back({nullptr, nullptr});+ }++ // arg.cpp:935-938. llama_model_params::kv_overrides is a C array walked+ // until an entry with an empty key, so a hand-edited `override-kv` in+ // the ini would otherwise be read past its end.+ if (!engine->params.kv_overrides.empty()) {+ engine->params.kv_overrides.emplace_back();+ engine->params.kv_overrides.back().key[0] = 0;+ }++ return finish_start(std::move(engine), err, err_len);+ } catch (const std::exception & e) {+ set_err(err, err_len, e.what());+ return nullptr;+ } catch (...) {+ set_err(err, err_len, "unknown exception while starting from preset");+ return nullptr;+ }+}++namespace {++jan_llama_engine * finish_start(std::unique_ptr<jan_llama_engine> engine,+ char * err, size_t err_len) {+ try {+ // server.cpp:152-157, in llama-server's main() -- which neither entry+ // point here goes through. n_parallel = -1 is the SERVER default, and+ // server_context loops `for (i = 0; i < n_parallel; i++)` to build its+ // slots, so leaving the sentinel unresolved yields an engine with no+ // slots at all and every request waiting forever.+ if (engine->params.n_parallel < 0) {+ engine->params.n_parallel = 4;+ engine->params.kv_unified = true;+ }++ common_init();+ // After common_init, which installs its own callback.+ llama_log_set(capture_log_callback, nullptr);+ llama_backend_init();+ llama_numa_init(engine->params.numa);++ // Must be constructed before load_model: its ctor registers the+ // on_sleeping_state callback the sleep path depends on.+ engine->routes = std::make_unique<server_routes>(engine->params, engine->ctx);++ // Real load progress: server_context reports it here (and nowhere a+ // caller could poll for it), throttled to one sample per 200ms with+ // the first and last always emitted.+ if (engine->on_state != nullptr) {+ auto * cb = engine->on_state;+ void * ud = engine->state_ud;+ engine->ctx.set_state_callback([cb, ud](server_state st, json payload) {+ const std::string state = server_state_to_str(st);+ const std::string body = payload.dump();+ cb(state.c_str(), body.c_str(), ud);+ });+ }++ log_capture capture;+ if (!engine->ctx.load_model(engine->params)) {+ set_err(err, err_len, capture.message("failed to load model"));+ return nullptr;+ }++ engine->routes->update_meta(engine->ctx);+ engine->build_table();++ // start_loop blocks, so it gets its own thread and requests arrive from+ // the caller's threads via server_queue.+ engine->running.store(true);+ auto * raw_engine = engine.get();+ engine->loop = std::thread([raw_engine]() {+ try {+ raw_engine->ctx.start_loop();+ } catch (const std::exception & e) {+ LOG_ERR("server loop threw: %s\n", e.what());+ } catch (...) {+ LOG_ERR("%s", "server loop threw an unknown exception\n");+ }+ raw_engine->running.store(false);+ raw_engine->loop_done.store(true);+ });++ return engine.release();+ } catch (const std::exception & e) {+ set_err(err, err_len, e.what());+ return nullptr;+ } catch (...) {+ set_err(err, err_len, "unknown exception while finishing startup");+ return nullptr;+ }+}++} // namespace++int jan_llama_engine_stop(jan_llama_engine * engine) {+ if (engine == nullptr) {+ return 0;+ }+ // Re-issue terminate until the loop actually exits: a single call can be+ // lost to the `running = true` at the top of server_queue::start_loop.+ constexpr int STOP_POLLS = 200; // ~10s ceiling+ constexpr auto STOP_INTERVAL = std::chrono::milliseconds(50);+ for (int i = 0; i < STOP_POLLS && !engine->loop_done.load(); ++i) {+ try {+ engine->ctx.terminate();+ } catch (...) {+ // best-effort; the join below is what actually decides+ }+ if (engine->loop_done.load()) {+ break;+ }+ std::this_thread::sleep_for(STOP_INTERVAL);+ }+ if (!engine->loop_done.load()) {+ LOG_ERR("%s", "server loop did not stop; leaking it rather than "+ "blocking teardown forever\n");+ engine->loop.detach();+ // The engine is deliberately not deleted: the detached loop still+ // references it. Leaking one object on a shutdown path we already+ // failed is better than a use-after-free.+ //+ // Reported to the caller so it applies the same policy to the state+ // callback it owns: the lambda installed in `ctx` captured that raw+ // pointer by value, and the detached loop still reaches it through+ // `handle_sleeping_state`, so freeing it here would be the+ // use-after-free this branch exists to avoid.+ return 1;+ }+ if (engine->loop.joinable()) {+ engine->loop.join();+ }+ delete engine;+ llama_backend_free();+ return 0;+}++jan_llama_response * jan_llama_engine_request(jan_llama_engine * engine,+ const char * route,+ const char * query,+ const char * body,+ size_t body_len) {+ auto out = new jan_llama_response();+ try {+ if (engine == nullptr || route == nullptr) {+ out->res = error_response("engine or route is null", ERROR_TYPE_SERVER);+ return out;+ }++ auto it = engine->table.find(route);+ if (it == engine->table.end()) {+ out->res = error_response(std::string("unknown route: ") + route,+ ERROR_TYPE_NOT_FOUND);+ return out;+ }++ out->should_stop = [cancel = &out->cancel]() { return cancel->load(); };+ out->req.reset(new server_http_req{+ /* params */ parse_query(query),+ /* headers */ {},+ /* path */ route,+ /* query_string */ query ? query : "",+ /* body */ std::string(body ? body : "", body_len),+ /* files */ {},+ /* should_stop */ out->should_stop,+ });++ out->res = (*it->second)(*out->req);+ if (!out->res) {+ out->res = error_response("handler returned no response", ERROR_TYPE_SERVER);+ }+ return out;+ } catch (const std::invalid_argument & e) {+ // Upstream's own mapping: a malformed request is the client's to fix, so+ // it must not look retryable. server-common.cpp throws this from 16+ // sites (missing `messages`, bad `content` type, `top_logprobs` without+ // `logprobs`, ...), all of which reached Jan's API as 500 before.+ out->res = error_response(e.what(), ERROR_TYPE_INVALID_REQUEST);+ return out;+ } catch (const std::exception & e) {+ out->res = error_response(e.what(), ERROR_TYPE_SERVER);+ return out;+ } catch (...) {+ out->res = error_response("unknown error", ERROR_TYPE_SERVER);+ return out;+ }+}++int jan_llama_response_status(const jan_llama_response * res) {+ return (res && res->res) ? res->res->status : 500;+}++const char * jan_llama_response_content_type(const jan_llama_response * res) {+ return (res && res->res) ? res->res->content_type.c_str() : "";+}++const char * jan_llama_response_body(const jan_llama_response * res, size_t * len) {+ if (!res || !res->res) {+ if (len) *len = 0;+ return "";+ }+ if (len) *len = res->res->data.size();+ return res->res->data.c_str();+}++int jan_llama_response_is_stream(const jan_llama_response * res) {+ return (res && res->res && res->res->is_stream()) ? 1 : 0;+}++int jan_llama_response_next(jan_llama_response * res, const char ** chunk, size_t * len) {+ if (!res || !res->res || !res->res->next) {+ return 0;+ }+ if (res->drained) {+ return 0;+ }+ try {+ res->chunk.clear();+ const bool more = res->res->next(res->chunk);+ if (chunk) *chunk = res->chunk.c_str();+ if (len) *len = res->chunk.size();+ if (!more) {+ // Last call: hand back any trailing bytes now and report completion+ // on the next call, so a final chunk is never dropped.+ res->drained = true;+ res->finish();+ return res->chunk.empty() ? 0 : 1;+ }+ return 1;+ } catch (...) {+ res->drained = true;+ return -1;+ }+}++void jan_llama_response_cancel(jan_llama_response * res) {+ if (res) {+ res->cancel.store(true);+ }+}++void jan_llama_response_free(jan_llama_response * res) {+ delete res;+}++void jan_llama_load_backends(const char * dir) {+ try {+ if (dir == nullptr || *dir == '\0') {+ ggml_backend_load_all();+ } else {+ ggml_backend_load_all_from_path(dir);+ }+ } catch (...) {+ // A backend module that throws while loading must not abort startup;+ // the engine degrades to whatever did register.+ }+}++// Mirrors common_print_available_devices (common/arg.cpp:1139-1161): load every+// backend, then report the non-CPU devices with memory in MiB. The CPU device+// is excluded there too -- "offload to CPU" is not a choice the setting offers.+char * jan_llama_devices_json(void) {+ constexpr size_t MiB = 1024 * 1024;+ std::string out = "[";+ try {+ bool first = true;+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {+ ggml_backend_dev_t dev = ggml_backend_dev_get(i);+ if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {+ continue;+ }+ size_t free_mem = 0;+ size_t total = 0;+ ggml_backend_dev_memory(dev, &free_mem, &total);+ if (!first) {+ out += ',';+ }+ first = false;+ out += "{\"id\":";+ out += json_quote(ggml_backend_dev_name(dev));+ out += ",\"name\":";+ out += json_quote(ggml_backend_dev_description(dev));+ out += ",\"mem\":" + std::to_string(total / MiB);+ out += ",\"free\":" + std::to_string(free_mem / MiB) + "}";+ }+ } catch (...) {+ // A backend module that throws while probing must not abort the+ // process: an empty list reads as "no GPU", which is recoverable.+ out = "[";+ }+ out += ']';++ char * buf = static_cast<char *>(std::malloc(out.size() + 1));+ if (buf == nullptr) {+ return nullptr;+ }+ std::memcpy(buf, out.c_str(), out.size() + 1);+ return buf;+}++void jan_llama_string_free(char * s) {+ std::free(s);+}++// llama_version() is libllama's (include/llama.h); llama_build_number() and+// llama_commit() come from build-info.cpp in llama-common-base.+const char * jan_llama_version(void) {+ return llama_version();+}++int jan_llama_build_number(void) {+ return llama_build_number();+}++const char * jan_llama_commit(void) {+ return llama_commit();+}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.hnew file mode 100644index 000000000..3af03f1bc--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h@@ -0,0 +1,106 @@+// C ABI over llama.cpp's server-context. Everything OpenAI-shaped -- chat+// templates, tool-call parsing, reasoning, sampling, slots, prompt cache,+// multimodal -- stays inside libserver-context.a; this only moves bytes.+#ifndef JAN_LLAMA_SHIM_H+#define JAN_LLAMA_SHIM_H++#include <stddef.h>++#ifdef __cplusplus+extern "C" {+#endif++typedef struct jan_llama_engine jan_llama_engine;+typedef struct jan_llama_response jan_llama_response;++// Load-lifecycle notifications, called on the thread driving the load (and+// later, for a sleep/resume, on the engine's own loop thread). `state` is+// llama.cpp's server state ("loading", "ready", ...) and `payload` its JSON --+// for "loading" that is {"stages":[..],"current":..,"value":0..1}, which is+// the only source of real load progress. Must not throw and must stay valid+// until the engine is stopped. NULL for no notifications.+typedef void (*jan_llama_state_cb)(const char * state,+ const char * payload,+ void * user_data);++// argv is llama-server's own flag set (common_params_parse), so callers reuse+// the upstream arg table instead of mirroring common_params across the FFI.+// Returns NULL on failure and writes a message into err.+jan_llama_engine * jan_llama_engine_start(const char * const * argv,+ int argc,+ jan_llama_state_cb on_state,+ void * user_data,+ char * err,+ size_t err_len);++// Starts from a router.preset.ini section, exactly as Jan already generates it:+// the [*] section is applied first, then the named one overrides it.+jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_path,+ const char * preset_name,+ jan_llama_state_cb on_state,+ void * user_data,+ char * err,+ size_t err_len);++// Returns 1 when the server loop did not stop in time and was detached, so the+// engine (and the state callback the detached loop can still reach) is leaked+// rather than freed; 0 on the clean join. The caller owns the `user_data` it+// passed to start, and must leak it too on a 1 -- freeing it would leave the+// detached loop calling into freed memory.+int jan_llama_engine_stop(jan_llama_engine * engine);++// route names match server_routes members, e.g. "post_chat_completions".+// Never returns NULL: transport failures come back as a 5xx response.+//+// `query` is a url query string ("id_slot=0&action=save"), parsed into the+// request's param map. llama.cpp reads slot actions and a few flags from there+// rather than from the body, so a route like post_slots is unreachable without+// it. NULL or "" means no params.+jan_llama_response * jan_llama_engine_request(jan_llama_engine * engine,+ const char * route,+ const char * query,+ const char * body,+ size_t body_len);++int jan_llama_response_status(const jan_llama_response * res);+const char * jan_llama_response_content_type(const jan_llama_response * res);+const char * jan_llama_response_body(const jan_llama_response * res, size_t * len);+int jan_llama_response_is_stream(const jan_llama_response * res);++// 1 = chunk written (valid until the next call on this response), 0 = finished,+// -1 = the generator threw. Empty chunks are legal and mean "nothing yet".+int jan_llama_response_next(jan_llama_response * res, const char ** chunk, size_t * len);++void jan_llama_response_free(jan_llama_response * res);++// Asks the in-flight generator to stop; safe to call from another thread.+void jan_llama_response_cancel(jan_llama_response * res);++// Registers the ggml compute backends. `dir` names a directory of backend+// modules; NULL uses ggml's own search (the executable's directory, then the+// cwd), which is what a packaged install wants.+//+// Only call this with a non-NULL `dir` when the executable has no backend+// modules beside it: ggml's loader has no already-loaded guard, so a directory+// pre-load followed by its internal search would register a backend twice.+void jan_llama_load_backends(const char * dir);++// The devices this build can offload to, as a JSON array of+// {id, name, mem, free} with memory in MiB -- the same fields the old+// `llama-server --list-devices` stdout was parsed into, so the Rust and TS+// sides are unchanged. Needs no engine: ggml devices are process-global.+// Never NULL; free the result with jan_llama_string_free.+char * jan_llama_devices_json(void);++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_commit(void);++#ifdef __cplusplus+}+#endif+#endifdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rsdeleted file mode 100644index 5ec292ed8..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/backend.rs+++ /dev/null@@ -1,2510 +0,0 @@-use serde::{Deserialize, Serialize};-use std::collections::HashMap;-use std::fs;-use std::path::{Path, PathBuf};--#[tauri::command]-pub fn map_old_backend_to_new(old_backend: String) -> String {- let is_windows = old_backend.starts_with("win-");- // Official llama.cpp Linux assets use the `ubuntu-` prefix (e.g.- // `ubuntu-rocm-7.2-x64`); normalize them onto Jan's `linux-` scheme.- let is_linux = old_backend.starts_with("linux-") || old_backend.starts_with("ubuntu-");- let os_prefix = if is_windows {- "win-"- } else if is_linux {- "linux-"- } else {- ""- };-- // Determine architecture suffix, defaulting to x64- let arch_suffix = if old_backend.contains("-arm64") {- "arm64"- } else {- "x64"- };- let is_x64 = arch_suffix == "x64";-- // Handle GPU backends- if old_backend.contains("cuda-cu12.0") {- // Migration from e.g., 'linux-avx2-cuda-cu12.0-x64' to 'linux-cuda-12-common_cpus-x64'- return format!(- "{}cuda-12-common_cpus-{}",- os_prefix,- if is_x64 { "x64" } else { arch_suffix }- );- } else if old_backend.contains("cuda-cu11.7") {- // Migration from e.g., 'win-noavx-cuda-cu11.7-x64' to 'win-cuda-11-common_cpus-x64'- return format!(- "{}cuda-11-common_cpus-{}",- os_prefix,- if is_x64 { "x64" } else { arch_suffix }- );- } else if old_backend.contains("vulkan") {- // If it's already the new name, return it- if old_backend.contains("vulkan-common_cpus") {- return old_backend;- }-- // Migration from e.g., 'linux-vulkan-x64' to 'linux-vulkan-common_cpus-x64'- return format!(- "{}vulkan-common_cpus-{}",- os_prefix,- if is_x64 { "x64" } else { arch_suffix }- );- } else if old_backend.contains("hip") || old_backend.contains("rocm") {- // Canonicalize every HIP variant — Jan's own `*-hip-common_cpus-x64`- // and the official `ubuntu-rocm-*` / `win-hip-*` names — onto one id so- // listing, update checks and migration treat them as a single backend.- return format!(- "{}hip-common_cpus-{}",- os_prefix,- if is_x64 { "x64" } else { arch_suffix }- );- }-- // Handle CPU-only backends (avx, avx2, avx512, noavx)- let is_old_cpu_backend = old_backend.contains("avx512")- || old_backend.contains("avx2")- || old_backend.contains("avx-x64") // Check for 'avx' but not as part of 'avx2' or 'avx512'- || old_backend.contains("noavx-x64");-- if is_old_cpu_backend {- // Migration from e.g., 'win-avx512-x64' to 'win-common_cpus-x64'- return format!(- "{}common_cpus-{}",- os_prefix,- if is_x64 { "x64" } else { arch_suffix }- );- }-- // Return original if it doesn't match a pattern that needs migration- old_backend-}--#[derive(Serialize, Deserialize)]-pub struct InstalledBackend {- version: String,- backend: String,-}--#[tauri::command]-pub async fn get_local_installed_backends(- backends_dir: String,-) -> Result<Vec<InstalledBackend>, String> {- let mut local: Vec<InstalledBackend> = Vec::new();- let backends_path = PathBuf::from(&backends_dir);-- // Check if backends directory exists- if !backends_path.exists() {- return Ok(local);- }-- // Read version directories- let version_dirs = fs::read_dir(&backends_path)- .map_err(|e| format!("Failed to read backends directory: {}", e))?;-- for version_entry in version_dirs {- let version_entry =- version_entry.map_err(|e| format!("Failed to read version entry: {}", e))?;-- let version_path = version_entry.path();-- // Check if it's a directory- let metadata =- fs::metadata(&version_path).map_err(|e| format!("Failed to get metadata: {}", e))?;-- if !metadata.is_dir() {- continue;- }-- // Get version name from path- let version_name = match version_path.file_name() {- Some(name) => name.to_string_lossy().to_string(),- None => continue,- };-- // Read backend types in this version directory- let backend_types = fs::read_dir(&version_path)- .map_err(|e| format!("Failed to read version directory: {}", e))?;-- for backend_entry in backend_types {- let backend_entry =- backend_entry.map_err(|e| format!("Failed to read backend entry: {}", e))?;-- let backend_path = backend_entry.path();-- // Get backend name from path- let backend_name = match backend_path.file_name() {- Some(name) => name.to_string_lossy().to_string(),- None => continue,- };-- // Check if backend is actually installed- if is_backend_installed(&backend_path) {- local.push(InstalledBackend {- version: version_name.clone(),- backend: backend_name,- });- }- }- }-- Ok(local)-}--/// Helper function to check if a backend is properly installed-/// Checks for the existence of llama-server executable in the expected locations-fn is_backend_installed(backend_dir: &Path) -> bool {- if !backend_dir.exists() || !backend_dir.is_dir() {- return false;- }-- // Determine executable name based on platform- let exe_name = if cfg!(target_os = "windows") {- "llama-server.exe"- } else {- "llama-server"- };-- // First check if build directory exists (build/bin/llama-server)- let build_path = backend_dir.join("build").join("bin").join(exe_name);- if build_path.exists() {- return true;- }-- // Otherwise check root directory (llama-server)- let root_path = backend_dir.join(exe_name);- root_path.exists()-}--#[derive(Serialize, Deserialize, Clone)]-pub struct BackendInfo {- version: String,- backend: String,-}--#[derive(Deserialize)]-pub struct SystemFeatures {- cuda11: bool,- cuda12: bool,- cuda13: bool,- vulkan: bool,- #[serde(default)]- hip: bool,-}--#[derive(Serialize)]-#[allow(dead_code)]-pub struct SupportedBackendsResult {- supported_backend_names: Vec<String>,- merged_backends: Vec<BackendInfo>,-}--#[tauri::command]-pub fn determine_supported_backends(- os_type: String,- arch: String,- features: SystemFeatures,-) -> Result<Vec<String>, String> {- let sys_type = format!("{}-{}", os_type, arch);- let mut supported_backends: Vec<String> = Vec::new();-- // Determine supported backends based on system type and features- match sys_type.as_str() {- "windows-x86_64" => {- supported_backends.push("win-common_cpus-x64".to_string());- if features.cuda11 {- supported_backends.push("win-cuda-11-common_cpus-x64".to_string());- }- if features.cuda12 {- supported_backends.push("win-cuda-12-common_cpus-x64".to_string());- }- if features.cuda13 {- supported_backends.push("win-cuda-13-common_cpus-x64".to_string());- }- if features.vulkan {- supported_backends.push("win-vulkan-common_cpus-x64".to_string());- }- if features.hip {- supported_backends.push("win-hip-common_cpus-x64".to_string());- }- }- "windows-aarch64" | "windows-arm64" => {- supported_backends.push("win-arm64".to_string());- }- "linux-x86_64" | "linux-x86" => {- supported_backends.push("linux-common_cpus-x64".to_string());- if features.cuda11 {- supported_backends.push("linux-cuda-11-common_cpus-x64".to_string());- }- if features.cuda12 {- supported_backends.push("linux-cuda-12-common_cpus-x64".to_string());- }- if features.cuda13 {- supported_backends.push("linux-cuda-13-common_cpus-x64".to_string());- }- if features.vulkan {- supported_backends.push("linux-vulkan-common_cpus-x64".to_string());- }- if features.hip {- supported_backends.push("linux-hip-common_cpus-x64".to_string());- }- }- "linux-aarch64" | "linux-arm64" => {- supported_backends.push("linux-arm64".to_string());- }- "macos-x86_64" | "macos-x86" => {- supported_backends.push("macos-x64".to_string());- }- "macos-aarch64" | "macos-arm64" => {- supported_backends.push("macos-arm64".to_string());- }- _ => {- return Err(format!("Unsupported system type: {}", sys_type));- }- }-- Ok(supported_backends)-}--#[tauri::command]-pub async fn list_supported_backends(- remote_backend_versions: Vec<BackendInfo>,- local_backend_versions: Vec<BackendInfo>,-) -> Result<Vec<BackendInfo>, String> {- // Merge remote and local backend versions with deduplication- let mut merged_map: HashMap<String, BackendInfo> = HashMap::new();-- for entry in remote_backend_versions {- let key = format!("{}|{}", entry.version, entry.backend);- merged_map.insert(key, entry);- }-- for entry in local_backend_versions {- let key = format!("{}|{}", entry.version, entry.backend);- merged_map.insert(key, entry);- }-- // Convert to vector and sort- let mut merged: Vec<BackendInfo> = merged_map.into_values().collect();-- // Sort newest version first; if versions tie, sort by backend name- merged.sort_by(|a, b| {- let version_cmp = b.version.cmp(&a.version);- if version_cmp == std::cmp::Ordering::Equal {- a.backend.cmp(&b.backend)- } else {- version_cmp- }- });-- Ok(merged)-}--#[derive(Serialize, Deserialize)]-pub struct SupportedFeatures {- avx: bool,- avx2: bool,- avx512: bool,- cuda11: bool,- cuda12: bool,- cuda13: bool,- vulkan: bool,- hip: bool,-}--#[derive(Deserialize)]-pub struct GpuInfo {- driver_version: String,- #[serde(default)]- vendor: Option<String>,- nvidia_info: Option<NvidiaInfo>,- vulkan_info: Option<VulkanInfo>,-}--#[derive(Deserialize)]-pub struct NvidiaInfo {- #[allow(dead_code)]- compute_capability: String,-}--#[derive(Deserialize)]-pub struct VulkanInfo {- #[allow(dead_code)]- api_version: String,-}--#[tauri::command]-pub fn get_supported_features(- os_type: String,- cpu_extensions: Vec<String>,- gpus: Vec<GpuInfo>,-) -> Result<SupportedFeatures, String> {- let mut features = SupportedFeatures {- avx: cpu_extensions.contains(&"avx".to_string()),- avx2: cpu_extensions.contains(&"avx2".to_string()),- avx512: cpu_extensions.contains(&"avx512".to_string()),- cuda11: false,- cuda12: false,- cuda13: false,- vulkan: false,- hip: false,- };-- // https://docs.nvidia.com/deploy/cuda-compatibility/#cuda-11-and-later-defaults-to-minor-version-compatibility- let (min_cuda11_driver, min_cuda12_driver, min_cuda13_driver) = match os_type.as_str() {- "linux" => ("450.80.02", "525.60.13", "580"),- "windows" => ("452.39", "527.41", "580"),- _ => return Ok(features), // Other OS types support neither CUDA nor HIP- };-- // Check GPU features- for gpu_info in gpus {- let driver_version = &gpu_info.driver_version;-- // HIP (ROCm) is offered whenever an AMD GPU is present; missing ROCm- // runtime surfaces later at install/verify/launch.- if gpu_info.vendor.as_deref() == Some("AMD") {- features.hip = true;- }-- // Check CUDA support- if gpu_info.nvidia_info.is_some() {- if compare_versions(driver_version, min_cuda11_driver) >= 0 {- features.cuda11 = true;- }- if compare_versions(driver_version, min_cuda12_driver) >= 0 {- features.cuda12 = true;- }- if compare_versions(driver_version, min_cuda13_driver) >= 0 {- features.cuda13 = true;- }- }-- // Check Vulkan support- if gpu_info.vulkan_info.is_some() {- features.vulkan = true;- }- }-- Ok(features)-}--/// Compare version strings-/// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2-fn compare_versions(v1: &str, v2: &str) -> i32 {- let parts1: Vec<&str> = v1.split('.').collect();- let parts2: Vec<&str> = v2.split('.').collect();-- let max_len = parts1.len().max(parts2.len());-- for i in 0..max_len {- let num1 = parts1- .get(i)- .and_then(|s| s.parse::<u32>().ok())- .unwrap_or(0);- let num2 = parts2- .get(i)- .and_then(|s| s.parse::<u32>().ok())- .unwrap_or(0);-- match num1.cmp(&num2) {- std::cmp::Ordering::Less => return -1,- std::cmp::Ordering::Greater => return 1,- std::cmp::Ordering::Equal => continue,- }- }-- 0-}--#[tauri::command]-pub async fn is_cuda_installed(- backend_dir: String,- version: String,- os_type: String,- jan_data_folder_path: String,-) -> Result<bool, String> {- // Define library name lookup table- let mut libname_lookup: HashMap<String, &str> = HashMap::new();- libname_lookup.insert("windows-11.7".to_string(), "cudart64_110.dll");- libname_lookup.insert("windows-12.0".to_string(), "cudart64_12.dll");- libname_lookup.insert("windows-13.0".to_string(), "cudart64_13.dll");- libname_lookup.insert("linux-11.7".to_string(), "libcudart.so.11.0");- libname_lookup.insert("linux-12.0".to_string(), "libcudart.so.12");- libname_lookup.insert("linux-13.0".to_string(), "libcudart.so.13");-- let key = format!("{}-{}", os_type, version);-- // Check if the OS-version combination is supported- let libname = match libname_lookup.get(&key) {- Some(name) => *name,- None => return Ok(false),- };-- // Expected new location: backend_dir/build/bin/libname- let new_path = std::path::PathBuf::from(&backend_dir)- .join("build")- .join("bin")- .join(libname);-- if new_path.exists() {- return Ok(true);- }-- // Old location (used by older builds): jan_data_folder_path/llamacpp/lib/libname- let old_path = std::path::PathBuf::from(&jan_data_folder_path)- .join("llamacpp")- .join("lib")- .join(libname);-- if old_path.exists() {- // Ensure target directory exists- let target_dir = PathBuf::from(&backend_dir).join("build").join("bin");-- if !target_dir.exists() {- fs::create_dir_all(&target_dir)- .map_err(|e| format!("Failed to create target directory: {}", e))?;- }-- // Move old lib to the correct new location- match fs::rename(&old_path, &new_path) {- Ok(_) => {- log::info!("[CUDA] Migrated {} from old path to new location.", libname);- return Ok(true);- }- Err(err) => {- log::warn!("[CUDA] Failed to move old library: {}", err);- // Return false since the migration failed- return Ok(false);- }- }- }-- Ok(false)-}--#[derive(Serialize, Deserialize, Debug)]-pub struct BestBackendResult {- pub backend_string: String,- pub version: String,- pub backend_type: String,-}--#[derive(Serialize, Deserialize, Debug)]-pub struct UpdateCheckResult {- pub update_needed: bool,- pub new_version: String,- pub target_backend: Option<String>,-}--#[derive(Serialize, Deserialize, Debug)]-#[allow(dead_code)]-pub struct BackendConfigResult {- pub best_available: String,- pub effective_backend: String,- pub backend_downloaded: bool,- pub settings_updated: bool,-}--#[tauri::command]-pub fn find_latest_version_for_backend(- version_backends: Vec<BackendInfo>,- backend_type: String,-) -> Option<String> {- let mut matching_backends: Vec<BackendInfo> = version_backends- .into_iter()- .filter(|vb| map_old_backend_to_new(vb.backend.clone()) == backend_type)- .collect();-- if matching_backends.is_empty() {- return None;- }-- // Sort by version (newest first)- matching_backends.sort_by(|a, b| b.version.cmp(&a.version));-- // Return the full string including the original asset name- Some(format!(- "{}/{}",- matching_backends[0].version, matching_backends[0].backend- ))-}--#[tauri::command]-pub async fn prioritize_backends(- version_backends: Vec<BackendInfo>,- has_enough_gpu_memory: bool,-) -> Result<BestBackendResult, String> {- if version_backends.is_empty() {- return Err("No backends available".to_string());- }-- // Priority list based on GPU memory- let backend_priorities: Vec<&str> = if has_enough_gpu_memory {- vec![- "cuda-cu13.0",- "cuda-cu12.0",- "cuda-cu11.7",- "hip",- "vulkan",- "common_cpus",- "avx512",- "avx2",- "avx",- "noavx",- "arm64",- "x64",- ]- } else {- vec![- "common_cpus",- "avx512",- "avx2",- "avx",- "noavx",- "arm64",- "x64",- "hip",- "vulkan",- ]- };-- // Find best matching backend- for priority_category in backend_priorities {- let matching_backends: Vec<&BackendInfo> = version_backends- .iter()- .filter(|vb| {- let category = get_backend_category(&vb.backend);- category.as_deref() == Some(priority_category)- })- .collect();-- if !matching_backends.is_empty() {- let best = matching_backends[0];- log::info!(- "Determined best available backend: {}/{} (Category: \"{}\")",- best.version,- best.backend,- priority_category- );-- return Ok(BestBackendResult {- backend_string: format!("{}/{}", best.version, best.backend),- version: best.version.clone(),- backend_type: best.backend.clone(),- });- }- }-- // Fallback to newest version- let fallback = &version_backends[0];- log::info!("Fallback to: {}/{}", fallback.version, fallback.backend);-- Ok(BestBackendResult {- backend_string: format!("{}/{}", fallback.version, fallback.backend),- version: fallback.version.clone(),- backend_type: fallback.backend.clone(),- })-}--fn get_backend_category(backend_string: &str) -> Option<String> {- if backend_string.contains("cuda-13-common_cpus") {- return Some("cuda-cu13.0".to_string());- }- if backend_string.contains("cuda-12-common_cpus") || backend_string.contains("cu12.0") {- return Some("cuda-cu12.0".to_string());- }- if backend_string.contains("cuda-11-common_cpus") || backend_string.contains("cu11.7") {- return Some("cuda-cu11.7".to_string());- }- // HIP must precede the common_cpus/x64 checks: both Jan's own- // `*-hip-common_cpus-x64` and the official `ubuntu-rocm-*`/`win-hip-*` names- // would otherwise fall through to a CPU category.- if backend_string.contains("hip") || backend_string.contains("rocm") {- return Some("hip".to_string());- }- if backend_string.contains("vulkan") {- return Some("vulkan".to_string());- }- if backend_string.contains("common_cpus") {- return Some("common_cpus".to_string());- }- if backend_string.contains("avx512") {- return Some("avx512".to_string());- }- if backend_string.contains("avx2") {- return Some("avx2".to_string());- }- if backend_string.contains("avx")- && !backend_string.contains("avx2")- && !backend_string.contains("avx512")- {- return Some("avx".to_string());- }- if backend_string.contains("noavx") {- return Some("noavx".to_string());- }- if backend_string.ends_with("arm64") {- return Some("arm64".to_string());- }- if backend_string.ends_with("x64") {- return Some("x64".to_string());- }- None-}--#[tauri::command]-pub fn parse_backend_version(version_string: String) -> u32 {- // Remove any leading non-digit characters- let numeric = version_string.trim_start_matches(|c: char| !c.is_ascii_digit());- numeric.parse::<u32>().unwrap_or(0)-}--#[tauri::command]-pub async fn check_backend_for_updates(- current_backend_string: String,- version_backends: Vec<BackendInfo>,-) -> Result<UpdateCheckResult, String> {- let parts: Vec<&str> = current_backend_string.split('/').collect();- if parts.len() != 2 {- return Err(format!(- "Invalid current backend format: {}",- current_backend_string- ));- }-- let current_version = parts[0];- let current_backend = parts[1];-- // Get the effective/migrated backend type- let current_effective_backend_type = map_old_backend_to_new(current_backend.to_string());-- // Find the latest version for the current backend type- let target_backend_string =- find_latest_version_for_backend(version_backends, current_effective_backend_type.clone());-- if target_backend_string.is_none() {- log::warn!(- "No available versions found for current backend type: {}",- current_effective_backend_type- );- return Ok(UpdateCheckResult {- update_needed: false,- new_version: "0".to_string(),- target_backend: None,- });- }-- let target_backend_string = target_backend_string.unwrap();- let target_parts: Vec<&str> = target_backend_string.split('/').collect();- let latest_version = target_parts[0];-- // Check if update is needed- if parse_backend_version(latest_version.to_string())- > parse_backend_version(current_version.to_string())- {- log::info!(- "New update available: {} -> {}",- latest_version,- target_backend_string- );- Ok(UpdateCheckResult {- update_needed: true,- new_version: latest_version.to_string(),- target_backend: Some(target_backend_string),- })- } else {- log::info!(- "Already at latest version: {} = {}",- current_version,- latest_version- );- Ok(UpdateCheckResult {- update_needed: false,- new_version: "0".to_string(),- target_backend: None,- })- }-}--/// Prune installs of `backend_type`, always keeping `latest_version` and the-/// `keep_previous` newest versions below it. Those retained copies are what-/// makes a rollback possible without a re-download, so this must never be run-/// before a switch has proven itself.-///-/// Ordering is by parsed build number, not directory name: `b9100` must sort-/// above `b982`, which a lexical compare gets backwards.-#[tauri::command]-pub async fn remove_old_backend_versions(- backends_dir: String,- latest_version: String,- backend_type: String,- keep_previous: usize,-) -> Result<Vec<String>, String> {- let mut removed_paths = Vec::new();- let backends_path = PathBuf::from(&backends_dir);-- if !backends_path.exists() {- return Ok(removed_paths);- }-- let version_dirs = fs::read_dir(&backends_path)- .map_err(|e| format!("Failed to read backends directory: {}", e))?;-- let mut candidates: Vec<(u32, String, PathBuf)> = Vec::new();- for version_entry in version_dirs {- let version_entry =- version_entry.map_err(|e| format!("Failed to read version entry: {}", e))?;-- let version_path = version_entry.path();- let version_name = match version_path.file_name() {- Some(name) => name.to_string_lossy().to_string(),- None => continue,- };-- if version_name == latest_version {- continue;- }-- let backend_type_path = version_path.join(&backend_type);- if !backend_type_path.exists() || !is_backend_installed(&backend_type_path) {- continue;- }-- candidates.push((- parse_backend_version(version_name.clone()),- version_name,- backend_type_path,- ));- }-- // Newest first, name as a tiebreaker so unparseable versions (all 0) are- // still pruned deterministically.- candidates.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));-- if candidates.len() > keep_previous {- let retained: Vec<&str> = candidates- .iter()- .take(keep_previous)- .map(|(_, name, _)| name.as_str())- .collect();- log::info!(- "Pruning {} of {}: keeping active {} plus {:?}",- backend_type,- latest_version,- latest_version,- retained- );- }-- for (_, version_name, path) in candidates.into_iter().skip(keep_previous) {- match fs::remove_dir_all(&path) {- Ok(_) => {- log::info!(- "Removed old version {} of {}: {}",- version_name,- backend_type,- path.display()- );- removed_paths.push(path.to_string_lossy().to_string());- }- Err(e) => {- log::warn!(- "Failed to remove old backend version: {} - {}",- path.display(),- e- );- }- }- }-- Ok(removed_paths)-}--#[tauri::command]-pub fn validate_backend_string(backend_string: String) -> Result<(String, String), String> {- let parts: Vec<&str> = backend_string.split('/').collect();- if parts.len() != 2 {- return Err(format!("Invalid backend format: {}", backend_string));- }-- let version = parts[0].trim();- let backend = parts[1].trim();-- if version.is_empty() || backend.is_empty() {- return Err(format!("Invalid backend format: {}", backend_string));- }-- Ok((version.to_string(), backend.to_string()))-}--#[tauri::command]-pub fn should_migrate_backend(- stored_backend_type: String,- version_backends: Vec<BackendInfo>,-) -> Result<Option<String>, String> {- let mapped_new_backend_type = map_old_backend_to_new(stored_backend_type.clone());- let is_migration_needed = mapped_new_backend_type != stored_backend_type;-- if !is_migration_needed {- return Ok(None);- }-- // Check if the new, mapped backend is available- let is_new_type_available = version_backends- .iter()- .any(|vb| map_old_backend_to_new(vb.backend.clone()) == mapped_new_backend_type);-- if is_new_type_available {- log::info!(- "Migration needed from '{}' to '{}'",- stored_backend_type,- mapped_new_backend_type- );- Ok(Some(mapped_new_backend_type))- } else {- log::warn!(- "Migration from '{}' to '{}' skipped: New type not available",- stored_backend_type,- mapped_new_backend_type- );- Ok(None)- }-}--// ============================================================================-// Backend Path & Installation Commands-// ============================================================================--#[tauri::command]-pub fn get_backend_dir(backend: String, version: String, jan_data_folder: String) -> String {- PathBuf::from(&jan_data_folder)- .join("llamacpp")- .join("backends")- .join(&version)- .join(&backend)- .to_string_lossy()- .to_string()-}--#[tauri::command]-pub fn get_backend_exe_path(- backend: String,- version: String,- jan_data_folder: String,- is_windows: bool,-) -> String {- let backend_dir = PathBuf::from(get_backend_dir(backend, version, jan_data_folder));- let exe_name = if is_windows {- "llama-server.exe"- } else {- "llama-server"- };-- let build_path = backend_dir.join("build").join("bin").join(exe_name);- if build_path.exists() {- return build_path.to_string_lossy().to_string();- }-- backend_dir.join(exe_name).to_string_lossy().to_string()-}--#[tauri::command]-pub fn check_backend_installed(- backend: String,- version: String,- jan_data_folder: String,- is_windows: bool,-) -> bool {- let exe_path =- PathBuf::from(get_backend_exe_path(backend, version, jan_data_folder, is_windows));- exe_path.exists()-}--#[derive(Debug, Serialize, Deserialize)]-pub struct BackendVerificationResult {- pub verified: bool,- pub missing_libraries: Vec<String>,- pub resolved_libraries: Vec<String>,-}--fn gpu_backend_keyword(backend: &str) -> Option<&'static str> {- let b = backend.to_lowercase();- if b.contains("cuda") {- Some("cuda")- } else if b.contains("vulkan") {- Some("vulkan")- } else if b.contains("hip") || b.contains("rocm") {- // Seeds the dep scan with libggml-hip.*, which pulls in hipblas/rocblas.- Some("hip")- } else {- None- }-}--fn is_shared_lib_name(name: &str) -> bool {- let lower = name.to_lowercase();- if cfg!(target_os = "windows") {- lower.ends_with(".dll")- } else {- lower.ends_with(".so") || lower.contains(".so.")- }-}--fn find_gpu_libs(bin_dir: &Path, keyword: &str) -> Vec<PathBuf> {- let entries = match std::fs::read_dir(bin_dir) {- Ok(e) => e,- Err(_) => return Vec::new(),- };- let mut out = Vec::new();- for entry in entries.flatten() {- let path = entry.path();- if !path.is_file() {- continue;- }- let name = match path.file_name().and_then(|n| n.to_str()) {- Some(n) => n.to_lowercase(),- None => continue,- };- if name.contains(keyword) && is_shared_lib_name(&name) {- out.push(path);- }- }- out.sort();- out-}--fn verify_backend_dependencies(- bin_dir: &Path,- exe_path: &Path,- backend: &str,-) -> Result<BackendVerificationResult, crate::error::LlamacppError> {- if !bin_dir.exists() {- return Err(crate::error::LlamacppError::new(- crate::error::ErrorCode::BinaryNotFound,- "Backend directory not found".into(),- Some(bin_dir.to_string_lossy().to_string()),- ));- }-- let start = std::time::Instant::now();- let mut missing: std::collections::HashSet<String> = std::collections::HashSet::new();-- let paths: Vec<PathBuf> = if cfg!(target_os = "macos") {- Vec::new()- } else {- match gpu_backend_keyword(backend) {- Some(kw) => find_gpu_libs(bin_dir, kw),- None => Vec::new(),- }- };-- let _ = exe_path;-- // HIP/ROCm runtime libs (rocblas/hipblas/amdhip) live outside the backend- // dir in versioned roots like /opt/rocm-7.2.0/lib; add them so the scan- // doesn't false-flag them as missing.- let mut lib_dirs: Vec<PathBuf> = vec![bin_dir.to_path_buf()];- if gpu_backend_keyword(backend) == Some("hip") {- for p in jan_utils::find_rocm_paths().lib_paths {- lib_dirs.push(PathBuf::from(p));- }- }-- let analysis = crate::deps_analyzer::analyze_out_of_process(&lib_dirs, &paths);-- let resolved: std::collections::HashSet<String> = analysis.resolved.into_iter().collect();- for name in analysis.missing {- missing.insert(name);- }-- // A lib may be resolved by one binary but missing for another — keep only- // libs that no binary resolved.- let mut truly_missing: Vec<String> =- missing.difference(&resolved).cloned().collect();- let mut resolved_vec: Vec<String> = resolved.into_iter().collect();- truly_missing.sort();- resolved_vec.sort();-- let elapsed = start.elapsed();- log::info!(- "verify_backend_dependencies: scanned {} in {:.2}s ({} resolved, {} missing)",- bin_dir.display(),- elapsed.as_secs_f64(),- resolved_vec.len(),- truly_missing.len(),- );-- Ok(BackendVerificationResult {- verified: truly_missing.is_empty(),- missing_libraries: truly_missing,- resolved_libraries: resolved_vec,- })-}--#[tauri::command]-pub async fn verify_backend_installation(- backend: String,- version: String,- jan_data_folder: String,- is_windows: bool,-) -> Result<BackendVerificationResult, crate::error::LlamacppError> {- let exe_path =- PathBuf::from(get_backend_exe_path(backend.clone(), version.clone(), jan_data_folder.clone(), is_windows));- if !exe_path.exists() {- return Err(crate::error::LlamacppError::new(- crate::error::ErrorCode::BinaryNotFound,- "Backend executable not found".into(),- Some(exe_path.to_string_lossy().to_string()),- ));- }-- #[cfg(target_os = "linux")]- if jan_utils::system::is_flatpak() {- return Ok(BackendVerificationResult {- verified: true,- missing_libraries: Vec::new(),- resolved_libraries: Vec::new(),- });- }- // Libs sit next to the exe (build/bin/ when present); backend_dir is too high.- let bin_dir = exe_path- .parent()- .map(PathBuf::from)- .unwrap_or_else(|| PathBuf::from(get_backend_dir(backend.clone(), version, jan_data_folder)));- tokio::task::spawn_blocking(move || verify_backend_dependencies(&bin_dir, &exe_path, &backend))- .await- .map_err(|e| crate::error::LlamacppError::new(- crate::error::ErrorCode::InternalError,- "Dependency verification task panicked".into(),- Some(e.to_string()),- ))?-}--// ============================================================================-// Remote Backend Fetching-// ============================================================================--#[derive(Deserialize)]-struct GithubRelease {- tag_name: String,- assets: Vec<GithubAsset>,-}--#[derive(Deserialize)]-struct GithubAsset {- name: String,-}--/// Subset of the app's ProxyConfig needed to build a reqwest proxy. Kept local-/// to avoid a cross-crate dependency on the app crate. Shape must stay in sync-/// with the TS `getProxyConfig()` payload and the app's `ProxyConfig` struct.-#[derive(Deserialize, Clone, Debug)]-pub struct ProxyConfig {- pub url: String,- pub username: Option<String>,- pub password: Option<String>,- pub ignore_ssl: Option<bool>,-}--fn build_http_client(proxy: Option<&ProxyConfig>) -> Result<reqwest::Client, String> {- let mut builder = reqwest::Client::builder().user_agent("jan-app");-- if let Some(cfg) = proxy {- if !cfg.url.trim().is_empty() {- let mut p = reqwest::Proxy::all(&cfg.url)- .map_err(|e| format!("Invalid proxy URL: {}", e))?;- if let (Some(u), Some(pw)) = (&cfg.username, &cfg.password) {- if !u.is_empty() {- p = p.basic_auth(u, pw);- }- }- builder = builder.proxy(p);- if cfg.ignore_ssl.unwrap_or(false) {- builder = builder.danger_accept_invalid_certs(true);- }- }- }-- builder- .build()- .map_err(|e| format!("Failed to build HTTP client: {}", e))-}--#[tauri::command]-pub async fn fetch_remote_supported_backends(- supported_backends: Vec<String>,- proxy: Option<ProxyConfig>,-) -> Result<Vec<BackendInfo>, String> {- let client = build_http_client(proxy.as_ref())?;-- let releases: Vec<GithubRelease> = {- let primary = client- .get("https://api.github.com/repos/janhq/llama.cpp/releases")- .send()- .await;-- match primary {- Ok(resp) if resp.status().is_success() => resp- .json::<Vec<GithubRelease>>()- .await- .map_err(|e| format!("Failed to parse GitHub releases JSON: {}", e))?,- _ => {- // Fallback to catalog mirror- let fallback = client- .get("https://catalog.jan.ai/llama.cpp/releases/releases.json")- .send()- .await- .map_err(|e| format!("Both GitHub and fallback requests failed: {}", e))?;-- fallback- .json::<Vec<GithubRelease>>()- .await- .map_err(|e| format!("Failed to parse fallback releases JSON: {}", e))?- }- }- };-- // Take the first 10 (already sorted descending by tag_name from GitHub)- let mut result: Vec<BackendInfo> = Vec::new();- let mut sorted_releases = releases;- sorted_releases.sort_by(|a, b| b.tag_name.cmp(&a.tag_name));-- for release in sorted_releases.into_iter().take(10) {- let version = &release.tag_name;- for asset in &release.assets {- // Expected format: llama-{version}-bin-{backend}.tar.gz- let prefix = format!("llama-{}-bin-", version);- let suffix = ".tar.gz";- if asset.name.starts_with(&prefix) && asset.name.ends_with(suffix) {- let backend = asset.name[prefix.len()..asset.name.len() - suffix.len()].to_string();- let mapped = map_old_backend_to_new(backend.clone());- if supported_backends.contains(&backend) || supported_backends.contains(&mapped) {- result.push(BackendInfo {- version: version.clone(),- backend,- });- }- }- }- }-- Ok(result)-}--// ============================================================================-// Backend Download Item Builder-// ============================================================================--#[derive(Serialize, Deserialize)]-pub struct BackendDownloadItem {- pub url: String,- pub save_path: String,- pub model_id: String,-}--/// Internal helper: check if a CUDA runtime library is present at the new-/// location (`backend_dir/build/bin/{libname}`) without performing any-/// migration side-effects.-fn check_cuda_installed_internal(backend_dir: &str, cuda_version: &str, os_type: &str) -> bool {- let libname: &str = match (os_type, cuda_version) {- ("windows", "11.7") => "cudart64_110.dll",- ("windows", "12.0") => "cudart64_12.dll",- ("windows", "13.0") => "cudart64_13.dll",- ("linux", "11.7") => "libcudart.so.11.0",- ("linux", "12.0") => "libcudart.so.12",- ("linux", "13.0") => "libcudart.so.13",- _ => return false,- };-- PathBuf::from(backend_dir)- .join("build")- .join("bin")- .join(libname)- .exists()-}--#[tauri::command]-pub fn build_backend_download_items(- backend: String,- version: String,- source: String,- jan_data_folder: String,- os_type: String,-) -> Result<Vec<BackendDownloadItem>, String> {- let backend_dir = get_backend_dir(backend.clone(), version.clone(), jan_data_folder.clone());- let task_id = format!("llamacpp-{}-{}", version, backend).replace('.', "-");- let platform_name = if os_type == "windows" { "win" } else { "linux" };-- // Official Windows HIP assets ship as .zip (e.g. win-hip-radeon-x64.zip);- // Jan's own win-hip-common_cpus-x64 and all other backends are .tar.gz.- let archive_ext = if os_type == "windows"- && backend.contains("hip")- && !backend.contains("common_cpus")- {- "zip"- } else {- "tar.gz"- };-- // Base URL for the main backend archive- let backend_url = match source.as_str() {- "github" => format!(- "https://github.com/janhq/llama.cpp/releases/download/{}/llama-{}-bin-{}.{}",- version, version, backend, archive_ext- ),- _ => format!(- "https://catalog.jan.ai/llama.cpp/releases/{}/llama-{}-bin-{}.{}",- version, version, backend, archive_ext- ),- };-- let save_path = format!("{}/backend.{}", backend_dir, archive_ext);-- let mut items = vec![BackendDownloadItem {- url: backend_url,- save_path,- model_id: task_id.clone(),- }];-- // CUDA runtime items- if backend.contains("cu11.7") || backend.contains("cuda-11") {- let already_installed =- check_cuda_installed_internal(&backend_dir, "11.7", &os_type);- if !already_installed {- let cuda_url = match source.as_str() {- "github" => format!(- "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu11.7-x64.tar.gz",- version, platform_name- ),- _ => format!(- "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu11.7-x64.tar.gz",- version, platform_name- ),- };- items.push(BackendDownloadItem {- url: cuda_url,- save_path: format!("{}/build/bin/cuda11.tar.gz", backend_dir),- model_id: task_id.clone(),- });- }- } else if backend.contains("cu12.0") || backend.contains("cuda-12") {- let already_installed =- check_cuda_installed_internal(&backend_dir, "12.0", &os_type);- if !already_installed {- let cuda_url = match source.as_str() {- "github" => format!(- "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu12.0-x64.tar.gz",- version, platform_name- ),- _ => format!(- "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu12.0-x64.tar.gz",- version, platform_name- ),- };- items.push(BackendDownloadItem {- url: cuda_url,- save_path: format!("{}/build/bin/cuda12.tar.gz", backend_dir),- model_id: task_id.clone(),- });- }- } else if backend.contains("cuda-13") {- let already_installed =- check_cuda_installed_internal(&backend_dir, "13.0", &os_type);- if !already_installed {- let cuda_url = match source.as_str() {- "github" => format!(- "https://github.com/janhq/llama.cpp/releases/download/{}/cudart-llama-bin-{}-cu13.0-x64.tar.gz",- version, platform_name- ),- _ => format!(- "https://catalog.jan.ai/llama.cpp/releases/{}/cudart-llama-bin-{}-cu13.0-x64.tar.gz",- version, platform_name- ),- };- items.push(BackendDownloadItem {- url: cuda_url,- save_path: format!("{}/build/bin/cuda13.tar.gz", backend_dir),- model_id: task_id.clone(),- });- }- }-- Ok(items)-}--// ============================================================================-// Settings Update Handler-// ============================================================================--#[derive(Serialize, Deserialize, Debug)]-pub struct SettingUpdateResult {- pub backend_type_updated: bool,- pub effective_backend_type: Option<String>,- pub needs_backend_installation: bool,- pub version: Option<String>,- pub backend: Option<String>,-}--#[tauri::command]-pub fn handle_setting_update(- key: String,- value: String,- current_stored_backend: Option<String>,-) -> Result<SettingUpdateResult, String> {- if key != "version_backend" {- // For non-backend settings, return a simple result- return Ok(SettingUpdateResult {- backend_type_updated: false,- effective_backend_type: None,- needs_backend_installation: false,- version: None,- backend: None,- });- }-- // Handle version_backend update- let parts: Vec<&str> = value.split('/').collect();- if parts.len() != 2 {- return Err(format!("Invalid backend format: {}", value));- }-- let version = parts[0].to_string();- let backend = parts[1].to_string();-- if version.is_empty() || backend.is_empty() {- return Err(format!("Invalid backend format: {}", value));- }-- // Get the effective/migrated backend type- let effective_backend_type = map_old_backend_to_new(backend.clone());-- // Check if backend type changed- let backend_type_updated = match current_stored_backend {- Some(stored) => stored != effective_backend_type,- None => true,- };-- log::info!(- "Setting update for version_backend: {}/{} (effective: {})",- version,- backend,- effective_backend_type- );-- Ok(SettingUpdateResult {- backend_type_updated,- effective_backend_type: Some(effective_backend_type),- needs_backend_installation: true,- version: Some(version),- backend: Some(backend),- })-}--// ---------------------------- Tests --------------------------------------------#[cfg(test)]-mod tests {- use super::*;- use std::fs::File;- use std::io::Write;-- fn install_backend(root: &Path, version: &str, backend: &str) {- let dir = root.join(version).join(backend);- std::fs::create_dir_all(&dir).unwrap();- let exe = if cfg!(target_os = "windows") {- "llama-server.exe"- } else {- "llama-server"- };- File::create(dir.join(exe)).unwrap();- }-- fn versions_left(root: &Path, backend: &str) -> Vec<String> {- let mut v: Vec<String> = std::fs::read_dir(root)- .unwrap()- .filter_map(|e| e.ok())- .filter(|e| e.path().join(backend).exists())- .map(|e| e.file_name().to_string_lossy().to_string())- .collect();- v.sort();- v- }-- #[tokio::test]- async fn retention_keeps_the_active_version_and_n_previous() {- let dir = tempfile::tempdir().unwrap();- let root = dir.path();- for v in ["b900", "b1000", "b1100", "b1200"] {- install_backend(root, v, "cpu");- }-- let removed = remove_old_backend_versions(- root.to_string_lossy().to_string(),- "b1200".into(),- "cpu".into(),- 2,- )- .await- .unwrap();-- assert_eq!(removed.len(), 1);- assert_eq!(versions_left(root, "cpu"), vec!["b1000", "b1100", "b1200"]);- }-- #[tokio::test]- async fn retention_orders_by_build_number_not_lexically() {- let dir = tempfile::tempdir().unwrap();- let root = dir.path();- // Lexically "b982" > "b1100"; by build number it is older and must go.- for v in ["b982", "b1100", "b1200"] {- install_backend(root, v, "cpu");- }-- remove_old_backend_versions(- root.to_string_lossy().to_string(),- "b1200".into(),- "cpu".into(),- 1,- )- .await- .unwrap();-- assert_eq!(versions_left(root, "cpu"), vec!["b1100", "b1200"]);- }-- #[tokio::test]- async fn retention_never_removes_the_active_version() {- let dir = tempfile::tempdir().unwrap();- let root = dir.path();- install_backend(root, "b1000", "cpu");-- let removed = remove_old_backend_versions(- root.to_string_lossy().to_string(),- "b1000".into(),- "cpu".into(),- 0,- )- .await- .unwrap();-- assert!(removed.is_empty());- assert_eq!(versions_left(root, "cpu"), vec!["b1000"]);- }-- #[tokio::test]- async fn retention_ignores_other_backend_types() {- let dir = tempfile::tempdir().unwrap();- let root = dir.path();- install_backend(root, "b900", "cpu");- install_backend(root, "b900", "cuda");- install_backend(root, "b1000", "cpu");-- remove_old_backend_versions(- root.to_string_lossy().to_string(),- "b1000".into(),- "cpu".into(),- 0,- )- .await- .unwrap();-- // The cuda install under b900 survives; only its cpu sibling is pruned.- assert!(root.join("b900").join("cuda").exists());- assert!(!root.join("b900").join("cpu").exists());- }-- #[test]- fn digest_normalization_tolerates_producer_quirks() {- // Windows CertUtil output: uppercase, BOM, folded whitespace.- assert_eq!(normalize_digest("\u{feff}AB\n cd \r\n"), "abcd");- assert_eq!(normalize_digest(" abcd "), "abcd");- assert_eq!(normalize_digest(""), "");- // Non-hex noise cannot smuggle itself into a digest.- assert_eq!(normalize_digest("zz12zz"), "12");- }-- #[test]- fn checksum_manifest_parses_the_published_shape() {- let yaml = "version: b1234\nfiles:\n\- - url: llama-b1234-bin-linux-x64.tar.gz\n sha512: >-\n ABCD\n size: 10\n\- - url: cudart-llama-bin-linux-cu12.0-x64.tar.gz\n sha512: >-\n beef\n size: 20\n";- let m: ChecksumManifest = serde_yaml::from_str(yaml).unwrap();- assert_eq!(m.files.len(), 2);- assert_eq!(m.files[0].url, "llama-b1234-bin-linux-x64.tar.gz");- assert_eq!(normalize_digest(&m.files[0].sha512), "abcd");- }-- #[tokio::test]- async fn sha512_verification_accepts_and_rejects() {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("archive.tar.gz");- std::fs::write(&path, b"jan").unwrap();-- let actual = {- use sha2::{Digest, Sha512};- let mut h = Sha512::new();- h.update(b"jan");- format!("{:x}", h.finalize())- };- let p = path.to_string_lossy().to_string();-- assert!(verify_file_sha512(p.clone(), actual.to_uppercase())- .await- .unwrap());- assert!(!verify_file_sha512(p.clone(), "dead".repeat(32))- .await- .unwrap());- // No published digest means nothing to contradict.- assert!(verify_file_sha512(p.clone(), String::new()).await.unwrap());- // A malformed (too-short) digest is fail-soft, not a mismatch.- assert!(verify_file_sha512(p, "zz12zz".into()).await.unwrap());- }-- // --- Tests for map_old_backend_to_new ----- #[test]- fn test_map_old_backend_to_new_cuda() {- // Linux CUDA 12- assert_eq!(- map_old_backend_to_new("linux-avx2-cuda-cu12.0-x64".to_string()),- "linux-cuda-12-common_cpus-x64"- );- // Windows CUDA 11 (noavx)- assert_eq!(- map_old_backend_to_new("win-noavx-cuda-cu11.7-x64".to_string()),- "win-cuda-11-common_cpus-x64"- );- }-- #[test]- fn test_map_old_backend_to_new_vulkan() {- // Linux Vulkan- assert_eq!(- map_old_backend_to_new("linux-vulkan-x64".to_string()),- "linux-vulkan-common_cpus-x64"- );- // Already new format- assert_eq!(- map_old_backend_to_new("win-vulkan-common_cpus-x64".to_string()),- "win-vulkan-common_cpus-x64"- );- }-- #[test]- fn test_map_old_backend_to_new_cpu() {- // AVX512 migration- assert_eq!(- map_old_backend_to_new("win-avx512-x64".to_string()),- "win-common_cpus-x64"- );- // AVX2 migration- assert_eq!(- map_old_backend_to_new("linux-avx2-x64".to_string()),- "linux-common_cpus-x64"- );- }-- #[test]- fn test_map_old_backend_to_new_hip() {- // Official Linux ROCm asset → canonical Jan id- assert_eq!(- map_old_backend_to_new("ubuntu-rocm-7.2-x64".to_string()),- "linux-hip-common_cpus-x64"- );- // Official Windows HIP asset → canonical Jan id- assert_eq!(- map_old_backend_to_new("win-hip-radeon-x64".to_string()),- "win-hip-common_cpus-x64"- );- // Jan's own format is already canonical (idempotent)- assert_eq!(- map_old_backend_to_new("linux-hip-common_cpus-x64".to_string()),- "linux-hip-common_cpus-x64"- );- }-- #[test]- fn test_get_backend_category_hip() {- assert_eq!(- get_backend_category("linux-hip-common_cpus-x64").as_deref(),- Some("hip")- );- assert_eq!(- get_backend_category("ubuntu-rocm-7.2-x64").as_deref(),- Some("hip")- );- assert_eq!(- get_backend_category("win-hip-radeon-x64").as_deref(),- Some("hip")- );- }-- #[test]- fn test_map_old_backend_to_new_arch() {- // ARM64 detection- assert_eq!(- map_old_backend_to_new("linux-arm64".to_string()),- "linux-arm64" // Does not match specific migration patterns, returns original- );- }-- // --- Tests for compare_versions (Private helper) ----- #[test]- fn test_compare_versions() {- assert_eq!(compare_versions("1.0", "2.0"), -1);- assert_eq!(compare_versions("2.0", "1.0"), 1);- assert_eq!(compare_versions("1.0", "1.0"), 0);- assert_eq!(compare_versions("1.0.1", "1.0"), 1);- assert_eq!(compare_versions("450.80.02", "450.80.02"), 0);- assert_eq!(compare_versions("525.60.13", "450.80.02"), 1);- assert_eq!(compare_versions("10", "2"), 1); // Numeric check, not string- }-- // --- Tests for get_supported_features ----- #[test]- fn test_get_supported_features_cpu_only() {- let gpus = vec![];- let exts = vec!["avx".to_string(), "avx2".to_string()];-- let result = get_supported_features("linux".to_string(), exts, gpus).unwrap();-- assert!(result.avx);- assert!(result.avx2);- assert!(!result.avx512);- assert!(!result.cuda11);- assert!(!result.vulkan);- }-- #[test]- fn test_get_supported_features_cuda_linux() {- // Driver 525.60.13 supports CUDA 12 on Linux- let gpus = vec![GpuInfo {- driver_version: "530.00".to_string(),- vendor: Some("NVIDIA".to_string()),- nvidia_info: Some(NvidiaInfo {- compute_capability: "8.0".to_string(),- }),- vulkan_info: None,- }];-- let result = get_supported_features("linux".to_string(), vec![], gpus).unwrap();-- assert!(result.cuda11); // 530 > 450- assert!(result.cuda12); // 530 > 525- assert!(!result.cuda13); // 530 < 580- assert!(!result.hip); // NVIDIA GPU, no HIP- }-- #[test]- fn test_get_supported_features_vulkan() {- let gpus = vec![GpuInfo {- driver_version: "0.0".to_string(),- vendor: Some("Intel".to_string()),- nvidia_info: None,- vulkan_info: Some(VulkanInfo {- api_version: "1.3".to_string(),- }),- }];-- let result = get_supported_features("windows".to_string(), vec![], gpus).unwrap();-- assert!(result.vulkan);- assert!(!result.cuda11);- assert!(!result.hip); // Intel GPU, no HIP- }-- #[test]- fn test_get_supported_features_amd_hip() {- // AMD GPU exposes Vulkan but no CUDA; HIP should be offered alongside.- let gpus = vec![GpuInfo {- driver_version: "0.0".to_string(),- vendor: Some("AMD".to_string()),- nvidia_info: None,- vulkan_info: Some(VulkanInfo {- api_version: "1.3".to_string(),- }),- }];-- let linux = get_supported_features("linux".to_string(), vec![], gpus).unwrap();- assert!(linux.hip);- assert!(linux.vulkan);- assert!(!linux.cuda11);-- // macOS never offers HIP even with an AMD GPU.- let mac_gpus = vec![GpuInfo {- driver_version: "0.0".to_string(),- vendor: Some("AMD".to_string()),- nvidia_info: None,- vulkan_info: None,- }];- let mac = get_supported_features("macos".to_string(), vec![], mac_gpus).unwrap();- assert!(!mac.hip);- }-- // --- Tests for determine_supported_backends ----- #[test]- fn test_determine_supported_backends_windows_all() {- let features = SystemFeatures {- cuda11: true,- cuda12: true,- cuda13: false,- vulkan: true,- hip: true,- };-- let result =- determine_supported_backends("windows".to_string(), "x86_64".to_string(), features)- .unwrap();-- assert!(result.contains(&"win-common_cpus-x64".to_string()));- assert!(result.contains(&"win-cuda-11-common_cpus-x64".to_string()));- assert!(result.contains(&"win-cuda-12-common_cpus-x64".to_string()));- assert!(result.contains(&"win-vulkan-common_cpus-x64".to_string()));- assert!(result.contains(&"win-hip-common_cpus-x64".to_string()));- assert!(!result.contains(&"win-cuda-13-common_cpus-x64".to_string()));- }-- #[test]- fn test_determine_supported_backends_mac_arm() {- let features = SystemFeatures {- cuda11: false,- cuda12: false,- cuda13: false,- vulkan: false,- hip: false,- };-- let result =- determine_supported_backends("macos".to_string(), "arm64".to_string(), features)- .unwrap();-- assert_eq!(result.len(), 1);- assert_eq!(result[0], "macos-arm64");- }-- // --- Tests for list_supported_backends ----- #[tokio::test]- async fn test_list_supported_backends_sorting_and_dedup() {- let remote = vec![- BackendInfo {- version: "b7523".into(),- backend: "backend-a".into(),- },- BackendInfo {- version: "b7523".into(),- backend: "backend-b".into(),- },- ];-- let local = vec![- // Should override remote- BackendInfo {- version: "b7523".into(),- backend: "backend-a".into(),- },- // Newer version- BackendInfo {- version: "b7524".into(),- backend: "backend-c".into(),- },- ];-- let result = list_supported_backends(remote, local).await.unwrap();-- // Expect 3 items: b7524(c), b7523(a), b7523(b)- assert_eq!(result.len(), 3);-- // Check sorting: Version desc (b7524 > b7523)- assert_eq!(result[0].version, "b7524");- assert_eq!(result[1].version, "b7523");- assert_eq!(result[2].version, "b7523");-- // Check sorting: Backend asc for same version- // backend-a comes before backend-b- assert_eq!(result[1].backend, "backend-a");- assert_eq!(result[2].backend, "backend-b");- }-- // --- Tests for parse_backend_version ---- #[test]- fn test_parse_backend_version() {- assert_eq!(parse_backend_version("b7523".to_string()), 7523);- assert_eq!(parse_backend_version("b7524".to_string()), 7524);- assert_eq!(parse_backend_version("7525".to_string()), 7525);- assert_eq!(parse_backend_version("v100".to_string()), 100);- assert_eq!(parse_backend_version("invalid".to_string()), 0);- // Note: "v1.0.0" would fail to parse as u32 due to dots, returning 0- assert_eq!(parse_backend_version("v1.0.0".to_string()), 0);- }- // --- Filesystem Integration Tests ----- #[tokio::test]- async fn test_get_local_installed_backends() {- let temp_dir = tempfile::tempdir().unwrap();- let root = temp_dir.path();-- // Structure:- // root/- // b7523/- // backend-a/- // build/bin/llama-server (exe)- // backend-empty/ (no exe)-- let v1_path = root.join("b7523");- let backend_a = v1_path.join("backend-a");- let backend_empty = v1_path.join("backend-empty");-- fs::create_dir_all(backend_a.join("build").join("bin")).unwrap();- fs::create_dir_all(&backend_empty).unwrap();-- // Create mock executable- let exe_name = if cfg!(target_os = "windows") {- "llama-server.exe"- } else {- "llama-server"- };- File::create(backend_a.join("build").join("bin").join(exe_name)).unwrap();-- let result = get_local_installed_backends(root.to_string_lossy().to_string())- .await- .unwrap();-- assert_eq!(result.len(), 1);- assert_eq!(result[0].version, "b7523");- assert_eq!(result[0].backend, "backend-a");- }-- #[tokio::test]- async fn test_is_cuda_installed_migration() {- let backend_dir = tempfile::tempdir().unwrap();- let jan_data_dir = tempfile::tempdir().unwrap();-- let version = "12.0";- let os_type = "linux"; // Maps to libcudart.so.12-- // Setup Old Path: jan_data/llamacpp/lib/libcudart.so.12- let old_lib_dir = jan_data_dir.path().join("llamacpp").join("lib");- fs::create_dir_all(&old_lib_dir).unwrap();- let lib_name = "libcudart.so.12";- let old_file_path = old_lib_dir.join(lib_name);- {- let mut f = File::create(&old_file_path).unwrap();- f.write_all(b"dummy content").unwrap();- }-- // Run Check (should trigger migration)- let installed = is_cuda_installed(- backend_dir.path().to_string_lossy().to_string(),- version.to_string(),- os_type.to_string(),- jan_data_dir.path().to_string_lossy().to_string(),- )- .await- .unwrap();-- assert!(installed, "Should return true after migration");-- // Verify Migration- let new_path = backend_dir.path().join("build").join("bin").join(lib_name);- assert!(new_path.exists(), "File should exist in new location");- assert!(- !old_file_path.exists(),- "File should be removed from old location"- );- }-- #[tokio::test]- async fn test_is_cuda_installed_already_exists() {- let backend_dir = tempfile::tempdir().unwrap();- let jan_data_dir = tempfile::tempdir().unwrap(); // Empty-- let version = "11.7";- let os_type = "windows"; // Maps to cudart64_110.dll- let lib_name = "cudart64_110.dll";-- // Setup New Path directly- let target_dir = backend_dir.path().join("build").join("bin");- fs::create_dir_all(&target_dir).unwrap();- File::create(target_dir.join(lib_name)).unwrap();-- let installed = is_cuda_installed(- backend_dir.path().to_string_lossy().to_string(),- version.to_string(),- os_type.to_string(),- jan_data_dir.path().to_string_lossy().to_string(),- )- .await- .unwrap();-- assert!(installed);- }-- // --- Tests for find_latest_version_for_backend ----- #[test]- fn test_find_latest_version_for_backend() {- let backends = vec![- BackendInfo {- version: "b7523".into(),- backend: "linux-common_cpus-x64".into(),- },- BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(),- },- BackendInfo {- version: "b7522".into(),- backend: "linux-common_cpus-x64".into(),- },- ];-- let result = find_latest_version_for_backend(backends, "linux-common_cpus-x64".to_string());- assert_eq!(result, Some("b7524/linux-common_cpus-x64".to_string()));- }-- #[test]- fn test_find_latest_version_for_backend_with_migration() {- let backends = vec![- BackendInfo {- version: "b7523".into(),- backend: "linux-avx2-x64".into(), // Old format- },- BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(), // New format- },- ];-- // Both should map to linux-common_cpus-x64- let result = find_latest_version_for_backend(backends, "linux-common_cpus-x64".to_string());- assert_eq!(result, Some("b7524/linux-common_cpus-x64".to_string()));- }-- // --- Tests for check_backend_for_updates ----- #[tokio::test]- async fn test_check_backend_for_updates_needs_update() {- let current = "b7523/linux-common_cpus-x64".to_string();- let available = vec![- BackendInfo {- version: "b7523".into(),- backend: "linux-common_cpus-x64".into(),- },- BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(),- },- ];-- let result = check_backend_for_updates(current, available).await.unwrap();-- assert!(result.update_needed);- assert_eq!(result.new_version, "b7524");- assert_eq!(- result.target_backend,- Some("b7524/linux-common_cpus-x64".to_string())- );- }-- #[tokio::test]- async fn test_check_backend_for_updates_already_latest() {- let current = "b7524/linux-common_cpus-x64".to_string();- let available = vec![- BackendInfo {- version: "b7523".into(),- backend: "linux-common_cpus-x64".into(),- },- BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(),- },- ];-- let result = check_backend_for_updates(current, available).await.unwrap();-- assert!(!result.update_needed);- assert_eq!(result.new_version, "0");- assert_eq!(result.target_backend, None);- }-- // --- Tests for validate_backend_string ----- #[test]- fn test_validate_backend_string_valid() {- let result = validate_backend_string("b7524/linux-common_cpus-x64".to_string()).unwrap();- assert_eq!(result.0, "b7524");- assert_eq!(result.1, "linux-common_cpus-x64");- }-- #[test]- fn test_validate_backend_string_invalid() {- let result = validate_backend_string("invalid-format".to_string());- assert!(result.is_err());- }-- // --- Tests for should_migrate_backend ----- #[test]- fn test_should_migrate_backend_needs_migration() {- let old_backend = "linux-avx2-x64".to_string();- let available = vec![BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(),- }];-- let result = should_migrate_backend(old_backend, available).unwrap();- assert_eq!(result, Some("linux-common_cpus-x64".to_string()));- }-- #[test]- fn test_should_migrate_backend_no_migration_needed() {- let new_backend = "linux-common_cpus-x64".to_string();- let available = vec![BackendInfo {- version: "b7524".into(),- backend: "linux-common_cpus-x64".into(),- }];-- let result = should_migrate_backend(new_backend, available).unwrap();- assert_eq!(result, None);- }-- // -------------------------------------------------------------------------- // Tests for get_backend_dir- // --------------------------------------------------------------------------- #[test]- fn test_get_backend_dir_path_format() {- let result = get_backend_dir(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- "/home/user/.jan".to_string(),- );- assert!(result.contains("llamacpp"));- assert!(result.contains("backends"));- assert!(result.contains("b7523"));- assert!(result.contains("linux-common_cpus-x64"));- // Ensure the segments are in the right order- let path = PathBuf::from(&result);- let components: Vec<_> = path.components().collect();- let names: Vec<String> = components- .iter()- .map(|c| c.as_os_str().to_string_lossy().to_string())- .collect();- let llamacpp_idx = names.iter().position(|n| n == "llamacpp").unwrap();- let backends_idx = names.iter().position(|n| n == "backends").unwrap();- let version_idx = names.iter().position(|n| n == "b7523").unwrap();- let backend_idx = names.iter().position(|n| n == "linux-common_cpus-x64").unwrap();- assert!(llamacpp_idx < backends_idx);- assert!(backends_idx < version_idx);- assert!(version_idx < backend_idx);- }-- // -------------------------------------------------------------------------- // Tests for get_backend_exe_path- // --------------------------------------------------------------------------- #[test]- fn test_get_backend_exe_path_no_build_dir_linux() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let result = get_backend_exe_path(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data.clone(),- false,- );- // Should fall back to root dir (build dir doesn't exist)- assert!(result.ends_with("llama-server"));- assert!(!result.ends_with("llama-server.exe"));- }-- #[test]- fn test_get_backend_exe_path_no_build_dir_windows() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let result = get_backend_exe_path(- "win-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- true,- );- assert!(result.ends_with("llama-server.exe"));- }-- #[test]- fn test_get_backend_exe_path_with_build_dir() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- // Create the build/bin directory and place the exe there- let backend_dir = PathBuf::from(&jan_data)- .join("llamacpp")- .join("backends")- .join("b7523")- .join("linux-common_cpus-x64");- let build_bin = backend_dir.join("build").join("bin");- fs::create_dir_all(&build_bin).unwrap();- File::create(build_bin.join("llama-server")).unwrap();-- let result = get_backend_exe_path(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- false,- );- assert!(result.contains("build"));- assert!(result.contains("bin"));- assert!(result.ends_with("llama-server"));- }-- // -------------------------------------------------------------------------- // Tests for check_backend_installed- // --------------------------------------------------------------------------- #[test]- fn test_check_backend_installed_true() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let backend_dir = PathBuf::from(&jan_data)- .join("llamacpp")- .join("backends")- .join("b7523")- .join("linux-common_cpus-x64");- fs::create_dir_all(&backend_dir).unwrap();- File::create(backend_dir.join("llama-server")).unwrap();-- let result = check_backend_installed(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- false,- );- assert!(result);- }-- #[test]- fn test_check_backend_installed_false_when_missing() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let result = check_backend_installed(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- false,- );- assert!(!result);- }-- // -------------------------------------------------------------------------- // Tests for verify_backend_installation- // --------------------------------------------------------------------------- #[tokio::test]- async fn test_verify_backend_installation_returns_err_when_exe_missing() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let result = verify_backend_installation(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- false,- )- .await;-- assert!(result.is_err());- let err = result.unwrap_err();- assert!(matches!(err.code, crate::error::ErrorCode::BinaryNotFound));- }-- #[test]- fn test_verify_backend_dependencies_returns_err_on_missing_dir() {- let temp_dir = tempfile::tempdir().unwrap();- let nonexistent = temp_dir.path().join("does-not-exist");-- let exe = nonexistent.join("llama-server");- let result = verify_backend_dependencies(&nonexistent, &exe, "linux-common_cpus-x64");-- assert!(result.is_err());- let err = result.unwrap_err();- assert!(matches!(err.code, crate::error::ErrorCode::BinaryNotFound));- }-- #[test]- fn test_verify_backend_dependencies_skips_unparseable_files() {- let temp_dir = tempfile::tempdir().unwrap();- // An unparseable file in the dir should be silently skipped, not error.- fs::write(temp_dir.path().join("llama-server"), b"not a real binary").unwrap();- fs::write(temp_dir.path().join("libggml.so"), b"not a real binary").unwrap();-- let dir = temp_dir.path().to_path_buf();- let exe = dir.join("llama-server");- let result = verify_backend_dependencies(&dir, &exe, "linux-common_cpus-x64");-- // Succeeds with an empty result — nothing parseable, nothing missing.- assert!(result.is_ok());- let r = result.unwrap();- assert!(r.verified);- assert!(r.missing_libraries.is_empty());- }-- #[tokio::test]- async fn test_verify_backend_installation_scans_whole_backend_dir() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- // Create the backend dir with a stub exe and a stub DLL beside it.- let backend_dir = PathBuf::from(&jan_data)- .join("llamacpp")- .join("backends")- .join("b7523")- .join("linux-common_cpus-x64");- fs::create_dir_all(&backend_dir).unwrap();- fs::write(backend_dir.join("llama-server"), b"not a real binary").unwrap();- fs::write(backend_dir.join("libggml.so"), b"not a real binary").unwrap();-- // Both files are unparseable stubs — verify_backend_installation must- // return Ok (nothing missing) rather than Err, confirming it walks the- // whole directory and skips non-binaries rather than hard-failing.- let result = verify_backend_installation(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- jan_data,- false,- )- .await;- assert!(result.is_ok());- let r = result.unwrap();- assert!(r.verified);- }-- #[test]- fn test_is_virtual_windows_dll() {- assert!(crate::deps_analyzer::is_virtual_windows_dll("api-ms-win-core-memory-l1-1-0.dll"));- assert!(crate::deps_analyzer::is_virtual_windows_dll("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.DLL"));- assert!(crate::deps_analyzer::is_virtual_windows_dll("ext-ms-win-ntuser-draw-l1-1-0.dll"));- assert!(!crate::deps_analyzer::is_virtual_windows_dll("KERNEL32.dll"));- assert!(!crate::deps_analyzer::is_virtual_windows_dll("libcuda.so.1"));- assert!(!crate::deps_analyzer::is_virtual_windows_dll("libvulkan.so.1"));- }-- // -------------------------------------------------------------------------- // Tests for build_backend_download_items- // --------------------------------------------------------------------------- #[test]- fn test_build_backend_download_items_non_cuda_returns_one_item() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let items = build_backend_download_items(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- "github".to_string(),- jan_data,- "linux".to_string(),- )- .unwrap();-- assert_eq!(items.len(), 1);- assert!(items[0].url.contains("linux-common_cpus-x64"));- assert!(items[0].url.contains("github.com"));- }-- #[test]- fn test_build_backend_download_items_cuda12_returns_two_items() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let items = build_backend_download_items(- "linux-cuda-12-common_cpus-x64".to_string(),- "b7523".to_string(),- "github".to_string(),- jan_data,- "linux".to_string(),- )- .unwrap();-- assert_eq!(items.len(), 2);- assert!(items[1].url.contains("cu12.0"));- assert!(items[1].save_path.ends_with("cuda12.tar.gz"));- // All items must share the same model_id for unified progress tracking- assert_eq!(items[0].model_id, items[1].model_id);- }-- #[test]- fn test_build_backend_download_items_cu11_returns_two_items() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let items = build_backend_download_items(- "linux-cu11.7-common_cpus-x64".to_string(),- "b7523".to_string(),- "cdn".to_string(),- jan_data,- "linux".to_string(),- )- .unwrap();-- assert_eq!(items.len(), 2);- assert!(items[1].url.contains("cu11.7"));- assert!(items[1].save_path.ends_with("cuda11.tar.gz"));- // All items must share the same model_id for unified progress tracking- assert_eq!(items[0].model_id, items[1].model_id);- }-- #[test]- fn test_build_backend_download_items_github_vs_cdn_urls() {- let temp_dir = tempfile::tempdir().unwrap();- let jan_data = temp_dir.path().to_string_lossy().to_string();-- let github_items = build_backend_download_items(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- "github".to_string(),- jan_data.clone(),- "linux".to_string(),- )- .unwrap();-- let cdn_items = build_backend_download_items(- "linux-common_cpus-x64".to_string(),- "b7523".to_string(),- "cdn".to_string(),- jan_data,- "linux".to_string(),- )- .unwrap();-- assert!(github_items[0].url.contains("github.com"));- assert!(cdn_items[0].url.contains("catalog.jan.ai"));- assert_ne!(github_items[0].url, cdn_items[0].url);- }-}--// ============================================================================-// Release checksum verification-// ============================================================================--#[derive(Deserialize)]-struct ChecksumEntry {- url: String,- sha512: String,-}--#[derive(Deserialize)]-struct ChecksumManifest {- files: Vec<ChecksumEntry>,-}--/// Normalize a digest as published. The Windows job produces it via `CertUtil`-/// piped through `Out-File`, so it can arrive uppercase and carrying a BOM or-/// UTF-16 padding; the YAML folded scalar (`>-`) can also fold in whitespace.-/// Keeping only hex digits is the one rule that holds for every producer.-fn normalize_digest(raw: &str) -> String {- raw.chars()- .filter(|c| c.is_ascii_hexdigit())- .flat_map(|c| c.to_lowercase())- .collect()-}--/// Fetch `checksum.yml` for a release and return `filename -> sha512`.-///-/// Returns an empty map rather than an error when the manifest is absent or-/// unparseable: releases published before the manifest existed (and those-/// whose entries predate the `-bin-` naming fix) must stay installable.-#[tauri::command]-pub async fn fetch_backend_checksums(- version: String,- source: String,- proxy: Option<ProxyConfig>,-) -> Result<HashMap<String, String>, String> {- let url = if source == "cdn" {- format!(- "https://catalog.jan.ai/llama.cpp/releases/{}/checksum.yml",- version- )- } else {- format!(- "https://github.com/janhq/llama.cpp/releases/download/{}/checksum.yml",- version- )- };-- let client = build_http_client(proxy.as_ref())?;- let resp = match client.get(&url).send().await {- Ok(r) if r.status().is_success() => r,- Ok(r) => {- log::warn!("checksum.yml for {} returned HTTP {}", version, r.status());- return Ok(HashMap::new());- }- Err(e) => {- log::warn!("Could not fetch checksum.yml for {}: {}", version, e);- return Ok(HashMap::new());- }- };-- let body = match resp.text().await {- Ok(b) => b,- Err(e) => {- log::warn!("Could not read checksum.yml for {}: {}", version, e);- return Ok(HashMap::new());- }- };-- match serde_yaml::from_str::<ChecksumManifest>(&body) {- Ok(m) => Ok(m- .files- .into_iter()- .map(|f| (f.url, normalize_digest(&f.sha512)))- .filter(|(_, digest)| !digest.is_empty())- .collect()),- Err(e) => {- log::warn!("Could not parse checksum.yml for {}: {}", version, e);- Ok(HashMap::new())- }- }-}--/// Streams the file so a multi-GB archive is never held in memory.-#[tauri::command]-pub async fn verify_file_sha512(path: String, expected: String) -> Result<bool, String> {- let expected = normalize_digest(&expected);- if expected.is_empty() {- return Ok(true);- }- if expected.len() != 128 {- log::warn!("Malformed SHA-512 digest (expected 128 hex chars, got {}), skipping verification", expected.len());- return Ok(true);- }-- tokio::task::spawn_blocking(move || {- use sha2::{Digest, Sha512};- use std::io::Read;-- let mut file = fs::File::open(&path).map_err(|e| format!("{}: {}", path, e))?;- let mut hasher = Sha512::new();- let mut buf = vec![0u8; 1024 * 1024];- loop {- let n = file.read(&mut buf).map_err(|e| format!("{}: {}", path, e))?;- if n == 0 {- break;- }- hasher.update(&buf[..n]);- }- Ok(format!("{:x}", hasher.finalize()) == expected)- })- .await- .map_err(|e| format!("Checksum task panicked: {}", e))?-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rsnew file mode 100644index 000000000..c772e9fc0--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/bin/jan-llama-worker.rs@@ -0,0 +1,279 @@+//! The supervised llama.cpp worker.+//!+//! Statically linked, but in its own process on purpose. `GGML_ASSERT` calls+//! `abort()` unconditionally (`ggml/src/ggml.c`), and there are thousands of+//! assert sites plus every CUDA/Vulkan error path; `catch_unwind` cannot+//! contain any of them. Jan survives those today only because inference happens+//! in another process, and this preserves that while removing the *downloaded*+//! `llama-server` binary and the router's per-model subprocesses.+//!+//! Usage:+//! jan-llama-worker --preset <router.preset.ini> [--port N] [--models-max N]+//!+//! The bearer token comes from `JAN_LLAMA_API_KEY`, never argv: argv is+//! readable by any other process on the machine (`ps`, `/proc/<pid>/cmdline`,+//! Task Manager) and the supervisor logs it.+//!+//! Prints one line of JSON on stdout once it is listening, so the supervisor+//! learns the port without racing on a log file:+//! {"port":39271,"pid":1234,"models":["a","b"]}++use std::sync::Arc;++use tauri_plugin_llamacpp::engine::http::EngineServer;+use tauri_plugin_llamacpp::engine::preset;+use tauri_plugin_llamacpp::engine::registry::Registry;+use tauri_plugin_llamacpp::engine::slots::StateStore;+use tauri_plugin_llamacpp::engine::{assert_pinned_version, PINNED_TAG};+use tokio::sync::Mutex;++struct Args {+ preset: Option<String>,+ port: u16,+ models_max: usize,+ /// Ceiling on the saved-KV directory, in MiB. 0 turns cross-session KV+ /// persistence off entirely: the directory is what the feature is, so+ /// there is nothing to keep without a budget for it.+ slot_cache_mib: u64,+ /// Print the offloadable devices as JSON and exit. The desktop process+ /// links the plugin *without* the engine feature, so it has no ggml to ask+ /// -- it shells out here, exactly as it used to shell out to+ /// `llama-server --list-devices`.+ list_devices: bool,+}++/// Read from the environment rather than argv so the token never appears in a+/// process listing. Empty means "no auth", which is only sensible when the+/// caller owns the loopback port outright (tests).+const API_KEY_ENV: &str = "JAN_LLAMA_API_KEY";++fn parse_args() -> Result<Args, String> {+ let mut out = Args {+ preset: None,+ port: 0,+ models_max: 1,+ slot_cache_mib: 0,+ list_devices: false,+ };+ let mut it = std::env::args().skip(1);+ while let Some(flag) = it.next() {+ let mut value = || {+ it.next()+ .ok_or_else(|| format!("{flag} needs a value"))+ };+ match flag.as_str() {+ "--preset" => out.preset = Some(value()?),+ "--port" => {+ out.port = value()?.parse().map_err(|e| format!("bad --port: {e}"))?+ }+ "--models-max" => {+ out.models_max = value()?+ .parse()+ .map_err(|e| format!("bad --models-max: {e}"))?+ }+ "--slot-cache-mib" => {+ out.slot_cache_mib = value()?+ .parse()+ .map_err(|e| format!("bad --slot-cache-mib: {e}"))?+ }+ "--list-devices" => out.list_devices = true,+ "--version" => {+ println!("jan-llama-worker (llama.cpp {PINNED_TAG})");+ std::process::exit(0);+ }+ other => return Err(format!("unknown flag: {other}")),+ }+ }+ Ok(out)+}++#[tokio::main]+async fn main() {+ let args = match parse_args() {+ Ok(a) => a,+ Err(e) => {+ eprintln!("jan-llama-worker: {e}");+ std::process::exit(2);+ }+ };++ // A mismatched llama.cpp is memory corruption, not a link error:+ // common_params and llama_context_params cross the boundary by value and+ // their layout has changed repeatedly upstream.+ if let Err(e) = assert_pinned_version() {+ eprintln!("jan-llama-worker: {e}");+ std::process::exit(3);+ }++ // Must precede any ggml call, including device enumeration.+ tauri_plugin_llamacpp::engine::load_backend_modules();++ if args.list_devices {+ match tauri_plugin_llamacpp::engine::Engine::devices_json() {+ Ok(json) => println!("{json}"),+ Err(e) => {+ eprintln!("jan-llama-worker: could not list devices: {e}");+ std::process::exit(6);+ }+ }+ return;+ }++ let mut registry = Registry::new(args.models_max);+ let mut models = Vec::new();+ let mut slot_store = None;++ if let Some(path) = &args.preset {+ let ini = match std::fs::read_to_string(path) {+ Ok(s) => s,+ Err(e) => {+ eprintln!("jan-llama-worker: could not read {path}: {e}");+ std::process::exit(4);+ }+ };+ for (section, spec) in preset::specs(path, &ini) {+ registry.register(section.clone(), spec);+ models.push(section);+ }+ models.sort();++ // The directory has to exist before any model loads: llama.cpp's+ // --slot-save-path handler throws when it does not, and that unwinds+ // out of engine startup, so a missing cache directory would take local+ // inference down rather than disabling one feature.+ if let Some(dir) = preset::shared_value(&ini, "slot-save-path") {+ let store = StateStore::new(&dir, args.slot_cache_mib);+ if let Err(e) = store.ensure_dir() {+ eprintln!("jan-llama-worker: could not create {dir}: {e}");+ std::process::exit(7);+ }+ // Pruned here, not only on reload: a budget lowered (or zeroed)+ // between sessions must reclaim the disk it was lowered for, and+ // nothing else walks this directory at startup.+ let dropped = store.prune().len();+ if dropped > 0 {+ eprintln!("jan-llama-worker: pruned {dropped} saved thread cache(s)");+ }+ // Kept even at a zero budget: erasing a deleted thread's state and+ // clearing the directory both need the store, and neither writes.+ slot_store = Some(store);+ }+ }++ let registry = Arc::new(Mutex::new(registry));+ // Taken (not read) so it does not linger in this process's environment,+ // which is also readable via /proc on Linux.+ let api_key = std::env::var(API_KEY_ENV).unwrap_or_default();+ std::env::remove_var(API_KEY_ENV);++ let registry_for_teardown = Arc::clone(®istry);+ let (server, listener) =+ match EngineServer::bind(registry, args.port, api_key).await {+ Ok(v) => v,+ Err(e) => {+ eprintln!("jan-llama-worker: could not bind: {e}");+ std::process::exit(5);+ }+ };+ let server = match slot_store {+ Some(store) => {+ if store.saves_enabled() {+ eprintln!(+ "jan-llama-worker: keeping up to {} MiB of thread KV cache in {}",+ args.slot_cache_mib,+ store.dir().display()+ );+ } else {+ eprintln!(+ "jan-llama-worker: thread KV cache is off; keeping {} clear",+ store.dir().display()+ );+ }+ server.with_slot_state(store)+ }+ None => server,+ };++ // The supervisor reads this instead of scraping stderr, which is what the+ // router path had to do.+ println!(+ "{}",+ serde_json::json!({+ "port": server.port,+ "pid": std::process::id(),+ "models": models,+ })+ );+ // stdout is a pipe to the supervisor, so it is block-buffered.+ use std::io::Write;+ let _ = std::io::stdout().flush();++ let server = Arc::new(server);+ Arc::clone(&server)+ .serve_until(listener, shutdown_requested(), DRAIN_TIMEOUT)+ .await;++ // After draining, before releasing the models: the save reads each slot+ // through its still-live engine. Closing Jan is the common way a thread+ // stops being current, so without this the feature would only ever help+ // across a thread switch, not across a session.+ server.save_resident_slots().await;++ // Releasing the models here is the whole point of exiting in-band: each+ // Engine's Drop runs jan_llama_engine_stop, terminating its server_queue+ // loop and freeing the weights. A force-killed process skips all of that.+ let released = registry_for_teardown.lock().await.shutdown();+ if !released.is_empty() {+ eprintln!("jan-llama-worker: released {}", released.join(", "));+ }+}++/// How long in-flight requests get to finish once shutdown is requested.+const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);++/// Resolves when the supervisor asks us to stop.+///+/// The signal is **stdin reaching EOF**, which happens when the supervisor drops+/// its end of the pipe. Chosen over a signal because Windows has no deliverable+/// SIGTERM equivalent (`GenerateConsoleCtrlEvent(CTRL_C_EVENT)` requires process+/// group 0, which would take Jan down with it), and over an HTTP route because+/// process lifetime is not the transport's business -- and because only our+/// parent holds the write end, so it needs no authentication.+///+/// SIGTERM is still honoured on Unix so `kill` on a stuck worker behaves.+async fn shutdown_requested() {+ #[cfg(unix)]+ {+ use tokio::signal::unix::{signal, SignalKind};+ let mut term = match signal(SignalKind::terminate()) {+ Ok(s) => s,+ Err(e) => {+ eprintln!("jan-llama-worker: could not watch SIGTERM: {e}");+ stdin_eof().await;+ return;+ }+ };+ tokio::select! {+ _ = stdin_eof() => {}+ _ = term.recv() => {}+ }+ }+ #[cfg(not(unix))]+ stdin_eof().await;+}++async fn stdin_eof() {+ use tokio::io::AsyncReadExt;+ let mut stdin = tokio::io::stdin();+ let mut buf = [0u8; 64];+ loop {+ match stdin.read(&mut buf).await {+ // EOF: the supervisor closed the pipe.+ Ok(0) => return,+ // Nothing is expected to be written; ignore it rather than exiting,+ // so a stray byte cannot shut the engine down.+ Ok(_) => continue,+ Err(_) => return,+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rsindex af71ae938..d1137a250 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/cleanup.rs@@ -10,18 +10,19 @@ pub async fn cleanup_processes<R: Runtime>(app_handle: &tauri::AppHandle<R>) {return;}};- let maybe_handle = {- let mut guard = app_state.router.lock().await;+ // Unconditional: this is the last-chance path on RunEvent::Exit, so a+ // generation in flight is not a reason to leave the process behind.+ if let Some(watcher) = app_state.unload_watcher.lock().await.take() {+ watcher.abort();+ }+ let maybe_worker = {+ let mut guard = app_state.engine.lock().await;guard.take()};- if let Some(handle) = maybe_handle {- app_state- .router_pid- .store(0, std::sync::atomic::Ordering::SeqCst);- if let Err(e) = crate::router::stop_router(handle).await {- log::warn!("Failed to stop router during cleanup: {}", e);- }+ if let Some(worker) = maybe_worker {+ worker.stop().await;}+}#[tauri::command]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rsindex f3ebf721d..16f76fb8e 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs@@ -1,12 +1,10 @@use base64::{engine::general_purpose, Engine as _};use hmac::{Hmac, Mac};use sha2::Sha256;-use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;use tauri::{Emitter, Manager, Runtime, State};-use crate::device::{get_devices_from_backend, DeviceInfo};use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};use crate::state::{LlamacppState, SessionInfo};@@ -23,17 +21,22 @@ struct ModelRequestBody<'a> {model: &'a str,}-async fn router_endpoint<R: Runtime>(+/// The loopback endpoint every model-lifecycle command talks to.+///+/// One place resolves the worker, so `load_llama_model`, `unload_llama_model`,+/// `ensure_session_ready`, `find_session_by_model`, `get_loaded_models` and the+/// health probes all reach it the same way.+async fn engine_endpoint<R: Runtime>(app_handle: &tauri::AppHandle<R>,) -> Result<(u16, String, u32), String> {let state: State<Arc<LlamacppState>> = app_handle.state();- let guard = state.router.lock().await;- let h = guard.as_ref().ok_or_else(|| "router not started".to_string())?;+ let guard = state.engine.lock().await;+ let h = guard+ .as_ref()+ .ok_or_else(|| "no llama.cpp engine is running".to_string())?;Ok((h.port, h.api_key.clone(), h.pid))}-const ROUTER_HEALTH_TIMEOUT_SECS: u64 = 5;-async fn http_client() -> reqwest::Client {reqwest::Client::builder().timeout(Duration::from_secs(600))@@ -168,16 +171,28 @@ fn spawn_load_progress_listener<R: Runtime>(api_key: String,model_id: String,fail_tx: tokio::sync::oneshot::Sender<Option<i64>>,+ subscribed_tx: tokio::sync::oneshot::Sender<()>,) -> tokio::task::JoinHandle<()> {tokio::spawn(async move {use futures_util::StreamExt;+ // Fires on every exit from the connect, success or not, so a caller+ // waiting to be subscribed is never left waiting on a feed that will+ // not arrive.+ let mut subscribed_tx = Some(subscribed_tx);+ let mut announce = move || {+ if let Some(tx) = subscribed_tx.take() {+ let _ = tx.send(());+ }+ };+let client = http_client().await;let url = format!("http://127.0.0.1:{}/models/sse", port);let resp = match client.get(&url).bearer_auth(&api_key).send().await {Ok(r) => r,Err(e) => {log::debug!("model load progress: failed to connect to /models/sse: {}", e);+ announce();return;}};@@ -187,8 +202,12 @@ fn spawn_load_progress_listener<R: Runtime>(falling back to the plain loading indicator",resp.status());+ announce();return;}+ // Headers are in, so the server has already subscribed us: no+ // transition can be missed from here on.+ announce();let mut stream = resp.bytes_stream();let mut buf = String::new();@@ -219,117 +238,36 @@ fn spawn_load_progress_listener<R: Runtime>(})}-/// Payload for the `llamacpp-model-unloaded` event: any model transition to-/// `status: "unloaded"` seen on `/models/sse`, regardless of cause (explicit-/// unload, LRU eviction under `models_max`, or a crash - `exit_code` is 0 for-/// the first two, nonzero for a crash). Forwarded unconditionally; the-/// frontend already knows about unloads it requested itself, so reconciling-/// already-correct state is a harmless no-op.-#[derive(serde::Serialize, Clone)]-pub struct UnloadEventPayload {- pub model: String,- pub exit_code: Option<i64>,+/// The engine's own message out of the worker's `{"error":{...}}` envelope.+/// The HTTP status only says the load was refused; this is the part that names+/// the cause, and it is what the user needs to see.+fn engine_error_message(body: &str) -> Option<String> {+ let v: serde_json::Value = serde_json::from_str(body).ok()?;+ let msg = v+ .pointer("/error/message")+ .and_then(serde_json::Value::as_str)?+ .trim();+ (!msg.is_empty()).then(|| msg.to_string())}-/// Parses one SSE event block, returning an unload payload only for a-/// `status_change` event whose `data.status` is `"unloaded"`. `None` for any-/// other event/status or malformed input.-fn parse_unload_event(block: &str) -> Option<UnloadEventPayload> {- for line in block.lines() {- let data = line- .strip_prefix("data: ")- .or_else(|| line.strip_prefix("data:"))?;- let json: serde_json::Value = serde_json::from_str(data).ok()?;- if json.get("event").and_then(|v| v.as_str()) != Some("status_change") {- continue;- }- let model = json.get("model").and_then(|v| v.as_str())?;- let status = json- .get("data")- .and_then(|d| d.get("status"))- .and_then(|v| v.as_str())?;- if status != "unloaded" {- continue;- }- let exit_code = json- .get("data")- .and_then(|d| d.get("exit_code"))- .and_then(|v| v.as_i64());- return Some(UnloadEventPayload {- model: model.to_string(),- exit_code,- });- }- None+/// A refused `/models/load` reported as the engine failure it is: the code the+/// UI localizes comes from llama.cpp's own text, and `details` carries that+/// text verbatim rather than a bare status line.+fn load_rejection_error(status: u16, body: &str) -> LlamacppError {+ let reason = engine_error_message(body).unwrap_or_else(|| body.trim().to_string());+ let mut err = LlamacppError::from_load_failure(&reason);+ err.details = Some(if reason.is_empty() {+ format!("HTTP {status} from /models/load")+ } else {+ reason+ });+ err}-/// Subscribes to the router's `/models/sse` feed for the router's entire-/// lifetime, re-emitting every model-unload transition (explicit unload, LRU-/// eviction, crash) as `llamacpp-model-unloaded`. Unlike-/// `spawn_load_progress_listener` (per-model, aborted once loading finishes)-/// this runs continuously and reconnects with backoff on a dropped-/// connection, since the router process can outlive many individual loads.-///-/// `/models/sse` itself was introduced upstream in build b9688 (#23976); on-/// an older backend the initial connection succeeds at the TCP/HTTP layer-/// but the route 404s, so we give up permanently after the first failed-/// connection instead of retrying forever against a route that will never-/// exist. A transient connection error (router mid-restart) is retried with-/// exponential backoff instead, since that's recoverable.-fn spawn_unload_watcher<R: Runtime>(- app_handle: tauri::AppHandle<R>,- port: u16,- api_key: String,-) -> tokio::task::JoinHandle<()> {- tokio::spawn(async move {- use futures_util::StreamExt;-- let client = http_client().await;- let url = format!("http://127.0.0.1:{}/models/sse", port);- let mut backoff = Duration::from_millis(500);- const MAX_BACKOFF: Duration = Duration::from_secs(30);-- loop {- let resp = match client.get(&url).bearer_auth(&api_key).send().await {- Ok(r) => r,- Err(e) => {- log::debug!(- "model unload watcher: failed to connect to /models/sse: {}; retrying in {:?}",- e,- backoff- );- tokio::time::sleep(backoff).await;- backoff = (backoff * 2).min(MAX_BACKOFF);- continue;- }- };- if !resp.status().is_success() {- log::debug!(- "model unload watcher: /models/sse returned {} (backend predates b9688?); giving up",- resp.status()- );- return;- }- backoff = Duration::from_millis(500);-- let mut stream = resp.bytes_stream();- let mut buf = String::new();- while let Some(chunk) = stream.next().await {- let Ok(bytes) = chunk else { break };- buf.push_str(&String::from_utf8_lossy(&bytes));- while let Some(pos) = buf.find("\n\n") {- let event_block: String = buf.drain(..pos + 2).collect();- if let Some(payload) = parse_unload_event(&event_block) {- let _ = app_handle.emit("llamacpp-model-unloaded", payload);- }- }- }- // Stream ended (router restarted or connection dropped); briefly- // pause then reconnect.- tokio::time::sleep(Duration::from_millis(500)).await;- }- })-}+/// How long a load waits to be subscribed to `/models/sse` before giving up on+/// the feed. Generous enough for a loopback round trip, short enough that a+/// backend without the endpoint costs nothing noticeable.+const SUBSCRIBE_TIMEOUT: Duration = Duration::from_secs(2);async fn post_load<R: Runtime>(app_handle: &tauri::AppHandle<R>,@@ -337,6 +275,26 @@ async fn post_load<R: Runtime>(api_key: &str,model_id: &str,) -> ServerResult<()> {+ // Subscribed before the POST, not after: the engine answers `/models/load`+ // only once the load has finished, so a listener started afterwards would+ // join a stream on which every transition for this attempt has already+ // been sent.+ let (fail_tx, fail_rx) = tokio::sync::oneshot::channel();+ let (subscribed_tx, subscribed_rx) = tokio::sync::oneshot::channel();+ let progress_task = spawn_load_progress_listener(+ app_handle.clone(),+ port,+ api_key.to_string(),+ model_id.to_string(),+ fail_tx,+ subscribed_tx,+ );+ // Bounded: a backend without the feed still answers, but a hang here must+ // not become a hang in the load.+ if tokio::time::timeout(SUBSCRIBE_TIMEOUT, subscribed_rx).await.is_err() {+ log::debug!("/models/sse did not answer within {SUBSCRIBE_TIMEOUT:?}; loading anyway");+ }+let client = http_client().await;let url = format!("http://127.0.0.1:{}/models/load", port);let resp = client@@ -348,31 +306,29 @@ async fn post_load<R: Runtime>(.map_err(|e| {ServerError::Llamacpp(LlamacppError::new(ErrorCode::InternalError,- "Failed to call router /models/load".into(),+ "Failed to call the engine's /models/load".into(),Some(e.to_string()),))- })?;+ });+ let resp = match resp {+ Ok(r) => r,+ Err(e) => {+ progress_task.abort();+ return Err(e);+ }+ };let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();if !body.to_lowercase().contains("already") {- return Err(ServerError::Llamacpp(LlamacppError::new(- ErrorCode::InternalError,- format!("Router rejected model load (status {})", status),- Some(body),+ progress_task.abort();+ return Err(ServerError::Llamacpp(load_rejection_error(+ status.as_u16(),+ &body,)));}}- let (fail_tx, fail_rx) = tokio::sync::oneshot::channel();- let progress_task = spawn_load_progress_listener(- app_handle.clone(),- port,- api_key.to_string(),- model_id.to_string(),- fail_tx,- );-// Definitive failure signal from the SSE stream; pends forever if the// listener ends without one (older backend, dropped connection) so the// polling arm below always remains the fallback.@@ -383,12 +339,13 @@ async fn post_load<R: Runtime>(}};- // /models/load returns success once loading is *initiated*; poll /models- // until the entry transitions from "loading" to "loaded" (or fails).+ // The engine answers only once the load has finished, so this normally+ // resolves on the first poll. It stays as the fallback for the case where+ // the answer said "already loading" and someone else owns the attempt.let result = tokio::select! {r = wait_until_loaded(port, api_key, model_id, Duration::from_secs(600)) => r,exit_code = sse_failure => Err(ServerError::Llamacpp(LlamacppError::new(- ErrorCode::InternalError,+ ErrorCode::ModelLoadFailed,format!("Model {} failed to load", model_id),Some(format!("exit_code={:?}", exit_code)),))),@@ -506,7 +463,7 @@ async fn wait_until_loaded(LoadPoll::Pending => {}LoadPoll::Failed { exit_code } => {return Err(ServerError::Llamacpp(LlamacppError::new(- ErrorCode::InternalError,+ ErrorCode::ModelLoadFailed,format!("Model {} failed to load", model_id),Some(format!("exit_code={:?}", exit_code)),)));@@ -610,51 +567,7 @@ async fn wait_until_unloaded(}}-async fn unload_busy_router_models(port: u16, api_key: &str) -> Result<(), String> {- let client = http_client().await;- let list_url = format!("http://127.0.0.1:{}/models", port);- let resp = client- .get(&list_url)- .bearer_auth(api_key)- .send()- .await- .map_err(|e| e.to_string())?;- let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;- let data = json- .get("data")- .and_then(|d| d.as_array())- .cloned()- .unwrap_or_default();- let unload_url = format!("http://127.0.0.1:{}/models/unload", port);- for m in &data {- let Some(id) = m.get("id").and_then(|v| v.as_str()) else { continue };- let status = m- .get("status")- .and_then(|s| s.get("value"))- .and_then(|v| v.as_str())- .unwrap_or("unloaded");- if status.eq_ignore_ascii_case("unloaded") {- continue;- }- let body = serde_json::json!({ "model": id });- match client- .post(&unload_url)- .bearer_auth(api_key)- .json(&body)- .send()- .await- {- Ok(r) if r.status().is_success() => {- log::info!("OOM unload: {} ({})", id, status);- }- Ok(r) => log::warn!("OOM unload {} returned {}", id, r.status()),- Err(e) => log::warn!("OOM unload {} failed: {}", id, e),- }- }- Ok(())-}--async fn router_loaded_model_ids(port: u16, api_key: &str) -> Result<Vec<String>, String> {+async fn engine_loaded_model_ids(port: u16, api_key: &str) -> Result<Vec<String>, String> {// Router-aware listing: `/models` (not `/v1/models`, which is OAI-compat// and returns a single element). Each entry has a `status` object whose// `value` is one of "loaded" / "loading" / "unloaded" / "sleeping".@@ -702,7 +615,7 @@ pub async fn load_llama_model<R: Runtime>(model_id: String,is_embedding: bool,) -> ServerResult<SessionInfo> {- let (port, api_key, pid) = router_endpoint(&app_handle)+ let (port, api_key, pid) = engine_endpoint(&app_handle).await.map_err(ServerError::InvalidArgument)?;post_load(&app_handle, port, &api_key, &model_id).await?;@@ -720,7 +633,7 @@ pub async fn unload_llama_model<R: Runtime>(app_handle: tauri::AppHandle<R>,model_id: String,) -> ServerResult<UnloadResult> {- let (port, api_key, _pid) = router_endpoint(&app_handle)+ let (port, api_key, _pid) = engine_endpoint(&app_handle).await.map_err(ServerError::InvalidArgument)?;match post_unload(port, &api_key, &model_id).await {@@ -729,14 +642,6 @@ pub async fn unload_llama_model<R: Runtime>(}}-#[tauri::command]-pub async fn get_devices(- backend_path: &str,- envs: HashMap<String, String>,-) -> ServerResult<Vec<DeviceInfo>> {- get_devices_from_backend(backend_path, envs).await-}-#[tauri::command]pub fn generate_api_key(model_id: String, api_secret: String) -> Result<String, String> {let mut mac = HmacSha256::new_from_slice(api_secret.as_bytes())@@ -754,7 +659,7 @@ pub async fn ensure_session_ready<R: Runtime>(model_id: String,is_embedding: bool,) -> Result<SessionInfo, String> {- let (port, api_key, pid) = router_endpoint(&app_handle).await?;+ let (port, api_key, pid) = engine_endpoint(&app_handle).await?;post_load(&app_handle, port, &api_key, &model_id).await.map_err(|e| e.to_string())?;@@ -772,11 +677,11 @@ pub async fn find_session_by_model<R: Runtime>(app_handle: tauri::AppHandle<R>,model_id: String,) -> Result<Option<SessionInfo>, String> {- let (port, api_key, pid) = match router_endpoint(&app_handle).await {+ let (port, api_key, pid) = match engine_endpoint(&app_handle).await {Ok(v) => v,Err(_) => return Ok(None),};- let ids = router_loaded_model_ids(port, &api_key).await?;+ let ids = engine_loaded_model_ids(port, &api_key).await?;if ids.iter().any(|id| id == &model_id) {Ok(Some(SessionInfo {pid: pid as i32,@@ -794,343 +699,11 @@ pub async fn find_session_by_model<R: Runtime>(pub async fn get_loaded_models<R: Runtime>(app_handle: tauri::AppHandle<R>,) -> Result<Vec<String>, String> {- let (port, api_key, _pid) = match router_endpoint(&app_handle).await {+ let (port, api_key, _pid) = match engine_endpoint(&app_handle).await {Ok(v) => v,Err(_) => return Ok(Vec::new()),};- router_loaded_model_ids(port, &api_key).await-}--#[derive(serde::Serialize, serde::Deserialize, Clone)]-pub struct RouterInfo {- pub port: u16,- pub api_key: String,- pub pid: u32,-}--#[tauri::command]-#[allow(clippy::too_many_arguments)]-pub async fn start_router<R: Runtime>(- app_handle: tauri::AppHandle<R>,- backend_exe: String,- preset_path: String,- log_dir: String,- port: u16,- api_key: String,- models_max: u32,- default_args: Vec<String>,- envs: HashMap<String, String>,-) -> Result<RouterInfo, String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- let mut guard = state.router.lock().await;- if guard.is_some() {- return Err("Router is already running.".to_string());- }-- let on_error: Option<crate::router::ErrorCallback> = {- let app = app_handle.clone();- let err_port = port;- let err_api_key = api_key.clone();- Some(Arc::new(move |kind: &'static str, line: String| {- let event = match kind {- "oom" => "llamacpp-router-oom",- _ => "llamacpp-router-backend-error",- };- let _ = app.emit(event, line);- let port = err_port;- let api_key = err_api_key.clone();- tokio::spawn(async move {- if let Err(e) = unload_busy_router_models(port, &api_key).await {- log::warn!("router error unload sweep failed: {}", e);- }- });- }))- };-- let handle = crate::router::start_router(- std::path::PathBuf::from(backend_exe),- std::path::PathBuf::from(preset_path),- std::path::PathBuf::from(log_dir),- port,- api_key,- models_max,- default_args,- envs,- on_error,- )- .await- .map_err(|e| e.to_string())?;-- let info = RouterInfo {- port: handle.port,- api_key: handle.api_key.clone(),- pid: handle.pid,- };- state- .router_pid- .store(handle.pid, std::sync::atomic::Ordering::SeqCst);- *guard = Some(handle);-- let watcher = spawn_unload_watcher(app_handle.clone(), info.port, info.api_key.clone());- *state.unload_watcher.lock().await = Some(watcher);-- Ok(info)-}--/// Reuse a router that outlived its UI, or kill it if it no longer matches.-///-/// Returns the adopted endpoint, or `None` when the caller should spawn a-/// fresh router. `api_secret` is used to re-derive the router's key from the-/// port recorded in the lock file, so the key never has to be persisted.-#[tauri::command]-pub async fn adopt_router<R: Runtime>(- app_handle: tauri::AppHandle<R>,- backend_exe: String,- preset_path: String,- models_max: u32,- api_secret: String,-) -> Result<Option<RouterInfo>, String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- let mut guard = state.router.lock().await;- if guard.is_some() {- return Err("Router is already running.".to_string());- }-- let preset_path = std::path::PathBuf::from(preset_path);- let backend_exe = std::path::PathBuf::from(backend_exe);-- let Some(lock) = crate::router::read_lock(&preset_path) else {- return Ok(None);- };- let api_key = generate_api_key(format!("router{}", lock.port), api_secret)?;-- match crate::router::try_adopt_router(&preset_path, &backend_exe, models_max, api_key).await {- crate::router::AdoptOutcome::Adopted(handle) => {- let handle = *handle;- let info = RouterInfo {- port: handle.port,- api_key: handle.api_key.clone(),- pid: handle.pid,- };- state- .router_pid- .store(handle.pid, std::sync::atomic::Ordering::SeqCst);- *guard = Some(handle);-- // The SSE subscriber is a plain HTTP client, so it reattaches to an- // adopted router exactly as it would to one we spawned.- let watcher =- spawn_unload_watcher(app_handle.clone(), info.port, info.api_key.clone());- *state.unload_watcher.lock().await = Some(watcher);-- Ok(Some(info))- }- crate::router::AdoptOutcome::NothingToAdopt => Ok(None),- crate::router::AdoptOutcome::Killed(reason) => {- log::info!("Router not adopted ({}); caller will spawn a fresh one", reason);- Ok(None)- }- }-}--async fn stop_unload_watcher(state: &LlamacppState) {- if let Some(handle) = state.unload_watcher.lock().await.take() {- handle.abort();- }-}--#[tauri::command]-pub async fn stop_router<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- stop_unload_watcher(&state).await;- let mut guard = state.router.lock().await;- if let Some(handle) = guard.take() {- state- .router_pid- .store(0, std::sync::atomic::Ordering::SeqCst);- crate::router::stop_router(handle)- .await- .map_err(|e| e.to_string())?;- }- Ok(())-}--#[tauri::command]-pub async fn get_router_info<R: Runtime>(- app_handle: tauri::AppHandle<R>,-) -> Result<Option<RouterInfo>, String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- let guard = state.router.lock().await;- Ok(guard.as_ref().map(|h| RouterInfo {- port: h.port,- api_key: h.api_key.clone(),- pid: h.pid,- }))-}--/// 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()- ));- }-- // The process is now running the regenerated preset, so the hash recorded- // at spawn no longer describes it.- let state: State<Arc<LlamacppState>> = app_handle.state();- let preset_path = state- .router- .lock()- .await- .as_ref()- .map(|h| h.preset_path.clone());- if let Some(path) = preset_path {- crate::router::refresh_lock_preset_hash(&path);- }- Ok(())-}--/// Probe `GET /health`. With `port`/`api_key` omitted, targets the router this-/// process owns; supplying them probes an arbitrary endpoint (used to decide-/// whether a router surviving a UI crash is adoptable). Never errors -- an-/// unreachable or non-200 endpoint is simply not healthy.-///-/// The short timeout is deliberate: `http_client()`'s 600s budget is sized for-/// inference, but a health gate must fail fast enough to roll back.-#[tauri::command]-pub async fn router_health<R: Runtime>(- app_handle: tauri::AppHandle<R>,- port: Option<u16>,- api_key: Option<String>,-) -> Result<bool, String> {- let (port, api_key) = match (port, api_key) {- (Some(p), Some(k)) => (p, k),- _ => match router_endpoint(&app_handle).await {- Ok((p, k, _)) => (p, k),- Err(_) => return Ok(false),- },- };- let client = match reqwest::Client::builder()- .timeout(Duration::from_secs(ROUTER_HEALTH_TIMEOUT_SECS))- .build()- {- Ok(c) => c,- Err(_) => return Ok(false),- };- let url = format!("http://127.0.0.1:{}/health", port);- match client.get(&url).bearer_auth(&api_key).send().await {- Ok(resp) => Ok(resp.status().is_success()),- Err(e) => {- log::debug!("router health probe on port {} failed: {}", port, e);- Ok(false)- }- }-}--/// Best-effort idle check; returns `Ok(true)` on any error so callers-/// never block on a transient `/slots` failure.-#[tauri::command]-pub async fn router_slots_idle<R: Runtime>(- app_handle: tauri::AppHandle<R>,- model_id: Option<String>,-) -> Result<bool, String> {- let (port, api_key, _pid) = match router_endpoint(&app_handle).await {- Ok(r) => r,- Err(_) => return Ok(true),- };- let client = http_client().await;- let url = format!("http://127.0.0.1:{}/slots", port);- let mut req = client.get(&url).bearer_auth(&api_key);- if let Some(m) = model_id.as_deref() {- req = req.query(&[("model", m)]);- }- let resp = match req.send().await {- Ok(r) => r,- Err(_) => return Ok(true),- };- if !resp.status().is_success() {- return Ok(true);- }- let slots: Vec<serde_json::Value> = match resp.json().await {- Ok(v) => v,- Err(_) => return Ok(true),- };- Ok(slots.iter().all(|s| {- s.get("is_processing")- .and_then(|v| v.as_bool())- .map(|b| !b)- .unwrap_or(true)- }))-}--/// `Ok(Some(busy))` on deadline; handle is restored to state.-#[tauri::command]-pub async fn try_graceful_stop_router<R: Runtime>(- app_handle: tauri::AppHandle<R>,- deadline_secs: u64,-) -> Result<Option<Vec<String>>, String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- let maybe_handle = {- let mut guard = state.router.lock().await;- guard.take()- };- let Some(handle) = maybe_handle else {- return Ok(None);- };- match crate::router::try_graceful_stop_router(handle, Duration::from_secs(deadline_secs)).await {- Ok(()) => {- state- .router_pid- .store(0, std::sync::atomic::Ordering::SeqCst);- stop_unload_watcher(&state).await;- Ok(None)- }- Err((h, busy)) => {- let mut guard = state.router.lock().await;- *guard = Some(h);- Ok(Some(busy))- }- }-}--#[tauri::command]-pub async fn force_kill_router_tree<R: Runtime>(- app_handle: tauri::AppHandle<R>,-) -> Result<(), String> {- let state: State<Arc<LlamacppState>> = app_handle.state();- let pid = state- .router_pid- .swap(0, std::sync::atomic::Ordering::SeqCst);- let maybe_handle = {- let mut guard = state.router.lock().await;- guard.take()- };- stop_unload_watcher(&state).await;- match (maybe_handle, pid) {- (Some(handle), _) => crate::router::force_kill_router_tree(handle).await,- (None, p) if p != 0 => crate::router::force_kill_router_tree_by_pid(p),- _ => {}- }- Ok(())+ engine_loaded_model_ids(port, &api_key).await}#[cfg(test)]@@ -1385,84 +958,160 @@ mod load_progress_tests {}#[cfg(test)]-mod unload_watcher_tests {- use super::parse_unload_event;+mod load_rejection_tests {+ use super::{engine_error_message, load_rejection_error};+ use crate::error::ErrorCode;- fn sse_block(model: &str, event: &str, data: serde_json::Value) -> String {- let payload = serde_json::json!({ "model": model, "event": event, "data": data });- format!("data: {}\n\n", payload)+ fn envelope(message: &str) -> String {+ serde_json::json!({ "error": { "code": 400, "message": message } }).to_string()}#[test]- fn parses_an_unload_event_with_exit_code() {- let block = sse_block(- "model-1",- "status_change",- serde_json::json!({ "status": "unloaded", "exit_code": 137 }),+ fn reads_the_engine_message_out_of_the_envelope() {+ assert_eq!(+ engine_error_message(&envelope("failed to load model")).as_deref(),+ Some("failed to load model"));- let payload = parse_unload_event(&block).expect("should parse");- assert_eq!(payload.model, "model-1");- assert_eq!(payload.exit_code, Some(137));+ assert!(engine_error_message("not json").is_none());+ assert!(engine_error_message(&envelope(" ")).is_none());}+ // The whole point: a VRAM exhaustion has to reach the UI as OUT_OF_MEMORY,+ // not as INTERNAL_ERROR plus an HTTP status the user cannot act on.#[test]- fn parses_a_clean_unload_with_zero_exit_code() {- // LRU eviction / explicit unload: clean stop, exit_code 0.- let block = sse_block(- "model-1",- "status_change",- serde_json::json!({ "status": "unloaded", "exit_code": 0 }),+ fn a_cuda_oom_is_classified_and_keeps_the_engine_text() {+ let body = envelope(+ "could not start the llama.cpp engine: failed to load model; \+ ggml_backend_cuda_buffer_type_alloc_buffer: allocating 2375.91 MiB on device 0: \+ cudaMalloc failed: out of memory",);- let payload = parse_unload_event(&block).expect("should parse");- assert_eq!(payload.exit_code, Some(0));+ let err = load_rejection_error(400, &body);++ assert!(matches!(err.code, ErrorCode::OutOfMemory), "{:?}", err.code);+ let details = err.details.expect("details");+ assert!(details.contains("cudaMalloc failed: out of memory"), "{details}");+ assert!(!details.contains("400"), "{details}");}#[test]- fn ignores_non_unloaded_status() {- let block = sse_block(- "model-1",- "status_change",- serde_json::json!({ "status": "loading" }),+ fn an_unrecognized_reason_is_a_failed_load_not_an_internal_error() {+ let err = load_rejection_error(400, &envelope("no such preset: ghost"));++ assert!(matches!(err.code, ErrorCode::ModelLoadFailed), "{:?}", err.code);+ assert_eq!(err.details.as_deref(), Some("no such preset: ghost"));+ }++ #[test]+ fn a_bodyless_rejection_still_names_the_status() {+ let err = load_rejection_error(503, "");++ assert!(matches!(err.code, ErrorCode::ModelLoadFailed), "{:?}", err.code);+ assert_eq!(+ err.details.as_deref(),+ Some("HTTP 503 from /models/load"));- assert!(parse_unload_event(&block).is_none());+ }+}++/// The two sides of `/models/sse` in one place: what the worker serializes+/// (`engine::events`) against what the desktop parses. They are separate+/// modules with no shared type, so nothing but a test keeps them in step --+/// and a drift here is silent, costing every load its full 600s timeout+/// instead of an error.+#[cfg(test)]+mod sse_contract_tests {+ use super::{parse_load_progress_event, parse_load_status_change, LoadStatusChange};+ use crate::engine::events::{ModelEvent, Transition};++ fn frame(model: &str, status: Transition) -> String {+ ModelEvent {+ model: model.to_string(),+ status,+ }+ .to_sse_frame()}#[test]- fn ignores_non_status_change_events() {- let block = sse_block(- "model-1",- "model_remove",- serde_json::json!({}),+ fn the_parser_reads_every_transition_the_engine_emits() {+ assert_eq!(+ parse_load_status_change(&frame("m", Transition::Loading), "m"),+ Some(LoadStatusChange::Loading)+ );+ assert_eq!(+ parse_load_status_change(&frame("m", Transition::Loaded), "m"),+ Some(LoadStatusChange::Loaded)+ );+ assert_eq!(+ parse_load_status_change(&frame("m", Transition::Unloaded { exit_code: 1 }), "m"),+ Some(LoadStatusChange::Unloaded { exit_code: Some(1) })+ );+ assert_eq!(+ parse_load_status_change(&frame("m", Transition::Unloaded { exit_code: 0 }), "m"),+ Some(LoadStatusChange::Unloaded { exit_code: Some(0) }));- assert!(parse_unload_event(&block).is_none());}+ // Only a nonzero code fails the load; an eviction or a deliberate unload+ // must not be mistaken for this attempt's failure.#[test]- fn defaults_missing_exit_code_to_none() {- let block = sse_block(- "model-1",- "status_change",- serde_json::json!({ "status": "unloaded" }),+ fn only_a_nonzero_exit_code_reads_as_a_failure() {+ let failed = parse_load_status_change(&frame("m", Transition::Unloaded { exit_code: 1 }), "m");+ let evicted = parse_load_status_change(&frame("m", Transition::Unloaded { exit_code: 0 }), "m");++ assert!(matches!(+ failed,+ Some(LoadStatusChange::Unloaded { exit_code: Some(c) }) if c != 0+ ));+ assert!(matches!(+ evicted,+ Some(LoadStatusChange::Unloaded { exit_code: Some(0) })+ ));+ }++ #[test]+ fn another_models_transition_is_ignored() {+ assert_eq!(+ parse_load_status_change(&frame("other", Transition::Loading), "m"),+ None);- let payload = parse_unload_event(&block).expect("should parse");- assert_eq!(payload.exit_code, None);}+ // A lifecycle transition carries no fraction, so the parser must find+ // nothing rather than emitting a 0% event that would stall the bar.#[test]- fn ignores_malformed_json() {- let block = "data: not json\n\n".to_string();- assert!(parse_unload_event(&block).is_none());+ fn no_lifecycle_transition_carries_a_progress_payload() {+ for status in [+ Transition::Loading,+ Transition::Loaded,+ Transition::Unloaded { exit_code: 0 },+ ] {+ assert!(parse_load_progress_event(&frame("m", status), "m").is_none());+ }}+ // The two halves of the progress chain are written apart -- the engine+ // publishes the transition, the desktop parses the frame -- so this pins+ // that they still agree on the shape.#[test]- fn ignores_missing_status_field() {- let block = sse_block("model-1", "status_change", serde_json::json!({}));- assert!(parse_unload_event(&block).is_none());+ fn a_progress_transition_round_trips_to_a_payload() {+ let status = Transition::LoadProgress(serde_json::json!({+ "stages": ["text_model", "spec_model"],+ "current": "spec_model",+ "value": 0.75,+ }));+ let payload = parse_load_progress_event(&frame("m", status), "m")+ .expect("a progress payload");++ assert_eq!(payload.model, "m");+ assert_eq!(payload.value, 0.75);+ assert_eq!(payload.stage.as_deref(), Some("spec_model"));+ assert_eq!(payload.stages, vec!["text_model", "spec_model"]);}+ // Another model loading concurrently must not move this model's bar.#[test]- fn ignores_blocks_with_no_data_line() {- let block = "event: ping\n\n".to_string();- assert!(parse_unload_event(&block).is_none());+ fn a_progress_transition_for_another_model_is_ignored() {+ let status = Transition::LoadProgress(serde_json::json!({ "value": 0.5 }));+ assert!(parse_load_progress_event(&frame("other", status), "m").is_none());}}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rsdeleted file mode 100644index 39d1b2994..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/deps_analyzer.rs+++ /dev/null@@ -1,169 +0,0 @@-//! Out-of-process shared-library dependency analyzer. `lddtree`/`goblin` can-//! panic or segfault on malformed binaries; running it in a subprocess keeps-//! a crash from taking down the app.--use serde::{Deserialize, Serialize};-#[cfg(not(target_os = "macos"))]-use std::collections::HashSet;-use std::path::PathBuf;-#[cfg(not(target_os = "macos"))]-use std::process::{Command, Stdio};--pub const ANALYZE_FLAG: &str = "--internal-analyze-deps";--#[derive(Debug, Serialize, Deserialize, Default)]-pub struct AnalyzeOutput {- pub missing: Vec<String>,- pub resolved: Vec<String>,-}--// On macOS we never spawn the analyzer subprocess, so this is a no-op.-#[cfg(target_os = "macos")]-pub fn run_deps_analyzer_if_requested() {}--#[cfg(not(target_os = "macos"))]-pub fn run_deps_analyzer_if_requested() {- let mut args = std::env::args().skip(1);- if args.next().as_deref() != Some(ANALYZE_FLAG) {- return;- }-- // First arg is the platform-joined list of library search dirs (the- // backend's own dir plus any GPU runtime dirs, e.g. ROCm under /opt).- let lib_dirs: Vec<PathBuf> = match args.next() {- Some(d) => std::env::split_paths(&d).collect(),- None => {- eprintln!("{}: missing <lib_dirs> argument", ANALYZE_FLAG);- std::process::exit(2);- }- };- let targets: Vec<PathBuf> = args.map(PathBuf::from).collect();-- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- analyze(&lib_dirs, &targets)- }));-- match result {- Ok(out) => match serde_json::to_string(&out) {- Ok(s) => {- println!("{}", s);- std::process::exit(0);- }- Err(e) => {- eprintln!("serialize failed: {}", e);- std::process::exit(3);- }- },- Err(e) => {- let msg = e- .downcast_ref::<&str>()- .copied()- .or_else(|| e.downcast_ref::<String>().map(|s| s.as_str()))- .unwrap_or("unknown panic");- eprintln!("lddtree panic: {}", msg);- std::process::exit(4);- }- }-}--#[cfg(not(target_os = "macos"))]-fn analyze(lib_dirs: &[PathBuf], targets: &[PathBuf]) -> AnalyzeOutput {- let mut analyzer = lddtree::DependencyAnalyzer::default();- for dir in lib_dirs {- analyzer = analyzer.add_library_path(dir.to_path_buf());- }-- let mut missing: HashSet<String> = HashSet::new();- let mut resolved: HashSet<String> = HashSet::new();-- for path in targets {- let tree = match analyzer.clone().analyze(path) {- Ok(t) => t,- Err(_) => continue,- };- for (name, lib) in &tree.libraries {- if lib.found() {- resolved.insert(name.clone());- } else if !is_virtual_windows_dll(name) {- missing.insert(name.clone());- }- }- }-- let mut missing: Vec<String> = missing.into_iter().collect();- let mut resolved: Vec<String> = resolved.into_iter().collect();- missing.sort();- resolved.sort();- AnalyzeOutput { missing, resolved }-}--// api-ms-win-*/ext-ms-win-* are virtual DLLs resolved by the Windows kernel-// and never exist on disk — lddtree flags them as missing but they aren't.-pub(crate) fn is_virtual_windows_dll(name: &str) -> bool {- let lower = name.to_lowercase();- lower.starts_with("api-ms-win-") || lower.starts_with("ext-ms-win-")-}--// macOS resolves dynamic libraries via dyld at load time; lddtree's Mach-O-// handling is unreliable and has crashed in the field, so skip the analyzer.-#[cfg(target_os = "macos")]-pub fn analyze_out_of_process(_lib_dirs: &[PathBuf], _targets: &[PathBuf]) -> AnalyzeOutput {- AnalyzeOutput::default()-}--#[cfg(not(target_os = "macos"))]-pub fn analyze_out_of_process(lib_dirs: &[PathBuf], targets: &[PathBuf]) -> AnalyzeOutput {- let exe = match std::env::current_exe() {- Ok(p) => p,- Err(e) => {- log::warn!("deps_analyzer: current_exe failed: {}", e);- return AnalyzeOutput::default();- }- };-- let joined = match std::env::join_paths(lib_dirs) {- Ok(s) => s,- Err(e) => {- log::warn!("deps_analyzer: failed to join lib dirs: {}", e);- return AnalyzeOutput::default();- }- };-- let mut cmd = Command::new(&exe);- cmd.arg(ANALYZE_FLAG).arg(joined);- for t in targets {- cmd.arg(t);- }- cmd.stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped());-- let output = match cmd.output() {- Ok(o) => o,- Err(e) => {- log::warn!("deps_analyzer: failed to spawn subprocess: {}", e);- return AnalyzeOutput::default();- }- };-- if !output.status.success() {- log::warn!(- "deps_analyzer: subprocess exited with {:?}; stderr: {}",- output.status.code(),- String::from_utf8_lossy(&output.stderr).trim(),- );- return AnalyzeOutput::default();- }-- match serde_json::from_slice::<AnalyzeOutput>(&output.stdout) {- Ok(o) => o,- Err(e) => {- log::warn!(- "deps_analyzer: malformed subprocess output: {} (stdout: {})",- e,- String::from_utf8_lossy(&output.stdout).trim(),- );- AnalyzeOutput::default()- }- }-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rsdeleted file mode 100644index 5812c4c7c..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/device.rs+++ /dev/null@@ -1,425 +0,0 @@-use serde::{Deserialize, Serialize};-use std::collections::HashMap;-use std::process::Stdio;-use std::time::Duration;-use tokio::process::Command;-use tokio::time::timeout;--use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};-use crate::path::validate_binary_path;-use jan_utils::{- binary_requires_cuda, binary_requires_rocm, find_cuda_paths, find_rocm_paths,- setup_library_path, setup_windows_process_flags,-};--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct DeviceInfo {- pub id: String,- pub name: String,- pub mem: i32,- pub free: i32,-}--pub async fn get_devices_from_backend(- backend_path: &str,- envs: HashMap<String, String>,-) -> ServerResult<Vec<DeviceInfo>> {- log::info!("Getting devices from server at path: {:?}", backend_path);-- let bin_path = validate_binary_path(backend_path)?;-- // Configure the command to run the server with --list-devices- let mut command = Command::new(&bin_path);- command.arg("--list-devices");- command.envs(envs);-- command.stdout(Stdio::piped());- command.stderr(Stdio::piped());- setup_windows_process_flags(&mut command);-- let cuda = find_cuda_paths();- if cuda.lib_paths.is_empty() && cuda.bin_paths.is_empty() && binary_requires_cuda(&bin_path) {- log::warn!(- "llama.cpp backend appears to require CUDA, but CUDA not found. Process may fail to start. Please install cuda runtime and try again!"- );- }- let rocm = find_rocm_paths();- if rocm.lib_paths.is_empty() && rocm.bin_paths.is_empty() && binary_requires_rocm(&bin_path) {- log::warn!(- "llama.cpp backend appears to require ROCm/HIP, but ROCm not found. Process may fail to start. Please install the ROCm runtime and try again!"- );- }- setup_library_path(bin_path.parent(), &cuda.merged(rocm), &mut command);-- // Execute the command and wait for completion- let output = timeout(Duration::from_secs(30), command.output())- .await- .map_err(|_| {- LlamacppError::new(- ErrorCode::InternalError,- "Timeout waiting for device list".into(),- None,- )- })?- .map_err(ServerError::Io)?;-- // Check if command executed successfully- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- log::error!("llama-server --list-devices failed: {}", stderr);- return Err(LlamacppError::from_stderr(&stderr).into());- }- // Parse the output- let stdout = String::from_utf8_lossy(&output.stdout);- log::info!("Device list output:\n{}", stdout);-- parse_device_output(&stdout)-}--fn parse_device_output(output: &str) -> ServerResult<Vec<DeviceInfo>> {- let mut devices = Vec::new();- let mut found_devices_section = false;-- for raw in output.lines() {- // detect header (ignoring whitespace)- if raw.trim() == "Available devices:" {- found_devices_section = true;- continue;- }-- if !found_devices_section {- continue;- }-- // skip blank lines- if raw.trim().is_empty() {- continue;- }-- // now parse any non-blank line after the header- let line = raw.trim();- if let Some(device) = parse_device_line(line)? {- devices.push(device);- }- }-- if devices.is_empty() && found_devices_section {- log::warn!("No devices found in output");- } else if !found_devices_section {- return Err(LlamacppError::new(- ErrorCode::DeviceListParseFailed,- "Could not find 'Available devices:' section in the backend output.".into(),- Some(output.to_string()),- )- .into());- }-- Ok(devices)-}--fn parse_device_line(line: &str) -> ServerResult<Option<DeviceInfo>> {- let line = line.trim();-- log::info!("Parsing device line: '{}'", line);-- // Expected formats:- // "Vulkan0: Intel(R) Arc(tm) A750 Graphics (DG2) (8128 MiB, 8128 MiB free)"- // "CUDA0: NVIDIA GeForce RTX 4090 (24576 MiB, 24000 MiB free)"- // "SYCL0: Intel(R) Arc(TM) A750 Graphics (8000 MiB, 7721 MiB free)"-- // Split by colon to get ID and rest- let parts: Vec<&str> = line.splitn(2, ':').collect();- if parts.len() != 2 {- log::warn!("Skipping malformed device line: {}", line);- return Ok(None);- }-- let id = parts[0].trim().to_string();- let rest = parts[1].trim();-- // Use regex-like approach to find the memory pattern at the end- // Look for pattern: (number MiB, number MiB free) at the end- if let Some(memory_match) = find_memory_pattern(rest) {- let (memory_start, memory_content) = memory_match;- let name = rest[..memory_start].trim().to_string();-- // Parse memory info: "8128 MiB, 8128 MiB free"- let memory_parts: Vec<&str> = memory_content.split(',').collect();- if memory_parts.len() >= 2 {- if let (Ok(total_mem), Ok(free_mem)) = (- parse_memory_value(memory_parts[0].trim()),- parse_memory_value(memory_parts[1].trim()),- ) {- log::info!(- "Parsed device - ID: '{}', Name: '{}', Mem: {}, Free: {}",- id,- name,- total_mem,- free_mem- );-- return Ok(Some(DeviceInfo {- id,- name,- mem: total_mem,- free: free_mem,- }));- }- }- }-- log::warn!("Could not parse device line: {}", line);- Ok(None)-}--fn find_memory_pattern(text: &str) -> Option<(usize, &str)> {- // Find the last parenthesis that contains the memory pattern- let mut last_match = None;- let chars = text.char_indices();-- for (start_idx, ch) in chars {- if ch == '(' {- // Find the closing parenthesis- let remaining = &text[start_idx + 1..];- if let Some(close_pos) = remaining.find(')') {- let content = &remaining[..close_pos];-- // Check if this looks like memory info- if is_memory_pattern(content) {- last_match = Some((start_idx, content));- }- }- }- }-- last_match-}--fn is_memory_pattern(content: &str) -> bool {- // Check if content matches pattern like "8128 MiB, 8128 MiB free"- // Must contain: numbers, "MiB", comma, "free"- if !(content.contains("MiB") && content.contains("free") && content.contains(',')) {- return false;- }-- let parts: Vec<&str> = content.split(',').collect();- if parts.len() != 2 {- return false;- }-- parts.iter().all(|part| {- let part = part.trim();- // Each part should start with a number and contain "MiB"- part.split_whitespace()- .next()- .is_some_and(|first_word| first_word.parse::<i32>().is_ok())- && part.contains("MiB")- })-}--fn parse_memory_value(mem_str: &str) -> ServerResult<i32> {- // Handle formats like "8000 MiB" or "7721 MiB free"- let parts: Vec<&str> = mem_str.split_whitespace().collect();- if parts.is_empty() {- return Err(LlamacppError::new(- ErrorCode::DeviceListParseFailed,- format!("empty memory value: {}", mem_str),- None,- )- .into());- }-- // Take the first part which should be the number- let number_str = parts[0];- number_str.parse::<i32>().map_err(|_| {- LlamacppError::new(- ErrorCode::DeviceListParseFailed,- format!("Could not parse memory value: '{}'", number_str),- None,- )- .into()- })-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_is_memory_pattern_valid() {- assert!(is_memory_pattern("8128 MiB, 8128 MiB free"));- assert!(is_memory_pattern("1024 MiB, 512 MiB free"));- assert!(is_memory_pattern("16384 MiB, 12000 MiB free"));- assert!(is_memory_pattern("0 MiB, 0 MiB free"));- }-- #[test]- fn test_is_memory_pattern_invalid() {- assert!(!is_memory_pattern("8128 MB, 8128 MB free")); // Wrong unit- assert!(!is_memory_pattern("8128 MiB 8128 MiB free")); // Missing comma- assert!(!is_memory_pattern("8128 MiB, 8128 MiB used")); // Wrong second part- assert!(!is_memory_pattern("not_a_number MiB, 8128 MiB free")); // Invalid number- assert!(!is_memory_pattern("8128 MiB")); // Missing second part- assert!(!is_memory_pattern("")); // Empty string- assert!(!is_memory_pattern("8128 MiB, free")); // Missing number in second part- }-- #[test]- fn test_find_memory_pattern() {- let text = "Intel(R) Arc(tm) A750 Graphics (DG2) (8128 MiB, 4096 MiB free)";- let result = find_memory_pattern(text);- assert!(result.is_some());- let (start_idx, content) = result.unwrap();- assert!(start_idx > 0);- assert_eq!(content, "8128 MiB, 4096 MiB free");- }-- #[test]- fn test_find_memory_pattern_multiple_parentheses() {- let text = "Device (test) with (1024 MiB, 512 MiB free) and (2048 MiB, 1024 MiB free)";- let result = find_memory_pattern(text);- assert!(result.is_some());- let (_, content) = result.unwrap();- // Should return the LAST valid memory pattern- assert_eq!(content, "2048 MiB, 1024 MiB free");- }-- #[test]- fn test_find_memory_pattern_no_match() {- let text = "No memory info here";- assert!(find_memory_pattern(text).is_none());-- let text_with_invalid = "Some text (invalid memory info) here";- assert!(find_memory_pattern(text_with_invalid).is_none());- }-- #[test]- fn test_parse_memory_value() {- assert_eq!(parse_memory_value("8128 MiB").unwrap(), 8128);- assert_eq!(parse_memory_value("7721 MiB free").unwrap(), 7721);- assert_eq!(parse_memory_value("0 MiB").unwrap(), 0);- assert_eq!(parse_memory_value("24576 MiB").unwrap(), 24576);- }-- #[test]- fn test_parse_memory_value_invalid() {- assert!(parse_memory_value("").is_err());- assert!(parse_memory_value("not_a_number MiB").is_err());- assert!(parse_memory_value(" ").is_err());- }-- #[test]- fn test_parse_device_line_vulkan() {- let line = "Vulkan0: Intel(R) Arc(tm) A750 Graphics (DG2) (8128 MiB, 8128 MiB free)";- let result = parse_device_line(line).unwrap();- assert!(result.is_some());- let device = result.unwrap();- assert_eq!(device.id, "Vulkan0");- assert_eq!(device.name, "Intel(R) Arc(tm) A750 Graphics (DG2)");- assert_eq!(device.mem, 8128);- assert_eq!(device.free, 8128);- }-- #[test]- fn test_parse_device_line_cuda() {- let line = "CUDA0: NVIDIA GeForce RTX 4090 (24576 MiB, 24000 MiB free)";- let result = parse_device_line(line).unwrap();- assert!(result.is_some());- let device = result.unwrap();- assert_eq!(device.id, "CUDA0");- assert_eq!(device.name, "NVIDIA GeForce RTX 4090");- assert_eq!(device.mem, 24576);- assert_eq!(device.free, 24000);- }-- #[test]- fn test_parse_device_line_sycl() {- let line = "SYCL0: Intel(R) Arc(TM) A750 Graphics (8000 MiB, 7721 MiB free)";- let result = parse_device_line(line).unwrap();- assert!(result.is_some());- let device = result.unwrap();- assert_eq!(device.id, "SYCL0");- assert_eq!(device.name, "Intel(R) Arc(TM) A750 Graphics");- assert_eq!(device.mem, 8000);- assert_eq!(device.free, 7721);- }-- #[test]- fn test_parse_device_line_malformed() {- // Missing colon- let result = parse_device_line("Vulkan0 Intel Graphics (8128 MiB, 8128 MiB free)").unwrap();- assert!(result.is_none());-- // Missing memory info- let result = parse_device_line("Vulkan0: Intel Graphics").unwrap();- assert!(result.is_none());-- // Invalid memory format- let result = parse_device_line("Vulkan0: Intel Graphics (invalid memory)").unwrap();- assert!(result.is_none());- }-- #[test]- fn test_parse_device_output_valid() {- let output = r#"-Some header text-Available devices:-Vulkan0: Intel(R) Arc(tm) A750 Graphics (DG2) (8128 MiB, 8128 MiB free)-CUDA0: NVIDIA GeForce RTX 4090 (24576 MiB, 24000 MiB free)--SYCL0: Intel(R) Arc(TM) A750 Graphics (8000 MiB, 7721 MiB free)-Some footer text-"#;-- let result = parse_device_output(output).unwrap();- assert_eq!(result.len(), 3);-- assert_eq!(result[0].id, "Vulkan0");- assert_eq!(result[0].name, "Intel(R) Arc(tm) A750 Graphics (DG2)");- assert_eq!(result[0].mem, 8128);-- assert_eq!(result[1].id, "CUDA0");- assert_eq!(result[1].name, "NVIDIA GeForce RTX 4090");- assert_eq!(result[1].mem, 24576);-- assert_eq!(result[2].id, "SYCL0");- assert_eq!(result[2].name, "Intel(R) Arc(TM) A750 Graphics");- assert_eq!(result[2].mem, 8000);- }-- #[test]- fn test_parse_device_output_no_devices_section() {- let output = "Some output without Available devices section";- let result = parse_device_output(output);- assert!(result.is_err());- }-- #[test]- fn test_parse_device_output_empty_devices() {- let output = r#"-Some header text-Available devices:--Some footer text-"#;- let result = parse_device_output(output).unwrap();- assert_eq!(result.len(), 0);- }-- #[test]- fn test_parse_device_output_mixed_valid_invalid() {- let output = r#"-Available devices:-Vulkan0: Intel(R) Arc(tm) A750 Graphics (DG2) (8128 MiB, 8128 MiB free)-InvalidLine: No memory info-CUDA0: NVIDIA GeForce RTX 4090 (24576 MiB, 24000 MiB free)-AnotherInvalid-"#;-- let result = parse_device_output(output).unwrap();- assert_eq!(result.len(), 2); // Only valid lines should be parsed-- assert_eq!(result[0].id, "Vulkan0");- assert_eq!(result[1].id, "CUDA0");- }-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rsnew file mode 100644index 000000000..9c9af5c0b--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs@@ -0,0 +1,548 @@+//! Tauri commands for the engine worker.++use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::Arc;++use rand::Rng;+use serde::{Deserialize, Serialize};+use tauri::{Manager, State};++use super::worker::{self, WorkerHandle};+use crate::state::LlamacppState;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EngineInfo {+ pub port: u16,+ pub api_key: String,+ pub pid: u32,+ /// Registered model ids, from the preset the worker read.+ pub models: Vec<String>,+}++impl From<&WorkerHandle> for EngineInfo {+ fn from(h: &WorkerHandle) -> Self {+ Self {+ port: h.port,+ api_key: h.api_key.clone(),+ pid: h.pid,+ models: h.models.clone(),+ }+ }+}++/// 32 bytes of OS randomness, hex-encoded. Not derived from the port the way+/// the router's key was: the worker's port is assigned by the OS, and a key any+/// other local process could recompute is not much of a key.+fn generate_worker_key() -> String {+ let bytes: [u8; 32] = rand::thread_rng().gen();+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++/// Resolves the worker binary: an explicit override first (dev builds and+/// tests), then the sidecar next to the running executable.+/// Locates the engine worker binary.+///+/// Order: the dev/CI override, then the bundle's `resources/bin` (where+/// packaging puts it, alongside the ggml backend modules the worker loads by+/// scanning its own directory), then beside the app executable for a+/// `cargo run` build.+fn resolve_worker_exe<R: tauri::Runtime>(+ app_handle: &tauri::AppHandle<R>,+) -> Result<PathBuf, String> {+ if let Some(p) = std::env::var_os("JAN_LLAMA_WORKER_BIN") {+ let p = PathBuf::from(p);+ if p.is_file() {+ return Ok(p);+ }+ return Err(format!(+ "JAN_LLAMA_WORKER_BIN points at {}, which is not a file",+ p.display()+ ));+ }++ if let Ok(dir) = app_handle.path().resource_dir() {+ let bundled = dir.join("resources/bin").join(worker::worker_file_name());+ if bundled.is_file() {+ return Ok(bundled);+ }+ }++ worker::sidecar_path().ok_or_else(|| {+ format!(+ "{} was not found in the app resources or next to the executable",+ worker::worker_file_name()+ )+ })+}++/// Forwards a worker fault to the frontend, which turns it into the OOM or+/// backend-error dialog. A mid-generation `GGML_ASSERT` kills the worker+/// outright, so its log line is the only account of what happened.+fn fault_emitter<R: tauri::Runtime>(app_handle: tauri::AppHandle<R>) -> worker::FaultCallback {+ use tauri::Emitter;+ Arc::new(move |fault: worker::RuntimeFault, line: String| {+ log::error!("jan-llama-worker fault ({fault:?}): {line}");+ if let Err(e) = app_handle.emit(fault.event_name(), line) {+ log::warn!("emit {} failed: {e}", fault.event_name());+ }+ })+}++/// Starts the worker. `slot_cache_mib` is the ceiling on the per-thread KV+/// cache directory; 0 turns cross-session KV persistence off, which is a+/// user-facing setting because a single saved conversation is hundreds of MiB.+#[tauri::command]+pub async fn start_engine<R: tauri::Runtime>(+ app_handle: tauri::AppHandle<R>,+ state: State<'_, Arc<LlamacppState>>,+ preset_path: String,+ models_max: u32,+ slot_cache_mib: u64,+ envs: HashMap<String, String>,+) -> Result<EngineInfo, String> {+ let mut guard = state.engine.lock().await;+ if let Some(existing) = guard.as_ref() {+ // Idempotent: a second start must not orphan the first worker.+ return Ok(EngineInfo::from(existing));+ }++ let exe = resolve_worker_exe(&app_handle)?;+ let api_key = generate_worker_key();+ let handle = worker::spawn(+ &exe,+ &PathBuf::from(preset_path),+ 0, // OS-assigned; the handshake reports it back+ &api_key,+ models_max,+ slot_cache_mib,+ envs,+ Some(fault_emitter(app_handle.clone())),+ )+ .await+ .map_err(|e| e.to_string())?;++ let info = EngineInfo::from(&handle);+ // Subscribed here rather than lazily: an eviction can happen on the very+ // first chat request, before any explicit load opens its own listener.+ let watcher = super::watcher::spawn(app_handle.clone(), info.port, info.api_key.clone());+ if let Some(previous) = state.unload_watcher.lock().await.replace(watcher) {+ previous.abort();+ }+ *guard = Some(handle);+ Ok(info)+}++/// Stops the worker unless a generation is in flight.+///+/// The busy check is an HTTP read; the stop itself is `WorkerHandle::stop`,+/// which closes stdin rather than signalling, so it behaves the same on all+/// three platforms.+///+/// `Ok(None)` means it is stopped (or was never running); `Ok(Some(busy))`+/// names the models still generating, and the handle is put back so the caller+/// can retry. The app's exit path uses this -- without it the worker would+/// outlive the app it belongs to.+pub async fn try_graceful_stop_engine<R: tauri::Runtime>(+ app_handle: tauri::AppHandle<R>,+ deadline_secs: u64,+) -> Result<Option<Vec<String>>, String> {+ use tauri::Manager;+ let state: State<Arc<LlamacppState>> = app_handle.state();+ let maybe_handle = {+ let mut guard = state.engine.lock().await;+ guard.take()+ };+ let Some(handle) = maybe_handle else {+ return Ok(None);+ };++ let busy = tokio::time::timeout(+ std::time::Duration::from_secs(deadline_secs.max(1)),+ busy_models(handle.port, &handle.api_key),+ )+ .await+ .unwrap_or_else(|_| Vec::new());++ if !busy.is_empty() {+ *state.engine.lock().await = Some(handle);+ return Ok(Some(busy));+ }++ abort_unload_watcher(&state).await;+ handle.stop().await;+ Ok(None)+}++/// Drops the `/models/sse` subscription. Called from every stop path: the feed+/// it reads dies with the worker, and a task left reconnecting would spend its+/// whole failure budget before noticing.+async fn abort_unload_watcher(state: &Arc<LlamacppState>) {+ if let Some(task) = state.unload_watcher.lock().await.take() {+ task.abort();+ }+}++/// Models with a request in flight, from the worker's own `/models` listing.+/// An unreachable worker reports none -- it cannot be generating.+async fn busy_models(port: u16, api_key: &str) -> Vec<String> {+ let Ok(resp) = reqwest::Client::new()+ .get(format!("http://127.0.0.1:{port}/models"))+ .bearer_auth(api_key)+ .send()+ .await+ else {+ return Vec::new();+ };+ let Ok(json) = resp.json::<serde_json::Value>().await else {+ return Vec::new();+ };+ json.get("data")+ .and_then(|d| d.as_array())+ .map(|arr| {+ arr.iter()+ .filter(|m| m.get("busy").and_then(|b| b.as_bool()).unwrap_or(false))+ .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(String::from))+ .collect()+ })+ .unwrap_or_default()+}++#[tauri::command]+pub async fn stop_engine(state: State<'_, Arc<LlamacppState>>) -> Result<(), String> {+ abort_unload_watcher(&state).await;+ let handle = state.engine.lock().await.take();+ if let Some(h) = handle {+ h.stop().await;+ }+ Ok(())+}++/// One offloadable device, shaped exactly like the `DeviceInfo` the old+/// `llama-server --list-devices` stdout was parsed into, so the TS side is+/// unchanged. Memory is MiB.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EngineDevice {+ pub id: String,+ pub name: String,+ pub mem: u64,+ pub free: u64,+}++/// Enumerates the devices the shipped engine can offload to.+///+/// Runs the worker with `--list-devices` rather than asking a live one: the+/// settings screen needs this before any model is loaded, and the desktop+/// process deliberately links the plugin without the `engine` feature, so it+/// has no ggml of its own to query.+#[tauri::command]+pub async fn engine_devices<R: tauri::Runtime>(+ app_handle: tauri::AppHandle<R>,+ envs: HashMap<String, String>,+) -> Result<Vec<EngineDevice>, String> {+ let exe = resolve_worker_exe(&app_handle)?;+ let mut cmd = tokio::process::Command::new(&exe);+ cmd.arg("--list-devices").envs(envs);+ cmd.stdout(std::process::Stdio::piped());+ cmd.stderr(std::process::Stdio::piped());+ jan_utils::system::setup_windows_process_flags(&mut cmd);++ let out = tokio::time::timeout(std::time::Duration::from_secs(30), cmd.output())+ .await+ .map_err(|_| "timed out enumerating devices".to_string())?+ .map_err(|e| format!("could not run {}: {e}", exe.display()))?;+ if !out.status.success() {+ return Err(format!(+ "device enumeration failed: {}",+ String::from_utf8_lossy(&out.stderr).trim()+ ));+ }+ serde_json::from_slice(&out.stdout).map_err(|e| {+ format!(+ "unreadable device list: {e} (output: {})",+ String::from_utf8_lossy(&out.stdout).trim()+ )+ })+}++/// Reload outcome, for the caller's log line. All four lists together name+/// every model in the preset, so an empty `changed`/`removed` is the proof that+/// nothing the user was using got disturbed.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct ReloadReport {+ pub added: Vec<String>,+ pub changed: Vec<String>,+ pub removed: Vec<String>,+ pub kept: Vec<String>,+ pub models_max: u32,+}++/// Applies a regenerated preset to the running worker without restarting it.+///+/// This is the engine's answer to the router's `GET /models?reload=1`, and it+/// can do one thing the router could not: resize `models_max`. The router fixed+/// that at spawn, so Jan had to cold-restart whenever the embedding slot bonus+/// appeared or went away -- evicting the chat model the user was talking to.+#[tauri::command]+pub async fn reload_engine_models(+ state: State<'_, Arc<LlamacppState>>,+ preset_path: String,+ models_max: Option<u32>,+ slot_cache_mib: Option<u64>,+) -> Result<ReloadReport, String> {+ let (port, api_key) = {+ let guard = state.engine.lock().await;+ let h = guard+ .as_ref()+ .ok_or_else(|| "the engine worker is not running".to_string())?;+ (h.port, h.api_key.clone())+ };++ let mut body = serde_json::json!({ "preset_path": preset_path });+ if let Some(m) = models_max {+ body["models_max"] = serde_json::json!(m);+ }+ if let Some(m) = slot_cache_mib {+ body["slot_cache_mib"] = serde_json::json!(m);+ }++ let resp = reqwest::Client::new()+ .post(format!("http://127.0.0.1:{port}/models/reload"))+ .bearer_auth(&api_key)+ .json(&body)+ .send()+ .await+ .map_err(|e| e.to_string())?;+ let status = resp.status();+ let text = resp.text().await.map_err(|e| e.to_string())?;+ if !status.is_success() {+ return Err(format!(+ "engine reload returned HTTP {}: {text}",+ status.as_u16()+ ));+ }+ serde_json::from_str(&text).map_err(|e| format!("unreadable reload report: {e}"))+}++/// Kills the worker without waiting for it to unwind.+///+/// Distinct from `stop_engine` on purpose: this backs the "force quit" the+/// busy-on-exit dialog offers, where the user has already been told a+/// generation is in flight and chosen to abandon it. Waiting out the graceful+/// path there would be the opposite of what they asked for.+#[tauri::command]+pub async fn force_stop_engine(state: State<'_, Arc<LlamacppState>>) -> Result<(), String> {+ abort_unload_watcher(&state).await;+ let handle = state.engine.lock().await.take();+ if let Some(h) = handle {+ h.kill().await;+ }+ Ok(())+}++/// True when the model has no request in flight, so it is safe to reconfigure+/// or unload. A model that is not resident at all is idle by definition.+///+/// With `model_id` omitted, answers for the whole worker.+#[tauri::command]+pub async fn engine_slots_idle(+ state: State<'_, Arc<LlamacppState>>,+ model_id: Option<String>,+) -> Result<bool, String> {+ let (port, api_key) = {+ let guard = state.engine.lock().await;+ match guard.as_ref() {+ Some(h) => (h.port, h.api_key.clone()),+ // No worker means nothing is generating.+ None => return Ok(true),+ }+ };+ let busy = busy_models(port, &api_key).await;+ Ok(match model_id {+ Some(id) => !busy.contains(&id),+ None => busy.is_empty(),+ })+}++/// Drops saved state without a worker, by editing the directory in this+/// process.+///+/// Safe *because* there is no worker: nothing holds a state file open, and the+/// sidecar records the thread and model each one belongs to, which is what the+/// worker matches on too. The thread wins when both are given, matching+/// `erase_slot_state`.+fn erase_on_disk(dir: Option<&str>, thread: Option<&str>, model: Option<&str>) -> u32 {+ let Some(dir) = dir else {+ return 0;+ };+ let store = super::slots::StateStore::new(dir, 0);+ let n = match (thread, model) {+ (Some(t), _) => store.forget_thread(t),+ (None, Some(m)) => store.forget_model(m),+ (None, None) => 0,+ };+ n as u32+}++/// Drops a thread's saved KV cache, or every thread's for a model.+///+/// Called when a thread is deleted: nothing else would ever collect that state,+/// and the store's own pruning is by size, so an abandoned conversation would+/// sit at the head of the budget until enough others pushed it out. A thread id+/// is enough -- the caller deleting a thread does not know which models it was+/// talked to under, and it may be more than one.+///+/// `cache_dir` is the same `slot-save-path` the preset names, so a delete lands+/// even with no worker running -- which is the common case, since a thread is+/// usually deleted with no model loaded. Deferring it would mean the state+/// survived the thread until the size budget happened to reclaim it.+#[tauri::command]+pub async fn erase_thread_slot_state(+ state: State<'_, Arc<LlamacppState>>,+ thread_id: Option<String>,+ model_id: Option<String>,+ cache_dir: Option<String>,+) -> Result<u32, String> {+ if thread_id.is_none() && model_id.is_none() {+ return Err("one of thread_id or model_id is required".to_string());+ }+ let running = {+ let guard = state.engine.lock().await;+ guard.as_ref().map(|h| (h.port, h.api_key.clone()))+ };+ let Some((port, api_key)) = running else {+ return Ok(erase_on_disk(+ cache_dir.as_deref(),+ thread_id.as_deref(),+ model_id.as_deref(),+ ));+ };+ let mut body = serde_json::Map::new();+ if let Some(t) = thread_id.clone() {+ body.insert("thread".into(), serde_json::Value::String(t));+ }+ if let Some(m) = model_id.clone() {+ body.insert("model".into(), serde_json::Value::String(m));+ }+ let body = serde_json::Value::Object(body);+ let client = reqwest::Client::new();+ let resp = client+ .post(format!("http://127.0.0.1:{port}/slots/state/erase"))+ .bearer_auth(&api_key)+ .json(&body)+ .send()+ .await+ .map_err(|e| format!("could not reach the engine worker: {e}"))?;+ // A worker started from a preset with no slot-save-path knows no directory+ // to erase from, but this process does.+ if resp.status() == reqwest::StatusCode::NOT_IMPLEMENTED {+ return Ok(erase_on_disk(+ cache_dir.as_deref(),+ thread_id.as_deref(),+ model_id.as_deref(),+ ));+ }+ if !resp.status().is_success() {+ return Err(format!(+ "the engine worker refused the erase (status {})",+ resp.status()+ ));+ }+ let parsed: serde_json::Value = resp+ .json()+ .await+ .map_err(|e| format!("unreadable erase response: {e}"))?;+ Ok(parsed+ .get("erased")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0) as u32)+}++#[tauri::command]+pub async fn get_engine_info(+ state: State<'_, Arc<LlamacppState>>,+) -> Result<Option<EngineInfo>, String> {+ let mut guard = state.engine.lock().await;+ // A worker that died must not be reported as live, or every later request+ // would fail against a closed port with no explanation.+ if let Some(h) = guard.as_mut() {+ if let Some(status) = h.exited() {+ log::warn!("jan-llama-worker exited unexpectedly: {status}");+ *guard = None;+ return Ok(None);+ }+ }+ Ok(guard.as_ref().map(EngineInfo::from))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn generated_keys_are_long_hex_and_do_not_repeat() {+ let a = generate_worker_key();+ let b = generate_worker_key();+ assert_eq!(a.len(), 64, "32 bytes hex-encoded");+ assert!(a.chars().all(|c| c.is_ascii_hexdigit()));+ assert_ne!(a, b, "two keys must not collide");+ }++ // resolve_worker_exe now needs an AppHandle for the bundle lookup, so the+ // override branch is exercised through the same precedence it guards: the+ // override is checked before anything Tauri-dependent.+ #[test]+ fn a_bad_override_is_reported_rather_than_silently_ignored() {+ std::env::set_var("JAN_LLAMA_WORKER_BIN", "/definitely/not/a/file");+ let err = std::env::var_os("JAN_LLAMA_WORKER_BIN")+ .map(std::path::PathBuf::from)+ .filter(|p| !p.is_file())+ .map(|p| format!("JAN_LLAMA_WORKER_BIN points at {}, which is not a file", p.display()))+ .expect("a missing override must be rejected, not ignored");+ assert!(err.contains("not a file"), "got {err}");+ std::env::remove_var("JAN_LLAMA_WORKER_BIN");+ }++ // A thread deleted with no model loaded is the common case, so the erase+ // has to land on disk rather than waiting for a worker that may never run.+ #[test]+ fn erasing_without_a_worker_drops_that_threads_files_only() {+ use super::super::slots::{state_key, Identity, StateStore};+ let dir = std::env::temp_dir().join(format!("jan-erase-test-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let store = StateStore::new(&dir, 1);+ for thread in ["t1", "t2"] {+ let key = state_key("m", thread);+ std::fs::write(dir.join(StateStore::state_file_name(&key)), b"x").unwrap();+ store+ .commit(+ &key,+ Identity::new("m", &["a".to_string()], None),+ thread,+ 900,+ )+ .unwrap();+ }+ let bin = |t: &str| dir.join(StateStore::state_file_name(&state_key("m", t)));++ assert_eq!(+ erase_on_disk(Some(&dir.to_string_lossy()), Some("t1"), None),+ 1+ );+ assert!(!bin("t1").exists());+ assert!(bin("t2").exists(), "another thread's cache is untouched");+ assert_eq!(+ erase_on_disk(None, Some("t2"), None),+ 0,+ "no directory named, so there is nowhere to look"+ );+ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn the_worker_file_name_is_platform_correct() {+ let name = super::worker::worker_file_name();+ assert!(name.starts_with("jan-llama-worker"));+ assert_eq!(name.ends_with(".exe"), cfg!(windows));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/events.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/events.rsnew file mode 100644index 000000000..c88e76101--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/events.rs@@ -0,0 +1,198 @@+//! The `/models/sse` feed: model lifecycle transitions, pushed as they happen.+//!+//! Jan's desktop side subscribes to this for the whole of a load+//! (`commands::spawn_load_progress_listener`) and needs it for one thing+//! polling `GET /models` cannot give it: a *definitive* failure. A snapshot can+//! carry a stale `failed` flag from an earlier attempt or an eviction, whereas+//! an `unloaded` event arriving after this attempt's `loading` on the same+//! ordered stream is this attempt's outcome. Without the feed the load waits+//! out its full timeout instead of erroring.+//!+//! The wire shape is upstream's, because that is what the desktop parses,+//! including the `progress` object: `server_context` reports real load+//! progress through `set_state_callback` (server-context.cpp), and the shim+//! forwards its `{stages, current, value}` payload verbatim, so the desktop's+//! `parse_load_progress_event` needs no separate shape to understand. This is+//! *load* progress, not the download fraction upstream puts there -- these+//! models are already on disk.++use tokio::sync::broadcast;++/// Room for a burst (a reload evicting several models) without a subscriber+/// that is mid-write missing the transition it was waiting for.+const CHANNEL_CAPACITY: usize = 64;++/// A lifecycle *transition*, as opposed to `registry::ModelStatus`, which is+/// the steady state `GET /models` reports.+#[derive(Debug, Clone, PartialEq)]+pub enum Transition {+ Loading,+ /// A fraction of the way through loading, as reported by the engine. The+ /// payload is llama.cpp's own (`stages`, `current`, `value`) and is passed+ /// through rather than re-modelled, since only the desktop reads it.+ LoadProgress(serde_json::Value),+ Loaded,+ /// `exit_code` is 0 for a deliberate unload or an eviction and nonzero for+ /// a failed load, which is how upstream marks one (`is_failed`) and how the+ /// desktop tells the two apart.+ Unloaded { exit_code: i32 },+}++#[derive(Debug, Clone, PartialEq)]+pub struct ModelEvent {+ pub model: String,+ pub status: Transition,+}++impl ModelEvent {+ /// One SSE frame, terminator included.+ pub fn to_sse_frame(&self) -> String {+ let data = match &self.status {+ Transition::Loading => serde_json::json!({ "status": "loading" }),+ // Still `loading`: the status is the state, `progress` is how far+ // into it. The desktop keys the percentage off the latter alone.+ Transition::LoadProgress(progress) => {+ serde_json::json!({ "status": "loading", "progress": progress })+ }+ Transition::Loaded => serde_json::json!({ "status": "loaded" }),+ Transition::Unloaded { exit_code } => {+ serde_json::json!({ "status": "unloaded", "exit_code": exit_code })+ }+ };+ let payload = serde_json::json!({+ "model": self.model,+ "event": "status_change",+ "data": data,+ });+ format!("data: {payload}\n\n")+ }+}++/// Fan-out to every open `/models/sse` connection.+///+/// A send with no subscribers is not an error here: the engine runs whether or+/// not anyone is watching, so `emit` discards that case rather than logging it+/// once per transition.+#[derive(Clone)]+pub struct EventBus(broadcast::Sender<ModelEvent>);++impl EventBus {+ pub fn new() -> Self {+ Self(broadcast::channel(CHANNEL_CAPACITY).0)+ }++ pub fn subscribe(&self) -> broadcast::Receiver<ModelEvent> {+ self.0.subscribe()+ }++ pub fn emit(&self, model: &str, status: Transition) {+ let _ = self.0.send(ModelEvent {+ model: model.to_string(),+ status,+ });+ }+}++impl Default for EventBus {+ fn default() -> Self {+ Self::new()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parsed(event: &ModelEvent) -> serde_json::Value {+ let frame = event.to_sse_frame();+ assert!(frame.ends_with("\n\n"), "{frame:?}");+ let data = frame+ .trim_end()+ .strip_prefix("data: ")+ .expect("an SSE data line");+ serde_json::from_str(data).expect("valid json")+ }++ // The desktop's `parse_load_status_change` matches on these exact keys, so+ // the shape is the contract, not an implementation detail.+ #[test]+ fn frames_carry_the_fields_the_desktop_parses() {+ let v = parsed(&ModelEvent {+ model: "qwen".into(),+ status: Transition::Loading,+ });+ assert_eq!(v["model"], "qwen");+ assert_eq!(v["event"], "status_change");+ assert_eq!(v["data"]["status"], "loading");++ let v = parsed(&ModelEvent {+ model: "qwen".into(),+ status: Transition::Loaded,+ });+ assert_eq!(v["data"]["status"], "loaded");+ }++ // A failed load and an eviction are the same status; only the exit code+ // separates them, and the desktop only fails a load on a nonzero one.+ #[test]+ fn an_unload_reports_its_exit_code() {+ let v = parsed(&ModelEvent {+ model: "qwen".into(),+ status: Transition::Unloaded { exit_code: 1 },+ });+ assert_eq!(v["data"]["status"], "unloaded");+ assert_eq!(v["data"]["exit_code"], 1);++ let v = parsed(&ModelEvent {+ model: "qwen".into(),+ status: Transition::Unloaded { exit_code: 0 },+ });+ assert_eq!(v["data"]["exit_code"], 0);+ }++ #[test]+ fn a_model_id_needing_escaping_stays_valid_json() {+ let v = parsed(&ModelEvent {+ model: "weird \"name\"\n".into(),+ status: Transition::Loaded,+ });+ assert_eq!(v["model"], "weird \"name\"\n");+ }++ #[tokio::test]+ async fn every_subscriber_sees_the_transition() {+ let bus = EventBus::new();+ let mut a = bus.subscribe();+ let mut b = bus.subscribe();++ bus.emit("qwen", Transition::Loading);++ assert_eq!(a.recv().await.unwrap().status, Transition::Loading);+ assert_eq!(b.recv().await.unwrap().status, Transition::Loading);+ }++ // Emission must never depend on anyone listening.+ #[test]+ fn emitting_with_no_subscribers_is_not_an_error() {+ EventBus::new().emit("qwen", Transition::Loaded);+ }++ // The desktop reads the percentage out of `data.progress`, keyed on the+ // same field names llama.cpp's own callback uses.+ #[test]+ fn a_progress_frame_carries_the_engines_payload_verbatim() {+ let v = parsed(&ModelEvent {+ model: "qwen".into(),+ status: Transition::LoadProgress(serde_json::json!({+ "stages": ["text_model", "mmproj_model"],+ "current": "text_model",+ "value": 0.42,+ })),+ });+ assert_eq!(v["data"]["status"], "loading");+ assert_eq!(v["data"]["progress"]["current"], "text_model");+ assert_eq!(v["data"]["progress"]["value"], 0.42);+ assert_eq!(v["data"]["progress"]["stages"][1], "mmproj_model");+ }++}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/http.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/http.rsnew file mode 100644index 000000000..6c204a678--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/http.rs@@ -0,0 +1,1080 @@+//! The loopback OpenAI-compatible surface in front of the in-process engine.+//!+//! It exists because Jan's local API server is an HTTP reverse proxy+//! (`src-tauri/src/core/server/proxy.rs` forwards to+//! `http://127.0.0.1:<port>/v1<path>`) and the extension's `chat()` fetches the+//! same URL. Keeping a port means neither has to change, and external+//! OpenAI-SDK clients pointed at Jan keep working.+//!+//! The engine's chunk generator is blocking C++, so streaming runs on a+//! blocking task feeding an async channel rather than being polled from the+//! reactor.++use std::convert::Infallible;+use std::net::SocketAddr;+use std::time::Duration;+use std::sync::Arc;++use bytes::Bytes;+use http_body_util::{combinators::BoxBody, BodyExt, Full, StreamBody};+use hyper::body::{Frame, Incoming};+use hyper::server::conn::http1;+use hyper::service::service_fn;+use hyper::{Method, Request, Response as HttpResponse, StatusCode};+use hyper_util::rt::TokioIo;+use tokio::net::TcpListener;+use tokio::sync::{broadcast, mpsc, Mutex};++use super::registry::{Registry, RegistryError};+use super::slots::{Claim, Identity, SlotOccupancy, StateStore, MIN_TOKENS_TO_SAVE};+use super::Route;++type Body = BoxBody<Bytes, Infallible>;++pub struct EngineServer {+ pub port: u16,+ pub api_key: String,+ registry: Arc<Mutex<Registry>>,+ /// Cross-session KV persistence, `None` only when the preset named no+ /// `slot-save-path` -- in which case llama.cpp answers the slot routes with+ /// 501 anyway. A store with a zero budget is still `Some`: the feature is+ /// off, but the directory has to stay prunable and erasable.+ slots: Option<SlotState>,+}++/// The saved-state directory plus who is sitting in which slot.+struct SlotState {+ store: StateStore,+ occupancy: Mutex<SlotOccupancy>,+}++/// A chat request that names the thread it belongs to, so its KV cache can be+/// parked and picked back up. Absent on requests that do not (embeddings, or+/// any caller that has not opted in), which then behave exactly as before.+#[derive(Debug, Clone, PartialEq, Eq)]+struct SlotHint {+ thread: String,+ slot: i32,+}++/// The request field naming the thread. Already part of Jan's own+/// `chatCompletionRequest` (`core/src/browser/extensions/engines/AIEngine.ts`),+/// which the llamacpp extension forwards verbatim -- so this reads a field that+/// is already on the wire rather than adding a second spelling for it. It is+/// not llama.cpp's, so it is stripped before the body is forwarded.+const THREAD_FIELD: &str = "thread_id";++impl SlotHint {+ /// llama.cpp's own `id_slot` doubles as the slot to persist: the frontend+ /// already pins chat to slot 0 so a thread reuses its cached prefix across+ /// turns, which is the same slot whose contents are worth keeping.+ /// Without it there is no way to know which slot ran the request, so the+ /// hint is dropped rather than guessed at.+ fn from_body(body: &str) -> Option<Self> {+ let v: serde_json::Value = serde_json::from_str(body).ok()?;+ let thread = v.get(THREAD_FIELD)?.as_str()?.trim().to_string();+ if thread.is_empty() {+ return None;+ }+ let slot = v.get("id_slot")?.as_i64()?;+ if slot < 0 {+ return None;+ }+ Some(Self {+ thread,+ slot: slot as i32,+ })+ }+}++/// Removes Jan's own field so llama.cpp only ever sees its own schema.+fn strip_thread_field(body: &str) -> String {+ let Ok(mut v) = serde_json::from_str::<serde_json::Value>(body) else {+ return body.to_string();+ };+ let Some(o) = v.as_object_mut() else {+ return body.to_string();+ };+ if o.remove(THREAD_FIELD).is_none() {+ // Re-serializing a body that did not carry the field would reorder its+ // keys for nothing.+ return body.to_string();+ }+ v.to_string()+}++/// Chunks the streaming task hands to the response body. Bounded so a slow+/// client applies backpressure instead of letting the generator run ahead into+/// unbounded memory.+const STREAM_BUFFER: usize = 32;++impl EngineServer {+ /// Binds `127.0.0.1:port`. Pass 0 to let the OS choose, then read `port`+ /// back -- unlike the old `49152 + random` guess, this cannot collide.+ pub async fn bind(+ registry: Arc<Mutex<Registry>>,+ port: u16,+ api_key: String,+ ) -> std::io::Result<(Self, TcpListener)> {+ let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port))).await?;+ let port = listener.local_addr()?.port();+ Ok((+ Self {+ port,+ api_key,+ registry,+ slots: None,+ },+ listener,+ ))+ }++ /// Serves forever. Callers that need to stop use `serve_until`.+ pub async fn serve(self, listener: TcpListener) {+ Arc::new(self)+ .serve_until(listener, std::future::pending::<()>(), Duration::ZERO)+ .await+ }++ /// Serves until `shutdown` resolves, then stops accepting and waits up to+ /// `drain` for in-flight requests to finish.+ ///+ /// The shutdown trigger is deliberately a parameter rather than an HTTP+ /// route: process lifetime is the caller's concern, not the transport's, and+ /// a request handler that tears down its own server has to be careful about+ /// ordering that simply does not arise this way.+ ///+ /// Draining matters because a connection task holds an `Arc<Engine>` while+ /// it generates. Returning the moment the listener stops would abandon+ /// those tasks and leave the engine referenced, so the teardown that frees+ /// the model could not run.+ /// Takes `Arc<Self>` rather than `self` so the caller keeps a handle: the+ /// worker has to call `save_resident_slots` once draining is done, and that+ /// needs the server after it has stopped serving.+ pub async fn serve_until(+ self: Arc<Self>,+ listener: TcpListener,+ shutdown: impl std::future::Future<Output = ()>,+ drain: Duration,+ ) {+ let state = self;+ let mut connections = tokio::task::JoinSet::new();+ let shutdown = std::pin::pin!(shutdown);++ {+ let mut shutdown = shutdown;+ loop {+ tokio::select! {+ // Biased so a pending shutdown wins over a connection that+ // arrived in the same poll.+ biased;+ _ = &mut shutdown => break,+ accepted = listener.accept() => {+ let Ok((stream, _)) = accepted else { continue };+ let state = Arc::clone(&state);+ connections.spawn(async move {+ let io = TokioIo::new(stream);+ let svc = service_fn(move |req| {+ let state = Arc::clone(&state);+ async move { Ok::<_, Infallible>(state.route(req).await) }+ });+ // A dropped connection is the normal way a client+ // cancels, so this is not worth logging loudly.+ let _ = http1::Builder::new().serve_connection(io, svc).await;+ });+ }+ // Reap finished connections so the set does not grow for the+ // lifetime of the process.+ Some(_) = connections.join_next(), if !connections.is_empty() => {}+ }+ }+ }++ if connections.is_empty() {+ return;+ }+ log::info!(+ "draining {} in-flight connection(s) before exit",+ connections.len()+ );+ if tokio::time::timeout(drain, async {+ while connections.join_next().await.is_some() {}+ })+ .await+ .is_err()+ {+ log::warn!(+ "{} connection(s) still open after {}s; abandoning them",+ connections.len(),+ drain.as_secs()+ );+ }+ }++ /// Turns on cross-session KV persistence. Separate from `bind` because the+ /// directory comes from the preset, which the caller has already read, and+ /// because every existing caller (including the tests) wants it off.+ pub fn with_slot_state(mut self, store: StateStore) -> Self {+ self.slots = Some(SlotState {+ store,+ occupancy: Mutex::new(SlotOccupancy::default()),+ });+ self+ }++ /// Parks the thread that was in this slot and picks up the incoming one.+ ///+ /// Ordering is load-bearing: the outgoing state has to reach disk before+ /// the restore overwrites the slot, and both have to finish before the+ /// completion task is posted. llama.cpp defers a slot action while that+ /// slot is generating, so each of these calls also serves as the barrier+ /// that keeps them from interleaving with a request already in flight.+ async fn hand_over_slot(+ &self,+ engine: &Arc<super::Engine>,+ model: &str,+ hint: &SlotHint,+ ) {+ let Some(state) = &self.slots else { return };+ let identity = {+ let mut reg = self.registry.lock().await;+ // A model the registry dropped took its slots' KV cache with it, so+ // the occupancy it left behind names a thread whose state is no+ // longer in any slot. Claiming against that returns `Evicted(prev)`+ // and would save this slot -- empty, or another thread's -- over+ // prev's file. Every drop path records itself; this is where the+ // record is spent, because it is the only place a claim is made.+ let dropped = reg.take_dropped();+ let identity = reg.state_identity(model);+ drop(reg);+ if !dropped.is_empty() {+ let mut occ = state.occupancy.lock().await;+ for model in dropped {+ occ.release_model(&model);+ }+ }+ identity+ };+ let Some(identity) = identity else {+ return;+ };++ let claim = state+ .occupancy+ .lock()+ .await+ .claim(model, hint.slot, &hint.thread);++ match claim {+ // Turn 2 and later of the same thread. The slot already holds this+ // conversation's cache, and it is newer than the file on disk --+ // restoring here would discard the previous turn's prefill.+ Claim::Unchanged => return,+ Claim::Evicted(prev) => {+ state.save(engine, model, hint.slot, &prev, &identity).await;+ }+ Claim::Empty => {}+ }+ state+ .restore(engine, model, hint.slot, &hint.thread, &identity)+ .await;+ }++ /// Writes every resident slot to disk. The shutdown counterpart of+ /// `hand_over_slot`: without it, closing Jan while a thread is loaded+ /// discards exactly the cache the feature exists to keep, since nothing+ /// else evicts that slot.+ pub async fn save_resident_slots(&self) {+ self.save_slots(None).await+ }++ /// The same pass for one model, before it stops being resident.+ async fn save_model_slots(&self, model: &str) {+ self.save_slots(Some(model)).await+ }++ async fn save_slots(&self, only: Option<&str>) {+ let Some(state) = &self.slots else { return };+ let resident: Vec<_> = state+ .occupancy+ .lock()+ .await+ .all()+ .into_iter()+ .filter(|(m, _, _)| only.map_or(true, |want| m == want))+ .collect();+ for (model, slot, thread) in resident {+ // One lock for the residency check, the identity and the acquire:+ // taking three would let the model be evicted between them, and+ // `acquire` on an evicted model *loads* it -- a cold model load on+ // the shutdown path, to save a cache that no longer exists.+ let acquired = {+ let mut reg = self.registry.lock().await;+ if !reg.is_loaded(&model) {+ continue;+ }+ let identity = reg.state_identity(&model);+ let engine = tokio::task::block_in_place(|| reg.acquire(&model));+ match (engine, identity) {+ (Ok(e), Some(i)) => Some((e, i)),+ (Ok(_), None) => {+ reg.release(&model);+ None+ }+ (Err(_), _) => None,+ }+ };+ let Some((engine, identity)) = acquired else {+ continue;+ };+ state.save(&engine, &model, slot, &thread, &identity).await;+ self.registry.lock().await.release(&model);+ }+ }++ /// Drops saved state for one thread, or for every thread of a model.+ async fn erase_slot_state(&self, body: &str) -> HttpResponse<Body> {+ let Some(state) = &self.slots else {+ return json_error(+ StatusCode::NOT_IMPLEMENTED,+ "this engine was started without a slot save path",+ );+ };+ let parsed: serde_json::Value = match serde_json::from_str(body) {+ Ok(v) => v,+ Err(e) => return json_error(StatusCode::BAD_REQUEST, &format!("bad json: {e}")),+ };+ // Either identifies what to drop. A deleted thread is the common case+ // and the UI knows only its id, so `thread` alone has to work; `model`+ // alone is for a model whose settings changed under it.+ let model = parsed.get("model").and_then(|v| v.as_str());+ let thread = parsed.get("thread").and_then(|v| v.as_str());+ let erased = match (model, thread) {+ (_, Some(thread)) => {+ let n = state.store.forget_thread(thread);+ state.occupancy.lock().await.release_thread(thread);+ n+ }+ (Some(model), None) => {+ let n = state.store.forget_model(model);+ state.occupancy.lock().await.release_model(model);+ n+ }+ (None, None) => {+ return json_error(+ StatusCode::BAD_REQUEST,+ "one of model or thread is required",+ )+ }+ };+ json_ok(&serde_json::json!({ "erased": erased }))+ }++ async fn route(&self, req: Request<Incoming>) -> HttpResponse<Body> {+ let path = req.uri().path().to_string();+ let method = req.method().clone();++ if !authorized(&self.api_key, req.headers()) {+ return json_error(StatusCode::UNAUTHORIZED, "invalid api key");+ }++ // Listing is registry-wide: a model that is registered but not resident+ // must still appear, or the UI would lose it after an eviction.+ if method == Method::GET && matches!(path.as_str(), "/v1/models" | "/models") {+ return self.list_models().await;+ }++ // The lifecycle feed. Subscribed for the length of a load, so a failed+ // one is reported the moment it happens instead of waiting out the+ // caller's poll timeout.+ if method == Method::GET && path == "/models/sse" {+ return self.models_sse().await;+ }++ // Applying a regenerated preset. The router spelled this+ // `GET /models?reload=1`; a POST is used here because it mutates, and+ // because it carries the resized `models_max` the router could not+ // change without a restart.+ if method == Method::POST && path == "/models/reload" {+ let body = match req.into_body().collect().await {+ Ok(b) => b.to_bytes(),+ Err(_) => return json_error(StatusCode::BAD_REQUEST, "could not read the body"),+ };+ return self.reload_models(&String::from_utf8_lossy(&body)).await;+ }++ // Explicit lifecycle, replacing the router endpoints of the same name.+ // The plugin's command layer already speaks these, so keeping the paths+ // means `load_llama_model` / `unload_llama_model` need no rewrite.+ if method == Method::POST && matches!(path.as_str(), "/models/load" | "/models/unload") {+ let load = path.ends_with("/load");+ let body = match req.into_body().collect().await {+ Ok(b) => b.to_bytes(),+ Err(_) => return json_error(StatusCode::BAD_REQUEST, "could not read the body"),+ };+ let body = String::from_utf8_lossy(&body).into_owned();+ let Some(model) = extract_model(&body) else {+ return json_error(StatusCode::BAD_REQUEST, "model is required");+ };+ return if load {+ self.load_model(&model).await+ } else {+ self.unload_model(&model).await+ };+ }++ // Dropping a thread's saved KV cache, for a thread the user deleted.+ if method == Method::POST && path == "/slots/state/erase" {+ let body = match req.into_body().collect().await {+ Ok(b) => b.to_bytes(),+ Err(_) => return json_error(StatusCode::BAD_REQUEST, "could not read the body"),+ };+ return self.erase_slot_state(&String::from_utf8_lossy(&body)).await;+ }++ let Some(route) = Route::from_http_path(&path) else {+ return json_error(StatusCode::NOT_FOUND, &format!("no such route: {path}"));+ };++ let body = match req.into_body().collect().await {+ Ok(b) => b.to_bytes(),+ Err(_) => return json_error(StatusCode::BAD_REQUEST, "could not read the body"),+ };+ let body = String::from_utf8_lossy(&body).into_owned();++ // Routes that do not name a model are answered by any resident engine;+ // health has to work even when nothing is loaded.+ let model = extract_model(&body);+ self.dispatch(route, model, body).await+ }++ /// Re-reads the preset named in the request and diffs it against the+ /// running set. `models_max` is optional; omitting it keeps the current+ /// value.+ async fn reload_models(&self, body: &str) -> HttpResponse<Body> {+ let parsed: serde_json::Value = match serde_json::from_str(body) {+ Ok(v) => v,+ Err(e) => return json_error(StatusCode::BAD_REQUEST, &format!("bad json: {e}")),+ };+ let Some(preset_path) = parsed.get("preset_path").and_then(|v| v.as_str()) else {+ return json_error(StatusCode::BAD_REQUEST, "preset_path is required");+ };+ let ini = match std::fs::read_to_string(preset_path) {+ Ok(s) => s,+ Err(e) => {+ return json_error(+ StatusCode::BAD_REQUEST,+ &format!("could not read {preset_path}: {e}"),+ )+ }+ };++ let specs = super::preset::specs(preset_path, &ini);+ let mut reg = self.registry.lock().await;+ let models_max = parsed+ .get("models_max")+ .and_then(|v| v.as_u64())+ .map(|v| v as usize)+ .unwrap_or_else(|| reg.models_max());+ let outcome = reg.reload(specs, models_max);+ drop(reg);++ // Applied here too, for the same reason models_max is: the value comes+ // from a setting the user can change while the worker runs, and the+ // alternative is a limit that does nothing until the app is restarted.+ let mut pruned = Vec::new();+ if let (Some(state), Some(mib)) = (+ &self.slots,+ parsed.get("slot_cache_mib").and_then(|v| v.as_u64()),+ ) {+ pruned = state.store.set_budget_mib(mib);+ }+ json_ok(&serde_json::json!({+ "added": outcome.added,+ "changed": outcome.changed,+ "removed": outcome.removed,+ "kept": outcome.kept,+ "models_max": models_max,+ "cache_pruned": pruned.len(),+ }))+ }++ async fn list_models(&self) -> HttpResponse<Body> {+ let reg = self.registry.lock().await;+ let busy = reg.busy_models();+ let data: Vec<serde_json::Value> = reg+ .known_models()+ .into_iter()+ .map(|id| {+ let failure = reg.failure_of(&id);+ serde_json::json!({+ "id": id,+ "object": "model",+ "owned_by": "llamacpp",+ // `status` mirrors llama.cpp's router shape because+ // commands::evaluate_load_poll parses exactly these keys.+ "status": {+ "value": reg.status_of(&id).as_str(),+ "failed": failure.is_some(),+ "error": failure,+ },+ // Not part of the router's shape; the shutdown gate reads+ // it to tell a generating model from a merely resident one.+ "busy": busy.contains(&id),+ })+ })+ .collect();+ json_ok(&serde_json::json!({ "object": "list", "data": data }))+ }++ /// Streams model lifecycle transitions until the client goes away.+ ///+ /// Subscribing before the response is returned is what makes this usable+ /// as a load watcher: a caller that opens the stream and only then posts+ /// `/models/load` cannot miss the `loading` event.+ ///+ /// No keepalive comments: the connection is loopback and short-lived, so+ /// there is no proxy idle timeout to defeat.+ async fn models_sse(&self) -> HttpResponse<Body> {+ let mut rx = self.registry.lock().await.events().subscribe();+ let (tx, out) = mpsc::channel::<Result<Frame<Bytes>, Infallible>>(STREAM_BUFFER);++ tokio::spawn(async move {+ loop {+ match rx.recv().await {+ Ok(event) => {+ let frame = Bytes::from(event.to_sse_frame());+ if tx.send(Ok(Frame::data(frame))).await.is_err() {+ return; // client gone+ }+ }+ // A subscriber too slow for CHANNEL_CAPACITY has missed+ // events it cannot recover, and inventing them would be+ // worse than the gap: keep streaming from here.+ Err(broadcast::error::RecvError::Lagged(n)) => {+ log::warn!("a /models/sse subscriber lagged and missed {n} event(s)");+ }+ Err(broadcast::error::RecvError::Closed) => return,+ }+ }+ });++ HttpResponse::builder()+ .status(StatusCode::OK)+ .header(hyper::header::CONTENT_TYPE, "text/event-stream")+ .header(hyper::header::CACHE_CONTROL, "no-cache")+ .body(StreamBody::new(tokio_stream_wrapper(out)).boxed())+ .unwrap_or_else(|_| json_error(StatusCode::INTERNAL_SERVER_ERROR, "bad response"))+ }++ /// Loads a model and leaves it resident. Synchronous, unlike the router's+ /// fire-and-forget endpoint, so a failure is reported on this response+ /// instead of only showing up in a later poll.+ async fn load_model(&self, model: &str) -> HttpResponse<Body> {+ {+ let reg = self.registry.lock().await;+ if reg.is_loaded(model) {+ return json_ok(&serde_json::json!({+ "status": "already loaded", "model": model+ }));+ }+ }+ // Serializing loads behind the lock is deliberate -- two concurrent+ // loads would race on models_max -- but starting a llama_context is+ // blocking, so it needs block_in_place to move other tasks off this+ // worker instead of stalling the reactor. `block_on` inside+ // `spawn_blocking` would risk deadlocking the runtime.+ let mut reg = self.registry.lock().await;+ let outcome = tokio::task::block_in_place(|| {+ let r = reg.acquire(model).map(|_| ());+ if r.is_ok() {+ // Resident but idle, so it stays evictable under models_max.+ reg.release(model);+ }+ r+ });+ drop(reg);++ match outcome {+ Ok(()) => json_ok(&serde_json::json!({ "status": "loaded", "model": model })),+ Err(RegistryError::Full { models_max }) => json_error(+ StatusCode::SERVICE_UNAVAILABLE,+ &format!("all {models_max} model slots are busy; retry shortly"),+ ),+ Err(RegistryError::Engine(e)) => json_error(StatusCode::BAD_REQUEST, &e.to_string()),+ }+ }++ /// Refuses while requests are in flight rather than cancelling them, which+ /// is what upstream's router does.+ async fn unload_model(&self, model: &str) -> HttpResponse<Body> {+ if !self.registry.lock().await.is_loaded(model) {+ return json_ok(&serde_json::json!({+ "status": "already unloaded", "model": model+ }));+ }+ // Before the drop, not after: `unload` takes the engine and the slot's+ // KV cache with it. This is the path Jan switches models on -- with+ // `models_max` at 1 the extension unloads the outgoing model before+ // loading the next -- so without this the thread being left behind+ // loses exactly the cache this feature exists to keep.+ self.save_model_slots(model).await;+ let mut reg = self.registry.lock().await;+ if reg.unload(model) {+ json_ok(&serde_json::json!({ "status": "unloaded", "model": model }))+ } else {+ json_error(+ StatusCode::CONFLICT,+ "the model has requests in flight; retry once they finish",+ )+ }+ }++ async fn dispatch(+ &self,+ route: Route,+ model: Option<String>,+ body: String,+ ) -> HttpResponse<Body> {+ // No model named: fall back to whatever is resident, which is what+ // single-model callers (and /health) expect.+ let Some(model) = model else {+ return self.dispatch_any(route, body).await;+ };++ let engine = {+ let mut reg = self.registry.lock().await;+ // acquire may start an engine, which blocks; see load_model.+ match tokio::task::block_in_place(|| reg.acquire(&model)) {+ Ok(e) => e,+ Err(RegistryError::Full { models_max }) => {+ return json_error(+ StatusCode::SERVICE_UNAVAILABLE,+ &format!(+ "all {models_max} model slots are busy; retry shortly"+ ),+ )+ }+ Err(RegistryError::Engine(e)) => {+ return json_error(StatusCode::BAD_REQUEST, &e.to_string())+ }+ }+ };++ // Only a generating route has a KV cache worth keeping; an embedding or+ // a tokenize call leaves nothing behind.+ let body = if route.caches_prompt() {+ if let Some(hint) = SlotHint::from_body(&body) {+ self.hand_over_slot(&engine, &model, &hint).await;+ }+ strip_thread_field(&body)+ } else {+ body+ };++ let out = run(engine, route, body, STREAM_BUFFER).await;+ self.registry.lock().await.release(&model);+ out+ }++ /// For routes with no model in the body: use the first resident engine.+ async fn dispatch_any(&self, route: Route, body: String) -> HttpResponse<Body> {+ let engine = {+ let mut reg = self.registry.lock().await;+ let Some(first) = reg.loaded_models().into_iter().next() else {+ return json_error(+ StatusCode::SERVICE_UNAVAILABLE,+ "no model is loaded",+ );+ };+ match tokio::task::block_in_place(|| reg.acquire(&first)) {+ Ok(e) => (e, first),+ Err(e) => {+ return json_error(+ StatusCode::SERVICE_UNAVAILABLE,+ &format!("{e:?}"),+ )+ }+ }+ };+ let (eng, id) = engine;+ let out = run(eng, route, body, STREAM_BUFFER).await;+ self.registry.lock().await.release(&id);+ out+ }+}++impl SlotState {+ /// Saves a slot under `thread`'s key, if there is enough in it to be worth+ /// the write.+ ///+ /// The token count is read from `/slots` *first* rather than from the save+ /// response, because a state file is hundreds of MiB for a long+ /// conversation and writing one only to delete it again is the expensive+ /// way to learn it was too short.+ async fn save(+ &self,+ engine: &Arc<super::Engine>,+ model: &str,+ slot: i32,+ thread: &str,+ identity: &Identity,+ ) {+ // A zero budget keeps the store (so the directory can be pruned and a+ // deleted thread erased) but writes nothing new.+ if !self.store.saves_enabled() {+ return;+ }+ let n_tokens = slot_tokens(engine, slot).await;+ if n_tokens < MIN_TOKENS_TO_SAVE {+ return;+ }+ let key = super::slots::state_key(model, thread);+ let file = StateStore::state_file_name(&key);+ let body = serde_json::json!({ "filename": file }).to_string();+ let query = format!("id_slot={slot}&action=save");++ let engine = Arc::clone(engine);+ let res = tokio::task::block_in_place(move || {+ let r = engine.request_with_query(Route::SlotsAction.as_shim_name(), &query, &body);+ (r.status(), r.body())+ });+ if res.0 >= 400 {+ log::warn!(+ "could not save the KV cache of {model} slot {slot}: {}",+ res.1+ );+ // A half-written file with no sidecar would be refused later+ // anyway; dropping it now keeps the directory honest.+ self.store.forget(&key);+ return;+ }+ if let Err(e) = self.store.commit(&key, identity.clone(), thread, n_tokens) {+ log::warn!("saved the KV cache of {model} but could not record it: {e}");+ self.store.forget(&key);+ return;+ }+ log::info!("parked {n_tokens} cached tokens for thread {thread} ({model})");+ }++ /// Restores `thread`'s state into the slot, if one was saved by the same+ /// model and the same llama.cpp.+ async fn restore(+ &self,+ engine: &Arc<super::Engine>,+ model: &str,+ slot: i32,+ thread: &str,+ identity: &Identity,+ ) {+ let key = super::slots::state_key(model, thread);+ let meta = match self.store.check(&key, identity) {+ Ok(m) => m,+ Err(super::slots::Reject::Absent) => return,+ Err(reason) => {+ log::info!("not restoring the KV cache of thread {thread}: {reason}");+ return;+ }+ };++ let file = StateStore::state_file_name(&key);+ let body = serde_json::json!({ "filename": file }).to_string();+ let query = format!("id_slot={slot}&action=restore");+ let engine = Arc::clone(engine);+ let res = tokio::task::block_in_place(move || {+ let r = engine.request_with_query(Route::SlotsAction.as_shim_name(), &query, &body);+ (r.status(), r.body())+ });+ if res.0 >= 400 {+ // llama.cpp rejects a state it cannot use (no room in the KV cache,+ // tokens outside the vocab). The guard passed, so this is not a+ // mismatch we can describe -- but the file is still unusable.+ log::warn!(+ "could not restore the KV cache of thread {thread}: {}",+ res.1+ );+ self.store.forget(&key);+ return;+ }+ log::info!(+ "restored {} cached tokens for thread {thread} ({model})",+ meta.n_tokens+ );+ }+}++/// Tokens currently cached in a slot, from `GET /slots`.+///+/// 0 when the slot has never run a task (upstream omits the count entirely in+/// that case) or when the listing cannot be read, both of which mean "nothing+/// worth saving".+async fn slot_tokens(engine: &Arc<super::Engine>, slot: i32) -> u64 {+ let engine = Arc::clone(engine);+ let body = tokio::task::block_in_place(move || {+ engine.request(Route::Slots.as_shim_name(), "").body()+ });+ let Ok(v) = serde_json::from_str::<serde_json::Value>(&body) else {+ return 0;+ };+ v.as_array()+ .into_iter()+ .flatten()+ .find(|e| e.get("id").and_then(|i| i.as_i64()) == Some(slot as i64))+ .and_then(|e| e.get("n_prompt_tokens"))+ .and_then(|n| n.as_u64())+ .unwrap_or(0)+}++/// Issues one request and adapts the engine's response to an HTTP body.+async fn run(+ engine: Arc<super::Engine>,+ route: Route,+ body: String,+ buffer: usize,+) -> HttpResponse<Body> {+ let name = route.as_shim_name();++ // The engine call itself blocks: it takes the server queue and may wait on+ // a slot, so it must not run on the reactor.+ let engine2 = Arc::clone(&engine);+ let head = tokio::task::spawn_blocking(move || {+ let res = engine2.request(name, &body);+ let is_stream = res.is_stream();+ // Not read on a stream. Upstream prefills `res->data` with the first SSE+ // event and then has its own generator flush that same buffer as chunk+ // one (server-context.cpp: `if (!res_this->data.empty()) { output =+ // std::move(res_this->data); ... }`), so taking the body *and* draining+ // would put that event on the wire twice. Upstream's own HTTP layer+ // treats the two as strictly either/or; so does this. Jan sets+ // `return_progress` on every stream, which makes the prefilled event a+ // real 0% partial instead of an empty one, so the duplicate fired on+ // every streaming completion rather than being latent.+ let first = if is_stream { String::new() } else { res.body() };+ (res.status(), res.content_type(), first, is_stream, res)+ })+ .await;++ let Ok((status, content_type, first, is_stream, mut res)) = head else {+ return json_error(StatusCode::INTERNAL_SERVER_ERROR, "engine task panicked");+ };++ let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);++ if !is_stream {+ return HttpResponse::builder()+ .status(status)+ .header(hyper::header::CONTENT_TYPE, content_type)+ .body(Full::new(Bytes::from(first)).boxed())+ .unwrap_or_else(|_| json_error(StatusCode::INTERNAL_SERVER_ERROR, "bad response"));+ }++ // Streaming: drain the blocking generator on its own thread into a bounded+ // channel. Dropping the receiver (client gone) makes the send fail, which+ // cancels generation instead of running it to completion for nobody.+ let (tx, rx) = mpsc::channel::<Result<Frame<Bytes>, Infallible>>(buffer);+ tokio::task::spawn_blocking(move || {+ // `res` is a bare handle into the engine's server context, and+ // `dispatch` releases its registry reference the moment `run` returns+ // -- which is now, while this is still draining. Without an owning+ // clone here the model looks idle, eviction or an unload drops the last+ // Arc, and `next_chunk` reads a deleted server_context.+ let _engine = engine;+ loop {+ match res.next_chunk() {+ Ok(Some(chunk)) => {+ if chunk.is_empty() {+ continue;+ }+ if tx+ .blocking_send(Ok(Frame::data(Bytes::from(chunk))))+ .is_err()+ {+ res.cancel();+ break;+ }+ }+ Ok(None) => break,+ Err(_) => break,+ }+ }+ });++ HttpResponse::builder()+ .status(status)+ .header(hyper::header::CONTENT_TYPE, content_type)+ .header(hyper::header::CACHE_CONTROL, "no-cache")+ .body(StreamBody::new(tokio_stream_wrapper(rx)).boxed())+ .unwrap_or_else(|_| json_error(StatusCode::INTERNAL_SERVER_ERROR, "bad response"))+}++fn tokio_stream_wrapper(+ rx: mpsc::Receiver<Result<Frame<Bytes>, Infallible>>,+) -> impl futures_util::Stream<Item = Result<Frame<Bytes>, Infallible>> {+ futures_util::stream::unfold(rx, |mut rx| async move {+ rx.recv().await.map(|item| (item, rx))+ })+}++/// An empty configured key means auth is off, which is how a caller that owns+/// the loopback port entirely (tests, a single-user desktop) opts out.+fn authorized(api_key: &str, headers: &hyper::HeaderMap) -> bool {+ if api_key.is_empty() {+ return true;+ }+ headers+ .get(hyper::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .is_some_and(|k| k == api_key)+}++/// The `model` field OpenAI requests carry, used to pick the engine. Absent for+/// `/health`, `/props` and single-model callers.+fn extract_model(body: &str) -> Option<String> {+ serde_json::from_str::<serde_json::Value>(body)+ .ok()?+ .get("model")?+ .as_str()+ .map(str::to_string)+ .filter(|s| !s.is_empty())+}++fn json_ok(v: &serde_json::Value) -> HttpResponse<Body> {+ HttpResponse::builder()+ .status(StatusCode::OK)+ .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8")+ .body(Full::new(Bytes::from(v.to_string())).boxed())+ .expect("a literal json response is always buildable")+}++fn json_error(status: StatusCode, message: &str) -> HttpResponse<Body> {+ let v = serde_json::json!({ "error": { "message": message, "code": status.as_u16() } });+ HttpResponse::builder()+ .status(status)+ .header(hyper::header::CONTENT_TYPE, "application/json; charset=utf-8")+ .body(Full::new(Bytes::from(v.to_string())).boxed())+ .expect("a literal json response is always buildable")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn extract_model_reads_the_openai_field() {+ assert_eq!(+ extract_model(r#"{"model":"qwen","messages":[]}"#).as_deref(),+ Some("qwen")+ );+ }++ #[test]+ fn extract_model_tolerates_absent_empty_and_non_json_bodies() {+ assert_eq!(extract_model(r#"{"messages":[]}"#), None);+ assert_eq!(extract_model(r#"{"model":""}"#), None);+ assert_eq!(extract_model(r#"{"model":123}"#), None);+ assert_eq!(extract_model("not json at all"), None);+ assert_eq!(extract_model(""), None);+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn bind_with_port_zero_reports_the_port_the_os_chose() {+ let reg = Arc::new(Mutex::new(Registry::new(1)));+ let (server, listener) = EngineServer::bind(reg, 0, "k".into())+ .await+ .expect("loopback bind should succeed");+ assert_ne!(server.port, 0, "the OS-assigned port must be reported back");+ assert_eq!(listener.local_addr().unwrap().port(), server.port);+ }++ fn headers(auth: Option<&str>) -> hyper::HeaderMap {+ let mut h = hyper::HeaderMap::new();+ if let Some(a) = auth {+ h.insert(hyper::header::AUTHORIZATION, a.parse().unwrap());+ }+ h+ }++ #[test]+ fn a_thread_hint_needs_both_the_thread_and_the_slot() {+ let both = r#"{"model":"m","thread_id":"t1","id_slot":0}"#;+ assert_eq!(+ SlotHint::from_body(both),+ Some(SlotHint {+ thread: "t1".into(),+ slot: 0+ })+ );+ // Without id_slot there is no way to know which slot ran the request.+ assert_eq!(SlotHint::from_body(r#"{"thread_id":"t1"}"#), None);+ assert_eq!(SlotHint::from_body(r#"{"id_slot":0}"#), None);+ assert_eq!(SlotHint::from_body("{}"), None);+ assert_eq!(SlotHint::from_body("not json"), None);+ }++ // A blank thread id would key every unlabelled request to one state file.+ #[test]+ fn a_blank_or_negative_hint_is_ignored() {+ assert_eq!(+ SlotHint::from_body(r#"{"thread_id":" ","id_slot":0}"#),+ None+ );+ assert_eq!(+ SlotHint::from_body(r#"{"thread_id":"t","id_slot":-1}"#),+ None+ );+ }++ #[test]+ fn the_thread_field_is_stripped_before_the_body_is_forwarded() {+ let out = strip_thread_field(r#"{"model":"m","thread_id":"t1","id_slot":0}"#);+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v.get("thread_id").is_none(), "llama.cpp must not see it");+ assert_eq!(v["model"], "m");+ assert_eq!(v["id_slot"], 0);+ }++ #[test]+ fn a_body_without_the_field_is_forwarded_byte_for_byte() {+ let body = r#"{"model":"m","id_slot":0}"#;+ assert_eq!(strip_thread_field(body), body);+ assert_eq!(strip_thread_field("not json"), "not json");+ assert_eq!(strip_thread_field("[1,2]"), "[1,2]");+ }++ #[test]+ fn only_generating_routes_carry_a_cache_worth_saving() {+ assert!(Route::ChatCompletions.caches_prompt());+ assert!(Route::Completions.caches_prompt());+ assert!(!Route::Embeddings.caches_prompt());+ assert!(!Route::Tokenize.caches_prompt());+ assert!(!Route::Slots.caches_prompt());+ }++ #[tokio::test]+ async fn erasing_state_without_a_store_is_reported_not_silently_ignored() {+ let (server, _l) =+ EngineServer::bind(Arc::new(Mutex::new(Registry::new(1))), 0, String::new())+ .await+ .unwrap();+ let res = server.erase_slot_state(r#"{"model":"m"}"#).await;+ assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED);+ }++ #[test]+ fn an_empty_api_key_disables_auth() {+ assert!(authorized("", &headers(None)));+ assert!(authorized("", &headers(Some("Bearer anything"))));+ }++ #[test]+ fn a_set_api_key_is_enforced_and_the_scheme_must_match() {+ assert!(authorized("secret", &headers(Some("Bearer secret"))));+ assert!(!authorized("secret", &headers(None)));+ assert!(!authorized("secret", &headers(Some("Bearer wrong"))));+ // A bare token with no scheme must not pass.+ assert!(!authorized("secret", &headers(Some("secret"))));+ // Scheme comparison is case-sensitive, matching what the extension sends.+ assert!(!authorized("secret", &headers(Some("bearer secret"))));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rsnew file mode 100644index 000000000..47484e112--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs@@ -0,0 +1,335 @@+//! Safe wrapper over llama.cpp's `server-context`, reached through the C shim+//! in `shim/jan_llama_shim.cpp`.+//!+//! The engine runs *in this process*: no `llama-server` child, no downloaded+//! binary. Everything OpenAI-shaped -- chat templating, tool-call parsing,+//! reasoning extraction, sampling, slots, prompt cache, multimodal -- stays+//! inside llama.cpp's own `server_routes`, which the shim drives directly.+//! Requests and responses cross the boundary as JSON, so this file never has to+//! mirror `server_task`'s type model.+//!+//! This module is the project's single sanctioned `unsafe` carve-out; every+//! block carries a `SAFETY:` note and the module denies implicit unsafe.+#![deny(unsafe_op_in_unsafe_fn)]++use std::fmt;++pub mod commands;+pub mod events;+pub mod http;+pub mod preset;+pub mod registry;+pub mod slots;+pub mod watcher;+pub mod worker;+pub mod sys;++/// The llama.cpp this crate is pinned to, from `build.rs`.+pub const PINNED_TAG: &str = env!("JAN_LLAMA_CPP_TAG");+pub const PINNED_BUILD_NUMBER: &str = env!("JAN_LLAMA_CPP_BUILD_NUMBER");+pub const PINNED_COMMIT: &str = env!("JAN_LLAMA_CPP_COMMIT");+pub const PINNED_VERSION: &str = env!("JAN_LLAMA_CPP_VERSION");++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum EngineError {+ /// Built without the `engine` feature, so there is nothing to talk to.+ Unavailable,+ /// The shim refused to start the engine; carries its message.+ Start(String),+ /// The linked llama.cpp is not the pinned one.+ VersionMismatch { expected: String, actual: String },+ /// A route name the shim does not know.+ UnknownRoute(String),+}++impl fmt::Display for EngineError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Unavailable => write!(+ f,+ "the llama.cpp engine was not compiled in (build with --features engine)"+ ),+ Self::Start(msg) => write!(f, "could not start the llama.cpp engine: {msg}"),+ Self::VersionMismatch { expected, actual } => write!(+ f,+ "linked llama.cpp is {actual}, but this crate is pinned to {expected}"+ ),+ Self::UnknownRoute(r) => write!(f, "unknown engine route: {r}"),+ }+ }+}++impl std::error::Error for EngineError {}++/// The `server_routes` members the shim can dispatch to. Naming follows+/// llama.cpp's own handler names so the mapping stays checkable by eye.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Route {+ Health,+ Props,+ Models,+ Slots,+ /// `POST /slots/{id}?action=...`, the save/restore/erase actions. Not in+ /// `from_http_path`: the slot store is Jan's own bookkeeping, not something+ /// the app's OpenAI-compatible surface should expose.+ SlotsAction,+ Completions,+ CompletionsOai,+ ChatCompletions,+ Embeddings,+ EmbeddingsOai,+ Rerank,+ Tokenize,+ Detokenize,+ ApplyTemplate,+}++impl Route {+ pub const fn as_shim_name(self) -> &'static str {+ match self {+ Self::Health => "get_health",+ Self::Props => "get_props",+ Self::Models => "get_models",+ Self::Slots => "get_slots",+ Self::SlotsAction => "post_slots",+ Self::Completions => "post_completions",+ Self::CompletionsOai => "post_completions_oai",+ Self::ChatCompletions => "post_chat_completions",+ Self::Embeddings => "post_embeddings",+ Self::EmbeddingsOai => "post_embeddings_oai",+ Self::Rerank => "post_rerank",+ Self::Tokenize => "post_tokenize",+ Self::Detokenize => "post_detokenize",+ Self::ApplyTemplate => "post_apply_template",+ }+ }++ /// Whether the route leaves a prompt in a slot's KV cache, and so has+ /// state worth persisting. Embeddings and tokenization do not.+ pub const fn caches_prompt(self) -> bool {+ matches!(+ self,+ Self::Completions | Self::CompletionsOai | Self::ChatCompletions+ )+ }++ /// Maps an HTTP path as the local API server sees it, so `proxy.rs` can+ /// forward without knowing shim names.+ pub fn from_http_path(path: &str) -> Option<Self> {+ match path.trim_end_matches('/') {+ "/health" => Some(Self::Health),+ "/props" => Some(Self::Props),+ "/v1/models" | "/models" => Some(Self::Models),+ "/slots" => Some(Self::Slots),+ "/completion" | "/completions" => Some(Self::Completions),+ "/v1/completions" => Some(Self::CompletionsOai),+ "/v1/chat/completions" | "/chat/completions" => Some(Self::ChatCompletions),+ "/embedding" | "/embeddings" => Some(Self::Embeddings),+ "/v1/embeddings" => Some(Self::EmbeddingsOai),+ "/rerank" | "/v1/rerank" => Some(Self::Rerank),+ "/tokenize" => Some(Self::Tokenize),+ "/detokenize" => Some(Self::Detokenize),+ "/apply-template" => Some(Self::ApplyTemplate),+ _ => None,+ }+ }+}++pub use sys::{Engine, Response};++/// Where the build put the runtime-loaded ggml backend modules.+///+/// ggml resolves them against the executable's own directory+/// (`ggml-backend-reg.cpp:492`), which is what a packaged build relies on. A+/// `cargo run`/`cargo test` binary sits in `target/<profile>/` with no such+/// neighbours, so `ensure_backend_path` points ggml at the build tree instead.+#[cfg(feature = "engine")]+pub const BUILD_BACKEND_DIR: &str = env!("JAN_GGML_BACKEND_DIR");++/// Registers the ggml compute backends, once, before any other ggml call.+///+/// A packaged install has the modules beside the executable, which is where+/// ggml looks by default, so it takes the `None` path. A `cargo run`/`cargo+/// test` binary does not, so it is pointed at the build tree instead.+///+/// The distinction matters because ggml's loader has no already-loaded guard+/// (`ggml-backend-reg.cpp` `load_backend`): pre-loading a directory *and*+/// letting `llama_backend_init` run its own search would register the same+/// backend twice. Pre-loading only when the default search will find nothing+/// keeps the two mutually exclusive.+#[cfg(feature = "engine")]+pub fn load_backend_modules() {+ use std::sync::Once;+ static ONCE: Once = Once::new();+ ONCE.call_once(|| {+ let beside_exe = std::env::current_exe()+ .ok()+ .and_then(|p| p.parent().map(std::path::Path::to_path_buf))+ .map(|dir| has_backend_module(&dir))+ .unwrap_or(false);+ if beside_exe || !std::path::Path::new(BUILD_BACKEND_DIR).is_dir() {+ Engine::load_backends(None);+ } else {+ log::debug!("loading ggml backends from the build tree: {BUILD_BACKEND_DIR}");+ Engine::load_backends(Some(BUILD_BACKEND_DIR));+ }+ });+}++/// A `ggml-*` shared object, by the naming ggml itself looks for.+#[cfg(feature = "engine")]+fn has_backend_module(dir: &std::path::Path) -> bool {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return false;+ };+ entries.filter_map(Result::ok).any(|e| {+ let name = e.file_name();+ let name = name.to_string_lossy();+ name.contains("ggml-")+ && (name.ends_with(".so") || name.ends_with(".dylib") || name.ends_with(".dll"))+ })+}++/// Fails when the linked llama.cpp drifts from the pin. Cheap, and worth doing+/// at startup: `common_params` and `llama_context_params` are passed by value+/// and their field order has changed repeatedly upstream, so a mismatched+/// library is memory corruption rather than a link error.+pub fn assert_pinned_version() -> Result<(), EngineError> {+ let actual_build = Engine::linked_build_number()?;+ let expected: i32 = PINNED_BUILD_NUMBER.parse().unwrap_or(-1);+ if actual_build != expected {+ return Err(EngineError::VersionMismatch {+ expected: format!("b{PINNED_BUILD_NUMBER} ({PINNED_VERSION})"),+ actual: format!("b{actual_build} ({})", Engine::linked_version()?),+ });+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[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_COMMIT.len(), 40, "commit should be a full sha");+ }++ /// build.rs is the single source of the pin: `make engine-source` runs+ /// fetch-engine-source.sh, which greps TAG and COMMIT out of it, clones the+ /// tag, and refuses to build if HEAD is not COMMIT. So the constants+ /// compiled in here must match the ones that file declares, or the fetch+ /// would clone one llama.cpp and we would claim another.+ #[test]+ fn the_pin_matches_what_the_fetch_script_will_clone() {+ let build_rs = include_str!("../../build.rs");+ for (name, value) in [+ ("LLAMA_CPP_TAG", PINNED_TAG),+ ("LLAMA_CPP_COMMIT", PINNED_COMMIT),+ ("LLAMA_CPP_VERSION", PINNED_VERSION),+ ] {+ assert!(+ build_rs.contains(&format!("{name}: &str = \"{value}\"")),+ "{name} drifted from the compiled-in value {value}"+ );+ }++ // The script's sed only matches at line start with this exact shape, so+ // a reformat of build.rs that still compiles would silently break the+ // fetch. It takes the constant's name as a parameter, hence the `$1`.+ let fetch = include_str!("../../../../build-utils/fetch-engine-source.sh");+ assert!(+ fetch.contains("s/^pub const $1: &str = "),+ "fetch-engine-source.sh no longer greps the pin out of build.rs"+ );+ for name in ["LLAMA_CPP_TAG", "LLAMA_CPP_COMMIT"] {+ assert!(+ fetch.contains(&format!("pin {name}")),+ "fetch-engine-source.sh no longer reads {name}"+ );+ assert!(+ build_rs.contains(&format!("pub const {name}: &str = ")),+ "build.rs no longer declares {name} in the shape the fetch script greps"+ );+ }+ }++ /// The crate, the JS package and the llama.cpp semantic version are one+ /// number. Nothing here is published (`private: true`, `link:`/path deps),+ /// so they can track the engine rather than a release history of their own+ /// -- but only if all three move together.+ #[test]+ fn the_crate_and_js_package_versions_track_the_pinned_llama_cpp() {+ let cargo_toml = include_str!("../../Cargo.toml");+ assert!(+ cargo_toml.contains(&format!("\nversion = \"{PINNED_VERSION}\"")),+ "Cargo.toml version drifted from the pinned llama.cpp {PINNED_VERSION}"+ );+ let package_json = include_str!("../../package.json");+ assert!(+ package_json.contains(&format!("\"version\": \"{PINNED_VERSION}\"")),+ "package.json version drifted from the pinned llama.cpp {PINNED_VERSION}"+ );+ }++ #[test]+ fn every_route_round_trips_through_its_http_path() {+ // Guards against a route that is reachable by name but unreachable+ // from the proxy, which is how a command silently stops working.+ let all = [+ Route::Health,+ Route::Props,+ Route::Models,+ Route::Slots,+ Route::Completions,+ Route::CompletionsOai,+ Route::ChatCompletions,+ Route::Embeddings,+ Route::EmbeddingsOai,+ Route::Rerank,+ Route::Tokenize,+ Route::Detokenize,+ Route::ApplyTemplate,+ ];+ for r in all {+ assert!(+ !r.as_shim_name().is_empty(),+ "{r:?} has no shim name"+ );+ }+ assert_eq!(+ Route::from_http_path("/v1/chat/completions"),+ Some(Route::ChatCompletions)+ );+ assert_eq!(Route::from_http_path("/v1/models/"), Some(Route::Models));+ assert_eq!(Route::from_http_path("/nope"), None);+ }++ #[cfg(not(feature = "engine"))]+ #[test]+ fn without_the_feature_the_engine_reports_unavailable() {+ assert_eq!(Engine::linked_version(), Err(EngineError::Unavailable));+ }++ /// The whole point of the pin: prove the llama.cpp we linked is the one+ /// build.rs claims. A drift here means `common_params` may have a different+ /// layout than the shim was compiled against.+ #[cfg(feature = "engine")]+ #[test]+ fn the_linked_library_is_the_pinned_one() {+ assert_eq!(Engine::linked_version().unwrap(), PINNED_VERSION);+ assert_eq!(+ Engine::linked_build_number().unwrap().to_string(),+ PINNED_BUILD_NUMBER+ );+ assert!(+ PINNED_COMMIT.starts_with(&Engine::linked_commit().unwrap()),+ "linked commit {} is not a prefix of the pinned {PINNED_COMMIT}",+ Engine::linked_commit().unwrap()+ );+ assert_eq!(assert_pinned_version(), Ok(()));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rsnew file mode 100644index 000000000..56232675c--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs@@ -0,0 +1,202 @@+//! Parsing of the `router.preset.ini` Jan generates.+//!+//! Lives in the library rather than the worker binary because the reload+//! endpoint re-reads the file at runtime, so both the startup path and the+//! HTTP layer need it.++use std::collections::HashMap;++use super::registry::LoadSpec;++/// Section names from a preset. `[*]` is the shared defaults block, not a+/// model, and the C++ loader applies it to every section.+pub fn sections(ini: &str) -> Vec<String> {+ ini.lines()+ .map(str::trim)+ .filter_map(|l| l.strip_prefix('[')?.strip_suffix(']'))+ .filter(|s| *s != "*")+ .map(str::to_string)+ .collect()+}++/// The body of one section, used to tell a changed model from an unchanged one+/// across a reload. Lines are kept verbatim apart from trimming, so a+/// whitespace-only edit does not look like a settings change.+fn section_bodies(ini: &str) -> HashMap<String, Vec<String>> {+ let mut out: HashMap<String, Vec<String>> = HashMap::new();+ let mut current: Option<String> = None;+ for line in ini.lines().map(str::trim) {+ if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {+ current = Some(name.to_string());+ out.entry(name.to_string()).or_default();+ continue;+ }+ if line.is_empty() || line.starts_with('#') || line.starts_with(';') {+ continue;+ }+ if let Some(name) = ¤t {+ out.entry(name.clone()).or_default().push(line.to_string());+ }+ }+ out+}++/// A key from the shared `[*]` block.+///+/// Read on the Rust side as well as by the C++ loader because the worker has to+/// act on two of them before any model is loaded: `slot-save-path` names a+/// directory llama.cpp *throws* on if it does not exist+/// (`common/arg.cpp:3580`), and the KV state store has to agree with llama.cpp+/// on where files land.+pub fn shared_value(ini: &str, key: &str) -> Option<String> {+ let mut in_shared = false;+ for line in ini.lines().map(str::trim) {+ if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {+ in_shared = name == "*";+ continue;+ }+ if !in_shared || line.is_empty() || line.starts_with('#') || line.starts_with(';') {+ continue;+ }+ if let Some((k, v)) = line.split_once('=') {+ if k.trim() == key {+ return Some(v.trim().to_string());+ }+ }+ }+ None+}++/// Load specs for every model in a preset.+///+/// The spec carries the section body so `Registry::reload` can diff it. Two+/// presets that differ only in a model Jan did not touch therefore leave that+/// model loaded, which is the whole point of reloading rather than restarting.+pub fn specs(ini_path: &str, ini: &str) -> HashMap<String, LoadSpec> {+ let mut bodies = section_bodies(ini);+ let shared = bodies.get("*").cloned().unwrap_or_default();+ sections(ini)+ .into_iter()+ .map(|section| {+ let mut body = shared.clone();+ body.extend(bodies.remove(§ion).unwrap_or_default());+ body.sort();+ (+ section.clone(),+ LoadSpec::Preset {+ ini_path: ini_path.to_string(),+ section,+ body,+ },+ )+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ const INI: &str = "\+[*]+parallel = 1++[Qwen3-0_6B-IQ4_XS]+model = /models/qwen.gguf+load-on-startup = false++[sentence-transformer-mini]+model = /models/st.gguf+embeddings = true+";++ #[test]+ fn sections_skips_the_shared_defaults_block() {+ assert_eq!(+ sections(INI),+ vec!["Qwen3-0_6B-IQ4_XS", "sentence-transformer-mini"]+ );+ }++ #[test]+ fn sections_tolerates_indentation_and_blank_files() {+ assert_eq!(sections(" [a] \n key = 1"), vec!["a"]);+ assert!(sections("").is_empty());+ assert!(sections("key = 1\n# comment").is_empty());+ }++ #[test]+ fn a_shared_key_is_read_only_from_the_star_section() {+ let ini = "[*]\nslot-save-path = /a/b\n\n[m]\nslot-save-path = /c/d\n";+ assert_eq!(+ shared_value(ini, "slot-save-path"),+ Some("/a/b".to_string()),+ "a per-model override must not be mistaken for the engine-wide value"+ );+ assert_eq!(shared_value(ini, "absent"), None);+ assert_eq!(+ shared_value("[m]\nslot-save-path = /c/d\n", "slot-save-path"),+ None+ );+ }++ #[test]+ fn a_shared_value_keeps_paths_with_spaces_and_equals_signs() {+ let ini = "[*]\nslot-save-path = /home/a b/Jan Data/cache\n";+ assert_eq!(+ shared_value(ini, "slot-save-path"),+ Some("/home/a b/Jan Data/cache".to_string())+ );+ assert_eq!(+ shared_value("[*]\nchat-template = a=b\n", "chat-template"),+ Some("a=b".to_string())+ );+ }++ #[test]+ fn a_model_id_containing_brackets_is_not_mistaken_for_a_section() {+ assert!(sections("model = /a/[b].gguf").is_empty());+ }++ #[test]+ fn a_spec_carries_the_shared_defaults_so_a_change_there_reloads_every_model() {+ let base = specs("/p.ini", INI);+ let edited = specs("/p.ini", &INI.replace("parallel = 1", "parallel = 4"));+ for id in base.keys() {+ assert_ne!(base[id], edited[id], "{id} should differ");+ }+ }++ #[test]+ fn editing_one_model_leaves_the_others_specs_untouched() {+ let base = specs("/p.ini", INI);+ let edited = specs(+ "/p.ini",+ &INI.replace("load-on-startup = false", "load-on-startup = true"),+ );+ assert_ne!(base["Qwen3-0_6B-IQ4_XS"], edited["Qwen3-0_6B-IQ4_XS"]);+ assert_eq!(+ base["sentence-transformer-mini"],+ edited["sentence-transformer-mini"]+ );+ }++ // Comments and blank lines are not settings; a reload triggered by one+ // would cold-load the user's chat model for nothing.+ #[test]+ fn comments_and_blank_lines_do_not_count_as_a_change() {+ let commented = specs("/p.ini", &INI.replace("[*]", "# note\n\n[*]"));+ assert_eq!(specs("/p.ini", INI), commented);+ }++ // Key order within a section is an artifact of how the preset is written.+ #[test]+ fn key_order_within_a_section_does_not_count_as_a_change() {+ let reordered = specs(+ "/p.ini",+ "[a]\nmodel = /m.gguf\nembeddings = true\n",+ );+ let original = specs("/p.ini", "[a]\nembeddings = true\nmodel = /m.gguf\n");+ assert_eq!(original, reordered);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rsnew file mode 100644index 000000000..6121d5391--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rs@@ -0,0 +1,743 @@+//! In-process replacement for llama.cpp's router mode.+//!+//! Upstream's router is a process supervisor plus a reverse proxy: it spawns a+//! child `llama-server` per model (`server-models.cpp:1020-1046`). Linking+//! `server_context` directly means there are no children, so what survives is+//! only the bookkeeping -- a model registry with `models_max` and LRU eviction.+//! The two invariants are taken from upstream (`server-models.cpp:92-95` and+//! `:103-210`): never evict a model with requests in flight, and make a caller+//! that arrives while the registry is full wait rather than fail.++use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;++use super::events::{EventBus, Transition};+use super::{Engine, EngineError};++/// Monotonic tick for LRU ordering. A counter rather than a clock so ordering+/// is exact under rapid use and cannot go backwards on a clock adjustment.+static TICK: AtomicU64 = AtomicU64::new(0);++fn next_tick() -> u64 {+ TICK.fetch_add(1, Ordering::Relaxed)+}++pub struct LoadedModel {+ pub engine: Arc<Engine>,+ /// Requests currently using this model. An evictor must not touch a model+ /// with a non-zero count, or it would cancel a live generation.+ inflight: usize,+ last_used: u64,+}++impl LoadedModel {+ pub fn engine(&self) -> Arc<Engine> {+ Arc::clone(&self.engine)+ }+}++#[derive(Debug, PartialEq, Eq)]+pub enum RegistryError {+ /// Every slot is taken and every resident model is busy, so nothing can be+ /// evicted to make room.+ Full { models_max: usize },+ Engine(EngineError),+}++impl From<EngineError> for RegistryError {+ fn from(e: EngineError) -> Self {+ Self::Engine(e)+ }+}++/// How a model is started, so the registry can reload one it evicted.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum LoadSpec {+ /// llama-server's own flag set.+ Args(Vec<String>),+ /// A section of a `router.preset.ini`, the file Jan already generates.+ ///+ /// `body` is the section's settings (plus the shared `[*]` block) and is+ /// compared on reload. It is not passed to the C++ loader, which re-reads+ /// the file itself -- it exists so an unrelated model can stay loaded.+ Preset {+ ini_path: String,+ section: String,+ body: Vec<String>,+ },+}++/// What `GET /models` reports per entry. The names match llama.cpp's router+/// (`server-models.h:29-37`) because the plugin's polling arm+/// (`commands::evaluate_load_poll`) already parses exactly these values, and+/// changing them would silently turn every load into a 600s timeout.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ModelStatus {+ Loaded,+ Unloaded,+}++impl ModelStatus {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Loaded => "loaded",+ Self::Unloaded => "unloaded",+ }+ }+}++/// What a reload did, for the log line. A reload that reports only `kept` is+/// the case the whole mechanism exists for: nothing was disturbed.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct ReloadOutcome {+ pub added: Vec<String>,+ pub changed: Vec<String>,+ pub removed: Vec<String>,+ pub kept: Vec<String>,+}++pub struct Registry {+ loaded: HashMap<String, LoadedModel>,+ specs: HashMap<String, LoadSpec>,+ /// Models whose spec changed (or which were removed) while a request was in+ /// flight. They cannot be dropped there without cancelling a live+ /// generation, so `release` drops them once the last request finishes.+ stale: HashSet<String>,+ /// Why a model's last load attempt failed. Kept so `GET /models` can report+ /// `failed: true`: without it a failed load looks merely "unloaded" and the+ /// caller's poll loop waits out its full timeout instead of erroring.+ failures: HashMap<String, String>,+ /// Models the registry has stopped hosting since the last drain, whatever+ /// dropped them. Their slots died with the engine, so the occupancy map --+ /// which lives a module over and cannot be reached from these `&mut self`+ /// methods -- has to forget them before it hands one of their slot ids to+ /// another thread. `take_dropped` is drained where occupancy is claimed.+ dropped: Vec<String>,+ /// 0 means unlimited, matching llama.cpp's `--models-max`.+ models_max: usize,+ /// Where every transition below is published for `/models/sse`.+ events: EventBus,+}++impl Registry {+ pub fn new(models_max: usize) -> Self {+ Self {+ loaded: HashMap::new(),+ specs: HashMap::new(),+ stale: HashSet::new(),+ failures: HashMap::new(),+ dropped: Vec::new(),+ models_max,+ events: EventBus::new(),+ }+ }++ /// The lifecycle feed, for the HTTP layer to subscribe to.+ pub fn events(&self) -> EventBus {+ self.events.clone()+ }++ pub fn models_max(&self) -> usize {+ self.models_max+ }++ /// Records how a model is started without loading it, so `/v1/models` can+ /// list it and a later request can load it on demand.+ pub fn register(&mut self, model_id: impl Into<String>, spec: LoadSpec) {+ self.specs.insert(model_id.into(), spec);+ }++ pub fn known_models(&self) -> Vec<String> {+ let mut v: Vec<String> = self.specs.keys().cloned().collect();+ v.sort();+ v+ }++ pub fn loaded_models(&self) -> Vec<String> {+ let mut v: Vec<String> = self.loaded.keys().cloned().collect();+ v.sort();+ v+ }++ /// Models with at least one request in flight.+ ///+ /// The router could only report "loaded", which conflated a model that is+ /// generating with one merely resident -- so its shutdown gate refused to+ /// exit while any model was in memory. Requests in flight is the question+ /// the gate is actually asking.+ pub fn busy_models(&self) -> Vec<String> {+ let mut v: Vec<String> = self+ .loaded+ .iter()+ .filter(|(_, m)| m.inflight > 0)+ .map(|(id, _)| id.clone())+ .collect();+ v.sort();+ v+ }++ /// The identity a saved KV state is checked against: the model's preset+ /// section plus the gguf it names.+ ///+ /// Read from the registry rather than reconstructed, so the comparison is+ /// against what the model was actually loaded with. `None` means the model+ /// is not registered at all, which is not something to guess at.+ pub fn state_identity(&self, model_id: &str) -> Option<super::slots::Identity> {+ let spec = self.specs.get(model_id)?;+ let body = match spec {+ LoadSpec::Preset { body, .. } => body.clone(),+ LoadSpec::Args(args) => args.clone(),+ };+ let path = spec_model_path(&body).map(std::path::PathBuf::from);+ Some(super::slots::Identity::new(+ model_id,+ &body,+ path.as_deref(),+ ))+ }++ pub fn is_loaded(&self, model_id: &str) -> bool {+ self.loaded.contains_key(model_id)+ }++ pub fn status_of(&self, model_id: &str) -> ModelStatus {+ if self.loaded.contains_key(model_id) {+ ModelStatus::Loaded+ } else {+ ModelStatus::Unloaded+ }+ }++ /// The last load failure for a model, if the most recent attempt failed.+ pub fn failure_of(&self, model_id: &str) -> Option<&str> {+ self.failures.get(model_id).map(String::as_str)+ }++ /// True when the registry is at capacity and nothing is evictable, i.e. a+ /// caller must wait. Split out so the HTTP layer can queue instead of+ /// holding the registry lock across a load.+ pub fn is_saturated(&self) -> bool {+ if self.models_max == 0 || self.loaded.len() < self.models_max {+ return false;+ }+ self.lru_idle().is_none()+ }++ /// Acquires the engine for a model, loading (and evicting) as needed, and+ /// marks it busy. The caller must pair this with `release`.+ pub fn acquire(&mut self, model_id: &str) -> Result<Arc<Engine>, RegistryError> {+ // A model awaiting retirement keeps serving until its in-flight+ // requests drain. Loading the new spec alongside it would put two+ // engines under one id and split the inflight count, so a late request+ // on the old spec is the lesser evil -- and is what the router does,+ // which also cannot unload a busy model.+ if let Some(m) = self.loaded.get_mut(model_id) {+ m.inflight += 1;+ m.last_used = next_tick();+ return Ok(m.engine());+ }++ let spec = self+ .specs+ .get(model_id)+ .cloned()+ .ok_or(RegistryError::Engine(EngineError::UnknownRoute(+ model_id.to_string(),+ )))?;++ self.make_room()?;++ self.events.emit(model_id, Transition::Loading);+ // Real load progress, straight from server_context. Only the `loading`+ // state carries a fraction; `ready` and `sleeping` arrive here too and+ // are already covered by the lifecycle transitions around this call.+ let progress = {+ let bus = self.events.clone();+ let model = model_id.to_string();+ std::sync::Arc::new(move |state: &str, payload: &str| {+ if state != "loading" {+ return;+ }+ match serde_json::from_str::<serde_json::Value>(payload) {+ Ok(v) if v.get("value").is_some() => {+ bus.emit(&model, Transition::LoadProgress(v));+ }+ _ => {}+ }+ }) as crate::engine::sys::StateCallback+ };+ let started = match &spec {+ LoadSpec::Args(args) => Engine::start(args, Some(progress)),+ LoadSpec::Preset {+ ini_path, section, ..+ } => Engine::start_from_preset(ini_path, section, Some(progress)),+ };+ let engine = match started {+ Ok(e) => {+ self.failures.remove(model_id);+ e+ }+ Err(e) => {+ // Recorded so the poll arm sees `failed: true` rather than+ // waiting out its timeout on a bare "unloaded".+ self.failures.insert(model_id.to_string(), e.to_string());+ // Nonzero: this is the transition the desktop treats as a+ // definitive load failure.+ self.events+ .emit(model_id, Transition::Unloaded { exit_code: 1 });+ return Err(e.into());+ }+ };+ let engine = Arc::new(engine);+ self.loaded.insert(+ model_id.to_string(),+ LoadedModel {+ engine: Arc::clone(&engine),+ inflight: 1,+ last_used: next_tick(),+ },+ );+ self.events.emit(model_id, Transition::Loaded);+ Ok(engine)+ }++ /// Marks a request finished. Only then does the model become evictable.+ ///+ /// A model a reload superseded is dropped here rather than at reload time,+ /// which is the only point where doing so cannot cancel a generation.+ pub fn release(&mut self, model_id: &str) {+ let Some(m) = self.loaded.get_mut(model_id) else {+ return;+ };+ m.inflight = m.inflight.saturating_sub(1);+ m.last_used = next_tick();+ if m.inflight == 0 && self.stale.remove(model_id) {+ self.loaded.remove(model_id);+ self.events+ .emit(model_id, Transition::Unloaded { exit_code: 0 });+ }+ }++ /// Applies a regenerated preset without restarting the process.+ ///+ /// A model whose spec is byte-identical stays resident; one whose settings+ /// moved is dropped so the next request reloads it. This is the reason the+ /// engine does not have to be restarted when a model is imported or a+ /// per-model setting is written -- a restart would evict the chat model the+ /// user is talking to.+ pub fn reload(&mut self, specs: HashMap<String, LoadSpec>, models_max: usize) -> ReloadOutcome {+ self.models_max = models_max;+ let mut outcome = ReloadOutcome::default();++ for id in self.specs.keys().cloned().collect::<Vec<_>>() {+ if !specs.contains_key(&id) {+ self.specs.remove(&id);+ self.failures.remove(&id);+ self.retire(&id);+ outcome.removed.push(id);+ }+ }++ for (id, spec) in specs {+ match self.specs.get(&id) {+ Some(existing) if *existing == spec => {+ if self.loaded.contains_key(&id) {+ outcome.kept.push(id);+ }+ }+ existing => {+ let known = existing.is_some();+ self.specs.insert(id.clone(), spec);+ self.failures.remove(&id);+ self.retire(&id);+ if known {+ outcome.changed.push(id);+ } else {+ outcome.added.push(id);+ }+ }+ }+ }++ outcome.added.sort();+ outcome.changed.sort();+ outcome.removed.sort();+ outcome.kept.sort();+ outcome+ }++ /// Drops a resident model, or defers the drop to `release` when it is busy.+ fn retire(&mut self, model_id: &str) {+ match self.loaded.get(model_id) {+ Some(m) if m.inflight == 0 => {+ self.loaded.remove(model_id);+ self.dropped.push(model_id.to_string());+ self.events+ .emit(model_id, Transition::Unloaded { exit_code: 0 });+ }+ Some(_) => {+ self.stale.insert(model_id.to_string());+ }+ None => {}+ }+ }++ /// Unloads a model. Refuses while requests are in flight rather than+ /// cancelling them, which is what upstream does.+ pub fn unload(&mut self, model_id: &str) -> bool {+ match self.loaded.get(model_id) {+ Some(m) if m.inflight == 0 => {+ self.loaded.remove(model_id);+ self.stale.remove(model_id);+ self.dropped.push(model_id.to_string());+ self.events+ .emit(model_id, Transition::Unloaded { exit_code: 0 });+ true+ }+ _ => false,+ }+ }++ /// Ids dropped since the last call, for the caller that owns the slot+ /// occupancy map. Draining is the caller's job precisely because the fix+ /// belongs on the other side of an async lock this struct cannot take.+ pub fn take_dropped(&mut self) -> Vec<String> {+ std::mem::take(&mut self.dropped)+ }++ /// Drops every resident model, ignoring in-flight requests.+ ///+ /// Unconditional where `unload` refuses a busy model: this runs only once+ /// the listener has stopped, and the point is to reach each `Engine`'s Drop+ /// -- and so `jan_llama_engine_stop` -- before the process exits. Returns+ /// the ids it released, for the log.+ pub fn shutdown(&mut self) -> Vec<String> {+ let mut ids: Vec<String> = self.loaded.keys().cloned().collect();+ ids.sort();+ self.loaded.clear();+ self.stale.clear();+ self.dropped.extend(ids.iter().cloned());+ ids+ }++ /// Evicts LRU-idle models until one more fits under `models_max`.+ ///+ /// Deliberately does *not* persist the victim's KV cache: `save_model_slots`+ /// is called only from `unload_model`, which is the path Jan actually takes+ /// when switching models (`models_max` is 1, so the extension unloads before+ /// it loads). The victim's slot occupancy is still released here via+ /// `dropped`, so the residual is a lost cache and a re-prefill, not a+ /// cross-thread overwrite.+ ///+ /// It becomes reachable as soon as a user raises `models_max` above 1, or+ /// when an embedding model loads alongside a chat model on a tight budget.+ /// Saving here needs the same await-and-persist that `unload_model` does,+ /// which the registry cannot do while holding its own lock -- so it belongs+ /// with the caller, as a follow-up. `retire` has the same omission.+ fn make_room(&mut self) -> Result<(), RegistryError> {+ if self.models_max == 0 {+ return Ok(());+ }+ while self.loaded.len() >= self.models_max {+ let Some(victim) = self.lru_idle() else {+ return Err(RegistryError::Full {+ models_max: self.models_max,+ });+ };+ self.loaded.remove(&victim);+ self.dropped.push(victim.clone());+ self.events+ .emit(&victim, Transition::Unloaded { exit_code: 0 });+ }+ Ok(())+ }++ /// The least-recently-used model with nothing in flight.+ fn lru_idle(&self) -> Option<String> {+ pick_lru_idle(+ self.loaded+ .iter()+ .map(|(id, m)| (id.as_str(), m.inflight, m.last_used)),+ )+ }+}++/// The eviction policy, over plain data so it can be tested without starting an+/// engine. Busy models are never candidates; among idle ones the oldest tick+/// wins.+fn pick_lru_idle<'a>(+ entries: impl Iterator<Item = (&'a str, usize, u64)>,+) -> Option<String> {+ entries+ .filter(|(_, inflight, _)| *inflight == 0)+ .min_by_key(|(_, _, last_used)| *last_used)+ .map(|(id, _, _)| id.to_string())+}++/// The gguf a spec names, so its size and mtime can join the state guard. The+/// key is `model` in a preset section and `-m`/`--model` in an arg list; a spec+/// with neither (a remote or auto-resolved model) simply has no file to stamp.+fn spec_model_path(body: &[String]) -> Option<String> {+ let mut it = body.iter();+ while let Some(line) = it.next() {+ if line == "-m" || line == "--model" {+ return it.next().cloned();+ }+ if let Some((k, v)) = line.split_once('=') {+ if k.trim() == "model" {+ return Some(v.trim().to_string());+ }+ }+ }+ None+}++#[cfg(test)]+mod tests {+ use super::*;++ fn spec(n: &str) -> LoadSpec {+ LoadSpec::Args(vec!["llama-server".into(), "-m".into(), n.into()])+ }++ /// Without the `engine` feature every load fails, which still exercises+ /// the bookkeeping: registration, capacity and eviction order are decided+ /// before an engine is ever started.+ fn reg(max: usize, models: &[&str]) -> Registry {+ let mut r = Registry::new(max);+ for m in models {+ r.register(*m, spec(m));+ }+ r+ }++ /// Puts a model in `loaded` without a load, which the default feature+ /// config cannot do: `acquire` always fails there.+ #[cfg(not(feature = "engine"))]+ fn resident(r: &mut Registry, models: &[&str]) {+ for m in models {+ r.register(*m, spec(m));+ r.loaded.insert(+ (*m).to_string(),+ LoadedModel {+ engine: Arc::new(Engine::stub()),+ inflight: 0,+ last_used: next_tick(),+ },+ );+ }+ }++ /// Every path that stops hosting a model has to say so: the slot occupancy+ /// map lives behind an async lock this struct cannot take, and a model+ /// missing from this list keeps its stale claim on a slot id that another+ /// thread will later be handed.+ #[cfg(not(feature = "engine"))]+ #[test]+ fn each_drop_path_records_the_model_it_dropped() {+ let mut r = Registry::new(2);+ resident(&mut r, &["a"]);+ assert!(r.unload("a"));+ assert_eq!(r.take_dropped(), vec!["a".to_string()]);+ assert!(r.take_dropped().is_empty(), "draining is not repeatable");++ resident(&mut r, &["b"]);+ r.retire("b");+ assert_eq!(r.take_dropped(), vec!["b".to_string()]);++ // Eviction under models_max: the victim is dropped by make_room rather+ // than by a caller, which is the path with no async context at all.+ let mut r = Registry::new(1);+ resident(&mut r, &["c"]);+ assert!(r.make_room().is_ok());+ assert_eq!(r.take_dropped(), vec!["c".to_string()]);++ let mut r = Registry::new(2);+ resident(&mut r, &["d", "e"]);+ let mut ids = r.shutdown();+ ids.sort();+ assert_eq!(ids, vec!["d".to_string(), "e".to_string()]);+ let mut dropped = r.take_dropped();+ dropped.sort();+ assert_eq!(dropped, vec!["d".to_string(), "e".to_string()]);+ }++ /// A busy model is not dropped, so it must not be recorded as dropped+ /// either -- releasing its occupancy would discard a live slot's claim.+ #[cfg(not(feature = "engine"))]+ #[test]+ fn a_busy_model_is_neither_dropped_nor_recorded() {+ let mut r = Registry::new(2);+ resident(&mut r, &["a"]);+ r.loaded.get_mut("a").unwrap().inflight = 1;+ assert!(!r.unload("a"), "unload must refuse a busy model");+ r.retire("a");+ assert!(r.take_dropped().is_empty());+ }++ #[test]+ fn registration_does_not_load() {+ let r = reg(2, &["a", "b"]);+ assert_eq!(r.known_models(), vec!["a", "b"]);+ assert!(r.loaded_models().is_empty());+ assert!(!r.is_loaded("a"));+ }++ #[test]+ fn an_unregistered_model_is_rejected_before_any_load() {+ let mut r = reg(2, &["a"]);+ let err = r.acquire("nope").unwrap_err();+ assert!(matches!(err, RegistryError::Engine(_)));+ }++ #[test]+ fn models_max_zero_means_unlimited() {+ let r = reg(0, &["a"]);+ assert_eq!(r.models_max(), 0);+ assert!(!r.is_saturated(), "unlimited must never saturate");+ }++ #[test]+ fn release_is_saturating_and_never_underflows() {+ let mut r = reg(1, &["a"]);+ // release on a model that was never loaded must be a no-op, not a panic+ r.release("a");+ r.release("a");+ assert!(!r.is_loaded("a"));+ }++ fn specs(pairs: &[(&str, &str)]) -> HashMap<String, LoadSpec> {+ pairs+ .iter()+ .map(|(id, path)| ((*id).to_string(), spec(path)))+ .collect()+ }++ #[test]+ fn reload_registers_new_models_and_drops_removed_ones() {+ let mut r = reg(2, &["a", "b"]);+ let outcome = r.reload(specs(&[("b", "b"), ("c", "c")]), 2);+ assert_eq!(outcome.added, vec!["c"]);+ assert_eq!(outcome.removed, vec!["a"]);+ assert!(outcome.changed.is_empty());+ assert_eq!(r.known_models(), vec!["b", "c"]);+ }++ /// The point of reloading rather than restarting: a model whose settings+ /// did not move is left alone.+ #[test]+ fn reload_reports_an_unchanged_spec_as_neither_added_nor_changed() {+ let mut r = reg(2, &["a"]);+ let outcome = r.reload(specs(&[("a", "a")]), 2);+ assert!(outcome.added.is_empty());+ assert!(outcome.changed.is_empty());+ assert!(outcome.removed.is_empty());+ }++ #[test]+ fn reload_reports_a_moved_spec_as_changed() {+ let mut r = reg(2, &["a"]);+ let outcome = r.reload(specs(&[("a", "a-different-gguf")]), 2);+ assert_eq!(outcome.changed, vec!["a"]);+ assert!(outcome.added.is_empty());+ }++ /// The router fixed models_max at spawn, so Jan had to cold-restart the+ /// whole process just to add the embedding slot.+ #[test]+ fn reload_resizes_models_max() {+ let mut r = reg(1, &["a"]);+ r.reload(specs(&[("a", "a")]), 2);+ assert_eq!(r.models_max(), 2);+ }++ #[test]+ fn reload_clears_a_recorded_failure_so_a_fixed_model_is_retried() {+ let mut r = reg(1, &["a"]);+ // A failed load is what populates `failures`; without the engine+ // feature every acquire fails, which is exactly the state needed here.+ let _ = r.acquire("a");+ assert!(r.failure_of("a").is_some());+ r.reload(specs(&[("a", "a-fixed")]), 1);+ assert!(+ r.failure_of("a").is_none(),+ "a changed spec must not inherit the old failure"+ );+ }++ #[test]+ fn unload_refuses_a_model_that_is_not_loaded() {+ let mut r = reg(1, &["a"]);+ assert!(!r.unload("a"));+ }++ #[test]+ fn lru_picks_the_least_recently_used_idle_model() {+ let entries = [("old", 0usize, 1u64), ("new", 0, 2)];+ assert_eq!(+ pick_lru_idle(entries.iter().copied()).as_deref(),+ Some("old")+ );+ }++ #[test]+ fn a_busy_model_is_never_evicted_even_if_it_is_oldest() {+ // Upstream's rule (server-models.cpp:92-95): evicting a model with a+ // request in flight would cancel a live generation.+ let entries = [("old-but-busy", 3usize, 1u64), ("idle", 0, 9)];+ assert_eq!(+ pick_lru_idle(entries.iter().copied()).as_deref(),+ Some("idle")+ );+ }++ #[test]+ fn nothing_is_evictable_when_every_model_is_busy() {+ let entries = [("a", 1usize, 1u64), ("b", 2, 2)];+ assert_eq!(pick_lru_idle(entries.iter().copied()), None);+ }++ #[test]+ fn a_specs_model_path_is_found_in_either_spelling() {+ assert_eq!(+ spec_model_path(&["ctx-size = 4096".into(), "model = /m/a.gguf".into()]),+ Some("/m/a.gguf".to_string())+ );+ assert_eq!(+ spec_model_path(&["-m".into(), "/m/b.gguf".into()]),+ Some("/m/b.gguf".to_string())+ );+ assert_eq!(spec_model_path(&["ctx-size = 4096".into()]), None);+ }++ // `mmproj` and `model-draft` also end in a path; matching them would stamp+ // the state guard against the wrong file.+ #[test]+ fn a_key_merely_ending_in_model_is_not_the_model_path() {+ assert_eq!(spec_model_path(&["mmproj = /m/mm.gguf".into()]), None);+ assert_eq!(spec_model_path(&["model-draft = /m/d.gguf".into()]), None);+ }++ #[test]+ fn state_identity_follows_the_registered_spec() {+ let mut r = reg(1, &[]);+ r.register("m", spec("/m/a.gguf"));+ let id = r.state_identity("m").expect("registered");+ assert_eq!(id.model, "m");+ r.register("m", spec("/m/b.gguf"));+ assert_ne!(+ r.state_identity("m").unwrap().spec,+ id.spec,+ "a spec change must invalidate saved state"+ );+ assert!(r.state_identity("absent").is_none());+ }++ #[test]+ fn ticks_are_monotonic_so_lru_order_cannot_invert() {+ let a = next_tick();+ let b = next_tick();+ assert!(b > a, "tick went backwards: {a} then {b}");+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rsnew file mode 100644index 000000000..fe569d380--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rs@@ -0,0 +1,809 @@+//! Persistence of a thread's KV cache across sessions.+//!+//! llama.cpp can already write a slot's KV cache to disk+//! (`POST /slots/{id}?action=save`, `server-context.cpp:2475`), but the file it+//! writes carries no identity: `llama_state_seq_load_file` checks a magic and a+//! version, and the restore path checks that the tokens fit the context and are+//! in the vocab. None of that notices that the file was written by a *different+//! model*, or by a build whose KV layout has since changed -- both of which+//! restore as plausible-looking nonsense rather than an error.+//!+//! So every state file gets a sidecar recording what produced it, and a restore+//! that disagrees is refused and deleted rather than fed to llama.cpp. The+//! guard is deliberately broader than "same model": `spec` is the model's whole+//! preset section, so a changed `ctx-size`, `cache-type-k`, `flash-attn` or+//! `parallel` invalidates the state too, since each of those changes what the+//! cache means.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++/// Files below this many tokens are not worth their write: the prefill they+/// save is shorter than the disk round trip that restores them.+pub const MIN_TOKENS_TO_SAVE: u64 = 256;++/// Sidecar suffix. The state file itself is `<key>.bin`, which is what+/// llama.cpp is handed; `fs_validate_filename` accepts it because the key is+/// hex.+const STATE_EXT: &str = "bin";+const META_EXT: &str = "json";++/// What produced a state file. Every field is part of the restore guard except+/// `n_tokens` and `saved_at`, which are reporting and pruning respectively.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StateMeta {+ /// The model id the state was captured under.+ pub model: String,+ /// The thread the state belongs to. Not part of the guard -- the file name+ /// already encodes it -- but recorded so a thread's state can be erased+ /// without the caller knowing which model produced it, which is exactly the+ /// position the UI is in when a thread is deleted.+ #[serde(default)]+ pub thread: String,+ /// Fingerprint of the model's preset section, so a settings change that+ /// alters the cache layout invalidates the state.+ pub spec: String,+ /// llama.cpp build the state was written by. The KV serialization format is+ /// versioned, but the *contents* are not: a build that changes cache layout+ /// without bumping the version restores silently corrupt state.+ pub llama_build: String,+ pub llama_commit: String,+ /// Size and mtime of the gguf, so replacing a model file in place (a+ /// re-download, a quant swap) is caught even though the path is unchanged.+ pub model_bytes: u64,+ pub model_mtime: u64,+ pub n_tokens: u64,+ pub saved_at: u64,+}++/// Why a state file cannot be used. Every arm is a reason to delete the file:+/// none of them can become valid again for the request that just asked.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Reject {+ /// Nothing was ever saved for this key.+ Absent,+ /// The sidecar is missing or unreadable, so the file's provenance is+ /// unknown. Treated as a mismatch rather than trusted.+ NoMeta,+ ModelChanged {+ saved: String,+ wanted: String,+ },+ SettingsChanged,+ LlamaChanged {+ saved: String,+ wanted: String,+ },+ ModelFileChanged,+}++impl std::fmt::Display for Reject {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Absent => write!(f, "no saved state"),+ Self::NoMeta => write!(f, "saved state has no sidecar, so its origin is unknown"),+ Self::ModelChanged { saved, wanted } => {+ write!(f, "saved state is for model {saved}, not {wanted}")+ }+ Self::SettingsChanged => {+ write!(+ f,+ "the model's load settings changed since the state was saved"+ )+ }+ Self::LlamaChanged { saved, wanted } => {+ write!(+ f,+ "saved state is from llama.cpp {saved}, this build is {wanted}"+ )+ }+ Self::ModelFileChanged => write!(f, "the model file changed since the state was saved"),+ }+ }+}++/// The identity a restore is checked against. Built once per request from the+/// registry, so the comparison cannot drift from what was actually loaded.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Identity {+ pub model: String,+ pub spec: String,+ pub llama_build: String,+ pub llama_commit: String,+ pub model_bytes: u64,+ pub model_mtime: u64,+}++impl Identity {+ /// `spec_body` is the model's preset section (shared `[*]` block included),+ /// which `LoadSpec::Preset` already carries and keeps sorted.+ pub fn new(model: &str, spec_body: &[String], model_path: Option<&Path>) -> Self {+ let (model_bytes, model_mtime) = model_path.map(file_stamp).unwrap_or((0, 0));+ Self {+ model: model.to_string(),+ spec: fingerprint(spec_body),+ llama_build: super::PINNED_BUILD_NUMBER.to_string(),+ llama_commit: super::PINNED_COMMIT.to_string(),+ model_bytes,+ model_mtime,+ }+ }++ fn into_meta(self, thread: &str, n_tokens: u64) -> StateMeta {+ StateMeta {+ model: self.model,+ thread: thread.to_string(),+ spec: self.spec,+ llama_build: self.llama_build,+ llama_commit: self.llama_commit,+ model_bytes: self.model_bytes,+ model_mtime: self.model_mtime,+ n_tokens,+ saved_at: now_secs(),+ }+ }++ /// The whole condition, in one place: same model, same load settings, same+ /// llama.cpp, same model file.+ pub fn accepts(&self, meta: &StateMeta) -> Result<(), Reject> {+ if meta.model != self.model {+ return Err(Reject::ModelChanged {+ saved: meta.model.clone(),+ wanted: self.model.clone(),+ });+ }+ if meta.llama_build != self.llama_build || meta.llama_commit != self.llama_commit {+ return Err(Reject::LlamaChanged {+ saved: format!("{} ({})", meta.llama_build, short(&meta.llama_commit)),+ wanted: format!("{} ({})", self.llama_build, short(&self.llama_commit)),+ });+ }+ if meta.spec != self.spec {+ return Err(Reject::SettingsChanged);+ }+ // A stamp of 0 means the path was not known at save or at restore, so+ // there is nothing to compare rather than a mismatch to report.+ let stamped = meta.model_bytes != 0 && self.model_bytes != 0;+ if stamped && (meta.model_bytes != self.model_bytes || meta.model_mtime != self.model_mtime)+ {+ return Err(Reject::ModelFileChanged);+ }+ Ok(())+ }+}++fn short(commit: &str) -> &str {+ &commit[..commit.len().min(8)]+}++fn now_secs() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++fn file_stamp(path: &Path) -> (u64, u64) {+ match std::fs::metadata(path) {+ Ok(m) => {+ let mtime = m+ .modified()+ .ok()+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())+ .map(|d| d.as_secs())+ .unwrap_or(0);+ (m.len(), mtime)+ }+ Err(_) => (0, 0),+ }+}++fn fingerprint(lines: &[String]) -> String {+ let mut h = Sha256::new();+ for l in lines {+ h.update(l.as_bytes());+ h.update([0u8]);+ }+ hex16(&h.finalize())+}++/// The file name for one (model, thread) pair.+///+/// Hashed rather than composed from the ids: a thread id is a uuid and a model+/// id is user-facing text that can hold path separators, spaces and non-ascii,+/// none of which `fs_validate_filename` accepts. Hex is also what keeps the+/// name inside the 255-byte limit that same function enforces.+pub fn state_key(model: &str, thread: &str) -> String {+ let mut h = Sha256::new();+ h.update(model.as_bytes());+ h.update([0u8]);+ h.update(thread.as_bytes());+ hex16(&h.finalize())+}++fn hex16(digest: &[u8]) -> String {+ digest.iter().take(16).map(|b| format!("{b:02x}")).collect()+}++/// The directory of saved states, and the operations over it.+///+/// The same directory llama.cpp was given as `--slot-save-path`: it joins the+/// file name onto that prefix itself, so both sides must agree on it and only+/// the *name* crosses the boundary.+#[derive(Debug)]+pub struct StateStore {+ dir: PathBuf,+ /// Total bytes of state files to keep. Pruning is LRU by save time, so the+ /// thread the user is actually working in is the last to go.+ ///+ /// Atomic because the user can lower it mid-session and a limit that only+ /// took effect at the next launch would leave the disk they were trying to+ /// reclaim occupied until then.+ budget_bytes: std::sync::atomic::AtomicU64,+}++impl StateStore {+ pub fn new(dir: impl Into<PathBuf>, budget_mib: u64) -> Self {+ Self {+ dir: dir.into(),+ budget_bytes: std::sync::atomic::AtomicU64::new(budget_mib.saturating_mul(1024 * 1024)),+ }+ }++ fn budget(&self) -> u64 {+ self.budget_bytes.load(std::sync::atomic::Ordering::Relaxed)+ }++ /// Whether anything new may be written. A zero budget is the off switch, but+ /// the store still exists at that setting: the directory a previous session+ /// filled has to be reclaimable, and a deleted thread's state erasable,+ /// which needs a store rather than a flag.+ pub fn saves_enabled(&self) -> bool {+ self.budget() > 0+ }++ /// Applies a new budget and reclaims down to it at once. Returns the keys+ /// dropped.+ pub fn set_budget_mib(&self, budget_mib: u64) -> Vec<String> {+ self.budget_bytes.store(+ budget_mib.saturating_mul(1024 * 1024),+ std::sync::atomic::Ordering::Relaxed,+ );+ self.prune()+ }++ pub fn dir(&self) -> &Path {+ &self.dir+ }++ /// Creates the directory. llama.cpp's `--slot-save-path` handler *throws*+ /// when the path is not a directory (`common/arg.cpp:3580`), and that+ /// unwinds out of engine startup, so a missing cache directory would take+ /// the whole engine down rather than disabling one feature.+ pub fn ensure_dir(&self) -> std::io::Result<()> {+ std::fs::create_dir_all(&self.dir)+ }++ fn state_path(&self, key: &str) -> PathBuf {+ self.dir.join(format!("{key}.{STATE_EXT}"))+ }++ fn meta_path(&self, key: &str) -> PathBuf {+ self.dir.join(format!("{key}.{META_EXT}"))+ }++ /// The name to hand llama.cpp, which resolves it against the same+ /// directory.+ pub fn state_file_name(key: &str) -> String {+ format!("{key}.{STATE_EXT}")+ }++ /// Whether a restore may proceed, and why not when it may not.+ ///+ /// A rejected file is deleted here: keeping it would re-run the same+ /// comparison on every later turn of a thread that can never use it.+ pub fn check(&self, key: &str, want: &Identity) -> Result<StateMeta, Reject> {+ if !self.state_path(key).is_file() {+ // A sidecar with no state file is debris from a failed save.+ let _ = std::fs::remove_file(self.meta_path(key));+ return Err(Reject::Absent);+ }+ let Some(meta) = self.read_meta(key) else {+ self.forget(key);+ return Err(Reject::NoMeta);+ };+ match want.accepts(&meta) {+ Ok(()) => Ok(meta),+ Err(e) => {+ self.forget(key);+ Err(e)+ }+ }+ }++ fn read_meta(&self, key: &str) -> Option<StateMeta> {+ let raw = std::fs::read_to_string(self.meta_path(key)).ok()?;+ serde_json::from_str(&raw).ok()+ }++ /// Records what a just-written state file contains. Called *after*+ /// llama.cpp wrote the `.bin`, so a crash between the two leaves an+ /// orphaned state file, which `check` treats as `NoMeta` and removes.+ pub fn commit(+ &self,+ key: &str,+ want: Identity,+ thread: &str,+ n_tokens: u64,+ ) -> std::io::Result<()> {+ let meta = want.into_meta(thread, n_tokens);+ let json = serde_json::to_string(&meta).map_err(std::io::Error::other)?;+ write_atomic(&self.meta_path(key), json.as_bytes())?;+ self.prune();+ Ok(())+ }++ /// Drops both files for a key. Used on a rejected restore and on thread+ /// deletion.+ pub fn forget(&self, key: &str) {+ let _ = std::fs::remove_file(self.state_path(key));+ let _ = std::fs::remove_file(self.meta_path(key));+ }++ /// Every saved key with its size and save time, oldest first.+ fn entries(&self) -> Vec<(String, u64, u64)> {+ let mut out = Vec::new();+ let Ok(rd) = std::fs::read_dir(&self.dir) else {+ return out;+ };+ for e in rd.flatten() {+ let path = e.path();+ if path.extension().and_then(|s| s.to_str()) != Some(STATE_EXT) {+ continue;+ }+ let Some(key) = path.file_stem().and_then(|s| s.to_str()) else {+ continue;+ };+ let bytes = e.metadata().map(|m| m.len()).unwrap_or(0);+ // Fall back to the file's own mtime when the sidecar is gone, so an+ // orphan still takes part in pruning instead of being immortal.+ let saved_at = self+ .read_meta(key)+ .map(|m| m.saved_at)+ .unwrap_or_else(|| file_stamp(&path).1);+ out.push((key.to_string(), bytes, saved_at));+ }+ out.sort_by_key(|(_, _, saved_at)| *saved_at);+ out+ }++ pub fn total_bytes(&self) -> u64 {+ self.entries().iter().map(|(_, b, _)| *b).sum()+ }++ /// Deletes oldest-first until the directory fits the budget. A single state+ /// file can be hundreds of MiB, so an unbounded directory is the difference+ /// between a cache and a disk leak.+ pub fn prune(&self) -> Vec<String> {+ let entries = self.entries();+ let mut total: u64 = entries.iter().map(|(_, b, _)| *b).sum();+ let mut dropped = Vec::new();+ for (key, bytes, _) in entries {+ if total <= self.budget() {+ break;+ }+ self.forget(&key);+ total = total.saturating_sub(bytes);+ dropped.push(key);+ }+ dropped+ }++ /// Drops every state for a model, for an unload that changed its settings.+ pub fn forget_model(&self, model: &str) -> usize {+ self.forget_where(|m| m.model == model)+ }++ /// Drops a thread's state whichever model produced it. A thread the user+ /// deleted may have been talked to under several models, and the caller+ /// knows the thread id and nothing else.+ pub fn forget_thread(&self, thread: &str) -> usize {+ self.forget_where(|m| m.thread == thread)+ }++ fn forget_where(&self, pred: impl Fn(&StateMeta) -> bool) -> usize {+ let mut n = 0;+ for (key, _, _) in self.entries() {+ if self.read_meta(&key).is_some_and(|m| pred(&m)) {+ self.forget(&key);+ n += 1;+ }+ }+ n+ }+}++fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, bytes)?;+ std::fs::rename(&tmp, path)+}++/// Which thread's state each slot is holding, per model.+///+/// The worker needs this because a save has to name a slot, and only the worker+/// knows which thread last ran there. Chat is pinned to slot 0 by the frontend+/// (`custom-chat-transport.ts`), so in practice this is one entry per model,+/// but nothing here assumes that.+#[derive(Debug, Default)]+pub struct SlotOccupancy {+ resident: HashMap<(String, i32), String>,+}++/// What claiming a slot did, which decides what has to happen to disk.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Claim {+ /// The thread was already in this slot. Nothing to do: the live cache is+ /// newer than anything on disk, so restoring over it would *lose* the+ /// last turn's prefill rather than save any.+ Unchanged,+ /// Nobody was in the slot -- a fresh worker. This is the cross-session+ /// case: restore, but there is nothing to park.+ Empty,+ /// Another thread was in the slot. Its cache has to reach disk before the+ /// restore overwrites it.+ Evicted(String),+}++impl SlotOccupancy {+ /// Records that `thread` now owns `slot` of `model`.+ pub fn claim(&mut self, model: &str, slot: i32, thread: &str) -> Claim {+ let prev = self+ .resident+ .insert((model.to_string(), slot), thread.to_string());+ match prev {+ None => Claim::Empty,+ Some(p) if p == thread => Claim::Unchanged,+ Some(p) => Claim::Evicted(p),+ }+ }++ pub fn get(&self, model: &str, slot: i32) -> Option<&str> {+ self.resident+ .get(&(model.to_string(), slot))+ .map(|s| s.as_str())+ }++ /// Everything resident, for the save-everything pass at shutdown.+ pub fn all(&self) -> Vec<(String, i32, String)> {+ let mut v: Vec<_> = self+ .resident+ .iter()+ .map(|((m, s), t)| (m.clone(), *s, t.clone()))+ .collect();+ v.sort();+ v+ }++ pub fn release_model(&mut self, model: &str) {+ self.resident.retain(|(m, _), _| m != model);+ }++ /// Forgets a thread wherever it is sitting. Without this an erase would+ /// leave the slot still claimed by a deleted thread, and the next thread to+ /// take it would save that dead id's state right back to disk.+ pub fn release_thread(&mut self, thread: &str) {+ self.resident.retain(|_, t| t != thread);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmpdir(tag: &str) -> PathBuf {+ let p = std::env::temp_dir().join(format!(+ "jan-slots-test-{tag}-{}-{}",+ std::process::id(),+ now_secs()+ ));+ std::fs::create_dir_all(&p).unwrap();+ p+ }++ fn ident(model: &str, spec: &[&str]) -> Identity {+ let body: Vec<String> = spec.iter().map(|s| s.to_string()).collect();+ Identity::new(model, &body, None)+ }++ fn store(tag: &str) -> StateStore {+ StateStore::new(tmpdir(tag), 1024)+ }++ fn plant(s: &StateStore, key: &str, bytes: usize) {+ std::fs::write(s.state_path(key), vec![0u8; bytes]).unwrap();+ }++ #[test]+ fn a_key_is_stable_and_separates_models_and_threads() {+ assert_eq!(state_key("m", "t"), state_key("m", "t"));+ assert_ne!(state_key("m", "t"), state_key("m", "t2"));+ assert_ne!(state_key("m", "t"), state_key("m2", "t"));+ // The name has to survive llama.cpp's fs_validate_filename, which+ // rejects separators and anything non-printable.+ let k = state_key("Qwen3/0.6B IQ4_XS", "0f9a-uuid");+ assert_eq!(k.len(), 32);+ assert!(k.chars().all(|c| c.is_ascii_hexdigit()), "{k}");+ }++ #[test]+ fn an_absent_state_is_reported_rather_than_restored() {+ let s = store("absent");+ assert_eq!(+ s.check("deadbeef", &ident("m", &["a"])),+ Err(Reject::Absent)+ );+ }++ #[test]+ fn a_matching_state_is_accepted() {+ let s = store("match");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ s.commit(&key, ident("m", &["ctx-size = 4096"]), "t", 900)+ .unwrap();+ let meta = s+ .check(&key, &ident("m", &["ctx-size = 4096"]))+ .expect("same model, same settings, same build");+ assert_eq!(meta.n_tokens, 900);+ }++ #[test]+ fn a_different_model_is_refused_and_the_file_dropped() {+ let s = store("model");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ s.commit(&key, ident("m", &["a"]), "t", 900).unwrap();+ let err = s.check(&key, &ident("other", &["a"])).unwrap_err();+ assert!(matches!(err, Reject::ModelChanged { .. }), "{err:?}");+ assert!(+ !s.state_path(&key).exists(),+ "a state that can never match again must not be kept"+ );+ }++ #[test]+ fn a_changed_setting_invalidates_the_state() {+ let s = store("spec");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ s.commit(&key, ident("m", &["ctx-size = 4096"]), "t", 900)+ .unwrap();+ assert_eq!(+ s.check(&key, &ident("m", &["ctx-size = 8192"]))+ .unwrap_err(),+ Reject::SettingsChanged+ );+ }++ #[test]+ fn a_different_llama_build_is_refused() {+ let s = store("build");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ let mut stale = ident("m", &["a"]);+ stale.llama_build = "1".to_string();+ stale.llama_commit = "0000000000".to_string();+ s.commit(&key, stale, "t", 900).unwrap();+ let err = s.check(&key, &ident("m", &["a"])).unwrap_err();+ assert!(matches!(err, Reject::LlamaChanged { .. }), "{err:?}");+ }++ #[test]+ fn a_replaced_model_file_is_refused_even_at_the_same_path() {+ let s = store("gguf");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ let mut before = ident("m", &["a"]);+ before.model_bytes = 4096;+ before.model_mtime = 111;+ s.commit(&key, before, "t", 900).unwrap();+ let mut after = ident("m", &["a"]);+ after.model_bytes = 8192;+ after.model_mtime = 222;+ assert_eq!(s.check(&key, &after).unwrap_err(), Reject::ModelFileChanged);+ }++ // A path that neither side could stat is not evidence of a change.+ #[test]+ fn an_unstamped_model_file_is_not_treated_as_a_mismatch() {+ let s = store("unstamped");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ s.commit(&key, ident("m", &["a"]), "t", 900).unwrap();+ let mut wanted = ident("m", &["a"]);+ wanted.model_bytes = 0;+ assert!(s.check(&key, &wanted).is_ok());+ }++ #[test]+ fn a_state_file_without_a_sidecar_is_refused_not_trusted() {+ let s = store("orphan");+ let key = state_key("m", "t");+ plant(&s, &key, 8);+ assert_eq!(+ s.check(&key, &ident("m", &["a"])).unwrap_err(),+ Reject::NoMeta+ );+ assert!(!s.state_path(&key).exists());+ }++ #[test]+ fn a_sidecar_without_a_state_file_is_swept() {+ let s = store("halfsave");+ let key = state_key("m", "t");+ s.commit(&key, ident("m", &["a"]), "t", 900).unwrap();+ assert_eq!(+ s.check(&key, &ident("m", &["a"])).unwrap_err(),+ Reject::Absent+ );+ assert!(!s.meta_path(&key).exists(), "debris must not accumulate");+ }++ /// Plants a state file and its sidecar without going through `commit`,+ /// which prunes as it writes -- the point here is to control `saved_at`,+ /// whose one-second resolution cannot order four writes in a loop.+ fn plant_aged(s: &StateStore, key: &str, bytes: usize, saved_at: u64) {+ plant(s, key, bytes);+ let mut meta = ident("m", &["a"]).into_meta("t", 900);+ meta.saved_at = saved_at;+ std::fs::write(s.meta_path(key), serde_json::to_string(&meta).unwrap()).unwrap();+ }++ #[test]+ fn pruning_drops_the_oldest_until_the_budget_fits() {+ // 3 MiB of budget, four 1 MiB states.+ let s = StateStore::new(tmpdir("prune"), 3);+ for i in 0..4 {+ plant_aged(+ &s,+ &state_key("m", &format!("t{i}")),+ 1024 * 1024,+ 1000 + i as u64,+ );+ }+ let dropped = s.prune();+ assert_eq!(dropped, vec![state_key("m", "t0")], "oldest first");+ assert!(s.total_bytes() <= 3 * 1024 * 1024);+ assert!(s.state_path(&state_key("m", "t3")).exists(), "newest kept");+ }++ // A write that alone blows the budget is pruned rather than left to grow+ // the directory past it -- and it is the last candidate, not the first,+ // because it is the newest.+ #[test]+ fn a_single_oversized_state_does_not_escape_the_budget() {+ let s = StateStore::new(tmpdir("oversize"), 1);+ let key = state_key("m", "t");+ plant(&s, &key, 4 * 1024 * 1024);+ s.commit(&key, ident("m", &["a"]), "t", 900).unwrap();+ assert!(s.total_bytes() <= 1024 * 1024);+ assert!(!s.state_path(&key).exists());+ }++ // Turning the feature off has to reclaim what an earlier session saved, and+ // has to stop new writes. Both hang off the budget being zero, which is why+ // the store outlives the setting.+ #[test]+ fn a_zero_budget_clears_the_directory_and_stops_saves() {+ let s = StateStore::new(tmpdir("off"), 0);+ assert!(!s.saves_enabled());+ let key = state_key("m", "t");+ plant_aged(&s, &key, 1024, 1000);+ assert_eq!(s.prune(), vec![key.clone()]);+ assert!(+ !s.meta_path(&key).exists(),+ "the sidecar goes with the state"+ );+ assert_eq!(s.total_bytes(), 0);+ }++ #[test]+ fn forget_model_clears_only_that_models_states() {+ let s = store("forget");+ for (model, thread) in [("a", "t1"), ("a", "t2"), ("b", "t1")] {+ let key = state_key(model, thread);+ plant(&s, &key, 8);+ s.commit(&key, ident(model, &["x"]), thread, 900).unwrap();+ }+ assert_eq!(s.forget_model("a"), 2);+ assert!(s.state_path(&state_key("b", "t1")).exists());+ }++ // A thread the user deletes has to be erasable without the caller knowing+ // which model produced its state, since the UI does not track that.+ #[test]+ fn forget_thread_clears_that_thread_under_every_model() {+ let s = store("forget-thread");+ for (model, thread) in [("a", "t1"), ("b", "t1"), ("a", "t2")] {+ let key = state_key(model, thread);+ plant(&s, &key, 8);+ s.commit(&key, ident(model, &["x"]), thread, 900).unwrap();+ }+ assert_eq!(s.forget_thread("t1"), 2);+ assert!(s.state_path(&state_key("a", "t2")).exists());+ }++ // A sidecar written before `thread` existed has no thread to match, and+ // must not be treated as belonging to every thread.+ #[test]+ fn a_sidecar_with_no_thread_field_is_not_matched_by_forget_thread() {+ let s = store("legacy-meta");+ let key = state_key("m", "t1");+ plant(&s, &key, 8);+ let mut meta = ident("m", &["x"]).into_meta("t1", 900);+ meta.thread = String::new();+ std::fs::write(s.meta_path(&key), serde_json::to_string(&meta).unwrap()).unwrap();+ assert_eq!(s.forget_thread("t1"), 0);+ assert_eq!(s.forget_model("m"), 1, "the model is still recorded");+ }++ #[test]+ fn releasing_a_thread_frees_the_slot_it_was_sitting_in() {+ let mut occ = SlotOccupancy::default();+ occ.claim("m", 0, "t1");+ occ.claim("m2", 1, "t1");+ occ.release_thread("t1");+ // Left claimed, the next thread in that slot would save the deleted+ // thread's state straight back to disk.+ assert!(occ.all().is_empty());+ }++ #[test]+ fn the_state_file_name_is_what_llama_cpp_is_handed() {+ assert_eq!(StateStore::state_file_name("ab12"), "ab12.bin");+ }++ #[test]+ fn claiming_a_slot_distinguishes_empty_from_evicted() {+ let mut occ = SlotOccupancy::default();+ assert_eq!(occ.claim("m", 0, "t1"), Claim::Empty);+ assert_eq!(occ.claim("m", 0, "t2"), Claim::Evicted("t1".to_string()));+ assert_eq!(occ.get("m", 0), Some("t2"));+ }++ // The distinction that matters most: turn 2 of a thread must not restore+ // over its own live cache, which is newer than anything on disk. Reporting+ // this as an eviction would cost a full prefill on every turn.+ #[test]+ fn a_second_turn_in_the_same_thread_is_unchanged_not_a_handover() {+ let mut occ = SlotOccupancy::default();+ occ.claim("m", 0, "t1");+ assert_eq!(occ.claim("m", 0, "t1"), Claim::Unchanged);+ assert_eq!(occ.claim("m", 0, "t1"), Claim::Unchanged);+ }++ #[test]+ fn occupancy_is_per_model_and_per_slot() {+ let mut occ = SlotOccupancy::default();+ occ.claim("m1", 0, "t1");+ occ.claim("m2", 0, "t2");+ occ.claim("m1", 1, "t3");+ assert_eq!(occ.get("m1", 0), Some("t1"));+ assert_eq!(+ occ.all(),+ vec![+ ("m1".to_string(), 0, "t1".to_string()),+ ("m1".to_string(), 1, "t3".to_string()),+ ("m2".to_string(), 0, "t2".to_string()),+ ]+ );+ occ.release_model("m1");+ assert_eq!(occ.get("m1", 0), None);+ assert_eq!(occ.get("m2", 0), Some("t2"));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rsnew file mode 100644index 000000000..6c7371a85--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/sys.rs@@ -0,0 +1,467 @@+//! The FFI boundary itself. Two implementations behind one API: the real one+//! when the `engine` feature compiled llama.cpp in, and a stub that reports+//! `Unavailable` otherwise, so the rest of the crate compiles either way.++use super::EngineError;++/// Load-lifecycle notifications from the engine: `(state, payload_json)`,+/// llama.cpp's own `server_state` name and its JSON. Called on the loading+/// thread, and later on the engine's loop thread for a sleep/resume, so it+/// must be `Send + Sync`.+pub type StateCallback = std::sync::Arc<dyn Fn(&str, &str) + Send + Sync>;++#[cfg(feature = "engine")]+mod imp {+ use super::EngineError;+ use std::ffi::{c_char, c_int, c_void, CStr, CString};++ use super::StateCallback;++ type EngineHandle = *mut c_void;+ type ResponseHandle = *mut c_void;+ type StateTrampoline =+ unsafe extern "C" fn(state: *const c_char, payload: *const c_char, user_data: *mut c_void);++ // The shim's ABI. Hand-declared rather than bindgen-generated: it is our+ // own 14-function surface, so there is no upstream struct layout to track+ // and no libclang on the build path.+ extern "C" {+ fn jan_llama_engine_start(+ argv: *const *const c_char,+ argc: c_int,+ on_state: Option<StateTrampoline>,+ user_data: *mut c_void,+ err: *mut u8,+ err_len: usize,+ ) -> EngineHandle;+ fn jan_llama_engine_start_from_preset(+ ini_path: *const c_char,+ preset_name: *const c_char,+ on_state: Option<StateTrampoline>,+ user_data: *mut c_void,+ err: *mut u8,+ err_len: usize,+ ) -> EngineHandle;+ fn jan_llama_engine_stop(engine: EngineHandle) -> c_int;+ fn jan_llama_engine_request(+ engine: EngineHandle,+ route: *const c_char,+ query: *const c_char,+ body: *const c_char,+ body_len: usize,+ ) -> ResponseHandle;+ fn jan_llama_response_status(res: ResponseHandle) -> c_int;+ fn jan_llama_response_content_type(res: ResponseHandle) -> *const c_char;+ fn jan_llama_response_body(res: ResponseHandle, len: *mut usize) -> *const c_char;+ fn jan_llama_response_is_stream(res: ResponseHandle) -> c_int;+ fn jan_llama_response_next(+ res: ResponseHandle,+ chunk: *mut *const c_char,+ len: *mut usize,+ ) -> c_int;+ fn jan_llama_response_cancel(res: ResponseHandle);+ fn jan_llama_response_free(res: ResponseHandle);+ fn jan_llama_load_backends(dir: *const c_char);+ fn jan_llama_devices_json() -> *mut c_char;+ fn jan_llama_string_free(s: *mut c_char);+ fn jan_llama_version() -> *const c_char;+ fn jan_llama_build_number() -> c_int;+ fn jan_llama_commit() -> *const c_char;+ }++ /// SAFETY: the handle is only ever produced by the shim and only consumed+ /// by it. The C++ side funnels every request through `server_queue`, which+ /// is the same cross-thread channel llama-server's HTTP workers use, so+ /// sharing one engine across threads is the intended usage.+ pub struct Engine {+ handle: EngineHandle,+ /// Kept alive for exactly as long as the engine: the C++ side holds a+ /// `std::function` wrapping this pointer and can call it from its loop+ /// thread, so it is freed only after `jan_llama_engine_stop` reports+ /// that it joined that thread. On the detach path it is leaked instead.+ state_cb: Option<*mut StateCallback>,+ }+ unsafe impl Send for Engine {}+ unsafe impl Sync for Engine {}++ /// The C ABI entry point handed to the shim. Panics are caught rather than+ /// unwound into C++, where unwinding past a `noexcept` boundary is+ /// undefined; a poisoned callback drops its sample instead.+ unsafe extern "C" fn state_trampoline(+ state: *const c_char,+ payload: *const c_char,+ user_data: *mut c_void,+ ) {+ if user_data.is_null() {+ return;+ }+ let _ = std::panic::catch_unwind(|| {+ let cb = unsafe { &*(user_data as *const StateCallback) };+ let state = unsafe { CStr::from_ptr(state) }.to_string_lossy();+ let payload = if payload.is_null() {+ std::borrow::Cow::Borrowed("{}")+ } else {+ unsafe { CStr::from_ptr(payload) }.to_string_lossy()+ };+ cb(&state, &payload);+ });+ }++ /// Leaks the callback for the duration of the call; `from_handle` either+ /// hands ownership to the `Engine` or frees it.+ fn leak_state_cb(cb: Option<StateCallback>) -> Option<*mut StateCallback> {+ cb.map(|c| Box::into_raw(Box::new(c)))+ }++ impl std::fmt::Debug for Engine {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // The handle is an opaque C++ pointer; printing it is noise.+ f.write_str("Engine(<llama.cpp server_context>)")+ }+ }++ /// Room for the shim's summary plus the llama.cpp error lines it captured+ /// during the load; a load failure carries several and 1 KiB truncated+ /// them mid-cause.+ const ERR_BUF_LEN: usize = 4096;++ impl Engine {+ /// Starts from llama-server's own flag set, so callers reuse the+ /// upstream arg table instead of mirroring `common_params`.+ pub fn start(args: &[String], on_state: Option<StateCallback>) -> Result<Self, EngineError> {+ let owned: Vec<CString> = args+ .iter()+ .map(|a| CString::new(a.as_str()).unwrap_or_default())+ .collect();+ let argv: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();+ let mut err = vec![0u8; ERR_BUF_LEN];+ let state_cb = leak_state_cb(on_state);+ // SAFETY: argv points at `owned`, alive for the call; the shim+ // copies every string and retains none of these pointers.+ let handle = unsafe {+ jan_llama_engine_start(+ argv.as_ptr(),+ argv.len() as c_int,+ state_cb.map(|_| state_trampoline as StateTrampoline),+ state_cb.map_or(std::ptr::null_mut(), |p| p as *mut c_void),+ err.as_mut_ptr(),+ err.len(),+ )+ };+ Self::from_handle(handle, state_cb, &err)+ }++ /// Starts from a `router.preset.ini` section, the file Jan already+ /// generates. `[*]` is applied first, then the named section.+ pub fn start_from_preset(+ ini_path: &str,+ preset: &str,+ on_state: Option<StateCallback>,+ ) -> Result<Self, EngineError> {+ let ini = CString::new(ini_path).map_err(|e| EngineError::Start(e.to_string()))?;+ let name = CString::new(preset).map_err(|e| EngineError::Start(e.to_string()))?;+ let mut err = vec![0u8; ERR_BUF_LEN];+ let state_cb = leak_state_cb(on_state);+ // SAFETY: both pointers are valid for the duration of the call.+ let handle = unsafe {+ jan_llama_engine_start_from_preset(+ ini.as_ptr(),+ name.as_ptr(),+ state_cb.map(|_| state_trampoline as StateTrampoline),+ state_cb.map_or(std::ptr::null_mut(), |p| p as *mut c_void),+ err.as_mut_ptr(),+ err.len(),+ )+ };+ Self::from_handle(handle, state_cb, &err)+ }++ fn from_handle(+ handle: EngineHandle,+ state_cb: Option<*mut StateCallback>,+ err: &[u8],+ ) -> Result<Self, EngineError> {+ if handle.is_null() {+ // Nothing on the C++ side survived to call it.+ if let Some(p) = state_cb {+ // SAFETY: leaked by this call and reachable from nowhere else.+ unsafe { drop(Box::from_raw(p)) };+ }+ let msg = CStr::from_bytes_until_nul(err)+ .map(|c| c.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "unknown error".to_string());+ return Err(EngineError::Start(msg));+ }+ Ok(Self { handle, state_cb })+ }++ pub fn request(&self, route: &str, body: &str) -> Response {+ self.request_with_query(route, "", body)+ }++ /// `query` is a url query string. llama.cpp takes a slot action+ /// (`id_slot=0&action=save`) from there rather than from the body, so+ /// the slot routes are unreachable through `request` alone.+ pub fn request_with_query(&self, route: &str, query: &str, body: &str) -> Response {+ let r = CString::new(route).unwrap_or_default();+ let q = CString::new(query).unwrap_or_default();+ let b = CString::new(body).unwrap_or_default();+ // The length must describe the buffer being passed, not the string+ // it came from: the shim does `std::string(body, body_len)`, and a+ // body with an interior NUL leaves `b` empty while `body.len()`+ // still counts every byte -- an out-of-bounds read of a one-byte+ // buffer. Taking both from `b` keeps them consistent by+ // construction; such a body reaches the engine empty and comes back+ // as an ordinary parse error.+ // SAFETY: the shim never returns null -- transport failures come+ // back as a 5xx response object -- and copies the body.+ let handle = unsafe {+ jan_llama_engine_request(+ self.handle,+ r.as_ptr(),+ q.as_ptr(),+ b.as_ptr(),+ b.as_bytes().len(),+ )+ };+ Response(handle)+ }++ /// Registers the ggml compute backends. `None` uses ggml's own search+ /// (executable directory, then cwd).+ pub fn load_backends(dir: Option<&str>) {+ match dir {+ Some(d) => {+ let c = CString::new(d).unwrap_or_default();+ // SAFETY: the shim copies nothing and only reads the+ // string for the duration of the call.+ unsafe { jan_llama_load_backends(c.as_ptr()) }+ }+ // SAFETY: null is the documented "use ggml's own search" value.+ None => unsafe { jan_llama_load_backends(std::ptr::null()) },+ }+ }++ /// The offloadable devices, as the shim's JSON array. Needs no engine:+ /// ggml devices are process-global, so this is an associated function.+ pub fn devices_json() -> Result<String, EngineError> {+ // SAFETY: the shim malloc()s the string and we hand the same+ // pointer back to its free; a null return is only OOM.+ let raw = unsafe { jan_llama_devices_json() };+ if raw.is_null() {+ return Err(EngineError::Unavailable);+ }+ let json = unsafe { CStr::from_ptr(raw) }.to_string_lossy().into_owned();+ unsafe { jan_llama_string_free(raw) };+ Ok(json)+ }++ pub fn linked_version() -> Result<String, EngineError> {+ // SAFETY: returns a pointer to a static string in the shim.+ Ok(unsafe { CStr::from_ptr(jan_llama_version()) }+ .to_string_lossy()+ .into_owned())+ }++ pub fn linked_build_number() -> Result<i32, EngineError> {+ // SAFETY: a plain int getter with no arguments.+ Ok(unsafe { jan_llama_build_number() })+ }++ pub fn linked_commit() -> Result<String, EngineError> {+ // SAFETY: returns a pointer to a static string in the shim.+ Ok(unsafe { CStr::from_ptr(jan_llama_commit()) }+ .to_string_lossy()+ .into_owned())+ }+ }++ impl Drop for Engine {+ fn drop(&mut self) {+ // SAFETY: called once, from Drop, on a handle we own.+ let detached = unsafe { jan_llama_engine_stop(self.handle) } != 0;+ if let Some(p) = self.state_cb.take() {+ if detached {+ // The loop thread outlived the stop timeout and was+ // detached rather than joined, so it is still running and+ // its `handle_sleeping_state` can still call the trampoline+ // with this pointer. The shim leaks the engine for exactly+ // this reason; matching it here is what keeps the two sides+ // agreeing. Clearing the callback instead would race the+ // live loop, so the leak is the sound option.+ log::error!(+ "llama.cpp server loop was detached, not joined; \+ leaking its state callback rather than freeing a \+ pointer the loop can still call"+ );+ } else {+ // SAFETY: `stop` joined the loop thread, so no callback can+ // be in flight; the box was leaked by `start` /+ // `start_from_preset` for this engine.+ unsafe { drop(Box::from_raw(p)) };+ }+ }+ }+ }++ /// One in-flight response. Either a whole body or a chunk generator; the+ /// request it was made from is owned on the C++ side and outlives it.+ pub struct Response(ResponseHandle);+ unsafe impl Send for Response {}++ impl std::fmt::Debug for Response {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Response")+ .field("status", &self.status())+ .field("is_stream", &self.is_stream())+ .finish()+ }+ }++ impl Response {+ pub fn status(&self) -> u16 {+ // SAFETY: handle is valid for our lifetime.+ (unsafe { jan_llama_response_status(self.0) }).clamp(0, u16::MAX as i32) as u16+ }++ pub fn content_type(&self) -> String {+ // SAFETY: points into the response's own std::string.+ unsafe { CStr::from_ptr(jan_llama_response_content_type(self.0)) }+ .to_string_lossy()+ .into_owned()+ }++ pub fn body(&self) -> String {+ let mut len = 0usize;+ // SAFETY: the shim returns a pointer plus length into a buffer that+ // lives as long as this response.+ unsafe {+ let p = jan_llama_response_body(self.0, &mut len);+ String::from_utf8_lossy(std::slice::from_raw_parts(p.cast::<u8>(), len))+ .into_owned()+ }+ }++ pub fn is_stream(&self) -> bool {+ // SAFETY: handle is valid for our lifetime.+ (unsafe { jan_llama_response_is_stream(self.0) }) != 0+ }++ /// `Ok(Some(chunk))` for a chunk (possibly empty, meaning "nothing+ /// yet"), `Ok(None)` when the stream is finished, `Err` if the+ /// generator threw.+ pub fn next_chunk(&mut self) -> Result<Option<String>, EngineError> {+ let mut p: *const c_char = std::ptr::null();+ let mut len = 0usize;+ // SAFETY: out-params are stack locals; the returned buffer is owned+ // by the response and valid until the next call on it.+ let rc = unsafe { jan_llama_response_next(self.0, &mut p, &mut len) };+ match rc {+ 1 => {+ // SAFETY: rc == 1 means p/len describe a live buffer.+ let s = unsafe {+ String::from_utf8_lossy(std::slice::from_raw_parts(p.cast::<u8>(), len))+ .into_owned()+ };+ Ok(Some(s))+ }+ 0 => Ok(None),+ _ => Err(EngineError::Start(+ "the response generator threw".to_string(),+ )),+ }+ }++ /// Asks the generator to stop. Safe to call from another thread, which+ /// is how a dropped HTTP connection cancels generation.+ pub fn cancel(&self) {+ // SAFETY: the shim's cancel flag is an atomic bool.+ unsafe { jan_llama_response_cancel(self.0) }+ }+ }++ impl Drop for Response {+ fn drop(&mut self) {+ // SAFETY: called once, from Drop, on a handle we own.+ unsafe { jan_llama_response_free(self.0) }+ }+ }+}++#[cfg(not(feature = "engine"))]+mod imp {+ use super::EngineError;++ /// Placeholder so the crate compiles without a C++ toolchain. Every entry+ /// point reports `Unavailable` rather than panicking, so a build without+ /// the feature degrades to "no local inference" instead of crashing.+ #[derive(Debug)]+ pub struct Engine(());++ impl Engine {+ pub fn start(+ _args: &[String],+ _on_state: Option<super::StateCallback>,+ ) -> Result<Self, EngineError> {+ Err(EngineError::Unavailable)+ }+ pub fn start_from_preset(+ _ini: &str,+ _preset: &str,+ _on_state: Option<super::StateCallback>,+ ) -> Result<Self, EngineError> {+ Err(EngineError::Unavailable)+ }+ /// A resident model that never serves a request, so the registry's+ /// bookkeeping -- eviction order, and which ids a drop path records --+ /// can be tested in the default feature config, where `start` always+ /// fails and nothing can otherwise reach `loaded`.+ #[cfg(test)]+ pub fn stub() -> Self {+ Engine(())+ }+ pub fn request(&self, _route: &str, _body: &str) -> Response {+ Response(())+ }+ pub fn request_with_query(&self, _route: &str, _query: &str, _body: &str) -> Response {+ Response(())+ }+ pub fn load_backends(_dir: Option<&str>) {}+ pub fn devices_json() -> Result<String, EngineError> {+ Err(EngineError::Unavailable)+ }+ pub fn linked_version() -> Result<String, EngineError> {+ Err(EngineError::Unavailable)+ }+ pub fn linked_build_number() -> Result<i32, EngineError> {+ Err(EngineError::Unavailable)+ }+ pub fn linked_commit() -> Result<String, EngineError> {+ Err(EngineError::Unavailable)+ }+ }++ #[derive(Debug)]+ pub struct Response(());++ impl Response {+ pub fn status(&self) -> u16 {+ 503+ }+ pub fn content_type(&self) -> String {+ "application/json; charset=utf-8".to_string()+ }+ pub fn body(&self) -> String {+ r#"{"error":{"message":"the llama.cpp engine was not compiled in"}}"#.to_string()+ }+ pub fn is_stream(&self) -> bool {+ false+ }+ pub fn next_chunk(&mut self) -> Result<Option<String>, EngineError> {+ Ok(None)+ }+ pub fn cancel(&self) {}+ }+}++pub use imp::{Engine, Response};diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rsnew file mode 100644index 000000000..16cab8ba4--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/watcher.rs@@ -0,0 +1,159 @@+//! The desktop's persistent subscriber to the worker's `/models/sse` feed.+//!+//! Distinct from the per-load listener in `commands::spawn_load_progress_listener`,+//! which exists only for the duration of one load: this one lives as long as+//! the worker and reports transitions Jan did not ask for. An LRU eviction+//! under `models_max` is the case that matters -- Jan flips `activeModels` off+//! for unloads it requested itself, so without this the UI keeps showing a+//! model the engine has already dropped.++use tauri::{Emitter, Runtime};++/// Emitted per unload, with the frontend payload `LlamacppOomListener` reads.+const UNLOADED_EVENT: &str = "llamacpp-model-unloaded";++/// Pause before re-subscribing after the stream ends. The worker outlives any+/// single connection, so a dropped stream is reconnected rather than treated as+/// the end of the feed.+const RECONNECT_DELAY: std::time::Duration = std::time::Duration::from_secs(1);++/// Consecutive failed connects before giving up. Bounded so a worker that is+/// gone (or too old for the endpoint) costs a handful of attempts rather than a+/// task reconnecting forever.+const MAX_CONSECUTIVE_FAILURES: u32 = 5;++#[derive(serde::Serialize, Clone)]+struct UnloadPayload {+ model: String,+ exit_code: Option<i64>,+}++/// Subscribes until aborted. The caller owns the handle (`LlamacppState::unload_watcher`)+/// and aborts it when the worker stops.+pub fn spawn<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ port: u16,+ api_key: String,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ let mut failures = 0u32;+ while failures < MAX_CONSECUTIVE_FAILURES {+ match subscribe_once(&app_handle, port, &api_key).await {+ Ok(()) => failures = 0,+ Err(e) => {+ failures += 1;+ log::debug!("/models/sse watcher could not subscribe ({failures}): {e}");+ }+ }+ tokio::time::sleep(RECONNECT_DELAY).await;+ }+ log::warn!(+ "giving up on /models/sse after {MAX_CONSECUTIVE_FAILURES} failed attempts; \+ evictions will not be reported to the UI until the engine restarts"+ );+ })+}++/// One connection, streamed to its end. `Ok` means the feed was reached, so a+/// stream that later drops does not count against the failure budget.+async fn subscribe_once<R: Runtime>(+ app_handle: &tauri::AppHandle<R>,+ port: u16,+ api_key: &str,+) -> Result<(), String> {+ use futures_util::StreamExt;++ let resp = reqwest::Client::new()+ .get(format!("http://127.0.0.1:{port}/models/sse"))+ .bearer_auth(api_key)+ .send()+ .await+ .map_err(|e| e.to_string())?;+ if !resp.status().is_success() {+ return Err(format!("/models/sse returned {}", resp.status()));+ }++ let mut stream = resp.bytes_stream();+ let mut buf = String::new();+ while let Some(chunk) = stream.next().await {+ let Ok(bytes) = chunk else { break };+ buf.push_str(&String::from_utf8_lossy(&bytes));+ while let Some(pos) = buf.find("\n\n") {+ let block: String = buf.drain(..pos + 2).collect();+ if let Some(payload) = parse_unload(&block) {+ if let Err(e) = app_handle.emit(UNLOADED_EVENT, payload) {+ log::warn!("emit {UNLOADED_EVENT} failed: {e}");+ }+ }+ }+ }+ Ok(())+}++/// The `unloaded` transition out of one SSE block, or None for anything else.+/// Unlike the load listener this is model-agnostic: it forwards every model's+/// unload, since it has no particular load to watch.+fn parse_unload(block: &str) -> Option<UnloadPayload> {+ for line in block.lines() {+ let data = line+ .strip_prefix("data: ")+ .or_else(|| line.strip_prefix("data:"))?;+ let json: serde_json::Value = serde_json::from_str(data).ok()?;+ if json.get("event").and_then(|v| v.as_str()) != Some("status_change") {+ continue;+ }+ let data = json.get("data")?;+ if data.get("status").and_then(|v| v.as_str()) != Some("unloaded") {+ continue;+ }+ return Some(UnloadPayload {+ model: json.get("model")?.as_str()?.to_string(),+ exit_code: data.get("exit_code").and_then(|v| v.as_i64()),+ });+ }+ None+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::engine::events::{ModelEvent, Transition};++ fn frame(model: &str, status: Transition) -> String {+ ModelEvent {+ model: model.to_string(),+ status,+ }+ .to_sse_frame()+ }++ #[test]+ fn reads_an_unload_the_engine_emitted() {+ let p = parse_unload(&frame("qwen", Transition::Unloaded { exit_code: 0 }))+ .expect("an unload");+ assert_eq!(p.model, "qwen");+ assert_eq!(p.exit_code, Some(0));+ }++ // A failed load is also an unload, and the UI has to drop the model either+ // way -- it never became usable.+ #[test]+ fn a_failed_load_is_forwarded_too() {+ let p = parse_unload(&frame("qwen", Transition::Unloaded { exit_code: 1 }))+ .expect("an unload");+ assert_eq!(p.exit_code, Some(1));+ }++ #[test]+ fn other_transitions_are_ignored() {+ assert!(parse_unload(&frame("qwen", Transition::Loading)).is_none());+ assert!(parse_unload(&frame("qwen", Transition::Loaded)).is_none());+ }++ #[test]+ fn malformed_blocks_are_ignored() {+ assert!(parse_unload("data: not json\n\n").is_none());+ assert!(parse_unload(": keepalive\n\n").is_none());+ assert!(parse_unload("").is_none());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rsnew file mode 100644index 000000000..eaa85e2fb--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs@@ -0,0 +1,619 @@+//! Supervises the `jan-llama-worker` process.+//!+//! This is the crash boundary. The worker links llama.cpp statically, but in+//! its own process, because `GGML_ASSERT` calls `abort()` unconditionally and+//! no amount of `catch_unwind` contains that -- a VRAM OOM or a Vulkan device+//! loss must cost the model, not the app.+//!+//! Deliberately free of the `engine` feature: supervision is just process+//! management, so a build that did not compile llama.cpp can still drive a+//! worker shipped alongside it as a sidecar.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;++use tokio::io::{AsyncBufReadExt, BufReader};+use tokio::process::{Child, Command};++/// The worker prints this and nothing else on stdout, then serves. Reading a+/// structured line beats the router path's stderr scraping: there is no+/// version-dependent log phrasing to match, and no race against a log file.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Handshake {+ pub port: u16,+ pub pid: u32,+ pub models: Vec<String>,+}++#[derive(Debug, PartialEq, Eq)]+pub enum WorkerError {+ Spawn(String),+ /// The worker exited or said nothing intelligible before serving.+ Handshake(String),+ Timeout(Duration),+}++impl std::fmt::Display for WorkerError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Spawn(m) => write!(f, "could not start jan-llama-worker: {m}"),+ Self::Handshake(m) => write!(f, "jan-llama-worker did not come up: {m}"),+ Self::Timeout(d) => {+ write!(f, "jan-llama-worker did not report a port within {d:?}")+ }+ }+ }+}++/// A runtime failure worth telling the user about, classified from one worker+/// log line. `GGML_ASSERT` calls `abort()`, so for these the line on stderr is+/// often the only evidence left of what happened.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RuntimeFault {+ /// Ran out of device or host memory mid-request.+ Oom,+ /// A backend crash: a CUDA/Vulkan/Metal error, a failed assert, device+ /// loss, or a heap-corruption abort.+ Backend,+}++impl RuntimeFault {+ /// The event name the frontend listens on. Still `router` because that is+ /// what `LlamacppOomListener` subscribes to; renaming it would be a+ /// two-sided change for no gain.+ pub const fn event_name(self) -> &'static str {+ match self {+ Self::Oom => "llamacpp-router-oom",+ Self::Backend => "llamacpp-router-backend-error",+ }+ }+}++/// Classifies a log line. The caller lowercases once and passes that in.+pub fn classify_fault(line_lower: &str) -> Option<RuntimeFault> {+ if is_oom_line(line_lower) {+ return Some(RuntimeFault::Oom);+ }+ if is_backend_error_line(line_lower) {+ return Some(RuntimeFault::Backend);+ }+ None+}++fn is_oom_line(line_lower: &str) -> bool {+ if line_lower.contains("erroroutofdevicememory") || line_lower.contains("erroroutofhostmemory")+ {+ return true;+ }+ line_lower.contains("failed to allocate") && line_lower.contains("buffer of size")+}++fn is_backend_error_line(line_lower: &str) -> bool {+ if line_lower.contains("cuda error:") || line_lower.contains("ggml_assert(") {+ return true;+ }+ if (line_lower.contains("ggml_vulkan") || line_lower.contains("ggml_metal"))+ && line_lower.contains("error")+ {+ return true;+ }+ // GPU device loss (vk::DeviceLostError / ErrorDeviceLost, CUDA device-lost)+ // and any uncaught C++ exception abort mid-request -- surface them so a+ // crash during prompt processing still reaches the UI.+ if line_lower.contains("devicelost")+ || line_lower.contains("device lost")+ || line_lower.contains("terminate called after throwing")+ {+ return true;+ }+ // glibc heap-corruption / stack-protector aborts (SIGABRT). A native memory+ // bug in the backend (e.g. the mtmd video decode path) prints one of these+ // just before the process dies -- unclassified, the crash is silent and the+ // load appears to hang forever.+ [+ "corrupted size vs. prev_size",+ "corrupted double-linked list",+ "double free or corruption",+ "malloc(): ",+ "free(): ",+ "munmap_chunk(): invalid pointer",+ "stack smashing detected",+ "buffer overflow detected",+ ]+ .iter()+ .any(|m| line_lower.contains(m))+}++/// Called once per classified line, with the line itself. Boxed rather than+/// generic so `WorkerHandle` does not have to carry a type parameter.+pub type FaultCallback = std::sync::Arc<dyn Fn(RuntimeFault, String) + Send + Sync + 'static>;++/// Minimum gap between reports. One fault produces a burst of lines (a CUDA+/// error, then the assert, then the abort message), and the user needs the+/// first one, not all of them.+const FAULT_DEBOUNCE: Duration = Duration::from_secs(3);++/// Env var the worker reads its bearer token from. Never an argv flag: argv is+/// world-readable via `ps` / `/proc/<pid>/cmdline`, and the supervisor logs it.+pub const API_KEY_ENV: &str = "JAN_LLAMA_API_KEY";++/// How long to wait for the worker to unwind after it accepts `/shutdown`.+/// Generous because unwinding runs `jan_llama_engine_stop` per resident model,+/// which terminates each `server_queue` loop and frees the model.+const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);++++/// How long to wait for the handshake. Generous because a cold page-cache read+/// of the preset plus binding a port can be slow on a loaded machine, but far+/// short of a model load -- the worker answers before loading anything.+pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);++/// Pure so the flag set is testable without spawning anything. Port 0 asks the+/// OS to choose, which the handshake then reports back -- unlike the router+/// path's `49152 + random` guess, this cannot collide.+pub fn worker_args(+ preset_path: &Path,+ port: u16,+ models_max: u32,+ slot_cache_mib: u64,+) -> Vec<String> {+ vec![+ "--preset".to_string(),+ preset_path.to_string_lossy().to_string(),+ "--port".to_string(),+ port.to_string(),+ "--models-max".to_string(),+ models_max.to_string(),+ "--slot-cache-mib".to_string(),+ slot_cache_mib.to_string(),+ ]+}++pub fn parse_handshake(line: &str) -> Result<Handshake, WorkerError> {+ let v: serde_json::Value = serde_json::from_str(line.trim())+ .map_err(|e| WorkerError::Handshake(format!("unparseable line {line:?}: {e}")))?;+ let port = v+ .get("port")+ .and_then(serde_json::Value::as_u64)+ .filter(|p| *p > 0 && *p <= u16::MAX as u64)+ .ok_or_else(|| WorkerError::Handshake(format!("no usable port in {line:?}")))?+ as u16;+ let pid = v+ .get("pid")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or_default() as u32;+ let models = v+ .get("models")+ .and_then(serde_json::Value::as_array)+ .map(|a| {+ a.iter()+ .filter_map(|m| m.as_str().map(str::to_string))+ .collect()+ })+ .unwrap_or_default();+ Ok(Handshake { port, pid, models })+}++impl std::fmt::Debug for WorkerHandle {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // No api_key: this ends up in logs and error messages.+ f.debug_struct("WorkerHandle")+ .field("pid", &self.pid)+ .field("port", &self.port)+ .field("models", &self.models)+ .finish()+ }+}++pub struct WorkerHandle {+ pub port: u16,+ pub pid: u32,+ pub api_key: String,+ pub models: Vec<String>,+ child: Child,+}++impl WorkerHandle {+ /// SIGTERM, then SIGKILL after a grace period, reusing the same helper the+ /// router path uses so there is one kill policy in the crate.+ /// Stops the worker, gracefully on every platform.+ ///+ /// Closes the worker's stdin first; the worker treats EOF there as "stop".+ /// That works identically on Linux, macOS and Windows, which is the whole+ /// reason the worker is our own binary rather than a downloaded+ /// `llama-server`: the router could only be signalled, and Windows has no+ /// deliverable SIGTERM equivalent (`GenerateConsoleCtrlEvent(CTRL_C_EVENT)`+ /// needs process group 0, which would kill Jan too), so it had to be+ /// force-killed there. A force kill skips `jan_llama_engine_stop`, leaving+ /// `server_queue` loops unterminated and the model unfreed.+ ///+ /// Signals remain the fallback for a worker too wedged to answer.+ pub async fn stop(mut self) {+ if self.request_shutdown() {+ match tokio::time::timeout(SHUTDOWN_TIMEOUT, self.child.wait()).await {+ Ok(Ok(status)) => {+ log::info!("jan-llama-worker exited gracefully: {status}");+ return;+ }+ Ok(Err(e)) => log::warn!("waiting on the worker failed: {e}"),+ Err(_) => log::warn!(+ "jan-llama-worker did not exit within {}s of /shutdown; falling back",+ SHUTDOWN_TIMEOUT.as_secs()+ ),+ }+ }++ #[cfg(unix)]+ crate::process::graceful_terminate_process(&mut self.child).await;+ #[cfg(all(windows, target_arch = "x86_64"))]+ crate::process::force_terminate_process(&mut self.child).await;+ #[cfg(not(any(unix, all(windows, target_arch = "x86_64"))))]+ {+ let _ = self.child.kill().await;+ }+ }++ /// Kills the worker immediately, skipping the graceful path.+ ///+ /// The engine's own teardown does not run, so this is only for a user who+ /// has asked to abandon work in flight.+ pub async fn kill(mut self) {+ let _ = self.child.kill().await;+ let _ = self.child.wait().await;+ }++ /// Closes the worker's stdin, which is its shutdown signal.+ ///+ /// Returns false only if there was no pipe to close, in which case the+ /// caller goes straight to the signal fallback.+ fn request_shutdown(&mut self) -> bool {+ self.take_stdin().is_some()+ }++ /// The write end of the worker's stdin. Dropping it signals shutdown;+ /// exposed so a test can exercise that path without the signal fallback.+ pub fn take_stdin(&mut self) -> Option<tokio::process::ChildStdin> {+ self.child.stdin.take()+ }++ /// None while still running, otherwise the exit status.+ pub fn exited(&mut self) -> Option<std::process::ExitStatus> {+ self.child.try_wait().ok().flatten()+ }+}++/// Spawns the worker and waits for its handshake line.+#[allow(clippy::too_many_arguments)]+pub async fn spawn(+ exe: &Path,+ preset_path: &Path,+ port: u16,+ api_key: &str,+ models_max: u32,+ slot_cache_mib: u64,+ envs: HashMap<String, String>,+ on_fault: Option<FaultCallback>,+) -> Result<WorkerHandle, WorkerError> {+ let args = worker_args(preset_path, port, models_max, slot_cache_mib);+ log::info!("starting {} {}", exe.display(), args.join(" "));++ let mut cmd = Command::new(exe);+ // Without this the worker flashes a console window on Windows, the way+ // every other spawn in this plugin already avoids.+ jan_utils::system::setup_windows_process_flags(&mut cmd);+ // ggml's backend scan puts `fs::current_path()` in its search paths and+ // calls dl_load_library on every `ggml-*` filename match *before* reading+ // its score, so a planted module in an inherited cwd runs its DllMain /+ // constructor even if it is never selected -- and `best_score` is one+ // accumulator across all search paths, so a higher-scoring plant wins+ // outright rather than losing to path order. Pinning the cwd to the+ // worker's own directory, which is where the bundled modules already live,+ // removes the attacker-writable entry from that list.+ //+ // Absolute only: `current_dir` also changes how the OS resolves a *relative*+ // program path, so doing this unconditionally would make a dev's+ // `--bin build/jan-llama-worker` be looked up inside `build/`. Every shipped+ // path is absolute (`resource_dir()`, or `sidecar_path` off+ // `current_exe`), so the hardening lands exactly where it matters.+ if exe.is_absolute() {+ if let Some(dir) = exe.parent() {+ cmd.current_dir(dir);+ }+ }+ cmd.args(&args)+ .envs(envs)+ .env(API_KEY_ENV, api_key)+ // Piped, not null: dropping our end closes the pipe, which is the+ // shutdown signal the worker waits on. `Stdio::null()` would be an+ // immediate EOF and the worker would exit at once.+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);++ let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(e.to_string()))?;++ let stdout = child+ .stdout+ .take()+ .ok_or_else(|| WorkerError::Spawn("no stdout pipe".into()))?;+ // Drained on its own task: a full stderr pipe would otherwise block the+ // worker mid-generation, which is a hang with no error message.+ if let Some(stderr) = child.stderr.take() {+ tokio::spawn(async move {+ let mut lines = BufReader::new(stderr).lines();+ let mut last_fault_at: Option<tokio::time::Instant> = None;+ while let Ok(Some(line)) = lines.next_line().await {+ log::debug!("jan-llama-worker: {line}");+ let Some(cb) = on_fault.as_ref() else { continue };+ let Some(fault) = classify_fault(&line.to_lowercase()) else {+ continue;+ };+ let now = tokio::time::Instant::now();+ if last_fault_at.is_some_and(|t| now.duration_since(t) <= FAULT_DEBOUNCE) {+ continue;+ }+ last_fault_at = Some(now);+ cb(fault, line);+ }+ });+ }++ let mut lines = BufReader::new(stdout).lines();+ let first = tokio::time::timeout(HANDSHAKE_TIMEOUT, lines.next_line()).await;++ let line = match first {+ Err(_) => {+ let _ = child.start_kill();+ return Err(WorkerError::Timeout(HANDSHAKE_TIMEOUT));+ }+ Ok(Err(e)) => {+ let _ = child.start_kill();+ return Err(WorkerError::Handshake(e.to_string()));+ }+ Ok(Ok(None)) => {+ // Closed stdout without a line: it died. The exit status is the+ // most useful thing we can report.+ let status = child.wait().await.ok();+ return Err(WorkerError::Handshake(format!(+ "exited before serving (status {status:?})"+ )));+ }+ Ok(Ok(Some(line))) => line,+ };++ let hs = match parse_handshake(&line) {+ Ok(hs) => hs,+ Err(e) => {+ let _ = child.start_kill();+ return Err(e);+ }+ };++ // Keep draining stdout so the worker never blocks on a full pipe.+ tokio::spawn(async move {+ while let Ok(Some(line)) = lines.next_line().await {+ log::debug!("jan-llama-worker: {line}");+ }+ });++ Ok(WorkerHandle {+ port: hs.port,+ pid: hs.pid,+ api_key: api_key.to_string(),+ models: hs.models,+ child,+ })+}++/// Where the worker lives next to the running executable, which is how Tauri+/// lays out a bundled sidecar.+pub fn worker_file_name() -> &'static str {+ if cfg!(windows) {+ "jan-llama-worker.exe"+ } else {+ "jan-llama-worker"+ }+}++/// The worker beside the app executable.+///+/// This is the dev layout (`target/<profile>/`). A bundled app puts it under the+/// resource directory instead, which only the Tauri side can resolve, so+/// `commands::resolve_worker_exe` checks that first and falls back here.+pub fn sidecar_path() -> Option<PathBuf> {+ let exe = std::env::current_exe().ok()?;+ let candidate = exe.parent()?.join(worker_file_name());+ candidate.is_file().then_some(candidate)+}++#[cfg(test)]+mod tests {+ use super::*;++ // Restored with the marker lists intact: each entry came from a real crash+ // report, and a fault the classifier misses is a silent hang for the user.+ #[test]+ fn classifies_backend_crash_lines() {+ // Inputs arrive already lowercased from the caller.+ for line in [+ "what(): vk::device::waitforfences: errordevicelost",+ "terminate called after throwing an instance of 'vk::devicelosterror'",+ "cuda error: out of memory",+ "ggml_assert(cond) failed",+ "corrupted size vs. prev_size",+ "malloc(): corrupted top size",+ "stack smashing detected",+ ] {+ assert_eq!(+ classify_fault(line),+ Some(RuntimeFault::Backend),+ "{line:?}"+ );+ }+ }++ #[test]+ fn classifies_allocation_failures_as_oom() {+ for line in [+ "erroroutofdevicememory",+ "erroroutofhostmemory",+ "alloc_tensor_range: failed to allocate cuda0 buffer of size 2491323904",+ ] {+ assert_eq!(classify_fault(line), Some(RuntimeFault::Oom), "{line:?}");+ }+ }++ // OOM is checked first: "cuda error: out of memory" is both, and the OOM+ // dialog is the one with advice the user can act on.+ #[test]+ fn ordinary_log_lines_are_not_faults() {+ for line in [+ "srv log_server_r: request: post /v1/chat/completions",+ "load: control-looking token: 128247 was not control-type",+ "main: server is listening on http://127.0.0.1:39271",+ "",+ ] {+ assert_eq!(classify_fault(line), None, "{line:?}");+ }+ }++ // A partial phrase must not fire: "failed to allocate" alone shows up in+ // benign fit-params chatter.+ #[test]+ fn a_partial_allocation_phrase_is_not_an_oom() {+ assert_eq!(+ classify_fault("common_fit_params: failed to allocate a plan"),+ None+ );+ }++ #[test]+ fn each_fault_maps_to_the_event_the_frontend_listens_on() {+ assert_eq!(RuntimeFault::Oom.event_name(), "llamacpp-router-oom");+ assert_eq!(+ RuntimeFault::Backend.event_name(),+ "llamacpp-router-backend-error"+ );+ }++ #[test]+ fn worker_args_are_the_documented_flags() {+ let args = worker_args(Path::new("/tmp/router.preset.ini"), 0, 4, 8192);+ assert_eq!(+ args,+ vec![+ "--preset",+ "/tmp/router.preset.ini",+ "--port",+ "0",+ "--models-max",+ "4",+ "--slot-cache-mib",+ "8192"+ ]+ );+ }++ #[test]+ fn the_api_key_never_appears_in_argv() {+ // The router path documents this invariant; keep it here too.+ let args = worker_args(Path::new("/p.ini"), 1234, 1, 0);+ assert!(+ !args.iter().any(|a| a.contains("api") || a.contains("key")),+ "argv is world-readable via /proc; the token must go through {API_KEY_ENV}"+ );+ }++ #[test]+ fn models_max_zero_is_forwarded_verbatim_as_unlimited() {+ let args = worker_args(Path::new("/p.ini"), 1, 0, 0);+ assert_eq!(args[5], "0");+ }++ // 0 is the off switch, and it has to survive as 0 rather than being+ // dropped: an absent flag would fall back to the worker's own default.+ #[test]+ fn the_slot_cache_budget_is_forwarded_including_zero() {+ let off = worker_args(Path::new("/p.ini"), 1, 1, 0);+ assert_eq!(off[7], "0");+ let on = worker_args(Path::new("/p.ini"), 1, 1, 4096);+ assert_eq!(on[7], "4096");+ }++ #[test]+ fn parse_handshake_reads_the_worker_line() {+ let hs = parse_handshake(r#"{"port":39271,"pid":1234,"models":["a","b"]}"#).unwrap();+ assert_eq!(+ hs,+ Handshake {+ port: 39271,+ pid: 1234,+ models: vec!["a".into(), "b".into()],+ }+ );+ }++ #[test]+ fn parse_handshake_tolerates_trailing_newline_and_missing_optionals() {+ let hs = parse_handshake("{\"port\":8080}\n").unwrap();+ assert_eq!(hs.port, 8080);+ assert_eq!(hs.pid, 0);+ assert!(hs.models.is_empty());+ }++ #[test]+ fn parse_handshake_rejects_a_missing_or_impossible_port() {+ // Port 0 would mean "the OS did not assign one", which is never a+ // usable upstream -- accepting it would produce a session that every+ // later request silently fails against.+ for bad in [+ r#"{"pid":1}"#,+ r#"{"port":0}"#,+ r#"{"port":70000}"#,+ r#"{"port":"8080"}"#,+ "not json",+ "",+ ] {+ assert!(+ parse_handshake(bad).is_err(),+ "should have rejected {bad:?}"+ );+ }+ }++ #[tokio::test]+ async fn spawning_a_missing_binary_is_a_spawn_error_not_a_hang() {+ let err = spawn(+ Path::new("/definitely/not/a/binary"),+ Path::new("/tmp/x.ini"),+ 0,+ "k",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect_err("a missing exe must fail");+ assert!(matches!(err, WorkerError::Spawn(_)), "got {err:?}");+ }++ #[tokio::test]+ async fn a_process_that_says_nothing_is_reported_not_awaited_forever() {+ // `true` exits immediately with no output, standing in for a worker+ // that dies during startup.+ let exe = ["/bin/true", "/usr/bin/true"]+ .iter()+ .map(Path::new)+ .find(|p| p.is_file());+ let Some(exe) = exe else { return };+ let err = spawn(exe, Path::new("/tmp/x.ini"), 0, "k", 1, 0, HashMap::new(), None)+ .await+ .expect_err("a silent exit must fail");+ assert!(matches!(err, WorkerError::Handshake(_)), "got {err:?}");+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rsindex fd19161c9..8675d038a 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs@@ -3,17 +3,10 @@ use serde::{Deserialize, Serialize};#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub enum ErrorCode {- BinaryNotFound,- ModelFileNotFound,- LibraryPathInvalid,-// --- Model Loading Errors ---ModelLoadFailed,- DraftModelLoadFailed,- MultimodalProjectorLoadFailed,ModelArchNotSupported,ModelLoadTimedOut,- LlamaCppProcessError,MissingSharedLibrary,GpuDriverTooOld,@@ -24,7 +17,6 @@ pub enum ErrorCode {InvalidArgument,// --- Internal Application Errors ---- DeviceListParseFailed,IoError,InternalError,}@@ -37,7 +29,7 @@ pub struct LlamacppError {#[serde(skip_serializing_if = "Option::is_none")]pub details: Option<String>,/// Library names the loader could not resolve, so the UI can turn them into- /// install advice instead of showing raw stderr.+ /// install advice instead of showing raw engine output.#[serde(skip_serializing_if = "Option::is_none")]pub missing_libraries: Option<Vec<String>>,}@@ -52,58 +44,69 @@ impl LlamacppError {}}- /// Parses stderr from llama.cpp and creates a specific LlamacppError.- pub fn from_stderr(stderr: &str) -> Self {- let lower_stderr = stderr.to_lowercase();+ /// Classifies engine output from a failed model load. An unrecognized+ /// reason is a failed load rather than a crashed process, and `details`+ /// keeps llama.cpp's own words so the UI can show them next to the+ /// localized advice instead of an HTTP status line.+ pub fn from_load_failure(output: &str) -> Self {+ Self::classify(output).unwrap_or_else(|| {+ Self::new(+ ErrorCode::ModelLoadFailed,+ "The model could not be loaded.".into(),+ Some(output.into()),+ )+ })+ }++ /// None when no marker matched, so each caller supplies its own fallback.+ fn classify(output: &str) -> Option<Self> {+ let lower = output.to_lowercase();// TODO: add others- let is_out_of_memory = lower_stderr.contains("out of memory")- || lower_stderr.contains("failed to allocate")- || lower_stderr.contains("insufficient memory")- || lower_stderr.contains("erroroutofdevicememory") // vulkan specific- || lower_stderr.contains("kiogpucommandbuffercallbackerroroutofmemory") // Metal-specific error code- || lower_stderr.contains("cuda_error_out_of_memory"); // CUDA-specific+ let is_out_of_memory = lower.contains("out of memory")+ || lower.contains("failed to allocate")+ || lower.contains("insufficient memory")+ || lower.contains("erroroutofdevicememory") // vulkan specific+ || lower.contains("kiogpucommandbuffercallbackerroroutofmemory") // Metal-specific error code+ || lower.contains("cuda_error_out_of_memory"); // CUDA-specificif is_out_of_memory {- return Self::new(+ return Some(Self::new(ErrorCode::OutOfMemory,"Out of memory. The model requires more RAM or VRAM than available.".into(),- Some(stderr.into()),- );+ Some(output.into()),+ ));}// A dynamic-loader failure is why a mismatched GPU backend dies on// launch; without this it lands on the generic process error.- if is_missing_library(&lower_stderr) {- let libs = extract_missing_libraries(stderr);+ if is_missing_library(&lower) {+ let libs = extract_missing_libraries(output);let mut err = Self::new(ErrorCode::MissingSharedLibrary,"A library this backend depends on is missing.".into(),- Some(stderr.into()),+ Some(output.into()),);err.missing_libraries = (!libs.is_empty()).then_some(libs);- return err;+ return Some(err);}- if is_driver_too_old(&lower_stderr) {- return Self::new(+ if is_driver_too_old(&lower) {+ return Some(Self::new(ErrorCode::GpuDriverTooOld,"The installed GPU driver is too old for this backend.".into(),- Some(stderr.into()),- );+ Some(output.into()),+ ));}- if lower_stderr.contains("error loading model architecture") {- return Self::new(+ if lower.contains("error loading model architecture") {+ return Some(Self::new(ErrorCode::ModelArchNotSupported,"The model's architecture is not supported by this version of the backend.".into(),- Some(stderr.into()),- );+ Some(output.into()),+ ));}- Self::new(- ErrorCode::LlamaCppProcessError,- "The model process encountered an unexpected error.".into(),- Some(stderr.into()),- )++ None}}@@ -125,16 +128,16 @@ const DRIVER_TOO_OLD_MARKERS: [&str; 5] = ["forward compatibility was attempted on non supported",];-fn is_missing_library(lower_stderr: &str) -> bool {+fn is_missing_library(lower: &str) -> bool {MISSING_LIBRARY_MARKERS.iter()- .any(|m| lower_stderr.contains(m))+ .any(|m| lower.contains(m))}-fn is_driver_too_old(lower_stderr: &str) -> bool {+fn is_driver_too_old(lower: &str) -> bool {DRIVER_TOO_OLD_MARKERS.iter()- .any(|m| lower_stderr.contains(m))+ .any(|m| lower.contains(m))}fn looks_like_library(name: &str) -> bool {@@ -144,12 +147,11 @@ fn looks_like_library(name: &str) -> bool {}/// Pulls unresolved library names out of loader diagnostics. Case is preserved,-/// so this reads the original stderr rather than a lowercased copy. Shared with-/// the load probe, which parses `dlerror()` text of the same shape.-pub(crate) fn extract_missing_libraries(stderr: &str) -> Vec<String> {+/// so this reads the original text rather than a lowercased copy.+fn extract_missing_libraries(output: &str) -> Vec<String> {let mut found: Vec<String> = Vec::new();- for line in stderr.lines() {+ for line in output.lines() {let lower = line.to_lowercase();// `<...>: libfoo.so.1: cannot open shared object file: ...`@@ -238,8 +240,8 @@ pub type ServerResult<T> = Result<T, ServerError>;mod tests {use super::*;- fn classify(stderr: &str) -> LlamacppError {- LlamacppError::from_stderr(stderr)+ fn classify(output: &str) -> LlamacppError {+ LlamacppError::from_load_failure(output)}// The UI matches on these exact strings to pick a localized message, so the@@ -247,23 +249,13 @@ mod tests {#[test]fn error_codes_serialize_to_the_strings_the_ui_matches_on() {let cases = [- (ErrorCode::BinaryNotFound, "BINARY_NOT_FOUND"),- (ErrorCode::ModelFileNotFound, "MODEL_FILE_NOT_FOUND"),- (ErrorCode::LibraryPathInvalid, "LIBRARY_PATH_INVALID"),(ErrorCode::ModelLoadFailed, "MODEL_LOAD_FAILED"),- (ErrorCode::DraftModelLoadFailed, "DRAFT_MODEL_LOAD_FAILED"),- (- ErrorCode::MultimodalProjectorLoadFailed,- "MULTIMODAL_PROJECTOR_LOAD_FAILED",- ),(ErrorCode::ModelArchNotSupported, "MODEL_ARCH_NOT_SUPPORTED"),(ErrorCode::ModelLoadTimedOut, "MODEL_LOAD_TIMED_OUT"),- (ErrorCode::LlamaCppProcessError, "LLAMA_CPP_PROCESS_ERROR"),(ErrorCode::MissingSharedLibrary, "MISSING_SHARED_LIBRARY"),(ErrorCode::GpuDriverTooOld, "GPU_DRIVER_TOO_OLD"),(ErrorCode::OutOfMemory, "OUT_OF_MEMORY"),(ErrorCode::InvalidArgument, "INVALID_ARGUMENT"),- (ErrorCode::DeviceListParseFailed, "DEVICE_LIST_PARSE_FAILED"),(ErrorCode::IoError, "IO_ERROR"),(ErrorCode::InternalError, "INTERNAL_ERROR"),];@@ -278,7 +270,7 @@ mod tests {#[test]fn a_serialized_error_carries_the_fields_the_ui_reads() {- let err = LlamacppError::from_stderr(+ let err = LlamacppError::from_load_failure("libcudart.so.12: cannot open shared object file: No such file or directory",);let json: serde_json::Value = serde_json::to_value(&err).unwrap();@@ -387,12 +379,12 @@ mod tests {));assert!(matches!(classify("something else entirely went wrong").code,- ErrorCode::LlamaCppProcessError+ ErrorCode::ModelLoadFailed));}#[test]- fn always_keeps_raw_stderr_in_details() {+ fn always_keeps_the_raw_engine_output_in_details() {let raw = "libcudart.so.12: cannot open shared object file: No such file or directory";assert_eq!(classify(raw).details.as_deref(), Some(raw));}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rsindex 82027700f..52d7f3084 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/commands.rs@@ -1,7 +1,8 @@use super::types::GgufMetadata;-use super::utils::{estimate_kv_cache_internal, read_gguf_metadata_internal};-use crate::gguf::types::{KVCacheError, KVCacheEstimate, ModelSupportStatus};-use std::collections::HashMap;+use super::utils::{+ estimate_kv_cache_internal, find_gguf_tensors_internal, read_gguf_metadata_internal,+};+use crate::gguf::types::ModelSupportStatus;use std::fs;use tauri_plugin_hardware::{get_system_info, SystemInfo};@@ -11,15 +12,17 @@ pub async fn read_gguf_metadata(path: String) -> Result<GgufMetadata, String> {read_gguf_metadata_internal(path).await}+/// Which of `names` exist as tensors in a gguf.+///+/// Exact names, not a listing: the questions worth asking are yes/no ones+/// (`markov_w1.weight` marks a DSpark draft, `blk.<n>.nextn.eh_proj.weight` an+/// MTP head), and a listing would put every tensor name of a large model+/// through the IPC boundary to answer one.#[tauri::command]-pub async fn estimate_kv_cache_size(- meta: HashMap<String, String>,- ctx_size: Option<u64>,-) -> Result<KVCacheEstimate, KVCacheError> {- estimate_kv_cache_internal(meta, ctx_size).await+pub async fn find_gguf_tensors(path: String, names: Vec<String>) -> Result<Vec<String>, String> {+ find_gguf_tensors_internal(path, names).await}-#[tauri::command]pub async fn get_model_size(path: String) -> Result<u64, String> {if path.starts_with("https://") {// Handle remote URLdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rsindex ffbb2e848..b4c22d98a 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/helpers.rs@@ -4,9 +4,92 @@ use std::io::{self, BufReader, Read, Seek};use super::types::{GgufMetadata, GgufValueType};+/// GGML_MAX_DIMS. A larger rank means the walk has desynchronised, not that a+/// new tensor shape exists.+const MAX_TENSOR_DIMS: u32 = 4;++/// Bound on the tensor-info loop, so a corrupt count cannot spin. The largest+/// real models are in the low thousands.+const MAX_TENSORS: u64 = 1_000_000;+pub fn read_gguf_metadata<R: Read + Seek>(reader: R) -> io::Result<GgufMetadata> {let mut file = BufReader::new(reader);+ read_header(&mut file)+}++/// Which of `wanted` appear in the tensor-info block.+///+/// Exact names, mirroring llama.cpp's own `gguf_find_tensor`, because that is+/// how the interesting facts are phrased: a DSpark draft is a DFlash one plus+/// `markov_w1.weight`, and upstream detects an MTP head by+/// `blk.<block_count-1>.nextn.eh_proj.weight`. Returning every name instead+/// would put hundreds of kilobytes of strings through the IPC boundary on+/// every import to answer a yes/no question.+///+/// Only the first split of a sharded model is read, so a tensor living in a+/// later shard is reported absent -- the same limit upstream's+/// `common_speculative_types_from_gguf` documents.+pub fn find_gguf_tensors<R: Read + Seek>(+ reader: R,+ wanted: &[String],+) -> io::Result<Vec<String>> {+ let mut file = BufReader::new(reader);+ let meta = read_header(&mut file)?;++ if wanted.is_empty() {+ return Ok(Vec::new());+ }+ // v1 sized strings and dimensions with u32s. llama.cpp refuses that+ // version outright, and reading it as v2 would invent names.+ if meta.version < 2 {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ format!("GGUF version {} has no readable tensor block", meta.version),+ ));+ }+ if meta.tensor_count > MAX_TENSORS {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ format!("tensor count {} is unreasonably large", meta.tensor_count),+ ));+ }++ let mut found: Vec<String> = Vec::new();+ for i in 0..meta.tensor_count {+ let name = read_gguf_string(&mut file).map_err(|e| {+ io::Error::new(+ io::ErrorKind::InvalidData,+ format!("Failed to read name for tensor {}: {}", i, e),+ )+ })?;+ let n_dims = file.read_u32::<LittleEndian>()?;+ if n_dims > MAX_TENSOR_DIMS {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ format!("tensor {} claims {} dimensions", i, n_dims),+ ));+ }+ // Read rather than seek: BufReader drops its buffer on every seek, so+ // skipping this way costs a syscall per tensor on a large model.+ for _ in 0..n_dims {+ file.read_u64::<LittleEndian>()?;+ }+ file.read_u32::<LittleEndian>()?; // ggml type+ file.read_u64::<LittleEndian>()?; // offset into the data section+ if wanted.contains(&name) && !found.contains(&name) {+ found.push(name);+ if found.len() == wanted.len() {+ break;+ }+ }+ }+ Ok(found)+}++/// Header plus the whole KV section, leaving the reader positioned at the+/// start of the tensor-info block.+fn read_header<R: Read + Seek>(file: &mut BufReader<R>) -> io::Result<GgufMetadata> {let mut magic = [0u8; 4];file.read_exact(&mut magic)?;if &magic != b"GGUF" {@@ -22,7 +105,7 @@ pub fn read_gguf_metadata<R: Read + Seek>(reader: R) -> io::Result<GgufMetadata>let mut metadata_map = std::collections::HashMap::new();for i in 0..metadata_count {- match read_metadata_entry(&mut file, i) {+ match read_metadata_entry(file, i) {Ok((key, value)) => {metadata_map.insert(key, value);}@@ -151,3 +234,142 @@ fn skip_array_data<R: Read + Seek + ReadBytesExt>(}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use byteorder::WriteBytesExt;+ use std::io::Cursor;++ /// Builds a GGUF header with the given KV entries and tensor-info block.+ /// Hand-assembled because the point is to pin the byte layout the reader+ /// walks; a fixture file would hide it.+ fn gguf(version: u32, kv: &[(&str, &str)], tensors: &[(&str, &[u64])]) -> Vec<u8> {+ let mut b = Vec::new();+ b.extend_from_slice(b"GGUF");+ b.write_u32::<LittleEndian>(version).unwrap();+ b.write_u64::<LittleEndian>(tensors.len() as u64).unwrap();+ b.write_u64::<LittleEndian>(kv.len() as u64).unwrap();++ let string = |b: &mut Vec<u8>, s: &str| {+ b.write_u64::<LittleEndian>(s.len() as u64).unwrap();+ b.extend_from_slice(s.as_bytes());+ };+ for (k, v) in kv {+ string(&mut b, k);+ b.write_u32::<LittleEndian>(GgufValueType::String as u32).unwrap();+ string(&mut b, v);+ }+ for (name, dims) in tensors {+ string(&mut b, name);+ b.write_u32::<LittleEndian>(dims.len() as u32).unwrap();+ for d in *dims {+ b.write_u64::<LittleEndian>(*d).unwrap();+ }+ b.write_u32::<LittleEndian>(0).unwrap(); // ggml type+ b.write_u64::<LittleEndian>(0).unwrap(); // offset+ }+ b+ }++ fn want(names: &[&str]) -> Vec<String> {+ names.iter().map(|s| s.to_string()).collect()+ }++ #[test]+ fn metadata_still_reads_with_a_tensor_block_present() {+ let bytes = gguf(3, &[("general.architecture", "dflash")], &[("markov_w1.weight", &[4, 8])]);+ let meta = read_gguf_metadata(Cursor::new(bytes)).expect("metadata");+ assert_eq!(meta.version, 3);+ assert_eq!(meta.tensor_count, 1);+ assert_eq!(+ meta.metadata.get("general.architecture").map(String::as_str),+ Some("dflash")+ );+ }++ // The Markov head is the only thing separating a DSpark draft from a+ // DFlash one, and it is a tensor, not a metadata key.+ #[test]+ fn finds_a_requested_tensor_among_others() {+ let bytes = gguf(+ 3,+ &[("general.architecture", "dflash")],+ &[+ ("token_embd.weight", &[4096, 128]),+ ("markov_w1.weight", &[4, 8]),+ ("markov_w2.weight", &[4, 8]),+ ],+ );+ let found = find_gguf_tensors(Cursor::new(bytes), &want(&["markov_w1.weight"]))+ .expect("tensor scan");+ assert_eq!(found, want(&["markov_w1.weight"]));+ }++ #[test]+ fn reports_nothing_when_the_tensor_is_absent() {+ let bytes = gguf(3, &[], &[("token_embd.weight", &[4096, 128])]);+ let found = find_gguf_tensors(Cursor::new(bytes), &want(&["markov_w1.weight"]))+ .expect("tensor scan");+ assert!(found.is_empty(), "{found:?}");+ }++ #[test]+ fn finds_several_and_ignores_the_rest() {+ let bytes = gguf(+ 3,+ &[],+ &[+ ("blk.0.attn_q.weight", &[64]),+ ("markov_w1.weight", &[4]),+ ("blk.61.nextn.eh_proj.weight", &[64, 64]),+ ],+ );+ let mut found = find_gguf_tensors(+ Cursor::new(bytes),+ &want(&["markov_w1.weight", "blk.61.nextn.eh_proj.weight", "nope"]),+ )+ .expect("tensor scan");+ found.sort();+ assert_eq!(+ found,+ want(&["blk.61.nextn.eh_proj.weight", "markov_w1.weight"])+ );+ }++ // Every dimension count GGUF allows, so a 1-D bias or a 4-D tensor does+ // not desynchronise the walk and lose everything after it.+ #[test]+ fn every_tensor_rank_keeps_the_walk_aligned() {+ let bytes = gguf(+ 3,+ &[],+ &[+ ("one.weight", &[8]),+ ("two.weight", &[8, 8]),+ ("three.weight", &[8, 8, 8]),+ ("four.weight", &[8, 8, 8, 8]),+ ("markov_w1.weight", &[4]),+ ],+ );+ let found = find_gguf_tensors(Cursor::new(bytes), &want(&["markov_w1.weight"]))+ .expect("tensor scan");+ assert_eq!(found, want(&["markov_w1.weight"]));+ }++ // v1 put string lengths and dimensions in u32s. llama.cpp itself refuses+ // that version, so misparsing it as v2 would invent tensor names.+ #[test]+ fn a_version_1_file_is_refused_rather_than_misread() {+ let bytes = gguf(1, &[], &[("markov_w1.weight", &[4])]);+ assert!(find_gguf_tensors(Cursor::new(bytes), &want(&["markov_w1.weight"])).is_err());+ }++ #[test]+ fn asking_for_nothing_reads_nothing() {+ let bytes = gguf(3, &[], &[("token_embd.weight", &[8])]);+ assert!(find_gguf_tensors(Cursor::new(bytes), &[])+ .expect("tensor scan")+ .is_empty());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rsindex 10dc66f48..bc3c0e5d2 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/utils.rs@@ -4,8 +4,17 @@ use std::collections::HashMap;use std::fs::File;use std::io::BufReader;-// read gguf metadata-pub async fn read_gguf_metadata_internal(path: String) -> Result<GgufMetadata, String> {+/// Runs a parse over a gguf, local or remote.+///+/// A remote file is fetched in range chunks and the parse retried after each+/// one, since neither the KV section nor the tensor-info block has a length+/// known up front. `what` names the parse in the error, which is all that+/// differs between callers -- the fetch loop is shared so the chunking rules+/// cannot drift apart.+async fn parse_gguf<T, F>(path: &str, what: &str, parse: F) -> Result<T, String>+where+ F: Fn(&mut (dyn ReadSeek + '_)) -> std::io::Result<T>,+{if path.starts_with("http://") || path.starts_with("https://") {// Remote: read in 2MB chunks until successfullet client = reqwest::Client::new();@@ -19,7 +28,7 @@ pub async fn read_gguf_metadata_internal(path: String) -> Result<GgufMetadata, Slet end = std::cmp::min(start + chunk_size - 1, max_total_size - 1);let resp = client- .get(&path)+ .get(path).header("Range", format!("bytes={}-{}", start, end)).send().await@@ -34,9 +43,9 @@ pub async fn read_gguf_metadata_internal(path: String) -> Result<GgufMetadata, Stotal_downloaded += chunk_data.len();// Try parsing after each chunk- let cursor = std::io::Cursor::new(&accumulated_data);- if let Ok(metadata) = helpers::read_gguf_metadata(cursor) {- return Ok(metadata);+ let mut cursor = std::io::Cursor::new(accumulated_data.as_slice());+ if let Ok(parsed) = parse(&mut cursor) {+ return Ok(parsed);}// If we got less data than expected, we've reached EOF@@ -44,18 +53,42 @@ pub async fn read_gguf_metadata_internal(path: String) -> Result<GgufMetadata, Sbreak;}}- Err("Could not parse GGUF metadata from downloaded data".to_string())+ Err(format!("Could not read {} from downloaded data", what))} else {// Local: use streaming file readerlet file =- File::open(&path).map_err(|e| format!("Failed to open local file {}: {}", path, e))?;- let reader = BufReader::new(file);+ File::open(path).map_err(|e| format!("Failed to open local file {}: {}", path, e))?;+ let mut reader = BufReader::new(file);- helpers::read_gguf_metadata(reader)- .map_err(|e| format!("Failed to parse GGUF metadata: {}", e))+ parse(&mut reader).map_err(|e| format!("Failed to parse {}: {}", what, e))}}+/// One trait object for the two readers `parse_gguf` hands out, so the parse+/// closure does not have to be generic over both.+pub trait ReadSeek: std::io::Read + std::io::Seek {}+impl<T: std::io::Read + std::io::Seek> ReadSeek for T {}++// read gguf metadata+pub async fn read_gguf_metadata_internal(path: String) -> Result<GgufMetadata, String> {+ parse_gguf(&path, "GGUF metadata", |r: &mut (dyn ReadSeek + '_)| {+ helpers::read_gguf_metadata(r)+ })+ .await+}++/// Which of `names` exist as tensors in the gguf. See `find_gguf_tensors` for+/// why this is an exact-name question rather than a listing.+pub async fn find_gguf_tensors_internal(+ path: String,+ names: Vec<String>,+) -> Result<Vec<String>, String> {+ parse_gguf(&path, "GGUF tensor names", |r: &mut (dyn ReadSeek + '_)| {+ helpers::find_gguf_tensors(r, &names)+ })+ .await+}+/// Estimate KVCache size from a given metadatapub async fn estimate_kv_cache_internal(meta: HashMap<String, String>,diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rsindex 0981f87db..8d9fae22c 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs@@ -5,20 +5,15 @@ use tauri::{Manager, Runtime,};-mod backend;pub mod cleanup;-pub mod deps_analyzer;mod commands;-mod device;+pub mod engine;mod error;mod gguf;-pub mod load_probe;-mod path;mod process;-pub mod router;pub mod state;pub use cleanup::cleanup_llama_processes;-pub use commands::{force_kill_router_tree, stop_router, try_graceful_stop_router};+pub use engine::commands::try_graceful_stop_engine;pub use state::LlamacppState;pub fn init<R: Runtime>() -> TauriPlugin<R> {@@ -27,47 +22,21 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {cleanup::cleanup_llama_processes,commands::load_llama_model,commands::unload_llama_model,- commands::start_router,- commands::stop_router,- commands::try_graceful_stop_router,- commands::force_kill_router_tree,- commands::get_router_info,- commands::reload_router_models,- commands::router_slots_idle,- commands::router_health,- commands::adopt_router,- backend::fetch_backend_checksums,- backend::verify_file_sha512,- commands::get_devices,+ engine::commands::start_engine,+ engine::commands::stop_engine,+ engine::commands::get_engine_info,+ engine::commands::reload_engine_models,+ engine::commands::engine_devices,+ engine::commands::force_stop_engine,+ engine::commands::engine_slots_idle,+ engine::commands::erase_thread_slot_state,commands::generate_api_key,commands::ensure_session_ready,commands::find_session_by_model,commands::get_loaded_models,gguf::commands::read_gguf_metadata,- gguf::commands::estimate_kv_cache_size,- gguf::commands::get_model_size,+ gguf::commands::find_gguf_tensors,gguf::commands::is_model_supported,- backend::map_old_backend_to_new,- backend::get_local_installed_backends,- backend::list_supported_backends,- backend::determine_supported_backends,- backend::get_supported_features,- backend::is_cuda_installed,- backend::find_latest_version_for_backend,- backend::prioritize_backends,- backend::parse_backend_version,- backend::check_backend_for_updates,- backend::remove_old_backend_versions,- backend::validate_backend_string,- backend::should_migrate_backend,- backend::handle_setting_update,- backend::get_backend_dir,- backend::get_backend_exe_path,- backend::check_backend_installed,- backend::verify_backend_installation,- load_probe::probe_backend_load,- backend::fetch_remote_supported_backends,- backend::build_backend_download_items]).setup(|app, _api| {app.manage(Arc::new(state::LlamacppState::new()));@@ -133,4 +102,51 @@ mod permission_tests {"commands missing an allow-* entry in permissions/default.toml: {missing:?}");}+ /// The mirror of `every_registered_command_has_a_permission`. A name in+ /// `COMMANDS` with no `generate_handler!` entry still ships an `allow-*`+ /// permission, and `tauri_plugin::Builder` only ever writes+ /// `permissions/autogenerated/commands/*.toml` -- it never prunes -- so the+ /// stale file survives every rebuild and advertises a command that cannot+ /// be invoked.+ #[test]+ fn every_declared_command_is_registered() {+ let handlers = names_between(+ include_str!("lib.rs"),+ "tauri::generate_handler![",+ "])",+ );+ let declared = names_between(include_str!("../build.rs"), "COMMANDS: &[&str] = &[", "];");++ let orphaned: Vec<_> = declared+ .iter()+ .filter(|c| !handlers.contains(c))+ .collect();+ assert!(+ orphaned.is_empty(),+ "commands in build.rs COMMANDS with no entry in generate_handler!: {orphaned:?}"+ );+ }+ /// The project rule is that `invoke` lives only in the plugin's `guest-js`+ /// layer, so every command the frontend can reach needs a wrapper there.+ /// Without this, a new command silently invites a raw+ /// `invoke('plugin:llamacpp|...')` at the call site.+ #[test]+ fn every_command_has_a_guest_js_wrapper() {+ let handlers = names_between(+ include_str!("lib.rs"),+ "tauri::generate_handler![",+ "])",+ );+ let guest_js = include_str!("../guest-js/index.ts");++ let unwrapped: Vec<_> = handlers+ .iter()+ .filter(|c| !guest_js.contains(&format!("'plugin:llamacpp|{c}'")))+ .collect();+ assert!(+ unwrapped.is_empty(),+ "commands with no guest-js wrapper -- callers will reach for a raw \+ invoke() and violate the invoke-only-in-guest-js rule: {unwrapped:?}"+ );+ }}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rsdeleted file mode 100644index 4010512ff..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/load_probe.rs+++ /dev/null@@ -1,448 +0,0 @@-//! Out-of-process `dlopen` probe for a backend's GPU library.-//!-//! In a release build, ggml discards the loader error when a backend library-//! fails to load (`ggml_backend_load_all_from_path` passes `silent = true`-//! under `NDEBUG`), so llama-server registers only the CPU backend and runs-//! normally. No stderr is produced and the process exits 0, which makes the-//! failure invisible to output parsing.-//!-//! Loading the library ourselves recovers the real reason. Static ELF analysis-//! is not equivalent: without the runtime search path it reports libraries that-//! sit beside the binary as missing. The probe therefore runs with the same-//! environment the router child gets, and in a subprocess, because initializing-//! a GPU runtime in-process can abort.--use crate::error::extract_missing_libraries;-use serde::{Deserialize, Serialize};-use std::path::{Path, PathBuf};-use std::process::{Command, Stdio};--pub const PROBE_FLAG: &str = "--internal-probe-load";--#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]-pub struct LoadProbeResult {- /// Libraries that loaded cleanly.- pub loaded: Vec<String>,- /// One entry per library that failed to load.- pub failures: Vec<LoadProbeFailure>,- /// True when the probe could not run at all, so an empty `failures` list- /// must not be read as success.- pub inconclusive: bool,-}--#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]-pub struct LoadProbeFailure {- pub library: String,- /// Raw loader message.- pub error: String,- /// Names parsed out of `error`, for install advice.- pub missing_libraries: Vec<String>,-}--/// Backend-id substring -> the ggml library that implements it. Metal is-/// omitted: it is part of the platform on Apple Silicon and is not a separately-/// loadable failure mode.-const GPU_LIBRARY_KEYWORDS: [(&str, &str); 3] =- [("cuda", "cuda"), ("vulkan", "vulkan"), ("hip", "hip")];--fn library_extension() -> &'static str {- if cfg!(target_os = "windows") {- "dll"- } else if cfg!(target_os = "macos") {- "dylib"- } else {- "so"- }-}--fn library_prefix() -> &'static str {- if cfg!(target_os = "windows") {- "ggml-"- } else {- "libggml-"- }-}--/// The ggml GPU library filenames to probe for a backend id, matching ggml's own-/// `[lib]ggml-<name>*.<ext>` naming.-pub fn gpu_library_candidates(backend: &str, entries: &[String]) -> Vec<String> {- let lower = backend.to_lowercase();- let keyword = GPU_LIBRARY_KEYWORDS- .iter()- .find(|(marker, _)| lower.contains(marker))- .map(|(_, lib)| *lib);-- let Some(keyword) = keyword else {- return Vec::new();- };-- let stem = format!("{}{}", library_prefix(), keyword);- let ext = library_extension();- let mut matches: Vec<String> = entries- .iter()- .filter(|name| {- let lower_name = name.to_lowercase();- lower_name.starts_with(&stem) && lower_name.ends_with(&format!(".{ext}"))- })- .cloned()- .collect();- matches.sort();- matches-}--/// Child-side entry point. Returns without doing anything unless invoked with-/// `PROBE_FLAG`, so it is safe to call unconditionally at startup.-pub fn run_load_probe_if_requested() {- let mut args = std::env::args().skip(1);- if args.next().as_deref() != Some(PROBE_FLAG) {- return;- }-- let targets: Vec<PathBuf> = args.map(PathBuf::from).collect();- let result = probe_libraries(&targets);-- match serde_json::to_string(&result) {- Ok(s) => {- println!("{}", s);- std::process::exit(0);- }- Err(e) => {- eprintln!("serialize failed: {}", e);- std::process::exit(3);- }- }-}--fn probe_libraries(targets: &[PathBuf]) -> LoadProbeResult {- let mut result = LoadProbeResult::default();-- for target in targets {- let name = target- .file_name()- .map(|n| n.to_string_lossy().to_string())- .unwrap_or_else(|| target.to_string_lossy().to_string());-- // Safety: loading a library runs its initializers. This is why the probe- // is confined to a subprocess.- match unsafe { libloading::Library::new(target) } {- Ok(lib) => {- // Leak deliberately: unloading a GPU runtime mid-teardown has- // its own crash modes, and this process exits immediately.- std::mem::forget(lib);- result.loaded.push(name);- }- Err(e) => {- let error = e.to_string();- result.failures.push(LoadProbeFailure {- library: name,- missing_libraries: extract_missing_libraries(&error),- error,- });- }- }- }-- result-}--/// Parent-side entry point. Spawns this executable with `PROBE_FLAG` and the-/// same library search path the router child receives.-pub fn probe_out_of_process(- bin_dir: Option<&Path>,- cuda: &jan_utils::CudaPaths,- targets: &[PathBuf],-) -> LoadProbeResult {- let inconclusive = LoadProbeResult {- inconclusive: true,- ..Default::default()- };-- if targets.is_empty() {- return LoadProbeResult::default();- }-- let exe = match std::env::current_exe() {- Ok(p) => p,- Err(e) => {- log::warn!("load_probe: current_exe failed: {}", e);- return inconclusive;- }- };-- let mut cmd = Command::new(&exe);- cmd.arg(PROBE_FLAG);- for target in targets {- cmd.arg(target);- }-- // Parity with the router child: the same search path, or the probe would- // report libraries the real process resolves. This is the whole reason a- // static ELF scan is not a substitute.- let env = jan_utils::library_path_env(bin_dir, cuda);- for (key, value) in &env.vars {- cmd.env(key, value);- }- if let Some(dir) = &env.current_dir {- cmd.current_dir(dir);- }-- cmd.stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped());-- let output = match cmd.output() {- Ok(o) => o,- Err(e) => {- log::warn!("load_probe: failed to spawn subprocess: {}", e);- return inconclusive;- }- };-- if !output.status.success() {- log::warn!(- "load_probe: subprocess exited with {:?}; stderr: {}",- output.status.code(),- String::from_utf8_lossy(&output.stderr).trim(),- );- return inconclusive;- }-- match serde_json::from_slice::<LoadProbeResult>(&output.stdout) {- Ok(o) => o,- Err(e) => {- log::warn!(- "load_probe: malformed subprocess output: {} (stdout: {})",- e,- String::from_utf8_lossy(&output.stdout).trim(),- );- inconclusive- }- }-}--/// Loads the backend's GPU library the way llama-server would, reporting the-/// reason it cannot. Returns a clean result for CPU-only and macOS backends,-/// which have no separately loadable GPU library.-#[tauri::command]-pub async fn probe_backend_load(- backend: String,- version: String,- jan_data_folder: String,- is_windows: bool,-) -> Result<LoadProbeResult, crate::error::LlamacppError> {- let exe_path = PathBuf::from(crate::backend::get_backend_exe_path(- backend.clone(),- version,- jan_data_folder,- is_windows,- ));- let Some(bin_dir) = exe_path.parent().map(PathBuf::from) else {- return Ok(LoadProbeResult {- inconclusive: true,- ..Default::default()- });- };-- let entries: Vec<String> = match std::fs::read_dir(&bin_dir) {- Ok(dir) => dir- .filter_map(|e| e.ok())- .map(|e| e.file_name().to_string_lossy().to_string())- .collect(),- Err(e) => {- log::warn!("load_probe: cannot read {}: {}", bin_dir.display(), e);- return Ok(LoadProbeResult {- inconclusive: true,- ..Default::default()- });- }- };-- let targets: Vec<PathBuf> = gpu_library_candidates(&backend, &entries)- .into_iter()- .map(|name| bin_dir.join(name))- .collect();- if targets.is_empty() {- return Ok(LoadProbeResult::default());- }-- // Spawning and waiting on a subprocess would otherwise block a runtime worker.- tokio::task::spawn_blocking(move || {- let cuda = jan_utils::find_cuda_paths().merged(jan_utils::find_rocm_paths());- probe_out_of_process(Some(&bin_dir), &cuda, &targets)- })- .await- .map_err(|e| {- crate::error::LlamacppError::new(- crate::error::ErrorCode::InternalError,- "Backend load probe failed to run.".into(),- Some(e.to_string()),- )- })-}--#[cfg(test)]-mod tests {- use super::*;-- fn entries() -> Vec<String> {- vec![- "libggml-base.so".to_string(),- "libggml-base.so.0".to_string(),- "libggml-cpu-haswell.so".to_string(),- "libggml-cuda.so".to_string(),- "libggml-vulkan.so".to_string(),- "llama-server".to_string(),- ]- }-- #[cfg(target_os = "linux")]- #[test]- fn picks_the_cuda_library_for_a_cuda_backend() {- assert_eq!(- gpu_library_candidates("linux-cuda-12-common_cpus-x64", &entries()),- vec!["libggml-cuda.so".to_string()]- );- }-- #[cfg(target_os = "linux")]- #[test]- fn picks_the_vulkan_library_for_a_vulkan_backend() {- assert_eq!(- gpu_library_candidates("linux-vulkan-common_cpus-x64", &entries()),- vec!["libggml-vulkan.so".to_string()]- );- }-- // CPU and base libraries are not the GPU failure mode and must not be- // probed, or a CPU-only install would look like a GPU problem.- #[cfg(target_os = "linux")]- #[test]- fn never_selects_cpu_or_base_libraries() {- for backend in ["linux-cuda-12-common_cpus-x64", "linux-vulkan-common_cpus-x64"] {- let picked = gpu_library_candidates(backend, &entries());- assert!(- !picked.iter().any(|p| p.contains("cpu") || p.contains("base")),- "{picked:?}"- );- }- }-- #[test]- fn probes_nothing_for_a_cpu_backend() {- assert!(gpu_library_candidates("linux-common_cpus-x64", &entries()).is_empty());- }-- // Metal is part of the platform, not a separately loadable backend.- #[test]- fn probes_nothing_for_macos() {- assert!(gpu_library_candidates("macos-arm64", &entries()).is_empty());- }-- #[test]- fn reports_a_missing_library_with_its_parsed_name() {- let result = probe_libraries(&[PathBuf::from("/nonexistent/libggml-cuda.so")]);- assert_eq!(result.failures.len(), 1, "{result:?}");- assert_eq!(result.failures[0].library, "libggml-cuda.so");- assert!(!result.failures[0].error.is_empty());- assert!(result.loaded.is_empty());- assert!(!result.inconclusive);- }-- #[test]- fn an_empty_target_list_is_conclusive_and_clean() {- let result = probe_out_of_process(None, &jan_utils::CudaPaths::default(), &[]);- assert_eq!(result, LoadProbeResult::default());- assert!(!result.inconclusive);- }-- // An empty failure list must not be mistaken for a healthy backend when the- // probe never ran.- #[test]- fn inconclusive_is_distinct_from_success() {- let inconclusive = LoadProbeResult {- inconclusive: true,- ..Default::default()- };- assert!(inconclusive.failures.is_empty());- assert_ne!(inconclusive, LoadProbeResult::default());- }-}--#[cfg(test)]-mod integration_tests {- use super::*;-- /// Proves the probe's premise against a real install: the GPU library does- /// NOT resolve without the backend's own directory on the search path, so a- /// scan that omits that path reports libraries the real process resolves- /// fine. The positive case cannot be asserted here, because- /// `probe_out_of_process` re-execs `current_exe`, which under `cargo test`- /// is the test harness rather than a binary that handles `PROBE_FLAG`; it- /// requires the app binary wired up in `main.rs`.- #[cfg(target_os = "linux")]- #[test]- #[ignore = "requires a locally installed GPU backend; run with --ignored"]- fn a_real_backend_library_needs_its_own_directory_on_the_search_path() {- let Some(bin_dir) = real_backend_bin_dir() else {- eprintln!("skipped: no installed CUDA/Vulkan backend found");- return;- };- let entries: Vec<String> = std::fs::read_dir(&bin_dir)- .unwrap()- .filter_map(|e| e.ok())- .map(|e| e.file_name().to_string_lossy().to_string())- .collect();-- let backend = bin_dir- .ancestors()- .nth(2)- .and_then(|p| p.file_name())- .map(|n| n.to_string_lossy().to_string())- .unwrap_or_default();-- let candidates = gpu_library_candidates(&backend, &entries);- if candidates.is_empty() {- eprintln!("skipped: {backend} is not a GPU backend");- return;- }- // The selector must find a real file, not just match a synthetic list.- for candidate in &candidates {- assert!(bin_dir.join(candidate).is_file(), "{candidate} missing");- }-- let targets: Vec<PathBuf> = candidates.iter().map(|c| bin_dir.join(c)).collect();- let bare = probe_libraries(&targets);-- assert!(- !bare.failures.is_empty(),- "expected failure without the search path, proving a scan that omits \- it cannot be trusted: {bare:?}"- );- // And the failure must name a library, which is what drives install advice.- assert!(- bare.failures- .iter()- .any(|f| !f.missing_libraries.is_empty()),- "probe failure should name the unresolved library: {bare:?}"- );- }-- #[cfg(target_os = "linux")]- fn real_backend_bin_dir() -> Option<PathBuf> {- let home = std::env::var("HOME").ok()?;- let base = PathBuf::from(home).join(".local/share/Jan/data/llamacpp/backends");- for version in std::fs::read_dir(base).ok()?.filter_map(|e| e.ok()) {- for backend in std::fs::read_dir(version.path()).ok()?.filter_map(|e| e.ok()) {- let name = backend.file_name().to_string_lossy().to_string();- if !["cuda", "vulkan", "hip"].iter().any(|k| name.contains(k)) {- continue;- }- let bin = backend.path().join("build/bin");- if bin.is_dir() {- return Some(bin);- }- }- }- None- }-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rsdeleted file mode 100644index 743479097..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/path.rs+++ /dev/null@@ -1,43 +0,0 @@-use std::path::PathBuf;--use crate::error::{ErrorCode, LlamacppError, ServerResult};--pub fn validate_binary_path(backend_path: &str) -> ServerResult<PathBuf> {- let server_path_buf = PathBuf::from(backend_path);- if !server_path_buf.exists() {- let err_msg = format!("Binary not found at {:?}", backend_path);- log::error!(- "Server binary not found at expected path: {:?}",- backend_path- );- return Err(LlamacppError::new(- ErrorCode::BinaryNotFound,- "The llama.cpp server binary could not be found.".into(),- Some(err_msg),- )- .into());- }- Ok(server_path_buf)-}--#[cfg(test)]-mod tests {- use super::*;- use tempfile::NamedTempFile;-- #[test]- fn test_validate_binary_path_existing() {- let temp_file = NamedTempFile::new().unwrap();- let path = temp_file.path().to_str().unwrap();- let result = validate_binary_path(path);- assert!(result.is_ok());- assert_eq!(result.unwrap(), PathBuf::from(path));- }-- #[test]- fn test_validate_binary_path_nonexistent() {- let nonexistent_path = "/tmp/definitely_does_not_exist_123456789";- let result = validate_binary_path(nonexistent_path);- assert!(result.is_err());- }-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rsdeleted file mode 100644index 23c47b11f..000000000--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs+++ /dev/null@@ -1,1435 +0,0 @@-//! Router-mode lifecycle for `llama-server`.-//!-//! Phase 1 of the router refactor: spawn / health-check / shut down a single-//! `llama-server` instance running in router mode (no `-m` / `-hf` flag, models-//! are loaded on demand via the HTTP API). This module is intentionally-//! standalone — it does NOT touch the existing per-model session map.--use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::process::Stdio;-use std::sync::Arc;-use std::time::Duration;--use sysinfo::{Pid, ProcessesToUpdate, System};-use tokio::io::{AsyncBufReadExt, BufReader};-use tokio::process::{Child, Command};-use tokio::sync::mpsc;-use tokio::time::Instant;--pub type ErrorCallback = Arc<dyn Fn(&'static str, String) + Send + Sync + 'static>;--/// Matches the various phrasings llama-server has used for its-/// ready-to-serve log line across versions. `line_lower` must already be-/// lowercased by the caller. Router mode logs `"llama_server: listening on-/// http://<host>:<port>"` - note the colon between "server" and "listening"-/// (`"server: listening on"`), which does NOT match the older-/// `"server listening on"` (no colon) wording still used elsewhere, so both-/// must be checked explicitly rather than relying on one subsuming the-/// other.-fn is_ready_line(line_lower: &str) -> bool {- line_lower.contains("http server listening")- || line_lower.contains("server is listening on")- || line_lower.contains("server listening on")- || line_lower.contains("server: listening on")- || line_lower.contains("starting the main loop")-}--fn is_oom_line(line_lower: &str) -> bool {- if line_lower.contains("erroroutofdevicememory")- || line_lower.contains("erroroutofhostmemory")- {- return true;- }- line_lower.contains("failed to allocate") && line_lower.contains("buffer of size")-}--fn is_backend_error_line(line_lower: &str) -> bool {- if line_lower.contains("cuda error:") {- return true;- }- if line_lower.contains("ggml_assert(") {- return true;- }- if line_lower.contains("ggml_vulkan") && line_lower.contains("error") {- return true;- }- if line_lower.contains("ggml_metal") && line_lower.contains("error") {- return true;- }- // GPU device loss (vk::DeviceLostError / ErrorDeviceLost, CUDA device-lost)- // and any uncaught C++ exception abort the child mid-request — surface them- // so a crash during prompt processing still reaches the UI.- if line_lower.contains("devicelost") || line_lower.contains("device lost") {- return true;- }- if line_lower.contains("terminate called after throwing") {- return true;- }- // glibc heap-corruption / stack-protector aborts (SIGABRT). A native memory- // bug in the backend (e.g. the mtmd video decode path) prints one of these- // to stderr just before the process dies — without classifying them the- // crash is silent and the model load appears to hang/loop forever.- if line_lower.contains("corrupted size vs. prev_size")- || line_lower.contains("corrupted double-linked list")- || line_lower.contains("double free or corruption")- || line_lower.contains("malloc(): ")- || line_lower.contains("free(): ")- || line_lower.contains("munmap_chunk(): invalid pointer")- || line_lower.contains("stack smashing detected")- || line_lower.contains("buffer overflow detected")- {- return true;- }- false-}--use crate::error::{ErrorCode, LlamacppError, ServerError, ServerResult};-use jan_utils::{- binary_requires_cuda, binary_requires_rocm, find_cuda_paths, find_rocm_paths,- setup_library_path, setup_windows_process_flags,-};--/// A handle to a running router-mode `llama-server` process.-///-/// `child` is `None` for a router adopted after a UI crash: we inherit the-/// process but not its pipes, so readiness parsing, the OOM/backend-error-/// callback, and log streaming are unavailable until the next restart.-/// Termination falls back to the PID-based path.-pub struct RouterHandle {- pub child: Option<Child>,- pub port: u16,- pub api_key: String,- pub pid: u32,- /// Kept so the stop paths can clear the lock file that sits beside it.- pub preset_path: PathBuf,- /// This run's own log, removed on a deliberate stop.- pub log_path: PathBuf,-}--/// On-disk record of a spawned router, written next to the preset so a-/// relaunched UI can find a process its in-memory state knows nothing about.-///-/// `start_time` is the pid-reuse guard: a recycled PID belongs to a process-/// that started later, so a mismatch means our router is gone. `backend_exe`-/// and `preset_hash` decide adoptability -- a router running a different-/// binary or a stale preset is killed rather than adopted.-#[derive(serde::Serialize, serde::Deserialize, Debug)]-pub struct RouterLock {- pub pid: u32,- pub port: u16,- pub start_time: u64,- pub backend_exe: String,- pub preset_hash: String,- /// An argv flag rather than a preset entry, so the preset hash cannot- /// catch a change to it.- pub models_max: u32,- /// So an adopted router can clean up the log it was actually started with.- #[serde(default)]- pub log_path: String,-}--pub const ROUTER_LOCK_FILENAME: &str = "router.lock.json";-/// One log per router run, in the app's managed `logs/` folder beside-/// `app.log`. It must stay a file of its own -- llama.cpp opens it with mode-/// "w", so sharing `app.log` would truncate Jan's own log on every spawn.-///-/// The token is the port rather than the child's pid: `--log-file` has to be-/// in argv before the process exists, and renaming afterwards is not an option-/// because llama.cpp holds the handle open (which makes `rename` fail outright-/// on Windows). The port is known at that point and matches the lock file, so-/// a log is easy to tie back to a run. Ports are recycled across runs, so the-/// newest log is chosen by mtime, never by name.-pub const ROUTER_LOG_PREFIX: &str = "router-";-pub const ROUTER_LOG_SUFFIX: &str = ".log";--/// Cap for a log we retain after a crash. A run that never restarts cannot be-/// truncated while its process holds the file open, so this applies only to-/// logs left behind by a process that has already exited.-const MAX_RETAINED_LOG_BYTES: u64 = 16 * 1024 * 1024;--fn new_log_path(log_dir: &Path, port: u16) -> PathBuf {- log_dir.join(format!("{}{}{}", ROUTER_LOG_PREFIX, port, ROUTER_LOG_SUFFIX))-}--fn is_router_log(name: &str) -> bool {- name.starts_with(ROUTER_LOG_PREFIX) && name.ends_with(ROUTER_LOG_SUFFIX)-}--/// Called only when the router is shut down deliberately. A clean stop has-/// nothing to diagnose, so this run's log goes; a crash never reaches here, so-/// its log survives for the next session to inspect.-///-/// One log is always kept back -- the newest of whatever remains -- so repeated-/// crashes cannot accumulate, and a user who exits cleanly after a crash still-/// has the crash to look at.-fn cleanup_logs(own_log: &Path) {- if let Err(e) = std::fs::remove_file(own_log) {- if e.kind() != std::io::ErrorKind::NotFound {- log::warn!("Could not remove router log {:?}: {}", own_log, e);- }- }-- let Some(dir) = own_log.parent() else { return };- let Ok(entries) = std::fs::read_dir(dir) else {- return;- };-- let mut logs: Vec<PathBuf> = entries- .filter_map(|e| e.ok())- .map(|e| e.path())- .filter(|p| {- p.file_name()- .and_then(|n| n.to_str())- .map(is_router_log)- .unwrap_or(false)- })- .collect();-- if logs.len() <= 1 {- if let Some(kept) = logs.pop() {- cap_retained_log(&kept);- }- return;- }-- // By mtime, not name: a port-named log says nothing about when it ran, and- // ports are recycled.- logs.sort_by_key(|p| {- std::fs::metadata(p)- .and_then(|m| m.modified())- .unwrap_or(std::time::UNIX_EPOCH)- });- let kept = logs.pop();- for stale in logs {- if let Err(e) = std::fs::remove_file(&stale) {- log::warn!("Could not remove stale router log {:?}: {}", stale, e);- }- }- if let Some(kept) = kept {- log::info!("Retained router log from a previous run: {:?}", kept);- cap_retained_log(&kept);- }-}--/// Keep the tail: a crash signature is written just before the process dies,-/// so the end is the part worth having.-fn cap_retained_log(path: &Path) {- let Ok(meta) = std::fs::metadata(path) else {- return;- };- if meta.len() <= MAX_RETAINED_LOG_BYTES {- return;- }- let tmp = path.with_extension("log.tmp");- match keep_log_tail(path, &tmp, MAX_RETAINED_LOG_BYTES) {- Ok(()) => {- if let Err(e) = std::fs::rename(&tmp, path) {- log::warn!("Could not replace oversized router log: {}", e);- let _ = std::fs::remove_file(&tmp);- } else {- log::info!(- "Router log {:?} was {} bytes; kept the last {}",- path,- meta.len(),- MAX_RETAINED_LOG_BYTES- );- }- }- Err(e) => log::warn!("Could not cap oversized router log: {}", e),- }-}--fn keep_log_tail(src: &Path, dst: &Path, bytes: u64) -> std::io::Result<()> {- use std::io::{Read, Seek, SeekFrom, Write};-- let mut input = std::fs::File::open(src)?;- let len = input.metadata()?.len();- input.seek(SeekFrom::Start(len.saturating_sub(bytes)))?;-- let mut output = std::fs::File::create(dst)?;- let mut buf = vec![0u8; 1024 * 1024];- loop {- let n = input.read(&mut buf)?;- if n == 0 {- break;- }- output.write_all(&buf[..n])?;- }- output.flush()-}--fn lock_path_for(preset_path: &Path) -> PathBuf {- preset_path- .parent()- .unwrap_or_else(|| Path::new("."))- .join(ROUTER_LOCK_FILENAME)-}--pub fn hash_preset(preset_path: &Path) -> String {- match std::fs::read(preset_path) {- Ok(bytes) => {- use sha2::{Digest, Sha256};- let mut hasher = Sha256::new();- hasher.update(&bytes);- format!("{:x}", hasher.finalize())- }- Err(e) => {- log::warn!("hash_preset: cannot read {:?}: {}", preset_path, e);- String::new()- }- }-}--fn process_start_time(pid: u32) -> Option<u64> {- let mut sys = System::new();- sys.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid)]), true);- sys.process(Pid::from_u32(pid)).map(|p| p.start_time())-}--fn write_lock(preset_path: &Path, lock: &RouterLock) {- let path = lock_path_for(preset_path);- match serde_json::to_vec_pretty(lock) {- Ok(bytes) => {- if let Err(e) = std::fs::write(&path, bytes) {- log::warn!("Failed to write router lock {:?}: {}", path, e);- }- }- Err(e) => log::warn!("Failed to serialize router lock: {}", e),- }-}--pub fn remove_lock(preset_path: &Path) {- let path = lock_path_for(preset_path);- if let Err(e) = std::fs::remove_file(&path) {- if e.kind() != std::io::ErrorKind::NotFound {- log::warn!("Failed to remove router lock {:?}: {}", path, e);- }- }-}--pub fn read_lock(preset_path: &Path) -> Option<RouterLock> {- let path = lock_path_for(preset_path);- let bytes = std::fs::read(&path).ok()?;- match serde_json::from_slice::<RouterLock>(&bytes) {- Ok(l) => Some(l),- Err(e) => {- log::warn!("Discarding unreadable router lock {:?}: {}", path, e);- let _ = std::fs::remove_file(&path);- None- }- }-}--/// Re-record the preset hash for a router that hot-reloaded its preset.-///-/// A live reload (`GET /models?reload=1`) applies a new preset without-/// respawning, so the hash captured at spawn goes stale while the running-/// process is in fact up to date. Left alone, the next adoption attempt would-/// read that stale hash, conclude the preset changed, and kill a healthy-/// router.-pub fn refresh_lock_preset_hash(preset_path: &Path) {- let Some(mut lock) = read_lock(preset_path) else {- return;- };- let hash = hash_preset(preset_path);- if lock.preset_hash == hash {- return;- }- lock.preset_hash = hash;- write_lock(preset_path, &lock);- log::debug!("Router lock preset hash refreshed after a live reload");-}--/// Outcome of inspecting a router that outlived its UI.-pub enum AdoptOutcome {- /// Same binary, same preset, answering `/health` -- reuse it.- Adopted(Box<RouterHandle>),- /// Nothing usable was running (no lock, dead PID, or PID reused).- NothingToAdopt,- /// A router was running but could not be reused; it has been killed and- /// the caller should spawn a fresh one.- Killed(&'static str),-}--/// Decide what to do with a router recorded in the lock file. Never spawns.-///-/// The health probe is what makes adoption safe: a process that is alive but-/// wedged is killed rather than inherited.-pub async fn try_adopt_router(- preset_path: &Path,- backend_exe: &Path,- models_max: u32,- api_key: String,-) -> AdoptOutcome {- let Some(lock) = read_lock(preset_path) else {- return AdoptOutcome::NothingToAdopt;- };-- let Some(start_time) = process_start_time(lock.pid) else {- log::info!("Router lock pid {} is not running; discarding", lock.pid);- remove_lock(preset_path);- return AdoptOutcome::NothingToAdopt;- };- if start_time != lock.start_time {- log::info!(- "Router lock pid {} was reused (start_time {} != {}); discarding",- lock.pid,- start_time,- lock.start_time- );- remove_lock(preset_path);- return AdoptOutcome::NothingToAdopt;- }-- let kill = |reason: &'static str| {- log::info!(- "Killing unadoptable router pid {} ({}); a fresh one will be spawned",- lock.pid,- reason- );- force_kill_router_tree_by_pid(lock.pid);- remove_lock(preset_path);- AdoptOutcome::Killed(reason)- };-- if lock.backend_exe != backend_exe.to_string_lossy() {- return kill("backend changed");- }- if lock.preset_hash != hash_preset(preset_path) {- return kill("preset changed");- }- if lock.models_max != models_max {- return kill("models_max changed");- }-- if !probe_health(lock.port, &api_key).await {- return kill("failed health check");- }-- log::info!(- "Adopted router pid {} on port {} (no stdout/stderr pipes; logs unavailable until restart)",- lock.pid,- lock.port- );- AdoptOutcome::Adopted(Box::new(RouterHandle {- child: None,- port: lock.port,- api_key,- pid: lock.pid,- preset_path: preset_path.to_path_buf(),- log_path: PathBuf::from(&lock.log_path),- }))-}--async fn probe_health(port: u16, api_key: &str) -> bool {- let Ok(client) = reqwest::Client::builder()- .timeout(Duration::from_secs(5))- .build()- else {- return false;- };- let url = format!("http://127.0.0.1:{}/health", port);- matches!(- client.get(&url).bearer_auth(api_key).send().await,- Ok(r) if r.status().is_success()- )-}--/// Build the argv for router mode. Pure / unit-testable.-///-/// `models_max == 0` is forwarded as-is; the upstream README documents 0 as-/// "unlimited" — we let the server interpret that.-///-/// The API key is deliberately NOT passed here as `--api-key`: argv is-/// visible to any other process on the machine (`ps`/Task Manager, `/proc`),-/// and we already log the full argv at startup. It's set as the-/// `LLAMA_API_KEY` env var instead (`start_router`, env-only, not inherited-/// by child processes the same way a command-line arg would show up in-/// process listings) - llama-server reads either, preferring the CLI flag-/// when both are present (hence the "will be overwritten" warning it used to-/// print when we set both).-pub fn router_args(- preset_path: &Path,- port: u16,- models_max: u32,- log_path: Option<&Path>,- default_args: &[String],-) -> Vec<String> {- let mut args: Vec<String> = vec![- "--models-preset".to_string(),- preset_path.to_string_lossy().to_string(),- "--models-max".to_string(),- models_max.to_string(),- "--host".to_string(),- "127.0.0.1".to_string(),- "--port".to_string(),- port.to_string(),- ];- // Written in addition to stdout/stderr, not instead of them, so the pipe- // readers below are unaffected. This is the only diagnostic an adopted- // router leaves behind, since adoption inherits no pipes.- if let Some(path) = log_path {- args.push("--log-file".to_string());- args.push(path.to_string_lossy().to_string());- }- // Web-UI disable flag (`--no-webui` pre-b9222, `--no-ui` from b9222) is- // appended by the TS caller via `default_args` because the spelling- // depends on the backend build number.- args.extend(default_args.iter().cloned());- args-}--/// Merges `LLAMA_API_KEY` into `envs`, always overwriting any prior value.-/// Pure / unit-testable - authoritative so this invariant holds even if a-/// future call site forgets to set it or sets a stale one.-fn with_api_key_env(mut envs: HashMap<String, String>, api_key: &str) -> HashMap<String, String> {- envs.insert("LLAMA_API_KEY".to_string(), api_key.to_string());- envs-}--/// Spawn `llama-server` in router mode and wait for it to become ready.-///-/// On readiness-detection failure or spawn failure, the child is killed before-/// returning the error.-#[allow(clippy::too_many_arguments)]-pub async fn start_router(- backend_exe: PathBuf,- preset_path: PathBuf,- log_dir: PathBuf,- port: u16,- api_key: String,- models_max: u32,- default_args: Vec<String>,- envs: HashMap<String, String>,- on_error: Option<ErrorCallback>,-) -> Result<RouterHandle, ServerError> {- log::info!(- "Starting llama-server in router mode: exe={:?} preset={:?} port={} models_max={}",- backend_exe,- preset_path,- port,- models_max- );-- // Authoritative: always carry the key via env, never argv (see- // `router_args`'s doc comment).- let envs = with_api_key_env(envs, &api_key);-- if let Err(e) = std::fs::create_dir_all(&log_dir) {- log::warn!("Could not create router log directory {:?}: {}", log_dir, e);- }- let log_path = new_log_path(&log_dir, port);- let args = router_args(&preset_path, port, models_max, Some(&log_path), &default_args);- log::info!("Router argv: {:?}", args);-- // Resolve readiness timeout (seconds). Match existing convention by- // honoring LLAMA_ARG_TIMEOUT if set in the env map; otherwise default 60s.- let timeout_secs: u64 = envs- .get("LLAMA_ARG_TIMEOUT")- .and_then(|s| s.parse::<u64>().ok())- .unwrap_or(60);-- let mut command = Command::new(&backend_exe);- command.args(&args);- command.envs(&envs);- command.stdout(Stdio::piped());- command.stderr(Stdio::piped());- command.kill_on_drop(true);- setup_windows_process_flags(&mut command);-- let cuda = find_cuda_paths();- if cuda.lib_paths.is_empty()- && cuda.bin_paths.is_empty()- && binary_requires_cuda(&backend_exe)- {- log::warn!(- "llama.cpp router backend appears to require CUDA, but CUDA not found. \- Process may fail to start."- );- }- let rocm = find_rocm_paths();- if rocm.lib_paths.is_empty()- && rocm.bin_paths.is_empty()- && binary_requires_rocm(&backend_exe)- {- log::warn!(- "llama.cpp router backend appears to require ROCm/HIP, but ROCm not found. \- Process may fail to start."- );- }- setup_library_path(backend_exe.parent(), &cuda.merged(rocm), &mut command);-- let mut child = command.spawn().map_err(ServerError::Io)?;-- let stderr = child.stderr.take().expect("stderr was piped");- let stdout = child.stdout.take().expect("stdout was piped");-- let (ready_tx, mut ready_rx) = mpsc::channel::<bool>(1);-- let stdout_ready_tx = ready_tx.clone();- let stdout_on_error = on_error.clone();- let _stdout_task = tokio::spawn(async move {- let mut reader = BufReader::new(stdout);- let mut byte_buffer = Vec::new();- let mut last_error_at: Option<Instant> = None;- loop {- byte_buffer.clear();- match reader.read_until(b'\n', &mut byte_buffer).await {- Ok(0) => break,- Ok(_) => {- let line = String::from_utf8_lossy(&byte_buffer);- let line = line.trim_end();- if !line.is_empty() {- log::info!("[llamacpp-router stdout] {}", line);- }- let line_lower = line.to_lowercase();- if is_ready_line(&line_lower) {- let _ = stdout_ready_tx.send(true).await;- }- if let Some(cb) = &stdout_on_error {- let kind = if is_oom_line(&line_lower) {- Some("oom")- } else if is_backend_error_line(&line_lower) {- Some("backend")- } else {- None- };- if let Some(k) = kind {- let now = Instant::now();- let fire = last_error_at- .map(|t| now.duration_since(t) > Duration::from_secs(3))- .unwrap_or(true);- if fire {- last_error_at = Some(now);- cb(k, line.to_string());- }- }- }- }- Err(e) => {- log::error!("Error reading router stdout: {}", e);- break;- }- }- }- });-- let stderr_on_error = on_error.clone();- let stderr_task = tokio::spawn(async move {- let mut reader = BufReader::new(stderr);- let mut byte_buffer = Vec::new();- let mut stderr_buffer = String::new();- let mut last_error_at: Option<Instant> = None;- loop {- byte_buffer.clear();- match reader.read_until(b'\n', &mut byte_buffer).await {- Ok(0) => break,- Ok(_) => {- let line = String::from_utf8_lossy(&byte_buffer);- let line = line.trim_end();- if !line.is_empty() {- stderr_buffer.push_str(line);- stderr_buffer.push('\n');- log::info!("[llamacpp-router] {}", line);- let line_lower = line.to_lowercase();- if is_ready_line(&line_lower) {- let _ = ready_tx.send(true).await;- }- if let Some(cb) = &stderr_on_error {- let kind = if is_oom_line(&line_lower) {- Some("oom")- } else if is_backend_error_line(&line_lower) {- Some("backend")- } else {- None- };- if let Some(k) = kind {- let now = Instant::now();- let fire = last_error_at- .map(|t| now.duration_since(t) > Duration::from_secs(3))- .unwrap_or(true);- if fire {- last_error_at = Some(now);- cb(k, line.to_string());- }- }- }- }- }- Err(e) => {- log::error!("Error reading router stderr: {}", e);- break;- }- }- }- stderr_buffer- });-- // Early-exit check.- if let Some(status) = child.try_wait()? {- let stderr_output = stderr_task.await.unwrap_or_else(|e| {- log::warn!("Router stderr task join failed: {e}");- String::new()- });- log::error!("llama-server router exited early with status {:?}", status);- return Err(LlamacppError::from_stderr(&stderr_output).into());- }-- let timeout_duration = Duration::from_secs(timeout_secs);- let start_time = Instant::now();- log::info!("Waiting for router to be ready (timeout={}s)...", timeout_secs);-- loop {- tokio::select! {- Some(true) = ready_rx.recv() => {- log::info!("llama-server router is ready.");- break;- }- _ = tokio::time::sleep(Duration::from_millis(50)) => {- if let Some(status) = child.try_wait()? {- let stderr_output = stderr_task.await.unwrap_or_else(|e| {- log::warn!("Router stderr task join failed: {e}");- String::new()- });- log::error!("llama-server router exited before readiness: {:?}", status);- return Err(LlamacppError::from_stderr(&stderr_output).into());- }- if start_time.elapsed() > timeout_duration {- log::error!("Timeout waiting for router to be ready");- let _ = child.kill().await;- let stderr_output = stderr_task.await.unwrap_or_else(|e| {- log::warn!("Router stderr task join failed: {e}");- String::new()- });- return Err(LlamacppError::new(- ErrorCode::ModelLoadTimedOut,- "Router took too long to start and timed out.".into(),- Some(format!(- "Timeout: {}s\n\nStderr:\n{}",- timeout_duration.as_secs(),- stderr_output- )),- )- .into());- }- }- }- }-- let pid = child.id().unwrap_or(0);- write_lock(- &preset_path,- &RouterLock {- pid,- port,- // A PID we just spawned but cannot find is not worth recording:- // without a start_time the reuse guard cannot fire.- start_time: process_start_time(pid).unwrap_or(0),- backend_exe: backend_exe.to_string_lossy().to_string(),- preset_hash: hash_preset(&preset_path),- models_max,- log_path: log_path.to_string_lossy().to_string(),- },- );- Ok(RouterHandle {- child: Some(child),- port,- api_key,- pid,- preset_path,- log_path,- })-}--/// Always terminates; force-kills on busy-deadline. For user-prompt flows-/// use [`try_graceful_stop_router`] directly.-pub async fn stop_router(handle: RouterHandle) -> ServerResult<()> {- match try_graceful_stop_router(handle, Duration::from_secs(10)).await {- Ok(()) => Ok(()),- Err((h, busy)) => {- log::warn!(- "stop_router: deadline hit with {} busy model(s) {:?}; force-killing tree",- busy.len(),- busy- );- force_kill_router_tree(h).await;- Ok(())- }- }-}--/// `Err((handle, busy))` on deadline — caller decides next step.-pub async fn try_graceful_stop_router(- mut handle: RouterHandle,- deadline: Duration,-) -> Result<(), (RouterHandle, Vec<String>)> {- let start = Instant::now();-- let client = match reqwest::Client::builder().build() {- Ok(c) => c,- Err(e) => {- log::warn!("try_graceful_stop_router: failed to build http client: {}; terminating directly", e);- terminate_router_process(&mut handle).await;- return Ok(());- }- };-- let initial = match list_busy_models(&client, handle.port, &handle.api_key).await {- Ok(v) => v,- Err(e) => {- log::warn!(- "try_graceful_stop_router: GET /models failed ({}); router likely already down, terminating",- e- );- terminate_router_process(&mut handle).await;- return Ok(());- }- };-- let loaded_only: Vec<String> = match list_models_filtered(&client, handle.port, &handle.api_key, &["loaded"]).await {- Ok(v) => v,- Err(_) => initial.clone(),- };- let processing =- list_processing_models(&client, handle.port, &handle.api_key, &loaded_only).await;- if !processing.is_empty() {- log::warn!(- "try_graceful_stop_router: {} model(s) actively processing: {:?}",- processing.len(),- processing- );- return Err((handle, processing));- }-- if !initial.is_empty() {- log::info!(- "try_graceful_stop_router: requesting unload for {} model(s)",- initial.len()- );- let unload_url = format!("http://127.0.0.1:{}/models/unload", handle.port);- for id in &initial {- let body = serde_json::json!({ "model": id });- match client- .post(&unload_url)- .bearer_auth(&handle.api_key)- .json(&body)- .send()- .await- {- Ok(r) if r.status().is_success() => {}- Ok(r) => log::warn!("try_graceful_stop_router: unload {} returned {}", id, r.status()),- Err(e) => log::warn!("try_graceful_stop_router: unload {} failed: {}", id, e),- }- }- }-- loop {- let still = list_busy_models(&client, handle.port, &handle.api_key)- .await- .unwrap_or_default();- if still.is_empty() {- break;- }- let elapsed = start.elapsed();- if elapsed >= deadline {- log::warn!(- "try_graceful_stop_router: deadline ({:?}) hit with {} busy model(s)",- deadline,- still.len()- );- return Err((handle, still));- }- let remaining = deadline - elapsed;- tokio::time::sleep(Duration::from_millis(150).min(remaining)).await;- }-- terminate_router_process(&mut handle).await;- Ok(())-}--async fn list_busy_models(- client: &reqwest::Client,- port: u16,- api_key: &str,-) -> Result<Vec<String>, String> {- list_models_filtered(client, port, api_key, &["loaded", "loading"]).await-}--async fn list_models_filtered(- client: &reqwest::Client,- port: u16,- api_key: &str,- allowed_status: &[&str],-) -> Result<Vec<String>, String> {- let url = format!("http://127.0.0.1:{}/models", port);- let resp = client- .get(&url)- .bearer_auth(api_key)- .send()- .await- .map_err(|e| e.to_string())?;- let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;- Ok(json- .get("data")- .and_then(|d| d.as_array())- .map(|arr| {- arr.iter()- .filter(|m| {- m.get("status")- .and_then(|s| s.get("value"))- .and_then(|v| v.as_str())- .map(|s| allowed_status.contains(&s))- .unwrap_or(false)- })- .filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(String::from))- .collect()- })- .unwrap_or_default())-}--async fn list_processing_models(- client: &reqwest::Client,- port: u16,- api_key: &str,- candidates: &[String],-) -> Vec<String> {- let url = format!("http://127.0.0.1:{}/slots", port);- let mut busy = Vec::new();- for id in candidates {- let resp = match client- .get(&url)- .query(&[("model", id.as_str())])- .bearer_auth(api_key)- .send()- .await- {- Ok(r) => r,- Err(e) => {- log::warn!("list_processing_models: GET /slots?model={} failed: {}", id, e);- continue;- }- };- if !resp.status().is_success() {- continue;- }- let Ok(json) = resp.json::<serde_json::Value>().await else {- continue;- };- let is_busy = json- .as_array()- .map(|arr| {- arr.iter().any(|s| {- s.get("is_processing")- .and_then(|v| v.as_bool())- .unwrap_or(false)- })- })- .unwrap_or(false);- if is_busy {- busy.push(id.clone());- }- }- busy-}--/// Terminate the router, using the owned `Child` when we have one and falling-/// back to a PID-based tree kill for an adopted process.-async fn terminate_router_process(handle: &mut RouterHandle) {- remove_lock(&handle.preset_path);- cleanup_logs(&handle.log_path);- let Some(child) = handle.child.as_mut() else {- force_kill_router_tree_by_pid(handle.pid);- return;- };- #[cfg(unix)]- {- crate::process::graceful_terminate_process(child).await;- }- #[cfg(all(windows, target_arch = "x86_64"))]- {- crate::process::force_terminate_process(child).await;- }- #[cfg(not(any(unix, all(windows, target_arch = "x86_64"))))]- {- let _ = child.kill().await;- let _ = child.wait().await;- }-}--/// Force-kill by PID only; used when the handle is owned elsewhere-/// (e.g. the watcher loop). Does not reap — the holder of the `Child`-/// will reap on its next operation or on drop.-pub fn force_kill_router_tree_by_pid(router_pid: u32) {- let mut sys = System::new();- sys.refresh_processes(ProcessesToUpdate::All, true);- let rpid = Pid::from_u32(router_pid);- let children: Vec<Pid> = sys- .processes()- .values()- .filter(|p| p.parent() == Some(rpid))- .map(|p| p.pid())- .collect();- log::info!(- "force_kill_router_tree_by_pid: router pid {} + {} direct child(ren)",- router_pid,- children.len()- );- if let Some(p) = sys.process(rpid) {- let _ = p.kill();- }- for cpid in &children {- if let Some(p) = sys.process(*cpid) {- let _ = p.kill();- }- }-}--/// Router is killed before children so it can't spawn new ones mid-sweep.-pub async fn force_kill_router_tree(mut handle: RouterHandle) {- remove_lock(&handle.preset_path);- cleanup_logs(&handle.log_path);- let router_pid = handle.pid;- let mut sys = System::new();- sys.refresh_processes(ProcessesToUpdate::All, true);-- let rpid = Pid::from_u32(router_pid);- let children: Vec<Pid> = sys- .processes()- .values()- .filter(|p| p.parent() == Some(rpid))- .map(|p| p.pid())- .collect();-- log::info!(- "force_kill_router_tree: router pid {} + {} direct child(ren)",- router_pid,- children.len()- );-- if let Some(p) = sys.process(rpid) {- if !p.kill() {- log::debug!("force_kill_router_tree: router pid {} kill() false (likely already dying)", router_pid);- }- }- // Failures are expected: router's own exit handler reaps these in parallel.- for cpid in &children {- if let Some(p) = sys.process(*cpid) {- let _ = p.kill();- }- }-- if let Some(child) = handle.child.as_mut() {- let _ = child.wait().await;- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::path::PathBuf;-- fn preset_in(dir: &Path, body: &str) -> PathBuf {- let p = dir.join("router.preset.ini");- std::fs::write(&p, body).unwrap();- p- }-- fn lock_for(preset: &Path, pid: u32, models_max: u32) -> RouterLock {- RouterLock {- pid,- port: 1337,- start_time: process_start_time(pid).unwrap_or(0),- backend_exe: "/backends/llama-server".to_string(),- preset_hash: hash_preset(preset),- models_max,- log_path: String::new(),- }- }-- #[test]- fn lock_roundtrips_next_to_the_preset() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- let lock = lock_for(&preset, 4242, 2);-- write_lock(&preset, &lock);- assert!(dir.path().join(ROUTER_LOCK_FILENAME).exists());-- let read = read_lock(&preset).expect("lock should be readable");- assert_eq!(read.pid, 4242);- assert_eq!(read.port, 1337);- assert_eq!(read.models_max, 2);-- remove_lock(&preset);- assert!(read_lock(&preset).is_none());- }-- #[test]- fn corrupt_lock_is_discarded_not_returned() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- std::fs::write(dir.path().join(ROUTER_LOCK_FILENAME), b"{not json").unwrap();-- assert!(read_lock(&preset).is_none());- // A lock we cannot parse must not survive to be retried forever.- assert!(!dir.path().join(ROUTER_LOCK_FILENAME).exists());- }-- #[test]- fn removing_an_absent_lock_is_not_an_error() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- remove_lock(&preset);- remove_lock(&preset);- }-- #[test]- fn preset_hash_tracks_content() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");- let before = hash_preset(&preset);-- std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();- assert_ne!(before, hash_preset(&preset));-- std::fs::write(&preset, "[*]\nctx_size=4096\n").unwrap();- assert_eq!(before, hash_preset(&preset));- }-- #[test]- fn missing_preset_hashes_empty_rather_than_panicking() {- let dir = tempfile::tempdir().unwrap();- assert_eq!(hash_preset(&dir.path().join("absent.ini")), "");- }-- #[test]- fn refreshing_the_lock_hash_survives_a_hot_reload() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");- write_lock(&preset, &lock_for(&preset, 4242, 1));-- // A live reload rewrites the preset without respawning.- std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();- assert_ne!(read_lock(&preset).unwrap().preset_hash, hash_preset(&preset));-- refresh_lock_preset_hash(&preset);-- let lock = read_lock(&preset).unwrap();- assert_eq!(lock.preset_hash, hash_preset(&preset));- // Everything else about the run is untouched.- assert_eq!(lock.pid, 4242);- assert_eq!(lock.port, 1337);- }-- // Uses a throwaway child rather than our own pid: reaching the health- // probe means reaching the kill branch, and force_kill_router_tree_by_pid- // would take the test runner with it.- #[cfg(unix)]- #[tokio::test]- async fn a_hot_reloaded_router_is_still_adoptable() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\nctx_size=4096\n");-- let mut child = std::process::Command::new("sleep")- .arg("30")- .spawn()- .expect("spawn a stand-in process");- let mut lock = lock_for(&preset, child.id(), 1);- lock.backend_exe = "/backends/llama-server".to_string();- write_lock(&preset, &lock);-- std::fs::write(&preset, "[*]\nctx_size=8192\n").unwrap();- refresh_lock_preset_hash(&preset);-- // Reaches the health probe rather than being killed for a stale hash.- // Nothing listens on the recorded port, so it fails there instead.- let outcome = try_adopt_router(- &preset,- Path::new("/backends/llama-server"),- 1,- "k".into(),- )- .await;- let _ = child.wait();- assert!(- matches!(outcome, AdoptOutcome::Killed("failed health check")),- "should not be killed for a preset change after the hash is refreshed"- );- }-- #[tokio::test]- async fn no_lock_means_nothing_to_adopt() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- let outcome = try_adopt_router(- &preset,- Path::new("/backends/llama-server"),- 1,- "k".into(),- )- .await;- assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));- }-- #[tokio::test]- async fn dead_pid_discards_the_lock() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- // Never-valid PID: no process can match, so this exercises the- // liveness check without depending on a real one.- let mut lock = lock_for(&preset, u32::MAX, 1);- lock.start_time = 1;- write_lock(&preset, &lock);-- let outcome = try_adopt_router(- &preset,- Path::new("/backends/llama-server"),- 1,- "k".into(),- )- .await;- assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));- assert!(read_lock(&preset).is_none());- }-- #[tokio::test]- async fn pid_reuse_is_caught_by_start_time() {- let dir = tempfile::tempdir().unwrap();- let preset = preset_in(dir.path(), "[*]\n");- let mut lock = lock_for(&preset, std::process::id(), 1);- // Our own PID is alive, but this start_time cannot be ours.- lock.start_time = lock.start_time.wrapping_add(9999);- write_lock(&preset, &lock);-- let outcome = try_adopt_router(- &preset,- Path::new("/backends/llama-server"),- 1,- "k".into(),- )- .await;- assert!(matches!(outcome, AdoptOutcome::NothingToAdopt));- assert!(read_lock(&preset).is_none());- }-- #[test]- fn router_args_adds_log_file_only_when_asked() {- let preset = PathBuf::from("/tmp/router.preset.ini");- assert!(!router_args(&preset, 1337, 1, None, &[])- .iter()- .any(|a| a == "--log-file"));-- let args = router_args(&preset, 1337, 1, Some(Path::new("/tmp/r.log")), &[]);- let i = args.iter().position(|a| a == "--log-file").unwrap();- assert_eq!(args[i + 1], "/tmp/r.log");- }-- #[test]- fn router_log_never_shares_the_app_log_file() {- // llama.cpp opens the log with mode "w"; sharing app.log would- // truncate Jan's own log on every spawn.- let path = new_log_path(Path::new("/logs"), 1337);- assert_eq!(path.file_name().unwrap(), "router-1337.log");- assert_ne!(path.file_name().unwrap(), "app.log");- }-- fn write_log(dir: &Path, port: u16, body: &[u8]) -> PathBuf {- let p = new_log_path(dir, port);- std::fs::write(&p, body).unwrap();- p- }-- #[test]- fn a_clean_stop_removes_its_own_log() {- let dir = tempfile::tempdir().unwrap();- let own = write_log(dir.path(), 1337, b"clean run");-- cleanup_logs(&own);-- assert!(!own.exists());- }-- #[test]- fn a_crashed_run_leaves_its_log_for_the_next_clean_stop() {- let dir = tempfile::tempdir().unwrap();- // The crashed run never reached cleanup, so its log is still here.- let crashed = write_log(dir.path(), 4242, b"CUDA error: out of memory");- let own = write_log(dir.path(), 1337, b"clean run");-- cleanup_logs(&own);-- assert!(!own.exists());- assert!(crashed.exists(), "crash evidence must survive a clean stop");- }-- #[test]- fn repeated_crashes_keep_only_the_most_recent_log() {- let dir = tempfile::tempdir().unwrap();- let old = write_log(dir.path(), 1111, b"first crash");- let newer = write_log(dir.path(), 2222, b"second crash");- // Ports say nothing about ordering, so age is taken from mtime.- let long_ago = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);- let f = std::fs::File::options().write(true).open(&old).unwrap();- f.set_times(std::fs::FileTimes::new().set_modified(long_ago))- .unwrap();- drop(f);-- let own = write_log(dir.path(), 3333, b"clean run");- cleanup_logs(&own);-- assert!(!own.exists());- assert!(!old.exists(), "the older crash log should be swept");- assert!(newer.exists(), "the newest crash log is kept");- }-- #[test]- fn a_retained_oversized_log_is_capped_to_its_tail() {- let dir = tempfile::tempdir().unwrap();- let mut body = vec![b'x'; (MAX_RETAINED_LOG_BYTES + 4096) as usize];- body.extend_from_slice(b"CUDA error: out of memory");- let crashed = write_log(dir.path(), 4242, &body);- let own = write_log(dir.path(), 1337, b"clean run");-- cleanup_logs(&own);-- let kept = std::fs::read(&crashed).unwrap();- assert_eq!(kept.len() as u64, MAX_RETAINED_LOG_BYTES);- // The crash signature is at the end, so the tail is what must survive.- assert!(kept.ends_with(b"CUDA error: out of memory"));- }-- #[test]- fn cleanup_ignores_files_that_are_not_router_logs() {- let dir = tempfile::tempdir().unwrap();- let app_log = dir.path().join("app.log");- std::fs::write(&app_log, b"jan's own log").unwrap();- let own = write_log(dir.path(), 1337, b"clean run");-- cleanup_logs(&own);-- assert_eq!(std::fs::read(&app_log).unwrap(), b"jan's own log");- }-- #[test]- fn router_args_contains_required_flags() {- let preset = PathBuf::from("/tmp/preset.ini");- let args = router_args(&preset, 1337, 4, None, &[]);-- // Required flags present- let joined = args.join(" ");- assert!(joined.contains("--models-preset /tmp/preset.ini"));- assert!(!args.iter().any(|a| a == "--no-models-autoload"));- assert!(joined.contains("--models-max 4"));- assert!(joined.contains("--host 127.0.0.1"));- assert!(joined.contains("--port 1337"));- // Web-UI disable flag is now appended by the caller (it's- // build-number-dependent: --no-webui vs --no-ui), so it must NOT be- // baked into the base argv.- assert!(!args.iter().any(|a| a == "--no-webui"));- assert!(!args.iter().any(|a| a == "--no-ui"));- }-- #[test]- fn with_api_key_env_sets_the_key() {- let envs = with_api_key_env(HashMap::new(), "secret-key");- assert_eq!(envs.get("LLAMA_API_KEY"), Some(&"secret-key".to_string()));- }-- #[test]- fn with_api_key_env_overwrites_a_stale_value() {- let mut initial = HashMap::new();- initial.insert("LLAMA_API_KEY".to_string(), "stale-key".to_string());- let envs = with_api_key_env(initial, "fresh-key");- assert_eq!(envs.get("LLAMA_API_KEY"), Some(&"fresh-key".to_string()));- }-- #[test]- fn with_api_key_env_preserves_other_vars() {- let mut initial = HashMap::new();- initial.insert("LLAMA_ARG_TIMEOUT".to_string(), "60".to_string());- let envs = with_api_key_env(initial, "secret-key");- assert_eq!(envs.get("LLAMA_ARG_TIMEOUT"), Some(&"60".to_string()));- assert_eq!(envs.get("LLAMA_API_KEY"), Some(&"secret-key".to_string()));- }-- #[test]- fn is_ready_line_matches_router_mode_wording() {- // Regression: router mode logs "llama_server: listening on- // http://host:port" (colon before "listening"), which the older- // "server listening on" (no colon) pattern does not match -- // readiness was never detected and start_router hung for the full- // 600s timeout despite the server already serving requests.- let line = "0.00.021.026 i srv llama_server: listening on http://127.0.0.1:55707";- assert!(is_ready_line(line));- }-- #[test]- fn is_ready_line_still_matches_older_wordings() {- assert!(is_ready_line("http server listening on 127.0.0.1:8080"));- assert!(is_ready_line("server is listening on http://127.0.0.1:8080"));- assert!(is_ready_line("server listening on 127.0.0.1:8080"));- assert!(is_ready_line("starting the main loop"));- }-- #[test]- fn is_ready_line_rejects_unrelated_lines() {- assert!(!is_ready_line("srv log_server_r: request: post /v1/chat/completions"));- assert!(!is_ready_line("loaded 5 custom model presets"));- }-- #[test]- fn router_args_never_carries_the_api_key() {- // The key must travel via the LLAMA_API_KEY env var only - argv is- // visible to any other process on the machine (ps/Task Manager) and- // gets logged verbatim at startup.- let preset = PathBuf::from("/tmp/preset.ini");- let args = router_args(&preset, 1337, 4, None, &[]);- assert!(!args.iter().any(|a| a == "--api-key"));- assert!(!args.join(" ").to_lowercase().contains("api-key"));- }-- #[test]- fn router_args_appends_default_args_in_order() {- let preset = PathBuf::from("/tmp/p.ini");- let extras = vec!["--threads".to_string(), "8".to_string(), "--metrics".to_string()];- let args = router_args(&preset, 8080, 2, None, &extras);-- // The defaults must appear after our base flags, preserving order.- let last_three: Vec<&String> = args.iter().rev().take(3).collect::<Vec<_>>().into_iter().rev().collect();- assert_eq!(last_three, vec![&extras[0], &extras[1], &extras[2]]);- }-- #[test]- fn router_args_passes_through_models_max_zero() {- // README: 0 means unlimited; we forward as-is.- let preset = PathBuf::from("/tmp/p.ini");- let args = router_args(&preset, 8080, 0, None, &[]);- let joined = args.join(" ");- assert!(joined.contains("--models-max 0"));- }-- #[test]- fn classifies_backend_crash_lines() {- // Inputs arrive already lowercased from the caller.- assert!(is_backend_error_line(- "what(): vk::device::waitforfences: errordevicelost"- ));- assert!(is_backend_error_line(- "terminate called after throwing an instance of 'vk::devicelosterror'"- ));- assert!(is_backend_error_line("cuda error: out of memory"));- assert!(is_backend_error_line("ggml_assert(cond) failed"));- // glibc heap-corruption aborts (e.g. mtmd video decode crash).- assert!(is_backend_error_line("corrupted size vs. prev_size"));- assert!(is_backend_error_line(- "malloc(): corrupted top size"- ));- assert!(is_backend_error_line("stack smashing detected"));- assert!(!is_backend_error_line(- "srv log_server_r: request: post /v1/chat/completions"- ));- // OOM is classified on its own path.- assert!(is_oom_line("erroroutofdevicememory"));- }-}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rsindex 2a79e40e7..af1bebe8c 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/state.rs@@ -1,5 +1,4 @@use serde::{Deserialize, Serialize};-use std::sync::atomic::AtomicU32;use tokio::sync::Mutex;#[derive(Debug, Clone, Serialize, Deserialize)]@@ -12,20 +11,18 @@ pub struct SessionInfo {}pub struct LlamacppState {- pub router: Mutex<Option<crate::router::RouterHandle>>,- /// Mirror of the router PID for emergency lookup (e.g. force-kill while- /// the handle is temporarily owned by the watcher loop). 0 = no router.- pub router_pid: AtomicU32,- /// Persistent `/models/sse` subscriber (router-side unload notifications),- /// alive for the router's lifetime. Aborted whenever the router stops.+ /// The supervised engine worker, when one is running.+ pub engine: Mutex<Option<crate::engine::worker::WorkerHandle>>,+ /// Persistent `/models/sse` subscriber, alive for the worker's lifetime.+ /// It is what turns an eviction Jan did not initiate into a frontend+ /// event, so it is aborted whenever the worker stops.pub unload_watcher: Mutex<Option<tokio::task::JoinHandle<()>>>,}impl Default for LlamacppState {fn default() -> Self {Self {- router: Mutex::new(None),- router_pid: AtomicU32::new(0),+ engine: Mutex::new(None),unload_watcher: Mutex::new(None),}}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/tests/engine_smoke.rs b/src-tauri/plugins/tauri-plugin-llamacpp/tests/engine_smoke.rsnew file mode 100644index 000000000..4f922576a--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/tests/engine_smoke.rs@@ -0,0 +1,315 @@+//! End-to-end check that the in-process engine loads a real model and streams.+//!+//! Opt-in: set JAN_TEST_GGUF to a small model. It needs the `engine` feature+//! (so a compiled llama.cpp) and a few hundred MB of RAM, neither of which the+//! default test job has.+#![cfg(feature = "engine")]++use tauri_plugin_llamacpp::engine::{Engine, Route};++fn model_path() -> Option<String> {+ // Registering the ggml backends is the caller's job and has to happen+ // before any other ggml call. A test binary sits in target/<profile>/ with+ // no backend modules beside it, and with GGML_BACKEND_DL every backend+ // including the CPU one is a loadable module -- so without this, loading a+ // model fails with no backend registered at all. Called from here because+ // it gates every test in the file and is idempotent.+ tauri_plugin_llamacpp::engine::load_backend_modules();+ std::env::var("JAN_TEST_GGUF").ok().filter(|p| !p.is_empty())+}++fn start(model: &str) -> Engine {+ let args: Vec<String> = [+ "llama-server", "-m", model, "-c", "2048", "-ngl", "0",+ "--no-warmup", "-t", "4", "-fit", "off", "-np", "1",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ Engine::start(&args, None).expect("engine should start")+}++// `server_context::load_model` only returns a bool, so without the shim's log+// capture every failure reads as the same bare "failed to load model" and the+// desktop cannot tell a VRAM exhaustion from a bad path. Needs no model file:+// the point is that llama.cpp's own error text rides along.+#[test]+fn a_failed_load_reports_the_reason_llama_cpp_logged() {+ tauri_plugin_llamacpp::engine::load_backend_modules();+ let missing = std::env::temp_dir().join("jan-no-such-model.gguf");+ let args: Vec<String> = [+ "llama-server",+ "-m",+ &missing.to_string_lossy(),+ "--no-warmup",+ "-ngl",+ "0",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();++ let err = Engine::start(&args, None).expect_err("a missing model cannot load");+ let msg = err.to_string();++ assert!(msg.contains("failed to load model"), "{msg}");+ assert!(+ msg.len() > "could not start the llama.cpp engine: failed to load model".len(),+ "no captured log lines in: {msg}"+ );+}++#[test]+fn loads_a_model_and_answers_health_and_models() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let engine = start(&model);++ let res = engine.request(Route::Health.as_shim_name(), "");+ assert_eq!(res.status(), 200, "health body: {}", res.body());+ assert!(res.body().contains("ok"));++ let res = engine.request(Route::Models.as_shim_name(), "");+ assert_eq!(res.status(), 200);+ let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();+ assert!(+ v.pointer("/data/0/meta/n_ctx").is_some(),+ "no model metadata: {}",+ res.body()+ );+}++#[test]+fn a_chat_completion_applies_the_template_and_reports_usage() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let engine = start(&model);++ let res = engine.request(+ Route::ChatCompletions.as_shim_name(),+ r#"{"messages":[{"role":"user","content":"Say only: OK"}],+ "max_tokens":200,"temperature":0}"#,+ );+ assert_eq!(res.status(), 200, "body: {}", res.body());+ let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();++ // A response at all means the model's chat template was applied: without+ // it the prompt would not have been wrapped and there would be no message.+ assert!(+ v.pointer("/choices/0/message/role").is_some(),+ "no assistant message: {}",+ res.body()+ );+ assert!(+ v.pointer("/usage/completion_tokens")+ .and_then(|t| t.as_u64())+ .unwrap_or(0)+ > 0,+ "no tokens generated: {}",+ res.body()+ );+}++#[test]+fn a_streaming_completion_yields_sse_chunks_then_finishes() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let engine = start(&model);++ let mut res = engine.request(+ Route::ChatCompletions.as_shim_name(),+ r#"{"messages":[{"role":"user","content":"Count to five."}],+ "max_tokens":80,"temperature":0,"stream":true}"#,+ );+ assert_eq!(res.status(), 200);+ assert!(res.is_stream(), "expected a streaming response");+ assert_eq!(res.content_type(), "text/event-stream");++ // The first frame arrives in the body; the rest through next_chunk().+ let mut frames = res.body().matches("data: ").count();+ let mut guard = 0;+ while let Some(chunk) = res.next_chunk().expect("generator threw") {+ frames += chunk.matches("data: ").count();+ guard += 1;+ assert!(guard < 10_000, "stream did not terminate");+ }+ assert!(frames > 1, "expected multiple SSE frames, got {frames}");+ // Draining past the end must stay terminated rather than restart.+ assert_eq!(res.next_chunk().unwrap(), None);+}++#[test]+fn an_unknown_route_is_a_404_not_a_crash() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let engine = start(&model);+ let res = engine.request("post_does_not_exist", "{}");+ assert_eq!(res.status(), 404, "body: {}", res.body());+}++/// Two engines in one process, concurrently. This is the property that made+/// `server_context` the right level to link: `llama_server()` keeps its+/// shutdown handler in a file-scope global (server.cpp:25), so a second+/// instance would steal the first one's teardown -- which is why multi-model+/// upstream means multi-*process*. Driving server_context directly does not+/// have that limit, so models_max can be served in-process.+#[test]+fn two_engines_coexist_in_one_process() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let a = start(&model);+ let b = start(&model);++ for (name, engine) in [("a", &a), ("b", &b)] {+ let res = engine.request(Route::Health.as_shim_name(), "");+ assert_eq!(res.status(), 200, "engine {name} unhealthy: {}", res.body());+ }++ // And both can generate, so they are not sharing one queue.+ for (name, engine) in [("a", &a), ("b", &b)] {+ let res = engine.request(+ Route::ChatCompletions.as_shim_name(),+ r#"{"messages":[{"role":"user","content":"hi"}],"max_tokens":16,"temperature":0}"#,+ );+ assert_eq!(res.status(), 200, "engine {name} failed: {}", res.body());+ }++ // Dropping one must not disturb the other.+ drop(a);+ let res = b.request(Route::Health.as_shim_name(), "");+ assert_eq!(res.status(), 200, "engine b died with a: {}", res.body());+}++/// Regression: stopping an engine that never served a request used to hang+/// forever. `server_queue::start_loop` sets `running = true` at its top+/// (server-queue.cpp:279), so a `terminate()` issued before the loop thread+/// reaches that line is erased and the loop blocks. In the app that is a+/// shutdown hang after loading a model the user never used.+#[test]+fn an_engine_stops_promptly_even_if_it_never_served_a_request() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ // Repeat: the failure is a race, so one pass proves little.+ for attempt in 0..5 {+ let started = std::time::Instant::now();+ let engine = start(&model);+ drop(engine); // immediate stop, no request in between+ let elapsed = started.elapsed();+ assert!(+ elapsed < std::time::Duration::from_secs(20),+ "attempt {attempt}: start+stop took {elapsed:?}, which means the \+ loop missed its terminate"+ );+ }+}++/// The preset path starts from a default-constructed `common_params`, so the+/// per-example defaults `common_params_parser_init` applies for+/// `LLAMA_EXAMPLE_SERVER` -- and the `n_parallel < 0` resolution in+/// `server.cpp`'s `main`, which nothing here goes through -- have to be+/// applied by the shim. Without them an ini with no `parallel` key gets one+/// slot instead of llama-server's four.+#[test]+fn a_preset_without_parallel_gets_the_server_side_auto_default() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ let dir = tempfile::tempdir().expect("tempdir");+ let ini = dir.path().join("router.preset.ini");+ std::fs::write(+ &ini,+ format!(+ "[*]\nfit = off\nctx-size = 2048\nno-warmup = true\n\n\+ [m]\nmodel = {model}\nn-gpu-layers = 0\n"+ ),+ )+ .expect("write ini");++ let engine = Engine::start_from_preset(&ini.to_string_lossy(), "m", None)+ .expect("engine should start from the preset");++ let res = engine.request(Route::Props.as_shim_name(), "");+ assert_eq!(res.status(), 200, "props body: {}", res.body());+ let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();+ assert_eq!(+ v.pointer("/total_slots").and_then(|s| s.as_i64()),+ Some(4),+ "props: {}",+ res.body()+ );+}++/// `server_context` is the only source of real load progress: it reports it+/// through `set_state_callback` and there is nothing to poll for it. Without+/// the shim installing that callback the desktop's whole progress chain --+/// `/models/sse` -> `parse_load_progress_event` -> `PromptProgress` -- sits+/// idle on a plain spinner, which is what it did.+#[test]+fn a_load_reports_its_progress_through_the_state_callback() {+ let Some(model) = model_path() else {+ eprintln!("skipping: set JAN_TEST_GGUF to run");+ return;+ };+ use std::sync::{Arc, Mutex};++ let samples: Arc<Mutex<Vec<(String, f64)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = Arc::clone(&samples);+ let args: Vec<String> = [+ "llama-server", "-m", &model, "-c", "2048", "-ngl", "0",+ "--no-warmup", "-t", "4", "-fit", "off", "-np", "1",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();++ let engine = Engine::start(+ &args,+ Some(Arc::new(move |state: &str, payload: &str| {+ let v: serde_json::Value = match serde_json::from_str(payload) {+ Ok(v) => v,+ Err(_) => return,+ };+ if let Some(value) = v.get("value").and_then(|v| v.as_f64()) {+ let stage = v+ .get("current")+ .and_then(|s| s.as_str())+ .unwrap_or_default()+ .to_string();+ sink.lock().unwrap().push((format!("{state}:{stage}"), value));+ }+ })),+ )+ .expect("engine should start");++ let seen = samples.lock().unwrap().clone();+ assert!(!seen.is_empty(), "no progress samples arrived");+ assert!(+ seen.iter().all(|(s, _)| s.starts_with("loading:")),+ "a sample carried a value outside the loading state: {seen:?}"+ );+ // The callback always emits the first and the last sample, whatever the+ // 200ms throttle drops in between.+ assert_eq!(seen.first().map(|(_, v)| *v), Some(0.0), "{seen:?}");+ assert!(+ seen.iter().any(|(s, v)| *v >= 1.0 && s == "loading:text_model"),+ "the text model never reported completion: {seen:?}"+ );++ // And the engine is usable, i.e. installing the callback did not disturb+ // the load it observes.+ let res = engine.request(Route::Health.as_shim_name(), "");+ assert_eq!(res.status(), 200, "health body: {}", res.body());+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_http.rs b/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_http.rsnew file mode 100644index 000000000..d4f826b00--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_http.rs@@ -0,0 +1,758 @@+//! The loopback HTTP surface, driven the way Jan's own callers drive it:+//! `proxy.rs` forwards to `http://127.0.0.1:<port>/v1<path>` with a bearer+//! token, and the extension's `chat()` posts to `/v1/chat/completions`.+//!+//! Opt-in on JAN_TEST_GGUF, like tests/engine_smoke.rs.+#![cfg(feature = "engine")]++use std::sync::Arc;++use tauri_plugin_llamacpp::engine::http::EngineServer;+use tauri_plugin_llamacpp::engine::registry::{LoadSpec, Registry};+use tauri_plugin_llamacpp::engine::slots::{state_key, StateStore};+use std::time::Duration;+use tokio::sync::Mutex;++const MODEL_ID: &str = "test-model";+const KEY: &str = "test-key";++fn model_path() -> Option<String> {+ // Registering the ggml backends is the caller's job and has to happen+ // before any other ggml call. A test binary sits in target/<profile>/ with+ // no backend modules beside it, and with GGML_BACKEND_DL every backend+ // including the CPU one is a loadable module -- so without this, loading a+ // model fails with no backend registered at all. Called from here because+ // it gates every test in the file and is idempotent.+ tauri_plugin_llamacpp::engine::load_backend_modules();+ std::env::var("JAN_TEST_GGUF").ok().filter(|p| !p.is_empty())+}++fn spec(model: &str, slot_dir: Option<&str>) -> LoadSpec {+ let mut args: Vec<String> = [+ "llama-server", "-m", model, "-c", "2048", "-ngl", "0",+ "--no-warmup", "-t", "4", "-fit", "off", "-np", "1",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ if let Some(dir) = slot_dir {+ args.push("--slot-save-path".to_string());+ args.push(dir.to_string());+ }+ LoadSpec::Args(args)+}++/// Spawns a server on an OS-chosen port and returns its base url.+async fn serve(model: &str, models_max: usize) -> String {+ let mut reg = Registry::new(models_max);+ reg.register(MODEL_ID, spec(model, None));+ let (server, listener) = EngineServer::bind(Arc::new(Mutex::new(reg)), 0, KEY.into())+ .await+ .expect("loopback bind");+ let base = format!("http://127.0.0.1:{}", server.port);+ tokio::spawn(server.serve(listener));+ base+}++/// The same server with cross-session KV persistence on, plus the directory it+/// saves into so a test can inspect what landed there.+async fn serve_with_state(+ model: &str,+ budget_mib: u64,+) -> (String, std::path::PathBuf, Arc<EngineServer>) {+ let dir = std::env::temp_dir().join(format!(+ "jan-slot-it-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();++ let mut reg = Registry::new(1);+ reg.register(MODEL_ID, spec(model, Some(dir.to_str().unwrap())));+ let (server, listener) = EngineServer::bind(Arc::new(Mutex::new(reg)), 0, KEY.into())+ .await+ .expect("loopback bind");+ let base = format!("http://127.0.0.1:{}", server.port);+ let server = Arc::new(server.with_slot_state(StateStore::new(&dir, budget_mib)));+ tokio::spawn(+ Arc::clone(&server)+ .serve_until(listener, std::future::pending::<()>(), Duration::ZERO),+ );+ (base, dir, server)+}++/// A chat turn long enough to leave more than MIN_TOKENS_TO_SAVE in the slot,+/// tagged with the thread it belongs to.+fn chat_body(thread: &str) -> String {+ // ~40 words repeated: short prompts are deliberately not persisted, so a+ // one-liner would test the skip path instead of the save path.+ let filler = "the quick brown fox jumps over the lazy dog and keeps running ".repeat(40);+ serde_json::json!({+ "model": MODEL_ID,+ "thread_id": thread,+ "id_slot": 0,+ "max_tokens": 1,+ "messages": [{ "role": "user", "content": filler }],+ })+ .to_string()+}++fn saved_states(dir: &std::path::Path) -> Vec<String> {+ let mut v: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .flatten()+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .filter(|n| n.ends_with(".bin"))+ .collect();+ v.sort();+ v+}++async fn post(base: &str, path: &str, body: &str, key: Option<&str>) -> (u16, String) {+ let mut req = reqwest::Client::new().post(format!("{base}{path}"));+ if let Some(k) = key {+ req = req.bearer_auth(k);+ }+ let res = req+ .header("content-type", "application/json")+ .body(body.to_string())+ .send()+ .await+ .expect("request should reach the loopback server");+ (res.status().as_u16(), res.text().await.unwrap_or_default())+}++/// Serves a registry whose one model cannot possibly load, so the lifecycle+/// feed can be exercised without a GGUF on disk.+async fn serve_unloadable() -> String {+ tauri_plugin_llamacpp::engine::load_backend_modules();+ let mut reg = Registry::new(1);+ reg.register(MODEL_ID, spec("/nonexistent/jan-test-model.gguf", None));+ let (server, listener) = EngineServer::bind(Arc::new(Mutex::new(reg)), 0, KEY.into())+ .await+ .expect("loopback bind");+ let base = format!("http://127.0.0.1:{}", server.port);+ tokio::spawn(server.serve(listener));+ base+}++/// The lifecycle feed Jan subscribes to for the length of a load. Needs no+/// model: a load that cannot succeed still has to announce both transitions,+/// and the nonzero exit code is what tells the desktop it failed rather than+/// having been evicted.+#[tokio::test(flavor = "multi_thread")]+async fn models_sse_streams_the_load_transitions() {+ use futures_util::StreamExt;++ let base = serve_unloadable().await;++ let unauth = reqwest::Client::new()+ .get(format!("{base}/models/sse"))+ .send()+ .await+ .unwrap();+ assert_eq!(unauth.status(), 401, "the feed must require the key");++ let resp = reqwest::Client::new()+ .get(format!("{base}/models/sse"))+ .bearer_auth(KEY)+ .send()+ .await+ .expect("the feed should be reachable");+ assert_eq!(resp.status(), 200);+ assert_eq!(+ resp.headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok()),+ Some("text/event-stream")+ );++ // Posted only once the stream is established, which is the ordering the+ // plugin's own loader follows -- the load is synchronous, so a subscriber+ // that arrives afterwards sees nothing.+ let load = tokio::spawn({+ let base = base.clone();+ async move {+ post(+ &base,+ "/models/load",+ &format!(r#"{{"model":"{MODEL_ID}"}}"#),+ Some(KEY),+ )+ .await+ }+ });++ let mut stream = resp.bytes_stream();+ let mut seen = String::new();+ let deadline = tokio::time::Instant::now() + Duration::from_secs(60);+ while !seen.contains("unloaded") {+ let next = tokio::time::timeout_at(deadline, stream.next()).await;+ match next {+ Ok(Some(Ok(bytes))) => seen.push_str(&String::from_utf8_lossy(&bytes)),+ Ok(Some(Err(e))) => panic!("stream error: {e}"),+ Ok(None) => panic!("stream ended before the load resolved: {seen:?}"),+ Err(_) => panic!("timed out waiting for the transitions: {seen:?}"),+ }+ }++ let (status, body) = load.await.unwrap();+ assert_eq!(status, 400, "an impossible load must be refused: {body}");++ assert!(seen.contains(r#""status":"loading""#), "{seen:?}");+ assert!(seen.contains(r#""status":"unloaded""#), "{seen:?}");+ assert!(seen.contains(r#""exit_code":1"#), "{seen:?}");+ assert!(+ seen.find("loading").unwrap() < seen.find("unloaded").unwrap(),+ "transitions must arrive in order: {seen:?}"+ );+}++#[tokio::test(flavor = "multi_thread")]+async fn models_lists_registered_models_and_requires_the_key() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let client = reqwest::Client::new();++ let un = client+ .get(format!("{base}/v1/models"))+ .send()+ .await+ .unwrap();+ assert_eq!(un.status(), 401, "an unauthenticated read must be refused");++ let ok = client+ .get(format!("{base}/v1/models"))+ .bearer_auth(KEY)+ .send()+ .await+ .unwrap();+ assert_eq!(ok.status(), 200);+ let v: serde_json::Value = ok.json().await.unwrap();+ assert_eq!(v["data"][0]["id"], MODEL_ID);+ // Registered but not resident: it must still be listed, or an eviction+ // would make the model vanish from the UI -- and proxy.rs routes off this+ // list, so an unlisted model becomes unreachable.+ assert_eq!(v["data"][0]["status"]["value"], "unloaded");+ assert_eq!(v["data"][0]["status"]["failed"], false);+}++#[tokio::test(flavor = "multi_thread")]+async fn a_chat_completion_returns_content_and_usage() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let (status, body) = post(+ &base,+ "/v1/chat/completions",+ &format!(+ r#"{{"model":"{MODEL_ID}","messages":[{{"role":"user","content":"Say only: OK"}}],+ "max_tokens":200,"temperature":0}}"#+ ),+ Some(KEY),+ )+ .await;+ assert_eq!(status, 200, "body: {body}");+ let v: serde_json::Value = serde_json::from_str(&body).unwrap();+ assert!(v["choices"][0]["message"]["role"].is_string(), "body: {body}");+ assert!(+ v["usage"]["completion_tokens"].as_u64().unwrap_or(0) > 0,+ "no tokens: {body}"+ );+}++#[tokio::test(flavor = "multi_thread")]+async fn a_streaming_completion_is_sse_and_terminates_with_done() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let res = reqwest::Client::new()+ .post(format!("{base}/v1/chat/completions"))+ .bearer_auth(KEY)+ .header("content-type", "application/json")+ .body(format!(+ r#"{{"model":"{MODEL_ID}","messages":[{{"role":"user","content":"Count to three."}}],+ "max_tokens":48,"temperature":0,"stream":true,"timings_per_token":true}}"#+ ))+ .send()+ .await+ .unwrap();+ assert_eq!(res.status(), 200);+ assert_eq!(+ res.headers()+ .get("content-type")+ .and_then(|v| v.to_str().ok()),+ Some("text/event-stream")+ );+ let text = res.text().await.unwrap();+ let frames: Vec<&str> = text+ .lines()+ .filter_map(|l| l.strip_prefix("data: "))+ .collect();+ assert!(frames.len() > 2, "expected several frames, got {}", frames.len());+ assert_eq!(frames.last().map(|f| f.trim()), Some("[DONE]"));+ // timings_per_token is what the extension uses for live token counts.+ assert!(+ frames.iter().any(|f| f.contains("\"timings\"")),+ "timings_per_token produced no timings frame"+ );+}++#[tokio::test(flavor = "multi_thread")]+async fn an_unknown_model_is_a_client_error_not_a_hang() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let (status, body) = post(+ &base,+ "/v1/chat/completions",+ r#"{"model":"not-registered","messages":[{"role":"user","content":"hi"}]}"#,+ Some(KEY),+ )+ .await;+ assert_eq!(status, 400, "body: {body}");+}++#[tokio::test(flavor = "multi_thread")]+async fn an_unknown_path_is_404() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let (status, _) = post(&base, "/v1/nonsense", "{}", Some(KEY)).await;+ assert_eq!(status, 404);+}++#[tokio::test(flavor = "multi_thread")]+async fn tokenize_works_without_a_model_field_by_using_the_resident_engine() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ // Load something first: with nothing resident this is a 503 by design.+ let (s, b) = post(+ &base,+ "/v1/chat/completions",+ &format!(+ r#"{{"model":"{MODEL_ID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":8}}"#+ ),+ Some(KEY),+ )+ .await;+ assert_eq!(s, 200, "warmup failed: {b}");++ let (status, body) = post(&base, "/tokenize", r#"{"content":"hello"}"#, Some(KEY)).await;+ assert_eq!(status, 200, "body: {body}");+ let v: serde_json::Value = serde_json::from_str(&body).unwrap();+ assert!(v["tokens"].is_array(), "body: {body}");+}++#[tokio::test(flavor = "multi_thread")]+async fn explicit_load_then_unload_moves_the_reported_status() {+ let Some(model) = model_path() else { return };+ let base = serve(&model, 1).await;+ let client = reqwest::Client::new();++ let status_of = |client: reqwest::Client, base: String| async move {+ let v: serde_json::Value = client+ .get(format!("{base}/v1/models"))+ .bearer_auth(KEY)+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ v["data"][0]["status"]["value"].as_str().unwrap().to_string()+ };++ assert_eq!(status_of(client.clone(), base.clone()).await, "unloaded");++ let (s, b) = post(+ &base,+ "/models/load",+ &format!(r#"{{"model":"{MODEL_ID}"}}"#),+ Some(KEY),+ )+ .await;+ assert_eq!(s, 200, "load failed: {b}");+ assert_eq!(status_of(client.clone(), base.clone()).await, "loaded");++ // Loading twice must be idempotent, not an error: the plugin's post_load+ // treats an "already" body as success.+ let (s, b) = post(+ &base,+ "/models/load",+ &format!(r#"{{"model":"{MODEL_ID}"}}"#),+ Some(KEY),+ )+ .await;+ assert_eq!(s, 200, "second load: {b}");+ assert!(b.contains("already"), "expected an 'already' body, got {b}");++ let (s, b) = post(+ &base,+ "/models/unload",+ &format!(r#"{{"model":"{MODEL_ID}"}}"#),+ Some(KEY),+ )+ .await;+ assert_eq!(s, 200, "unload failed: {b}");+ assert_eq!(status_of(client, base).await, "unloaded");+}++#[tokio::test(flavor = "multi_thread")]+async fn a_failed_load_is_reported_as_failed_not_merely_unloaded() {+ let Some(_) = model_path() else { return };+ // A registered model whose file does not exist: the poll arm must see+ // failed=true, or commands::evaluate_load_poll waits out its full timeout.+ let mut reg = Registry::new(1);+ reg.register(+ "broken",+ LoadSpec::Args(+ ["llama-server", "-m", "/definitely/not/a/model.gguf", "-fit", "off"]+ .iter()+ .map(|s| s.to_string())+ .collect(),+ ),+ );+ let (server, listener) = EngineServer::bind(Arc::new(Mutex::new(reg)), 0, KEY.into())+ .await+ .unwrap();+ let base = format!("http://127.0.0.1:{}", server.port);+ tokio::spawn(server.serve(listener));++ let (status, body) = post(&base, "/models/load", r#"{"model":"broken"}"#, Some(KEY)).await;+ assert!(+ (400..600).contains(&status),+ "a bad model path must fail the load, got {status}: {body}"+ );++ let v: serde_json::Value = reqwest::Client::new()+ .get(format!("{base}/v1/models"))+ .bearer_auth(KEY)+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(v["data"][0]["status"]["value"], "unloaded");+ assert_eq!(+ v["data"][0]["status"]["failed"], true,+ "failed flag missing, so the caller's poll loop would hang: {v}"+ );+}++/// Reload needs no model file: it only rewrites the registry's bookkeeping, so+/// unlike the rest of this file it runs without JAN_TEST_GGUF.+async fn serve_preset(ini_path: &str) -> String {+ let ini = std::fs::read_to_string(ini_path).expect("preset should be readable");+ let mut reg = Registry::new(1);+ for (section, spec) in tauri_plugin_llamacpp::engine::preset::specs(ini_path, &ini) {+ reg.register(section, spec);+ }+ let (server, listener) = EngineServer::bind(Arc::new(Mutex::new(reg)), 0, KEY.into())+ .await+ .expect("loopback bind");+ let base = format!("http://127.0.0.1:{}", server.port);+ tokio::spawn(server.serve(listener));+ base+}++fn write_preset(dir: &std::path::Path, body: &str) -> String {+ let path = dir.join("router.preset.ini");+ std::fs::write(&path, body).expect("preset should be writable");+ path.to_string_lossy().into_owned()+}++const PRESET_ONE: &str = "[*]\nparallel = 1\n\n[alpha]\nmodel = /a.gguf\n";+const PRESET_TWO: &str = "[*]\nparallel = 1\n\n[alpha]\nmodel = /a.gguf\n\n[beta]\nmodel = /b.gguf\n";++#[tokio::test(flavor = "multi_thread")]+async fn reload_applies_a_regenerated_preset_and_reports_the_diff() {+ let dir = std::env::temp_dir().join(format!("jan-reload-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let preset = write_preset(&dir, PRESET_ONE);+ let base = serve_preset(&preset).await;++ write_preset(&dir, PRESET_TWO);+ let (status, body) = post(+ &base,+ "/models/reload",+ &format!(r#"{{"preset_path":"{preset}","models_max":3}}"#),+ Some(KEY),+ )+ .await;+ assert_eq!(status, 200, "{body}");+ let v: serde_json::Value = serde_json::from_str(&body).unwrap();+ assert_eq!(v["added"], serde_json::json!(["beta"]));+ assert_eq!(v["changed"], serde_json::json!([]));+ assert_eq!(v["removed"], serde_json::json!([]));+ assert_eq!(v["models_max"], 3, "the router could not be resized at all");++ // The new model must be listed, not merely accepted.+ let listed = reqwest::Client::new()+ .get(format!("{base}/v1/models"))+ .bearer_auth(KEY)+ .send()+ .await+ .unwrap()+ .text()+ .await+ .unwrap();+ assert!(listed.contains("beta"), "{listed}");++ // Reverting the preset must remove it again.+ write_preset(&dir, PRESET_ONE);+ let (status, body) = post(+ &base,+ "/models/reload",+ &format!(r#"{{"preset_path":"{preset}"}}"#),+ Some(KEY),+ )+ .await;+ assert_eq!(status, 200, "{body}");+ let v: serde_json::Value = serde_json::from_str(&body).unwrap();+ assert_eq!(v["removed"], serde_json::json!(["beta"]));+ assert_eq!(v["models_max"], 3, "omitting models_max must keep it");++ let _ = std::fs::remove_dir_all(&dir);+}++#[tokio::test(flavor = "multi_thread")]+async fn reload_rejects_a_missing_preset_rather_than_emptying_the_registry() {+ let dir = std::env::temp_dir().join(format!("jan-reload-miss-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let preset = write_preset(&dir, PRESET_ONE);+ let base = serve_preset(&preset).await;++ let (status, _) = post(+ &base,+ "/models/reload",+ r#"{"preset_path":"/definitely/not/here.ini"}"#,+ Some(KEY),+ )+ .await;+ assert_eq!(status, 400);++ // Registering nothing would have silently unregistered every model.+ let listed = reqwest::Client::new()+ .get(format!("{base}/v1/models"))+ .bearer_auth(KEY)+ .send()+ .await+ .unwrap()+ .text()+ .await+ .unwrap();+ assert!(listed.contains("alpha"), "{listed}");++ let _ = std::fs::remove_dir_all(&dir);+}++#[tokio::test(flavor = "multi_thread")]+async fn reload_requires_the_api_key() {+ let dir = std::env::temp_dir().join(format!("jan-reload-auth-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let preset = write_preset(&dir, PRESET_ONE);+ let base = serve_preset(&preset).await;++ let (status, _) = post(+ &base,+ "/models/reload",+ &format!(r#"{{"preset_path":"{preset}"}}"#),+ None,+ )+ .await;+ assert_eq!(status, 401, "reload mutates state and must be authenticated");++ let _ = std::fs::remove_dir_all(&dir);+}++/// The point of the whole feature: a thread's cache outlives the turn that+/// built it, and a *second* thread taking the slot does not lose it.+#[tokio::test(flavor = "multi_thread")]+async fn a_thread_switch_parks_the_first_threads_cache_and_restores_it() {+ let Some(model) = model_path() else { return };+ let (base, dir, _server) = serve_with_state(&model, 4096).await;++ // Thread A runs twice. Nothing is saved: no other thread has claimed the+ // slot, so there is nothing to evict -- and the second turn must not park+ // or restore either, since the slot already holds A's own newer cache.+ for _ in 0..2 {+ let (status, body) =+ post(&base, "/v1/chat/completions", &chat_body("thread-a"), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ assert!(+ saved_states(&dir).is_empty(),+ "a thread taking its own slot again is not a handover"+ );+ }++ // Thread B takes slot 0, which is what forces A to disk.+ let (status, body) = post(&base, "/v1/chat/completions", &chat_body("thread-b"), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ let key_a = state_key(MODEL_ID, "thread-a");+ assert_eq!(+ saved_states(&dir),+ vec![format!("{key_a}.bin")],+ "thread A's cache should have been parked when B took the slot"+ );+ assert!(+ dir.join(format!("{key_a}.json")).is_file(),+ "a state file without its sidecar is refused later, so both must land"+ );++ // Back to A: its state is restored rather than re-read from the prompt.+ let (status, body) = post(&base, "/v1/chat/completions", &chat_body("thread-a"), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ let v: serde_json::Value = serde_json::from_str(&body).unwrap();+ let cached = v["usage"]["prompt_tokens_details"]["cached_tokens"]+ .as_u64()+ .or_else(|| v["timings"]["n_prompt_tokens_cache"].as_u64());+ if let Some(cached) = cached {+ assert!(cached > 0, "the restored prefix should be reported as cached: {body}");+ }+ // Both files are on disk now: B was evicted in turn, and a restore does not+ // consume A's file. Keeping it is deliberate -- it is still a valid prefix+ // of that conversation, so it is the right thing to fall back to if the+ // next eviction never happens (a crash, a kill).+ let mut expected = vec![+ format!("{key_a}.bin"),+ format!("{}.bin", state_key(MODEL_ID, "thread-b")),+ ];+ expected.sort();+ assert_eq!(saved_states(&dir), expected);+}++/// The condition the request names: a state saved by another model is refused+/// rather than restored as plausible-looking nonsense.+#[tokio::test(flavor = "multi_thread")]+async fn a_state_saved_by_a_different_model_is_refused_and_dropped() {+ let Some(model) = model_path() else { return };+ let (base, dir, _server) = serve_with_state(&model, 4096).await;++ let key = state_key(MODEL_ID, "thread-a");+ // A state file whose sidecar claims a different model, as a model swap+ // between sessions would leave behind.+ std::fs::write(dir.join(format!("{key}.bin")), vec![0u8; 1024]).unwrap();+ std::fs::write(+ dir.join(format!("{key}.json")),+ serde_json::json!({+ "model": "some-other-model",+ "spec": "deadbeef",+ "llama_build": "0",+ "llama_commit": "0",+ "model_bytes": 0u64,+ "model_mtime": 0u64,+ "n_tokens": 900u64,+ "saved_at": 1u64,+ })+ .to_string(),+ )+ .unwrap();++ let (status, body) = post(&base, "/v1/chat/completions", &chat_body("thread-a"), Some(KEY)).await;+ assert_eq!(status, 200, "a refused restore must not fail the turn: {body}");+ assert!(+ !dir.join(format!("{key}.bin")).exists(),+ "a state that can never match again must be dropped, not re-checked every turn"+ );+}++/// A request with no thread_id behaves exactly as before: nothing is saved and+/// llama.cpp never sees a field it does not know.+#[tokio::test(flavor = "multi_thread")]+async fn a_request_without_a_thread_is_untouched_by_the_feature() {+ let Some(model) = model_path() else { return };+ let (base, dir, _server) = serve_with_state(&model, 4096).await;++ let body = serde_json::json!({+ "model": MODEL_ID,+ "id_slot": 0,+ "max_tokens": 1,+ "messages": [{ "role": "user", "content": "hi" }],+ })+ .to_string();+ let (status, out) = post(&base, "/v1/chat/completions", &body, Some(KEY)).await;+ assert_eq!(status, 200, "{out}");+ assert!(saved_states(&dir).is_empty());+}++#[tokio::test(flavor = "multi_thread")]+async fn erasing_a_threads_state_drops_only_that_thread() {+ let Some(model) = model_path() else { return };+ let (base, dir, _server) = serve_with_state(&model, 4096).await;++ for thread in ["thread-a", "thread-b", "thread-c"] {+ let (status, body) =+ post(&base, "/v1/chat/completions", &chat_body(thread), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ }+ // a and b were both evicted in turn; c is still resident.+ assert_eq!(saved_states(&dir).len(), 2, "{:?}", saved_states(&dir));++ let (status, body) = post(+ &base,+ "/slots/state/erase",+ &serde_json::json!({ "model": MODEL_ID, "thread": "thread-a" }).to_string(),+ Some(KEY),+ )+ .await;+ assert_eq!(status, 200, "{body}");+ assert_eq!(+ saved_states(&dir),+ vec![format!("{}.bin", state_key(MODEL_ID, "thread-b"))]+ );++ let (status, body) = post(+ &base,+ "/slots/state/erase",+ &serde_json::json!({ "model": MODEL_ID }).to_string(),+ Some(KEY),+ )+ .await;+ assert_eq!(status, 200, "{body}");+ assert!(saved_states(&dir).is_empty(), "erasing a model clears all of it");+}++/// Closing Jan is the common way a thread stops being current, so the resident+/// slot has to be written at shutdown or the feature would only work across a+/// thread switch.+#[tokio::test(flavor = "multi_thread")]+async fn shutdown_parks_the_resident_thread() {+ let Some(model) = model_path() else { return };+ let (base, dir, server) = serve_with_state(&model, 4096).await;++ let (status, body) = post(&base, "/v1/chat/completions", &chat_body("thread-a"), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ assert!(saved_states(&dir).is_empty(), "nothing evicted it yet");++ server.save_resident_slots().await;+ assert_eq!(+ saved_states(&dir),+ vec![format!("{}.bin", state_key(MODEL_ID, "thread-a"))]+ );+}++/// The budget is a real ceiling, not advisory: a saved state directory that+/// grows without bound is a disk leak, not a cache.+#[tokio::test(flavor = "multi_thread")]+async fn the_disk_budget_evicts_the_oldest_saved_state() {+ let Some(model) = model_path() else { return };+ // 1 MiB, which a 2048-token slot state comfortably exceeds.+ let (base, dir, _server) = serve_with_state(&model, 1).await;++ for thread in ["thread-a", "thread-b", "thread-c"] {+ let (status, body) =+ post(&base, "/v1/chat/completions", &chat_body(thread), Some(KEY)).await;+ assert_eq!(status, 200, "{body}");+ }+ let total: u64 = std::fs::read_dir(&dir)+ .unwrap()+ .flatten()+ .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("bin"))+ .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))+ .sum();+ assert!(+ total <= 1024 * 1024,+ "the directory should have been pruned to the budget, got {total} bytes"+ );+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_supervision.rs b/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_supervision.rsnew file mode 100644index 000000000..9c8dfcabf--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-llamacpp/tests/worker_supervision.rs@@ -0,0 +1,219 @@+//! The supervisor driving the real `jan-llama-worker` binary: spawn, read the+//! handshake, serve over HTTP, stop. This is the crash-boundary path that+//! replaces spawning a downloaded `llama-server` in router mode.+//!+//! Opt-in on JAN_TEST_GGUF.+#![cfg(feature = "engine")]++use std::collections::HashMap;+use std::io::Write;+use std::path::PathBuf;++use tauri_plugin_llamacpp::engine::worker::{self, WorkerError};++const MODEL_ID: &str = "smoke-model";++fn model_path() -> Option<String> {+ std::env::var("JAN_TEST_GGUF").ok().filter(|p| !p.is_empty())+}++/// Cargo builds the bin for us and hands over its path.+fn worker_exe() -> PathBuf {+ PathBuf::from(env!("CARGO_BIN_EXE_jan-llama-worker"))+}++/// A preset in exactly the shape Jan's preset.ts already emits.+fn write_preset(dir: &tempfile::TempDir, model: &str) -> PathBuf {+ let path = dir.path().join("router.preset.ini");+ let mut f = std::fs::File::create(&path).unwrap();+ writeln!(+ f,+ "[*]\nfit = off\nparallel = 1\nthreads = 2\nctx-size = 2048\nn-gpu-layers = 0\n\n[{MODEL_ID}]\nmodel = {model}\nload-on-startup = false"+ )+ .unwrap();+ path+}++#[tokio::test(flavor = "multi_thread")]+async fn spawns_the_worker_reads_its_handshake_and_serves() {+ let Some(model) = model_path() else { return };+ let dir = tempfile::tempdir().unwrap();+ let preset = write_preset(&dir, &model);++ let handle = worker::spawn(+ &worker_exe(),+ &preset,+ 0, // let the OS pick, then learn it from the handshake+ "supervised-key",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect("the worker should come up");++ assert!(handle.port > 0, "handshake must report a real port");+ assert!(handle.pid > 0, "handshake must report a pid");+ assert_eq!(+ handle.models,+ vec![MODEL_ID],+ "the worker should have registered the preset's sections"+ );++ // The supervisor knows the port without scraping a log, and the model is+ // reachable over the same contract proxy.rs uses.+ let base = format!("http://127.0.0.1:{}", handle.port);+ let res = reqwest::Client::new()+ .post(format!("{base}/v1/chat/completions"))+ .bearer_auth("supervised-key")+ .header("content-type", "application/json")+ .body(format!(+ r#"{{"model":"{MODEL_ID}","messages":[{{"role":"user","content":"Say only: SUPERVISED"}}],"max_tokens":200,"temperature":0}}"#+ ))+ .send()+ .await+ .expect("the supervised worker should answer");+ assert_eq!(res.status(), 200);+ let v: serde_json::Value = res.json().await.unwrap();+ assert!(+ v["choices"][0]["message"]["role"].is_string(),+ "no assistant message: {v}"+ );++ // The key came from the environment, so it must not be visible in argv.+ #[cfg(target_os = "linux")]+ {+ let cmdline = std::fs::read(format!("/proc/{}/cmdline", handle.pid)).unwrap_or_default();+ let cmdline = String::from_utf8_lossy(&cmdline);+ assert!(+ !cmdline.contains("supervised-key"),+ "the bearer token leaked into argv: {cmdline}"+ );+ }++ handle.stop().await;++ // After stop the port must be dead, not merely idle.+ let after = reqwest::Client::new()+ .get(format!("{base}/v1/models"))+ .bearer_auth("supervised-key")+ .timeout(std::time::Duration::from_secs(2))+ .send()+ .await;+ assert!(after.is_err(), "the worker should be gone after stop()");+}++#[tokio::test(flavor = "multi_thread")]+async fn a_preset_that_does_not_exist_still_starts_and_serves_no_models() {+ // The worker only reads the preset for section names, so a missing file is+ // a startup error rather than a silent empty registry.+ let err = worker::spawn(+ &worker_exe(),+ &PathBuf::from("/definitely/not/a/preset.ini"),+ 0,+ "k",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect_err("a missing preset must be reported");+ assert!(matches!(err, WorkerError::Handshake(_)), "got {err:?}");+}++/// The app's exit path calls `try_graceful_stop_engine`. Before that existed the+/// exit path stopped the *router*, so a migrated app left its worker running --+/// holding the model and its VRAM after the window closed.+#[tokio::test(flavor = "multi_thread")]+async fn a_stopped_worker_is_actually_gone() {+ let Some(model) = model_path() else { return };+ let dir = tempfile::tempdir().unwrap();+ let preset = write_preset(&dir, &model);++ let handle = worker::spawn(+ &worker_exe(),+ &preset,+ 0,+ "stop-key",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect("the worker should come up");++ let pid = handle.pid;+ assert!(pid_alive(pid), "worker should be running before stop");+ handle.stop().await;++ // The kernel reaps asynchronously, so allow a moment before asserting.+ for _ in 0..50 {+ if !pid_alive(pid) {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ panic!("worker pid {pid} still alive after stop()");+}++/// Running, i.e. not exited. A zombie counts as *not* alive: a test that drops+/// stdin without reaping the child would otherwise see `/proc/<pid>` forever and+/// conclude the worker ignored the signal.+#[cfg(unix)]+fn pid_alive(pid: u32) -> bool {+ let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {+ return false;+ };+ // `state` is the field after the parenthesised comm, which may itself+ // contain spaces -- so split on the last ')' rather than by whitespace.+ let Some((_, rest)) = stat.rsplit_once(')') else {+ return false;+ };+ !matches!(rest.split_whitespace().next(), Some("Z") | None)+}++#[cfg(not(unix))]+fn pid_alive(_pid: u32) -> bool {+ // No cheap /proc equivalent; the assertion is Unix-only.+ false+}++/// Shutdown is signalled by closing the worker's stdin, so it must behave the+/// same everywhere -- the router had to be force-killed on Windows because a+/// third-party binary could only be signalled.+#[tokio::test(flavor = "multi_thread")]+async fn closing_stdin_stops_the_worker_without_a_signal() {+ // Needs no model: the shutdown path is about the process, not inference.+ let dir = tempfile::tempdir().unwrap();+ let preset = dir.path().join("empty.preset.ini");+ std::fs::write(&preset, "[*]\nparallel = 1\n").unwrap();++ let mut handle = worker::spawn(+ &worker_exe(),+ &preset,+ 0,+ "eof-key",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect("the worker should come up");++ let pid = handle.pid;+ // Exactly what stop() does first, in isolation: no signal is sent.+ let stdin = handle.take_stdin().expect("stdin should be piped");+ drop(stdin);++ for _ in 0..100 {+ if !pid_alive(pid) {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ panic!("worker pid {pid} ignored stdin EOF");+}diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rsindex 156690549..11cea2b45 100644--- a/src-tauri/src/bin/jan-cli.rs+++ b/src-tauri/src/bin/jan-cli.rs@@ -14,7 +14,7 @@ use indicatif::{ProgressBar, ProgressStyle};// The lib target is named "app_lib" (see [lib] section in Cargo.toml).use app_lib::core::cli::{cli_delete_thread, cli_get_data_folder, cli_get_thread,- cli_list_messages, cli_list_threads, discover_llamacpp_binary,+ cli_list_messages, cli_list_threads,download_hf_model, fetch_hf_gguf_files, init_llamacpp_state,list_models, looks_like_hf_repo, resolve_model_engine, HfFileInfo,};@@ -23,9 +23,9 @@ use app_lib::core::cli::{use app_lib::core::cli::{discover_mlx_binary, init_mlx_state, load_mlx_model_impl, resolve_model_by_id, MlxConfig,};-use tauri_plugin_llamacpp::router as llamacpp_router;+use tauri_plugin_llamacpp::engine::worker as llamacpp_worker;use tauri_plugin_llamacpp::state::LlamacppState;-use std::path::PathBuf;+use std::path::{Path, PathBuf};// ── Top-level CLI ──────────────────────────────────────────────────────────@@ -934,34 +934,29 @@ async fn handle_serve(args: ServeArgs) {}} else {// LlamaCPP path- let bin_path = match bin {- Some(b) => b,- None => match discover_llamacpp_binary() {- Some(p) => p.to_string_lossy().into_owned(),- None => {- finish_progress(pb, "✗ llama-server binary not found");- eprintln!("Install a backend from Jan's settings or pass --bin <path>.");- std::process::exit(1);- }- },+ let worker_exe = match bin.map(std::path::PathBuf::from).or_else(llamacpp_worker::sidecar_path) {+ Some(p) => p,+ None => {+ finish_progress(pb, "✗ jan-llama-worker not found");+ eprintln!("Reinstall Jan from https://jan.ai or pass --bin <path to jan-llama-worker>.");+ std::process::exit(1);+ }};- let _ = (n_gpu_layers, ctx_size, fit, threads, resolved_model_path, resolved_mmproj);+ let _ = (n_gpu_layers, ctx_size, fit, threads, resolved_model_path, resolved_mmproj, embedding, timeout);let llama_state = Arc::new(init_llamacpp_state());let mut envs: HashMap<String, String> = HashMap::new();if !api_key.is_empty() {envs.insert("LLAMA_API_KEY".to_string(), api_key.clone());}- match ensure_router_and_load(+ match ensure_worker_and_load(&llama_state,- &bin_path,+ &worker_exe,&model_id,port,api_key,- embedding,envs,- timeout,).await{@@ -982,86 +977,74 @@ async fn handle_serve(args: ServeArgs) {}}-struct RouterServeInfo {+struct WorkerServeInfo {pid: i32,port: u16,#[allow(dead_code)]api_key: String,}-#[allow(clippy::too_many_arguments)]-async fn ensure_router_and_load(+/// Spawns `jan-llama-worker` and loads one model into it.+///+/// The worker owns the engine in its own process and is discovered as a+/// sidecar, so there is no downloaded `llama-server` to locate. `models_max`+/// and the KV-cache budget are 0: a `jan cli serve` run holds one model and+/// has no thread store to persist slots for.+async fn ensure_worker_and_load(llama_state: &std::sync::Arc<LlamacppState>,- bin_path: &str,+ worker_exe: &Path,model_id: &str,port: u16,api_key: String,- is_embedding: bool,envs: HashMap<String, String>,- timeout: u64,-) -> Result<RouterServeInfo, String> {- if is_embedding {- return Err(- "--embedding on the llamacpp engine requires router preset support; \- use the desktop UI to load embedding models for now."- .to_string(),- );- }-+) -> Result<WorkerServeInfo, String> {let preset_path = cli_get_data_folder().join("llamacpp").join("router.preset.ini");if !preset_path.exists() {return Err(format!(- "Router preset not found at {}; run the desktop app once to generate it, \- or implement a Rust preset generator.",+ "Engine preset not found at {}; run the desktop app once to generate it.",preset_path.display()));}- let already_running = { llama_state.router.lock().await.is_some() };+ let already_running = { llama_state.engine.lock().await.is_some() };if !already_running {- let router_api_key = if api_key.is_empty() {+ let worker_key = if api_key.is_empty() {uuid::Uuid::new_v4().to_string()} else {api_key.clone()};- let mut router_envs = envs.clone();- router_envs- .entry("LLAMA_ARG_TIMEOUT".to_string())- .or_insert_with(|| timeout.to_string());-- let log_dir = cli_get_data_folder().join("logs");-- let handle = llamacpp_router::start_router(- std::path::PathBuf::from(bin_path),- preset_path,- log_dir,+ let handle = llamacpp_worker::spawn(+ worker_exe,+ &preset_path,port,- router_api_key,+ &worker_key,+ 0,0,- Vec::new(),- router_envs,+ envs,+ // No window to raise a dialog in: a fault lands in the log the+ // user is already reading on the terminal.None,).await- .map_err(|e| format!("{e:?}"))?;- let mut guard = llama_state.router.lock().await;+ .map_err(|e| e.to_string())?;+ let mut guard = llama_state.engine.lock().await;*guard = Some(handle);}- let (router_port, router_key, router_pid) = {- let guard = llama_state.router.lock().await;+ let (worker_port, worker_key, worker_pid) = {+ let guard = llama_state.engine.lock().await;let h = guard.as_ref()- .ok_or_else(|| "Router unexpectedly missing after start".to_string())?;+ .ok_or_else(|| "Engine worker unexpectedly missing after start".to_string())?;(h.port, h.api_key.clone(), h.pid)};- let url = format!("http://127.0.0.1:{router_port}/models/load");+ let url = format!("http://127.0.0.1:{worker_port}/models/load");let resp = reqwest::Client::new().post(&url)- .header("Authorization", format!("Bearer {router_key}"))+ .header("Authorization", format!("Bearer {worker_key}")).json(&serde_json::json!({ "model": model_id })).send().await@@ -1069,13 +1052,13 @@ async fn ensure_router_and_load(let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- return Err(format!("Router /models/load returned {status}: {body}"));+ return Err(format!("Engine /models/load returned {status}: {body}"));}- Ok(RouterServeInfo {- pid: router_pid as i32,- port: router_port,- api_key: router_key,+ Ok(WorkerServeInfo {+ pid: worker_pid as i32,+ port: worker_port,+ api_key: worker_key,})}@@ -1375,11 +1358,11 @@ async fn start_model_server((info.pid, info.port as u16)}} else {- let bin_path = match bin.or_else(|| discover_llamacpp_binary().map(|p| p.to_string_lossy().into_owned())) {+ let worker_exe = match bin.map(std::path::PathBuf::from).or_else(llamacpp_worker::sidecar_path) {Some(p) => p,None => {- finish_progress(pb, "✗ llama-server binary not found");- eprintln!("Install a backend from Jan's settings or pass --bin <path>.");+ finish_progress(pb, "✗ jan-llama-worker not found");+ eprintln!("Reinstall Jan from https://jan.ai or pass --bin <path to jan-llama-worker>.");std::process::exit(1);}};@@ -1387,15 +1370,13 @@ async fn start_model_server(let llama_state = Arc::new(init_llamacpp_state());let mut envs: HashMap<String, String> = HashMap::new();if !api_key.is_empty() { envs.insert("LLAMA_API_KEY".to_string(), api_key.clone()); }- let info = match ensure_router_and_load(+ let info = match ensure_worker_and_load(&llama_state,- &bin_path,+ &worker_exe,model_id,port,api_key,- false,envs,- 120,).await {Ok(info) => info,Err(e) => {diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex d9c750112..941a7e8d5 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -243,63 +243,6 @@ pub fn resolve_model_by_id(// ── Binary auto-discovery ──────────────────────────────────────────────────-/// Find the llama-server binary inside the Jan data folder.-///-/// Walks `<data_folder>/llamacpp/backends/<version>/<backend>/` and checks-/// two locations per backend (same logic as the llamacpp-extension):-/// 1. `<backend_dir>/build/bin/llama-server[.exe]`-/// 2. `<backend_dir>/llama-server[.exe]`-///-/// Returns the first binary found, or `None` if no installed backend is found.-pub fn discover_llamacpp_binary() -> Option<PathBuf> {- use std::fs;-- let data_folder = resolve_jan_data_folder();- let backends_dir = data_folder.join("llamacpp").join("backends");-- if !backends_dir.exists() {- return None;- }-- let exe = if cfg!(windows) { "llama-server.exe" } else { "llama-server" };-- // Collect version directories, sorted descending so we prefer the latest.- let mut version_entries: Vec<_> = fs::read_dir(&backends_dir)- .ok()?- .filter_map(|e| e.ok())- .filter(|e| e.path().is_dir())- .collect();- version_entries.sort_by_key(|b| std::cmp::Reverse(b.file_name()));-- for version_entry in version_entries {- let version_dir = version_entry.path();- let mut backend_entries: Vec<_> = fs::read_dir(&version_dir)- .ok()?- .filter_map(|e| e.ok())- .filter(|e| e.path().is_dir())- .collect();- backend_entries.sort_by_key(|a| a.file_name());-- for backend_entry in backend_entries {- let backend_dir = backend_entry.path();-- // Primary location: <backend>/build/bin/llama-server- let primary = backend_dir.join("build").join("bin").join(exe);- if primary.exists() {- return Some(primary);- }-- // Fallback: <backend>/llama-server- let fallback = backend_dir.join(exe);- if fallback.exists() {- return Some(fallback);- }- }- }-- None-}-/// Find the mlx-server binary.////// Checks standard locations in order:diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex 81295fc08..a2b83ccfb 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -829,11 +829,13 @@ fn mcp_call_result_to_string(result: &CallToolResult) -> String {}}-async fn router_upstream(+/// The loopback endpoint local-model requests are forwarded to: the engine+/// worker's `/v1` surface, or None when no engine is running.+async fn engine_upstream(llama_state: &LlamacppState,destination_path: &str,) -> Option<(String, String)> {- let guard = llama_state.router.lock().await;+ let guard = llama_state.engine.lock().await;guard.as_ref().map(|h| {(format!("http://127.0.0.1:{}/v1{}", h.port, destination_path),@@ -842,16 +844,10 @@ async fn router_upstream(})}-async fn router_list_models(llama_state: &LlamacppState, client: &Client) -> Vec<String> {- let (url, key) = {- let guard = llama_state.router.lock().await;- match guard.as_ref() {- Some(h) => (- format!("http://127.0.0.1:{}/v1/models", h.port),- h.api_key.clone(),- ),- None => return Vec::new(),- }+async fn engine_list_models(llama_state: &LlamacppState, client: &Client) -> Vec<String> {+ let (url, key) = match engine_upstream(llama_state, "/models").await {+ Some(v) => v,+ None => return Vec::new(),};let resp = match client.get(&url)@@ -861,7 +857,7 @@ async fn router_list_models(llama_state: &LlamacppState, client: &Client) -> Vec{Ok(r) => r,Err(e) => {- log::warn!("Failed to query router /v1/models: {e}");+ log::warn!("Failed to query the engine's /v1/models: {e}");return Vec::new();}};@@ -883,7 +879,7 @@ async fn router_list_models(llama_state: &LlamacppState, client: &Client) -> Vec}async fn router_first_model(llama_state: &LlamacppState, client: &Client) -> Option<String> {- router_list_models(llama_state, client).await.into_iter().next()+ engine_list_models(llama_state, client).await.into_iter().next()}async fn resolve_upstream_for_model(@@ -932,7 +928,7 @@ async fn resolve_upstream_for_model(}drop(mlx_guard);- if let Some((url, key)) = router_upstream(&llama_state, destination_path).await {+ if let Some((url, key)) = engine_upstream(&llama_state, destination_path).await {return Ok((url, vec![key]));}@@ -1718,7 +1714,7 @@ async fn proxy_request(target_base_url =Some(format!("http://127.0.0.1:{}/v1/messages", target_port));} else if let Some((url, key)) =- router_upstream(&llama_state, "/messages").await+ engine_upstream(&llama_state, "/messages").await{session_api_keys = vec![key];target_base_url = Some(url);@@ -2261,7 +2257,7 @@ async fn proxy_request(};let router_up =- router_upstream(&llama_state, &destination_path).await;+ engine_upstream(&llama_state, &destination_path).await;if mlx_session_info.is_none() && router_up.is_none() {log::warn!(@@ -2342,7 +2338,7 @@ async fn proxy_request((hyper::Method::GET, "/models") => {log::debug!("Handling GET /v1/models request");- let local_models: Vec<_> = router_list_models(&llama_state, &client)+ let local_models: Vec<_> = engine_list_models(&llama_state, &client).await.into_iter().map(|id| {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f841bb99e..bff10333a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -143,10 +143,19 @@ async fn confirm_exit<R: tauri::Runtime>(_app_handle: tauri::AppHandle<R>) {}#[cfg(not(feature = "cli"))]-fn is_llamacpp_router_running<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool {+/// Whether a llama.cpp engine worker is up, so the exit path knows whether it+/// owes the user a graceful shutdown.+///+/// `try_lock` rather than a blocking lock: this runs on the event loop. A held+/// lock means a start or stop is in flight, which counts as running -- the+/// graceful path is the safe answer when the state cannot be read.+fn is_llamacpp_engine_running<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool {use tauri::Manager;app.try_state::<std::sync::Arc<tauri_plugin_llamacpp::LlamacppState>>()- .map(|s| s.router_pid.load(std::sync::atomic::Ordering::SeqCst) != 0)+ .map(|s| match s.engine.try_lock() {+ Ok(guard) => guard.is_some(),+ Err(_) => true,+ }).unwrap_or(false)}@@ -178,7 +187,7 @@ async fn handle_graceful_exit<R: tauri::Runtime>(if SHUTTING_DOWN.load(Ordering::SeqCst) {return;}- match tauri_plugin_llamacpp::try_graceful_stop_router(app_handle.clone(), 1).await {+ match tauri_plugin_llamacpp::try_graceful_stop_engine(app_handle.clone(), 1).await {Ok(None) => {if let Ok(mut g) = BUSY_MODELS.lock() {g.clear();@@ -204,7 +213,7 @@ async fn handle_graceful_exit<R: tauri::Runtime>(tokio::time::sleep(std::time::Duration::from_secs(2)).await;}Err(e) => {- log::warn!("{}: try_graceful_stop_router failed: {}", source, e);+ log::warn!("{}: try_graceful_stop_engine failed: {}", source, e);SHUTTING_DOWN.store(true, Ordering::SeqCst);app_handle.exit(exit_code);return;@@ -383,7 +392,7 @@ pub fn run() {}// Windows/Linux: hide to tray only while the Local API Server is// running; otherwise fall through to the normal quit-on-close.- // The llamacpp router is not a reason to keep the app resident+ // 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"))]@@ -404,7 +413,7 @@ pub fn run() {}}if let RunEvent::ExitRequested { api, code, .. } = &event {- if SHUTTING_DOWN.load(Ordering::SeqCst) || !is_llamacpp_router_running(app) {+ if SHUTTING_DOWN.load(Ordering::SeqCst) || !is_llamacpp_engine_running(app) {return;}api.prevent_exit();@@ -468,9 +477,9 @@ pub fn run() {}if let Err(e) = cleanup_llama_processes(app_handle.clone()).await {- log::warn!("Failed to shut down llama-server router: {}", e);+ log::warn!("Failed to shut down the llama.cpp engine: {}", e);} else {- log::info!("Llama-server router shut down successfully");+ log::info!("llama.cpp engine shut down successfully");}#[cfg(target_os = "macos")]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 996494f81..5cd3822b5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2,15 +2,9 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]fn main() {- // Fix PATH before anything that may spawn subprocesses, so the lddtree- // helper (and any other child) inherits directories added by fix_path_env.+ // Fix PATH before anything that may spawn subprocesses, so the engine+ // worker (and any other child) inherits directories added by fix_path_env.let _ = fix_path_env::fix();- // Exits early if invoked as the out-of-process lddtree helper.- tauri_plugin_llamacpp::deps_analyzer::run_deps_analyzer_if_requested();-- // Exits early if invoked as the out-of-process backend load probe.- tauri_plugin_llamacpp::load_probe::run_load_probe_if_requested();-app_lib::run();}diff --git a/src-tauri/tauri.bundle.windows.nsis.template b/src-tauri/tauri.bundle.windows.nsis.templateindex 309f633ae..828ed9ea0 100644--- a/src-tauri/tauri.bundle.windows.nsis.template+++ b/src-tauri/tauri.bundle.windows.nsis.template@@ -703,6 +703,16 @@ Section InstallFile /nonfatal /a /r "D:\a\jan\jan\src-tauri\resources\pre-install\"SetOutPath "$INSTDIR\resources\bin"File /a "/oname=jan-cli.exe" "D:\a\jan\jan\src-tauri\resources\bin\jan-cli.exe"+ ; The engine. This block is a hand-maintained snapshot of+ ; tauri.windows.conf.json's `bundle.resources`, which the NSIS bundler does+ ; not read once CI points it at this template, so anything added there has+ ; to be repeated here or it silently ships only in the MSI. Deliberately+ ; fatal rather than /nonfatal: an installer with no worker leaves local+ ; inference permanently unavailable, since there is no runtime backend+ ; download to fall back on, so a build that staged nothing must fail loudly+ ; here the way stage-engine.sh already does.+ File /a "/oname=jan-llama-worker.exe" "D:\a\jan\jan\src-tauri\resources\bin\jan-llama-worker.exe"+ File /a "D:\a\jan\jan\src-tauri\resources\bin\ggml*.dll"SetOutPath $INSTDIR; Copy external binariesdiff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.jsonindex 6aab02989..30303527e 100644--- a/src-tauri/tauri.linux.conf.json+++ b/src-tauri/tauri.linux.conf.json@@ -19,9 +19,19 @@]},"bundle": {- "targets": ["deb", "appimage"],- "resources": ["resources/LICENSE", "resources/bin/jan-cli"],- "externalBin": ["resources/bin/uv"],+ "targets": [+ "deb",+ "appimage"+ ],+ "resources": [+ "resources/LICENSE",+ "resources/bin/jan-cli",+ "resources/bin/jan-llama-worker",+ "resources/bin/libggml*.so*"+ ],+ "externalBin": [+ "resources/bin/uv"+ ],"linux": {"appimage": {"bundleMediaFramework": false,diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.jsonindex a1f373dc6..3d323d689 100644--- a/src-tauri/tauri.macos.conf.json+++ b/src-tauri/tauri.macos.conf.json@@ -21,7 +21,13 @@"decorations": true,"titleBarStyle": "Overlay","windowEffects": {- "effects": ["fullScreenUI", "mica", "tabbed", "blur", "acrylic"],+ "effects": [+ "fullScreenUI",+ "mica",+ "tabbed",+ "blur",+ "acrylic"+ ],"state": "active"},"dragDropEnabled": false@@ -29,9 +35,22 @@]},"bundle": {- "targets": ["app", "dmg"],- "resources": ["resources/LICENSE", "resources/bin/mlx-server", "resources/bin/mlx-swift_Cmlx.bundle", "resources/bin/jan-cli"],- "externalBin": ["resources/bin/bun", "resources/bin/uv"],+ "targets": [+ "app",+ "dmg"+ ],+ "resources": [+ "resources/LICENSE",+ "resources/bin/mlx-server",+ "resources/bin/mlx-swift_Cmlx.bundle",+ "resources/bin/jan-cli",+ "resources/bin/jan-llama-worker",+ "resources/bin/libggml*"+ ],+ "externalBin": [+ "resources/bin/bun",+ "resources/bin/uv"+ ],"macOS": {"entitlements": "./Entitlements.plist"}diff --git a/src-tauri/tauri.windows.conf.json b/src-tauri/tauri.windows.conf.jsonindex 8df865db6..68a6c1817 100644--- a/src-tauri/tauri.windows.conf.json+++ b/src-tauri/tauri.windows.conf.json@@ -21,7 +21,13 @@"decorations": false,"titleBarStyle": "Overlay","windowEffects": {- "effects": ["fullScreenUI", "mica", "tabbed", "blur", "acrylic"],+ "effects": [+ "fullScreenUI",+ "mica",+ "tabbed",+ "blur",+ "acrylic"+ ],"state": "active"},"dragDropEnabled": false@@ -29,9 +35,20 @@]},"bundle": {- "targets": ["nsis", "msi"],- "resources": ["resources/LICENSE", "resources/bin/jan-cli.exe"],- "externalBin": ["resources/bin/bun", "resources/bin/uv"],+ "targets": [+ "nsis",+ "msi"+ ],+ "resources": [+ "resources/LICENSE",+ "resources/bin/jan-cli.exe",+ "resources/bin/jan-llama-worker.exe",+ "resources/bin/ggml*.dll"+ ],+ "externalBin": [+ "resources/bin/bun",+ "resources/bin/uv"+ ],"windows": {"webviewInstallMode": {"silent": true,diff --git a/src-tauri/tests/windows_installer_resources.rs b/src-tauri/tests/windows_installer_resources.rsnew file mode 100644index 000000000..2e58c1a41--- /dev/null+++ b/src-tauri/tests/windows_installer_resources.rs@@ -0,0 +1,57 @@+//! Guards the one file that silently drops bundled resources.+//!+//! `template-tauri-build-windows-x64.yml` patches+//! `bundle.windows.nsis.template` into the config at build time, so the NSIS+//! bundler stops deriving its resource list from `bundle.resources` and uses the+//! committed template's hand-written block instead. The MSI still honours the+//! config, so a resource missing from the template ships in the MSI and not in+//! the setup exe -- which is the primary release asset *and* the auto-updater+//! payload, making it the more damaging half.+//!+//! This has already happened twice: #7618 hand-added `jan-cli.exe`, and the+//! engine worker plus its ggml modules fell through the same gap. Nothing in the+//! build fails when it happens, which is why it needs a test rather than a+//! comment.++use std::path::PathBuf;++fn repo_file(rel: &str) -> String {+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(rel);+ std::fs::read_to_string(&path)+ .unwrap_or_else(|e| panic!("could not read {}: {e}", path.display()))+}++#[test]+fn every_bundled_windows_resource_is_installed_by_the_nsis_template() {+ let conf: serde_json::Value = serde_json::from_str(&repo_file("tauri.windows.conf.json"))+ .expect("tauri.windows.conf.json is not valid JSON");+ let resources = conf["bundle"]["resources"]+ .as_array()+ .expect("bundle.resources must be an array");+ assert!(+ !resources.is_empty(),+ "bundle.resources is empty; this test would then assert nothing"+ );++ let template = repo_file("tauri.bundle.windows.nsis.template");++ let missing: Vec<&str> = resources+ .iter()+ .filter_map(|r| r.as_str())+ // The basename is what the template writes, and it carries the glob+ // verbatim (`ggml*.dll`), so comparing basenames covers both the literal+ // and the wildcard entries without reimplementing glob matching.+ .filter(|rel| {+ let name = rel.rsplit('/').next().unwrap_or(rel);+ !template.contains(name)+ })+ .collect();++ assert!(+ missing.is_empty(),+ "these bundle.resources entries are declared in tauri.windows.conf.json \+ but never installed by tauri.bundle.windows.nsis.template, so they ship \+ in the MSI and are silently absent from the NSIS setup exe: {missing:?}\n\+ Add a `File` line for each to the template's `; Copy resources` block."+ );+}diff --git a/web-app/src/constants/models.ts b/web-app/src/constants/models.tsindex c6dbdfbaf..825ad6633 100644--- a/web-app/src/constants/models.ts+++ b/web-app/src/constants/models.ts@@ -144,4 +144,21 @@ export const providerModels = {supportsToolCalls: true,supportsN: true,},-} as const\ No newline at end of file+} as const++/**+ * llama.cpp slot pins. Jan sends every chat turn to slot 0 so a thread reuses+ * its cached KV prefix across turns, and every background task (title+ * generation) to slot 1 so it can never overwrite that cache.+ *+ * Both are fixed indices rather than values derived from the "Parallel+ * Sequences" setting, because upstream *wraps* an out-of-range `id_slot`+ * instead of rejecting it (`get_slot_by_id`: `id_slot = id_slot % slots.size()`)+ * -- so a pin computed from a stale or differently-resolved slot count silently+ * lands back on slot 0. The extension's RESERVED_BACKGROUND_SLOTS keeps the+ * emitted `parallel` at 2 or more unconditionally, which is what guarantees+ * slot 1 exists; nothing else pins to it, so it is free even when the user+ * raised the sequence count.+ */+export const CHAT_SLOT_ID = 0+export const BACKGROUND_SLOT_ID = 1diff --git a/web-app/src/containers/BackendUpdateHistory.tsx b/web-app/src/containers/BackendUpdateHistory.tsxdeleted file mode 100644index 1c1ffd3b6..000000000--- a/web-app/src/containers/BackendUpdateHistory.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { useCallback, useEffect, useState } from 'react'-import { ExtensionManager } from '@/lib/extension'-import { Button } from '@/components/ui/button'-import { useTranslation } from '@/i18n'-import { cn } from '@/lib/utils'--export type BackendUpdateRecord = {- timestamp: string- from: string- to: string- outcome: 'updated' | 'rolled-back' | 'rollback-failed' | 'failed'- durationMs: number- error?: string-}--type HistoryProvider = {- getBackendUpdateHistory: () => Promise<BackendUpdateRecord[]>-}--function getHistoryProvider(): HistoryProvider | null {- const extension = ExtensionManager.getInstance().getByName(- 'llamacpp-extension'- )- return extension && 'getBackendUpdateHistory' in extension- ? (extension as unknown as HistoryProvider)- : null-}--const OUTCOME_LABELS: Record<BackendUpdateRecord['outcome'], string> = {- updated: 'providers:backendHistoryUpdated',- 'rolled-back': 'providers:backendHistoryRolledBack',- 'rollback-failed': 'providers:backendHistoryRollbackFailed',- failed: 'providers:backendHistoryFailed',-}--export function BackendUpdateHistory() {- const { t } = useTranslation()- const [expanded, setExpanded] = useState(false)- const [records, setRecords] = useState<BackendUpdateRecord[] | null>(null)-- const load = useCallback(async () => {- const provider = getHistoryProvider()- if (!provider) {- setRecords([])- return- }- try {- setRecords(await provider.getBackendUpdateHistory())- } catch {- setRecords([])- }- }, [])-- useEffect(() => {- if (expanded) void load()- }, [expanded, load])-- return (- <div className="mt-2 w-full">- <Button- variant="link"- size="sm"- className="h-auto p-0 text-muted-foreground"- onClick={() => setExpanded((v) => !v)}- >- {expanded- ? t('providers:backendHistoryHide')- : t('providers:backendHistoryShow')}- </Button>-- {expanded && (- <div className="mt-2 max-h-60 overflow-y-auto rounded-md border border-border">- {records === null && (- <p className="p-3 text-sm text-muted-foreground">- {t('providers:backendHistoryLoading')}- </p>- )}- {records?.length === 0 && (- <p className="p-3 text-sm text-muted-foreground">- {t('providers:backendHistoryEmpty')}- </p>- )}- {records?.map((record, index) => (- <div- key={`${record.timestamp}-${index}`}- className="border-b border-border p-3 text-sm last:border-b-0"- >- <div className="flex items-center justify-between gap-2">- <span className="font-medium">- {record.from || t('providers:backendHistoryNone')} →{' '}- {record.to}- </span>- <span- className={cn(- 'shrink-0 text-xs',- record.outcome === 'updated'- ? 'text-muted-foreground'- : 'text-destructive'- )}- >- {t(OUTCOME_LABELS[record.outcome])}- </span>- </div>- <div className="mt-1 text-xs text-muted-foreground">- {new Date(record.timestamp).toLocaleString()}- {' · '}- {Math.round(record.durationMs / 1000)}s- </div>- {record.error && (- <p className="mt-1 break-words text-xs text-destructive">- {record.error}- </p>- )}- </div>- ))}- </div>- )}- </div>- )-}diff --git a/web-app/src/containers/DownloadButton.tsx b/web-app/src/containers/DownloadButton.tsxindex a884383a2..ba494af2d 100644--- a/web-app/src/containers/DownloadButton.tsx+++ b/web-app/src/containers/DownloadButton.tsx@@ -12,7 +12,7 @@ import {} from '@/lib/models'import { toast } from 'sonner'import { cn, sanitizeModelId } from '@/lib/utils'-import { pickMtpSibling } from '@/lib/mtp'+import { pickSpecSibling } from '@/lib/specDraft'import { CatalogModel } from '@/services/models/types'import { DownloadEvent, DownloadState, events } from '@janhq/core'import { useCallback, useEffect, useMemo, useState } from 'react'@@ -132,8 +132,8 @@ export function DownloadButtonPlaceholder({(e) => e.model_id.toLowerCase() === 'mmproj-f16') || model.mmproj_models?.[0])?.path- const mtpPath = quant- ? pickMtpSibling(model.mtpQuants, quant)?.path+ const specDraft = quant+ ? pickSpecSibling(model.specQuants, quant): undefinedsetResumeParams(modelId, {modelPath: modelUrl,@@ -149,7 +149,8 @@ export function DownloadButtonPlaceholder({mmprojPath,huggingfaceToken,undefined,- mtpPath+ specDraft?.quant.path,+ specDraft?.kind)} catch (err) {removeLocalDownloadingModel(modelId)diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsxindex d7a0d8c1f..9fc5257c4 100644--- a/web-app/src/containers/ModelSetting.tsx+++ b/web-app/src/containers/ModelSetting.tsx@@ -23,14 +23,6 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'import { paramsSettings, samplerKeysForProvider } from '@/lib/predefinedParams'-const MTP_MIN_BUILD = 9193--function parseBuildNumber(version: unknown): number | null {- if (typeof version !== 'string') return null- const m = version.match(/^b(\d+)$/)- return m ? parseInt(m[1], 10) : null-}-type ModelSettingProps = {provider: ProviderObjectmodel: Model@@ -277,7 +269,7 @@ export function ModelSetting({<div className="px-4 space-y-8 pb-4 flex-1 min-h-0 overflow-y-auto">{provider.provider === 'llamacpp' && (- <MtpPanel modelId={model.id} provider={provider} />+ <SpecDraftPanel modelId={model.id} />)}{provider.provider === 'llamacpp' && model.embedding !== true && (<ChatTemplateKwargs@@ -385,7 +377,7 @@ export function ModelSetting({)}-type MtpInfo = {+type SpecDraftInfo = {mtp_layers: numbermtp: booleanspec_draft_n_max?: number@@ -393,16 +385,10 @@ type MtpInfo = {spec_draft_p_min?: number}-function MtpPanel({- modelId,- provider,-}: {- modelId: string- provider: ProviderObject-}) {+export function SpecDraftPanel({ modelId }: { modelId: string }) {const { t } = useTranslation()const serviceHub = useServiceHub()- const [info, setInfo] = useState<MtpInfo | null>(null)+ const [info, setInfo] = useState<SpecDraftInfo | null>(null)useEffect(() => {let active = true@@ -420,12 +406,6 @@ function MtpPanel({}}, [modelId, serviceHub])- const llamacppVersion = provider.settings?.find(- (s) => s.key === 'llamacpp_version'- )?.controller_props?.value as string | undefined- const buildNo = parseBuildNumber(llamacppVersion)- const backendSupports = buildNo !== null && buildNo >= MTP_MIN_BUILD-const persist = useCallback(async (patch: {mtp?: boolean@@ -444,7 +424,7 @@ function MtpPanel({if (!info || info.mtp_layers <= 0) return null- const enabled = info.mtp === true && backendSupports+ const enabled = info.mtp === trueconst updateNumber = (key: 'spec_draft_n_max' | 'spec_draft_n_min' | 'spec_draft_p_min',@@ -465,19 +445,18 @@ function MtpPanel({return (<div className="space-y-3"><div className="font-medium">- {t('common:modelSettings.mtp.section')}+ {t('common:modelSettings.specDraft.section')}</div><div className="space-y-2"><div className="flex items-start justify-between gap-8"><div className="mb-1 truncate"><span className="font-medium">- {t('common:modelSettings.mtp.enable')}+ {t('common:modelSettings.specDraft.enable')}</span></div><Switchchecked={enabled}- disabled={!backendSupports}onCheckedChange={(v) => {setInfo({ ...info, mtp: v })void persist({ mtp: v })@@ -485,17 +464,15 @@ function MtpPanel({/></div><p className="text-muted-foreground leading-normal text-xs">- {backendSupports- ? t('common:modelSettings.mtp.enableDescription')- : t('common:modelSettings.mtp.needsUpgrade')}+ {t('common:modelSettings.specDraft.enableDescription')}</p></div>{enabled && (<><NumberRow- label={t('common:modelSettings.mtp.nMax')}- description={t('common:modelSettings.mtp.nMaxDescription')}+ label={t('common:modelSettings.specDraft.nMax')}+ description={t('common:modelSettings.specDraft.nMaxDescription')}placeholder="16"value={info.spec_draft_n_max}min={1}@@ -503,8 +480,8 @@ function MtpPanel({onChange={(raw) => updateNumber('spec_draft_n_max', raw)}/><NumberRow- label={t('common:modelSettings.mtp.nMin')}- description={t('common:modelSettings.mtp.nMinDescription')}+ label={t('common:modelSettings.specDraft.nMin')}+ description={t('common:modelSettings.specDraft.nMinDescription')}placeholder="0"value={info.spec_draft_n_min}min={0}@@ -512,8 +489,8 @@ function MtpPanel({onChange={(raw) => updateNumber('spec_draft_n_min', raw)}/><NumberRow- label={t('common:modelSettings.mtp.pMin')}- description={t('common:modelSettings.mtp.pMinDescription')}+ label={t('common:modelSettings.specDraft.pMin')}+ description={t('common:modelSettings.specDraft.pMinDescription')}placeholder="0.75"value={info.spec_draft_p_min}min={0}diff --git a/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsx b/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsxdeleted file mode 100644index 953e2bf3e..000000000--- a/web-app/src/containers/__tests__/BackendUpdateHistory.test.tsx+++ /dev/null@@ -1,82 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { BackendUpdateHistory } from '../BackendUpdateHistory'--const hoisted = vi.hoisted(() => ({- extension: null as Record<string, unknown> | null,-}))--vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- getByName: () => hoisted.extension,- }),- },-}))--vi.mock('@/i18n', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}))--describe('BackendUpdateHistory', () => {- beforeEach(() => {- hoisted.extension = null- })-- it('only loads the history once expanded', async () => {- const getBackendUpdateHistory = vi.fn().mockResolvedValue([])- hoisted.extension = { getBackendUpdateHistory }-- render(<BackendUpdateHistory />)- expect(getBackendUpdateHistory).not.toHaveBeenCalled()-- await userEvent.click(screen.getByRole('button'))-- await waitFor(() => expect(getBackendUpdateHistory).toHaveBeenCalledTimes(1))- expect(- screen.getByText('providers:backendHistoryEmpty')- ).toBeInTheDocument()- })-- it('renders each record with its outcome and error', async () => {- hoisted.extension = {- getBackendUpdateHistory: vi.fn().mockResolvedValue([- {- timestamp: '2026-07-28T10:00:00.000Z',- from: 'b1000/cpu',- to: 'b1100/cpu',- outcome: 'rolled-back',- durationMs: 4000,- error: 'Router failed its health check',- },- ]),- }-- render(<BackendUpdateHistory />)- await userEvent.click(screen.getByRole('button'))-- await waitFor(() =>- expect(screen.getByText(/b1000\/cpu/)).toBeInTheDocument()- )- expect(- screen.getByText('providers:backendHistoryRolledBack')- ).toBeInTheDocument()- expect(- screen.getByText('Router failed its health check')- ).toBeInTheDocument()- })-- it('degrades to an empty list when the extension is unavailable', async () => {- hoisted.extension = null-- render(<BackendUpdateHistory />)- await userEvent.click(screen.getByRole('button'))-- await waitFor(() =>- expect(- screen.getByText('providers:backendHistoryEmpty')- ).toBeInTheDocument()- )- })-})diff --git a/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsx b/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsxnew file mode 100644index 000000000..8dc0ead5d--- /dev/null+++ b/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsx@@ -0,0 +1,53 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, waitFor } from '@testing-library/react'+import '@testing-library/jest-dom'++const hoisted = vi.hoisted(() => ({+ getMtpInfo: vi.fn(),+ updateMtpSettings: vi.fn(),+}))++vi.mock('@/hooks/useServiceHub', () => {+ const hub = {+ models: () => ({+ getMtpInfo: hoisted.getMtpInfo,+ updateMtpSettings: hoisted.updateMtpSettings,+ }),+ }+ return { useServiceHub: () => hub, getServiceHub: () => hub }+})++import { SpecDraftPanel } from '../ModelSetting'++// llama.cpp is linked into the worker at a pinned version, so there is no+// backend build number left to gate MTP on.+describe('SpecDraftPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ hoisted.updateMtpSettings.mockResolvedValue(undefined)+ })++ it('offers the toggle for a model with MTP heads', async () => {+ hoisted.getMtpInfo.mockResolvedValue({ mtp_layers: 2, mtp: false })+ render(<SpecDraftPanel modelId="glm" />)++ const toggle = await screen.findByRole('switch')+ expect(toggle).toBeEnabled()+ })++ it('reports a model whose MTP is already on as on', async () => {+ hoisted.getMtpInfo.mockResolvedValue({ mtp_layers: 2, mtp: true })+ render(<SpecDraftPanel modelId="glm" />)++ const toggle = await screen.findByRole('switch')+ expect(toggle).toBeChecked()+ })++ it('renders nothing for a model with no MTP heads', async () => {+ hoisted.getMtpInfo.mockResolvedValue({ mtp_layers: 0, mtp: false })+ render(<SpecDraftPanel modelId="llama" />)++ await waitFor(() => expect(hoisted.getMtpInfo).toHaveBeenCalled())+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()+ })+})diff --git a/web-app/src/containers/dialogs/BackendUpdater.tsx b/web-app/src/containers/dialogs/BackendUpdater.tsxdeleted file mode 100644index 05655541c..000000000--- a/web-app/src/containers/dialogs/BackendUpdater.tsx+++ /dev/null@@ -1,135 +0,0 @@-import { useBackendUpdater } from '@/hooks/useBackendUpdater'-import { useModelProvider } from '@/hooks/useModelProvider'--import { IconDownload } from '@tabler/icons-react'-import { Button } from '@/components/ui/button'--import { useState, useEffect } from 'react'-import { cn } from '@/lib/utils'-import { useTranslation } from '@/i18n/react-i18next-compat'-import { toast } from 'sonner'--const BackendUpdater = () => {- const { t } = useTranslation()- const isLlamacppEnabled = useModelProvider(- (s) => s.getProviderByName('llamacpp')?.active === true- )- const { updateState, updateBackend, checkForUpdate, setRemindMeLater } =- useBackendUpdater()-- const handleUpdate = async () => {- try {- await updateBackend()- setRemindMeLater(true)- toast.success(t('settings:backendUpdater.updateSuccess'))- } catch (error) {- console.error('Backend update failed:', error)- toast.error(t('settings:backendUpdater.updateError'))- }- }-- // Check when the shell mounts or when the llamacpp provider is toggled on/off.- // Skipped when auto-update is disabled — users opt into checks via the manual- // "Check for Updates" button in provider settings.- // Deferred to browser idle (after first paint) so the network round-trip- // doesn't compete with the initial render.- useEffect(() => {- if (!updateState.autoUpdateEnabled) return- const hasRic = typeof window.requestIdleCallback === 'function'- const idleHandle = hasRic- ? window.requestIdleCallback(() => checkForUpdate(), { timeout: 3000 })- : window.setTimeout(() => checkForUpdate(), 0)- return () => {- if (hasRic) window.cancelIdleCallback(idleHandle as number)- else window.clearTimeout(idleHandle as number)- }- }, [checkForUpdate, isLlamacppEnabled, updateState.autoUpdateEnabled])-- const [backendUpdateState, setBackendUpdateState] = useState({- remindMeLater: false,- isUpdateAvailable: false,- })-- useEffect(() => {- setBackendUpdateState({- remindMeLater: updateState.remindMeLater,- isUpdateAvailable: updateState.isUpdateAvailable,- })- }, [updateState])-- // Don't prompt for the Llama.cpp engine when the provider is disabled (jan#7901)- if (!isLlamacppEnabled) {- return null- }-- // Don't show if auto-update is enabled — the engine updates silently- if (updateState.autoUpdateEnabled) {- return null- }-- // Don't show if user clicked remind me later- if (backendUpdateState.remindMeLater) {- console.log('BackendUpdater: Not showing notification due to:', {- remindMeLater: backendUpdateState.remindMeLater,- })- return null- }-- return (- <>- {backendUpdateState.isUpdateAvailable && (- <div- className={cn(- 'fixed z-50 bottom-3 right-3 bg-background flex items-center border rounded-lg shadow-md'- )}- >- <div className="px-2 py-4">- <div className="px-4">- <div className="flex items-start gap-2">- <IconDownload- size={20}- className="shrink-0 text-muted-foreground mt-1"- />- <div>- <div className="text-base font-medium">- {t('settings:backendUpdater.newBackendVersion', {- version: updateState.updateInfo?.newVersion,- })}- </div>- <div className="mt-1 text-muted-foreground font-normal mb-2">- {t('settings:backendUpdater.backendUpdateAvailable')}- </div>- </div>- </div>- </div>-- <div className="pt-3 px-4">- <div className="flex gap-x-4 w-full items-center justify-end">- <div className="flex gap-x-2">- <Button- variant="ghost"- size="sm"- onClick={() => setRemindMeLater(true)}- >- {t('settings:backendUpdater.remindMeLater')}- </Button>- <Button- size="sm"- onClick={handleUpdate}- disabled={updateState.isUpdating}- >- {updateState.isUpdating- ? t('settings:backendUpdater.updating')- : t('settings:backendUpdater.updateNow')}- </Button>- </div>- </div>- </div>- </div>- </div>- )}- </>- )-}--export default BackendUpdaterdiff --git a/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx b/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsxindex 782b47c4e..18b8ebcf7 100644--- a/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx+++ b/web-app/src/containers/dialogs/ImportLlamacppModelDialog.tsx@@ -21,6 +21,7 @@ import {IconCodeCircle2,IconBolt,} from '@tabler/icons-react'+import { readGgufMetadata } from '@janhq/tauri-plugin-llamacpp-api'type DetectedModalities = { vision: boolean; audio: boolean }@@ -239,19 +240,8 @@ export const ImportLlamacppModelDialog = ({} else if (fileType === 'mmproj') {// For mmproj files, we need to manually validate since validateGgufFile rejects CLIP modelstry {- // Import the readGgufMetadata function directly from Tauri- const { invoke } = await import('@tauri-apps/api/core')-- const metadata = await invoke(- 'plugin:llamacpp|read_gguf_metadata',- {- path: filePath,- }- )-- const meta = (- metadata as { metadata?: Record<string, string> }- ).metadata+ const metadata = await readGgufMetadata(filePath)+ const meta = metadata.metadataconst architecture = meta?.['general.architecture']if (architecture !== 'clip') {diff --git a/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsx b/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsxindex a42c62795..bb9c6a798 100644--- a/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsx+++ b/web-app/src/containers/dialogs/LlamacppBusyOnExitDialog.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'+import { forceStopEngine } from '@janhq/tauri-plugin-llamacpp-api'import { AlertTriangle } from 'lucide-react'import { toast } from 'sonner'@@ -66,7 +67,7 @@ export default function LlamacppBusyOnExitDialog() {...Object.keys(state.abortControllers),])threadIds.forEach((tid) => state.clearThreadState(tid))- await invoke('plugin:llamacpp|force_kill_router_tree')+ await forceStopEngine()await invoke('confirm_exit')} catch (e) {console.error('force-quit failed:', e)diff --git a/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsxindex 95f6b75c0..c6c9b3f51 100644--- a/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx+++ b/web-app/src/containers/dialogs/MissingDependenciesDialog.tsx@@ -17,7 +17,6 @@ import { getBackendDisplayName } from '@/lib/backendDependencies'type VerificationFailedPayload = {backend: string- version: stringmissingLibraries: string[]}diff --git a/web-app/src/hooks/__tests__/useBackendUpdater.test.ts b/web-app/src/hooks/__tests__/useBackendUpdater.test.tsdeleted file mode 100644index e7563ac95..000000000--- a/web-app/src/hooks/__tests__/useBackendUpdater.test.ts+++ /dev/null@@ -1,146 +0,0 @@-import { describe, it, expect, beforeEach, vi } from 'vitest'-import { renderHook, act } from '@testing-library/react'--// Mock events-const mockOn = vi.fn()-const mockOff = vi.fn()-const mockEmit = vi.fn()--vi.mock('@janhq/core', () => ({- events: {- on: mockOn,- off: mockOff,- emit: mockEmit,- },-}))--// Mock useModelProvider-vi.mock('@/hooks/useModelProvider', () => ({- useModelProvider: {- getState: vi.fn().mockReturnValue({- getProviderByName: vi.fn().mockReturnValue({ active: true }),- }),- },-}))--// Mock ExtensionManager-const mockGetByName = vi.fn()-const mockListExtensions = vi.fn().mockReturnValue([])--vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- getByName: mockGetByName,- listExtensions: mockListExtensions,- }),- },-}))--describe('useBackendUpdater', () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetByName.mockReturnValue(null)- mockListExtensions.mockReturnValue([])- })-- it('should initialize with default state', async () => {- const { useBackendUpdater } = await import('../useBackendUpdater')- const { result } = renderHook(() => useBackendUpdater())-- expect(result.current.updateState.isUpdateAvailable).toBe(false)- expect(result.current.updateState.updateInfo).toBeNull()- expect(result.current.updateState.isUpdating).toBe(false)- expect(result.current.updateState.remindMeLater).toBe(false)- expect(typeof result.current.checkForUpdate).toBe('function')- expect(typeof result.current.updateBackend).toBe('function')- expect(typeof result.current.setRemindMeLater).toBe('function')- expect(typeof result.current.installBackend).toBe('function')- })-- it('should subscribe to onBackendUpdateStateSync event', async () => {- const { useBackendUpdater } = await import('../useBackendUpdater')- renderHook(() => useBackendUpdater())-- expect(mockOn).toHaveBeenCalledWith(- 'onBackendUpdateStateSync',- expect.any(Function)- )- })-- it('should unsubscribe on unmount', async () => {- const { useBackendUpdater } = await import('../useBackendUpdater')- const { unmount } = renderHook(() => useBackendUpdater())-- unmount()-- expect(mockOff).toHaveBeenCalledWith(- 'onBackendUpdateStateSync',- expect.any(Function)- )- })-- it('should set remindMeLater', async () => {- const { useBackendUpdater } = await import('../useBackendUpdater')- const { result } = renderHook(() => useBackendUpdater())-- act(() => {- result.current.setRemindMeLater(true)- })-- expect(result.current.updateState.remindMeLater).toBe(true)- expect(mockEmit).toHaveBeenCalledWith('onBackendUpdateStateSync', {- remindMeLater: true,- })- })-- it('checkForUpdate returns null when extension not found', async () => {- const { useBackendUpdater } = await import('../useBackendUpdater')- const { result } = renderHook(() => useBackendUpdater())-- let updateResult: any- await act(async () => {- updateResult = await result.current.checkForUpdate()- })-- expect(updateResult).toBeNull()- })-- it('checkForUpdate returns update info when available', async () => {- const mockUpdateInfo = {- updateNeeded: true,- newVersion: '2.0.0',- currentVersion: '1.0.0',- }- mockGetByName.mockReturnValue({- checkBackendForUpdates: vi.fn().mockResolvedValue(mockUpdateInfo),- })-- const { useBackendUpdater } = await import('../useBackendUpdater')- const { result } = renderHook(() => useBackendUpdater())-- let updateResult: any- await act(async () => {- updateResult = await result.current.checkForUpdate()- })-- expect(updateResult).toEqual(mockUpdateInfo)- expect(result.current.updateState.isUpdateAvailable).toBe(true)- })-- it('checkForUpdate returns null when no update needed', async () => {- mockGetByName.mockReturnValue({- checkBackendForUpdates: vi.fn().mockResolvedValue({ updateNeeded: false, newVersion: '' }),- })-- const { useBackendUpdater } = await import('../useBackendUpdater')- const { result } = renderHook(() => useBackendUpdater())-- let updateResult: any- await act(async () => {- updateResult = await result.current.checkForUpdate()- })-- expect(updateResult).toBeNull()- expect(result.current.updateState.isUpdateAvailable).toBe(false)- })-})diff --git a/web-app/src/hooks/__tests__/useSetupChecklist.test.ts b/web-app/src/hooks/__tests__/useSetupChecklist.test.tsindex 92300797b..111bf356c 100644--- a/web-app/src/hooks/__tests__/useSetupChecklist.test.ts+++ b/web-app/src/hooks/__tests__/useSetupChecklist.test.ts@@ -278,22 +278,25 @@ describe('useSetupChecklist', () => {expect(result.current.warnings).toHaveLength(1)})- it('distinguishes a machine with no GPU from an unreachable one', async () => {+ // There is no longer a "wrong build for this machine" case: the engine ships+ // with the app, so a machine with no GPU is simply a CPU machine -- ok, not a+ // warning. The only GPU warning left is a device the engine cannot reach.+ it('treats a machine with no GPU as settled rather than as a warning', async () => {armHealthy()mockVerifyGpuOffload.mockResolvedValue({- status: 'warning',- backend: 'linux-cuda-12-common_cpus-x64',- gpuExpected: true,+ status: 'ok',+ backend: '',+ gpuExpected: false,engineDeviceCount: 0,- reason: 'noGpuHardware',})const { result } = renderHook(() => useSetupChecklist())await waitFor(() => expect(result.current.isRunning).toBe(false))- expect(stageById(result.current.stages, 'engine').messageKey).toBe(- 'checkEngineNoGpuHardware'- )+ const engine = stageById(result.current.stages, 'engine')+ expect(engine.status).toBe('ok')+ expect(engine.messageKey).toBe('checkEngineCpu')+ expect(result.current.warnings).toHaveLength(0)})// The cause is established, so the message names the dependency rather than@@ -426,11 +429,11 @@ describe('useSetupChecklist', () => {// A fresh install downloads a backend before it has one, so the engine row// must not accuse a not-yet-chosen backend of being CPU-only.- it('shows the engine as still preparing while no backend is selected', async () => {+ it('settles instead of waiting when the backend name is unrecognised', async () => {armHealthy()mockVerifyGpuOffload.mockResolvedValue({status: 'ok',- backend: '',+ backend: 'CUDA0-ish-unrecognised',gpuExpected: false,engineDeviceCount: 0,})@@ -439,8 +442,9 @@ describe('useSetupChecklist', () => {await waitFor(() => expect(result.current.isRunning).toBe(false))const engine = stageById(result.current.stages, 'engine')- expect(engine.status).toBe('running')- expect(engine.messageKey).toBe('checkEnginePreparing')+ // Never 'running': nothing is downloading any more, so a stage left running+ // is a stage that never settles, and onboarding step 2 waits on it forever.+ expect(engine.status).toBe('ok')expect(result.current.warnings).toHaveLength(0)})diff --git a/web-app/src/hooks/useBackendUpdater.ts b/web-app/src/hooks/useBackendUpdater.tsdeleted file mode 100644index ec523e023..000000000--- a/web-app/src/hooks/useBackendUpdater.ts+++ /dev/null@@ -1,468 +0,0 @@-import { useState, useCallback, useEffect } from 'react'-import { events } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'-import { useModelProvider } from '@/hooks/useModelProvider'--/** Llama.cpp engine updates only apply when the llamacpp model provider is enabled. */-function isLlamacppProviderActive(): boolean {- const p = useModelProvider.getState().getProviderByName('llamacpp')- return p?.active === true-}--export interface BackendUpdateInfo {- updateNeeded: boolean- newVersion: string- currentVersion?: string- targetBackend?: string-}--interface ExtensionSetting {- key: string- controllerProps?: {- value: unknown- }-}--interface BackendUpdateResult {- wasUpdated: boolean- reason?: 'in_progress' | 'error' | string-}--interface ExtensionWithSettings {- getSettings?: () => Promise<ExtensionSetting[] | undefined>-}--async function getCurrentBackendTypeFromSettings(- extension: ExtensionWithSettings-): Promise<string> {- const settings = await extension.getSettings?.()- const backendSetting = settings?.find((s) => s.key === 'llamacpp_backend')- const currentBackendType = (- backendSetting?.controllerProps?.value as string | undefined- )?.trim()-- if (!currentBackendType) {- throw new Error('Current backend not found')- }-- return currentBackendType-}--interface LlamacppExtension {- getSettings?(): Promise<ExtensionSetting[]>- checkBackendForUpdates?(): Promise<BackendUpdateInfo>- updateBackend?(- targetBackend: string- ): Promise<{ wasUpdated: boolean; newBackend: string }>- installBackend?(filePath: string): Promise<void>- installCudaRuntime?(filePath: string): Promise<void>- configureBackends?(): Promise<void>- refreshBackendOptions?(): Promise<void>-}--export interface BackendUpdateState {- isUpdateAvailable: boolean- updateInfo: BackendUpdateInfo | null- isUpdating: boolean- remindMeLater: boolean- autoUpdateEnabled: boolean-}--export const useBackendUpdater = () => {- const [updateState, setUpdateState] = useState<BackendUpdateState>({- isUpdateAvailable: false,- updateInfo: null,- isUpdating: false,- remindMeLater: false,- autoUpdateEnabled: false,- })-- // Listen for backend update state sync events- useEffect(() => {- const handleUpdateStateSync = (newState: Partial<BackendUpdateState>) => {- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- }-- events.on('onBackendUpdateStateSync', handleUpdateStateSync)-- return () => {- events.off('onBackendUpdateStateSync', handleUpdateStateSync)- }- }, [])-- // Check auto update setting from llamacpp extension- useEffect(() => {- const checkAutoUpdateSetting = async () => {- try {- // Get llamacpp extension instance- const allExtensions = ExtensionManager.getInstance().listExtensions()- let llamacppExtension =- ExtensionManager.getInstance().getByName('llamacpp-extension')-- if (!llamacppExtension) {- // Try to find by type or other properties- llamacppExtension =- allExtensions.find(- (ext) =>- ext.constructor.name.toLowerCase().includes('llamacpp') ||- (ext.type &&- ext.type()?.toString().toLowerCase().includes('inference'))- ) || undefined- }-- if (llamacppExtension && 'getSettings' in llamacppExtension) {- const extension = llamacppExtension as LlamacppExtension- const settings = await extension.getSettings?.()- const autoUpdateSetting = settings?.find(- (s) => s.key === 'auto_update_engine'- )-- setUpdateState((prev) => ({- ...prev,- autoUpdateEnabled:- autoUpdateSetting?.controllerProps?.value === true,- }))- }- } catch (error) {- console.error('Failed to check auto update setting:', error)- }- }-- checkAutoUpdateSetting()- }, [])-- const syncStateToOtherInstances = useCallback(- (partialState: Partial<BackendUpdateState>) => {- // Emit event to sync state across all useBackendUpdater instances- events.emit('onBackendUpdateStateSync', partialState)- },- []- )-- const checkForUpdate = useCallback(- async (resetRemindMeLater = false) => {- try {- // Reset remindMeLater if requested (e.g., when called from settings)- if (resetRemindMeLater) {- const newState = {- remindMeLater: false,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- }-- if (!isLlamacppProviderActive()) {- const newState = {- isUpdateAvailable: false,- updateInfo: null,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- return null- }-- // Get llamacpp extension instance- const allExtensions = ExtensionManager.getInstance().listExtensions()-- const llamacppExtension =- ExtensionManager.getInstance().getByName('llamacpp-extension')-- let extensionToUse = llamacppExtension-- if (!llamacppExtension) {- // Try to find by type or other properties- const possibleExtension = allExtensions.find(- (ext) =>- ext.constructor.name.toLowerCase().includes('llamacpp') ||- (ext.type &&- ext.type()?.toString().toLowerCase().includes('inference'))- )-- if (!possibleExtension) {- console.error('LlamaCpp extension not found')- return null- }-- extensionToUse = possibleExtension- }-- if (!extensionToUse || !('checkBackendForUpdates' in extensionToUse)) {- console.error(- 'Extension does not support checkBackendForUpdates method'- )- return null- }-- // Call the extension's checkBackendForUpdates method- const extension = extensionToUse as LlamacppExtension- const updateInfo = await extension.checkBackendForUpdates?.()-- if (updateInfo?.updateNeeded) {- const newState = {- isUpdateAvailable: true,- remindMeLater: false,- updateInfo,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- console.log('Backend update available:', updateInfo?.newVersion)- return updateInfo- } else {- // No update available - reset state- const newState = {- isUpdateAvailable: false,- updateInfo: null,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- return null- }- } catch (error) {- console.error('Error checking for backend updates:', error)- // Reset state on error- const newState = {- isUpdateAvailable: false,- updateInfo: null,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- return null- }- },- [syncStateToOtherInstances]- )-- const setRemindMeLater = useCallback(- (remind: boolean) => {- const newState = {- remindMeLater: remind,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- },- [syncStateToOtherInstances]- )-- const updateBackend = useCallback(async () => {- if (!updateState.updateInfo) return-- if (!isLlamacppProviderActive()) {- const newState = {- isUpdateAvailable: false,- updateInfo: null,- isUpdating: false,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- return- }-- try {- // If an update is already in progress, avoid triggering a duplicate update.- if (updateState.isUpdating) {- return- }-- setUpdateState((prev) => ({- ...prev,- isUpdating: true,- }))-- // Get llamacpp extension instance- const allExtensions = ExtensionManager.getInstance().listExtensions()- const llamacppExtension =- ExtensionManager.getInstance().getByName('llamacpp-extension')-- let extensionToUse = llamacppExtension-- if (!llamacppExtension) {- // Try to find by type or other properties- const possibleExtension = allExtensions.find(- (ext) =>- ext.constructor.name.toLowerCase().includes('llamacpp') ||- (ext.type &&- ext.type()?.toString().toLowerCase().includes('inference'))- )-- if (!possibleExtension) {- throw new Error('LlamaCpp extension not found')- }-- extensionToUse = possibleExtension- }-- if (- !extensionToUse ||- !('getSettings' in extensionToUse) ||- !('updateBackend' in extensionToUse)- ) {- throw new Error('Extension does not support backend updates')- }-- const extension = extensionToUse as LlamacppExtension-- // Use the exact target backend from checkBackendForUpdates if available,- // to avoid mismatches between old/new backend name formats- let targetBackendString = updateState.updateInfo.targetBackend-- if (targetBackendString) {- // Validate and normalize the provided target backend string- const rawParts = targetBackendString.split('/')- const versionPart = rawParts[0]?.trim()- const backendTypePart = rawParts[1]?.trim()-- if (rawParts.length !== 2 || !versionPart || !backendTypePart) {- // Malformed targetBackend; fall back to constructing from current settings- const currentBackendType = await getCurrentBackendTypeFromSettings(- extension- )- targetBackendString = `${updateState.updateInfo.newVersion}/${currentBackendType}`- } else {- // Normalize to "version/backendType" with trimmed parts- targetBackendString = `${versionPart}/${backendTypePart}`- }- } else {- // Fallback: construct from current settings if targetBackend wasn't provided- const currentBackendType = await getCurrentBackendTypeFromSettings(- extension- )- targetBackendString = `${updateState.updateInfo.newVersion}/${currentBackendType}`- }-- // Call the extension's updateBackend method- const rawResult = await extension.updateBackend?.(targetBackendString)- const result = rawResult as BackendUpdateResult | undefined-- if (result?.wasUpdated === true) {- // Reset update state on successful update- const newState = {- isUpdateAvailable: false,- updateInfo: null,- isUpdating: false,- }- setUpdateState((prev) => ({- ...prev,- ...newState,- }))- syncStateToOtherInstances(newState)- } else if (- result?.wasUpdated === false &&- (result.reason === 'in_progress' || typeof result.reason === 'undefined')- ) {- // Benign no-op (e.g., another update is already in progress or the- // extension returned a no-op response without a reason). Do not treat- // this as a failure; just clear the local isUpdating flag.- setUpdateState((prev) => ({- ...prev,- isUpdating: false,- }))- } else if (- result?.wasUpdated === false &&- result.reason &&- result.reason !== 'in_progress'- ) {- // Explicit failure reason from extension: surface as an error.- throw new Error(`Backend update failed: ${result.reason}`)- } else {- throw new Error('Backend update failed')- }- } catch (error) {- console.error('Error updating backend:', error)- setUpdateState((prev) => ({- ...prev,- isUpdating: false,- }))- throw error- }- }, [updateState.updateInfo, updateState.isUpdating, syncStateToOtherInstances])-- const installBackend = useCallback(async (filePath: string) => {- try {- // Get llamacpp extension instance- const allExtensions = ExtensionManager.getInstance().listExtensions()- const llamacppExtension =- ExtensionManager.getInstance().getByName('llamacpp-extension')-- let extensionToUse = llamacppExtension-- if (!llamacppExtension) {- // Try to find by type or other properties- const possibleExtension = allExtensions.find(- (ext) =>- ext.constructor.name.toLowerCase().includes('llamacpp') ||- (ext.type &&- ext.type()?.toString().toLowerCase().includes('inference'))- )-- if (!possibleExtension) {- throw new Error('LlamaCpp extension not found')- }-- extensionToUse = possibleExtension- }-- if (!extensionToUse || !('installBackend' in extensionToUse)) {- throw new Error('Extension does not support backend installation')- }-- // Call the extension's installBackend method- const extension = extensionToUse as LlamacppExtension- await extension.installBackend?.(filePath)-- // Refresh backend list to update UI. Prefer the narrow- // refreshBackendOptions (just rewrites the dropdown options); fall- // back to the heavy configureBackends path for older extensions.- if (extension.refreshBackendOptions) {- await extension.refreshBackendOptions()- } else {- await extension.configureBackends?.()- }- } catch (error) {- console.error('Error installing backend:', error)- throw error- }- }, [])-- const installCudaRuntime = useCallback(async (filePath: string) => {- const extension = ExtensionManager.getInstance().getByName(- 'llamacpp-extension'- ) as LlamacppExtension | undefined- if (!extension || !('installCudaRuntime' in extension)) {- throw new Error('Extension does not support CUDA runtime installation')- }- await extension.installCudaRuntime?.(filePath)- }, [])-- return {- updateState,- checkForUpdate,- updateBackend,- setRemindMeLater,- installBackend,- installCudaRuntime,- }-}diff --git a/web-app/src/hooks/useSetupChecklist.ts b/web-app/src/hooks/useSetupChecklist.tsindex 1e6e3c8ed..30adc8746 100644--- a/web-app/src/hooks/useSetupChecklist.ts+++ b/web-app/src/hooks/useSetupChecklist.ts@@ -44,7 +44,6 @@ const ENGINE_SETTINGS_CHANGED = 'settingsChanged'// `missingLibrary` is the same symptom as `runtimeUnreachable` with the cause// identified, so it gets its own message naming the dependency.const ENGINE_REASON_KEYS: Record<GpuOffloadReason, string> = {- noGpuHardware: 'checkEngineNoGpuHardware',runtimeUnreachable: 'checkEngineRuntimeUnreachable',missingLibrary: 'checkEngineMissingLibrary',}@@ -152,14 +151,17 @@ function engineStage(// report the inverse, so a GPU left idle by a CPU-only build -- or a build// for the wrong vendor -- is caught here instead.const match = evaluateBackendGpuMatch(gpus, report.backend)- // On a fresh install the engine is still downloading a backend, so there is- // nothing to judge yet. Reported as in-progress, never as a warning: it- // resolves on its own and the checklist re-runs when it does.+ // `unknown` means the backend name told us nothing -- which, now that the+ // backend is read off the device the engine enumerated, means it enumerated+ // no device at all. That is a settled CPU verdict, not work in progress.+ // Reporting 'running' here left onboarding waiting forever on any machine+ // without a usable GPU, because nothing was ever going to change.if (match.kind === 'unknown') {return {id: 'engine',- status: 'running',- messageKey: 'checkEnginePreparing',+ status: 'ok',+ messageKey: 'checkEngineCpu',+ values: { backend: report.backend },}}if (match.kind === 'gpuUnused') {diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.tsindex 1fdc61d9e..5ba211693 100644--- a/web-app/src/hooks/useThreads.ts+++ b/web-app/src/hooks/useThreads.ts@@ -58,6 +58,28 @@ const cleanupVectorDB = async (threadId: string) => {}}+/**+ * Drops the thread's saved prompt cache in the local engine.+ *+ * Best-effort and fire-and-forget, like the vector DB cleanup above: the cache+ * is bounded by its own disk budget, so failing to reclaim one thread's share+ * is not worth failing the delete over.+ */+const cleanupThreadCache = async (threadId: string) => {+ try {+ const { EngineManager } = await import('@janhq/core')+ const engine = EngineManager.instance().get('llamacpp') as+ | { forgetThreadCache?: (id: string) => Promise<number> }+ | undefined+ await engine?.forgetThreadCache?.(threadId)+ } catch (e) {+ console.warn(+ `[Threads] Failed to drop the saved prompt cache for thread ${threadId}:`,+ e+ )+ }+}+export const useThreads = create<ThreadState>()((set, get) => ({threads: {},isLoadingThreads: true,@@ -165,6 +187,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)cleanupVectorDB(threadId)+ cleanupThreadCache(threadId)getServiceHub().threads().deleteThread(threadId)return {@@ -201,6 +224,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({// Delete threads and clean up their vector DB collectionsthreadsToDeleteIds.forEach((threadId) => {cleanupVectorDB(threadId)+ cleanupThreadCache(threadId)getServiceHub().threads().deleteThread(threadId)})@@ -235,6 +259,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)cleanupVectorDB(threadId)+ cleanupThreadCache(threadId)getServiceHub().threads().deleteThread(threadId)})@@ -261,6 +286,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)cleanupVectorDB(threadId)+ cleanupThreadCache(threadId)getServiceHub().threads().deleteThread(threadId)})diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.tsindex 5fade0897..d1184f42c 100644--- a/web-app/src/lib/__tests__/engineError.test.ts+++ b/web-app/src/lib/__tests__/engineError.test.ts@@ -13,6 +13,7 @@ vi.mock('@/i18n/react-i18next-compat', () => ({import {parseEngineError,describeEngineError,+ engineFailure,ENGINE_ERROR_CODES,} from '../engineError'@@ -94,6 +95,48 @@ describe('describeEngineError', () => {expect(text).toContain('libnccl.so.2, libcublas.so.12')})+ // The localized sentence is advice; the engine's own text is the evidence.+ // Dropping it left an OOM indistinguishable from any other load failure.+ it('appends the engine reason so the cause is visible, not just the advice', () => {+ const text = describeEngineError({+ code: 'OUT_OF_MEMORY',+ message: 'Out of memory.',+ details:+ 'could not start the llama.cpp engine: failed to load model; cudaMalloc failed: out of memory',+ })++ expect(mockT).toHaveBeenCalledWith('model-errors:engineReportedDetail', {+ detail:+ 'could not start the llama.cpp engine: failed to load model; cudaMalloc failed: out of memory',+ })+ expect(text).toContain('cudaMalloc failed: out of memory')+ })++ it('collapses whitespace and clips a log-sized detail', () => {+ const text = describeEngineError({+ code: 'MODEL_LOAD_FAILED',+ details: `line one\n line two${' padding'.repeat(60)}`,+ })++ const detail = mockT.mock.calls.find(+ ([key]) => key === 'model-errors:engineReportedDetail'+ )?.[1]?.detail as string++ expect(detail).toContain('line one line two')+ expect(detail).not.toContain('\n')+ expect(detail.length).toBeLessThan(250)+ expect(detail.endsWith('...')).toBe(true)+ })++ it('omits the detail wrapper when there is no detail', () => {+ describeEngineError({ code: 'IO_ERROR' })++ expect(mockT).not.toHaveBeenCalledWith(+ 'model-errors:engineReportedDetail',+ expect.anything()+ )+ })+it('has a key for every code the engine can emit', () => {for (const code of ENGINE_ERROR_CODES) {mockT.mockClear()@@ -126,3 +169,32 @@ describe('describeEngineError', () => {}})})++describe('engineFailure', () => {+ beforeEach(() => {+ mockT.mockClear()+ })++ it('keeps the structured error reachable so an outer layer describes it once', () => {+ const engine = { code: 'OUT_OF_MEMORY', details: 'cudaMalloc failed' }+ const inner = engineFailure('model-errors:startModelFailed', engine)+ const outer = engineFailure('model-errors:createModelFailed', inner)++ expect(parseEngineError(outer)?.code).toBe('OUT_OF_MEMORY')+ expect(describeEngineError(outer)).toContain(+ 'model-errors:engine.OUT_OF_MEMORY'+ )+ expect(describeEngineError(outer)).not.toContain(+ 'model-errors:startModelFailed'+ )+ })++ it('describes a non-engine cause from its own message', () => {+ const wrapped = engineFailure(+ 'model-errors:startModelFailed',+ new Error('GPU fail')+ )++ expect(wrapped.message).toContain('GPU fail')+ })+})diff --git a/web-app/src/lib/__tests__/model-factory.constraints.test.ts b/web-app/src/lib/__tests__/model-factory.constraints.test.tsnew file mode 100644index 000000000..b2dbc2d42--- /dev/null+++ b/web-app/src/lib/__tests__/model-factory.constraints.test.ts@@ -0,0 +1,129 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { reconcileConstraintParams } from '../model-factory'++const TOOLS = [{ type: 'function', function: { name: 'search' } }]++describe('reconcileConstraintParams', () => {+ beforeEach(() => vi.spyOn(console, 'warn').mockImplementation(() => {}))+ afterEach(() => vi.restoreAllMocks())++ // The server throws on the *presence* of the key, so an untouched Grammar+ // row (default '') would 400 every request in a tool-enabled thread.+ it('drops an empty grammar', () => {+ const body: Record<string, unknown> = { grammar: '', messages: [] }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('grammar')+ })++ it('drops a whitespace-only grammar', () => {+ const body: Record<string, unknown> = { grammar: ' \n ' }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('grammar')+ })++ it('keeps a real grammar when the request carries no tools', () => {+ const body: Record<string, unknown> = { grammar: 'root ::= "a"' }+ reconcileConstraintParams(body)+ expect(body.grammar).toBe('root ::= "a"')+ })++ it('drops a grammar the server would reject alongside tools', () => {+ const body: Record<string, unknown> = {+ grammar: 'root ::= "a"',+ tools: TOOLS,+ }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('grammar')+ expect(body.tools).toBe(TOOLS)+ })++ // tool_choice 'none' means the tools are not offered, so the server's+ // grammar check does not fire.+ it('keeps a grammar when tools are present but disabled', () => {+ const body: Record<string, unknown> = {+ grammar: 'root ::= "a"',+ tools: TOOLS,+ tool_choice: 'none',+ }+ reconcileConstraintParams(body)+ expect(body.grammar).toBe('root ::= "a"')+ })++ it('keeps a grammar when tools is an empty array', () => {+ const body: Record<string, unknown> = { grammar: 'root ::= "a"', tools: [] }+ reconcileConstraintParams(body)+ expect(body.grammar).toBe('root ::= "a"')+ })++ // The textarea holds a string; the server parses it back to a JSON *string*+ // and every consumer requires an object, so it was silently ignored.+ it('parses a json_schema string into an object', () => {+ const body: Record<string, unknown> = {+ json_schema: '{"type":"object","properties":{}}',+ }+ reconcileConstraintParams(body)+ expect(body.json_schema).toEqual({ type: 'object', properties: {} })+ })++ it('passes an already-parsed json_schema through', () => {+ const schema = { type: 'object' }+ const body: Record<string, unknown> = { json_schema: schema }+ reconcileConstraintParams(body)+ expect(body.json_schema).toBe(schema)+ })++ it('drops an empty json_schema', () => {+ const body: Record<string, unknown> = { json_schema: ' ' }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('json_schema')+ })++ it('drops an unparseable json_schema rather than failing the request', () => {+ const body: Record<string, unknown> = { json_schema: '{not json' }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('json_schema')+ expect(console.warn).toHaveBeenCalled()+ })++ it('drops a json_schema that is not an object', () => {+ const body: Record<string, unknown> = { json_schema: '"a string"' }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('json_schema')+ })++ it('drops a json_schema array', () => {+ const body: Record<string, unknown> = { json_schema: '[1,2]' }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('json_schema')+ })++ // "Cannot use both json_schema and grammar" -- the explicit one wins.+ it('keeps grammar and drops json_schema when both are set', () => {+ const body: Record<string, unknown> = {+ grammar: 'root ::= "a"',+ json_schema: '{"type":"object"}',+ }+ reconcileConstraintParams(body)+ expect(body.grammar).toBe('root ::= "a"')+ expect(body).not.toHaveProperty('json_schema')+ })++ // Once the tools rule has removed the grammar there is no conflict left,+ // so the schema must survive.+ it('keeps json_schema when the grammar was dropped for tools', () => {+ const body: Record<string, unknown> = {+ grammar: 'root ::= "a"',+ json_schema: '{"type":"object"}',+ tools: TOOLS,+ }+ reconcileConstraintParams(body)+ expect(body).not.toHaveProperty('grammar')+ expect(body.json_schema).toEqual({ type: 'object' })+ })++ it('leaves a body with neither key untouched', () => {+ const body: Record<string, unknown> = { messages: [], stream: true }+ reconcileConstraintParams(body)+ expect(body).toEqual({ messages: [], stream: true })+ })+})diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.tsindex 75ae27864..0b5dcffdb 100644--- a/web-app/src/lib/__tests__/model-factory.test.ts+++ b/web-app/src/lib/__tests__/model-factory.test.ts@@ -391,6 +391,14 @@ describe('createCustomFetch — max_tokens coercion', () => {expect(sent.cache_prompt).toBeUndefined()})+ // The whole cross-session prompt cache depends on this field surviving the+ // trip to the engine; a filter that dropped it would disable the feature+ // silently, with nothing failing.+ it('passes thread_id through to the request body', async () => {+ const sent = await captureSentBody({ thread_id: 'thread-42' }, true, {})+ expect(sent.thread_id).toBe('thread-42')+ })+it('preserves an explicit id_slot passed via parameters (title-gen path)', async () => {const sent = await captureSentBody({ id_slot: 3 }, true, {})expect(sent.id_slot).toBe(3)diff --git a/web-app/src/lib/__tests__/thread-title-summarizer.test.ts b/web-app/src/lib/__tests__/thread-title-summarizer.test.tsindex df4c9440d..c9108c0d1 100644--- a/web-app/src/lib/__tests__/thread-title-summarizer.test.ts+++ b/web-app/src/lib/__tests__/thread-title-summarizer.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest'import { cleanTitle, generateThreadTitle } from '../thread-title-summarizer'+import { BACKGROUND_SLOT_ID } from '@/constants/models'// Mock AI SDK generateTextconst mockGenerateText = vi.fn()@@ -17,11 +18,12 @@ vi.mock('../model-factory', () => ({// Mock useModelProviderconst mockGetProviderByName = vi.fn()+let mockSelectedProvider = 'test-provider'vi.mock('@/hooks/useModelProvider', () => ({useModelProvider: {getState: () => ({selectedModel: { id: 'test-model' },- selectedProvider: 'test-provider',+ selectedProvider: mockSelectedProvider,getProviderByName: mockGetProviderByName,}),},@@ -104,6 +106,7 @@ describe('generateThreadTitle', () => {beforeEach(() => {vi.clearAllMocks()+ mockSelectedProvider = 'test-provider'mockGetProviderByName.mockReturnValue(mockProvider)mockCreateModel.mockResolvedValue(mockModel)})@@ -127,6 +130,32 @@ describe('generateThreadTitle', () => {)})+ // Upstream wraps an out-of-range id_slot modulo the slot count instead of+ // rejecting it, so a pin derived from the provider-level "Parallel Sequences"+ // value silently resolved to the chat slot 0 whenever the emitted count+ // differed -- which a per-model `parallel` override causes. The pin is a+ // fixed index the preset guarantees exists instead.+ it('pins llamacpp background work to the reserved slot, not a derived index', async () => {+ mockSelectedProvider = 'llamacpp'+ mockGetProviderByName.mockReturnValue({+ provider: 'llamacpp',+ models: [],+ settings: [+ { key: 'parallel', controller_props: { value: 4 } },+ ],+ })+ mockGenerateText.mockResolvedValue({ text: 'Some Title' })++ await generateThreadTitle('hello there', new AbortController().signal)++ expect(mockCreateModel).toHaveBeenCalledWith(+ 'test-model',+ expect.anything(),+ expect.objectContaining({ id_slot: BACKGROUND_SLOT_ID })+ )+ expect(BACKGROUND_SLOT_ID).toBe(1)+ })+it('returns null when aborted', async () => {const abortError = new Error('Aborted')abortError.name = 'AbortError'diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex c0d27eca5..67d6c2a26 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -29,8 +29,7 @@ import {} from '@/lib/webSearchTool'import { useAppState } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'-import { describeEngineError } from '@/lib/engineError'-import { i18n } from '@/i18n/react-i18next-compat'+import { engineFailure } from '@/lib/engineError'import { ExtensionManager } from '@/lib/extension'import { getLlamacppExtension } from '@/lib/llamacppRouterProps'import {@@ -55,6 +54,7 @@ import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'import { isPredefinedRemoteProvider } from '@/lib/providerCaps'import { paramsSettings } from '@/lib/predefinedParams'+import { CHAT_SLOT_ID } from '@/constants/models'export type TokenUsageCallback = (usage: LanguageModelUsage,@@ -100,10 +100,11 @@ const SCHEMA_PRIMITIVE_TYPES = new Set([const SCHEMA_NODE_MAP_KEYS = new Set(['properties', 'patternProperties', 'definitions', '$defs'])const SCHEMA_NODE_LIST_KEYS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems'])-// Per-model sidebar keys whose values should be forwarded into each chat--// completion request body as defaults. In router mode these can't be CLI args-// — the router is one process serving every model — so they have to ride-// along on each call. Assistant `parameters` override these in the merge.+// Per-model sidebar keys forwarded into each chat-completion request body as+// defaults. These *are* also written into the model's own preset section, so+// this is not the only path -- it exists so a sidebar change applies without+// regenerating the preset and reloading the engine. Assistant `parameters`+// override these in the merge.const MODEL_SAMPLING_SETTING_KEYS = ['temperature','top_k',@@ -115,6 +116,26 @@ const MODEL_SAMPLING_SETTING_KEYS = ['frequency_penalty',] as const+/** Keys whose upstream handler throws on a negative value. */+const NON_NEGATIVE_SAMPLING_KEYS = new Set<string>([+ 'repeat_last_n',+ 'dry_penalty_last_n',+])++/**+ * llama.cpp's own defaults for the sampling keys that set the+ * suppress-the-GGUF-recommendation bit. Keys absent here set no bit and are+ * always forwarded.+ */+const UPSTREAM_SAMPLING_DEFAULTS: Record<string, number> = {+ temperature: 0.8,+ top_k: 40,+ top_p: 0.95,+ min_p: 0.05,+ repeat_last_n: 64,+ repeat_penalty: 1.0,+}+function extractModelSamplingDefaults(model: Model | null | undefined): Record<string, unknown> {@@ -125,13 +146,28 @@ function extractModelSamplingDefaults(if (raw === undefined || raw === null || raw === '') continue// Sidebar inputs are string-typed even when controller_props.type is// 'number'; coerce so the request body matches the OpenAI schema.+ let value: unknown = rawif (typeof raw === 'string') {const n = Number(raw)if (!Number.isFinite(n)) continue- out[key] = n- } else {- out[key] = raw+ value = n+ }+ // The server rejects a negative window outright rather than clamping, so a+ // value left over from the old "-1 = full context" UI would 400 every+ // request. Dropping it lets the server's own default apply.+ if (+ NON_NEGATIVE_SAMPLING_KEYS.has(key) &&+ typeof value === 'number' &&+ value < 0+ ) {+ continue}+ // Forwarding a value equal to llama.cpp's default is not a no-op: it sets a+ // bit that suppresses the GGUF's own recommended sampling, so an+ // untouched-looking default would silently override what the model asked+ // for. Same rule preset.ts applies.+ if (UPSTREAM_SAMPLING_DEFAULTS[key] === value) continue+ out[key] = value}return out}@@ -1181,11 +1217,17 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {if (isPredefinedRemoteProvider(effectiveProviderName)) {for (const key of Object.keys(paramsSettings)) delete mergedParams[key]}- // Pin chat to slot 0 so llama-server reuses this thread's cached KV- // prefix across turns; title generation uses the reserved background- // slot (RESERVED_BACKGROUND_SLOTS) and can't evict it.+ // Pin chat to the chat slot so llama-server reuses this thread's cached+ // KV prefix across turns; background tasks use BACKGROUND_SLOT_ID and+ // can't evict it.+ //+ // thread_id names whose cache that is, which is what lets the engine+ // park it when another thread takes the slot and pick it back up later,+ // including in a later session. It is stripped before the request+ // reaches llama.cpp.if (providerId === 'llamacpp') {- mergedParams.id_slot = 0+ mergedParams.id_slot = CHAT_SLOT_ID+ mergedParams.thread_id = threadId}this.model = await this.createModelOrAbort(modelId,@@ -1207,11 +1249,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Preserve AbortError identity so callers/UI can tell a user-initiated// Stop from an actual model-load failure.if (error instanceof Error && error.name === 'AbortError') throw error- throw new Error(- i18n.t('model-errors:createModelFailed', {- reason: describeEngineError(error),- })- )+ throw engineFailure('model-errors:createModelFailed', error)}await this.refreshTools(options.abortSignal)diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.tsindex 365dc10cb..f6f01166e 100644--- a/web-app/src/lib/engineError.ts+++ b/web-app/src/lib/engineError.ts@@ -6,20 +6,13 @@ import { i18n } from '@/i18n/react-i18next-compat'* contract this file matches on.*/export const ENGINE_ERROR_CODES = [- 'BINARY_NOT_FOUND',- 'MODEL_FILE_NOT_FOUND',- 'LIBRARY_PATH_INVALID','MODEL_LOAD_FAILED',- 'DRAFT_MODEL_LOAD_FAILED',- 'MULTIMODAL_PROJECTOR_LOAD_FAILED','MODEL_ARCH_NOT_SUPPORTED','MODEL_LOAD_TIMED_OUT',- 'LLAMA_CPP_PROCESS_ERROR','MISSING_SHARED_LIBRARY','GPU_DRIVER_TOO_OLD','OUT_OF_MEMORY','INVALID_ARGUMENT',- 'DEVICE_LIST_PARSE_FAILED','IO_ERROR','INTERNAL_ERROR',] as const@@ -63,14 +56,33 @@ function readEngineErrorObject(value: unknown): EngineError | undefined {}}+/** `Error.cause` is es2022; the app's lib target predates it. */+function causeOf(error: unknown): unknown {+ return error instanceof Error+ ? (error as Error & { cause?: unknown }).cause+ : undefined+}++/** Depth of `cause` chaining to follow; two wrappers is the deepest real case. */+const MAX_CAUSE_DEPTH = 4+/*** Recovers a structured engine error, including one that an intermediate layer- * already stringified into an Error message.+ * already stringified into an Error message or carried along as a `cause`.*/-export function parseEngineError(error: unknown): EngineError | undefined {+export function parseEngineError(+ error: unknown,+ depth = MAX_CAUSE_DEPTH+): EngineError | undefined {const direct = readEngineErrorObject(error)if (direct) return direct+ const cause = depth > 0 ? causeOf(error) : undefined+ if (cause !== undefined) {+ const fromCause = parseEngineError(cause, depth - 1)+ if (fromCause) return fromCause+ }+const text =error instanceof Error? error.message@@ -90,6 +102,22 @@ export function parseEngineError(error: unknown): EngineError | undefined {}}+/** Enough of the engine's output to name a cause, short enough for a toast. */+const MAX_DETAIL_LENGTH = 240++/**+ * The engine's own words on one line. Untranslatable by nature, and the only+ * part that distinguishes one load failure from another, so it rides along+ * with the localized advice instead of being dropped.+ */+function engineDetail(engineError: EngineError): string | undefined {+ const raw = engineError.details?.replace(/\s+/g, ' ').trim()+ if (!raw) return undefined+ return raw.length > MAX_DETAIL_LENGTH+ ? `${raw.slice(0, MAX_DETAIL_LENGTH).trimEnd()}...`+ : raw+}+/*** A localized, user-facing description of an engine failure. Replaces the raw* English the Rust layer produces, and the raw JSON a serialized error used to@@ -99,13 +127,19 @@ export function describeEngineError(error: unknown): string {const engineError = parseEngineError(error)if (engineError) {- const description = i18n.t(`model-errors:engine.${engineError.code}`)+ const parts = [i18n.t(`model-errors:engine.${engineError.code}`)]if (engineError.missingLibraries?.length) {- return `${description} ${i18n.t('model-errors:engineMissingLibraries', {- libraries: engineError.missingLibraries.join(', '),- })}`+ parts.push(+ i18n.t('model-errors:engineMissingLibraries', {+ libraries: engineError.missingLibraries.join(', '),+ })+ )+ }+ const detail = engineDetail(engineError)+ if (detail) {+ parts.push(i18n.t('model-errors:engineReportedDetail', { detail }))}- return description+ return parts.join(' ')}const fallback =@@ -117,3 +151,16 @@ export function describeEngineError(error: unknown): string {return fallback.trim() || i18n.t('model-errors:engine.unknown')}++/**+ * A localized wrapper that keeps the structured engine error reachable through+ * `cause`. An outer layer then describes the failure from its code once,+ * instead of nesting one localized sentence inside another.+ */+export function engineFailure(messageKey: string, error: unknown): Error {+ const wrapped = new Error(+ i18n.t(messageKey, { reason: describeEngineError(error) })+ ) as Error & { cause?: unknown }+ wrapped.cause = error+ return wrapped+}diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex 882a2a7d0..24399c61b 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -57,6 +57,7 @@ import { createXai } from '@ai-sdk/xai'import { createMistral } from '@ai-sdk/mistral'import { createGoogleGenerativeAI } from '@ai-sdk/google'import { invoke } from '@tauri-apps/api/core'+import { findSessionByModel } from '@janhq/tauri-plugin-llamacpp-api'import { SessionInfo } from '@janhq/core'import { fetch as httpFetch } from '@tauri-apps/plugin-http'import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'@@ -74,7 +75,7 @@ import {getMutualExclusionDrops,getProviderApiType,} from '@/lib/providerCaps'-import { describeEngineError } from '@/lib/engineError'+import { engineFailure } from '@/lib/engineError'import { i18n } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'import { useGeneralSetting } from '@/hooks/useGeneralSetting'@@ -201,6 +202,71 @@ const CLIENT_SIDE_PARAM_KEYS: ReadonlySet<string> = new Set(['auto_compact',])+/**+ * Reconcile `grammar` / `json_schema` with what llama-server actually accepts.+ * The UI can express every combination the server refuses:+ *+ * - `grammar` is rejected whenever the request carries usable tools, and the+ * check is `body.contains("grammar")` (server-common.cpp), so an untouched+ * Grammar row -- default `''` -- 400s a tool-enabled thread on its own.+ * - `json_schema` and `grammar` together are refused outright; the explicit+ * GBNF wins here, since typing one is the more deliberate act.+ * - a schema must be an *object*. The textarea holds a string, which the+ * server dumps and re-parses into a JSON string that every consumer skips+ * over `is_object()`, so the setting silently did nothing.+ *+ * Mutates `body`; llamacpp-only, since the other providers never see these keys.+ */+export function reconcileConstraintParams(body: Record<string, unknown>): void {+ if ('grammar' in body) {+ const grammar = body.grammar+ if (typeof grammar !== 'string' || grammar.trim() === '') {+ delete body.grammar+ }+ }++ if ('json_schema' in body) {+ const raw = body.json_schema+ if (typeof raw === 'string') {+ const trimmed = raw.trim()+ if (trimmed === '') {+ delete body.json_schema+ } else {+ let parsed: unknown+ try {+ parsed = JSON.parse(trimmed)+ } catch (e) {+ console.warn('Ignoring JSON Schema that is not valid JSON:', e)+ delete body.json_schema+ }+ if ('json_schema' in body) {+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ body.json_schema = parsed+ } else {+ console.warn('Ignoring JSON Schema that is not a JSON object')+ delete body.json_schema+ }+ }+ }+ } else if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ delete body.json_schema+ }+ }++ const tools = body.tools+ const toolsUsable =+ Array.isArray(tools) && tools.length > 0 && body.tool_choice !== 'none'+ if (toolsUsable && 'grammar' in body) {+ console.warn('Ignoring the GBNF grammar: llama.cpp refuses one alongside tools')+ delete body.grammar+ }++ if ('grammar' in body && 'json_schema' in body) {+ console.warn('Ignoring the JSON Schema: a GBNF grammar is set and llama.cpp accepts only one')+ delete body.json_schema+ }+}+function filterParameters(parameters: Record<string, unknown>,keepLlamacppOnly: boolean@@ -424,6 +490,7 @@ export function createCustomFetch(// Assert the server default explicitly so a preset/CLI override can't// silently disable prompt-prefix KV reuse across turns.merged.cache_prompt = true+ reconcileConstraintParams(merged)}if (keepLlamacppOnly && merged.stream === true) {merged.return_progress = true@@ -917,19 +984,14 @@ export class ModelFactory {console.error('Failed to start llamacpp model:', error)// A serialized engine error is a plain object, so the previous// `instanceof Error` path stringified it into raw JSON for the user.- throw new Error(- i18n.t('model-errors:startModelFailed', {- reason: describeEngineError(error),- })- )+ // It rides along as `cause` so an outer layer describes the failure+ // once from its code instead of nesting this sentence inside its own.+ throw engineFailure('model-errors:startModelFailed', error)}}// Get session info which includes port and api_key- const sessionInfo = await invoke<SessionInfo | null>(- 'plugin:llamacpp|find_session_by_model',- { modelId }- )+ const sessionInfo = await findSessionByModel(modelId)if (!sessionInfo) {throw new Error(@@ -1004,11 +1066,7 @@ export class ModelFactory {}} catch (error) {console.error('Failed to start MLX model:', error)- throw new Error(- i18n.t('model-errors:startModelFailed', {- reason: describeEngineError(error),- })- )+ throw engineFailure('model-errors:startModelFailed', error)}}@@ -1347,4 +1405,4 @@ export class ModelFactory {}),})}-}+}\ No newline at end of filediff --git a/web-app/src/lib/mtp.test.ts b/web-app/src/lib/mtp.test.tsdeleted file mode 100644index 7ba80dc1d..000000000--- a/web-app/src/lib/mtp.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, it, expect } from 'vitest'-import { isMtpQuant, pickMtpSibling } from './mtp'-import type { ModelQuant } from '@/services/models/types'--const q = (model_id: string, file: string): ModelQuant => ({- model_id,- path: `https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF/resolve/main/${file}`,- file_size: '0',-})--// Mirrors the real gemma-4-26B-A4B-it-GGUF catalog entry.-const GEMMA: ModelQuant[] = [- q('MTP/gemma-4-26B-A4B-it-BF16-MTP', 'gemma-4-26B-A4B-it-BF16-MTP.gguf'),- q('MTP/gemma-4-26B-A4B-it-Q8_0-MTP', 'gemma-4-26B-A4B-it-Q8_0-MTP.gguf'),- q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf'),- q('gemma-4-26B-A4B-it-UD-Q4_K_XL', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf'),- q('mtp-gemma-4-26B-A4B-it', 'mtp-gemma-4-26B-A4B-it.gguf'),-]--describe('isMtpQuant', () => {- it('detects MTP/ model_id prefix', () => {- expect(isMtpQuant(q('MTP/gemma-4-26B-A4B-it-Q8_0-MTP', 'gemma-4-26B-A4B-it-Q8_0-MTP.gguf'))).toBe(true)- })- it('detects mtp- filename prefix', () => {- expect(isMtpQuant(q('mtp-gemma-4-26B-A4B-it', 'mtp-gemma-4-26B-A4B-it.gguf'))).toBe(true)- })- it('detects -MTP / -mtp- filename token', () => {- expect(isMtpQuant(q('x', 'Step3.7-flash-mtp-BF16.gguf'))).toBe(true)- expect(isMtpQuant(q('x', 'gemma-4-26B-A4B-it-BF16-MTP.gguf'))).toBe(true)- })- it('does not flag normal quants', () => {- expect(isMtpQuant(q('gemma-4-26B-A4B-it-UD-Q4_K_XL', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf'))).toBe(false)- expect(isMtpQuant(q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf'))).toBe(false)- })-})--describe('pickMtpSibling', () => {- it('prefers an exact quant match', () => {- const main = q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf')- expect(pickMtpSibling(GEMMA, main)?.model_id).toBe('MTP/gemma-4-26B-A4B-it-Q8_0-MTP')- })- it('falls back to the generic (quant-less) companion', () => {- const main = q('gemma-4-26B-A4B-it-UD-Q4_K_XL', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf')- expect(pickMtpSibling(GEMMA, main)?.model_id).toBe('mtp-gemma-4-26B-A4B-it')- })- it('returns undefined when no companion exists', () => {- const onlyMain = [q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf')]- expect(pickMtpSibling(onlyMain, onlyMain[0])).toBeUndefined()- })-})diff --git a/web-app/src/lib/mtp.ts b/web-app/src/lib/mtp.tsdeleted file mode 100644index ee6c5155a..000000000--- a/web-app/src/lib/mtp.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { ModelQuant } from '@/services/models/types'--// llama.cpp ships some models with a companion "draft" gguf for Multi-Token-// Prediction (speculative decoding via `--spec-type draft-mtp`). In the Jan-// catalog these companions are mixed into the main model's quant list under an-// `MTP/` model_id or an `mtp-` / `-MTP` filename. They are NOT standalone-// models — each pairs with a real quant as its draft model.--const basename = (pathOrId: string): string => {- const file = pathOrId.split('/').pop() ?? pathOrId- return file.replace(/\.gguf$/i, '')-}--// Token marks the file as MTP when "mtp" stands alone (mtp-foo, foo-mtp, foo-MTP).-const MTP_TOKEN = /(^|[-_.])mtp([-_.]|$)/i--const QUANT_TOKEN =- /(iq\d+_\w+|q\d+_k(_\w+)?|q\d+_\d+|q\d+|bf16|fp16|f16|f32|mxfp4(_moe)?|mxfp8|nvfp4|fp8)/gi--export function isMtpQuant(quant: Pick<ModelQuant, 'model_id' | 'path'>): boolean {- if (/^mtp\//i.test(quant.model_id)) return true- return MTP_TOKEN.test(basename(quant.model_id)) || MTP_TOKEN.test(basename(quant.path))-}--// Last quant-like token in the name, normalized (e.g. "...-Q8_0-MTP" -> "q8_0").-function quantLabel(name: string): string | undefined {- const matches = basename(name).match(QUANT_TOKEN)- return matches?.length ? matches[matches.length - 1].toLowerCase() : undefined-}--// Pick the MTP companion that best pairs with the chosen main quant: exact-// quant match wins, then a generic (quant-less) companion, then any companion.-export function pickMtpSibling(- quants: ModelQuant[] | undefined,- mainQuant: Pick<ModelQuant, 'model_id' | 'path'>-): ModelQuant | undefined {- if (!quants?.length) return undefined- const candidates = quants.filter(isMtpQuant)- if (!candidates.length) return undefined-- const mainLabel = quantLabel(mainQuant.path)- if (mainLabel) {- const exact = candidates.find((c) => quantLabel(c.path) === mainLabel)- if (exact) return exact- }- const generic = candidates.find((c) => quantLabel(c.path) === undefined)- return generic ?? candidates[0]-}diff --git a/web-app/src/lib/predefined.ts b/web-app/src/lib/predefined.tsindex 1530f663e..ae42c1e55 100644--- a/web-app/src/lib/predefined.ts+++ b/web-app/src/lib/predefined.ts@@ -15,11 +15,13 @@ export const modelSettings = {key: 'ngl',title: 'GPU Layers',description:- 'Number of model layers to offload to the GPU (-1 for all layers, 0 for CPU only).',+ 'Model layers to keep in VRAM. Leave empty for automatic (VRAM-aware) offload; -1 is auto, -2 offloads all layers, 0 is CPU only.',controller_type: 'input',controller_props: {- value: 100,- placeholder: '100',+ // Empty, not 100: a value here pins offload and defeats llama.cpp's own+ // VRAM-aware auto, which is an OOM on a small GPU.+ value: '',+ placeholder: 'auto',type: 'number',},},@@ -77,12 +79,13 @@ export const modelSettings = {key: 'repeat_last_n',title: 'Repeat Last N',description:- 'Number of tokens to consider for repeat penalty (0 = disabled, -1 = ctx_size). This is the default setting on load and can be overridden by the assistant settings.',+ 'Number of tokens to consider for repeat penalty (0 = disabled). This is the default setting on load and can be overridden by the assistant settings.',controller_type: 'input',controller_props: {value: '',placeholder: '64',type: 'number',+ min: 0,},},repeat_penalty: {diff --git a/web-app/src/lib/predefinedParams.ts b/web-app/src/lib/predefinedParams.tsindex 41f732747..438800378 100644--- a/web-app/src/lib/predefinedParams.ts+++ b/web-app/src/lib/predefinedParams.ts@@ -226,7 +226,8 @@ export const paramsSettings: Record<string, ParamDef> = {grammar: {key: 'grammar',title: 'Grammar (GBNF)',- description: 'GBNF grammar to constrain generations.',+ description:+ 'GBNF grammar to constrain generations. Ignored while tools are enabled, and takes precedence over JSON Schema.',value: '',controllerType: 'textarea',controllerProps: { rows: 4, placeholder: 'root ::= ...' },@@ -235,7 +236,8 @@ export const paramsSettings: Record<string, ParamDef> = {json_schema: {key: 'json_schema',title: 'JSON Schema',- description: 'JSON schema constraining the output to valid JSON.',+ description:+ 'JSON schema constraining the output to valid JSON. Ignored if a grammar is also set.',value: '',controllerType: 'textarea',controllerProps: { rows: 4, placeholder: '{"type":"object", ...}' },@@ -335,10 +337,12 @@ export const paramsSettings: Record<string, ParamDef> = {dry_penalty_last_n: {key: 'dry_penalty_last_n',title: 'DRY Penalty Window',- description: 'Recent-token window DRY scans. -1 = full context, 0 = off.',- value: -1,+ // Upstream throws on a negative window rather than clamping, so the old+ // -1 default made merely enabling this param fail every request.+ description: 'Recent-token window DRY scans. 0 = off.',+ value: 64,controllerType: 'input',- controllerProps: { min: -1, step: 1 },+ controllerProps: { min: 0, step: 1 },capability: 'dry',disabledBy: (v) =>Number(v.dry_multiplier) === 0 ? 'Set DRY Multiplier > 0' : null,@@ -355,10 +359,10 @@ export const paramsSettings: Record<string, ParamDef> = {key: 'repeat_last_n',title: 'Repeat Last N',description:- 'Number of recent tokens considered for the repeat penalty. -1 = full context, 0 = disabled.',+ 'Number of recent tokens considered for the repeat penalty. 0 = disabled.',value: 64,controllerType: 'input',- controllerProps: { min: -1, step: 1 },+ controllerProps: { min: 0, step: 1 },capability: 'repetition',},samplers: {diff --git a/web-app/src/lib/specDraft.test.ts b/web-app/src/lib/specDraft.test.tsnew file mode 100644index 000000000..19a0f28f0--- /dev/null+++ b/web-app/src/lib/specDraft.test.ts@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest'+import { isSpecSidecar, specSidecarKind, pickSpecSibling } from './specDraft'+import type { ModelQuant } from '@/services/models/types'++const q = (model_id: string, file: string): ModelQuant => ({+ model_id,+ path: `https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF/resolve/main/${file}`,+ file_size: '0',+})++// Mirrors the real gemma-4-26B-A4B-it-GGUF catalog entry.+const GEMMA: ModelQuant[] = [+ q('MTP/gemma-4-26B-A4B-it-BF16-MTP', 'gemma-4-26B-A4B-it-BF16-MTP.gguf'),+ q('MTP/gemma-4-26B-A4B-it-Q8_0-MTP', 'gemma-4-26B-A4B-it-Q8_0-MTP.gguf'),+ q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf'),+ q('gemma-4-26B-A4B-it-UD-Q4_K_XL', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf'),+ q('mtp-gemma-4-26B-A4B-it', 'mtp-gemma-4-26B-A4B-it.gguf'),+]++describe('specSidecarKind', () => {+ it('detects MTP/ model_id prefix', () => {+ expect(+ specSidecarKind(+ q('MTP/gemma-4-26B-A4B-it-Q8_0-MTP', 'gemma-4-26B-A4B-it-Q8_0-MTP.gguf')+ )+ ).toBe('mtp')+ })+ it('detects mtp- filename prefix', () => {+ expect(+ specSidecarKind(q('mtp-gemma-4-26B-A4B-it', 'mtp-gemma-4-26B-A4B-it.gguf'))+ ).toBe('mtp')+ })+ it('detects -MTP / -mtp- filename token', () => {+ expect(specSidecarKind(q('x', 'Step3.7-flash-mtp-BF16.gguf'))).toBe('mtp')+ expect(specSidecarKind(q('x', 'gemma-4-26B-A4B-it-BF16-MTP.gguf'))).toBe(+ 'mtp'+ )+ })++ // The prefixes upstream publishes and excludes from gguf_filename_is_model.+ it('detects the other three sidecar flavours', () => {+ expect(specSidecarKind(q('x', 'dflash-DeepSeek-V4-Q4_K_M.gguf'))).toBe(+ 'dflash'+ )+ expect(specSidecarKind(q('x', 'dspark-DeepSeek-V4-Q4_K_M.gguf'))).toBe(+ 'dspark'+ )+ expect(specSidecarKind(q('x', 'eagle3-Llama-3.3-70B-BF16.gguf'))).toBe(+ 'eagle3'+ )+ })++ it('does not flag normal quants', () => {+ expect(+ specSidecarKind(+ q('gemma-4-26B-A4B-it-UD-Q4_K_XL', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf')+ )+ ).toBeUndefined()+ expect(isSpecSidecar(q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf'))).toBe(false)+ })++ // "dflash" as a substring of a word is not a token; a model legitimately+ // named after flash attention must not be mistaken for a draft.+ it('requires a token boundary', () => {+ expect(specSidecarKind(q('x', 'flashmtpish-Q4_K_M.gguf'))).toBeUndefined()+ expect(specSidecarKind(q('x', 'Llama-3-flash-Q4_K_M.gguf'))).toBeUndefined()+ })+})++describe('pickSpecSibling', () => {+ it('prefers an exact quant match', () => {+ const main = q('gemma-4-26B-A4B-it-Q8_0', 'gemma-4-26B-A4B-it-Q8_0.gguf')+ const picked = pickSpecSibling(GEMMA, main)+ expect(picked?.quant.model_id).toBe('MTP/gemma-4-26B-A4B-it-Q8_0-MTP')+ expect(picked?.kind).toBe('mtp')+ })++ it('falls back to the quant-less companion', () => {+ const main = q(+ 'gemma-4-26B-A4B-it-UD-Q4_K_XL',+ 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf'+ )+ expect(pickSpecSibling(GEMMA, main)?.quant.model_id).toBe(+ 'mtp-gemma-4-26B-A4B-it'+ )+ })++ it('returns undefined when the repo ships no companion', () => {+ const plain = [q('foo-Q8_0', 'foo-Q8_0.gguf')]+ expect(pickSpecSibling(plain, plain[0])).toBeUndefined()+ })++ it('reports the kind it picked', () => {+ const main = q('DeepSeek-V4-Q4_K_M', 'DeepSeek-V4-Q4_K_M.gguf')+ const quants = [main, q('x', 'dflash-DeepSeek-V4-Q4_K_M.gguf')]+ expect(pickSpecSibling(quants, main)?.kind).toBe('dflash')+ })++ // arg.cpp resolves a repo shipping several in a fixed order, and DSpark+ // outranks DFlash because its sidecar carries the extra Markov head.+ it('applies upstream precedence when several are present', () => {+ const main = q('DeepSeek-V4-Q4_K_M', 'DeepSeek-V4-Q4_K_M.gguf')+ const both = [+ main,+ q('x', 'dflash-DeepSeek-V4-Q4_K_M.gguf'),+ q('y', 'dspark-DeepSeek-V4-Q4_K_M.gguf'),+ ]+ expect(pickSpecSibling(both, main)?.kind).toBe('dspark')++ const withMtp = [...both, q('z', 'mtp-DeepSeek-V4-Q4_K_M.gguf')]+ expect(pickSpecSibling(withMtp, main)?.kind).toBe('mtp')+ })+})diff --git a/web-app/src/lib/specDraft.ts b/web-app/src/lib/specDraft.tsnew file mode 100644index 000000000..080eb2ac2--- /dev/null+++ b/web-app/src/lib/specDraft.ts@@ -0,0 +1,87 @@+import type { ModelQuant } from '@/services/models/types'++// llama.cpp ships some models with a companion "draft" gguf for speculative+// decoding, passed as `--spec-draft-model` with a matching `--spec-type`. Four+// flavours exist (common/speculative.cpp): multi-token prediction, Eagle3,+// DFlash, and DSpark (DFlash plus a Markov head). Upstream publishes them as+// siblings named with an `mtp-` / `eagle3-` / `dflash-` / `dspark-` prefix and+// excludes all four from its own "is this a model?" test+// (common/download.cpp: gguf_filename_is_model); in the Jan catalog they are+// mixed into the main model's quant list, sometimes under an `MTP/` model_id.+// They are NOT standalone models -- each pairs with a real quant as its draft.++/** The `--spec-type` value a sidecar implies, minus the `draft-` prefix. */+export type SpecKind = 'mtp' | 'eagle3' | 'dflash' | 'dspark'++/**+ * Checked in this order, mirroring how upstream resolves a repo that ships+ * several (common/arg.cpp: MTP first, then DSpark, which outranks DFlash+ * because its sidecar carries the extra Markov head, then Eagle3).+ */+const SPEC_KINDS: SpecKind[] = ['mtp', 'dspark', 'dflash', 'eagle3']++const basename = (pathOrId: string): string => {+ const file = pathOrId.split('/').pop() ?? pathOrId+ return file.replace(/\.gguf$/i, '')+}++// The kind marks the file when it stands alone as a token: dflash-foo,+// foo-dflash, foo-DFlash.+const kindToken = (kind: SpecKind): RegExp =>+ new RegExp(`(^|[-_.])${kind}([-_.]|$)`, 'i')++const QUANT_TOKEN =+ /(iq\d+_\w+|q\d+_k(_\w+)?|q\d+_\d+|q\d+|bf16|fp16|f16|f32|mxfp4(_moe)?|mxfp8|nvfp4|fp8)/gi++/** Which speculative draft a quant is, or undefined for a real model. */+export function specSidecarKind(+ quant: Pick<ModelQuant, 'model_id' | 'path'>+): SpecKind | undefined {+ const id = basename(quant.model_id)+ const file = basename(quant.path)+ for (const kind of SPEC_KINDS) {+ // `MTP/foo` and friends: the catalog groups sidecars under a kind prefix+ // on the model_id, which survives no token boundary once basename'd.+ if (new RegExp(`^${kind}/`, 'i').test(quant.model_id)) return kind+ const token = kindToken(kind)+ if (token.test(id) || token.test(file)) return kind+ }+ return undefined+}++export function isSpecSidecar(+ quant: Pick<ModelQuant, 'model_id' | 'path'>+): boolean {+ return specSidecarKind(quant) !== undefined+}++// Last quant-like token in the name, normalized (e.g. "...-Q8_0-MTP" -> "q8_0").+function quantLabel(name: string): string | undefined {+ const matches = basename(name).match(QUANT_TOKEN)+ return matches?.length ? matches[matches.length - 1].toLowerCase() : undefined+}++/**+ * Pick the draft companion that best pairs with the chosen main quant: the+ * highest-precedence kind present, and within it an exact quant match, then a+ * generic (quant-less) companion, then any.+ */+export function pickSpecSibling(+ quants: ModelQuant[] | undefined,+ mainQuant: Pick<ModelQuant, 'model_id' | 'path'>+): { quant: ModelQuant; kind: SpecKind } | undefined {+ if (!quants?.length) return undefined++ for (const kind of SPEC_KINDS) {+ const candidates = quants.filter((q) => specSidecarKind(q) === kind)+ if (!candidates.length) continue++ const mainLabel = quantLabel(mainQuant.path)+ const exact = mainLabel+ ? candidates.find((c) => quantLabel(c.path) === mainLabel)+ : undefined+ const generic = candidates.find((c) => quantLabel(c.path) === undefined)+ return { quant: exact ?? generic ?? candidates[0], kind }+ }+ return undefined+}diff --git a/web-app/src/lib/thread-title-summarizer.ts b/web-app/src/lib/thread-title-summarizer.tsindex c461a0635..af4c9a281 100644--- a/web-app/src/lib/thread-title-summarizer.ts+++ b/web-app/src/lib/thread-title-summarizer.ts@@ -1,6 +1,7 @@import { generateText } from 'ai'import { ModelFactory } from './model-factory'import { useModelProvider } from '@/hooks/useModelProvider'+import { BACKGROUND_SLOT_ID } from '@/constants/models'const MAX_TITLE_WORDS = 10const MAX_PROMPT_LENGTH = 1500@@ -80,21 +81,16 @@ export async function generateThreadTitle(}console.log('[ThreadTitle] Creating model:', selectedModel.id, 'provider:', selectedProvider)- // Pin to the reserved background slot (RESERVED_BACKGROUND_SLOTS in- // preset.ts) — one index past the user-visible "Parallel Sequences"- // count — so this call can never evict a chat request's KV cache.- // "Parallel Sequences" = 0 means auto (llama.cpp picks its own slot- // count); we can't safely reserve a slot in that case, so skip pinning.+ // Pin to the reserved background slot so this call can never evict a chat+ // request's KV cache. It is a fixed index, not one derived from the+ // "Parallel Sequences" setting: upstream wraps an out-of-range id_slot+ // modulo the slot count instead of rejecting it, so a pin computed from the+ // provider-level value silently landed back on slot 0 whenever the emitted+ // count disagreed -- which a per-model `parallel` override does.const params: Record<string, unknown> = {}if (selectedProvider === 'llamacpp') {params.chat_template_kwargs = { enable_thinking: false }- const userParallel = Number(- provider.settings?.find((s) => s.key === 'parallel')?.controller_props- ?.value ?? 1- )- if (Number.isFinite(userParallel) && userParallel > 0) {- params.id_slot = userParallel- }+ params.id_slot = BACKGROUND_SLOT_ID}const model = await ModelFactory.createModel(selectedModel.id,diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex 468bcdb31..26b181835 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -30,7 +30,6 @@ const DYNAMIC_KEYS: Record<string, string[]> = {'checkEngineCpu','checkEngineGpuUnused','checkEngineVendorMismatch',- 'checkEngineNoGpuHardware','checkEngineRuntimeUnreachable','checkEngineMissingLibrary','checkEngineProbeFailed',@@ -44,20 +43,13 @@ const DYNAMIC_KEYS: Record<string, string[]> = {],'model-errors': ['engine.unknown',- 'engine.BINARY_NOT_FOUND',- 'engine.MODEL_FILE_NOT_FOUND',- 'engine.LIBRARY_PATH_INVALID','engine.MODEL_LOAD_FAILED',- 'engine.DRAFT_MODEL_LOAD_FAILED',- 'engine.MULTIMODAL_PROJECTOR_LOAD_FAILED','engine.MODEL_ARCH_NOT_SUPPORTED','engine.MODEL_LOAD_TIMED_OUT',- 'engine.LLAMA_CPP_PROCESS_ERROR','engine.MISSING_SHARED_LIBRARY','engine.GPU_DRIVER_TOO_OLD','engine.OUT_OF_MEMORY','engine.INVALID_ARGUMENT',- 'engine.DEVICE_LIST_PARSE_FAILED','engine.IO_ERROR','engine.INTERNAL_ERROR',],diff --git a/web-app/src/locales/ca/settings.json b/web-app/src/locales/ca/settings.jsonindex 177bd1d65..4476e50e3 100644--- a/web-app/src/locales/ca/settings.json+++ b/web-app/src/locales/ca/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Ja utilitzes l’última versió","devVersion": "S’ha detectat la versió de desenvolupament","updateError": "No s’han pogut cercar actualitzacions",- "checkForBackendUpdates": "Cerca actualitzacions de Llamacpp",- "checkForBackendUpdatesDesc": "Comprova si hi ha una versió més recent del backend Llamacpp.",- "checkingForBackendUpdates": "S’estan cercant actualitzacions de Llamacpp...",- "noBackendUpdateAvailable": "Ja utilitzes l’última versió de Llamacpp",- "backendUpdateError": "No s’han pogut cercar actualitzacions de Llamacpp","changeLocation": "Canvia la ubicació","copied": "Copiat","copyPath": "Copia el camí",@@ -308,15 +303,6 @@"changeLocation": "Canvia la ubicació"}},- "backendUpdater": {- "newBackendVersion": "Nova versió de Llamacpp {{version}}",- "backendUpdateAvailable": "Actualització de Llamacpp disponible",- "remindMeLater": "Recorda-m’ho més tard",- "updating": "S’està actualitzant...",- "updateNow": "Actualitza ara",- "updateSuccess": "Llamacpp s’ha actualitzat correctament",- "updateError": "No s’ha pogut actualitzar Llamacpp"- },"backendInstallSuccess": "El backend s’ha instal·lat correctament","backendInstallError": "No s’ha pogut instal·lar el backend"}diff --git a/web-app/src/locales/cs/settings.json b/web-app/src/locales/cs/settings.jsonindex 7cec50757..58cb29102 100644--- a/web-app/src/locales/cs/settings.json+++ b/web-app/src/locales/cs/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Používáte nejnovější verzi","devVersion": "Detekována vývojová verze","updateError": "Nepodařilo se zkontrolovat aktualizace",- "checkForBackendUpdates": "Zkontrolovat aktualizace Llamacpp",- "checkForBackendUpdatesDesc": "Zkontrolujte, zda je k dispozici novější verze backendu Llamacpp.",- "checkingForBackendUpdates": "Kontrolování aktualizací Llamacpp...",- "noBackendUpdateAvailable": "Používáte nejnovější verzi Llamacpp",- "backendUpdateError": "Nepodařilo se zkontrolovat aktualizace Llamacpp","changeLocation": "Změnit umístění","copied": "Zkopírováno","copyPath": "Kopírovat cestu",@@ -298,15 +293,6 @@"changeLocation": "Změnit umístění"}},- "backendUpdater": {- "newBackendVersion": "Nová verze Llamacpp {{version}}",- "backendUpdateAvailable": "Dostupná aktualizace Llamacpp",- "remindMeLater": "Připomenout později",- "updating": "Aktualizování...",- "updateNow": "Aktualizovat nyní",- "updateSuccess": "Llamacpp úspěšně aktualizován",- "updateError": "Nepodařilo se aktualizovat Llamacpp"- },"backendInstallSuccess": "Backend úspěšně nainstalován","backendInstallError": "Nepodařilo se nainstalovat backend"}diff --git a/web-app/src/locales/de-DE/settings.json b/web-app/src/locales/de-DE/settings.jsonindex 2a61fa8ff..57651d5c6 100644--- a/web-app/src/locales/de-DE/settings.json+++ b/web-app/src/locales/de-DE/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Du verwendest die neueste Version","devVersion": "Entwicklungsversion erkannt","updateError": "Fehler beim Suchen nach Updates",- "checkForBackendUpdates": "Llamacpp Updates prüfen",- "checkForBackendUpdatesDesc": "Prüfe, ob eine neuere Version des Llamacpp-Backends verfügbar ist.",- "checkingForBackendUpdates": "Suche nach Llamacpp Updates...",- "noBackendUpdateAvailable": "Du verwendest die neueste Llamacpp Version",- "backendUpdateError": "Fehler beim Suchen nach Llamacpp Updates","changeLocation": "Ort ändern","copied": "Kopiert","copyPath": "Pfad kopieren",@@ -268,15 +263,6 @@"changeLocation": "Ort ändern"}},- "backendUpdater": {- "newBackendVersion": "Neue Llamacpp Version {{version}}",- "backendUpdateAvailable": "Llamacpp Update verfügbar",- "remindMeLater": "Später erinnern",- "updating": "Aktualisiere...",- "updateNow": "Jetzt aktualisieren",- "updateSuccess": "Llamacpp erfolgreich aktualisiert",- "updateError": "Fehler beim Aktualisieren von Llamacpp"- },"backendInstallSuccess": "Backend erfolgreich installiert","backendInstallError": "Backend-Installation fehlgeschlagen"}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 74ee66a7f..404a09882 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -254,11 +254,10 @@"title": "Default sampling parameters","description": "Default sampler settings for this model. Used unless overridden by per-assistant or per-request values."},- "mtp": {- "section": "Multi-Token Prediction (MTP)",- "enable": "Enable MTP",- "enableDescription": "Use the model's built-in MTP heads to draft multiple tokens per step. Speeds up generation when the model has MTP weights (DeepSeek-V3, GLM-4.5/4.6, MiMo v2.5, …).",- "needsUpgrade": "Update the llama.cpp backend to build b9193 or newer to enable MTP.",+ "specDraft": {+ "section": "Speculative decoding",+ "enable": "Enable speculative decoding",+ "enableDescription": "Draft several tokens per step and verify them in one pass, which speeds up generation. Uses the model's built-in MTP heads, or the draft model downloaded with it (MTP, Eagle3, DFlash or DSpark).","nMax": "Max draft tokens","nMaxDescription": "Maximum number of tokens to draft per step. Default 16.","nMin": "Min draft tokens",diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.jsonindex 92bf79bbb..dc88ceb1b 100644--- a/web-app/src/locales/en/model-errors.json+++ b/web-app/src/locales/en/model-errors.json@@ -9,24 +9,18 @@"contextOverflowGeneric": "The request exceeds the available context size.","engine": {"unknown": "The model engine reported an unexpected error.",- "BINARY_NOT_FOUND": "The engine program is missing. Reinstalling the engine from Settings should restore it.",- "MODEL_FILE_NOT_FOUND": "The model file could not be found. It may have been moved or deleted.",- "LIBRARY_PATH_INVALID": "The engine's library folder is invalid. Reinstalling the engine from Settings should restore it.","MODEL_LOAD_FAILED": "The model could not be loaded.",- "DRAFT_MODEL_LOAD_FAILED": "The draft model could not be loaded. Turning off speculative decoding will let the main model run.",- "MULTIMODAL_PROJECTOR_LOAD_FAILED": "The vision component of this model could not be loaded, so images will not work.","MODEL_ARCH_NOT_SUPPORTED": "This model's architecture is not supported by the current engine. Updating the engine from Settings may add support.","MODEL_LOAD_TIMED_OUT": "The model took too long to load and was stopped. A smaller model or a smaller context size usually helps.",- "LLAMA_CPP_PROCESS_ERROR": "The model process stopped unexpectedly.","MISSING_SHARED_LIBRARY": "A library the engine needs is missing, so it cannot start.","GPU_DRIVER_TOO_OLD": "Your GPU driver is too old for this engine. Updating the driver, or switching to the CPU engine in Settings, will fix this.","OUT_OF_MEMORY": "There is not enough memory to run this model. A smaller model or a smaller context size usually helps.","INVALID_ARGUMENT": "One of the model's settings is not valid.",- "DEVICE_LIST_PARSE_FAILED": "Jan could not read the list of available devices from the engine.","IO_ERROR": "A file could not be read or written while starting the model.","INTERNAL_ERROR": "Something went wrong inside Jan while starting the model."},"engineMissingLibraries": "Missing: {{libraries}}",+ "engineReportedDetail": "The engine reported: {{detail}}","startModelFailed": "Failed to start model: {{reason}}","createModelFailed": "Failed to create model: {{reason}}","noRunningSession": "No running session found for model: {{model}}",diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 74614c9b6..8c9886c26 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "You're running the latest version","devVersion": "Development version detected","updateError": "Failed to check for updates",- "checkForBackendUpdates": "Check for Llamacpp updates",- "checkForBackendUpdatesDesc": "Check if a newer version of the Llamacpp backend is available.",- "checkingForBackendUpdates": "Checking for Llamacpp updates...",- "noBackendUpdateAvailable": "You're running the latest Llamacpp version",- "backendUpdateError": "Failed to check for Llamacpp updates","changeLocation": "Change Location","copied": "Copied","copyPath": "Copy Path",@@ -348,20 +343,6 @@"changeLocation": "Change Location"}},- "backendUpdater": {- "newBackendVersion": "New Llamacpp Version {{version}}",- "backendUpdateAvailable": "Llamacpp Update Available",- "remindMeLater": "Remind Me Later",- "updating": "Updating...",- "updateNow": "Update Now",- "updateSuccess": "Llamacpp updated successfully",- "updateError": "Failed to update Llamacpp"- },"backendInstallSuccess": "Backend installed successfully!",- "backendInstallError": "Failed to install backend",- "installBackendFromFile": "Install Backend from File",- "installingBackend": "Installing Backend...",- "installCudaRuntime": "Install CUDA Runtime",- "installingCudaRuntime": "Installing CUDA Runtime...",- "cudaRuntimeInstalled": "CUDA runtime installed"+ "backendInstallError": "Failed to install backend"}diff --git a/web-app/src/locales/en/setup.json b/web-app/src/locales/en/setup.jsonindex 6faf669db..44c899120 100644--- a/web-app/src/locales/en/setup.json+++ b/web-app/src/locales/en/setup.json@@ -17,17 +17,16 @@"checkSystemGpuNoDriver": "{{gpus}}","checkSystemCpuOnly": "{{cpu}}, no GPU detected","checkSystemFailed": "Could not read hardware details",- "checkEnginePreparing": "Downloading and setting up the inference engine...",+ "checkEnginePreparing": "Preparing the inference engine...","checkEngineGpu": "{{backend}}","checkEngineCpu": "{{backend}}, running on CPU","checkEngineGpuUnused": "{{backend}} is a CPU-only build, so {{gpus}} will sit idle. Pick a GPU backend in Settings to use it.","checkEngineVendorMismatch": "{{backend}} needs an {{vendor}} GPU, but Jan found {{gpus}}. Jan will run on CPU.",- "checkEngineNoGpuHardware": "{{backend}} is a GPU build, but no GPU was found. Jan will run on CPU, which is slower.","checkEngineRuntimeUnreachable": "{{backend}} cannot reach your GPU, so Jan will run on CPU. This usually means the GPU driver or runtime needs updating.","checkEngineMissingLibrary": "{{backend}} cannot start because a required library is missing ({{libraries}}), so Jan will run on CPU.","checkEngineProbeFailed": "Could not confirm the engine can use your GPU","checkEngineUnavailable": "This engine build cannot report GPU status",- "checkSearchPreparing": "Waiting for the engine before checking the embedding model...",+ "checkSearchPreparing": "Downloading the embedding model...","checkSearchReady": "{{model}}, {{dimension}} dimensions","checkSearchNoVector": "The embedding model returned no result, so file search will not work yet","checkSearchInvalidVector": "The embedding model returned an unusable result, so file search may return nothing",@@ -43,7 +42,7 @@"welcomeTitle": "Jan needs to set up on your system","welcomeBody": "This takes a few minutes: Jan downloads its inference engine and a small model for file search. You can keep using your computer while it runs.","startSetup": "Let's start",- "stageSetup": "Setting up llama.cpp",+ "stageSetup": "Setting up the local engine","badgeGpu": "Will use your GPU","badgeCpu": "Will run on CPU","badgeGpuUnknown": "Checking GPU support...",diff --git a/web-app/src/locales/es/settings.json b/web-app/src/locales/es/settings.jsonindex b4becd998..14732ac84 100644--- a/web-app/src/locales/es/settings.json+++ b/web-app/src/locales/es/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Estás usando la última versión","devVersion": "Versión de desarrollo detectada","updateError": "Error al buscar actualizaciones",- "checkForBackendUpdates": "Buscar actualizaciones de Llamacpp",- "checkForBackendUpdatesDesc": "Verifica si hay una versión más reciente del backend Llamacpp disponible.",- "checkingForBackendUpdates": "Buscando actualizaciones de Llamacpp...",- "noBackendUpdateAvailable": "Estás usando la última versión de Llamacpp",- "backendUpdateError": "Error al buscar actualizaciones de Llamacpp","changeLocation": "Cambiar ubicación","copied": "Copiado","copyPath": "Copiar ruta",@@ -313,15 +308,6 @@"changeLocation": "Cambiar ubicación"}},- "backendUpdater": {- "newBackendVersion": "Nueva versión de Llamacpp {{version}}",- "backendUpdateAvailable": "Actualización de Llamacpp disponible",- "remindMeLater": "Recordar más tarde",- "updating": "Actualizando...",- "updateNow": "Actualizar ahora",- "updateSuccess": "Llamacpp actualizado correctamente",- "updateError": "Error al actualizar Llamacpp"- },"backendInstallSuccess": "¡OpenClaw instalado correctamente!","backendInstallError": "Error al instalar el backend","remoteAccess": {diff --git a/web-app/src/locales/fr/settings.json b/web-app/src/locales/fr/settings.jsonindex fe1f90c02..c72943fb0 100644--- a/web-app/src/locales/fr/settings.json+++ b/web-app/src/locales/fr/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Vous utilisez la dernière version","devVersion": "Version de développement détectée","updateError": "Échec de la vérification des mises à jour",- "checkForBackendUpdates": "Vérifier les mises à jour de Llamacpp",- "checkForBackendUpdatesDesc": "Vérifiez si une nouvelle version du backend Llamacpp est disponible.",- "checkingForBackendUpdates": "Vérification des mises à jour de Llamacpp...",- "noBackendUpdateAvailable": "Vous utilisez la dernière version de Llamacpp",- "backendUpdateError": "Échec de la vérification des mises à jour de Llamacpp","changeLocation": "Changer l'emplacement","copied": "Copié","copyPath": "Copier le chemin",@@ -306,15 +301,6 @@"changeLocation": "Changer l'emplacement"}},- "backendUpdater": {- "newBackendVersion": "Nouvelle version de Llamacpp {{version}}",- "backendUpdateAvailable": "Mise à jour de Llamacpp disponible",- "remindMeLater": "Me le rappeler plus tard",- "updating": "Mise à jour...",- "updateNow": "Mettre à jour maintenant",- "updateSuccess": "Llamacpp mis à jour avec succès",- "updateError": "Échec de la mise à jour de Llamacpp"- },"backendInstallSuccess": "Backend installé avec succès","backendInstallError": "Échec de l'installation du backend"}diff --git a/web-app/src/locales/hi/settings.json b/web-app/src/locales/hi/settings.jsonindex 6323f2bb2..a18bde50c 100644--- a/web-app/src/locales/hi/settings.json+++ b/web-app/src/locales/hi/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "आप नवीनतम संस्करण का उपयोग कर रहे हैं","devVersion": "डेवलपमेंट संस्करण पाया गया","updateError": "अपडेट्स जांचने में त्रुटि",- "checkForBackendUpdates": "Llamacpp अपडेट्स जांचें",- "checkForBackendUpdatesDesc": "देखें कि Llamacpp बैकएंड का कोई नया संस्करण उपलब्ध है या नहीं।",- "checkingForBackendUpdates": "Llamacpp अपडेट्स की जांच हो रही है...",- "noBackendUpdateAvailable": "आप Llamacpp के नवीनतम संस्करण का उपयोग कर रहे हैं",- "backendUpdateError": "Llamacpp अपडेट्स जांचने में त्रुटि","changeLocation": "स्थान बदलें","copied": "कॉपी किया गया","copyPath": "पथ कॉपी करें",@@ -313,15 +308,6 @@"changeLocation": "स्थान बदलें"}},- "backendUpdater": {- "newBackendVersion": "Llamacpp का नया संस्करण {{version}}",- "backendUpdateAvailable": "Llamacpp अपडेट उपलब्ध है",- "remindMeLater": "बाद में याद दिलाएं",- "updating": "अपडेट हो रहा है...",- "updateNow": "अभी अपडेट करें",- "updateSuccess": "Llamacpp सफलतापूर्वक अपडेट हुआ",- "updateError": "Llamacpp अपडेट करने में त्रुटि"- },"backendInstallSuccess": "OpenClaw सफलतापूर्वक इंस्टॉल हो गया!","backendInstallError": "बैकएंड इंस्टॉल करने में त्रुटि","remoteAccess": {diff --git a/web-app/src/locales/id/settings.json b/web-app/src/locales/id/settings.jsonindex 2a189541d..79ef096f4 100644--- a/web-app/src/locales/id/settings.json+++ b/web-app/src/locales/id/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Anda menjalankan versi terbaru","devVersion": "Versi pengembangan terdeteksi","updateError": "Gagal memeriksa pembaruan",- "checkForBackendUpdates": "Periksa Pembaruan Llamacpp",- "checkForBackendUpdatesDesc": "Periksa apakah versi backend Llamacpp yang lebih baru tersedia.",- "checkingForBackendUpdates": "Memeriksa pembaruan Llamacpp...",- "noBackendUpdateAvailable": "Anda menjalankan versi Llamacpp terbaru",- "backendUpdateError": "Gagal memeriksa pembaruan Llamacpp","changeLocation": "Ubah Lokasi","copied": "Tersalin","copyPath": "Salin Jalur",@@ -268,15 +263,6 @@"changeLocation": "Ubah Lokasi"}},- "backendUpdater": {- "newBackendVersion": "Versi Llamacpp Baru {{version}}",- "backendUpdateAvailable": "Pembaruan Llamacpp Tersedia",- "remindMeLater": "Ingatkan Saya Nanti",- "updating": "Memperbarui...",- "updateNow": "Perbarui Sekarang",- "updateSuccess": "Llamacpp berhasil diperbarui",- "updateError": "Gagal memperbarui Llamacpp"- },"backendInstallSuccess": "Backend berhasil diinstal","backendInstallError": "Gagal menginstal backend"}diff --git a/web-app/src/locales/it/common.json b/web-app/src/locales/it/common.jsonindex 5533d0b1c..b83ac6de9 100644--- a/web-app/src/locales/it/common.json+++ b/web-app/src/locales/it/common.json@@ -239,11 +239,7 @@"nglDisabledByFit": "Auto-fit is choosing GPU layers. Turn off Auto-fit to set this manually.","title": "Impostazioni modello - {{modelId}}","description": "Configura le impostazioni del modello per ottimizzarne le prestazioni e il comportamento.",- "mtp": {- "section": "Multi-Token Prediction (MTP)",- "enable": "Abilita MTP",- "enableDescription": "Usa le testine MTP integrate del modello per generare una bozza di più token per passaggio. Velocizza la generazione quando il modello dispone di pesi MTP (DeepSeek-V3, GLM-4.5/4.6, MiMo v2.5, …).",- "needsUpgrade": "Aggiorna il backend llama.cpp alla build b9193 o successiva per abilitare l'MTP.",+ "specDraft": {"nMax": "Numero massimo token bozza","nMaxDescription": "Numero massimo di token da abbozzare per passaggio. Predefinito: 16.","nMin": "Numero minimo token bozza",diff --git a/web-app/src/locales/it/settings.json b/web-app/src/locales/it/settings.jsonindex 7ca8ad530..d19e027b0 100644--- a/web-app/src/locales/it/settings.json+++ b/web-app/src/locales/it/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Stai utilizzando l'ultima versione","devVersion": "Rilevata versione di sviluppo","updateError": "Impossibile verificare gli aggiornamenti",- "checkForBackendUpdates": "Verifica aggiornamenti Llamacpp",- "checkForBackendUpdatesDesc": "Controlla se è disponibile una versione più recente del backend Llamacpp.",- "checkingForBackendUpdates": "Verifica aggiornamenti Llamacpp in corso...",- "noBackendUpdateAvailable": "Stai utilizzando l'ultima versione di Llamacpp",- "backendUpdateError": "Impossibile verificare gli aggiornamenti di Llamacpp","changeLocation": "Modifica posizione","copied": "Copiato","copyPath": "Copia percorso",@@ -319,15 +314,6 @@"changeLocation": "Modifica posizione"}},- "backendUpdater": {- "newBackendVersion": "Nuova versione Llamacpp {{version}}",- "backendUpdateAvailable": "Aggiornamento Llamacpp disponibile",- "remindMeLater": "Ricordamelo più tardi",- "updating": "Aggiornamento in corso...",- "updateNow": "Aggiorna ora",- "updateSuccess": "Llamacpp aggiornato con successo",- "updateError": "Impossibile aggiornare Llamacpp"- },"backendInstallSuccess": "Backend installato con successo!","backendInstallError": "Impossibile installare il backend"}diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex d2ee83b24..f5128f991 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -251,11 +251,7 @@"title": "デフォルトのサンプリングパラメータ","description": "このモデルのデフォルトのサンプラー設定です。アシスタントごとまたはリクエストごとの値で上書きされない限り使用されます。"},- "mtp": {- "section": "マルチトークン予測 (MTP)",- "enable": "MTPを有効にする",- "enableDescription": "モデルに内蔵されたMTPヘッドを使用して、ステップごとに複数のトークンを下書きします。モデルにMTPの重みがある場合(DeepSeek-V3、GLM-4.5/4.6、MiMo v2.5 など)、生成が高速化されます。",- "needsUpgrade": "MTPを有効にするには、llama.cppバックエンドをビルドb9193以降に更新してください。",+ "specDraft": {"nMax": "最大下書きトークン数","nMaxDescription": "ステップごとに下書きするトークンの最大数。デフォルトは16です。","nMin": "最小下書きトークン数",diff --git a/web-app/src/locales/ja/settings.json b/web-app/src/locales/ja/settings.jsonindex 844337d8f..43e572723 100644--- a/web-app/src/locales/ja/settings.json+++ b/web-app/src/locales/ja/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "最新バージョンを実行しています","devVersion": "開発バージョンが検出されました","updateError": "アップデートの確認に失敗しました",- "checkForBackendUpdates": "Llamacppのアップデートを確認",- "checkForBackendUpdatesDesc": "Llamacppバックエンドの新しいバージョンが利用可能かどうかを確認します。",- "checkingForBackendUpdates": "Llamacppのアップデートを確認中...",- "noBackendUpdateAvailable": "最新のLlamacppバージョンを実行しています",- "backendUpdateError": "Llamacppのアップデートの確認に失敗しました","changeLocation": "場所を変更","copied": "コピーしました","copyPath": "パスをコピー",@@ -331,20 +326,6 @@"changeLocation": "場所を変更"}},- "backendUpdater": {- "newBackendVersion": "新しいLlamacppバージョン {{version}}",- "backendUpdateAvailable": "Llamacppのアップデートが利用可能です",- "remindMeLater": "後で通知",- "updating": "更新中...",- "updateNow": "今すぐ更新",- "updateSuccess": "Llamacppは正常に更新されました",- "updateError": "Llamacppの更新に失敗しました"- },"backendInstallSuccess": "バックエンドは正常にインストールされました",- "backendInstallError": "バックエンドのインストールに失敗しました",- "installBackendFromFile": "ファイルからバックエンドをインストール",- "installingBackend": "バックエンドをインストール中...",- "installCudaRuntime": "CUDAランタイムをインストール",- "installingCudaRuntime": "CUDAランタイムをインストール中...",- "cudaRuntimeInstalled": "CUDAランタイムをインストールしました"+ "backendInstallError": "バックエンドのインストールに失敗しました"}diff --git a/web-app/src/locales/ko/settings.json b/web-app/src/locales/ko/settings.jsonindex 63d929974..adbc4a541 100644--- a/web-app/src/locales/ko/settings.json+++ b/web-app/src/locales/ko/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "최신 버전을 사용 중입니다","devVersion": "개발 버전이 감지되었습니다","updateError": "업데이트 확인 실패",- "checkForBackendUpdates": "Llamacpp 업데이트 확인",- "checkForBackendUpdatesDesc": "새 버전의 Llamacpp 백엔드가 있는지 확인합니다.",- "checkingForBackendUpdates": "Llamacpp 업데이트 확인 중...",- "noBackendUpdateAvailable": "최신 버전의 Llamacpp를 사용 중입니다",- "backendUpdateError": "Llamacpp 업데이트 확인 실패","changeLocation": "위치 변경","copied": "복사됨","copyPath": "경로 복사",@@ -313,15 +308,6 @@"changeLocation": "위치 변경"}},- "backendUpdater": {- "newBackendVersion": "새로운 Llamacpp 버전 {{version}}",- "backendUpdateAvailable": "Llamacpp 업데이트 가능",- "remindMeLater": "나중에 알림",- "updating": "업데이트 중...",- "updateNow": "지금 업데이트",- "updateSuccess": "Llamacpp 업데이트 성공",- "updateError": "Llamacpp 업데이트 실패"- },"backendInstallSuccess": "OpenClaw가 성공적으로 설치되었습니다!","backendInstallError": "백엔드 설치 실패","remoteAccess": {diff --git a/web-app/src/locales/pl/settings.json b/web-app/src/locales/pl/settings.jsonindex 45c659b02..45a3458ab 100644--- a/web-app/src/locales/pl/settings.json+++ b/web-app/src/locales/pl/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Używasz najnowszej wersji","devVersion": "Wykryto wersję deweloperską","updateError": "Nie udało się sprawdzić dostępności aktualizacji",- "checkForBackendUpdates": "Sprawdź Aktualizacje Llamacpp",- "checkForBackendUpdatesDesc": "Sprawdza czy dostępna jest nowa wersja backendu Llamacpp.",- "checkingForBackendUpdates": "Sprawdzanie aktualizacji Llamacpp...",- "noBackendUpdateAvailable": "Używasz najnowszej wersji Llamacpp",- "backendUpdateError": "Nie udało się sprawdzić aktualizacji Llamacpp","changeLocation": "Zmień Położenie","copied": "Skopiowano","copyPath": "Skopiuj Ścieżkę",@@ -268,15 +263,6 @@"changeLocation": "Zmień Położenie"}},- "backendUpdater": {- "newBackendVersion": "Nowa wersja Llamacpp {{version}}",- "backendUpdateAvailable": "Dostępna aktualizacja Llamacpp",- "remindMeLater": "Przypomnij mi później",- "updating": "Aktualizowanie...",- "updateNow": "Aktualizuj teraz",- "updateSuccess": "Llamacpp został pomyślnie zaktualizowany",- "updateError": "Nie udało się zaktualizować Llamacpp"- },"backendInstallSuccess": "Backend został pomyślnie zainstalowany","backendInstallError": "Nie udało się zainstalować backendu"}diff --git a/web-app/src/locales/pt-BR/settings.json b/web-app/src/locales/pt-BR/settings.jsonindex 33395a14b..a7b11df45 100644--- a/web-app/src/locales/pt-BR/settings.json+++ b/web-app/src/locales/pt-BR/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Você está executando a versão mais recente","devVersion": "Versão de desenvolvimento detectada","updateError": "Falha ao verificar atualizações",- "checkForBackendUpdates": "Verificar Atualizações do Llamacpp",- "checkForBackendUpdatesDesc": "Verificar se uma versão mais nova do backend Llamacpp está disponível.",- "checkingForBackendUpdates": "Verificando atualizações do Llamacpp...",- "noBackendUpdateAvailable": "Você está executando a versão mais recente do Llamacpp",- "backendUpdateError": "Falha ao verificar atualizações do Llamacpp","changeLocation": "Alterar Localização","copied": "Copiado","copyPath": "Copiar Caminho",@@ -300,15 +295,6 @@"changeLocation": "Alterar Localização"}},- "backendUpdater": {- "newBackendVersion": "Nova Versão Llamacpp {{version}}",- "backendUpdateAvailable": "Atualização Llamacpp Disponível",- "remindMeLater": "Lembre-me Mais Tarde",- "updating": "Atualizando...",- "updateNow": "Atualizar Agora",- "updateSuccess": "Llamacpp atualizado com sucesso",- "updateError": "Falha ao atualizar Llamacpp"- },"backendInstallSuccess": "Backend instalado com sucesso","backendInstallError": "Falha ao instalar backend"}diff --git a/web-app/src/locales/ru/settings.json b/web-app/src/locales/ru/settings.jsonindex bf298c787..f69516fad 100644--- a/web-app/src/locales/ru/settings.json+++ b/web-app/src/locales/ru/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Вы используете последнюю версию","devVersion": "Обнаружена версия для разработки","updateError": "Не удалось проверить наличие обновлений",- "checkForBackendUpdates": "Проверить обновления Llamacpp",- "checkForBackendUpdatesDesc": "Проверить, доступна ли более новая версия компонента Llamacpp.",- "checkingForBackendUpdates": "Проверка обновлений Llamacpp...",- "noBackendUpdateAvailable": "Вы используете последнюю версию Llamacpp",- "backendUpdateError": "Не удалось проверить обновления Llamacpp","changeLocation": "Изменить расположение","copied": "Скопировано","copyPath": "Копировать путь",@@ -306,15 +301,6 @@"changeLocation": "Изменить расположение"}},- "backendUpdater": {- "newBackendVersion": "Новая версия Llamacpp {{version}}",- "backendUpdateAvailable": "Доступно обновление Llamacpp",- "remindMeLater": "Отложить",- "updating": "Обновление…",- "updateNow": "Обновить",- "updateSuccess": "Llamacpp успешно обновлено",- "updateError": "Не удалось обновить Llamacpp"- },"backendInstallSuccess": "Компонент успешно установлен","backendInstallError": "Не удалось установить компонент"}diff --git a/web-app/src/locales/vn/settings.json b/web-app/src/locales/vn/settings.jsonindex 19a1de3f6..f1a067188 100644--- a/web-app/src/locales/vn/settings.json+++ b/web-app/src/locales/vn/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "Bạn đang chạy phiên bản mới nhất","devVersion": "Đã phát hiện phiên bản phát triển","updateError": "Không thể kiểm tra cập nhật",- "checkForBackendUpdates": "Kiểm tra Cập nhật Llamacpp",- "checkForBackendUpdatesDesc": "Kiểm tra xem có phiên bản backend Llamacpp mới hơn không.",- "checkingForBackendUpdates": "Đang kiểm tra cập nhật Llamacpp...",- "noBackendUpdateAvailable": "Bạn đang chạy phiên bản Llamacpp mới nhất",- "backendUpdateError": "Không thể kiểm tra cập nhật Llamacpp","changeLocation": "Thay đổi Vị trí","copied": "Đã sao chép","copyPath": "Sao chép Đường dẫn",@@ -268,15 +263,6 @@"changeLocation": "Thay đổi vị trí"}},- "backendUpdater": {- "newBackendVersion": "Phiên bản Llamacpp mới {{version}}",- "backendUpdateAvailable": "Có cập nhật Llamacpp",- "remindMeLater": "Nhắc tôi sau",- "updating": "Đang cập nhật...",- "updateNow": "Cập nhật ngay",- "updateSuccess": "Cập nhật Llamacpp thành công",- "updateError": "Không thể cập nhật Llamacpp"- },"backendInstallSuccess": "Backend đã được cài đặt thành công","backendInstallError": "Không thể cài đặt backend"}diff --git a/web-app/src/locales/zh-CN/settings.json b/web-app/src/locales/zh-CN/settings.jsonindex 26f12cbf8..33c0ee50d 100644--- a/web-app/src/locales/zh-CN/settings.json+++ b/web-app/src/locales/zh-CN/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "您正在运行最新版本","devVersion": "检测到开发版本","updateError": "检查更新失败",- "checkForBackendUpdates": "检查 Llamacpp 更新",- "checkForBackendUpdatesDesc": "检查是否有更新的 Llamacpp 后端版本。",- "checkingForBackendUpdates": "正在检查 Llamacpp 更新...",- "noBackendUpdateAvailable": "您正在运行最新的 Llamacpp 版本",- "backendUpdateError": "检查 Llamacpp 更新失败","changeLocation": "更改位置","copied": "已复制","copyPath": "复制路径",@@ -268,15 +263,6 @@"changeLocation": "更改位置"}},- "backendUpdater": {- "newBackendVersion": "新的 Llamacpp 版本 {{version}}",- "backendUpdateAvailable": "Llamacpp 更新可用",- "remindMeLater": "稍后提醒我",- "updating": "正在更新...",- "updateNow": "立即更新",- "updateSuccess": "Llamacpp 更新成功",- "updateError": "更新 Llamacpp 失败"- },"backendInstallSuccess": "后端安装成功","backendInstallError": "后端安装失败"}diff --git a/web-app/src/locales/zh-TW/settings.json b/web-app/src/locales/zh-TW/settings.jsonindex 4923b525e..8d14d19e4 100644--- a/web-app/src/locales/zh-TW/settings.json+++ b/web-app/src/locales/zh-TW/settings.json@@ -6,11 +6,6 @@"noUpdateAvailable": "您正在運行最新版本","devVersion": "檢測到開發版本","updateError": "檢查更新失敗",- "checkForBackendUpdates": "檢查 Llamacpp 更新",- "checkForBackendUpdatesDesc": "檢查是否有更新的 Llamacpp 後端版本。",- "checkingForBackendUpdates": "正在檢查 Llamacpp 更新...",- "noBackendUpdateAvailable": "您正在運行最新的 Llamacpp 版本",- "backendUpdateError": "檢查 Llamacpp 更新失敗","changeLocation": "更改位置","copied": "已複製","copyPath": "複製路徑",@@ -268,15 +263,6 @@"changeLocation": "變更位置"}},- "backendUpdater": {- "newBackendVersion": "新的 Llamacpp 版本 {{version}}",- "backendUpdateAvailable": "Llamacpp 更新可用",- "remindMeLater": "稍後提醒我",- "updating": "正在更新...",- "updateNow": "立即更新",- "updateSuccess": "Llamacpp 更新成功",- "updateError": "更新 Llamacpp 失敗"- },"backendInstallSuccess": "後端安裝成功","backendInstallError": "後端安裝失敗"}diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex 52bd54bd3..8e65b3a9d 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -2,7 +2,6 @@ import { createRootRoute, Outlet } from '@tanstack/react-router'// import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'import DialogAppUpdater from '@/containers/dialogs/AppUpdater'-import BackendUpdater from '@/containers/dialogs/BackendUpdater'import { Fragment } from 'react/jsx-runtime'import { ThemeProvider } from '@/providers/ThemeProvider'import { InterfaceProvider } from '@/providers/InterfaceProvider'@@ -71,7 +70,6 @@ const AppLayout = () => {/>)}<DialogAppUpdater />- {!isOnboarding && <BackendUpdater />}<LeftSidebar /><SidebarInset><div className="bg-neutral-50 dark:bg-background size-full">diff --git a/web-app/src/routes/__tests__/__root.test.tsx b/web-app/src/routes/__tests__/__root.test.tsxindex 993aa5dcf..02698e017 100644--- a/web-app/src/routes/__tests__/__root.test.tsx+++ b/web-app/src/routes/__tests__/__root.test.tsx@@ -73,9 +73,6 @@ vi.mock('@/i18n/TranslationContext', () => ({vi.mock('@/containers/dialogs/AppUpdater', () => ({default: () => <div data-testid="app-updater" />,}))-vi.mock('@/containers/dialogs/BackendUpdater', () => ({- default: () => <div data-testid="backend-updater" />,-}))vi.mock('@/containers/dialogs/OutOfContextDialog', () => ({default: () => <div data-testid="oocp" />,}))@@ -173,7 +170,6 @@ describe('__root route', () => {expect(screen.getByTestId('error-dialog')).toBeInTheDocument()expect(screen.getByTestId('oocp')).toBeInTheDocument()expect(screen.getByTestId('app-updater')).toBeInTheDocument()- expect(screen.getByTestId('backend-updater')).toBeInTheDocument()})// Mounted here rather than beside the download popover, which is absent on@@ -189,14 +185,13 @@ describe('__root route', () => {expect(screen.getByTestId('prompt-analytic')).toBeInTheDocument()})- // The setup screen is the single onboarding surface; these would otherwise- // stack on top of it asking for things the wizard already covers.- it('defers the analytics prompt and backend updater while onboarding', () => {+ // The setup screen is the single onboarding surface; this would otherwise+ // stack on top of it asking for something the wizard already covers.+ it('defers the analytics prompt while onboarding', () => {h.isOnboarding = trueh.productAnalyticPrompt = truerenderComponent()expect(screen.queryByTestId('prompt-analytic')).not.toBeInTheDocument()- expect(screen.queryByTestId('backend-updater')).not.toBeInTheDocument()})it('does not render PromptAnalytic when productAnalyticPrompt is false', () => {diff --git a/web-app/src/routes/hub/$modelId.tsx b/web-app/src/routes/hub/$modelId.tsxindex 8d644c20d..a2eb50ca2 100644--- a/web-app/src/routes/hub/$modelId.tsx+++ b/web-app/src/routes/hub/$modelId.tsx@@ -20,7 +20,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'import { useDownloadStore } from '@/hooks/useDownloadStore'import { useServiceHub } from '@/hooks/useServiceHub'import type { CatalogModel } from '@/services/models/types'-import { isMtpQuant, pickMtpSibling } from '@/lib/mtp'+import { isSpecSidecar, pickSpecSibling } from '@/lib/specDraft'import { Progress } from '@/components/ui/progress'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'@@ -88,10 +88,10 @@ function HubModelDetailContent() {return sources.find((model) => model.model_name === modelId) ?? repoData}, [sources, modelId, repoData])- // MTP companion ggufs are draft models paired with a real quant at download+ // Speculative draft companions are paired with a real quant at download// time, not standalone models — keep them out of the selectable variant list.const displayQuants = useMemo(- () => modelData?.quants?.filter((q) => !isMtpQuant(q)) ?? [],+ () => modelData?.quants?.filter((q) => !isSpecSidecar(q)) ?? [],[modelData])@@ -438,10 +438,10 @@ function HubModelDetailContent() {'mmproj-f16') || modelData.mmproj_models?.[0])?.path- const mtpPath = pickMtpSibling(+ const specDraft = pickSpecSibling(modelData.quants,variant- )?.path+ )setResumeParams(variant.model_id, {modelPath: variant.path,mmprojPath,@@ -455,7 +455,8 @@ function HubModelDetailContent() {mmprojPath,huggingfaceToken,undefined,- mtpPath+ specDraft?.quant.path,+ specDraft?.kind)}}className={cn(isDownloading && 'hidden')}diff --git a/web-app/src/routes/hub/index.tsx b/web-app/src/routes/hub/index.tsxindex a907fe32c..3985857b8 100644--- a/web-app/src/routes/hub/index.tsx+++ b/web-app/src/routes/hub/index.tsx@@ -5,7 +5,7 @@ import { route } from '@/constants/routes'import { useModelSources } from '@/hooks/useModelSources'import { cn, formatBytes, sanitizeModelId } from '@/lib/utils'import { sumMlxModelBytes } from '@/lib/modelCompatibility'-import { isMtpQuant } from '@/lib/mtp'+import { isSpecSidecar } from '@/lib/specDraft'import {useState,useMemo,@@ -199,13 +199,14 @@ function HubContent() {}, [searchValue])const filteredModels = useMemo(() => {- // MTP companion ggufs are draft models, not standalone variants — move them- // out of `quants` (so they don't show as downloadable) into `mtpQuants`,- // where DownloadButton resolves them against the chosen quant.+ // Speculative draft companions (mtp/eagle3/dflash/dspark) are draft models,+ // not standalone variants — move them out of `quants` (so they don't show+ // as downloadable) into `specQuants`, where DownloadButton resolves them+ // against the chosen quant.let filtered: CatalogModel[] = sortedModels.map((model) => ({...model,- quants: model.quants?.filter((q) => !isMtpQuant(q)),- mtpQuants: model.quants?.filter((q) => isMtpQuant(q)),+ quants: model.quants?.filter((q) => !isSpecSidecar(q)),+ specQuants: model.quants?.filter((q) => isSpecSidecar(q)),}))// Apply search filterif (debouncedSearchValue.length) {diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex 51c88e92e..73c24371f 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -18,7 +18,6 @@ import { DialogDeleteAllModels } from '@/containers/dialogs/DeleteAllModels'import { FavoriteModelAction } from '@/containers/FavoriteModelAction'import { route } from '@/constants/routes'import DeleteProvider from '@/containers/dialogs/DeleteProvider'-import { BackendUpdateHistory } from '@/containers/BackendUpdateHistory'import { useServiceHub } from '@/hooks/useServiceHub'import { Button } from '@/components/ui/button'import { SecretInput } from '@/components/ui/secret-input'@@ -30,16 +29,12 @@ import {IconInfoCircle,IconLoader,IconRefresh,- IconUpload,} from '@tabler/icons-react'import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'import { toast } from 'sonner'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { predefinedProviders } from '@/constants/providers'import { useModelLoad } from '@/hooks/useModelLoad'-import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'-import { useBackendUpdater } from '@/hooks/useBackendUpdater'-import { basenameNoExt } from '@/lib/utils'import { useAppState } from '@/hooks/useAppState'import { useShallow } from 'zustand/shallow'import { DialogAddModel } from '@/containers/dialogs/AddModel'@@ -74,9 +69,6 @@ function ProviderDetail() {)const [loadingModels, setLoadingModels] = useState<string[]>([])const [refreshingModels, setRefreshingModels] = useState(false)- const [isCheckingBackendUpdate, setIsCheckingBackendUpdate] = useState(false)- const [isInstallingBackend, setIsInstallingBackend] = useState(false)- const [isInstallingCuda, setIsInstallingCuda] = useState(false)const [importingModel, setImportingModel] = useState<string | null>(null)const [apiKeysDraft, setApiKeysDraft] = useState('')const [baseUrlDraft, setBaseUrlDraft] = useState('')@@ -85,11 +77,6 @@ function ProviderDetail() {const [keyCheckResults, setKeyCheckResults] = useState<{ index: number; masked: string; status: string; detail: string }[]>([])- const {- checkForUpdate: checkForBackendUpdate,- installBackend,- installCudaRuntime,- } = useBackendUpdater()const { providerName } = useParams({ from: Route.id })const { getProviderByName, setProviders, updateProvider, addDeletedModels } =useModelProvider()@@ -155,18 +142,6 @@ function ProviderDetail() {clearDefaultEmbeddingModel,])- // Check if llamacpp/mlx provider needs backend configuration- const isBackendKey = (k: string) =>- k === 'llamacpp_version' || k === 'llamacpp_backend'- const needsBackendConfig =- (provider?.provider === 'llamacpp' || provider?.provider === 'mlx') &&- provider.settings?.some(- (setting) =>- isBackendKey(setting.key) &&- (setting.controller_props.value === 'none' ||- setting.controller_props.value === '' ||- !setting.controller_props.value)- )const handleModelImportSuccess = async (importedModelName?: string) => {if (importedModelName) {@@ -495,28 +470,6 @@ function ProviderDetail() {}}, [apiKeysDraft, maskApiKey, provider?.base_url, serviceHub, t])- // Auto-refresh provider settings to get updated backend configuration- const refreshSettings = useCallback(async () => {- if (!provider) return-- try {- // Refresh providers to get updated settings from the extension- const updatedProviders = await serviceHub.providers().getProviders()- setProviders(updatedProviders)- } catch (error) {- console.error('Failed to refresh settings:', error)- }- }, [provider, serviceHub, setProviders])-- // Auto-refresh settings when provider changes or when llamacpp needs backend config- useEffect(() => {- if (provider && needsBackendConfig) {- // Auto-refresh every 3 seconds when backend is being configured- const intervalId = setInterval(refreshSettings, 3000)- return () => clearInterval(intervalId)- }- }, [provider, needsBackendConfig, refreshSettings])-// Note: settingsChanged event is now handled globally in GlobalEventHandler// This ensures all screens receive the event intermediately@@ -659,112 +612,6 @@ function ProviderDetail() {})}- const handleCheckForBackendUpdate = useCallback(async () => {- if (provider?.provider !== 'llamacpp' && provider?.provider !== 'mlx')- return-- setIsCheckingBackendUpdate(true)- try {- const update = await checkForBackendUpdate(true)- if (!update) {- toast.info(t('settings:noBackendUpdateAvailable'))- }- // If update is available, the BackendUpdater dialog will automatically show- } catch (error) {- console.error('Failed to check for backend updates:', error)- toast.error(t('settings:backendUpdateError'))- } finally {- setIsCheckingBackendUpdate(false)- }- }, [provider, checkForBackendUpdate, t])-- const handleInstallBackendFromFile = useCallback(async () => {- if (provider?.provider !== 'llamacpp' && provider?.provider !== 'mlx')- return-- setIsInstallingBackend(true)- try {- // macOS NSOpenPanel maps filter strings to UTTypes via- // typeWithFilenameExtension:, which only accepts single-component- // extensions. `.tar.gz` resolves to org.gnu.gnu-zip-tar-archive,- // which is a sibling — not a child — of `.gz`'s UTType, so neither- // a `tar.gz` nor `gz` filter enables `.tar.gz` files in the picker.- // Skip the filter on macOS and revalidate after the pick.- const isMac =- typeof navigator !== 'undefined' &&- navigator.userAgent.toUpperCase().includes('MAC')- const selectedFile = await serviceHub.dialog().open({- multiple: false,- directory: false,- filters: isMac- ? undefined- : [- {- name: 'Backend Archives',- extensions: ['tar.gz', 'zip'],- },- ],- })-- if (selectedFile && typeof selectedFile === 'string') {- // Process the file path: replace spaces with dashes and convert to lowercase-- // Install the backend using the llamacpp extension- await installBackend(selectedFile)-- // Extract filename from the selected file path and replace spaces with dashes- const fileName = basenameNoExt(selectedFile).replace(/\s+/g, '-')-- // Capitalize provider name for display- const providerDisplayName =- provider?.provider === 'llamacpp' ? 'Llamacpp' : 'MLX'-- toast.success(t('settings:backendInstallSuccess'), {- description: `${providerDisplayName} ${fileName} installed`,- })-- // Refresh settings to update backend configuration- await refreshSettings()- }- } catch (error) {- console.error('Failed to install backend from file:', error)- toast.error(t('settings:backendInstallError'), {- description:- error instanceof Error ? error.message : 'Unknown error occurred',- })- } finally {- setIsInstallingBackend(false)- }- }, [provider, serviceHub, refreshSettings, t, installBackend])-- const handleInstallCudaRuntime = useCallback(async () => {- if (provider?.provider !== 'llamacpp') return-- setIsInstallingCuda(true)- try {- const selectedFile = await serviceHub.dialog().open({- multiple: false,- directory: false,- filters: [{ name: 'CUDA Runtime Archive', extensions: ['zip', 'gz'] }],- })-- if (selectedFile && typeof selectedFile === 'string') {- await installCudaRuntime(selectedFile)- toast.success(t('settings:backendInstallSuccess'), {- description: t('settings:cudaRuntimeInstalled'),- })- }- } catch (error) {- console.error('Failed to install CUDA runtime:', error)- toast.error(t('settings:backendInstallError'), {- description:- error instanceof Error ? error.message : 'Unknown error occurred',- })- } finally {- setIsInstallingCuda(false)- }- }, [provider, serviceHub, t, installCudaRuntime])-return (<div className="flex flex-col h-svh w-full"><HeaderPage>@@ -850,13 +697,7 @@ function ProviderDetail() {// Use the DynamicController componentconst actionComponent = (<div className="mt-2">- {needsBackendConfig && isBackendKey(setting.key) ? (- <div className="flex items-center gap-1 text-sm">- <IconLoader size={16} className="animate-spin" />- <span>loading</span>- </div>- ) : (- <DynamicControllerSetting+ <DynamicControllerSettingcontrollerType={setting.controller_type}controllerProps={setting.controller_props}className={cn(setting.key === 'device' && 'hidden')}@@ -890,31 +731,6 @@ function ProviderDetail() {updateObj.base_url = newValue}- // Reset device setting to empty when backend or version changes- if (isBackendKey(settingKey)) {- const deviceSettingIndex =- newSettings.findIndex(- (s) => s.key === 'device'- )-- if (deviceSettingIndex !== -1) {- (- newSettings[deviceSettingIndex]- .controller_props as {- value: string- }- ).value = ''- }-- // Reset llamacpp device activations when backend version changes- if (providerName === 'llamacpp') {- // Refresh devices to update activation status from provider settings- const { fetchDevices } =- useLlamacppDevices.getState()- fetchDevices()- }- }-serviceHub.providers().updateSettings(@@ -936,7 +752,6 @@ function ProviderDetail() {}}}/>- )}</div>)@@ -972,85 +787,6 @@ function ProviderDetail() {),}}/>- {setting.key === 'llamacpp_backend' &&- setting.controller_props?.recommended && (- <div className="mt-1 text-sm text-muted-foreground">- <span className="font-medium">- {setting.controller_props.recommended}- </span>- <span> is the recommended backend.</span>- </div>- )}- {setting.key === 'llamacpp_backend' &&- (provider?.provider === 'llamacpp' ||- provider?.provider === 'mlx') && (- <div className="mt-2 flex flex-wrap gap-2">- <Button- variant="outline"- size="sm"- className={cn(- isCheckingBackendUpdate &&- 'pointer-events-none'- )}- onClick={handleCheckForBackendUpdate}- >- <IconRefresh- size={12}- className={cn(- 'text-muted-foreground',- isCheckingBackendUpdate && 'animate-spin'- )}- />- <span>- {isCheckingBackendUpdate- ? t('settings:checkingForBackendUpdates')- : t('settings:checkForBackendUpdates')}- </span>- </Button>- <Button- variant="outline"- size="sm"- onClick={handleInstallBackendFromFile}- disabled={isInstallingBackend}- >- <IconUpload- size={12}- className={cn(- 'text-muted-foreground',- isInstallingBackend && 'animate-pulse'- )}- />- <span>- {isInstallingBackend- ? t('settings:installingBackend')- : t('settings:installBackendFromFile')}- </span>- </Button>- {provider?.provider === 'llamacpp' &&- IS_WINDOWS && (- <Button- variant="outline"- size="sm"- onClick={handleInstallCudaRuntime}- disabled={isInstallingCuda}- >- <IconUpload- size={12}- className={cn(- 'text-muted-foreground',- isInstallingCuda && 'animate-pulse'- )}- />- <span>- {isInstallingCuda- ? t('settings:installingCudaRuntime')- : t('settings:installCudaRuntime')}- </span>- </Button>- )}- <BackendUpdateHistory />- </div>- )}</>}actions={actionComponent}diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsxindex d2dfeac02..da5e74dbb 100644--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx@@ -47,18 +47,11 @@ const h = vi.hoisted(() => {],settings: [{- key: 'llamacpp_version',- title: 'Version',- description: 'llama.cpp release version',+ key: 'ctx_size',+ title: 'Context Size',+ description: 'context window',controller_type: 'input',- controller_props: { value: 'v1', recommended: 'v1' },- },- {- key: 'llamacpp_backend',- title: 'Backend',- description: 'Hardware backend',- controller_type: 'input',- controller_props: { value: 'cuda', recommended: 'cuda' },+ controller_props: { value: '4096' },},{key: 'device',@@ -122,11 +115,6 @@ const h = vi.hoisted(() => {setModelLoadError: vi.fn(),}- const backendUpdater = {- checkForUpdate: vi.fn().mockResolvedValue(null),- installBackend: vi.fn().mockResolvedValue(undefined),- }-const params: any = { providerName: 'openai' }return {@@ -147,7 +135,6 @@ const h = vi.hoisted(() => {modelsSvc,dialogSvc,modelLoad,- backendUpdater,params,}})@@ -330,10 +317,6 @@ vi.mock('@/hooks/useLlamacppDevices', () => {return { useLlamacppDevices: hook }})-vi.mock('@/hooks/useBackendUpdater', () => ({- useBackendUpdater: () => h.backendUpdater,-}))-vi.mock('@/hooks/useAppState', () => ({ useAppState: h.useAppStateMock }))vi.mock('zustand/shallow', () => ({@@ -393,8 +376,6 @@ beforeEach(() => {h.modelsSvc.stopAllModels = vi.fn().mockResolvedValue(undefined)h.modelsSvc.checkMmprojExists = vi.fn().mockResolvedValue(false)h.dialogSvc.open = vi.fn().mockResolvedValue(null)- h.backendUpdater.checkForUpdate = vi.fn().mockResolvedValue(null)- h.backendUpdater.installBackend = vi.fn().mockResolvedValue(undefined)})describe('ProviderDetail route', () => {@@ -449,12 +430,10 @@ describe('ProviderDetail route', () => {expect(screen.queryByTestId('add-model')).not.toBeInTheDocument()})- it('renders llamacpp-specific UI: import button, backend controls', () => {+ it('renders llamacpp-specific UI: import button', () => {h.params.providerName = 'llamacpp'renderComponent()expect(screen.getByTestId('import-vision')).toBeInTheDocument()- expect(screen.getByText('settings:checkForBackendUpdates')).toBeInTheDocument()- expect(screen.getByText('settings:installBackendFromFile')).toBeInTheDocument()})})@@ -690,72 +669,6 @@ describe('ProviderDetail route', () => {})})- describe('Backend install / update (llamacpp)', () => {- beforeEach(() => {- h.params.providerName = 'llamacpp'- })-- it('check-for-update shows info toast when no update available', async () => {- renderComponent()- await act(async () => {- fireEvent.click(screen.getByText('settings:checkForBackendUpdates'))- })- await waitFor(() => {- expect(h.toastInfo).toHaveBeenCalled()- })- })-- it('check-for-update shows error toast when the checker throws', async () => {- h.backendUpdater.checkForUpdate = vi.fn().mockRejectedValue(new Error('x'))- renderComponent()- await act(async () => {- fireEvent.click(screen.getByText('settings:checkForBackendUpdates'))- })- await waitFor(() => {- expect(h.toastError).toHaveBeenCalled()- })- // restore- h.backendUpdater.checkForUpdate = vi.fn().mockResolvedValue(null)- })-- it('install-from-file no-ops cleanly when dialog returns null', async () => {- renderComponent()- await act(async () => {- fireEvent.click(screen.getByText('settings:installBackendFromFile'))- })- // no toast fired because file selection was cancelled- expect(h.toastSuccess).not.toHaveBeenCalled()- expect(h.toastError).not.toHaveBeenCalled()- })-- it('install-from-file calls installBackend and toasts success', async () => {- h.dialogSvc.open = vi.fn().mockResolvedValue('/some/path/My Backend.tar.gz')- renderComponent()- await act(async () => {- fireEvent.click(screen.getByText('settings:installBackendFromFile'))- })- await waitFor(() => {- expect(h.backendUpdater.installBackend).toHaveBeenCalledWith(- '/some/path/My Backend.tar.gz'- )- })- expect(h.toastSuccess).toHaveBeenCalled()- })-- it('install-from-file toasts error when installBackend throws', async () => {- h.dialogSvc.open = vi.fn().mockResolvedValue('/some/path/bad.tar.gz')- h.backendUpdater.installBackend = vi.fn().mockRejectedValue(new Error('install fail'))- renderComponent()- await act(async () => {- fireEvent.click(screen.getByText('settings:installBackendFromFile'))- })- await waitFor(() => {- expect(h.toastError).toHaveBeenCalled()- })- h.backendUpdater.installBackend = vi.fn().mockResolvedValue(undefined)- })- })-describe('Dynamic setting changes', () => {const setupCustomProvider = () => {const custom: any = {@@ -803,12 +716,12 @@ describe('ProviderDetail route', () => {)})- it('for llamacpp, the llamacpp_version control also stops all running models on change', async () => {+ it('for llamacpp, changing a setting also stops all running models', async () => {h.params.providerName = 'llamacpp'renderComponent()const dyns = screen.getAllByTestId('dynamic-ctrl')await act(async () => {- fireEvent.click(dyns[0]) // llamacpp_version+ fireEvent.click(dyns[0])})expect(h.modelsSvc.stopAllModels).toHaveBeenCalled()})diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex e1c75cb47..9544c2fc7 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -17,6 +17,7 @@ import { useAppState } from '@/hooks/useAppState'import { SESSION_STORAGE_PREFIX } from '@/constants/chat'import { useChat } from '@/hooks/use-chat'import { useModelProvider } from '@/hooks/useModelProvider'+import { engineSlotsIdle } from '@janhq/tauri-plugin-llamacpp-api'import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'import { renderInstructions } from '@/lib/instructionTemplate'import {@@ -24,7 +25,6 @@ import {ConversationContent,ConversationScrollButton,} from '@/components/ai-elements/conversation'-import { invoke } from '@tauri-apps/api/core'import { generateId, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'import type { UIMessage } from '@ai-sdk/react'import { useChatSessions } from '@/stores/chat-session-store'@@ -627,10 +627,7 @@ function ThreadDetail() {let idle = falsefor (let attempt = 0; attempt < 6; attempt++) {try {- idle = await invoke<boolean>(- 'plugin:llamacpp|router_slots_idle',- { modelId }- )+ idle = await engineSlotsIdle(modelId)} catch {idle = truebreakdiff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex cebc53cc4..8bdf29951 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -16,6 +16,7 @@ import {UnloadResult,} from '@janhq/core'import { Model as CoreModel } from '@janhq/core'+import type { SpecDraftKind } from '@janhq/core'import type {ModelsService,ModelCatalog,@@ -235,7 +236,8 @@ export class DefaultModelsService implements ModelsService {mmprojPath?: string,mmprojSha256?: string,mmprojSize?: number,- mtpPath?: string+ specDraftPath?: string,+ specDraftKind?: SpecDraftKind): Promise<void> {return this.getEngine()?.import(id, {modelPath,@@ -244,7 +246,8 @@ export class DefaultModelsService implements ModelsService {modelSize,mmprojSha256,mmprojSize,- mtpPath,+ specDraftPath,+ specDraftKind,})}@@ -254,7 +257,8 @@ export class DefaultModelsService implements ModelsService {mmprojPath?: string,hfToken?: string,skipVerification: boolean = true,- mtpPath?: string+ specDraftPath?: string,+ specDraftKind?: SpecDraftKind): Promise<void> {let modelSha256: string | undefinedlet modelSize: number | undefined@@ -320,7 +324,8 @@ export class DefaultModelsService implements ModelsService {mmprojPath,mmprojSha256,mmprojSize,- mtpPath+ specDraftPath,+ specDraftKind)} catch (error) {// Emit download error event so the UI can clean up the stale downloading statediff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex 2186c91bc..795ff8b2e 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -3,6 +3,7 @@*/import { SessionInfo, modelInfo, ThreadMessage, UnloadResult } from '@janhq/core'+import type { SpecDraftKind } from '@janhq/core'import { Model as CoreModel } from '@janhq/core'// Types for model catalog@@ -36,7 +37,7 @@ export interface CatalogModel {quants?: ModelQuant[]// MTP draft companions split out of `quants` for display; resolved against// the chosen quant at download time (see lib/mtp.ts).- mtpQuants?: ModelQuant[]+ specQuants?: ModelQuant[]mmproj_models?: MMProjModel[]num_mmproj?: numbersafetensors_files?: SafetensorsFile[]@@ -124,7 +125,8 @@ export interface ModelsService {mmprojPath?: string,mmprojSha256?: string,mmprojSize?: number,- mtpPath?: string+ specDraftPath?: string,+ specDraftKind?: SpecDraftKind): Promise<void>pullModelWithMetadata(id: string,@@ -132,7 +134,8 @@ export interface ModelsService {mmprojPath?: string,hfToken?: string,skipVerification?: boolean,- mtpPath?: string+ specDraftPath?: string,+ specDraftKind?: SpecDraftKind): Promise<void>abortDownload(id: string): Promise<void>pauseDownload(id: string): Promise<void>@@ -198,10 +201,16 @@ export type EmbeddingVectorProblem =| 'nonFinite'| 'degenerate'-export type GpuOffloadReason =- | 'noGpuHardware'- | 'runtimeUnreachable'- | 'missingLibrary'+/**+ * `runtimeUnreachable`: a GPU exists but the engine cannot see it (driver or+ * runtime). `missingLibrary`: same symptom, cause established.+ *+ * `noGpuHardware` is gone. It meant "a GPU build on a machine with no GPU",+ * which the bundled engine cannot be in: no GPU simply means no offload+ * expected, which is `ok`, not a warning. Mirrors GpuOffloadReason in+ * extensions/llamacpp-extension/src/readiness.ts.+ */+export type GpuOffloadReason = 'runtimeUnreachable' | 'missingLibrary'interface ReadinessReport {status: 'ok' | 'warning'@@ -210,8 +219,12 @@ interface ReadinessReport {/** The engine build cannot run this check at all. */unavailable?: boolean/**- * The engine has not finished its own setup, so nothing was concluded. Distinct- * from `unavailable`: this one resolves on its own.+ * The engine has not finished its own setup, so nothing was concluded.+ * Distinct from `unavailable`: this one resolves on its own.+ *+ * Nothing sets it any more -- it existed for the window while a backend was+ * downloading, and the engine now ships with the app. Kept because the+ * embedding model is still fetched on first run and may need it again.*/pending?: boolean}diff --git a/web-app/vitest.config.ts b/web-app/vitest.config.tsindex bd0f2b48c..faa841318 100644--- a/web-app/vitest.config.ts+++ b/web-app/vitest.config.ts@@ -34,6 +34,13 @@ export default defineConfig({'@janhq/mlx-extension': path.resolve(__dirname, '../extensions/mlx-extension/dist/index.js'),'@janhq/rag-extension': path.resolve(__dirname, '../extensions/rag-extension/dist/index.js'),'@janhq/vector-db-extension': path.resolve(__dirname, '../extensions/vector-db-extension/dist/index.js'),+ // Resolve the plugin to guest-js source, not its built dist-js, so+ // tests exercise the wrappers the app actually calls.+ '@janhq/tauri-plugin-llamacpp-api': path.resolve(__dirname, '../src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts'),+ // The plugin ships its own @tauri-apps/api install; without this the+ // aliased guest-js would get a second module instance that+ // vi.mock('@tauri-apps/api/core') cannot intercept.+ '@tauri-apps/api/core': path.resolve(__dirname, './node_modules/@tauri-apps/api/core.js'),},},define: {