Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(engine): dynamic-ISA sidecar build so the CPU choice happens at runtime (K1)

purpleefe556af5369
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ad38962d..d2b10797 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -179,6 +179,19 @@ jobs:
*) touch "src-tauri/bin/lu-llama-server-$triple" ;;
esac
ls -la src-tauri/bin/
+ # K1 (3.0.1): tauri.windows.conf.json / tauri.linux.conf.json now
+ # declare a bundle.resources glob for the dynamic-ISA companion
+ # libraries (src-tauri/resources/llama/<triple>/*), and the comment
+ # below already established that build.rs resolves bundle.resources
+ # during a plain `cargo check`, not only a full `tauri build`. A
+ # glob with zero matches would make that resolution fail here too,
+ # so this stub needs a companion file to match, the same reasoning
+ # as the exe stub above, just for the resources side of the bundle
+ # instead of externalBin.
+ case "$triple" in
+ *-windows-*) mkdir -p "src-tauri/resources/llama/$triple" && touch "src-tauri/resources/llama/$triple/ggml-cpu-x64.dll" ;;
+ *-linux-*) mkdir -p "src-tauri/resources/llama/$triple" && touch "src-tauri/resources/llama/$triple/ggml-cpu-x64.so" ;;
+ esac
# tauri-build also resolves bundle.resources, and ../dist only exists
# after a frontend build. This job runs no npm at all, so build.rs bailed
@@ -330,6 +343,18 @@ jobs:
*) touch "src-tauri/bin/lu-llama-server-$triple" ;;
esac
ls -la src-tauri/bin/
+ # K1 (3.0.1): this job runs a REAL `tauri build`, which resolves
+ # bundle.resources for real: tauri.windows.conf.json /
+ # tauri.linux.conf.json now glob src-tauri/resources/llama/<triple>/*
+ # for the dynamic-ISA companion libraries, and this gate never runs
+ # scripts/build-llama.sh to produce them. Same stub reasoning as the
+ # exe above, on the resources side of the bundle instead of
+ # externalBin, so a glob with zero matches cannot fail this gate for
+ # a reason that has nothing to do with what it is checking.
+ case "$triple" in
+ *-windows-*) mkdir -p "src-tauri/resources/llama/$triple" && touch "src-tauri/resources/llama/$triple/ggml-cpu-x64.dll" ;;
+ *-linux-*) mkdir -p "src-tauri/resources/llama/$triple" && touch "src-tauri/resources/llama/$triple/ggml-cpu-x64.so" ;;
+ esac
- name: Install npm dependencies
run: npm ci
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cff6c1e1..f5a276f4 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -219,6 +219,14 @@ jobs:
esac
ls -la src-tauri/bin/
+ # K1 (3.0.1): the guard against shipping a fixed x86-64-v3 binary again.
+ # Runs on the real build this lane just produced, on the real runner
+ # architecture (not emulated), so a regression here is the same failure
+ # a customer's older CPU would hit.
+ - name: Verify sidecar ISA layout (K1)
+ shell: bash
+ run: bash scripts/verify-sidecar-isa.sh ${{ matrix.sidecar_triple }}
+
# ── App build ────────────────────────────────────────────────────────
- name: Install npm dependencies
run: npm ci
diff --git a/.github/workflows/sidecar-windows.yml b/.github/workflows/sidecar-windows.yml
index 66f8977d..124b3457 100644
--- a/.github/workflows/sidecar-windows.yml
+++ b/.github/workflows/sidecar-windows.yml
@@ -58,13 +58,30 @@ jobs:
shell: bash
run: bash scripts/build-llama.sh x86_64-pc-windows-msvc
+ - name: Verify sidecar ISA layout (K1)
+ shell: bash
+ run: bash scripts/verify-sidecar-isa.sh x86_64-pc-windows-msvc
+
- name: Boot smoke — real model load + /health
shell: pwsh
run: |
- $bin = "src-tauri\bin\lu-llama-server-x86_64-pc-windows-msvc.exe"
+ $bin = (Resolve-Path "src-tauri\bin\lu-llama-server-x86_64-pc-windows-msvc.exe").Path
if (-not (Test-Path $bin)) { throw "sidecar binary missing" }
+ # K1 (3.0.1): the binary is dynamic now: GGML_BACKEND_DL loads its
+ # CPU-variant and Vulkan kernels from ggml-cpu-*/ggml-vulkan DLLs
+ # that live in src-tauri\resources\llama\<triple>\, not next to the
+ # exe (see scripts/build-llama.sh, engine.rs's
+ # resolve_engine_backend_dir/apply_engine_backend_dir). Running the
+ # bare exe from src-tauri\bin, as this step did before K1, would
+ # prove nothing about the layout a real install actually has;
+ # ggml_backend_load_all() only scans the executable's own directory
+ # and the process's CURRENT directory, so the working directory has
+ # to be the resource layout, exactly like the app spawns it.
+ $runDir = (Resolve-Path "src-tauri\resources\llama\x86_64-pc-windows-msvc").Path
+ Push-Location $runDir
& $bin --version
- if ($LASTEXITCODE -ne 0) { throw "llama-server --version exited $LASTEXITCODE" }
+ if ($LASTEXITCODE -ne 0) { throw "llama-server --version exited $LASTEXITCODE (run from $runDir)" }
+ Pop-Location
# Tiny (~1.2 MB) public GGUF so /health proves a real model load,
# not just the HTTP layer. Lands in the cached build root, so the
# sidecar cache step keeps it across runs.
@@ -74,7 +91,7 @@ jobs:
"https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf"
if ($LASTEXITCODE -ne 0) { throw "smoke model download failed" }
}
- $proc = Start-Process -FilePath $bin -ArgumentList "--host","127.0.0.1","--port","8129","-m",$model -PassThru -NoNewWindow
+ $proc = Start-Process -FilePath $bin -ArgumentList "--host","127.0.0.1","--port","8129","-m",$model -WorkingDirectory $runDir -PassThru -NoNewWindow
$ok = $false
foreach ($i in 1..40) {
Start-Sleep -Milliseconds 400
@@ -85,11 +102,17 @@ jobs:
}
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
if (-not $ok) { throw "llama-server /health never came up" }
- Write-Host "OK - sidecar boots, loads a model and answers /health"
+ Write-Host "OK - sidecar boots from the resource layout, loads a model and answers /health"
- name: Upload sidecar artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: lu-llama-server-x86_64-pc-windows-msvc
- path: src-tauri/bin/lu-llama-server-x86_64-pc-windows-msvc.exe
+ # K1: the exe alone cannot run any more, it needs the companion
+ # ggml-cpu-*/ggml-vulkan DLLs staged next to it (see above):
+ # shipping only the exe from this artifact would be shipping
+ # something that cannot boot.
+ path: |
+ src-tauri/bin/lu-llama-server-x86_64-pc-windows-msvc.exe
+ src-tauri/resources/llama/x86_64-pc-windows-msvc/*
retention-days: 14
diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh
index 4b966307..64c83b57 100755
--- a/scripts/build-llama.sh
+++ b/scripts/build-llama.sh
@@ -3,13 +3,24 @@
# build-llama.sh — build the bundled llama.cpp `llama-server` sidecar for
# Locally Uncensored's built-in inference engine (P0 of the built-in-engine plan).
#
-# The produced binary is statically linked with the GPU backend embedded, so a
+# mac: the produced binary is statically linked with Metal embedded, so a
# single self-contained file drops into `src-tauri/bin/llama-server-<triple>`
# and Tauri picks it up as an `externalBin` sidecar (target triple appended,
# code-signed with the app on macOS).
#
+# Windows and Linux (K1, 3.0.1): the binary is dynamic and loads its CPU
+# kernels and the Vulkan backend at runtime (GGML_BACKEND_DL +
+# GGML_CPU_ALL_VARIANTS, see cmake_flags_for below): a fixed x86-64-v3
+# binary made every pre-Haswell/pre-Excavator CPU crash with 0xC000001D
+# (Windows) or SIGILL (Linux) before llama-server could log anything. The
+# companion ggml-cpu-*/ggml-vulkan libraries this produces land in
+# `src-tauri/resources/llama/<triple>/`, bundled as Tauri `resources`
+# (tauri.windows.conf.json / tauri.linux.conf.json) alongside the exe
+# sidecar, not as more externalBin entries.
+#
# Idempotent: clones/pins llama.cpp once into a build cache, reuses it on reruns.
-# Binaries are NOT committed — see src-tauri/bin/.gitignore.
+# Binaries and companion libraries are NOT committed, see
+# src-tauri/bin/.gitignore and src-tauri/resources/llama/.gitignore.
#
# Usage:
# scripts/build-llama.sh # build for the host target triple
@@ -47,7 +58,10 @@ LLAMA_REPO="${LLAMA_REPO:-https://github.com/ggml-org/llama.cpp.git}"
# --- Paths -----------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+# Overridable only for tests (build-llama-script.test.ts), the same pattern as
+# LLAMA_BUILD_CACHE below: a real build always derives it from the script's
+# own location, so BIN_DIR/resources always land in the real checkout.
+REPO_ROOT="${BUILD_LLAMA_REPO_ROOT:-$(cd "$SCRIPT_DIR/.." && pwd)}"
CACHE_DIR="${LLAMA_BUILD_CACHE:-$REPO_ROOT/.llama-build}"
SRC_DIR="$CACHE_DIR/llama.cpp"
BIN_DIR="$REPO_ROOT/src-tauri/bin"
@@ -69,27 +83,79 @@ host_triple() {
fi
}
-# Map a Rust target triple → cmake flags for a static, GPU-embedded llama-server.
+# Map a Rust target triple → cmake flags for the llama-server build.
# LLAMA_OPENSSL=OFF: no HTTPS/downloader deps — the app manages model files.
# LLAMA_BUILD_UI/USE_PREBUILT_UI=OFF: headless sidecar — no npm build and no
# HF asset fetch at compile time.
+#
+# K1 (3.0.1): mac stays a single STATIC binary with Metal embedded. Apple
+# Silicon has one relevant CPU family, so there is nothing to select at
+# runtime and GGML_CPU_ALL_VARIANTS does not even claim ARM/Apple support for
+# it (ggml/src/CMakeLists.txt only wires ALL_VARIANTS for x86, ARM/Android/
+# PowerPC/s390x/riscv64, never "Apple x86_64" as a variant target; darwin
+# stays out of that switch entirely).
+#
+# Windows and Linux (x86_64) switch to a DYNAMIC, multi-ISA build instead of
+# one fixed x86-64-v3 binary. With GGML_NATIVE=OFF (unchanged, always was)
+# and INS_ENB therefore ON, ggml/CMakeLists.txt:141-166 forces SSE4.2 + AVX +
+# AVX2 + BMI2 + FMA + F16C into the ONE binary this script used to produce,
+# any CPU older than Haswell/Excavator (2013+) gets 0xC000001D on Windows or
+# SIGILL on Linux before llama-server can even log a line. Verified against
+# the pinned llama.cpp checkout, not guessed:
+# GGML_BACKEND_DL=ON + GGML_CPU_ALL_VARIANTS=ON is the exact pair
+# ggml/src/CMakeLists.txt:371-376 requires (GGML_CPU_ALL_VARIANTS without
+# GGML_BACKEND_DL is a FATAL_ERROR there), and GGML_CPU_ALL_VARIANTS in turn
+# requires BUILD_SHARED_LIBS=ON (ggml/src/CMakeLists.txt:188-190, also a
+# FATAL_ERROR otherwise). Under MSVC this produces nine ggml-cpu-*.dll
+# variants (x64, sse42, sandybridge, haswell, skylakex, cannonlake,
+# cascadelake, icelake, alderlake (ggml/src/CMakeLists.txt:378-402); GCC on
+# Linux additionally gets ivybridge, piledriver, cooperlake, zen4 and
+# sapphirerapids (same block, the four "if (NOT MSVC)" branches). At
+# startup llama-server calls ggml_backend_load_all() (src/llama.cpp,
+# common/arg.cpp), which (per ggml/src/ggml-backend-reg.cpp:479-486)
+# scores every ggml-cpu-*.{dll,so} beside the executable and in the current
+# working directory and dlopen()s the best-scoring one for the CPU it is
+# actually running on. GGML_VULKAN stays on for both; it becomes a sibling
+# loadable backend (ggml-vulkan.dll/.so) the same way, discovered through
+# the identical search, so the GPU path is unaffected by this switch.
cmake_flags_for() {
local triple="$1"
- local common="-DBUILD_SHARED_LIBS=OFF -DLLAMA_OPENSSL=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF -DGGML_NATIVE=OFF -DCMAKE_BUILD_TYPE=Release"
+ local common="-DLLAMA_OPENSSL=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF -DGGML_NATIVE=OFF -DCMAKE_BUILD_TYPE=Release"
case "$triple" in
aarch64-apple-darwin)
- echo "$common -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=arm64" ;;
+ echo "$common -DBUILD_SHARED_LIBS=OFF -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=arm64" ;;
x86_64-apple-darwin)
- echo "$common -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=x86_64" ;;
+ echo "$common -DBUILD_SHARED_LIBS=OFF -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=x86_64" ;;
x86_64-pc-windows-msvc)
- echo "$common -DGGML_VULKAN=ON" ;;
+ echo "$common -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_VULKAN=ON" ;;
x86_64-unknown-linux-gnu)
- echo "$common -DGGML_VULKAN=ON" ;;
+ echo "$common -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_VULKAN=ON" ;;
*)
die "unsupported target triple: $triple" ;;
esac
}
+# True for a triple this script builds as a dynamic, multi-ISA sidecar (a
+# main executable plus loadable ggml-cpu-*/ggml-vulkan companion libraries).
+# False for mac, which stays the old single static binary. Both the copy step
+# and the resource layout branch on this, so it is one function instead of
+# two case statements that could drift apart.
+is_dynamic_isa_triple() {
+ case "$1" in
+ x86_64-pc-windows-msvc | x86_64-unknown-linux-gnu) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+# Directory the companion ggml/llama shared libraries for a dynamic-ISA
+# triple are staged into, so Tauri can bundle them as `resources` (see
+# tauri.windows.conf.json / tauri.linux.conf.json) and so the same path is a
+# stable, known location in dev (no bundling involved, engine.rs reads it
+# straight off disk, see resolve_engine_backend_dir).
+resource_llama_dir_for() {
+ echo "$REPO_ROOT/src-tauri/resources/llama/$1"
+}
+
# The bundled file carries the app prefix (GitHub #120): Tauri's deb bundler
# copies external binaries into /usr/bin, and Debian's own llama.cpp-tools
# package already owns /usr/bin/llama-server, so a plain name made dpkg refuse
@@ -208,6 +274,62 @@ require_cmake() {
|| die "cmake not found — install it (macOS: brew install cmake, Windows: winget install Kitware.CMake)"
}
+# K1 (3.0.1): for a dynamic-ISA triple, `llama-server` no longer stands
+# alone: GGML_BACKEND_DL/GGML_CPU_ALL_VARIANTS build it next to a
+# ggml-cpu-<variant>.{dll,so} per CPU tier plus ggml-vulkan and the base
+# ggml/llama runtime libraries, ALL written into the executable's own build
+# output directory (ggml/src/CMakeLists.txt:269 pins every backend MODULE's
+# LIBRARY_OUTPUT_DIRECTORY to the same CMAKE_RUNTIME_OUTPUT_DIRECTORY the
+# exe uses). None of that is guessed or hardcoded here: whatever cmake
+# actually built next to the exe is what gets staged, so a variant list
+# upstream adds or drops later is picked up automatically.
+#
+# A copy, not a symlink: Linux SONAME resolution needs the exact versioned
+# filename the loader was linked against (e.g. libggml-base.so.1), which is
+# commonly a symlink to the real file. Plain `cp` (no -P/-d) dereferences, so
+# every matched name becomes its own real file, a little larger on disk, but
+# nothing a resource bundler or an installer can leave dangling.
+#
+# A standalone function (not inlined in build_triple) so it can be unit
+# tested against a directory of fake .dll/.so files, without paying for a
+# real cmake build to check the staging logic itself. Prints one
+# "path: digest" line per file it staged, plus the exe's own; empty stdin/no
+# output means "not a dynamic-ISA triple, nothing to stage" and is not an
+# error.
+stage_dynamic_isa_companions() {
+ local triple="$1" bin_out_dir="$2" exe_out="$3"
+ is_dynamic_isa_triple "$triple" || return 0
+ local companions_dir; companions_dir="$(resource_llama_dir_for "$triple")"
+ rm -rf "$companions_dir"
+ mkdir -p "$companions_dir"
+ local lib_glob
+ case "$triple" in
+ *-windows-*) lib_glob='*.dll' ;;
+ *) lib_glob='*.so*' ;;
+ esac
+ local found_any=""
+ local lib
+ while IFS= read -r lib; do
+ [ -n "$lib" ] || continue
+ found_any=1
+ local lib_out="$companions_dir/$(basename "$lib")"
+ cp "$lib" "$lib_out"
+ local lib_digest; lib_digest="$(sha256_of "$lib_out")"
+ printf '%s: %s\n' "$lib_out" "${lib_digest:-unavailable}"
+ # -L: follow symlinks so `-type f` also matches them. Without it, both BSD
+ # find (macOS, where this runs in dev/tests) and GNU find (the Linux
+ # runner) skip a symlink even when it points at a regular file, and Linux's
+ # own SONAME symlinks (libggml-base.so -> libggml-base.so.1 ->
+ # libggml-base.so.1.2.3) are exactly that: only the fully-versioned real
+ # file would be found, and the literal SONAME the dynamic linker actually
+ # looks for would be silently missing from what gets staged. Measured, not
+ # assumed: caught by the Linux companion-staging test below, red without
+ # this flag.
+ done < <(find -L "$bin_out_dir" -maxdepth 1 -type f -iname "$lib_glob")
+ [ -n "$found_any" ] \
+ || die "GGML_BACKEND_DL build for $triple produced no $lib_glob next to $exe_out: the dynamic CPU-variant libraries are missing, the sidecar would only run on the build host's own CPU"
+}
+
build_triple() {
require_cmake
local triple="$1"
@@ -229,26 +351,53 @@ build_triple() {
local out="$BIN_DIR/$(out_name_for "$triple")"
cp "$built" "$out"
chmod +x "$out"
+
+ local out_digest; out_digest="$(sha256_of "$out")"
+ local digest_lines="$out: ${out_digest:-unavailable}"
+ local companion_lines
+ companion_lines="$(stage_dynamic_isa_companions "$triple" "$(dirname "$built")" "$out")"
+ [ -z "$companion_lines" ] || digest_lines="$digest_lines
+$companion_lines"
+
# Record what actually got produced. A from-source build is not bit-for-bit
- # reproducible across machines, so this cannot be pinned to a constant — but
- # it puts the digest of the binary that ships, next to the source revision it
- # came from, in the release log, which is what an "which binary was that?"
- # question after the fact needs.
- local digest; digest="$(sha256_of "$out")"
- log "installed → $out (llama.cpp $LLAMA_TAG @ ${LLAMA_COMMIT:0:12}, sha256 ${digest:-unavailable})"
+ # reproducible across machines, so none of these can be pinned to a
+ # constant, but the digest of every file that ships, next to the source
+ # revision they came from, is what an "which binaries were those?" question
+ # after the fact needs. A list now, not a single line: the pin check in
+ # ensure_src/assert_clean_tree verifies the SOURCE TREE once per run and
+ # already covers every file this step produces (nothing here compiles from
+ # anything outside $SRC_DIR), but the digest log is per-OUTPUT-FILE by
+ # nature, so a multi-file build means a multi-line log, not a new pin
+ # mechanism.
+ log "installed (llama.cpp $LLAMA_TAG @ ${LLAMA_COMMIT:0:12}):"
+ while IFS= read -r line; do log " $line"; done <<<"$digest_lines"
}
# Boot the host binary and probe /health on an ephemeral port. Without a
# model llama-server starts in router mode (no weights loaded), so /health
# answers 200 on any machine.
+#
+# K1 (3.0.1): for a dynamic-ISA triple this MUST run the same way engine.rs
+# spawns it in the app: cwd set to the resource directory holding the
+# ggml-cpu-*/ggml-vulkan companion libraries, nothing copied next to the exe
+# because ggml_backend_load_best only scans the executable's own directory
+# and the process's current directory (ggml-backend-reg.cpp:479-486). A check
+# that ran the bare exe from $BIN_DIR would pass on a build host that also
+# happens to have those libraries lying around and prove nothing about the
+# layout a real install actually has.
check_binary() {
local triple; triple="$(host_triple)"
local bin="$BIN_DIR/$(out_name_for "$triple")"
[ -x "$bin" ] || die "no built binary at $bin — build first"
- "$bin" --version >/dev/null 2>&1 || die "$bin --version failed"
+ local run_dir="$BIN_DIR"
+ if is_dynamic_isa_triple "$triple"; then
+ run_dir="$(resource_llama_dir_for "$triple")"
+ [ -d "$run_dir" ] || die "no companion libraries at $run_dir, build first"
+ fi
+ ( cd "$run_dir" && "$bin" --version >/dev/null 2>&1 ) || die "$bin --version failed (run from $run_dir)"
local port=8129
- log "boot check: $bin on 127.0.0.1:$port (no model — router mode, /health only)"
- "$bin" --host 127.0.0.1 --port "$port" >/dev/null 2>&1 &
+ log "boot check: $bin on 127.0.0.1:$port, cwd=$run_dir (no model, router mode, /health only)"
+ ( cd "$run_dir" && "$bin" --host 127.0.0.1 --port "$port" >/dev/null 2>&1 ) &
local pid=$!
trap 'kill "$pid" 2>/dev/null || true' EXIT
local ok=""
diff --git a/scripts/verify-sidecar-isa.sh b/scripts/verify-sidecar-isa.sh
new file mode 100755
index 00000000..fba53583
--- /dev/null
+++ b/scripts/verify-sidecar-isa.sh
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+#
+# verify-sidecar-isa.sh: the guard for K1 (3.0.1). Fails the build RED when
+# the dynamic-ISA sidecar (scripts/build-llama.sh, Windows/Linux) is not what
+# it claims to be.
+#
+# Two things this checks, both measured on the actual built files, not on the
+# cmake command line that produced them (a wrong flag upstream, a stale
+# build cache, or a future llama.cpp release changing its own defaults could
+# all make the command line lie):
+#
+# 1. The BASELINE files (the "x64" CPU variant, and llama-server / ggml-base
+# themselves) must contain NO AVX-or-above instruction. These are the
+# files every CPU loads no matter how old, so an AVX instruction inside
+# one of them is exactly the K1 bug: a "dynamic" build that is secretly
+# still a fixed x86-64-v3 (or higher) binary. Checked by disassembling
+# and searching for ymm/zmm registers and VEX/EVEX-coded mnemonics (they
+# are the ones objdump prints with a leading "v", e.g. vmovaps,
+# vzeroupper, vfmadd231ps; no plain SSE mnemonic is spelled that way).
+# 2. The HASWELL variant (the first AVX2 tier) MUST contain at least one
+# such instruction. Without this positive control, a disassembler that
+# silently failed, or a grep pattern that never matches anything, would
+# make check 1 pass on every input, including a build that produced no
+# real code at all. Two files, two opposite expectations, in one script.
+#
+# Also fails RED when an expected CPU variant is simply missing from the
+# companions directory (a partial build, or a future cmake refactor that
+# drops a name this project still assumes).
+#
+# Usage: scripts/verify-sidecar-isa.sh <triple>
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck disable=SC1091
+source "$SCRIPT_DIR/build-llama.sh"
+
+vlog() { printf '\033[1;36m[verify-sidecar-isa]\033[0m %s\n' "$*"; }
+vdie() { printf '\033[1;31m[verify-sidecar-isa] FAIL:\033[0m %s\n' "$*" >&2; exit 1; }
+
+TRIPLE="${1:?usage: verify-sidecar-isa.sh <triple>}"
+
+if ! is_dynamic_isa_triple "$TRIPLE"; then
+ vlog "$TRIPLE is a static build (Metal), nothing to verify here"
+ exit 0
+fi
+
+# The CPU-variant names this project's PINNED llama.cpp checkout is known to
+# produce with GGML_CPU_ALL_VARIANTS=ON, per compiler family. Not a guess:
+# read straight off a live `cmake -S/-B` configure against LLAMA_COMMIT
+# (see build-llama.sh) and off ggml/src/CMakeLists.txt's own
+# `ggml_add_cpu_backend_variant` calls (the "if (NOT MSVC)" branches are
+# exactly the four names MSVC lacks). A future pin bump that changes this
+# list is expected to update this array in the same commit, the same way
+# LLAMA_TAG/LLAMA_COMMIT themselves are a deliberate, reviewed pin rather
+# than "whatever upstream has today".
+case "$TRIPLE" in
+ *-windows-*)
+ EXPECTED_VARIANTS=(x64 sse42 sandybridge haswell skylakex cannonlake cascadelake icelake alderlake)
+ LIB_EXT="dll"
+ ;;
+ *)
+ EXPECTED_VARIANTS=(x64 sse42 sandybridge ivybridge piledriver haswell skylakex cannonlake cascadelake icelake cooperlake zen4 alderlake sapphirerapids)
+ LIB_EXT="so"
+ ;;
+esac
+
+COMPANIONS_DIR="$(resource_llama_dir_for "$TRIPLE")"
+[ -d "$COMPANIONS_DIR" ] || vdie "no companion directory at $COMPANIONS_DIR, build first (scripts/build-llama.sh $TRIPLE)"
+
+# Companion files are named ggml-cpu-<variant>.<ext> possibly with a version
+# suffix on Linux (SONAME symlinks, dereferenced to real files by
+# stage_dynamic_isa_companions, see there). Match by prefix, same rule ggml
+# itself uses to find them at runtime.
+find_variant_file() {
+ local variant="$1"
+ find "$COMPANIONS_DIR" -maxdepth 1 -type f -iname "ggml-cpu-${variant}.${LIB_EXT}*" -print -quit
+}
+
+missing=()
+for variant in "${EXPECTED_VARIANTS[@]}"; do
+ f="$(find_variant_file "$variant")"
+ if [ -z "$f" ]; then
+ missing+=("$variant")
+ fi
+done
+if [ "${#missing[@]}" -gt 0 ]; then
+ vdie "expected CPU variant(s) missing from $COMPANIONS_DIR: ${missing[*]}"
+fi
+vlog "all ${#EXPECTED_VARIANTS[@]} expected CPU variants present for $TRIPLE"
+
+f="$(find_variant_file vulkan)"
+[ -n "$f" ] || vdie "ggml-vulkan.$LIB_EXT missing from $COMPANIONS_DIR, the GPU backend did not build as a loadable module"
+vlog "ggml-vulkan.$LIB_EXT present"
+
+# --- The disassembler ------------------------------------------------------
+
+disassemble() {
+ local file="$1"
+ if command -v objdump >/dev/null 2>&1; then
+ objdump -d "$file" 2>/dev/null
+ elif command -v llvm-objdump >/dev/null 2>&1; then
+ llvm-objdump -d "$file" 2>/dev/null
+ elif command -v dumpbin >/dev/null 2>&1; then
+ dumpbin /disasm "$file" 2>/dev/null
+ else
+ vdie "no disassembler found (need objdump, llvm-objdump or dumpbin)"
+ fi
+}
+
+# True when the disassembly contains an AVX-or-above register or a
+# VEX/EVEX-coded mnemonic. ymm*/zmm* registers cover AVX and AVX-512 data;
+# the mnemonic pattern catches the handful of VEX instructions that touch no
+# wide register at all (vzeroupper is the standing example: it clears the
+# upper bits of every ymm register and takes no operand). A mnemonic is the
+# first word after the opcode-byte column, so anchoring on tab/space
+# boundaries avoids matching inside a byte string or a symbol name.
+has_avx_or_above() {
+ grep -qE '%[yz]mm[0-9]+|[[:space:]]v[a-z0-9]{2,}([[:space:]]|$)' <<<"$1"
+}
+
+BASELINE_TARGETS=("x64" "sse42")
+POSITIVE_CONTROL="haswell"
+
+fail_count=0
+for variant in "${BASELINE_TARGETS[@]}"; do
+ f="$(find_variant_file "$variant")"
+ asm="$(disassemble "$f")"
+ if has_avx_or_above "$asm"; then
+ printf '\033[1;31m[verify-sidecar-isa] FAIL:\033[0m %s contains an AVX-or-above instruction, this is supposed to be the no-AVX baseline:\n' "$f" >&2
+ grep -E '%[yz]mm[0-9]+|[[:space:]]v[a-z0-9]{2,}([[:space:]]|$)' <<<"$asm" | head -5 >&2
+ fail_count=$((fail_count + 1))
+ else
+ vlog "$variant ($f): no AVX-or-above instruction found, as expected"
+ fi
+done
+
+exe_name="$(out_name_for "$TRIPLE")"
+exe_path="$BIN_DIR/$exe_name"
+if [ -f "$exe_path" ]; then
+ asm="$(disassemble "$exe_path")"
+ if has_avx_or_above "$asm"; then
+ printf '\033[1;31m[verify-sidecar-isa] FAIL:\033[0m %s (the exe itself) contains an AVX-or-above instruction, it must be ISA-neutral, all CPU-specific code belongs in the ggml-cpu-* variants:\n' "$exe_path" >&2
+ grep -E '%[yz]mm[0-9]+|[[:space:]]v[a-z0-9]{2,}([[:space:]]|$)' <<<"$asm" | head -5 >&2
+ fail_count=$((fail_count + 1))
+ else
+ vlog "$exe_name: no AVX-or-above instruction found, as expected"
+ fi
+else
+ vlog "no exe found at $exe_path, skipping the exe-itself check (build first for the full check)"
+fi
+
+# Positive control: without this, a broken disassembler invocation (a typo'd
+# flag, a tool that silently prints nothing) would make every check above
+# pass vacuously. haswell is the first tier with AVX2, so it MUST show up.
+f="$(find_variant_file "$POSITIVE_CONTROL")"
+asm="$(disassemble "$f")"
+if ! has_avx_or_above "$asm"; then
+ vdie "$f (the $POSITIVE_CONTROL variant, which IS supposed to use AVX2) shows no AVX instruction at all, the disassembler step itself is not working, every 'no AVX found' result above is unproven"
+fi
+vlog "$POSITIVE_CONTROL ($f): AVX-or-above instruction found, confirming the disassembler actually sees the ISA it is looking for"
+
+[ "$fail_count" -eq 0 ] || vdie "$fail_count file(s) failed the no-AVX-in-the-baseline check"
+
+vlog "OK: $TRIPLE sidecar, dynamic ISA layout intact, baseline files carry no AVX, disassembler proven working"
diff --git a/src-tauri/resources/llama/.gitignore b/src-tauri/resources/llama/.gitignore
new file mode 100644
index 00000000..795ef906
--- /dev/null
+++ b/src-tauri/resources/llama/.gitignore
@@ -0,0 +1,5 @@
+# Companion ggml/llama shared libraries for the dynamic-ISA sidecar builds
+# (Windows, Linux; see scripts/build-llama.sh, K1 3.0.1). Build artifacts,
+# never committed, same rule as src-tauri/bin/.gitignore.
+*/
+!.gitignore
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index b65e9a30..34c2378b 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -916,6 +916,104 @@ fn resolve_engine_binary(app: &AppHandle) -> Option<PathBuf> {
dev_candidates.into_iter().find(|p| p.exists())
}
+/// K1 (3.0.1): directory holding the dynamic-ISA sidecar's companion
+/// ggml-cpu-*/ggml-vulkan libraries (Windows, Linux; see
+/// scripts/build-llama.sh). `None` on mac, which keeps the old static Metal
+/// binary and has nothing to find, and `None` when nothing was built yet (a
+/// start then runs exactly as it did before this change, and a genuine
+/// failure still surfaces through the ordinary StartFailure path instead of
+/// a made-up error here).
+///
+/// Mirrors `resolve_engine_binary`'s tiers: the bundled resource location
+/// first, then the dev-time path the build script writes straight to.
+fn resolve_engine_backend_dir(app: &AppHandle) -> Option<PathBuf> {
+ if cfg!(target_os = "macos") {
+ return None;
+ }
+ let triple = host_target_triple();
+
+ // 1. Bundled. Windows: tauri.windows.conf.json flattens the companion
+ // DLLs into the ROOT of the resource dir, which on Windows IS the same
+ // directory as the running executable (tauri's own resource_dir()
+ // docs), so this is also where lu-llama-server.exe itself sits. Linux:
+ // tauri.linux.conf.json nests them under a "llama/" subdirectory
+ // instead, because deb/AppImage keep externalBin (the exe, in
+ // usr/bin) and `resources` (usr/lib/<exe_name>) apart (see GitHub
+ // #120 in sidecar_binary_name's comment above for the externalBin
+ // placement, and tauri::path::resource_dir's own platform doc for the
+ // resource placement).
+ if let Ok(res) = app.path().resource_dir() {
+ let candidate = if cfg!(target_os = "windows") { res } else { res.join("llama") };
+ if candidate.is_dir() {
+ return Some(candidate);
+ }
+ }
+
+ // 2. Dev: scripts/build-llama.sh writes straight to
+ // src-tauri/resources/llama/<triple>/, the same source path
+ // tauri.windows.conf.json / tauri.linux.conf.json bundle from.
+ let mut dev_candidates: Vec<PathBuf> = Vec::new();
+ if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
+ dev_candidates.push(PathBuf::from(&manifest).join("resources").join("llama").join(&triple));
+ }
+ if let Ok(cwd) = std::env::current_dir() {
+ dev_candidates.push(cwd.join("src-tauri").join("resources").join("llama").join(&triple));
+ dev_candidates.push(cwd.join("resources").join("llama").join(&triple));
+ }
+ dev_candidates.into_iter().find(|p| p.is_dir())
+}
+
+/// K1 (3.0.1): point a bundled llama-server child at its companion
+/// ggml-cpu-*/ggml-vulkan libraries. No-op when `backend_dir` is `None`
+/// (mac, or nothing built yet).
+///
+/// This IS our own bundled sidecar, not a foreign program: `Command::new` is
+/// the right call here and `foreign_system_command`/`strip_appimage_env`
+/// (process_util.rs) would be wrong. On an AppImage this process WANTS the
+/// AppImage-mounted `LD_LIBRARY_PATH` it inherits (its own libvulkan.so.1
+/// etc, see the comment at ILLEGAL_INSTRUCTION_EXIT_CODE below); stripping
+/// it would undo the very thing K11 fixed for foreign programs one file
+/// over. This function only ever ADDS our own resources directory in front
+/// of whatever LD_LIBRARY_PATH the process already inherited.
+///
+/// Measured against the pinned llama.cpp source, not assumed:
+/// `ggml_backend_load_best` (ggml/src/ggml-backend-reg.cpp:479-486) scans
+/// only two places when no explicit path is given, the executable's OWN
+/// directory and the process's CURRENT directory. There is no search-LIST
+/// environment variable: `GGML_BACKEND_PATH` (same file, line 582) loads
+/// exactly one named file, so it cannot stand in for a directory holding
+/// nine-plus CPU variants. The current directory is the one lever that
+/// works the same way on every platform, so this sets it instead of
+/// reaching for an env var that does not do what the name suggests.
+///
+/// On Windows the companions are bundled flattened into the exe's own
+/// directory (see `resolve_engine_backend_dir`), which Windows' own DLL
+/// search order already covers with no help from this function; `current_dir`
+/// is set anyway; one fewer thing that has to stay true forever for this to
+/// keep working, the same belt-and-suspenders reasoning
+/// `resolve_engine_binary` already uses for its own second lookup tier. On
+/// Linux the companions sit in a separate resources directory (deb/AppImage
+/// keep externalBin and `resources` apart), and nothing in the pinned
+/// llama.cpp build sets an `$ORIGIN` rpath, so `current_dir` alone would get
+/// ggml's own variant SCAN right but the winning file's OWN dependency on
+/// libggml-base.so would still fail to resolve. `LD_LIBRARY_PATH` closes
+/// that second half.
+fn apply_engine_backend_dir(cmd: &mut Command, backend_dir: Option<&Path>) {
+ let Some(dir) = backend_dir else { return };
+ cmd.current_dir(dir);
+ #[cfg(target_os = "linux")]
+ {
+ let mut value = std::ffi::OsString::from(dir);
+ if let Some(existing) = std::env::var_os("LD_LIBRARY_PATH") {
+ if !existing.is_empty() {
+ value.push(":");
+ value.push(existing);
+ }
+ }
+ cmd.env("LD_LIBRARY_PATH", value);
+ }
+}
+
// ── Health probe ─────────────────────────────────────────────────────────────
/// The slot that actually holds the conversation. llama-server distributes
@@ -1796,7 +1894,7 @@ fn start_bundled_engine_blocking(
{
Ok(v) => Ok(v),
Err(msg) => Err(match (vorher, resolve_engine_binary(app)) {
- (Some(p), Some(bin)) if restore_engine(&bin, state, &p) => {
+ (Some(p), Some(bin)) if restore_engine(&bin, state, &p, resolve_engine_backend_dir(app).as_deref()) => {
with_note_on_top(&msg, RESTORED_NOTE)
}
_ => msg,
@@ -1832,7 +1930,7 @@ const RESTORED_NOTE: &str = "The model that was serving before is running again.
/// Wiederholung: er bediente vor Sekunden noch, und ein zweiter Fehlschlag
/// hier waere nichts, woran ein Nutzer etwas aendern koennte. Er wuerde nur
/// die Fehlermeldung des eigentlichen Problems um Minuten verzoegern.
-fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine) -> bool {
+fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine, backend_dir: Option<&Path>) -> bool {
tracing::warn!(target: "engine", model = %vorher.model_path, port = vorher.port, "the model switch failed, bringing the previous model back");
let ok = spawn_engine_attempt(
state,
@@ -1842,6 +1940,7 @@ fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine) -> b
vorher.port,
vorher.ctx,
AttemptFlags { auto_layers: vorher.auto_layers, cpu_fallback: vorher.cpu_fallback },
+ backend_dir,
)
.is_ok();
if !ok {
@@ -1929,6 +2028,10 @@ fn start_after_stop(
sidecar_binary_name()
)
})?;
+ // K1 (3.0.1): where the dynamic-ISA sidecar's companion libraries are,
+ // None on mac / a static build. Resolved once here and carried through
+ // both attempts and the sanity-probe restarts below, same as `binary`.
+ let backend_dir = resolve_engine_backend_dir(app);
// Attempt 1, then exactly one clean retry.
//
@@ -2011,6 +2114,7 @@ fn start_after_stop(
port,
ctx,
AttemptFlags { auto_layers, cpu_fallback: false },
+ backend_dir.as_deref(),
);
let failure = match first {
Ok(startup) => {
@@ -2027,6 +2131,7 @@ fn start_after_stop(
ctx,
auto_layers,
&startup,
+ backend_dir.as_deref(),
));
}
Err(f) => f,
@@ -2117,6 +2222,7 @@ fn start_after_stop(
retry_port,
ctx,
AttemptFlags { auto_layers: retry_auto, cpu_fallback: offload_was_tried },
+ backend_dir.as_deref(),
) {
Ok(startup) => {
if offload_was_tried {
@@ -2146,6 +2252,7 @@ fn start_after_stop(
ctx,
retry_auto,
&startup,
+ backend_dir.as_deref(),
);
answer["retried"] = serde_json::json!(true);
answer["cpuOnly"] = serde_json::json!(offload_was_tried);
@@ -2209,6 +2316,7 @@ fn serve_or_heal_garbled(
ctx: Option<u32>,
auto_layers: bool,
startup: &str,
+ backend_dir: Option<&Path>,
) -> serde_json::Value {
let mut answer = started_answer(port, model_path, ctx);
// Measured once, from what llama-server itself printed on its way up. A
@@ -2326,6 +2434,7 @@ fn serve_or_heal_garbled(
port,
ctx,
AttemptFlags { auto_layers: false, cpu_fallback: cpu_rung },
+ backend_dir,
).is_err() {
// The restart did not come up, and an engine that at least served
// has just been torn down for it. Put the first one back rather
@@ -2344,6 +2453,7 @@ fn serve_or_heal_garbled(
port,
ctx,
AttemptFlags { auto_layers, cpu_fallback: false },
+ backend_dir,
);
answer["garbled"] = serde_json::json!(true);
// Not the CPU sentence. Nothing ran on the processor here and
@@ -2424,6 +2534,7 @@ struct AttemptFlags {
/// naming fp16, the warp size and whether the card has matrix cores, and the
/// flash-attention rung of the sanity probe is decided on it. It used to be
/// read on the failure paths only and thrown away whenever the engine came up.
+#[allow(clippy::too_many_arguments)]
fn spawn_engine_attempt(
state: &AppState,
binary: &Path,
@@ -2432,6 +2543,7 @@ fn spawn_engine_attempt(
port: u16,
ctx: Option<u32>,
flags: AttemptFlags,
+ backend_dir: Option<&Path>,
) -> Result<String, StartFailure> {
log_cpu_features_once();
// The one line a support log has to carry. Everything the start depends on
@@ -2460,6 +2572,10 @@ fn spawn_engine_attempt(
if let Ok(sel) = state.gpu_selection.lock() {
crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
}
+ // K1 (3.0.1): point a dynamic-ISA sidecar (Windows/Linux) at its
+ // ggml-cpu-*/ggml-vulkan companion libraries. No-op on mac / a static
+ // build, see apply_engine_backend_dir.
+ apply_engine_backend_dir(&mut cmd, backend_dir);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -3358,6 +3474,10 @@ fn start_bundled_embed_blocking(
if let Ok(sel) = state.gpu_selection.lock() {
crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
}
+ // K1 (3.0.1): this is the same dynamic-ISA binary the chat engine spawns
+ // (`spawn_engine_attempt`), so it needs the same companion-library
+ // directory; see apply_engine_backend_dir.
+ apply_engine_backend_dir(&mut cmd, resolve_engine_backend_dir(app).as_deref());
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -4445,6 +4565,115 @@ mod tests {
}
}
+ // ── K1 (3.0.1): apply_engine_backend_dir ──────────────────────────────
+
+ #[test]
+ fn apply_engine_backend_dir_is_a_noop_without_a_directory() {
+ // mac (static build) and "nothing built yet" both pass None here, and
+ // the spawned Command must come out exactly as `Command::new` left
+ // it: no current_dir, no LD_LIBRARY_PATH this function did not put
+ // there itself.
+ let mut cmd = Command::new("echo");
+ apply_engine_backend_dir(&mut cmd, None);
+ assert!(cmd.get_current_dir().is_none());
+ assert!(!cmd.get_envs().any(|(k, _)| k == "LD_LIBRARY_PATH"));
+ }
+
+ #[test]
+ fn apply_engine_backend_dir_sets_current_dir_when_given_one() {
+ // The one lever ggml_backend_load_best actually reads when no
+ // explicit search path is passed (ggml-backend-reg.cpp:479-486): the
+ // executable's own directory, and the process's CURRENT directory.
+ // Without this, a dynamic-ISA sidecar spawned from an arbitrary cwd
+ // would silently fail to find ggml-cpu-*/ggml-vulkan.
+ let dir = std::env::temp_dir();
+ let mut cmd = Command::new("echo");
+ apply_engine_backend_dir(&mut cmd, Some(&dir));
+ assert_eq!(cmd.get_current_dir(), Some(dir.as_path()));
+ }
+
+ // Serializes the two tests below: both read and mutate the process-wide
+ // LD_LIBRARY_PATH, and cargo test runs in threads by default. Same
+ // pattern as process_util.rs's own env_guard, kept local here since that
+ // one is private to its own test module.
+ #[cfg(target_os = "linux")]
+ fn ld_library_path_env_guard() -> std::sync::MutexGuard<'static, ()> {
+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ LOCK.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn apply_engine_backend_dir_prepends_ld_library_path_on_linux() {
+ // Linux-only: nothing in the pinned llama.cpp build sets an $ORIGIN
+ // rpath (measured against the checkout, not assumed), so a
+ // ggml-cpu-*.so's own dependency on libggml-base.so needs
+ // LD_LIBRARY_PATH, current_dir alone is not enough there. This test
+ // is red without the fix: before apply_engine_backend_dir touched
+ // LD_LIBRARY_PATH at all, get_envs() never carried the key.
+ let _guard = ld_library_path_env_guard();
+ std::env::set_var("LD_LIBRARY_PATH", "/tmp/.mount_LocallieGkad/usr/lib");
+ let dir = std::path::Path::new("/opt/lu/resources/llama/x86_64-unknown-linux-gnu");
+ let mut cmd = Command::new("echo");
+ apply_engine_backend_dir(&mut cmd, Some(dir));
+ let value = cmd
+ .get_envs()
+ .find(|(k, _)| *k == "LD_LIBRARY_PATH")
+ .and_then(|(_, v)| v)
+ .expect("LD_LIBRARY_PATH must be set")
+ .to_string_lossy()
+ .into_owned();
+ assert_eq!(value, "/opt/lu/resources/llama/x86_64-unknown-linux-gnu:/tmp/.mount_LocallieGkad/usr/lib");
+ // The process's OWN inherited value (the AppImage's own
+ // LD_LIBRARY_PATH, per K11/K14) survives behind it, not overwritten:
+ // this process's own sidecar WANTS the AppImage-mounted libraries too
+ // (Vulkan), unlike a foreign program.
+ assert!(value.ends_with("/tmp/.mount_LocallieGkad/usr/lib"), "{value}");
+ std::env::remove_var("LD_LIBRARY_PATH");
+ }
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn apply_engine_backend_dir_does_not_drop_an_empty_inherited_value() {
+ // Negative control: an empty (but SET) inherited LD_LIBRARY_PATH must
+ // not turn into a trailing ":" with nothing after it.
+ let _guard = ld_library_path_env_guard();
+ std::env::set_var("LD_LIBRARY_PATH", "");
+ let dir = std::path::Path::new("/opt/lu/resources/llama/x86_64-unknown-linux-gnu");
+ let mut cmd = Command::new("echo");
+ apply_engine_backend_dir(&mut cmd, Some(dir));
+ let value = cmd
+ .get_envs()
+ .find(|(k, _)| *k == "LD_LIBRARY_PATH")
+ .and_then(|(_, v)| v)
+ .expect("LD_LIBRARY_PATH must be set")
+ .to_string_lossy()
+ .into_owned();
+ assert_eq!(value, dir.to_str().unwrap());
+ std::env::remove_var("LD_LIBRARY_PATH");
+ }
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn apply_engine_backend_dir_sets_ld_library_path_with_none_inherited() {
+ // The base case: no LD_LIBRARY_PATH in the environment at all (a
+ // plain deb/rpm install, not an AppImage). Must still be set to
+ // exactly the backend dir, nothing appended.
+ let _guard = ld_library_path_env_guard();
+ std::env::remove_var("LD_LIBRARY_PATH");
+ let dir = std::path::Path::new("/opt/lu/resources/llama/x86_64-unknown-linux-gnu");
+ let mut cmd = Command::new("echo");
+ apply_engine_backend_dir(&mut cmd, Some(dir));
+ let value = cmd
+ .get_envs()
+ .find(|(k, _)| *k == "LD_LIBRARY_PATH")
+ .and_then(|(_, v)| v)
+ .expect("LD_LIBRARY_PATH must be set")
+ .to_string_lossy()
+ .into_owned();
+ assert_eq!(value, dir.to_str().unwrap());
+ }
+
#[test]
fn the_bundled_sidecar_name_is_ours_and_not_one_debian_already_owns() {
// GitHub #120 (AnnSdf1969, Ubuntu 26.04): Tauri's deb bundler copies
@@ -5015,6 +5244,7 @@ mod tests {
Path::new(&crate::test_support::posix_shell()),
&state,
&vorher,
+ None,
);
assert!(zurueck, "the previous engine did not come back");
@@ -5057,7 +5287,8 @@ mod tests {
assert!(!restore_engine(
Path::new(&crate::test_support::posix_shell()),
&state,
- &vorher
+ &vorher,
+ None,
));
assert!(
state.bundled_engine.lock().unwrap().is_none(),
diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.json
index b9663567..e35e8e0a 100644
--- a/src-tauri/tauri.linux.conf.json
+++ b/src-tauri/tauri.linux.conf.json
@@ -1,4 +1,10 @@
{
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
- "productName": "Locally Uncensored"
+ "productName": "Locally Uncensored",
+ "bundle": {
+ "resources": {
+ "resources/whisper_server.py": "resources/whisper_server.py",
+ "resources/llama/x86_64-unknown-linux-gnu/*": "llama/"
+ }
+ }
}
diff --git a/src-tauri/tauri.windows.conf.json b/src-tauri/tauri.windows.conf.json
index a9b290a3..438b90b3 100644
--- a/src-tauri/tauri.windows.conf.json
+++ b/src-tauri/tauri.windows.conf.json
@@ -15,5 +15,11 @@
"dragDropEnabled": false
}
]
+ },
+ "bundle": {
+ "resources": {
+ "resources/whisper_server.py": "resources/whisper_server.py",
+ "resources/llama/x86_64-pc-windows-msvc/*": ""
+ }
}
}
diff --git a/src/api/__tests__/build-llama-script.test.ts b/src/api/__tests__/build-llama-script.test.ts
index bd22612c..f02ae631 100644
--- a/src/api/__tests__/build-llama-script.test.ts
+++ b/src/api/__tests__/build-llama-script.test.ts
@@ -79,14 +79,47 @@ describe('build-llama.sh', () => {
expect(callFn('cmake_flags_for', 'x86_64-apple-darwin').out).toContain('x86_64')
})
- it('emits Vulkan flags for win/linux triples', () => {
+ it('emits Vulkan + dynamic-ISA flags for win/linux triples (K1, 3.0.1)', () => {
+ // K1: a fixed x86-64-v3 binary (SSE4.2+AVX+AVX2+BMI2+FMA+F16C baked in by
+ // GGML_NATIVE=OFF's INS_ENB=ON, ggml/CMakeLists.txt:141-166) crashed with
+ // 0xC000001D on Windows / SIGILL on Linux on any pre-Haswell/pre-Excavator
+ // CPU. GGML_BACKEND_DL + GGML_CPU_ALL_VARIANTS load the right CPU kernel
+ // at runtime instead, and that combination FATAL_ERRORs in the pinned
+ // llama.cpp unless BUILD_SHARED_LIBS=ON too
+ // (ggml/src/CMakeLists.txt:188-190, :371-376).
for (const triple of ['x86_64-pc-windows-msvc', 'x86_64-unknown-linux-gnu']) {
const { out } = callFn('cmake_flags_for', triple)
- expect(out).toContain('-DGGML_VULKAN=ON')
- expect(out).toContain('-DBUILD_SHARED_LIBS=OFF')
+ expect(out, triple).toContain('-DGGML_VULKAN=ON')
+ expect(out, triple).toContain('-DBUILD_SHARED_LIBS=ON')
+ expect(out, triple).toContain('-DGGML_BACKEND_DL=ON')
+ expect(out, triple).toContain('-DGGML_CPU_ALL_VARIANTS=ON')
+ // Unchanged: still no -march=native, still no runner-CPU lottery.
+ expect(out, triple).toContain('-DGGML_NATIVE=OFF')
+ }
+ })
+
+ it('keeps mac static: no dynamic-ISA flags on either Metal triple', () => {
+ for (const triple of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
+ const { out } = callFn('cmake_flags_for', triple)
+ expect(out, triple).not.toContain('GGML_BACKEND_DL')
+ expect(out, triple).not.toContain('GGML_CPU_ALL_VARIANTS')
}
})
+ it('is_dynamic_isa_triple: true only for the two win/linux triples', () => {
+ expect(callFn('is_dynamic_isa_triple', 'x86_64-pc-windows-msvc').code).toBe(0)
+ expect(callFn('is_dynamic_isa_triple', 'x86_64-unknown-linux-gnu').code).toBe(0)
+ expect(callFn('is_dynamic_isa_triple', 'aarch64-apple-darwin').code).not.toBe(0)
+ expect(callFn('is_dynamic_isa_triple', 'x86_64-apple-darwin').code).not.toBe(0)
+ })
+
+ it('resource_llama_dir_for: one directory per triple under src-tauri/resources/llama', () => {
+ const { out } = callFn('resource_llama_dir_for', 'x86_64-pc-windows-msvc')
+ expect(out.replace(/\\/g, '/')).toBe(
+ `${REPO_ROOT.replace(/\\/g, '/')}/src-tauri/resources/llama/x86_64-pc-windows-msvc`,
+ )
+ })
+
it('rejects an unsupported triple', () => {
const { code } = callFn('cmake_flags_for', 'mips-unknown-none')
expect(code).not.toBe(0)
@@ -114,6 +147,91 @@ describe('build-llama.sh', () => {
})
})
+/**
+ * K1 (3.0.1): staging the ggml-cpu-* and ggml-vulkan companion libraries a
+ * dynamic-ISA build produces next to llama-server. `stage_dynamic_isa_
+ * companions` is unit-tested against a directory of fake .dll/.so files
+ * rather than a real cmake build, the same way `ensure_src` above is tested
+ * against a fake git upstream instead of the real llama.cpp, the point is
+ * the shell logic, not the multi-minute compile.
+ */
+describe('build-llama.sh: staging the dynamic-ISA companion libraries', () => {
+ const temps: string[] = []
+ const tmp = (prefix: string) => {
+ const dir = mkdtempSync(join(tmpdir(), prefix))
+ temps.push(dir)
+ return dir.replace(/\\/g, '/')
+ }
+ afterAll(() => {
+ for (const dir of temps) rmSync(dir, { recursive: true, force: true })
+ })
+
+ /** Runs `stage_dynamic_isa_companions` with REPO_ROOT redirected into a
+ * throwaway directory, so a test run never writes into the real
+ * src-tauri/resources/llama/ tree. */
+ function stage(triple: string, binOutDir: string, exeOut: string) {
+ const repoRoot = tmp('llama-repo-root-')
+ const { code, out } = runScript(
+ `stage_dynamic_isa_companions '${triple}' '${binOutDir}' '${exeOut}'`,
+ { BUILD_LLAMA_REPO_ROOT: repoRoot },
+ )
+ return { code, out, repoRoot }
+ }
+
+ it('copies every matching .dll next to the resource dir on Windows, skipping the exe itself', () => {
+ const binOutDir = tmp('llama-bin-win-')
+ for (const name of ['llama-server.exe', 'ggml-cpu-x64.dll', 'ggml-cpu-haswell.dll', 'ggml-vulkan.dll', 'ggml-base.dll']) {
+ writeFileSync(join(binOutDir, name), name)
+ }
+ const { code, repoRoot } = stage('x86_64-pc-windows-msvc', binOutDir, join(binOutDir, 'llama-server.exe'))
+ expect(code).toBe(0)
+ const dir = join(repoRoot, 'src-tauri', 'resources', 'llama', 'x86_64-pc-windows-msvc')
+ for (const name of ['ggml-cpu-x64.dll', 'ggml-cpu-haswell.dll', 'ggml-vulkan.dll', 'ggml-base.dll']) {
+ expect(existsSync(join(dir, name)), name).toBe(true)
+ }
+ expect(existsSync(join(dir, 'llama-server.exe'))).toBe(false)
+ })
+
+ it('copies .so files on Linux, dereferencing symlinks (SONAME needs the real versioned name)', () => {
+ const binOutDir = tmp('llama-bin-linux-')
+ writeFileSync(join(binOutDir, 'llama-server'), 'exe')
+ writeFileSync(join(binOutDir, 'libggml-base.so.1.2.3'), 'real-bytes')
+ execFileSync('ln', ['-s', 'libggml-base.so.1.2.3', join(binOutDir, 'libggml-base.so.1')])
+ execFileSync('ln', ['-s', 'libggml-base.so.1', join(binOutDir, 'libggml-base.so')])
+ writeFileSync(join(binOutDir, 'libggml-cpu-haswell.so'), 'cpu-kernel')
+ const { code, repoRoot } = stage('x86_64-unknown-linux-gnu', binOutDir, join(binOutDir, 'llama-server'))
+ expect(code).toBe(0)
+ const dir = join(repoRoot, 'src-tauri', 'resources', 'llama', 'x86_64-unknown-linux-gnu')
+ // The exact SONAME the dynamic linker resolves DT_NEEDED against.
+ expect(readFileSync(join(dir, 'libggml-base.so.1'), 'utf8')).toBe('real-bytes')
+ // Dereferenced, not a dangling symlink: statSync follows by default, so
+ // this also proves it is a real file (a broken symlink throws ENOENT).
+ expect(statSync(join(dir, 'libggml-base.so.1')).isFile()).toBe(true)
+ expect(readFileSync(join(dir, 'libggml-cpu-haswell.so'), 'utf8')).toBe('cpu-kernel')
+ })
+
+ it('is a no-op for mac triples: no directory, no error, nothing staged', () => {
+ const binOutDir = tmp('llama-bin-mac-')
+ writeFileSync(join(binOutDir, 'llama-server'), 'exe')
+ const { code, out, repoRoot } = stage('aarch64-apple-darwin', binOutDir, join(binOutDir, 'llama-server'))
+ expect(code).toBe(0)
+ expect(out).toBe('')
+ expect(existsSync(join(repoRoot, 'src-tauri', 'resources', 'llama'))).toBe(false)
+ })
+
+ it('refuses a dynamic-ISA build with no companion libraries next to the exe', () => {
+ // Negative control for the fix itself: a plain llama-server with none of
+ // its ggml-cpu-*/ggml-vulkan libraries next to it is exactly the shape a
+ // broken cmake invocation (e.g. BUILD_SHARED_LIBS left OFF) would
+ // produce, and it must not ship silently as a single-ISA binary again.
+ const binOutDir = tmp('llama-bin-empty-')
+ writeFileSync(join(binOutDir, 'llama-server.exe'), 'exe')
+ const { code, out } = stage('x86_64-pc-windows-msvc', binOutDir, join(binOutDir, 'llama-server.exe'))
+ expect(code).not.toBe(0)
+ expect(out).toContain('produced no *.dll')
+ })
+})
+
/**
* The sidecar pin.
*