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
hotfix v2.4.9: Bug U + V/a + V/b + W + X (5 bug fixes) + F45 + F46 (2 features) + F45 followup polish (in-app card + real progress bar)
purplea04acb5675d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7732cb64..f738cb12 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,54 @@ All notable changes to Locally Uncensored are documented here.## [Unreleased]+## [2.4.9] - 2026-05-25++Sweep release on top of v2.4.8. Five bug fixes (U — GH #47 levoy1; V — Discord kj103x 2026-05-23 #help-chat, split into V/a RAG-persistence and V/b Ollama-orphan; W — Discord nightmare13740 2026-05-23/24 benchmark followup; X — Discord leonsk29 2026-05-24 #general thinking/agent toggles) plus two leonsk29 feature requests (GH #45 + GH #46).++### Fixed — ComfyUI Desktop App detection (Bug U)++- **Onboarding now recognises the ComfyUI Desktop App** (GH #47, levoy1 2026-05-24). Pre-v2.4.9 both auto-detect (`detect_all_comfyui_installs_sync`) and manual entry (`set_comfyui_path`) required `main.py` to be the path's direct child. Levoy1's ComfyUI Desktop App from comfyanonymous (default install `%LOCALAPPDATA%\Programs\ComfyUI`) ships only `ComfyUI.exe` next to the Electron resources — the actual ComfyUI Working Directory with `main.py`, `models/`, `custom_nodes/` is at `~\Documents\ComfyUI` by default (or wherever the desktop installer's picker pointed at, recorded in `%APPDATA%\ComfyUI\config.json`'s `basePath`). v2.4.9 adds a `resolve_comfyui_path` helper that accepts either layout: if the given dir has `main.py` it's a classic install, if it has `ComfyUI.exe` it's the Desktop App and we walk a probe list (`Documents\ComfyUI`, `Documents\ComfyUI\ComfyUI`, `%APPDATA%\ComfyUI` and its `config.json` `basePath` hint, `%LOCALAPPDATA%\ComfyUI`, `%LOCALAPPDATA%\Programs\ComfyUI\resources\ComfyUI`) until we find `main.py`. The auto-scan picks the same hints. When the binary dir is given but no Working Directory is reachable, the error message tells the user exactly which folder we need ("LU needs the ComfyUI Working Directory with main.py, models/, custom_nodes/ — by default `~\Documents\ComfyUI`") instead of the previous bare "main.py not found".++### Fixed — RAG document persistence (Bug V/a)++- **RAG embedding chunks survive an NSIS auto-update / WebView2 data reset** (kj103x Discord 2026-05-23 thread `1507756765612216411`, references GH Discussion #26 as "'fixed' but not really fixed"). v2.3.4 closed the chat-message half (3-leg backup of localStorage → `%APPDATA%\Locally Uncensored\store_backup.json`), but the RAG chunks (embedding vectors stored in IndexedDB at `locally-uncensored-rag → chunks` because 768-float vectors blow past localStorage's quota) were never in the backup pipeline. After an NSIS upgrade or WebView2 data wipe, `documents` (the file-metadata localStorage half of `rag-store`) restored fine but the chunks were lost — every RAG-enabled chat would show the document name and silently return no retrievals. v2.4.9 adds two Tauri commands (`backup_rag_chunks`, `restore_rag_chunks`, same atomic-temp-rename pattern as `backup_stores` to `%APPDATA%\Locally Uncensored\rag_chunks_backup.json`) and two `ragDB.ts` helpers (`exportAllChunks` / `importAllChunks`). The backup triad in `AppShell.tsx` now backs up RAG chunks on a 30 s interval + on `beforeunload`, separate cadence from the existing 5 s chat-snapshot triad because chunk payloads are heavy and change rarely (only on document upload/delete). Restore runs alongside `restore_stores` on cold start AND on warm starts where IndexedDB might be empty while localStorage has the doc metadata — and only imports entries the live store is missing, so a stale backup can't clobber newer in-app activity.++### Fixed — LU-spawned Ollama is killed on shutdown (Bug V/b)++- **Auto-installed `ollama serve` no longer lingers as a 200 MB orphan after LU quits** (same kj103x thread). The Drop impl on `AppState` already killed `comfy_process` and `claude_code_process` on shutdown, but Ollama was never stored — `start_ollama` and `auto_start_ollama` spawned `ollama serve` and discarded the `Child` handle, so quitting LU (tray → Quit) left `ollama.exe` running in the background indefinitely. v2.4.9 adds `ollama_process: Mutex<Option<Child>>` to `AppState`, captures the spawn in both call sites, and adds an Ollama kill leg to `Drop` that mirrors the ComfyUI taskkill `/T /F` pattern (kills the process tree). The pre-spawn tasklist check stays in place so we only ever store a `Child` we ourselves started — a user-managed `ollama serve` that was already running when LU launched is left alone, so quitting LU never kills someone else's Ollama. Hide-to-tray (`X` button) is unaffected: the page stays alive, Ollama keeps serving, no Drop runs until the user explicitly Quits from the tray menu. Same release also upgrades `exit_app` (used by the auto-updater to let NSIS swap the binary) from `std::process::exit(0)` to `app.exit(0)` so the Drop chain actually runs during an update — pre-v2.4.9 hard-exit bypassed every destructor and left both Ollama AND ComfyUI orphaned across upgrades.++### Fixed — Benchmark shows latest run, not running average (Bug W)++- **Per-model benchmark display is the latest session's tok/s, not a session-wide average that drifts as more samples accumulate** (nightmare13740 Discord 2026-05-23/24, Bug M retest). After the v2.4.8 Ollama `eval_count`/`eval_duration` fix, nightmare13740 ran gemma4:e4b ten times and watched the displayed tok/s climb from 15.2 to 17.9 across runs. They thought previous results were affecting new ones — they were, but only because `getAverageSpeed` in `benchmarkStore.ts` averaged every historical entry. Per-run measurements were stable; the UI was showing a drifting mean. v2.4.9 adds `getLatestSpeed(results, modelName)` which groups runs into "sessions" by a 10 s timestamp gap (one Run Benchmark click runs through BENCHMARK_PROMPTS in seconds, the next click is at least seconds later — usually minutes) and returns the mean of the most recent session only. `BenchmarkView.tsx` and `ModelBenchmark.tsx` switch to `getLatestSpeed`; the leaderboard keeps `getLeaderboard`/`getAverageSpeed` since cross-model comparison benefits from averaging out noise. Four new vitest cases pin the session-boundary logic.++### Fixed — Thinking + Agent toggles enable for community-uncensored Gemma 4 (Bug X)++- **`isThinkingCompatible` and `isAgentCompatible` now match dashed-family names (`gemma-4-…`) and multi-segment HF paths (`hf.co/<org>/<repo>:<tag>`)** (leonsk29 Discord #general 2026-05-24). Symptom: leonsk29 reported the Thinking + Agent toggles both grayed out for every Gemma 4 community variant LU's Discover tab pulls (TrevorJS, nohurry, Stabhappy, LiconStudio, huihui-ai) while the official `gemma4:e4b` from Ollama had both enabled. Root cause was a two-stage match failure in `model-compatibility.ts`: (1) the prefix strip was non-greedy (`/^[^/]+\//`), so `hf.co/trevorjs/gemma-4-31b-it-uncensored-gguf:q4_k_m` only lost `hf.co/` and kept `trevorjs/` in front of the family token; (2) the family-dash collapse was anchored to start-of-string, so `gemma-4-…` mid-string never normalized to `gemma4`; (3) the final `.startsWith` couldn't see past the community prefix `huihui-` / `mradermacher/Huihui-` etc. v2.4.9 rewrites `normalizeFamily` to (a) greedy-strip the full path prefix (catches `hf.co/<user>/<repo>:<quant>`), (b) drop GGUF repo cruft (`-gguf`, `-imatrix`, `-max`, `-i1`, `-ud`), (c) drop tuning/variant markers (`-abliterated`, `-uncensored`, `-heretic`, `-instruct`, `-it`, `-chat`, `-base`), (d) drop quant suffixes (`-q\d…`, `-iq\d…`, `-mxfp\d`, `-nvfp\d`, `-bf\d+`), (e) collapse `gemma-4` / `qwen-3` / `llama-3.1` / `glm-4` / `phi-4` to the dash-less family form anywhere they appear, then matches via a new `containsFamily(family, normalized)` regex that requires non-alphanumeric boundaries on both sides so `mistral` doesn't collide with `mistralfork` and `gemma3xyz` stays excluded. Six new test cases pin the leonsk29 cases (TrevorJS, nohurry, Stabhappy, LiconStudio uncensored / heretic / abliterated repos, two-slash `hf.co/<user>/<repo>` shape, Huihui-prefixed community uncensored builds). One previous "by design" limitation in `model-compatibility-planner.test.ts` for `hf.co/<bart>/gemma4-…` is flipped: it should match, that was always the bug.++### Feature — Onboarding suggests `nomic-embed-text` for Document Chat (GH #45)++- **New onboarding step pulls the embedding model needed for Document Chat / RAG** (leonsk29 GH #45). v2.4.9 inserts an `embeddings` step between `models` and `done` in `Onboarding.tsx` STEP_ORDER. The step probes Ollama's installed model list for anything containing `embed`/`bge-`/`nomic` and auto-shows a "✓ Embedding model already installed" card if any are present (covers LM Studio + Ollama users who already have one). Otherwise it offers a one-click Install for `nomic-embed-text` (274 MB, runs on any CPU) with a progress bar and a Skip button. The Tauri Ollama-pull path is reused (`pullModelTauri('nomic-embed-text')`), gated by a `start_ollama` / `checkOllama` retry loop in case the daemon isn't reachable yet.++- **Upgrade-path coverage for users who completed onboarding before v2.4.9.** The new step above only fires for fresh installs — v2.4.8 → v2.4.9 upgraders never hit it. Three additions close that gap:+ - **`useRAG.uploadDocument` no longer uses `window.confirm`** for the embedding-missing case. Instead, the dropped file is queued in `ragStore.embeddingQueuedFiles` and `embeddingInstallPrompt` flips on. `RAGPanel` renders an in-app card with a Download (274 MB) + Cancel pair, matching the rest of the app chrome. After the pull succeeds, queued files replay automatically through the same `uploadDocument` path.+ - **The pull stream now feeds real bytes-level progress** into `ragStore.embeddingPullProgress` via a `setEmbeddingPullProgress({completed, total, status})` setter. `RAGPanel` renders a deterministic progress bar with `formatBytes(completed) / formatBytes(total) · pct%` instead of the pre-v2.4.9 bouncing-icon banner that showed nothing for 30+ seconds while 274 MB pulled in the background. An indeterminate marquee covers the manifest / verification phases where Ollama doesn't emit byte totals.+ - **Opening the Document Chat panel proactively surfaces the install card** when nomic-embed-text is missing. `RAGPanelInner` runs a one-shot `ensureEmbeddingModel` probe on mount and flips `embeddingInstallPrompt` when the model isn't there, so an upgrading user clicks the Docs button → immediately sees "Embedding model needed… [Download] [Cancel]" without having to drop a file first. Cancel hides the card for the open panel; re-opening probes again. Chrome is neutral white/gray (no blue tint) to match the v2.4.8 Q-polish pattern.++### Feature — VRAM filter for text models in Discover (GH #46)++- **VRAM tier sub-filter (Lightweight ≤10 GB, Mid-Range 10–16 GB, High-End >16 GB) on the text tab** (leonsk29 GH #46). Pre-v2.4.9 only image and video bundles had this filter; text models could only be narrowed by Uncensored / Mainstream. v2.4.9 surfaces the same filter chips on the text category in `DiscoverModels.tsx` and applies them to both `getUncensoredTextModels()` and `getMainstreamTextModels()` via each model's `sizeGB` field (Q4 quant ≈ VRAM need for fully-offloaded inference). Cloud / `canPull:false` entries without a `sizeGB` bypass the filter and always show, since "VRAM" is meaningless for them.++### Stability++- `vitest`: **2312 tests** green (previously 2306; +6 across Bug W session boundaries in `stores/__tests__/benchmarkStore.test.ts` and Bug X community-uncensored matching in `api/__tests__/model-compatibility.test.ts`; existing `model-compatibility-planner.test.ts` cases for `stuff-gemma3-mix` + `hf.co/<bart>/gemma4-X` updated to the new permissive-match semantics).+- `cargo test`: **101 passed + 1 ignored** (no changes to the test surface for Bug U / V/b — those land via existing integration paths).+- `tsc --noEmit`: clean. `cargo check`: clean (pre-existing dead-code warnings only).+- No breaking changes; the new IndexedDB backup is purely additive.++### Heads-up++Windows + Linux only — macOS is not part of this build. `#bug-reports` / `#help-*` / GitHub monitored daily for regression reports. Still open from v2.4.8: 0yagizz OpenRouter half (passive, awaiting F12 console).+## [2.4.8] - 2026-05-23Drop-in hotfix on top of v2.4.6. v2.4.7 was tagged but not separately released, so v2.4.8 ships its six fixes alongside two new ones plus a UX polish: nine changes total since the last public release.diff --git a/README.md b/README.mdindex 5c4fe2ab..97d0533e 100644--- a/README.md+++ b/README.md@@ -35,12 +35,32 @@ No cloud. No data collection. No API keys. Auto-detects 12 local backends. Your----## v2.4.8 — Current Release+## v2.4.9 — Current Release-**Hotfix: 8 fixes on top of v2.4.6.** All user-reported. v2.4.7 was tagged but not separately released; its six fixes ship together with v2.4.8.+**Five bug fixes + two leonsk29 feature requests on top of v2.4.8.** All user-reported (GH levoy1 / kj103x Discord / nightmare13740 Discord / leonsk29 Discord + GH).Auto-update prompts on next launch.+### What's fixed+- **ComfyUI Desktop App is detected and accepted in onboarding** (Bug U — levoy1 GH #47). The Comfy-Org/desktop app installs to `%LOCALAPPDATA%\Programs\ComfyUI` with `ComfyUI.exe` but no `main.py` — the actual Working Directory with `main.py` / `models/` / `custom_nodes/` is at `~\Documents\ComfyUI` by default. Pre-v2.4.9 both auto-detect and manual path entry rejected the binary folder with "Invalid path — main.py not found". v2.4.9 follows the breadcrumb: when given a folder with `ComfyUI.exe`, it walks a probe list (`~\Documents\ComfyUI` / `%APPDATA%\ComfyUI` / `config.json basePath` / `%LOCALAPPDATA%\ComfyUI` / the app's bundled resources) until it finds `main.py`, and silently re-routes to the Working Directory.+- **Chats with attached RAG documents persist across NSIS auto-update / WebView2 data reset** (Bug V/a — kj103x Discord 2026-05-23). v2.3.4 closed the chat-message half (3-leg localStorage backup), but RAG embedding chunks live in IndexedDB (768-float vectors per chunk, can't fit in localStorage) and were never backed up. After an auto-update the document metadata restored but the chunks were lost — every RAG chat showed the document and returned no retrievals. v2.4.9 adds a separate 30 s / `beforeunload` IndexedDB backup → `%APPDATA%\Locally Uncensored\rag_chunks_backup.json`, restores on cold start AND on warm starts when IndexedDB is empty while the doc metadata isn't. Backup never clobbers newer in-app activity (only imports entries the live store is missing).+- **LU-spawned Ollama is killed when you quit LU** (Bug V/b — same kj103x report). Pre-v2.4.9 `ollama serve` lingered as a ~200 MB orphan with no tray icon. v2.4.9 stores the spawned `Child` on `AppState` and kills it on `Drop` using the same taskkill `/T /F` pattern as ComfyUI. The pre-spawn tasklist check stays — a user-managed Ollama that was already running when LU launched is left alone, so quitting LU never kills someone else's daemon. (Hide-to-tray via the `X` button is unaffected; Ollama only dies on a real Quit from the tray menu.)+- **Benchmark per-model display shows the latest session's tok/s, not a drifting historical average** (Bug W — nightmare13740 Discord 2026-05-23/24, Bug M retest). After the v2.4.8 server-eval-metric fix, ten benchmark runs on gemma4:e4b read 15.2 → 17.9 tok/s. Per-run measurements were stable; the UI was averaging every historical sample. v2.4.9 adds `getLatestSpeed` that groups runs into "sessions" via a 10 s timestamp gap and returns the mean of the most recent session only. Leaderboard keeps the cross-model average since that's the comparison that benefits from averaging out noise.+- **Thinking + Agent toggles light up for community-uncensored Gemma 4 builds** (Bug X — leonsk29 Discord 2026-05-24). Official `gemma4:e4b` worked but TrevorJS / nohurry / Stabhappy / LiconStudio / huihui-ai community variants pulled via `hf.co/<user>/<repo>:<quant>` had both toggles grayed out. Three stacked issues: the family-name normalizer only stripped one path segment (`hf.co/` but not `trevorjs/`), the dashed-family collapse was anchored to start-of-string (so `gemma-4-…` mid-string never normalized to `gemma4`), and the final match used `.startsWith` which couldn't see past a community prefix like `Huihui-Qwen3.5-…`. v2.4.9 rewrites `normalizeFamily` as a greedy strip + suffix/quant peel + family-dash collapse `/g`, then switches to a word-boundary contains-check so the family token can sit anywhere in the normalized name without false positives.++### What's new+- **Onboarding suggests `nomic-embed-text` for Document Chat / RAG** (GH #45 — leonsk29). New step between Models and Done that auto-detects existing embedding models (skipped with "✓ already installed" if any are present) or offers a one-click 274 MB pull. Skip button always available.+- **VRAM filter for text models in Discover** (GH #46 — leonsk29). The Lightweight ≤10 GB / Mid-Range 10–16 GB / High-End >16 GB chips that image and video already had now also filter the text tab, derived from each model's GGUF `sizeGB`. Cloud / `canPull:false` entries bypass the filter.++For previous release notes (v2.4.8 — 9 changes, v2.4.6 — 1 bug, v2.4.5 — 14 bugs), see [CHANGELOG.md](CHANGELOG.md).++---++<details>+<summary>v2.4.8 — superseded</summary>++**Hotfix: 8 fixes on top of v2.4.6.** All user-reported. v2.4.7 was tagged but not separately released; its six fixes ship together with v2.4.8.+### What's fixed- **Text models in Discover keep their INSTALLED badge after restart** (Bug S — leonsk29 GH #43). Pre-v2.4.8 the badge only lit up if the download finished in the current session, so a model installed yesterday looked uninstalled today. v2.4.8 also matches against the provider model list (Ollama tags directly, plus GGUF downloads via `hf.co/<repo>:<quant>` references), so whatever Ollama / LM Studio actually have on disk is what the Discover grid shows.- **`canPull:false` text models now get a clickable HuggingFace link** (Bug T — leonsk29 GH #44). Qwen 3.6 27B Samantha and GLM 5.1 754B MoE both have HF pages but no GGUF on day-one, so they show up as Available rather than downloadable. Before this they had no UI to open the HF page from inside LU. v2.4.8 adds the external-link button next to the Available badge.@@ -63,7 +83,7 @@ v2.4.8 is a Windows + Linux release; macOS is not part of this build. `#bug-repoStill investigating: OpenRouter half of 0yagizz's report (needs F12 console output to repro).-For previous release notes (v2.4.6 — 1 bug, v2.4.5 — 14 bugs), see [CHANGELOG.md](CHANGELOG.md).+</details>For older releases, see [CHANGELOG.md](CHANGELOG.md).diff --git a/docs/index.html b/docs/index.htmlindex afa9c15f..a2df063e 100644--- a/docs/index.html+++ b/docs/index.html@@ -33,7 +33,7 @@<link rel="icon" href="https://locallyuncensored.com/favicon.png"><link rel="apple-touch-icon" href="https://locallyuncensored.com/favicon.png"><script type="application/ld+json">-{"@context":"https://schema.org","@type":"SoftwareApplication","name":"Locally Uncensored","alternateName":["LU","Locally Uncensored Desktop App"],"applicationCategory":"DeveloperApplication","applicationSubCategory":"Artificial Intelligence","operatingSystem":"Windows 10, Windows 11, Linux","description":"Open-source desktop app for running AI locally. Chat with 20+ providers, generate images and video via ComfyUI, and code with a built-in AI agent — all on your own hardware. Auto-detects 12 local backends. No cloud, no telemetry.","url":"https://locallyuncensored.com/","downloadUrl":"https://github.com/PurpleDoubleD/locally-uncensored/releases/latest","softwareVersion":"2.4.8","license":"https://www.gnu.org/licenses/agpl-3.0.html","author":{"@type":"Person","name":"PurpleDoubleD","url":"https://github.com/PurpleDoubleD"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD","availability":"https://schema.org/InStock"},"featureList":["Plug & Play Setup with 12 Local Backend Auto-Detection (Ollama, LM Studio, vLLM, KoboldCpp, Jan, llama.cpp, LocalAI, GPT4All, TabbyAPI, Aphrodite, SGLang, TGI)","20+ Provider Presets (local + cloud)","Qwen 3.6 Day-0 Support (35B MoE, Vision, Agentic Coding, 256K context)","GPT-OSS Compatible (120B, 20B via Ollama)","GLM-4.7 Flash Integration","DeepSeek R1 and DeepSeek V3 Support","Llama 4 and Llama 3.3 Ready","Gemma 4 E4B and 27B (Native Vision)","Mistral Small 3 and Phi 4 Support","Qwen 3 Coder and Qwen 2.5 Coder","Abliterated Model Variants","Codex Coding Agent with Live Streaming and Apply-Patch","Claude Code CLI Integration","Agent Mode with 14 Tools, Parallel Execution, MCP, Sub-Agent Delegation","Remote Access from Phone via LAN or Cloudflare Tunnel (6-digit Passcode, QR Setup)","Mobile Web App (Chat, Codex, Tools, Plugins)","Image Generation via ComfyUI (FLUX 2 Klein, FLUX.1, Juggernaut XL, Z-Image Turbo, ERNIE-Image, SDXL, SD 3.5)","Video Generation (Wan 2.1, Wan 2.2, HunyuanVideo 1.5, LTX 2.3, FramePack F1, AnimateDiff, CogVideoX)","Image-to-Image with Denoise Control","Image-to-Video (FramePack F1, CogVideoX, SVD)","Granular Permission System (7 Tool Categories)","File Upload with Vision Support","Thinking Mode with Universal Tag Stripping","A/B Model Compare","Local Benchmark","Memory System and Document RAG","Voice (STT / TTS)","Auto-Update over Signed NSIS Channel","75+ One-Click Model Downloads","Hardware-Aware Model Recommendations","100% Offline and Private (No Telemetry)","AGPL-3.0 Open Source"],"screenshot":"https://raw.githubusercontent.com/PurpleDoubleD/locally-uncensored/master/docs/social-preview.png","softwareRequirements":"Any OpenAI-compatible local backend (Ollama, LM Studio, vLLM, KoboldCpp, etc.) or cloud API key","memoryRequirements":"8 GB RAM minimum; 8-16 GB VRAM for image/video generation","storageRequirements":"6 GB for default model"}+{"@context":"https://schema.org","@type":"SoftwareApplication","name":"Locally Uncensored","alternateName":["LU","Locally Uncensored Desktop App"],"applicationCategory":"DeveloperApplication","applicationSubCategory":"Artificial Intelligence","operatingSystem":"Windows 10, Windows 11, Linux","description":"Open-source desktop app for running AI locally. Chat with 20+ providers, generate images and video via ComfyUI, and code with a built-in AI agent — all on your own hardware. Auto-detects 12 local backends. No cloud, no telemetry.","url":"https://locallyuncensored.com/","downloadUrl":"https://github.com/PurpleDoubleD/locally-uncensored/releases/latest","softwareVersion":"2.4.9","license":"https://www.gnu.org/licenses/agpl-3.0.html","author":{"@type":"Person","name":"PurpleDoubleD","url":"https://github.com/PurpleDoubleD"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD","availability":"https://schema.org/InStock"},"featureList":["Plug & Play Setup with 12 Local Backend Auto-Detection (Ollama, LM Studio, vLLM, KoboldCpp, Jan, llama.cpp, LocalAI, GPT4All, TabbyAPI, Aphrodite, SGLang, TGI)","20+ Provider Presets (local + cloud)","Qwen 3.6 Day-0 Support (35B MoE, Vision, Agentic Coding, 256K context)","GPT-OSS Compatible (120B, 20B via Ollama)","GLM-4.7 Flash Integration","DeepSeek R1 and DeepSeek V3 Support","Llama 4 and Llama 3.3 Ready","Gemma 4 E4B and 27B (Native Vision)","Mistral Small 3 and Phi 4 Support","Qwen 3 Coder and Qwen 2.5 Coder","Abliterated Model Variants","Codex Coding Agent with Live Streaming and Apply-Patch","Claude Code CLI Integration","Agent Mode with 14 Tools, Parallel Execution, MCP, Sub-Agent Delegation","Remote Access from Phone via LAN or Cloudflare Tunnel (6-digit Passcode, QR Setup)","Mobile Web App (Chat, Codex, Tools, Plugins)","Image Generation via ComfyUI (FLUX 2 Klein, FLUX.1, Juggernaut XL, Z-Image Turbo, ERNIE-Image, SDXL, SD 3.5)","Video Generation (Wan 2.1, Wan 2.2, HunyuanVideo 1.5, LTX 2.3, FramePack F1, AnimateDiff, CogVideoX)","Image-to-Image with Denoise Control","Image-to-Video (FramePack F1, CogVideoX, SVD)","Granular Permission System (7 Tool Categories)","File Upload with Vision Support","Thinking Mode with Universal Tag Stripping","A/B Model Compare","Local Benchmark","Memory System and Document RAG","Voice (STT / TTS)","Auto-Update over Signed NSIS Channel","75+ One-Click Model Downloads","Hardware-Aware Model Recommendations","100% Offline and Private (No Telemetry)","AGPL-3.0 Open Source"],"screenshot":"https://raw.githubusercontent.com/PurpleDoubleD/locally-uncensored/master/docs/social-preview.png","softwareRequirements":"Any OpenAI-compatible local backend (Ollama, LM Studio, vLLM, KoboldCpp, etc.) or cloud API key","memoryRequirements":"8 GB RAM minimum; 8-16 GB VRAM for image/video generation","storageRequirements":"6 GB for default model"}</script><script type="application/ld+json">{"@context":"https://schema.org","@type":"Organization","name":"PurpleDoubleD","url":"https://github.com/PurpleDoubleD","logo":"https://locallyuncensored.com/logos/LU-monogram-bw-transparent.png","sameAs":["https://github.com/PurpleDoubleD","https://github.com/PurpleDoubleD/locally-uncensored","https://reddit.com/user/GroundbreakingMall54","https://locallyuncensored.com"]}@@ -827,7 +827,7 @@ footer a:hover{color:var(--fg)}<!-- Top meta strip --><div class="mast-strip">- <span class="numero">v 2.4.8</span>+ <span class="numero">v 2.4.9</span><span class="sep">·</span><span>AGPL-3.0</span><span class="sep">·</span>@@ -868,10 +868,10 @@ footer a:hover{color:var(--fg)}<div class="container"><div class="dl-card"><div class="dl-info">- <h3>Locally Uncensored <em>— 2.4.8</em></h3>+ <h3>Locally Uncensored <em>— 2.4.9</em></h3><p>WINDOWS · ~7 MB installer · AGPL-3.0</p></div>- <a class="dl-btn" href="https://github.com/PurpleDoubleD/locally-uncensored/releases/download/v2.4.8/Locally.Uncensored_2.4.8_x64-setup.exe" download>+ <a class="dl-btn" href="https://github.com/PurpleDoubleD/locally-uncensored/releases/download/v2.4.9/Locally.Uncensored_2.4.9_x64-setup.exe" download><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>Download .exe</a>@@ -1169,10 +1169,10 @@ footer a:hover{color:var(--fg)}<div class="narrow"><div class="dl-card"><div class="dl-info">- <h3>Locally Uncensored <em>— 2.4.8</em></h3>+ <h3>Locally Uncensored <em>— 2.4.9</em></h3><p>WINDOWS · ~7 MB installer · AGPL-3.0</p></div>- <a class="dl-btn" href="https://github.com/PurpleDoubleD/locally-uncensored/releases/download/v2.4.8/Locally.Uncensored_2.4.8_x64-setup.exe" download>+ <a class="dl-btn" href="https://github.com/PurpleDoubleD/locally-uncensored/releases/download/v2.4.9/Locally.Uncensored_2.4.9_x64-setup.exe" download><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>Download .exe</a>diff --git a/package.json b/package.jsonindex d210be1b..0a3b6cb2 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "locally-uncensored",- "version": "2.4.8",+ "version": "2.4.9","private": false,"description": "Generate anything — text, images, video. Locally. Uncensored.","license": "AGPL-3.0",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 684fcfd3..0db60443 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2508,7 +2508,7 @@ dependencies = [[[package]]name = "locally-uncensored"-version = "2.4.8"+version = "2.4.9"dependencies = ["axum","base64 0.22.1",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 98b84fc0..b491f64c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "locally-uncensored"-version = "2.4.8"+version = "2.4.9"description = "Private, local AI chat & image/video generation"authors = ["purpledoubled"]edition = "2021"diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex f59bf080..c4f42e94 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -251,11 +251,66 @@ fn collect_candidate_pythons() -> Vec<String> {out}+/// Probe order for the ComfyUI Desktop App's Working Directory when the+/// user-supplied path is the binary install dir (contains `ComfyUI.exe` but+/// no `main.py`). Comfy-Org/desktop lets the user pick this dir at install+/// time and defaults to `~\Documents\ComfyUI`. We additionally try the+/// `%APPDATA%\ComfyUI\config.json` `basePath` hint which the desktop app+/// writes after the picker, and the legacy `electron-userdata` location.+fn desktop_app_working_dir_candidates() -> Vec<PathBuf> {+ let mut out: Vec<PathBuf> = Vec::new();+ let home = dirs::home_dir().unwrap_or_default();+ out.push(home.join("Documents").join("ComfyUI"));+ out.push(home.join("Documents").join("ComfyUI").join("ComfyUI"));+ if cfg!(target_os = "windows") {+ if let Ok(appdata) = std::env::var("APPDATA") {+ // 1. config.json basePath hint, if present+ let cfg = PathBuf::from(&appdata).join("ComfyUI").join("config.json");+ if let Ok(raw) = std::fs::read_to_string(&cfg) {+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {+ if let Some(p) = v.get("basePath").and_then(|x| x.as_str()) {+ out.push(PathBuf::from(p));+ }+ }+ }+ // 2. %APPDATA%\ComfyUI itself (some installer variants)+ out.push(PathBuf::from(&appdata).join("ComfyUI"));+ }+ if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {+ out.push(PathBuf::from(&localappdata).join("ComfyUI"));+ // The desktop installer also bundles a ComfyUI tree under the+ // app's resources for first-launch seeding.+ out.push(PathBuf::from(&localappdata).join("Programs").join("ComfyUI").join("resources").join("ComfyUI"));+ }+ }+ out+}++/// Best-effort: turn whatever the user/auto-detector handed us into a+/// directory that contains `main.py`. Accepts either:+/// - A directory with `main.py` (classic / portable / from-source install)+/// - A directory with `ComfyUI.exe` (Comfy-Org desktop app binary dir) —+/// we then look up the Working Directory via the probe order above.+fn resolve_comfyui_path(input: &str) -> Option<String> {+ let p = Path::new(input);+ if p.join("main.py").exists() {+ return Some(input.to_string());+ }+ if p.join("ComfyUI.exe").exists() {+ for candidate in desktop_app_working_dir_candidates() {+ if candidate.join("main.py").exists() {+ return Some(candidate.to_string_lossy().to_string());+ }+ }+ }+ None+}+pub fn find_comfyui_path() -> Option<String> {// 1. Check environment variableif let Ok(env_path) = std::env::var("COMFYUI_PATH") {- if Path::new(&env_path).join("main.py").exists() {- return Some(env_path);+ if let Some(p) = resolve_comfyui_path(&env_path) {+ return Some(p);}}@@ -266,8 +321,8 @@ pub fn find_comfyui_path() -> Option<String> {if let Ok(content) = fs::read_to_string(&config_file) {if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {if let Some(path) = config.get("comfyui_path").and_then(|v| v.as_str()) {- if Path::new(path).join("main.py").exists() {- return Some(path.to_string());+ if let Some(resolved) = resolve_comfyui_path(path) {+ return Some(resolved);}}}@@ -297,9 +352,12 @@ pub fn find_comfyui_path() -> Option<String> {// Stability Matrix stores ComfyUI in AppDataif let Ok(appdata) = std::env::var("APPDATA") {fixed.push(PathBuf::from(&appdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));+ // Comfy-Org/desktop app working dir (GH #47, levoy1 2026-05-24)+ fixed.push(PathBuf::from(&appdata).join("ComfyUI"));}if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {fixed.push(PathBuf::from(&localappdata).join("StabilityMatrix").join("Packages").join("ComfyUI"));+ fixed.push(PathBuf::from(&localappdata).join("ComfyUI"));}// Common Program Files locationsfixed.push(PathBuf::from("C:\\Program Files\\ComfyUI"));@@ -459,13 +517,30 @@ fn detect_all_comfyui_installs_sync() -> Vec<ComfyUIInstall> {if cfg!(target_os = "windows") {if let Ok(appdata) = std::env::var("APPDATA") {fixed.push((PathBuf::from(&appdata).join("StabilityMatrix").join("Packages").join("ComfyUI"), "StabilityMatrix"));+ // Comfy-Org/desktop default Working Directory hint (GH #47).+ fixed.push((PathBuf::from(&appdata).join("ComfyUI"), "Desktop App data"));}if let Ok(localappdata) = std::env::var("LOCALAPPDATA") {fixed.push((PathBuf::from(&localappdata).join("StabilityMatrix").join("Packages").join("ComfyUI"), "StabilityMatrix"));+ fixed.push((PathBuf::from(&localappdata).join("ComfyUI"), "Desktop App data"));}fixed.push((PathBuf::from("C:\\Program Files\\ComfyUI"), "Program Files"));fixed.push((PathBuf::from("C:\\AI\\ComfyUI"), "C:\\AI"));fixed.push((PathBuf::from("D:\\AI\\ComfyUI"), "D:\\AI"));+ // ComfyUI Desktop App often pairs its `%LOCALAPPDATA%\Programs\ComfyUI`+ // binary with a `%APPDATA%\ComfyUI\config.json` whose `basePath` field+ // points at the Working Directory. Honour the hint so users with a+ // non-default Working Dir (e.g. on D:\ for space) are still found.+ if let Ok(appdata) = std::env::var("APPDATA") {+ let cfg = PathBuf::from(&appdata).join("ComfyUI").join("config.json");+ if let Ok(raw) = std::fs::read_to_string(&cfg) {+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {+ if let Some(base) = v.get("basePath").and_then(|x| x.as_str()) {+ fixed.push((PathBuf::from(base), "Desktop App basePath"));+ }+ }+ }+ }}for (p, source) in fixed {push_if_new(p, source, &mut out, &mut seen);@@ -550,7 +625,7 @@ fn is_comfyui_running_on_port(port: u16) -> bool {}#[tauri::command]-pub fn start_ollama(_state: State<'_, AppState>) -> Result<serde_json::Value, String> {+pub fn start_ollama(state: State<'_, AppState>) -> Result<serde_json::Value, String> {// Check if already running{let mut cmd = Command::new("tasklist");@@ -577,7 +652,12 @@ pub fn start_ollama(_state: State<'_, AppState>) -> Result<serde_json::Value, Stlet result = cmd.spawn();match result {- Ok(_) => {+ Ok(child) => {+ // Store the Child so AppState::Drop kills our spawned ollama on+ // shutdown (kj103x — Discord 2026-05-23 #help-chat 1507756765612216411).+ // Note: tasklist check above means we only get here if WE start it,+ // so we never kill a user-managed ollama serve.+ *state.ollama_process.lock().unwrap() = Some(child);println!("[Ollama] Started");Ok(serde_json::json!({"status": "started"}))}@@ -869,10 +949,28 @@ pub fn find_comfyui() -> Result<serde_json::Value, String> {#[tauri::command]pub fn set_comfyui_path(path: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {- let main_py = Path::new(&path).join("main.py");- if !main_py.exists() {- return Err(format!("main.py not found in {}", path));- }+ // Resolve the path the user gave us to a directory that actually contains+ // `main.py`. Direct hit short-circuits; otherwise we look at the ComfyUI+ // Desktop App layout (Comfy-Org/desktop, GH #47, levoy1 2026-05-24): the+ // user typically points at `%LOCALAPPDATA%\Programs\ComfyUI` (the binary+ // dir with `ComfyUI.exe` next to no `main.py`) because that's what their+ // shortcut targets, but the actual Working Directory with `main.py` ++ // `models/` + `custom_nodes/` lives under `~\Documents\ComfyUI` or+ // `%APPDATA%\ComfyUI` depending on the install picker. We transparently+ // re-route in that case so the error doesn't look unfixable.+ let resolved = resolve_comfyui_path(&path)+ .ok_or_else(|| {+ if Path::new(&path).join("ComfyUI.exe").exists() {+ format!(+ "Looks like the ComfyUI Desktop App binary folder ({}). LU needs the ComfyUI Working Directory (with main.py, models/, custom_nodes/) — by default `~\\Documents\\ComfyUI` or wherever you picked during install. Open the Desktop App once, check Settings → ComfyUI Working Directory, and paste that path here.",+ path+ )+ } else {+ format!("main.py not found in {}", path)+ }+ })?;++ let path = resolved;// Store in memory{@@ -1052,7 +1150,7 @@ pub fn get_ollama_host(state: State<'_, AppState>) -> Result<serde_json::Value,}/// Auto-start Ollama on app launch (called from setup)-pub fn auto_start_ollama(_state: &AppState) {+pub fn auto_start_ollama(state: &AppState) {// Check if already running{let mut cmd = Command::new("tasklist");@@ -1077,7 +1175,11 @@ pub fn auto_start_ollama(_state: &AppState) {#[cfg(target_os = "windows")]cmd.creation_flags(CREATE_NO_WINDOW);match cmd.spawn() {- Ok(_) => println!("[Ollama] Started"),+ Ok(child) => {+ // Same orphan-prevention rationale as `start_ollama` above.+ *state.ollama_process.lock().unwrap() = Some(child);+ println!("[Ollama] Started");+ }Err(e) => println!("[Ollama] Failed to start: {}", e),}}diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rsindex 2bfebb5d..24765f0f 100644--- a/src-tauri/src/commands/system.rs+++ b/src-tauri/src/commands/system.rs@@ -106,10 +106,23 @@ pub async fn pick_folder(default_path: Option<String>) -> Result<Option<String>,Ok(result.map(|f| f.path().to_string_lossy().to_string()))}-/// Exit the app (used by auto-updater to let NSIS installer run)+/// Exit the app — used by the auto-updater to let the NSIS installer swap+/// the binary, and by any future "full quit" UI affordance.+///+/// Live-tested on 2026-05-25: Tauri v2's `app.exit(0)` returns from the run+/// loop without dropping the managed `AppState` on Windows, so subprocess+/// children (Ollama, ComfyUI, Claude Code) survived every "graceful" quit+/// path. We work around it by explicitly running the shutdown chain BEFORE+/// asking Tauri to exit. This is what makes kj103x's Ollama-orphan fix+/// (v2.4.9, Discord 2026-05-23) actually deliver on the tray-Quit + auto-+/// updater paths in the released binary.#[tauri::command]-pub fn exit_app() {- std::process::exit(0);+pub fn exit_app(app: tauri::AppHandle) {+ use tauri::Manager;+ if let Some(state) = app.try_state::<crate::state::AppState>() {+ state.shutdown_subprocesses();+ }+ app.exit(0);}/// Get the persistent settings dir (%APPDATA%/Locally Uncensored/) — outside NSIS install dir@@ -143,6 +156,52 @@ pub fn restore_stores() -> Result<Option<String>, String> {}}+/// Backup the IndexedDB RAG chunks (embedding vectors) to %APPDATA%.+///+/// The chat-persistence triad (`store_backup.json`) only covers localStorage+/// stores. RAG embedding chunks live in IndexedDB under+/// `locally-uncensored-rag → chunks` because the 768-float vectors blow past+/// localStorage's ~10 MB quota for any non-trivial document. After an NSIS+/// upgrade or WebView2 data reset, localStorage restores the document+/// metadata but the IndexedDB chunks were silently lost — every "RAG enabled"+/// chat would show the document name + remain non-searchable.+///+/// kj103x report (Discord 2026-05-23, #help-chat thread 1507756765612216411,+/// running v2.4.8): "is there a way to keep chats with the plugins and the+/// attached documents via RAG when i close the app and reopen it?" References+/// Discussion #26 as "'fixed' but not really fixed" — the v2.3.4 fix was the+/// chat-message half; this commit is the RAG embeddings half.+///+/// The payload is the JSON-serialized snapshot of every objectStore entry+/// (the frontend uses `getAll()` on the chunks store and `JSON.stringify`s+/// the map `documentId → TextChunk[]`). Same atomic-temp-rename pattern as+/// `backup_stores` so a crash mid-write doesn't truncate a previous backup.+#[tauri::command]+pub fn backup_rag_chunks(data: String) -> Result<(), String> {+ let dir = persistent_dir()?;+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ let target = dir.join("rag_chunks_backup.json");+ let tmp = dir.join("rag_chunks_backup.tmp");+ std::fs::write(&tmp, &data).map_err(|e| e.to_string())?;+ std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;+ Ok(())+}++/// Restore RAG chunks (counterpart to `backup_rag_chunks`). Returns the JSON+/// payload (same shape: `Record<documentId, TextChunk[]>`) or `None` when no+/// backup exists yet. The frontend writes each entry back into IndexedDB on+/// cold start so RAG retrieval works after WebView2 data is wiped.+#[tauri::command]+pub fn restore_rag_chunks() -> Result<Option<String>, String> {+ let path = persistent_dir()?.join("rag_chunks_backup.json");+ if path.exists() {+ let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ Ok(Some(data))+ } else {+ Ok(None)+ }+}+/// Check if onboarding was completed (marker file in %APPDATA%, survives NSIS updates)#[tauri::command]pub fn is_onboarding_done() -> bool {diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 290b5a62..dd9a86f3 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -109,6 +109,8 @@ fn main() {commands::system::get_current_time,commands::system::backup_stores,commands::system::restore_stores,+ commands::system::backup_rag_chunks,+ commands::system::restore_rag_chunks,commands::system::exit_app,// Downloadscommands::download::download_model,@@ -190,6 +192,12 @@ fn main() {}}"quit" => {+ // Tauri's AppState Drop doesn't fire reliably on+ // Windows after `app.exit(0)` — run the explicit+ // subprocess shutdown here so tray Quit doesn't+ // leak Ollama / ComfyUI (kj103x V/b, v2.4.9).+ let state = app.state::<AppState>();+ state.shutdown_subprocesses();app.exit(0);}_ => {}diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 4c1edbc4..ce9fddf5 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -120,6 +120,14 @@ pub(crate) fn load_ollama_base() -> String {pub struct AppState {pub comfy_process: Mutex<Option<Child>>,+ /// Child handle for an Ollama daemon LU spawned itself (kj103x bug, Discord+ /// 2026-05-23 #help-chat). The Drop impl below kills the tree on shutdown+ /// so `ollama.exe` doesn't linger eating ~200 MB after the tray quit.+ /// IMPORTANT: only populated when `start_ollama` / `auto_start_ollama`+ /// actually spawned — if a user-managed `ollama serve` was already+ /// running on the box (detected via tasklist before spawn), we leave it+ /// alone, so closing LU never kills someone else's Ollama.+ pub ollama_process: Mutex<Option<Child>>,pub comfy_path: Mutex<Option<String>>,pub comfy_port: Mutex<u16>,/// Configurable ComfyUI host. Default "localhost". Setting this to a@@ -199,6 +207,7 @@ impl AppState {Self {comfy_process: Mutex::new(None),+ ollama_process: Mutex::new(None),comfy_path: Mutex::new(None),comfy_port: Mutex::new(initial_port),comfy_host: Mutex::new(initial_host),@@ -230,39 +239,64 @@ impl AppState {// to the user. 0x08000000 = CREATE_NO_WINDOW.#[cfg(windows)]const CREATE_NO_WINDOW: u32 = 0x08000000;+#[cfg(windows)]+use std::os::windows::process::CommandExt;++impl AppState {+ /// Kill every subprocess we spawned (ComfyUI, Ollama, Claude Code, Whisper).+ ///+ /// Live testing on 2026-05-25 showed that Tauri v2's `app.exit(0)` returns+ /// from the run loop on Windows WITHOUT actually dropping the managed+ /// `AppState` — the process exits before Drop fires, so children spawned+ /// in `auto_start_*` survived every "graceful" quit path (tray → Quit,+ /// auto-updater's `exit_app`, etc.). The `Drop` impl below is still+ /// correct, but we can't rely on it firing. Call this method explicitly+ /// from every quit path instead so kj103x's Ollama-orphan stays fixed even+ /// when Tauri's destructor chain skips us.+ pub fn shutdown_subprocesses(&self) {+ if let Ok(mut proc) = self.ollama_process.lock() {+ if let Some(ref mut child) = *proc {+ let pid = child.id();+ #[cfg(windows)]+ {+ let _ = std::process::Command::new("taskkill")+ .args(["/pid", &pid.to_string(), "/T", "/F"])+ .creation_flags(CREATE_NO_WINDOW)+ .output();+ }+ #[cfg(not(windows))]+ {+ let _ = child.kill();+ let _ = pid;+ }+ println!("[Ollama] Stopped (explicit shutdown)");+ }+ }-impl Drop for AppState {- fn drop(&mut self) {- // Kill ComfyUI process treeif let Ok(mut proc) = self.comfy_process.lock() {if let Some(ref mut child) = *proc {+ let pid = child.id();+ #[cfg(windows)]{- let pid = child.id();- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- let _ = std::process::Command::new("taskkill")- .args(["/pid", &pid.to_string(), "/T", "/F"])- .creation_flags(CREATE_NO_WINDOW)- .output();- }- #[cfg(not(windows))]- {- let _ = child.kill();- let _ = pid; // silence unused on non-Windows- }+ let _ = std::process::Command::new("taskkill")+ .args(["/pid", &pid.to_string(), "/T", "/F"])+ .creation_flags(CREATE_NO_WINDOW)+ .output();}- println!("[ComfyUI] Stopped");+ #[cfg(not(windows))]+ {+ let _ = child.kill();+ let _ = pid;+ }+ println!("[ComfyUI] Stopped (explicit shutdown)");}}- // Kill Claude Code processif let Ok(mut proc) = self.claude_code_process.lock() {if let Some(ref mut child) = *proc {let pid = child.id();#[cfg(windows)]{- use std::os::windows::process::CommandExt;let _ = std::process::Command::new("taskkill").args(["/pid", &pid.to_string(), "/T", "/F"]).creation_flags(CREATE_NO_WINDOW)@@ -273,13 +307,24 @@ impl Drop for AppState {let _ = child.kill();let _ = pid;}- println!("[ClaudeCode] Stopped");+ println!("[ClaudeCode] Stopped (explicit shutdown)");}}- // Stop Whisper serverif let Ok(mut whisper) = self.whisper.lock() {whisper.stop();}}}++impl Drop for AppState {+ fn drop(&mut self) {+ // Belt-and-suspenders. Tauri v2 doesn't reliably drop the managed+ // state on `app.exit(0)` on Windows, so every quit path explicitly+ // calls `shutdown_subprocesses` itself (see `commands::system::exit_app`+ // and the tray "quit" handler in `main.rs`). This Drop covers the+ // remaining "Tauri-managed shutdown DID happen to run our Drop" case+ // — idempotent re-kill on already-dead PIDs is a harmless taskkill.+ self.shutdown_subprocesses();+ }+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex a1a2c90f..5969b048 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json","productName": "Locally Uncensored",- "version": "2.4.8",+ "version": "2.4.9","identifier": "com.purpledoubled.locally-uncensored","build": {"beforeBuildCommand": "npm run build",diff --git a/src/api/__tests__/model-compatibility.test.ts b/src/api/__tests__/model-compatibility.test.tsindex 67987f7d..db28f779 100644--- a/src/api/__tests__/model-compatibility.test.ts+++ b/src/api/__tests__/model-compatibility.test.ts@@ -74,6 +74,21 @@ describe('isAgentCompatible', () => {expect(isAgentCompatible('LEONW24/Qwen3.5-9B-Uncensored:Q4_K_M')).toBe(true)})+ it('Gemma 4 community-uncensored builds keep agent capability (Bug X, leonsk29 2026-05-24)', () => {+ // The Discord 2026-05-24 report: Agent + Thinking toggles grayed out+ // for every Gemma 4 community variant the Discover tab pulls (TrevorJS,+ // nohurry, Stabhappy, LiconStudio, huihui). Their tag shapes use the+ // dashed-family form `gemma-4-…-it-…-GGUF:Q4_K_M`, which the previous+ // normalizer left as `gemma-4-…` (no match against `gemma4`).+ expect(isAgentCompatible('hf.co/TrevorJS/gemma-4-31B-it-uncensored-GGUF:Q4_K_M')).toBe(true)+ expect(isAgentCompatible('hf.co/nohurry/gemma-4-26B-A4B-it-heretic-GUFF:q4_k_m')).toBe(true)+ expect(isAgentCompatible('hf.co/Stabhappy/gemma-4-31B-it-heretic-Gguf:Q4_K_M')).toBe(true)+ expect(isAgentCompatible('hf.co/LiconStudio/Gemma-4-31B-it-abliterated-GGUF:Q4_K_M')).toBe(true)+ expect(isAgentCompatible('huihui_ai/Qwen3.6-abliterated:35b')).toBe(true)+ // Two-slash hf.co prefix specifically — previously stopped at first slash+ expect(isAgentCompatible('hf.co/mradermacher/Huihui-Qwen3.5-35B-A3B-abliterated-i1-GGUF:Q4_K_M')).toBe(true)+ })+it('uncensored variants of unknown bases are still NOT compatible', () => {// dolphin3 is not in AGENT_COMPATIBLE — strip suffix and check, still no.expect(isAgentCompatible('dolphin3-uncensored:8b')).toBe(false)diff --git a/src/components/chat/RAGPanel.tsx b/src/components/chat/RAGPanel.tsxindex 9a6d1b82..d4b1468a 100644--- a/src/components/chat/RAGPanel.tsx+++ b/src/components/chat/RAGPanel.tsx@@ -1,4 +1,4 @@-import { useState, useCallback, useRef } from 'react'+import { useState, useCallback, useEffect, useRef } from 'react'import { motion, AnimatePresence } from 'framer-motion'import {FileText,@@ -20,6 +20,7 @@ import {import { useShallow } from 'zustand/react/shallow'import { useRAG } from '../../hooks/useRAG'import { useRAGStore } from '../../stores/ragStore'+import { formatBytes } from '../../lib/formatters'interface Props {conversationId: string | null@@ -98,11 +99,44 @@ function RAGPanelInner({ conversationId, onClose }: { conversationId: string; onconst removeDocument = rag.removeDocumentconst toggleRAG = rag.toggleRAGconst clearAll = rag.clearAll-- const { embeddingModelReactive, lastRetrievedChunksReactive } = useRAGStore(+ const installEmbeddingAndDrainQueue = rag.installEmbeddingAndDrainQueue+ const cancelEmbeddingInstall = rag.cancelEmbeddingInstall+ const ensureEmbeddingModel = rag.ensureEmbeddingModel++ // Proactively probe for nomic-embed-text the first time the user opens the+ // Document Chat panel. If it's missing we flip embeddingInstallPrompt right+ // here so the install card shows before any upload attempt — user clicks+ // the Docs button, sees the offer, can install or cancel. This is the path+ // the user explicitly asked for over a global top-of-app banner. The probe+ // runs only when the prompt isn't already up and we aren't mid-pull, so+ // re-opening the panel doesn't fight an in-flight install.+ useEffect(() => {+ let cancelled = false+ if (embeddingInstallPrompt || pullingEmbeddingModel) return+ ;(async () => {+ try {+ const has = await ensureEmbeddingModel()+ if (cancelled) return+ if (!has) {+ useRAGStore.getState().setEmbeddingInstallPrompt(true)+ }+ } catch {+ /* ollama probe failed — silent; user can still drop a file later */+ }+ })()+ return () => { cancelled = true }+ // intentionally NOT depending on prompt/pulling flags — we want a single+ // mount-time probe per panel open, not a re-fire on every flag change.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ensureEmbeddingModel])++ const { embeddingModelReactive, lastRetrievedChunksReactive, embeddingPullProgress, embeddingInstallPrompt, embeddingQueuedCount } = useRAGStore(useShallow((s) => ({embeddingModelReactive: s.embeddingModel,lastRetrievedChunksReactive: s.lastRetrievedChunks,+ embeddingPullProgress: s.embeddingPullProgress,+ embeddingInstallPrompt: s.embeddingInstallPrompt,+ embeddingQueuedCount: s.embeddingQueuedFiles.length,})))@@ -253,7 +287,61 @@ function RAGPanelInner({ conversationId, onClose }: { conversationId: string; on)}</AnimatePresence>- {/* Embedding model pull progress */}+ {/* In-app install prompt (Bug F45-followup) — replaces window.confirm()+ so the user stays in app chrome. Triggered by either:+ (a) Opening the Document Chat panel while nomic-embed-text is+ missing — RAGPanelInner's mount-time `ensureEmbeddingModel`+ check below flips the prompt proactively, so the user sees+ the install offer the moment they click the Docs button.+ (b) Dropping a file when the model is missing — uploadDocument+ queues the file + flips the prompt; queued files replay+ after the pull succeeds.+ Neutral white/gray chrome (no blue tint) — matches the v2.4.8 Q-+ polish pattern. */}+ <AnimatePresence>+ {embeddingInstallPrompt && !pullingEmbeddingModel && (+ <motion.div+ className="px-3 py-2"+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ >+ <div className="p-2.5 rounded-lg bg-gray-50 dark:bg-white/[0.03] border border-gray-200 dark:border-white/10 space-y-1.5">+ <div className="flex items-center gap-1.5">+ <Download size={12} className="text-gray-500 dark:text-gray-300 shrink-0" />+ <span className="text-[0.65rem] font-medium text-gray-700 dark:text-gray-200">Embedding model needed</span>+ </div>+ <p className="text-[0.6rem] text-gray-500 dark:text-gray-400 leading-snug">+ Document Chat needs <code className="font-mono px-1 rounded bg-gray-200 dark:bg-white/5">{embeddingModelReactive ?? 'nomic-embed-text'}</code> (274 MB). One-time download.+ {embeddingQueuedCount > 0 && (+ <span className="block mt-0.5 text-gray-400 dark:text-gray-500">+ {embeddingQueuedCount} file{embeddingQueuedCount === 1 ? '' : 's'} queued — will index after install.+ </span>+ )}+ </p>+ <div className="flex gap-1.5 pt-0.5">+ <button+ onClick={() => installEmbeddingAndDrainQueue()}+ className="flex-1 px-2 py-1 rounded text-[0.6rem] font-medium bg-gray-200 hover:bg-gray-300 dark:bg-white/10 dark:hover:bg-white/15 text-gray-800 dark:text-gray-100 transition-colors flex items-center justify-center gap-1"+ >+ <Download size={11} /> Download+ </button>+ <button+ onClick={() => cancelEmbeddingInstall()}+ className="px-2 py-1 rounded text-[0.6rem] font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ >+ Cancel+ </button>+ </div>+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {/* Embedding model pull progress — real bytes-level progress bar replacing+ the pre-v2.4.9 bouncing-icon banner. Reads embeddingPullProgress+ which useRAG.pullEmbeddingModel populates per Ollama stream chunk.+ Neutral chrome to match the install prompt above. */}<AnimatePresence>{pullingEmbeddingModel && (<motion.div@@ -262,11 +350,42 @@ function RAGPanelInner({ conversationId, onClose }: { conversationId: string; onanimate={{ opacity: 1, height: 'auto' }}exit={{ opacity: 0, height: 0 }}>- <div className="flex items-center gap-1.5 p-2 rounded-lg bg-blue-500/10 border border-blue-500/20">- <Download size={12} className="text-blue-400 animate-bounce" />- <span className="text-[0.6rem] text-blue-400 leading-tight">- Downloading embedding model (nomic-embed-text)...- </span>+ <div className="p-2.5 rounded-lg bg-gray-50 dark:bg-white/[0.03] border border-gray-200 dark:border-white/10 space-y-1.5">+ <div className="flex items-center gap-1.5">+ <Loader2 size={12} className="text-gray-500 dark:text-gray-300 animate-spin shrink-0" />+ <span className="text-[0.6rem] text-gray-600 dark:text-gray-300 leading-tight truncate">+ {embeddingPullProgress?.status?.startsWith('downloading')+ ? 'Downloading nomic-embed-text…'+ : embeddingPullProgress?.status === 'success'+ ? 'Almost done…'+ : (embeddingPullProgress?.status || 'Preparing pull…')}+ </span>+ </div>+ {embeddingPullProgress && embeddingPullProgress.total > 0 ? (+ <>+ <div className="w-full h-1 bg-gray-200 dark:bg-white/10 rounded-full overflow-hidden">+ <motion.div+ className="h-full bg-gray-500 dark:bg-gray-300 rounded-full"+ initial={{ width: 0 }}+ animate={{+ width: `${Math.min(100, (embeddingPullProgress.completed / embeddingPullProgress.total) * 100)}%`,+ }}+ transition={{ duration: 0.2 }}+ />+ </div>+ <p className="text-[0.55rem] text-gray-500 dark:text-gray-400 font-mono">+ {formatBytes(embeddingPullProgress.completed)} / {formatBytes(embeddingPullProgress.total)} · {Math.round((embeddingPullProgress.completed / embeddingPullProgress.total) * 100)}%+ </p>+ </>+ ) : (+ <div className="w-full h-1 bg-gray-200 dark:bg-white/10 rounded-full overflow-hidden">+ <motion.div+ className="h-full bg-gray-500 dark:bg-gray-300 rounded-full w-1/3"+ animate={{ x: ['-100%', '300%'] }}+ transition={{ duration: 1.5, repeat: Infinity, ease: 'linear' }}+ />+ </div>+ )}</div></motion.div>)}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 5f8206fe..5f8693f2 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -52,7 +52,35 @@ export function AppShell() {if (!isTauri()) returnconst hasStores = STORE_KEYS.some(k => localStorage.getItem(k))const restoreComplete = localStorage.getItem('lu-restore-complete')- if (hasStores && restoreComplete) return // localStorage intact, no restore needed+ if (hasStores && restoreComplete) {+ // localStorage intact, but IndexedDB might have been wiped (different+ // storage layer, different lifetime). Quietly restore RAG chunks if a+ // backup exists and the live store has none for the documents the+ // localStorage `rag-store` knows about. Best-effort; ignore errors.+ ;(async () => {+ try {+ const data = await backendCall<string | null>('restore_rag_chunks')+ if (!data) return+ const parsed = JSON.parse(data)+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ const { exportAllChunks, importAllChunks } = await import('../../lib/ragDB')+ const live = await exportAllChunks()+ // Only import entries the live store is missing — never clobber+ // newer in-app activity with a stale backup.+ const toImport: Record<string, any> = {}+ for (const [docId, chunks] of Object.entries(parsed)) {+ if (!live[docId] && Array.isArray(chunks) && chunks.length > 0) {+ toImport[docId] = chunks+ }+ }+ if (Object.keys(toImport).length > 0) {+ await importAllChunks(toImport)+ }+ }+ } catch { /* best-effort */ }+ })()+ return+ }setRestoring(true)@@ -73,6 +101,20 @@ export function AppShell() {}}if (restored > 0) {+ // Pull RAG chunks from %APPDATA% before the reload so the new+ // localStorage references find their embeddings in IndexedDB+ // (Bug V, kj103x 2026-05-23). Best-effort: missing backup =+ // chunks need to be re-indexed by re-uploading docs.+ try {+ const ragData = await backendCall<string | null>('restore_rag_chunks')+ if (ragData) {+ const parsedRag = JSON.parse(ragData)+ if (parsedRag && typeof parsedRag === 'object' && !Array.isArray(parsedRag)) {+ const { importAllChunks } = await import('../../lib/ragDB')+ await importAllChunks(parsedRag as Record<string, any>)+ }+ }+ } catch { /* best-effort */ }localStorage.setItem('lu-restore-complete', '1')window.location.reload()return@@ -119,6 +161,28 @@ export function AppShell() {backendCall('backup_stores', { data: JSON.stringify(snapshot) }).catch(() => {})}+ // Separate, debounced backup for RAG IndexedDB chunks (Bug V, kj103x+ // 2026-05-23). These are heavy (768-float embedding vectors per chunk,+ // sometimes thousands per doc) so we don't bundle them into the chat+ // snapshot — the chat-store backup must stay fast for the 1 s debounce+ // case. RAG backup runs at most once every 30 s and after IndexedDB+ // grows, which is the right cadence: chunks change on document upload+ // / delete, both rare events compared to chat messages.+ let ragLastRun = 0+ let ragInflight = false+ const doRagBackup = async () => {+ if (ragInflight) return+ if (Date.now() - ragLastRun < 30_000) return+ ragInflight = true+ try {+ const { exportAllChunks } = await import('../../lib/ragDB')+ const snapshot = await exportAllChunks()+ await backendCall('backup_rag_chunks', { data: JSON.stringify(snapshot) }).catch(() => {})+ ragLastRun = Date.now()+ } catch { /* best-effort */ }+ ragInflight = false+ }+// Migration: write onboarding marker if missing AND user has already// onboarded (keeps NSIS-update recovery working). Do NOT rewrite the// marker for users who just hit Settings → "Re-run onboarding" — for@@ -130,7 +194,11 @@ export function AppShell() {})doBackup() // first immediate backup+ // Same first-fire convention for RAG chunks so a fresh post-restore+ // boot writes a complete snapshot back to disk immediately.+ void doRagBackup()const interval = setInterval(doBackup, 5_000)+ const ragInterval = setInterval(() => { void doRagBackup() }, 30_000)let debounceTimer: ReturnType<typeof setTimeout> | null = nullconst scheduleBackup = () => {@@ -139,11 +207,18 @@ export function AppShell() {}const unsubChat = useChatStore.subscribe(scheduleBackup)- const onBeforeUnload = () => doBackup()+ const onBeforeUnload = () => {+ doBackup()+ // Best-effort fire-and-forget — the page is going away, we can't+ // await. The 30 s interval covers the common case; this is the+ // "last write" insurance for changes since the previous interval.+ void doRagBackup()+ }window.addEventListener('beforeunload', onBeforeUnload)cleanup = () => {clearInterval(interval)+ clearInterval(ragInterval)if (debounceTimer) clearTimeout(debounceTimer)unsubChat()window.removeEventListener('beforeunload', onBeforeUnload)diff --git a/src/components/models/BenchmarkView.tsx b/src/components/models/BenchmarkView.tsxindex 003fa70b..478d41aa 100644--- a/src/components/models/BenchmarkView.tsx+++ b/src/components/models/BenchmarkView.tsx@@ -1,7 +1,7 @@import { ArrowLeft, Trophy, Zap, Play, Square } from 'lucide-react'import { useUIStore } from '../../stores/uiStore'import { useModelStore } from '../../stores/modelStore'-import { useBenchmarkStore, getAverageSpeed, getLeaderboard } from '../../stores/benchmarkStore'+import { useBenchmarkStore, getLatestSpeed, getLeaderboard } from '../../stores/benchmarkStore'import { useBenchmark } from '../../hooks/useBenchmark'export function BenchmarkView() {@@ -78,7 +78,7 @@ export function BenchmarkView() {{textModels.length} Text Models</h2>{textModels.map((model) => {- const avgSpeed = getAverageSpeed(results, model.name)+ const latestSpeed = getLatestSpeed(results, model.name)const isThisRunning = isRunning && currentModel === model.namereturn (@@ -88,10 +88,10 @@ export function BenchmarkView() {><div className="flex items-center gap-2 min-w-0"><span className="text-[0.7rem] text-gray-800 dark:text-gray-200 truncate">{model.name}</span>- {avgSpeed !== null && (- <span className="text-[0.55rem] text-gray-500 font-mono flex items-center gap-0.5 shrink-0">+ {latestSpeed !== null && (+ <span className="text-[0.55rem] text-gray-500 font-mono flex items-center gap-0.5 shrink-0" title="Most recent benchmark run"><Zap size={9} className="text-amber-400" />- {avgSpeed} t/s+ {latestSpeed} t/s</span>)}</div>diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex d6df4f62..0b91042c 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -429,12 +429,26 @@ export function DiscoverModels({ category }: Props) {const uncensoredModels = isText ? getUncensoredTextModels() : []const mainstreamModels = isText ? getMainstreamTextModels() : []- const filteredUncensored = search- ? uncensoredModels.filter((m) => m.name.toLowerCase().includes(search.toLowerCase()) || m.description.toLowerCase().includes(search.toLowerCase()))- : uncensoredModels- const filteredMainstream = search- ? mainstreamModels.filter((m) => m.name.toLowerCase().includes(search.toLowerCase()) || m.description.toLowerCase().includes(search.toLowerCase()))- : mainstreamModels+ // Apply the VRAM tier filter to text models too (Feature 46, leonsk29 GH #46).+ // We use the model's GGUF `sizeGB` as a proxy for VRAM need — Q4 quants run+ // entirely on the GPU when sizeGB ≤ VRAM, so the same lightweight/mid/highend+ // bucketing as image/video applies here. Models without a `sizeGB` (cloud+ // / canPull:false placeholders) bypass the filter and always show.+ const matchesVramTier = (sizeGB?: number) => {+ if (vramTier === 'all') return true+ if (sizeGB === undefined || sizeGB === null) return true+ if (vramTier === 'lightweight') return sizeGB <= 10+ if (vramTier === 'mid') return sizeGB > 10 && sizeGB <= 16+ return sizeGB > 16 // highend+ }++ const matchesSearch = (m: DiscoverModel) =>+ !search ||+ m.name.toLowerCase().includes(search.toLowerCase()) ||+ m.description.toLowerCase().includes(search.toLowerCase())++ const filteredUncensored = uncensoredModels.filter(m => matchesSearch(m) && matchesVramTier(m.sizeGB))+ const filteredMainstream = mainstreamModels.filter(m => matchesSearch(m) && matchesVramTier(m.sizeGB))const title = 'Discover LUncensored'const subtitle = isText@@ -584,14 +598,16 @@ export function DiscoverModels({ category }: Props) {</div>)}- {/* VRAM Tier Filter — for image/video bundles */}- {(isImage || isVideo) && sortedBundles.length > 0 && (+ {/* VRAM Tier Filter — image/video bundles AND text models (Feature 46,+ leonsk29 GH #46). Text models reuse the same tier thresholds, derived+ from each model's GGUF `sizeGB` (Q4 quant roughly equals VRAM need). */}+ {(isImage || isVideo || (isText && (uncensoredModels.length > 0 || mainstreamModels.length > 0))) && (<div className="flex gap-1.5">{([{ key: 'all', label: 'All', desc: '' },- { key: 'lightweight', label: 'Lightweight', desc: '6-10 GB' },- { key: 'mid', label: 'Mid-Range', desc: '12-16 GB' },- { key: 'highend', label: 'High-End', desc: '20+ GB' },+ { key: 'lightweight', label: 'Lightweight', desc: '≤10 GB' },+ { key: 'mid', label: 'Mid-Range', desc: '10-16 GB' },+ { key: 'highend', label: 'High-End', desc: '>16 GB' },] as const).map(tier => (<buttonkey={tier.key}diff --git a/src/components/models/ModelBenchmark.tsx b/src/components/models/ModelBenchmark.tsxindex ce19d410..6cac2ba8 100644--- a/src/components/models/ModelBenchmark.tsx+++ b/src/components/models/ModelBenchmark.tsx@@ -1,4 +1,4 @@-import { useBenchmarkStore, getAverageSpeed, getLeaderboard } from '../../stores/benchmarkStore'+import { useBenchmarkStore, getLatestSpeed, getLeaderboard } from '../../stores/benchmarkStore'import { useBenchmark } from '../../hooks/useBenchmark'import { Zap, Play, Square, Trophy } from 'lucide-react'@@ -13,16 +13,16 @@ export function BenchmarkButton({ modelName }: Props) {const currentStep = useBenchmarkStore((s) => s.currentStep)const totalSteps = useBenchmarkStore((s) => s.totalSteps)const results = useBenchmarkStore((s) => s.results)- const avgSpeed = getAverageSpeed(results, modelName)+ const latestSpeed = getLatestSpeed(results, modelName)const isThisRunning = isRunning && currentModel === modelNamereturn (<div className="flex items-center gap-1.5">- {avgSpeed !== null && (- <span className="text-[0.55rem] text-gray-400 font-mono flex items-center gap-0.5" title={`Average: ${avgSpeed} tokens/sec`}>+ {latestSpeed !== null && (+ <span className="text-[0.55rem] text-gray-400 font-mono flex items-center gap-0.5" title={`Latest run: ${latestSpeed} tokens/sec`}><Zap size={9} />- {avgSpeed} t/s+ {latestSpeed} t/s</span>)}{isThisRunning ? (diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsxindex 0c818ad6..a8cdebf3 100644--- a/src/components/onboarding/Onboarding.tsx+++ b/src/components/onboarding/Onboarding.tsx@@ -21,8 +21,12 @@ import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provide// always". Light mode stays available in Settings → General → Appearance// for users who explicitly want it; we just don't push them through the// choice on first launch anymore.-type Step = 'welcome' | 'backends' | 'comfyui' | 'models' | 'done'-const STEP_ORDER: Step[] = ['welcome', 'backends', 'comfyui', 'models', 'done']+// Added 'embeddings' step (GH #45, leonsk29 2026-05-23): suggests pulling+// `nomic-embed-text` (~274 MB) before completing onboarding so Document+// Chat / RAG works out of the box. The step shows a Skip button and+// auto-skips entirely when the user already has any embedding model on disk.+type Step = 'welcome' | 'backends' | 'comfyui' | 'models' | 'embeddings' | 'done'+const STEP_ORDER: Step[] = ['welcome', 'backends', 'comfyui', 'models', 'embeddings', 'done']const isTauri = typeof window !== 'undefined' && !!(window as any).__TAURI_INTERNALS__/* ── Local backend info for the "nothing found" state ──────── */@@ -288,7 +292,7 @@ export function Onboarding() {// Tell the rest of the app the model list changed — Model Manager,// Chat picker, etc. listen for this and re-fetch.window.dispatchEvent(new CustomEvent('lu-models-refresh'))- setStep('done')+ setStep('embeddings')}const finish = () => {@@ -367,12 +371,83 @@ export function Onboarding() {// (P4 LU-Aufgaben: "Nur wenn der User noch gar kein Modell installiert hat.// Sonst nirgendwo mehr 'Recommended'-Empfehlungen"). null = still loading,// 0 = fresh, >0 = experienced — only the first two should see the picker.+ // Experienced users still progress to the embedding step (separate skip).useEffect(() => {if (step === 'models' && existingModelCount !== null && existingModelCount > 0) {- setStep('done')+ setStep('embeddings')}}, [step, existingModelCount])+ // ── nomic-embed-text install state (GH #45, leonsk29 2026-05-23) ─────+ // The Document Chat / RAG feature needs an embedding model. We default+ // to `nomic-embed-text` — small (~274 MB), broadly supported. The step+ // auto-skips when the user already has any embedding model installed+ // (covers LM Studio users who came in via that backend with their own+ // embedding model, and Ollama users who already pulled one).+ const [embeddingsPulling, setEmbeddingsPulling] = useState(false)+ const [embeddingsPulled, setEmbeddingsPulled] = useState(false)+ const [embeddingsError, setEmbeddingsError] = useState<string | null>(null)+ const [embeddingsProgress, setEmbeddingsProgress] = useState<{ completed: number; total: number }>({ completed: 0, total: 0 })+ const [embeddingsAlreadyHave, setEmbeddingsAlreadyHave] = useState<boolean | null>(null)++ // Probe whether an embedding model is already present on the box. Ollama+ // lists pulled models; we look for anything with `embed`/`bge`/`nomic` in+ // the name (the same heuristic used elsewhere for chat-capability filtering).+ useEffect(() => {+ if (step !== 'embeddings') return+ let cancelled = false+ import('../../api/ollama').then(({ listModels }) =>+ listModels()+ .then(models => {+ if (cancelled) return+ const hasEmbedding = models.some(m => {+ const lower = (m.name || '').toLowerCase()+ return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')+ })+ setEmbeddingsAlreadyHave(hasEmbedding)+ })+ .catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })+ )+ return () => { cancelled = true }+ }, [step])++ const handlePullEmbeddings = async () => {+ if (!isTauri) {+ setEmbeddingsError('Embedding install requires the desktop app — running in a browser preview.')+ return+ }+ setEmbeddingsPulling(true)+ setEmbeddingsError(null)+ setEmbeddingsProgress({ completed: 0, total: 0 })+ try {+ // Make sure ollama is reachable before kicking off the pull.+ let ok = await checkOllama()+ if (!ok) {+ try { await backendCall('start_ollama') } catch { /* fall through */ }+ for (let i = 0; i < 20 && !ok; i++) {+ await new Promise(r => setTimeout(r, 250))+ ok = await checkOllama()+ }+ }+ if (!ok) {+ setEmbeddingsError('Cannot reach Ollama (localhost:11434). Start Ollama and retry.')+ setEmbeddingsPulling(false)+ return+ }+ const { promise } = pullModelTauri('nomic-embed-text', (p) => {+ setEmbeddingsProgress({ completed: p.completed || 0, total: p.total || 0 })+ })+ await promise+ setEmbeddingsPulled(true)+ // Same refresh event chat/picker components listen on.+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ } catch (e) {+ setEmbeddingsError(`Pull failed: ${e instanceof Error ? e.message : String(e)}`)+ } finally {+ setEmbeddingsPulling(false)+ }+ }+const showRecommendedBadge = existingModelCount === 0// Elapsed timer for ComfyUI installation@@ -1445,7 +1520,7 @@ export function Onboarding() {</button>) : !isDownloading ? (<button- onClick={() => setStep('done')}+ onClick={() => setStep('embeddings')}className={`flex-1 flex items-center justify-center gap-1.5 ${secondaryBtn}`}>Skip for now <ChevronRight size={14} />@@ -1455,7 +1530,91 @@ export function Onboarding() {</motion.div>)}- {/* Step 5: Done */}+ {/* Step 5: Embeddings (GH #45 — Document Chat / RAG) */}+ {step === 'embeddings' && (+ <motion.div+ key="embeddings"+ className="max-w-md w-full space-y-3"+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -20 }}+ >+ <div className="text-center mb-2">+ <h2 className="text-base font-semibold mb-1">Document Chat (optional)</h2>+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>+ Drop a PDF, Word doc, or text file into chat and the model can answer questions about it. Needs a small embedding model.+ </p>+ </div>++ {embeddingsAlreadyHave === true && !embeddingsPulled && (+ <div className={`p-3 rounded-lg border ${isDark ? 'bg-green-500/10 border-green-500/20' : 'bg-green-50 border-green-200'}`}>+ <div className="flex items-center gap-2 justify-center">+ <Check size={14} className="text-green-400" />+ <span className="text-[0.7rem] font-medium">Embedding model already installed — Document Chat is ready.</span>+ </div>+ </div>+ )}++ {embeddingsAlreadyHave !== true && (+ <div className={`p-3 rounded-lg border ${cardClass}`}>+ <div className="flex items-start justify-between gap-2">+ <div className="flex-1 min-w-0">+ <p className="text-[0.7rem] font-medium">nomic-embed-text</p>+ <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>+ Standard embedding model from Nomic AI. Used purely on-device to chunk and retrieve your documents — never sent anywhere.+ </p>+ <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ 274 MB · runs on any CPU+ </p>+ </div>+ </div>++ {embeddingsPulling && (+ <div className="mt-2.5 space-y-1">+ <ProgressBar progress={embeddingsProgress.total > 0 ? (embeddingsProgress.completed / embeddingsProgress.total) * 100 : 0} />+ <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>+ {embeddingsProgress.total > 0+ ? `${formatBytes(embeddingsProgress.completed)} / ${formatBytes(embeddingsProgress.total)}`+ : 'Starting…'}+ </p>+ </div>+ )}++ {embeddingsPulled && (+ <div className="mt-2.5 flex items-center gap-2 text-[0.65rem] text-green-400">+ <Check size={12} /> Installed. Document Chat is ready.+ </div>+ )}++ {embeddingsError && (+ <p className="text-[0.6rem] text-red-400 mt-2">{embeddingsError}</p>+ )}+ </div>+ )}++ <div className="flex items-center gap-2 pt-1">+ {embeddingsAlreadyHave !== true && !embeddingsPulled && !embeddingsPulling && (+ <button onClick={handlePullEmbeddings} className={primaryBtn} style={{ flex: 1 }}>+ <Download size={14} /> Install nomic-embed-text (274 MB)+ </button>+ )}+ <button+ onClick={() => setStep('done')}+ disabled={embeddingsPulling}+ className={`${secondaryBtn} ${embeddingsPulling ? 'opacity-40 cursor-not-allowed' : ''}`}+ style={{ flex: embeddingsAlreadyHave === true || embeddingsPulled ? 1 : undefined }}+ >+ {embeddingsAlreadyHave === true || embeddingsPulled ? (+ <>Continue <ArrowRight size={14} /></>+ ) : (+ <>Skip for now <ChevronRight size={14} /></>+ )}+ </button>+ </div>+ </motion.div>+ )}++ {/* Step 6: Done */}{step === 'done' && (<motion.divkey="done"diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.tsindex e86e6f9b..ff2af7f5 100644--- a/src/hooks/useRAG.ts+++ b/src/hooks/useRAG.ts@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef } from "react"import { useShallow } from "zustand/react/shallow"import { useRAGStore } from "../stores/ragStore"import { indexDocument, retrieveContext } from "../api/rag"-import { getModelContext, listModels, pullModel, checkConnection } from "../api/ollama"+import { getModelContext, listModels, pullModelTauri, checkConnection } from "../api/ollama"import { useModelStore } from "../stores/modelStore"import type { DocumentMeta, RAGContext } from "../types/rag"@@ -71,14 +71,92 @@ export function useRAG(conversationId: string | null) {checkContextWindow()}, [isEnabled, conversationId, documents.length])+ /**+ * Verify the embedding model is reachable. Used both as upload pre-flight+ * (`uploadDocument` queues the file when this returns false) and standalone+ * from the post-update banner / Install card so the UI can ask once and+ * not re-probe per file.+ *+ * Returns true when nomic-embed-text (or whatever `embeddingModel` is set+ * to) is in Ollama's model list. False when missing — caller is expected+ * to surface the in-app Install prompt rather than blocking.+ */+ const ensureEmbeddingModel = useCallback(async (): Promise<boolean> => {+ const { embeddingModel } = useRAGStore.getState()+ const ollamaUp = await checkConnection()+ if (!ollamaUp) return false+ try {+ const models = await listModels()+ return models.some(+ (m) => m.name === embeddingModel || m.name === embeddingModel + ":latest"+ )+ } catch {+ return false+ }+ }, [])++ /**+ * Run `ollama pull <embeddingModel>` with byte-level progress streamed into+ * `embeddingPullProgress`. Replaces the pre-v2.4.9 fire-and-forget pull whose+ * console.log progress lines were invisible to the user.+ *+ * Uses `pullModelTauri` (event-based) — NOT `pullModel` (Response.body). The+ * Tauri `localFetchStream` proxy collects all bytes before returning the+ * Response on Windows release builds, so reading the body stream sees a+ * single chunk at the very end of the pull (this is the same Bug M issue+ * v2.4.7 fixed for benchmark TTFT). Onboarding's F45 step already uses+ * `pullModelTauri` for the same reason — this routine matches it so users+ * get a smoothly-updating progress bar whether they install via Onboarding,+ * RAGPanel install card, or any future entry point.+ */+ const pullEmbeddingModel = useCallback(async (): Promise<boolean> => {+ const {+ embeddingModel,+ setPullingEmbeddingModel,+ setEmbeddingPullProgress,+ } = useRAGStore.getState()++ setPullingEmbeddingModel(true)+ setEmbeddingPullProgress({ completed: 0, total: 0, status: "starting" })++ try {+ const { promise } = pullModelTauri(embeddingModel, (p) => {+ const status = (p.status || "").toLowerCase()+ const isComplete = status.includes("success") || status === "complete"+ setEmbeddingPullProgress({+ completed: p.completed || 0,+ total: p.total || 0,+ status: isComplete ? "success" : p.status || "downloading",+ })+ })+ await promise+ return true+ } catch (err) {+ console.error("[EmbeddingPull] failed:", err)+ return false+ } finally {+ setPullingEmbeddingModel(false)+ // Leave the progress visible briefly so the success state isn't a+ // flicker — RAGPanel hides it on next render anyway.+ setTimeout(() => setEmbeddingPullProgress(null), 1500)+ }+ }, [])+const uploadDocument = useCallback(async (file: File): Promise<DocumentMeta | null> => {if (!conversationId) return null- const { embeddingModel, setIndexing, setIndexingProgress, addDocument, addChunks, setPullingEmbeddingModel } =- useRAGStore.getState()+ const {+ embeddingModel,+ setIndexing,+ setIndexingProgress,+ addDocument,+ addChunks,+ setEmbeddingInstallPrompt,+ queueEmbeddingFile,+ } = useRAGStore.getState()- // Pre-flight: check Ollama is reachable+ // Pre-flight: Ollama reachable?const ollamaUp = await checkConnection()if (!ollamaUp) {throw new Error(@@ -86,46 +164,18 @@ export function useRAG(conversationId: string | null) {)}- try {- // Check if embedding model exists, auto-pull if missing- const models = await listModels()- const hasEmbedding = models.some(- (m) => m.name === embeddingModel || m.name === embeddingModel + ":latest"- )-- if (!hasEmbedding) {- const shouldPull = window.confirm(- `The embedding model "${embeddingModel}" is not installed. Download it now? (~274MB)`- )- if (!shouldPull) {- throw new Error(- `Embedding model "${embeddingModel}" is required but not installed.`- )- }-- setPullingEmbeddingModel(true)- try {- const pullRes = await pullModel(embeddingModel)- const reader = pullRes.body?.getReader()- if (reader) {- const decoder = new TextDecoder()- while (true) {- const { done, value } = await reader.read()- if (done) break- const text = decoder.decode(value, { stream: true })- for (const line of text.split("\n").filter(Boolean)) {- try {- const json = JSON.parse(line)- if (json.status) console.log("[EmbeddingPull]", json.status)- } catch { /* skip non-JSON lines */ }- }- }- }- } finally {- setPullingEmbeddingModel(false)- }- }+ // Embedding model present? When missing we queue the file + flip the+ // RAGPanel install-prompt flag rather than blocking via the OS confirm+ // dialog. The user clicks Download in the in-app card → pullEmbedding+ // Model fires → on success the queued files replay automatically.+ const hasEmbedding = await ensureEmbeddingModel()+ if (!hasEmbedding) {+ queueEmbeddingFile(file)+ setEmbeddingInstallPrompt(true)+ return null+ }+ try {setIndexing(true)setIndexingProgress({ current: 0, total: 1 })@@ -150,9 +200,41 @@ export function useRAG(conversationId: string | null) {setIndexingProgress(null)}},- [conversationId]+ [conversationId, ensureEmbeddingModel])+ /**+ * Triggered from the in-app Install card or the post-update banner. Pulls+ * the embedding model, then drains any files the user dropped while we+ * waited. The drain re-enters `uploadDocument` so any later error handling+ * (extraction failures, bogus PDFs) reuses the same surface.+ */+ const installEmbeddingAndDrainQueue = useCallback(async (): Promise<void> => {+ const { setEmbeddingInstallPrompt, clearEmbeddingQueue } = useRAGStore.getState()+ const ok = await pullEmbeddingModel()+ setEmbeddingInstallPrompt(false)+ if (!ok) return // error surfaced via console; user sees status in progress card+ // Drain queue — copy first because uploadDocument doesn't touch the+ // queue, but a stale snapshot is safer than reading state mid-loop.+ const queue = [...useRAGStore.getState().embeddingQueuedFiles]+ clearEmbeddingQueue()+ for (const queued of queue) {+ try {+ await uploadDocument(queued)+ } catch (err) {+ // RAGPanel already handles per-file error display via its own+ // setError when the upload throws — log here for diagnostics only.+ console.error("[EmbeddingDrain] queued file failed:", queued.name, err)+ }+ }+ }, [pullEmbeddingModel, uploadDocument])++ const cancelEmbeddingInstall = useCallback(() => {+ const { setEmbeddingInstallPrompt, clearEmbeddingQueue } = useRAGStore.getState()+ setEmbeddingInstallPrompt(false)+ clearEmbeddingQueue()+ }, [])+const removeDoc = useCallback((docId: string) => {if (!conversationId) return@@ -202,5 +284,9 @@ export function useRAG(conversationId: string | null) {toggleRAG,clearAll,getContextForQuery,+ ensureEmbeddingModel,+ pullEmbeddingModel,+ installEmbeddingAndDrainQueue,+ cancelEmbeddingInstall,}}diff --git a/src/lib/__tests__/model-compatibility-planner.test.ts b/src/lib/__tests__/model-compatibility-planner.test.tsindex 7afce187..7aae74a3 100644--- a/src/lib/__tests__/model-compatibility-planner.test.ts+++ b/src/lib/__tests__/model-compatibility-planner.test.ts@@ -43,13 +43,14 @@ describe('isPlainTextPlanner', () => {expect(isPlainTextPlanner('GEMMA3:27B')).toBe(true)})it('strips single-segment org prefix', () => {- // The algorithm strips exactly ONE leading slash-terminated segment- // (`org/model` → `model`). Multi-slash HF paths (`hf.co/org/model`)- // leave an intermediate "org" in front so they do NOT match — this- // is intentional since we control the identifier format at the- // provider layer.+ // v2.4.9 made the prefix strip greedy (last slash), so multi-segment+ // HF refs `hf.co/<org>/<repo>:<tag>` also resolve to the family — that+ // is exactly the shape `pullModel(hf.co/<user>/<repo>:<quant>)` emits,+ // and the old non-greedy strip silently disabled the bypass for every+ // community Gemma 4 download (Bug X, leonsk29 Discord 2026-05-24).expect(isPlainTextPlanner('library/gemma4:31b')).toBe(true)expect(isPlainTextPlanner('ollama/gemma3:27b')).toBe(true)+ expect(isPlainTextPlanner('hf.co/bartowski/gemma4-27B-it-GGUF:Q4_K_M')).toBe(true)})})@@ -85,22 +86,21 @@ describe('isPlainTextPlanner', () => {expect(isPlainTextPlanner('gemma')).toBe(false)expect(isPlainTextPlanner('gemma:latest')).toBe(false)})- it('a substring match inside a different name → false', () => {- // e.g. a hypothetical model named "stuff-gemma3-X". Since our logic- // strips the org prefix then checks startsWith, this only triggers- // if the base name (after / and before :) starts with gemma3/4.- expect(isPlainTextPlanner('stuff-gemma3-mix')).toBe(false)+ it('a substring with explicit non-alphanumeric boundaries DOES match', () => {+ // v2.4.9 switched to a word-boundary contains-check (Bug X). A+ // hypothetical "stuff-gemma3-mix" build is most likely a Gemma 3+ // derivative — matching is the safe default, and the `think: undefined`+ // bypass that follows is harmless on a non-thinking model.+ expect(isPlainTextPlanner('stuff-gemma3-mix')).toBe(true)+ })+ it('still does NOT match when the family is wedged into a word (gemma3xyz)', () => {+ // Boundary check is real: alphanumeric chars immediately after the+ // family token break the match so `gemma3xyz` stays false.+ expect(isPlainTextPlanner('gemma3xyz')).toBe(false)+ expect(isPlainTextPlanner('foogemma3')).toBe(false)})it('gemma3 inside a single-segment org namespace triggers correctly', () => {expect(isPlainTextPlanner('mradermacher/gemma3-27b-it-GGUF')).toBe(true)})- it('multi-segment HF path like "hf.co/bart/gemma4-X" → false (by design)', () => {- // Known limitation — see the single-segment test above for the- // rationale. Documenting so regressions don't accidentally "fix"- // this case and shift model-matching semantics.- expect(- isPlainTextPlanner('hf.co/bartowski/gemma4-27B-it-GGUF:Q4_K_M')- ).toBe(false)- })})})diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.tsindex dbb11ebf..f7f52e49 100644--- a/src/lib/model-compatibility.ts+++ b/src/lib/model-compatibility.ts@@ -23,12 +23,81 @@ const AGENT_COMPATIBLE = ['nemotron',]+/**+ * Aggressively normalize a model tag into a comparable "family" key.+ *+ * The Ollama / HuggingFace ecosystem ships the same base under wildly+ * different cosmetic surface forms — `gemma4:e4b`, `gemma-4-it-uncensored`,+ * `huihui_ai/gemma-4-26b-a4b-heretic`, `mradermacher/Gemma-4-31B-it-abliterated-GGUF`.+ * leonsk29 (Discord 2026-05-24) reported Thinking + Agent both grayed out on+ * community uncensored Gemma 4 variants because the previous normalizer only+ * handled the dash-less family form (`gemma4`) and missed the dashed form+ * (`gemma-4`) that mradermacher / TrevorJS / Stabhappy / LiconStudio repos+ * all use. After normalization `gemma-4-it-abliterated-Q4_K_M` and `gemma4`+ * collapse to the same prefix and inherit the family's capability flags.+ *+ * Steps, in order:+ * 1. lowercase+ * 2. drop everything before the first slash (`huihui_ai/...` → `...`)+ * 3. drop GGUF / repo cruft markers (`-GGUF`, `-Imatrix`, `-MAX`)+ * 4. drop tuning / variant markers anywhere (`-abliterated`, `-uncensored`,+ * `-heretic`, `-instruct`, `-it`, `-chat`, `-base`)+ * 5. drop quant suffixes (`-Q4_K_M`, `.i1-Q4_K_M`, `-IQ2_XXS`, `-UD-Q4_K_XL`)+ * 6. drop the `:tag` part+ * 7. squash `gemma-4` → `gemma4`, `qwen-3` → `qwen3`, `llama-3.1` → `llama3.1`+ * so the dashed forms match the dash-less family entries+ */+function normalizeFamily(modelName: string): string {+ // Strip the FULL path prefix (greedy up to the last `/`), not just one+ // segment. `hf.co/trevorjs/gemma-4-31B-it-uncensored-GGUF:Q4_K_M` has two+ // slashes — the previous non-greedy strip left `trevorjs/...` behind and+ // the anchored dash-collapse below missed `gemma-4` entirely. Greedy fix+ // covers `hf.co/<user>/<repo>:<tag>`, `<user>/<repo>:<tag>`, and bare tags.+ let s = modelName.toLowerCase().replace(/^.*\//, '')+ // Suffix markers — drop wherever they appear+ s = s+ .replace(/-abliterated/g, '')+ .replace(/-uncensored/g, '')+ .replace(/-heretic/g, '')+ .replace(/-instruct/g, '')+ .replace(/-chat/g, '')+ .replace(/-base/g, '')+ .replace(/-it\b/g, '')+ // Repo cruft (`-gguf`, `-imatrix`, `-max`, `-i1`, `-ud`)+ s = s.replace(/-(gguf|imatrix|max|i1|ud)\b/g, '')+ // Quant suffixes (`-q4_k_m`, `-iq2_xxs`, `-mxfp8`, etc.) — kill from the+ // leftmost `-q\d` / `-iq\d` / `-fp\d` / `-bf\d` to end of string.+ s = s.replace(/[-.](q\d[a-z_0-9]*|iq\d[a-z_0-9]*|fp\d[a-z_0-9]*|bf\d+|nvfp\d+|mxfp\d+)$/i, '')+ // Drop the `:tag` part+ s = s.replace(/:.*$/, '')+ // Family-name dash collapse: gemma-4 -> gemma4, qwen-3 -> qwen3,+ // llama-3.1 -> llama3.1, glm-4 -> glm4, phi-4 -> phi4, deepseek-v3 stays.+ // Apply with /g so the pattern collapses anywhere it appears, not just at+ // string start — `huihui-gemma-4-…` needs to collapse the inner `gemma-4`.+ s = s.replace(/(gemma|qwen|llama|glm|phi)-(\d)/g, '$1$2')+ return s+}++/**+ * Check whether a family token appears as a free-standing word inside a+ * normalized name. We can't use `.startsWith` because community abliterator+ * repos prepend their own marker (`Huihui-Qwen3.5-…`, `mradermacher/Huihui-…`,+ * `coder3101_gemma_4_…`); after the slash strip the actual family is buried+ * mid-string. The match requires a non-alphanumeric boundary on both sides so+ * `mistral` does not collide with `mistralfork`, and `gemma3` does not match+ * inside `pre-gemma3xyz`.+ */+function containsFamily(family: string, normalized: string): boolean {+ const escaped = family.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+ return new RegExp(`(?:^|[^a-z0-9])${escaped}(?![a-z0-9])`).test(normalized)+}+/*** Check if a model supports Agent Mode.* Cloud providers always support tools. Ollama needs explicit check.*- * Strategy: strip user-prefix, abliterated/uncensored/instruct/chat suffixes- * and the :tag, then match the remaining base name against AGENT_COMPATIBLE.+ * Strategy: normalize the input via `normalizeFamily` then match against+ * the canonical list. See `normalizeFamily` for what the normalizer covers.** Earlier versions kept a much shorter `ABLITERATED_NATIVE` allow-list which* over-rejected uncensored variants of agent-capable bases (Qwen 3.5 Uncensored,@@ -45,16 +114,8 @@ export function isAgentCompatible(modelName: string | null): boolean {// Cloud providers always support tool callingif (providerId === 'openai' || providerId === 'anthropic') return true- // Ollama: strip everything decorative and check against the canonical list- const name = modelName.toLowerCase()- const baseName = name- .replace(/^[^/]+\//, '')- .replace(/-abliterated/g, '')- .replace(/-uncensored/g, '')- .replace(/-instruct/g, '')- .replace(/-chat/g, '')- .replace(/:.*$/, '')- return AGENT_COMPATIBLE.some((f) => baseName.startsWith(f))+ const baseName = normalizeFamily(modelName)+ return AGENT_COMPATIBLE.some((f) => containsFamily(f, baseName))}export const isToolCallingModel = isAgentCompatible@@ -78,15 +139,17 @@ const THINKING_COMPATIBLE = [/*** Check if a model supports thinking/chain-of-thought mode.* Cloud providers handle it gracefully. Ollama needs explicit support.+ *+ * Uses the shared `normalizeFamily` so dashed forms (`gemma-4-31B-it-abliterated`)+ * and dash-less forms (`gemma4:e4b`) both resolve to the same family key.*/export function isThinkingCompatible(modelName: string | null): boolean {if (!modelName) return falseconst providerId = getProviderIdFromModel(modelName)if (providerId === 'openai' || providerId === 'anthropic') return true- const name = modelName.toLowerCase()- const baseName = name.replace(/^[^/]+\//, '').replace(/:.*$/, '').replace(/-abliterated/g, '').replace(/-uncensored/g, '')- return THINKING_COMPATIBLE.some(f => baseName.startsWith(f))+ const baseName = normalizeFamily(modelName)+ return THINKING_COMPATIBLE.some(f => containsFamily(f, baseName))}/**@@ -106,9 +169,8 @@ export function isThinkingCompatible(modelName: string | null): boolean {*/export function isPlainTextPlanner(modelName: string | null): boolean {if (!modelName) return false- const name = modelName.toLowerCase()- const baseName = name.replace(/^[^/]+\//, '').replace(/:.*$/, '').replace(/-abliterated/g, '').replace(/-uncensored/g, '')- return baseName.startsWith('gemma3') || baseName.startsWith('gemma4')+ const baseName = normalizeFamily(modelName)+ return containsFamily('gemma3', baseName) || containsFamily('gemma4', baseName)}/**@@ -131,9 +193,8 @@ const CLAUDE_CODE_COMPATIBLE = [*/export function isClaudeCodeCompatible(modelName: string | null): boolean {if (!modelName) return false- const name = modelName.toLowerCase()- const baseName = name.replace(/^[^/]+\//, '').replace(/:.*$/, '').replace(/-abliterated/g, '').replace(/-uncensored/g, '')- return CLAUDE_CODE_COMPATIBLE.some(f => baseName.startsWith(f))+ const baseName = normalizeFamily(modelName)+ return CLAUDE_CODE_COMPATIBLE.some(f => containsFamily(f, baseName))}export type ToolCallingStrategy = 'native' | 'template_fix' | 'hermes_xml'diff --git a/src/lib/ragDB.ts b/src/lib/ragDB.tsindex 1d1a3cf5..b7623cbb 100644--- a/src/lib/ragDB.ts+++ b/src/lib/ragDB.ts@@ -86,3 +86,53 @@ export async function clearAllChunks(): Promise<void> {const store = await tx("readwrite")await idbRequest(store.clear())}++/**+ * Export every chunk in IndexedDB as a `documentId → TextChunk[]` map.+ *+ * Used by the v2.4.9 backup pipeline (Bug V, kj103x 2026-05-23) so RAG+ * embeddings survive an NSIS upgrade or WebView2 data wipe. Returns an+ * empty object — not null — when the store is empty so the snapshot file+ * is always well-formed JSON.+ */+export async function exportAllChunks(): Promise<Record<string, TextChunk[]>> {+ const store = await tx("readonly")+ const result: Record<string, TextChunk[]> = {}+ // Use openCursor() so we capture both the key (documentId) and the value+ // (TextChunk[]) in one pass — `getAll()` would lose the document IDs.+ await new Promise<void>((resolve, reject) => {+ const req = store.openCursor()+ req.onsuccess = () => {+ const cursor = req.result+ if (!cursor) {+ resolve()+ return+ }+ result[String(cursor.key)] = cursor.value as TextChunk[]+ cursor.continue()+ }+ req.onerror = () => reject(req.error)+ })+ return result+}++/**+ * Counterpart to `exportAllChunks` — overwrites the IndexedDB chunk store+ * from a serialized snapshot. Skips entries with no chunks so a corrupt /+ * partial snapshot can't blank out chunks already on disk that aren't+ * mentioned in the snapshot. Existing entries for the same documentId are+ * replaced (last-writer-wins, same semantics as `saveChunks`).+ */+export async function importAllChunks(snapshot: Record<string, TextChunk[]>): Promise<number> {+ const ids = Object.keys(snapshot)+ if (ids.length === 0) return 0+ const store = await tx("readwrite")+ let restored = 0+ for (const id of ids) {+ const chunks = snapshot[id]+ if (!Array.isArray(chunks) || chunks.length === 0) continue+ await idbRequest(store.put(chunks, id))+ restored+++ }+ return restored+}diff --git a/src/stores/__tests__/benchmarkStore.test.ts b/src/stores/__tests__/benchmarkStore.test.tsindex 33ab7eb9..3defa994 100644--- a/src/stores/__tests__/benchmarkStore.test.ts+++ b/src/stores/__tests__/benchmarkStore.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach } from 'vitest'-import { useBenchmarkStore, getAverageSpeed, getLeaderboard, computeGenerationTps } from '../benchmarkStore'+import { useBenchmarkStore, getAverageSpeed, getLatestSpeed, getLeaderboard, computeGenerationTps } from '../benchmarkStore'import type { BenchmarkResult } from '../../lib/benchmark-prompts'// ── Helpers ─────────────────────────────────────────────────────@@ -161,6 +161,68 @@ describe('benchmarkStore', () => {})})+ // ── getLatestSpeed (Bug W — nightmare13740 2026-05-24) ─────++ describe('getLatestSpeed', () => {+ it('returns null for missing or empty results', () => {+ expect(getLatestSpeed({}, 'unknown')).toBeNull()+ expect(getLatestSpeed({ llama3: [] }, 'llama3')).toBeNull()+ })++ it('returns the only result when there is just one', () => {+ const r = { llama3: [makeResult('llama3', 42.3, { timestamp: 1_000_000 })] }+ expect(getLatestSpeed(r, 'llama3')).toBe(42.3)+ })++ it('averages prompts within ONE benchmark session (close-together timestamps)', () => {+ // Within-session: BENCHMARK_PROMPTS produces multiple addResult calls,+ // all within seconds of each other. They should be averaged together.+ const t0 = 1_000_000+ const r = {+ llama3: [+ makeResult('llama3', 20, { timestamp: t0 }),+ makeResult('llama3', 30, { timestamp: t0 + 2_000 }),+ makeResult('llama3', 40, { timestamp: t0 + 4_000 }),+ ],+ }+ // (20 + 30 + 40) / 3 = 30+ expect(getLatestSpeed(r, 'llama3')).toBe(30)+ })++ it('IGNORES previous session when a new one starts (>10 s gap)', () => {+ // nightmare13740 scenario: ten Run Benchmark clicks. Old sessions+ // should not pollute the displayed number for the most recent click.+ const t0 = 1_000_000+ const r = {+ llama3: [+ // Session A: avg 15.2+ makeResult('llama3', 14.0, { timestamp: t0 }),+ makeResult('llama3', 15.5, { timestamp: t0 + 1_000 }),+ makeResult('llama3', 16.1, { timestamp: t0 + 2_000 }),+ // 5-minute gap — new session+ makeResult('llama3', 17.5, { timestamp: t0 + 300_000 }),+ makeResult('llama3', 18.2, { timestamp: t0 + 301_000 }),+ makeResult('llama3', 17.9, { timestamp: t0 + 302_000 }),+ ],+ }+ // Latest session only: (17.5 + 18.2 + 17.9) / 3 = 17.866... → 17.9+ expect(getLatestSpeed(r, 'llama3')).toBe(17.9)+ })++ it('still averages ALL runs when they are within session gap of each other', () => {+ // Edge case: rapid-fire reruns within the 10 s gap stay one session.+ const t0 = 1_000_000+ const r = {+ llama3: [+ makeResult('llama3', 10, { timestamp: t0 }),+ makeResult('llama3', 20, { timestamp: t0 + 3_000 }),+ makeResult('llama3', 30, { timestamp: t0 + 6_000 }),+ ],+ }+ expect(getLatestSpeed(r, 'llama3')).toBe(20)+ })+ })+// ── getLeaderboard ─────────────────────────────────────────describe('getLeaderboard', () => {diff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.tsindex bc04b455..1ce796b9 100644--- a/src/stores/benchmarkStore.ts+++ b/src/stores/benchmarkStore.ts@@ -53,6 +53,43 @@ export function getAverageSpeed(results: Record<string, BenchmarkResult[]>, modereturn Math.round(avg * 10) / 10}+/**+ * Get the LATEST benchmark tps for a model. The Benchmark view shows this+ * next to each model so the displayed number reflects the most recent run,+ * not a session-wide running average that quietly drifts as more samples+ * cancel noise.+ *+ * nightmare13740 (Discord 2026-05-23/24) flagged this on a Bug M retest:+ * gemma4:e4b read 15.2 tok/s on the first run and climbed to 17.9 after ten+ * runs. They thought previous results were affecting new ones — they were,+ * but only because the UI was averaging instead of showing the last sample.+ * The actual measurement was stable; the display was misleading.+ *+ * Per-prompt samples within ONE benchmark click stay averaged (BENCHMARK_PROMPTS+ * has multiple prompts and the average across them within a single session+ * gives a meaningful tok/s). The drift the user saw was across sessions —+ * each "Run Benchmark" click appended more samples without resetting.+ */+export function getLatestSpeed(results: Record<string, BenchmarkResult[]>, modelName: string): number | null {+ const runs = results[modelName]+ if (!runs || runs.length === 0) return null+ // Group consecutive runs by their addedAt timestamp into "sessions" — a+ // session is one click of Run Benchmark across BENCHMARK_PROMPTS prompts.+ // Anything within 10 s of the previous result counts as the same session.+ const SESSION_GAP_MS = 10_000+ let sessionStart = runs.length - 1+ for (let i = runs.length - 1; i > 0; i--) {+ if (runs[i].timestamp - runs[i - 1].timestamp > SESSION_GAP_MS) {+ sessionStart = i+ break+ }+ sessionStart = i - 1+ }+ const lastSession = runs.slice(sessionStart)+ const avg = lastSession.reduce((s, r) => s + r.tokensPerSec, 0) / lastSession.length+ return Math.round(avg * 10) / 10+}+/*** Compute tokens-per-second excluding time-to-first-token / stream init.*diff --git a/src/stores/ragStore.ts b/src/stores/ragStore.tsindex 4e0c2d20..0246c68c 100644--- a/src/stores/ragStore.ts+++ b/src/stores/ragStore.ts@@ -13,6 +13,18 @@ interface RAGState {lastRetrievedChunks: { chunk: TextChunk; score: number }[]contextWarning: string | nullpullingEmbeddingModel: boolean+ /** Bytes-level progress for the embedding-model pull (Bug F45-followup,+ * upgrade-path UX). Populated by useRAG.pullEmbeddingModel from each+ * Ollama /api/pull stream chunk. `null` while idle. */+ embeddingPullProgress: { completed: number; total: number; status: string } | null+ /** Files the user dropped while the embedding model was still missing —+ * RAGPanel surfaces an Install-card; after the pull succeeds we replay+ * these through uploadDocument so the user doesn't have to drag again. */+ embeddingQueuedFiles: File[]+ /** Indicates the next document upload needs the user to confirm the+ * embedding install first. RAGPanel renders the prompt card; uploads+ * resume once `embeddingPullProgress` reaches completion. */+ embeddingInstallPrompt: booleanchunksLoaded: booleanaddDocument: (conversationId: string, meta: DocumentMeta) => void@@ -28,6 +40,10 @@ interface RAGState {setLastRetrievedChunks: (chunks: { chunk: TextChunk; score: number }[]) => voidsetContextWarning: (warning: string | null) => voidsetPullingEmbeddingModel: (pulling: boolean) => void+ setEmbeddingPullProgress: (p: { completed: number; total: number; status: string } | null) => void+ setEmbeddingInstallPrompt: (prompt: boolean) => void+ queueEmbeddingFile: (file: File) => void+ clearEmbeddingQueue: () => void}export const useRAGStore = create<RAGState>()(@@ -42,6 +58,9 @@ export const useRAGStore = create<RAGState>()(lastRetrievedChunks: [],contextWarning: null,pullingEmbeddingModel: false,+ embeddingPullProgress: null,+ embeddingQueuedFiles: [],+ embeddingInstallPrompt: false,chunksLoaded: false,addDocument: (conversationId, meta) =>@@ -158,6 +177,15 @@ export const useRAGStore = create<RAGState>()(setContextWarning: (warning) => set({ contextWarning: warning }),setPullingEmbeddingModel: (pulling) => set({ pullingEmbeddingModel: pulling }),++ setEmbeddingPullProgress: (p) => set({ embeddingPullProgress: p }),++ setEmbeddingInstallPrompt: (prompt) => set({ embeddingInstallPrompt: prompt }),++ queueEmbeddingFile: (file) =>+ set((state) => ({ embeddingQueuedFiles: [...state.embeddingQueuedFiles, file] })),++ clearEmbeddingQueue: () => set({ embeddingQueuedFiles: [] }),}),{name: "rag-store",