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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(engine): P0 — bundled llama.cpp build script + sidecar bin dir
purple2f839256756a
diff --git a/.gitignore b/.gitignoreindex 52557da8..0aae7c02 100644--- a/.gitignore+++ b/.gitignore@@ -64,3 +64,6 @@ discord_invite.txtcarl-bot-setup.mdapp-discord-integration.mdSETUP_REPORT.md++# Built-in engine: llama.cpp build cache (P0 scripts/build-llama.sh)+.llama-build/diff --git a/ONBOARDING-BUILTIN-ENGINE-PLAN.md b/ONBOARDING-BUILTIN-ENGINE-PLAN.mdnew file mode 100644index 00000000..2b5b2291--- /dev/null+++ b/ONBOARDING-BUILTIN-ENGINE-PLAN.md@@ -0,0 +1,235 @@+# LU 2.5.7 — Onboarding ohne externe Provider (Built-in Engine)++**Master-Plan für den autonomen Lauf. Noch nichts implementiert.**+Ziel: Beim neuen Launch (2.5.7) ist das Chat-Onboarding **komplett unabhängig+von Ollama / LM Studio**. Die App bringt ihre eigene Inference-Engine mit+(gebündeltes `llama.cpp`-Server-Binary). Externe Provider werden weiterhin+*erkannt und optional genutzt*, aber nie mehr *vorausgesetzt*.++---++## 0. Prinzip++- **Nicht** Inference selbst schreiben. Wir bündeln `llama.cpp` (`llama-server`),+ dieselbe Engine, die Ollama/LM Studio intern nutzen.+- **Maximaler Reuse:** `llama-server` spricht eine **OpenAI-kompatible API**+ (`/v1/chat/completions`, SSE-Streaming). Die App hat bereits einen voll+ funktionierenden `OpenAIProvider` + Rust-Proxy + Token-Streaming. Der neue+ „Built-in"-Backend ist damit nur ein **weiterer lokaler OpenAI-Backend** mit+ von uns verwaltetem Lifecycle — kein neuer Provider-Typ nötig.+- **Hybrid, nicht Rausriss:** Ollama/LM-Studio-Erkennung bleibt als „Advanced"-+ Pfad. Unabhängigkeit heißt *nicht mehr voraussetzen*, nicht *löschen*.++---++## 1. Ist-Zustand (verifiziert)++### Onboarding+- `src/components/onboarding/Onboarding.tsx` — Steps:+ `welcome → backends → comfyui → models → embeddings → done`+ (`STEP_ORDER`, Z. 28–29).+- **backends-Step (Z. 665–1045):** `detectLocalBackends()` scannt 12 lokale+ Backends. Wenn keiner da: primäre CTAs **„Install Ollama" (~570 MB)** /+ **„Install LM Studio"** via Tauri-Commands `install_ollama` / `install_lmstudio`.+ → **Genau hier sitzt die externe Abhängigkeit.**+- **models-Step (Z. 1402–1531):** lädt EIN Starter-Modell+ (`ONBOARDING_MODELS` = Qwen 2.5 0.5B GGUF, 400 MB, `lib/constants.ts`).+ Download-Routing (Z. 177–296): Ollama → `ollama pull`; LM Studio → GGUF-Datei.+- **embeddings-Step (Z. 1533–1615):** `nomic-embed-text` via `pullModelTauri`+ → **läuft heute NUR über Ollama** (RAG/Document-Chat hängt an Ollama).+- **State:** `settings.onboardingDone` (Zustand, localStorage `chat-settings`)+ + Filesystem-Marker `{APPDATA}/Locally Uncensored/onboarding_done`+ (`src-tauri/src/commands/system.rs`: `set_onboarding_done` / `is_onboarding_done`).++### Provider-Schicht+- Interface `ProviderClient` (`src/api/providers/types.ts` Z. 145–173).+- Registry-Factory (`src/api/providers/registry.ts`): schaltet auf+ `ollama | openai | anthropic`. Model-Routing per Prefix `provider::model`.+- Presets (`types.ts` Z. 32–61): u. a. bereits ein **`llama.cpp`-Preset**+ (`providerId: 'openai'`, `isLocal: true`, Port 8080/v1). → OpenAI-Pfad kann+ llama.cpp schon.+- `providerStore` (`src/stores/providerStore.ts`): Keys `ollama|openai|anthropic`,+ Default enabled = **Ollama**.+- Rust-Proxy: `proxy_localhost` + `proxy_localhost_stream_chunked`+ (`src-tauri/src/commands/proxy.rs`) — CORS/CSP-Bypass + echtes Token-Streaming+ über Tauri-Channel.++### Prozess-/Sidecar-Infrastruktur+- **Kein** `externalBin`/Sidecar in `tauri.conf.json`. Einzige gebündelte+ Ressource: `resources/whisper_server.py` (Python-Subprozess).+- Subprozess-Muster existiert: `start_ollama` (`src-tauri/src/commands/process.rs`+ Z. 637–687) — `Command::new`, Child in `AppState.ollama_process`, GPU-Env+ (`CUDA_VISIBLE_DEVICES`/`HIP_*`/`ONEAPI_*`), Windows Job-Object-Cleanup.+- `AppState` (`src-tauri/src/state.rs`): hält `ollama_process`, `comfy_process`,+ `downloads`, `gpu_selection`, `shutdown_subprocesses()`.+- Health: `src-tauri/src/commands/health.rs` — HTTP-Probes 300 ms.+- Download: `src-tauri/src/commands/download.rs` — `download_model_to_path`+ (Resume, SSRF-Guard), `detect_model_path(provider)`.++### Build / Version+- Tauri 2, React 19 + Zustand 5, Vite 8.+- **Version an 3 Stellen:** `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`,+ `package.json` — aktuell alle `2.5.5` (Mac-Build 2.5.6 existiert lokal).+- CI `.github/workflows/release.yml`: Matrix **ubuntu-22.04 + windows-latest**;+ **macOS wird lokal gebaut** (kein CI). `tauri-action`, Updater-Signing.+- Release-Profile: `lto=true`, `opt-level="s"`, `strip=true`, `panic="abort"`.++---++## 2. Ziel-Architektur++```+Onboarding (built-in default)+ │ Download GGUF → App-Models-Dir+ ▼+Rust: start_bundled_engine(model, ctx, gpu)+ │ spawnt Sidecar llama-server -m <gguf> --host 127.0.0.1 --port 8127 ...+ ▼+llama-server ──OpenAI /v1/chat/completions (SSE)──► proxy_localhost_stream_chunked+ ▲ │+ └──────────── OpenAIProvider (unverändert) ◄─────────────┘+```++- **Neuer Backend `builtin`** = OpenAI-kompatibel auf verwaltetem Port,+ Lifecycle von der App gesteuert (Start/Stop/Model-Swap).+- **Model-Swap:** `llama-server` lädt 1 Modell pro Prozess → Modellwechsel =+ Prozess-Neustart mit neuem `-m`. (Ollama-artiges Verhalten, ~1–3 s.)+- **Binary:** `llama.cpp` **statisch** gebaut, Metal-Shader **eingebettet**+ (`-DGGML_METAL_EMBED_LIBRARY=ON`) → **ein einzelnes File pro Plattform**,+ ideal für Tauri-`externalBin` (kein dylib-Gefummel).++---++## 3. Entscheidungen (GELOCKT — 2026-07-06)++| # | Entscheidung | Beschluss |+|---|---|---|+| **E1** | Engine | ✅ `llama.cpp` `llama-server` als statisches Sidecar-Binary. |+| **E2** | Plattform-Scope für 2.5.7 | ✅ **mac-first** (arm64 + x86_64). Win/Linux = P6-Nachzug nach Launch. |+| **E3** | Externe Provider | ✅ **Behalten als „Advanced"**. Detection bleibt, CTAs wandern unter „andere Engine nutzen". Kein Code-Rausriss. |+| **E4** | Embeddings/RAG | ✅ **In-Scope für 2.5.7.** Voller Umbau: 2. `llama-server --embeddings` + RAG/Document-Chat auf Bundled-Embed umbiegen. Onboarding komplett Ollama-frei. → **P5 ist Kern, nicht optional.** |+| **E5** | Win/Linux GPU | Vulkan-Build (später, P6). CUDA-Variante danach. |++---++## 4. Phasenplan (autonom, Commit pro Phase)++Branch: `feat/builtin-engine`. Jede Phase: Unit-Test **und** (wo sinnvoll)+Playwright-e2e vor „done" (stehende Regel).++### P0 — Binary-Beschaffung & Build-Skript+- **Neu:** `scripts/build-llama.sh` — klont `llama.cpp` auf **gepinnten Tag**,+ cmake-Build mit:+ - mac: `-DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DBUILD_SHARED_LIBS=OFF`+ - win/linux: `-DGGML_VULKAN=ON -DBUILD_SHARED_LIBS=OFF`+ - kopiert `llama-server` → `src-tauri/bin/llama-server-<target-triple>[.exe]`.+- **Neu:** `src-tauri/bin/.gitignore` (Binaries **nicht** committen; im Build/CI+ erzeugt → kein Repo-Ballast, „no mess").+- Triples: `aarch64-apple-darwin`, `x86_64-apple-darwin`,+ `x86_64-pc-windows-msvc`, `x86_64-unknown-linux-gnu`.+- **Verifikation:** Skript lokal (mac arm64) → Binary startet,+ `curl 127.0.0.1:PORT/health` = ok, `/v1/models` antwortet.++### P1 — Rust: Sidecar-Lifecycle+- `tauri.conf.json` → `bundle.externalBin: ["bin/llama-server"]`+ (Tauri hängt Target-Triple automatisch an, signiert auf mac mit).+- **Neu:** `src-tauri/src/commands/engine.rs`:+ - `start_bundled_engine(model_path, ctx, gpu) -> u16` (Port, Sidecar-Resolve,+ `-m --host 127.0.0.1 --port --ctx-size -ngl 999` + GPU-Env, Child in State,+ auf `/health` warten).+ - `stop_bundled_engine()`, `bundled_engine_status()`,+ `swap_bundled_model(model_path)` (stop→start), `list_bundled_models()`+ (App-Models-Dir nach `*.gguf` scannen, geladenes markieren).+- `state.rs`: `bundled_engine: Mutex<Option<BundledEngine>>`+ ({child, model_path, port}); in `shutdown_subprocesses()` killen.+- `download.rs::detect_model_path`: `"builtin" =>` App-Data+ `.../Locally Uncensored/models` (auto-create).+- `main.rs`: Commands in `invoke_handler` registrieren.+- **Verifikation:** Rust-Unit-Test start/status/stop; manuell Chat-Roundtrip+ gegen den Sidecar.++### P2 — Frontend: Built-in-Backend verdrahten+- `types.ts`: Preset+ `{ id: 'builtin', name: 'Built-in Engine', providerId: 'openai',+ baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true }`.+- `registry.ts` / `providerStore.ts`: `builtin` → `OpenAIProvider` mit+ verwaltetem Base-URL; Default-enabled **von `ollama` auf `builtin`** umstellen.+ `managed`-Flag: kein User-URL/Key-Input, Lifecycle über Tauri-Commands.+- Model-Liste für `builtin` = `list_bundled_models` (nicht `/v1/models`, weil+ nur das geladene Modell erscheint). Modellwahl → `swap_bundled_model`.+- **Verifikation:** Unit-Test Registry-Routing `builtin→OpenAIProvider`;+ Chat-Stream-Test.++### P3 — Onboarding-UX+- **backends-Step:** neue Default-Karte **„Built-in Engine — nichts zu+ installieren"** (vorausgewählt). `detectLocalBackends()` bleibt; gefundene+ Ollama/LM-Studio erscheinen als **„Ebenfalls erkannt … (Advanced)"**. Die+ großen Install-CTAs wandern unter ein aufklappbares **„Andere Engine nutzen"**.+- **models-Step:** GGUF → App-Models-Dir (`download_model_to_path`), danach+ `start_bundled_engine`. Progress-Store unverändert nutzbar.+- **finish():** unverändert (`onboardingDone` + Marker).+- **Verifikation:** Playwright-e2e **Fresh-Onboarding**: welcome → built-in →+ Modell laden → Chat senden → Antwort. **Das ist der Akzeptanztest.**++### P4 — „Andere Engine" / Advanced-Settings+- Backend-Switcher (`BackendSelector.tsx`, Settings→Providers) zeigt `builtin`+ als Standard; Ollama/LM Studio wählbar wenn erkannt.+- Ollama/LM-Studio-Install-Buttons bleiben erreichbar (Advanced), nur nicht mehr+ im kritischen Onboarding-Pfad.++### P5 — Embeddings-Unabhängigkeit (E4, IN-SCOPE)+- 2. `llama-server --embeddings` auf eigenem Port mit Embedding-GGUF+ (`nomic-embed-text` / `bge-small` GGUF), eigener Lifecycle in `engine.rs`+ (`start/stop_bundled_embed`), Child in `AppState.bundled_embed`.+- **RAG-Umbau:** alle Aufrufe, die heute Ollama-`/api/embeddings` nutzen+ (Document-Chat, Memory-Embeddings), auf OpenAI-`/v1/embeddings` gegen den+ Bundled-Embed-Server umbiegen. → Ollama-Referenzen im RAG-Pfad suchen &+ ersetzen (Codebase-Sweep vor Umbau).+- Onboarding-embeddings-Step: statt `ollama pull` → GGUF-Download + Embed-Server+ starten. Auto-Skip-Heuristik (`embed`/`bge-`/`nomic`) beibehalten.+- **Verifikation:** e2e Document-Chat gegen den Bundled-Embed (kein Ollama läuft).++### P6 — Windows/Linux (nach mac-Launch)+- `build-llama.sh` Vulkan-Pfad; CI `release.yml` Matrix-Step+ „llama.cpp bauen vor `tauri build`".+- Windows-Defender-Whitelisting/Signing des Sidecars prüfen.++### P7 — Version, Cleanup, Doku+- Version `2.5.5 → 2.5.7` in **allen 3** Dateien.+- `bundle.longDescription`: „built-in engine, zero setup" ergänzen.+- Marketing-Copy (Onboarding-welcome) auf „läuft sofort, ohne Fremdsoftware".++---++## 5. Test-Strategie+- **Rust unit:** engine start/stop/status/swap (echtes Binary in CI-Job).+- **Frontend unit:** Registry-Routing, `list_bundled_models`, Model-Swap-Aktion.+- **Playwright e2e (Pflicht):** Fresh-Onboarding-Happy-Path bis erste+ Chat-Antwort über die Built-in-Engine; zweiter Lauf: Modellwechsel.+- **Regression:** Ollama-Pfad (falls installiert) weiterhin nutzbar.++## 6. Build / CI / Packaging+- `externalBin` → Tauri kopiert + signiert Sidecar in App-Bundle (mac).+- **Notarization prüfen:** Sidecar muss mit-notarisiert werden (Hardened Runtime,+ Entitlements für JIT falls nötig). Kritischer mac-Risikopunkt.+- CI: llama.cpp-Build-Step **vor** `tauri build` je Plattform.+- App-Größe: +~30–80 MB/Plattform (akzeptabel, dokumentieren).++## 7. No-Mess-Checkliste+- [ ] Sidecar-Binaries **nicht** im Git (nur Build-Artefakt).+- [ ] Kein toter Feature-Flag; `builtin` ist echtes Feature.+- [ ] Ollama/LM-Studio-Code bleibt funktional (Advanced), keine `_unused`-Leichen.+- [ ] `onboardingDone`-Marker-Semantik unangetastet.+- [ ] Version in allen 3 Dateien synchron.+- [ ] `scripts/build-llama.sh` idempotent, gepinnter Tag, reproduzierbar.++## 8. Rollback+- Alles auf `feat/builtin-engine`. Fällt Notarization/GPU: Branch nicht mergen,+ Onboarding-Default zurück auf Detection. Kein Prod-Impact bis Merge+Release.++## 9. Reihenfolge für den autonomen Lauf+`P0 → P1 → P2 → P3` = **Chat-Unabhängigkeit auf mac**.+`P4` Advanced-Politur, **`P5` Embeddings/RAG (in-scope, macht Onboarding+komplett Ollama-frei)**, `P7` Version/Release. **`P6` Win/Linux = nach Launch.**+Merge-Akzeptanz 2.5.7: e2e Fresh-Onboarding→Chat (P3) **und** e2e+Document-Chat ohne Ollama (P5) grün.diff --git a/scripts/build-llama.sh b/scripts/build-llama.shnew file mode 100755index 00000000..a0c50a7a--- /dev/null+++ b/scripts/build-llama.sh@@ -0,0 +1,152 @@+#!/usr/bin/env bash+#+# 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+# 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).+#+# Idempotent: clones/pins llama.cpp once into a build cache, reuses it on reruns.+# Binaries are NOT committed — see src-tauri/bin/.gitignore.+#+# Usage:+# scripts/build-llama.sh # build for the host target triple+# scripts/build-llama.sh <triple> ... # build for one or more explicit triples+# scripts/build-llama.sh --check # verify already-built host binary boots+#+# Supported triples:+# aarch64-apple-darwin (Metal, embedded shaders) — mac-first+# x86_64-apple-darwin (Metal, embedded shaders) — mac-first+# x86_64-pc-windows-msvc (Vulkan) — P6, after launch+# x86_64-unknown-linux-gnu (Vulkan) — P6, after launch+#+set -euo pipefail++# --- Pinned, reproducible llama.cpp revision -------------------------------+# Bump deliberately and re-test; do not float. llama.cpp tags are build numbers.+LLAMA_TAG="${LLAMA_TAG:-b6231}"+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)"+CACHE_DIR="${LLAMA_BUILD_CACHE:-$REPO_ROOT/.llama-build}"+SRC_DIR="$CACHE_DIR/llama.cpp"+BIN_DIR="$REPO_ROOT/src-tauri/bin"++log() { printf '\033[1;35m[build-llama]\033[0m %s\n' "$*"; }+die() { printf '\033[1;31m[build-llama] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }++host_triple() {+ if command -v rustc >/dev/null 2>&1; then+ rustc --print host-tuple 2>/dev/null && return+ rustc -vV 2>/dev/null | awk '/^host:/{print $2}'+ else+ # Fallback for macOS without rustc on PATH.+ case "$(uname -sm)" in+ "Darwin arm64") echo "aarch64-apple-darwin" ;;+ "Darwin x86_64") echo "x86_64-apple-darwin" ;;+ *) die "cannot infer host triple; pass one explicitly" ;;+ esac+ fi+}++# Map a Rust target triple → cmake flags for a static, GPU-embedded llama-server.+cmake_flags_for() {+ local triple="$1"+ local common="-DBUILD_SHARED_LIBS=OFF -DLLAMA_CURL=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" ;;+ x86_64-apple-darwin)+ echo "$common -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=x86_64" ;;+ x86_64-pc-windows-msvc)+ echo "$common -DGGML_VULKAN=ON" ;;+ x86_64-unknown-linux-gnu)+ echo "$common -DGGML_VULKAN=ON" ;;+ *)+ die "unsupported target triple: $triple" ;;+ esac+}++out_name_for() {+ case "$1" in+ *-windows-*) echo "llama-server-$1.exe" ;;+ *) echo "llama-server-$1" ;;+ esac+}++ensure_src() {+ command -v git >/dev/null 2>&1 || die "git not found"+ command -v cmake >/dev/null 2>&1 || die "cmake not found — install it (macOS: brew install cmake)"+ mkdir -p "$CACHE_DIR"+ if [ ! -d "$SRC_DIR/.git" ]; then+ log "cloning llama.cpp @ $LLAMA_TAG"+ git clone --depth 1 --branch "$LLAMA_TAG" "$LLAMA_REPO" "$SRC_DIR"+ else+ local have+ have="$(git -C "$SRC_DIR" describe --tags --exact-match 2>/dev/null || true)"+ if [ "$have" != "$LLAMA_TAG" ]; then+ log "updating llama.cpp checkout → $LLAMA_TAG"+ git -C "$SRC_DIR" fetch --depth 1 origin "refs/tags/$LLAMA_TAG:refs/tags/$LLAMA_TAG"+ git -C "$SRC_DIR" checkout -f "$LLAMA_TAG"+ fi+ fi+}++build_triple() {+ local triple="$1"+ local build_dir="$CACHE_DIR/build-$triple"+ local flags; flags="$(cmake_flags_for "$triple")"+ log "configuring $triple ($flags)"+ # shellcheck disable=SC2086+ cmake -S "$SRC_DIR" -B "$build_dir" $flags+ log "building llama-server for $triple"+ cmake --build "$build_dir" --config Release --target llama-server -j+ # Locate the produced binary (path differs by generator/platform).+ local built+ built="$(find "$build_dir" -type f \( -name 'llama-server' -o -name 'llama-server.exe' \) -print -quit)"+ [ -n "$built" ] || die "llama-server binary not found under $build_dir"+ mkdir -p "$BIN_DIR"+ local out="$BIN_DIR/$(out_name_for "$triple")"+ cp "$built" "$out"+ chmod +x "$out"+ log "installed → $out"+}++# Boot the host binary and probe /health + /v1/models on an ephemeral port.+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"+ local port=8129+ log "boot check: $bin on 127.0.0.1:$port (no model, /health only)"+ "$bin" --host 127.0.0.1 --port "$port" --models "$CACHE_DIR" >/dev/null 2>&1 &+ local pid=$!+ trap 'kill "$pid" 2>/dev/null || true' EXIT+ local ok=""+ for _ in $(seq 1 30); do+ if curl -fsS "http://127.0.0.1:$port/health" >/dev/null 2>&1; then ok=1; break; fi+ sleep 0.3+ done+ kill "$pid" 2>/dev/null || true+ trap - EXIT+ [ -n "$ok" ] || die "health endpoint never came up"+ log "OK — llama-server boots and answers /health"+}++main() {+ if [ "${1:-}" = "--check" ]; then check_binary; exit 0; fi+ local targets=("$@")+ if [ "${#targets[@]}" -eq 0 ]; then targets=("$(host_triple)"); fi+ ensure_src+ for t in "${targets[@]}"; do build_triple "$t"; done+ log "done: ${targets[*]}"+}++# Only run when executed directly, so tests can source the pure functions.+if [ "${BASH_SOURCE[0]}" = "${0}" ]; then+ main "$@"+fidiff --git a/src-tauri/bin/.gitignore b/src-tauri/bin/.gitignorenew file mode 100644index 00000000..14c2d370--- /dev/null+++ b/src-tauri/bin/.gitignore@@ -0,0 +1,4 @@+# Bundled llama.cpp sidecar binaries are build artifacts, never committed.+# Produced by scripts/build-llama.sh into llama-server-<target-triple>[.exe].+llama-server-*+!.gitignorediff --git a/src/api/__tests__/build-llama-script.test.ts b/src/api/__tests__/build-llama-script.test.tsnew file mode 100644index 00000000..8ee3bc9b--- /dev/null+++ b/src/api/__tests__/build-llama-script.test.ts@@ -0,0 +1,70 @@+import { describe, it, expect } from 'vitest'+import { execFileSync } from 'node:child_process'+import { resolve } from 'node:path'+import { existsSync, statSync } from 'node:fs'++// P0: unit-test the pure functions of scripts/build-llama.sh by sourcing it+// (main() is guarded so sourcing does not build anything) and invoking helpers.+const SCRIPT = resolve(__dirname, '../../../scripts/build-llama.sh')++function callFn(fn: string, ...args: string[]): { code: number; out: string } {+ const argv = args.map((a) => `'${a}'`).join(' ')+ try {+ const out = execFileSync(+ 'bash',+ ['-c', `source '${SCRIPT}'; ${fn} ${argv}`],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },+ )+ return { code: 0, out: out.trim() }+ } catch (e: any) {+ return { code: e.status ?? 1, out: String(e.stdout ?? '').trim() }+ }+}++describe('build-llama.sh', () => {+ it('exists and is executable', () => {+ expect(existsSync(SCRIPT)).toBe(true)+ // owner-executable bit set+ expect(statSync(SCRIPT).mode & 0o100).toBeTruthy()+ })++ it('emits Metal + embedded-library flags for both mac triples', () => {+ for (const triple of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {+ const { code, out } = callFn('cmake_flags_for', triple)+ expect(code).toBe(0)+ expect(out).toContain('-DGGML_METAL=ON')+ expect(out).toContain('-DGGML_METAL_EMBED_LIBRARY=ON')+ expect(out).toContain('-DBUILD_SHARED_LIBS=OFF')+ }+ expect(callFn('cmake_flags_for', 'aarch64-apple-darwin').out).toContain('arm64')+ expect(callFn('cmake_flags_for', 'x86_64-apple-darwin').out).toContain('x86_64')+ })++ it('emits Vulkan flags for win/linux triples', () => {+ 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')+ }+ })++ it('rejects an unsupported triple', () => {+ const { code } = callFn('cmake_flags_for', 'mips-unknown-none')+ expect(code).not.toBe(0)+ })++ it('appends .exe only for windows targets', () => {+ expect(callFn('out_name_for', 'x86_64-pc-windows-msvc').out).toBe(+ 'llama-server-x86_64-pc-windows-msvc.exe',+ )+ expect(callFn('out_name_for', 'aarch64-apple-darwin').out).toBe(+ 'llama-server-aarch64-apple-darwin',+ )+ })++ it('resolves a non-empty host triple', () => {+ const { code, out } = callFn('host_triple')+ expect(code).toBe(0)+ expect(out).toMatch(/-/)+ })+})