Skip to content

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

feat: v2.0 features — A/B Compare, Benchmark, LaTeX, Token Counter, Search Providers

PurpleDoubleDf65f46daf40f
diff --git a/README.md b/README.md
index c32eed8b..83f86434 100644
--- a/README.md
+++ b/README.md
@@ -44,11 +44,15 @@ Tired of switching between Ollama for chat, ComfyUI for images, and another tool
| Feature | Locally Uncensored | Open WebUI | LM Studio | SillyTavern |
|---------|:-:|:-:|:-:|:-:|
| AI Chat | ✅ | ✅ | ✅ | ✅ |
+| **Multi-Provider** (Ollama + Cloud) | **✅** | ✅ | ✅ | ❌ |
| **Agent Mode (Tool Calling)** | **✅** | ❌ | ❌ | ❌ |
+| **Model A/B Compare** | **✅** | ❌ | ❌ | ❌ |
+| **Local Benchmark** | **✅** | ❌ | ❌ | ❌ |
| Image Generation | ✅ | ❌ | ❌ | ❌ |
| Video Generation | ✅ | ❌ | ❌ | ❌ |
| Uncensored by Default | ✅ | ❌ | ❌ | ⚠️ |
| Memory System | ✅ | ❌ | ❌ | ❌ |
+| LaTeX / Math Rendering | ✅ | ✅ | ❌ | ❌ |
| One-Click Setup | ✅ | ❌ (Docker) | ✅ | ❌ (Node.js) |
| 25+ Built-in Personas | ✅ | ❌ | ❌ | ⚠️ (manual) |
| RAG / Document Chat | ✅ | ✅ | ❌ | ❌ |
@@ -61,18 +65,26 @@ Tired of switching between Ollama for chat, ComfyUI for images, and another tool
## ✨ Features
- **Uncensored AI Chat** — Run abliterated models locally with zero restrictions
+- **Multi-Provider Support** — Ollama (local), OpenAI-compatible (OpenRouter, Groq, LMStudio, vLLM), Anthropic (Claude). Switch providers per conversation.
- **Agent Mode (Beta)** — Give your AI tools: web search, web fetch, file I/O, code execution, image generation. It chains tools autonomously to answer questions with real data. Best with [Hermes 3](https://ollama.com/library/hermes3).
+- **Model A/B Compare** — Send the same prompt to two models side by side. Compare speed, quality, and token usage in real-time with parallel streaming.
+- **Local Benchmark** — One-click benchmark any model on your hardware. Measures tokens/sec, time-to-first-token. Leaderboard across all tested models.
- **Memory System** — Agent Mode auto-saves tool results. Persistent across sessions. Export/import as .md.
- **Image Generation** — Text-to-image via ComfyUI with full parameter control
- **Video Generation** — Text-to-video with Wan 2.1/2.2, HunyuanVideo, LTX support
- **Document Chat (RAG)** — Upload PDFs, DOCX, or TXT files and chat with your documents
- **Voice Chat** — Talk to your AI with push-to-talk and hear responses with TTS
+- **LaTeX / Math Rendering** — Full KaTeX support for inline and block math equations
+- **Chat Export** — Export conversations as Markdown or JSON with one click
+- **Token Counter** — Live token usage display with color-coded progress bar
+- **Keyboard Shortcuts** — Ctrl+N (new chat), Ctrl+E (export), Ctrl+L (focus input), Ctrl+/ (shortcuts)
+- **Search Providers** — Agent web search via SearXNG, Brave Search, Tavily, or DuckDuckGo. Configurable in settings.
- **25+ Personas** — From Helpful Assistant to Roast Master, switchable via dropdown
-- **Model Manager** — Browse, install, and switch models. HOT badges for recommended models. Variant selector for multi-size downloads.
+- **Model Manager** — Browse uncensored + mainstream models. HOT/AGENT badges. Variant selector for multi-size downloads.
- **Thinking Display** — See the AI's reasoning in collapsible blocks
- **Linear/Arc UI** — Compact, monochrome, collapsible settings. Premium feel.
- **Privacy First** — Zero tracking. All API calls proxied locally. No analytics.
-- **100% Local** — Everything runs on your machine
+- **100% Local** — Everything runs on your machine (cloud providers optional)
- **Standalone Desktop App** — Tauri v2 Rust backend. Download the .exe, run it.
## Tech Stack
@@ -80,7 +92,7 @@ Tired of switching between Ollama for chat, ComfyUI for images, and another tool
- **Desktop**: Tauri v2 (Rust backend, standalone .exe — no Node.js required)
- **Frontend**: React 19, TypeScript, Tailwind CSS 4, Framer Motion
- **State**: Zustand with localStorage persistence
-- **AI Backend**: Ollama (text), ComfyUI (images/video), faster-whisper (voice)
+- **AI Backend**: Ollama (local text), OpenAI-compat (cloud/local), Anthropic (cloud), ComfyUI (images/video), faster-whisper (voice)
- **Build**: Vite 8 (dev), Tauri CLI (production)
---
@@ -190,6 +202,8 @@ Just install models in the standard locations and the app picks them up.
|-------|------|------|----------|
| **Hermes 3 8B** | 4.3 GB | 6 GB | **Agent Mode** — uncensored + native tool calling |
| **Hermes 3 70B** | 42 GB | 48 GB | **Best Agent** — maximum power |
+| **Gemma 4 26B MoE** | 18 GB | 8 GB | 26B brain, runs like 4B. Vision + tools. Apache 2.0 |
+| Gemma 4 E4B | 9.6 GB | 6 GB | Vision + native tools. 128K context |
| Qwen 3.5 Abliterated | 5–18 GB | 6–16 GB | Best overall intelligence |
| Qwen 3 8B Abliterated | 5.2 GB | 6 GB | Fast, great for coding |
| DeepSeek R1 (8B–70B) | 5–42 GB | 6–48 GB | Chain-of-thought reasoning |
@@ -243,9 +257,18 @@ COMFYUI_PATH=/path/to/your/ComfyUI
- [x] **Agent Mode (Beta)** — Tool calling with web search, file I/O, code execution
- [x] **Memory System** — Persistent agent memory with export/import
- [x] **Voice Chat** — STT + TTS with local Whisper
-- [ ] **Audio Generation** — Text-to-speech and music generation
+- [x] **Multi-Provider** — Ollama + OpenAI-compatible + Anthropic
+- [x] **Model A/B Compare** — Side-by-side model comparison with parallel streaming
+- [x] **Local Benchmark** — One-click benchmark with leaderboard
+- [x] **LaTeX Rendering** — KaTeX for math equations
+- [x] **Token Counter** — Live context window usage
+- [x] **Chat Export** — Markdown and JSON export
+- [x] **Keyboard Shortcuts** — Power-user shortcuts (Ctrl+N, Ctrl+E, Ctrl+/)
+- [x] **Search Providers** — Brave Search, Tavily, SearXNG, DuckDuckGo
+- [ ] **MCP Support** — Model Context Protocol for extensible tool calling
+- [ ] **Create Modes** — img2img, upscale, inpainting, background removal
+- [ ] **Workflow Chains** — Chain multiple generation steps into pipelines
- [ ] **Plugin System** — Extend the app with community plugins
-- [ ] **Multi-User Mode** — Share your local AI server with your household
- [ ] **Mobile UI** — Responsive layout for phone/tablet access
Have an idea? [Open a discussion](https://github.com/PurpleDoubleD/locally-uncensored/discussions)!
@@ -256,18 +279,20 @@ Have an idea? [Open a discussion](https://github.com/PurpleDoubleD/locally-uncen
```
src/
- api/ # Ollama & ComfyUI API clients
- components/ # React components
- chat/ # Chat UI (messages, input, markdown)
- create/ # Image/Video generation UI
- models/ # Model management
- personas/ # Persona selection
- settings/ # App settings
- ui/ # Reusable UI components
- hooks/ # Custom React hooks
- stores/ # Zustand state management
- types/ # TypeScript definitions
- lib/ # Constants & utilities
+ api/ # Backend clients (Ollama, ComfyUI, providers, RAG, voice, agents)
+ providers/ # Multi-provider system (Ollama, OpenAI-compat, Anthropic)
+ components/ # React components
+ chat/ # Chat UI, A/B Compare, Token Counter, Export
+ create/ # Image/Video generation UI
+ models/ # Model management, Benchmark, Discovery
+ personas/ # Persona selection
+ settings/ # App settings, Provider config, Search provider
+ layout/ # App shell, Sidebar, Header, Shortcuts modal
+ ui/ # Reusable UI components
+ hooks/ # useChat, useABCompare, useBenchmark, useKeyboardShortcuts
+ stores/ # Zustand stores (chat, model, settings, provider, compare, benchmark)
+ types/ # TypeScript definitions
+ lib/ # Utilities, benchmark prompts, chat export, model compatibility
```
---
diff --git a/package-lock.json b/package-lock.json
index 356cf4c8..5ab944cf 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "locally-uncensored",
- "version": "1.5.5",
+ "version": "1.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "locally-uncensored",
- "version": "1.5.5",
+ "version": "1.9.0",
"license": "MIT",
"dependencies": {
"@react-three/drei": "^10.7.7",
@@ -24,7 +24,9 @@
"react-dom": "^19.2.4",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^16.1.1",
+ "rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.1",
+ "remark-math": "^6.0.0",
"tailwindcss": "^4.2.2",
"three": "^0.183.2",
"uuid": "^13.0.0",
@@ -1791,6 +1793,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/katex": {
+ "version": "0.16.8",
+ "resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.8.tgz",
+ "integrity": "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==",
+ "license": "MIT"
+ },
"node_modules/@types/mdast": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
@@ -2735,6 +2743,15 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/commander": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -2923,6 +2940,18 @@
"node": ">=10.13.0"
}
},
+ "node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/es-module-lexer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz",
@@ -3388,6 +3417,88 @@
"node": ">=8"
}
},
+ "node_modules/hast-util-from-dom": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz",
+ "integrity": "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==",
+ "license": "ISC",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hastscript": "^9.0.0",
+ "web-namespaces": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-html": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/hast-util-from-html/-/hast-util-from-html-2.0.3.tgz",
+ "integrity": "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "devlop": "^1.1.0",
+ "hast-util-from-parse5": "^8.0.0",
+ "parse5": "^7.0.0",
+ "vfile": "^6.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-html-isomorphic": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-from-html-isomorphic/-/hast-util-from-html-isomorphic-2.0.0.tgz",
+ "integrity": "sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hast-util-from-dom": "^5.0.0",
+ "hast-util-from-html": "^2.0.0",
+ "unist-util-remove-position": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-parse5": {
+ "version": "8.0.3",
+ "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz",
+ "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "devlop": "^1.0.0",
+ "hastscript": "^9.0.0",
+ "property-information": "^7.0.0",
+ "vfile": "^6.0.0",
+ "vfile-location": "^5.0.0",
+ "web-namespaces": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-is-element": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz",
+ "integrity": "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/hast-util-parse-selector": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",
@@ -3428,6 +3539,22 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/hast-util-to-text": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz",
+ "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "hast-util-is-element": "^3.0.0",
+ "unist-util-find-after": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/hast-util-whitespace": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
@@ -3778,6 +3905,22 @@
"setimmediate": "^1.0.5"
}
},
+ "node_modules/katex": {
+ "version": "0.16.44",
+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.44.tgz",
+ "integrity": "sha512-EkxoDTk8ufHqHlf9QxGwcxeLkWRR3iOuYfRpfORgYfqc8s13bgb+YtRY59NK5ZpRaCwq1kqA6a5lpX8C/eLphQ==",
+ "funding": [
+ "https://opencollective.com/katex",
+ "https://github.com/sponsors/katex"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "commander": "^8.3.0"
+ },
+ "bin": {
+ "katex": "cli.js"
+ }
+ },
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -4352,6 +4495,25 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/mdast-util-math": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-math/-/mdast-util-math-3.0.0.tgz",
+ "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.1.0",
+ "unist-util-remove-position": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/mdast-util-mdx-expression": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
@@ -4686,6 +4848,25 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/micromark-extension-math": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz",
+ "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/katex": "^0.16.0",
+ "devlop": "^1.0.0",
+ "katex": "^0.16.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/micromark-factory-destination": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
@@ -5243,6 +5424,18 @@
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
"license": "MIT"
},
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -5512,6 +5705,25 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/rehype-katex": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/rehype-katex/-/rehype-katex-7.0.1.tgz",
+ "integrity": "sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/katex": "^0.16.0",
+ "hast-util-from-html-isomorphic": "^2.0.0",
+ "hast-util-to-text": "^4.0.0",
+ "katex": "^0.16.0",
+ "unist-util-visit-parents": "^6.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/remark-gfm": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
@@ -5530,6 +5742,22 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/remark-math": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz",
+ "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-math": "^3.0.0",
+ "micromark-extension-math": "^3.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/remark-parse": {
"version": "11.0.0",
"resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",
@@ -6122,6 +6350,20 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/unist-util-find-after": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz",
+ "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/unist-util-is": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
@@ -6148,6 +6390,20 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/unist-util-remove-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz",
+ "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-visit": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/unist-util-stringify-position": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
@@ -6282,6 +6538,20 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/vfile-location": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.3.tgz",
+ "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/vfile-message": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
@@ -6455,6 +6725,16 @@
}
}
},
+ "node_modules/web-namespaces": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz",
+ "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/webgl-constants": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/webgl-constants/-/webgl-constants-1.1.1.tgz",
diff --git a/package.json b/package.json
index f24b65ce..91aa6704 100644
--- a/package.json
+++ b/package.json
@@ -49,7 +49,9 @@
"react-dom": "^19.2.4",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^16.1.1",
+ "rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.1",
+ "remark-math": "^6.0.0",
"tailwindcss": "^4.2.2",
"three": "^0.183.2",
"uuid": "^13.0.0",
diff --git a/src/api/__tests__/model-compatibility.test.ts b/src/api/__tests__/model-compatibility.test.ts
index 63deaed6..646541db 100644
--- a/src/api/__tests__/model-compatibility.test.ts
+++ b/src/api/__tests__/model-compatibility.test.ts
@@ -38,6 +38,14 @@ describe('isAgentCompatible', () => {
expect(isAgentCompatible('mistral-small:22b')).toBe(true)
})
+ it('gemma4 models are compatible (native tool calling)', () => {
+ expect(isAgentCompatible('gemma4:e2b')).toBe(true)
+ expect(isAgentCompatible('gemma4:e4b')).toBe(true)
+ expect(isAgentCompatible('gemma4:26b')).toBe(true)
+ expect(isAgentCompatible('gemma4:31b')).toBe(true)
+ expect(isAgentCompatible('gemma4:26b-a4b-it-q4_K_M')).toBe(true)
+ })
+
it('other compatible models', () => {
expect(isAgentCompatible('command-r:35b')).toBe(true)
expect(isAgentCompatible('phi-4:14b')).toBe(true)
@@ -93,6 +101,8 @@ describe('getToolCallingStrategy', () => {
expect(getToolCallingStrategy('hermes3:8b')).toBe('native')
expect(getToolCallingStrategy('qwen2.5:7b')).toBe('native')
expect(getToolCallingStrategy('llama3.1:8b')).toBe('native')
+ expect(getToolCallingStrategy('gemma4:26b')).toBe('native')
+ expect(getToolCallingStrategy('gemma4:e4b')).toBe('native')
})
it('Ollama abliterated models use hermes_xml', () => {
@@ -135,6 +145,14 @@ describe('getRecommendedAgentModels', () => {
expect(hermes!.hot).toBe(true)
})
+ it('gemma4 26b MoE is in recommended models', () => {
+ const models = getRecommendedAgentModels()
+ const gemma4 = models.find(m => m.name.includes('gemma4'))
+ expect(gemma4).toBeDefined()
+ expect(gemma4!.hot).toBe(true)
+ expect(gemma4!.provider).toBe('ollama')
+ })
+
it('all recommended models are actually compatible', () => {
const models = getRecommendedAgentModels()
for (const m of models) {
diff --git a/src/api/agents.ts b/src/api/agents.ts
index 40b64b95..7014546a 100644
--- a/src/api/agents.ts
+++ b/src/api/agents.ts
@@ -279,9 +279,15 @@ export async function executeTool(
}
case "web_search": {
+ // Pass search provider config from settings
+ const { useSettingsStore } = await import('../stores/settingsStore')
+ const searchSettings = useSettingsStore.getState().settings
const data = await backendCall("web_search", {
query: args.query,
count: args.maxResults || 5,
+ provider: searchSettings.searchProvider || 'auto',
+ braveApiKey: searchSettings.braveApiKey || '',
+ tavilyApiKey: searchSettings.tavilyApiKey || '',
});
if (Array.isArray(data.results)) {
return data.results
diff --git a/src/api/discover.ts b/src/api/discover.ts
index ee37265d..2ad0b469 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -205,17 +205,18 @@ function parseOllamaSearchHTML(html: string): DiscoverModel[] {
return models
}
-function getCuratedTextModels(): DiscoverModel[] {
+/** Uncensored / abliterated models — the core of LU */
+export function getUncensoredTextModels(): DiscoverModel[] {
return [
// ── HOT: Agent Mode + Uncensored ──
{ name: 'hermes3', description: 'NousResearch Hermes 3 — uncensored + native tool calling. THE agent model.', pulls: '500K+', tags: ['3B', '8B', '70B', '405B'], updated: 'Hot', hot: true, agent: true },
{ name: 'dolphin3', description: 'Dolphin 3 — uncensored from training. Coding, math, general purpose.', pulls: '3.7M', tags: ['8B'], updated: 'Hot', hot: true },
{ name: 'huihui_ai/qwen3.5-abliterated', description: 'Qwen 3.5 abliterated — newest, strongest reasoning + coding.', pulls: '10K+', tags: ['8B', '14B', '32B'], updated: 'Hot', hot: true },
+ { name: 'huihui_ai/gpt-oss-abliterated', description: 'OpenAI GPT-OSS — abliterated open-source GPT model.', pulls: '15K+', tags: ['8B', '32B'], updated: 'Hot', hot: true },
// ── Popular Uncensored ──
{ name: 'huihui_ai/qwen3-abliterated', description: 'Qwen3 abliterated — best overall. Exceptional reasoning, coding, multilingual.', pulls: '30K+', tags: ['8B', '30B'], updated: 'Popular' },
{ name: 'mannix/llama3.1-8b-abliterated', description: 'Llama 3.1 8B — fast, reliable, great entry point.', pulls: '200K+', tags: ['8B', 'Q5_K_M'], updated: 'Popular' },
{ name: 'huihui_ai/deepseek-r1-abliterated', description: 'DeepSeek R1 — chain-of-thought reasoning. Scales to your hardware.', pulls: '40K+', tags: ['8B', '14B', '32B', '70B'], updated: 'Popular' },
- { name: 'huihui_ai/gpt-oss-abliterated', description: 'OpenAI GPT-OSS — abliterated open-source GPT model.', pulls: '15K+', tags: ['8B', '32B'], updated: 'Hot', hot: true },
{ name: 'huihui_ai/glm4.6-abliterated', description: 'GLM 4.6 abliterated — newest model, strong coding and reasoning.', pulls: '5K+', tags: ['9B'], updated: 'New' },
{ name: 'huihui_ai/gemma3-abliterated', description: 'Google Gemma 3 — vision support, great quality.', pulls: '20K+', tags: ['4B', '12B', '27B'], updated: 'Popular' },
{ name: 'richardyoung/qwen3-14b-abliterated', description: 'Qwen3 14B — sweet spot of speed and intelligence.', pulls: '4K+', tags: ['14B', 'Q4_K_M'], updated: 'Recent' },
@@ -227,6 +228,23 @@ function getCuratedTextModels(): DiscoverModel[] {
]
}
+/** Mainstream models — not uncensored but excellent for specific tasks */
+export function getMainstreamTextModels(): DiscoverModel[] {
+ return [
+ { name: 'gemma4', description: 'Google Gemma 4 — native tool calling + vision. 128-256K context. Apache 2.0.', pulls: '100K+', tags: ['2B', '4B', '26B MoE', '31B'], updated: 'New', hot: true, agent: true },
+ { name: 'qwen3', description: 'Qwen 3 — top-tier reasoning and coding. Thinking mode support.', pulls: '5M+', tags: ['8B', '14B', '32B'], updated: 'Popular', agent: true },
+ { name: 'llama4', description: 'Meta Llama 4 — latest generation. Strong all-rounder with tool calling.', pulls: '1M+', tags: ['8B'], updated: 'New', agent: true },
+ { name: 'deepseek-r1', description: 'DeepSeek R1 — chain-of-thought reasoning model. Shows its thinking.', pulls: '2M+', tags: ['8B', '14B', '32B', '70B'], updated: 'Popular' },
+ { name: 'phi4', description: 'Microsoft Phi 4 — excellent math, logic, structured tasks.', pulls: '500K+', tags: ['14B'], updated: 'Popular', agent: true },
+ { name: 'mistral-small', description: 'Mistral Small — fast, multilingual, native tool calling.', pulls: '300K+', tags: ['24B'], updated: 'Popular', agent: true },
+ ]
+}
+
+/** Combined curated list for search fallback — uncensored first */
+function getCuratedTextModels(): DiscoverModel[] {
+ return [...getUncensoredTextModels(), ...getMainstreamTextModels()]
+}
+
// ─── Image Model Bundles ───
export function getImageBundles(): ModelBundle[] {
diff --git a/src/components/chat/ABCompare.tsx b/src/components/chat/ABCompare.tsx
new file mode 100644
index 00000000..34e034ed
--- /dev/null
+++ b/src/components/chat/ABCompare.tsx
@@ -0,0 +1,160 @@
+import { useState, useRef, useEffect } from 'react'
+import { useCompareStore } from '../../stores/compareStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useABCompare } from '../../hooks/useABCompare'
+import { MarkdownRenderer } from './MarkdownRenderer'
+import { ArrowLeft, Send, Square, Zap, Clock, Hash } from 'lucide-react'
+
+export function ABCompare() {
+ const {
+ modelA, modelB, messagesA, messagesB,
+ statsA, statsB, isStreamingA, isStreamingB,
+ setModelA, setModelB, setComparing, reset,
+ } = useCompareStore()
+ const models = useModelStore((s) => s.models)
+ const textModels = models.filter(m => m.type === 'text')
+ const { sendCompare, stopCompare } = useABCompare()
+ const [input, setInput] = useState('')
+ const scrollRefA = useRef<HTMLDivElement>(null)
+ const scrollRefB = useRef<HTMLDivElement>(null)
+ const isStreaming = isStreamingA || isStreamingB
+
+ // Auto-scroll during streaming
+ useEffect(() => {
+ if (isStreamingA && scrollRefA.current) {
+ scrollRefA.current.scrollTop = scrollRefA.current.scrollHeight
+ }
+ }, [messagesA, isStreamingA])
+
+ useEffect(() => {
+ if (isStreamingB && scrollRefB.current) {
+ scrollRefB.current.scrollTop = scrollRefB.current.scrollHeight
+ }
+ }, [messagesB, isStreamingB])
+
+ const handleSend = () => {
+ if (!input.trim() || isStreaming) return
+ sendCompare(input)
+ setInput('')
+ }
+
+ return (
+ <div className="h-full flex flex-col">
+ {/* Header */}
+ <div className="flex items-center gap-3 px-3 py-2 border-b border-white/5">
+ <button
+ onClick={() => { setComparing(false); reset() }}
+ className="p-1 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
+ >
+ <ArrowLeft size={14} />
+ </button>
+ <span className="text-[0.7rem] font-semibold text-white">A/B Compare</span>
+
+ {/* Model selectors */}
+ <div className="flex-1 flex items-center justify-center gap-3">
+ <select
+ value={modelA}
+ onChange={(e) => setModelA(e.target.value)}
+ className="px-2 py-1 rounded-lg bg-red-500/10 border border-red-500/30 text-[0.6rem] text-red-300 focus:outline-none"
+ >
+ <option value="">Model A</option>
+ {textModels.map(m => (
+ <option key={m.name} value={m.name}>{m.name}</option>
+ ))}
+ </select>
+ <span className="text-[0.6rem] text-gray-500 font-bold">VS</span>
+ <select
+ value={modelB}
+ onChange={(e) => setModelB(e.target.value)}
+ className="px-2 py-1 rounded-lg bg-blue-500/10 border border-blue-500/30 text-[0.6rem] text-blue-300 focus:outline-none"
+ >
+ <option value="">Model B</option>
+ {textModels.map(m => (
+ <option key={m.name} value={m.name}>{m.name}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {/* Split view */}
+ <div className="flex-1 flex min-h-0">
+ {/* Model A column */}
+ <div className="flex-1 flex flex-col border-r border-white/5">
+ <div className="px-3 py-1.5 border-b border-white/5 flex items-center justify-between">
+ <span className="text-[0.6rem] font-medium text-red-400">{modelA || 'Select Model A'}</span>
+ {statsA && (
+ <div className="flex items-center gap-2 text-[0.5rem] text-gray-500">
+ <span className="flex items-center gap-0.5"><Zap size={8} />{statsA.tokensPerSec.toFixed(1)} t/s</span>
+ <span className="flex items-center gap-0.5"><Clock size={8} />{(statsA.timeMs / 1000).toFixed(1)}s</span>
+ <span className="flex items-center gap-0.5"><Hash size={8} />{statsA.tokens}</span>
+ </div>
+ )}
+ </div>
+ <div ref={scrollRefA} className="flex-1 overflow-y-auto scrollbar-thin p-3 space-y-3">
+ {messagesA.map(msg => (
+ <div key={msg.id} className={`text-[0.7rem] ${msg.role === 'user' ? 'text-gray-400 italic' : 'text-gray-200'}`}>
+ {msg.role === 'assistant' ? (
+ <MarkdownRenderer content={msg.content || (isStreamingA ? '...' : '')} />
+ ) : (
+ <p>{msg.content}</p>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Model B column */}
+ <div className="flex-1 flex flex-col">
+ <div className="px-3 py-1.5 border-b border-white/5 flex items-center justify-between">
+ <span className="text-[0.6rem] font-medium text-blue-400">{modelB || 'Select Model B'}</span>
+ {statsB && (
+ <div className="flex items-center gap-2 text-[0.5rem] text-gray-500">
+ <span className="flex items-center gap-0.5"><Zap size={8} />{statsB.tokensPerSec.toFixed(1)} t/s</span>
+ <span className="flex items-center gap-0.5"><Clock size={8} />{(statsB.timeMs / 1000).toFixed(1)}s</span>
+ <span className="flex items-center gap-0.5"><Hash size={8} />{statsB.tokens}</span>
+ </div>
+ )}
+ </div>
+ <div ref={scrollRefB} className="flex-1 overflow-y-auto scrollbar-thin p-3 space-y-3">
+ {messagesB.map(msg => (
+ <div key={msg.id} className={`text-[0.7rem] ${msg.role === 'user' ? 'text-gray-400 italic' : 'text-gray-200'}`}>
+ {msg.role === 'assistant' ? (
+ <MarkdownRenderer content={msg.content || (isStreamingB ? '...' : '')} />
+ ) : (
+ <p>{msg.content}</p>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Input */}
+ <div className="px-3 py-2 border-t border-white/5">
+ <div className="flex gap-2">
+ <input
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleSend()}
+ placeholder={modelA && modelB ? 'Same prompt, two models...' : 'Select both models first'}
+ disabled={!modelA || !modelB || isStreaming}
+ className="flex-1 px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-[0.7rem] text-white placeholder-gray-500 focus:outline-none focus:border-white/25 disabled:opacity-40"
+ />
+ {isStreaming ? (
+ <button onClick={stopCompare} className="px-3 py-2 rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors">
+ <Square size={14} />
+ </button>
+ ) : (
+ <button
+ onClick={handleSend}
+ disabled={!input.trim() || !modelA || !modelB}
+ className="px-3 py-2 rounded-lg bg-white/10 text-white hover:bg-white/15 transition-colors disabled:opacity-30"
+ >
+ <Send size={14} />
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 274266b8..c67fcc1e 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -14,15 +14,21 @@ import { ErrorBoundary } from '../ui/ErrorBoundary'
import { useSettingsStore } from '../../stores/settingsStore'
import { FEATURE_FLAGS } from '../../lib/constants'
import { isAgentCompatible } from '../../lib/model-compatibility'
-import { FileText, Bot, User, ChevronDown } from 'lucide-react'
+import { FileText, Bot, User, ChevronDown, Download, GitCompareArrows } from 'lucide-react'
+import { TokenCounter } from './TokenCounter'
+import { ABCompare } from './ABCompare'
+import { useCompareStore } from '../../stores/compareStore'
+import { exportConversation } from '../../lib/chat-export'
export function ChatView() {
const { sendMessage, stopGeneration, isGenerating, isLoadingModel, pendingApproval, approveToolCall, rejectToolCall } = useChat()
const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const conversations = useChatStore((s) => s.conversations)
const activeModel = useModelStore((s) => s.activeModel)
const models = useModelStore((s) => s.models)
const [ragPanelOpen, setRagPanelOpen] = useState(false)
const [personaOpen, setPersonaOpen] = useState(false)
+ const [exportOpen, setExportOpen] = useState(false)
const { getActivePersona, setActivePersona } = useSettingsStore()
const activePersona = getActivePersona()
const allPersonas = useSettingsStore((s) => s.personas)
@@ -36,6 +42,13 @@ export function ChatView() {
const isAgentActive = useAgentModeStore((s) =>
activeConversationId ? s.agentModeActive[activeConversationId] ?? false : false
)
+ const isComparing = useCompareStore((s) => s.isComparing)
+ const setComparing = useCompareStore((s) => s.setComparing)
+
+ // A/B Compare mode takes over the entire view
+ if (isComparing) {
+ return <ABCompare />
+ }
return (
<div className="h-full flex flex-col min-w-0">
@@ -69,8 +82,42 @@ export function ChatView() {
transition={{ duration: 0.25, ease: 'easeOut' }}
>
<div className="flex-1 flex flex-col min-w-0">
- {/* Top bar: Documents + Agent Mode */}
+ {/* Top bar: Token Counter + Documents + Agent Mode */}
<div className="flex items-center justify-end gap-2 px-3 pt-1">
+ {/* Token Counter */}
+ <TokenCounter />
+
+ {/* Export */}
+ <div className="relative">
+ <button
+ onClick={() => setExportOpen(!exportOpen)}
+ className="flex items-center gap-1.5 px-3 py-1 rounded-full border border-gray-300 dark:border-white/15 hover:border-gray-400 dark:hover:border-white/25 text-gray-500 dark:text-gray-400 transition-colors text-xs"
+ title="Export chat"
+ >
+ <Download size={13} />
+ </button>
+ {exportOpen && (
+ <>
+ <div className="fixed inset-0 z-40" onClick={() => setExportOpen(false)} />
+ <div className="absolute right-0 top-full mt-1 z-50 w-36 rounded-lg bg-[#1a1a1a] border border-white/10 shadow-xl py-1">
+ {(['markdown', 'json'] as const).map(fmt => (
+ <button
+ key={fmt}
+ onClick={() => {
+ const conv = conversations.find(c => c.id === activeConversationId)
+ if (conv) exportConversation(conv, fmt)
+ setExportOpen(false)
+ }}
+ className="w-full text-left px-3 py-1.5 text-[0.65rem] text-gray-400 hover:bg-white/5 hover:text-gray-200 transition-colors"
+ >
+ Export as .{fmt === 'markdown' ? 'md' : fmt}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+
{/* Persona selector */}
<div className="relative">
<button
@@ -132,6 +179,16 @@ export function ChatView() {
)}
</button>
+ {/* A/B Compare */}
+ <button
+ onClick={() => setComparing(true)}
+ className="flex items-center gap-1.5 px-3 py-1 rounded-full border border-gray-300 dark:border-white/15 hover:border-gray-400 dark:hover:border-white/25 text-gray-500 dark:text-gray-400 transition-colors text-xs"
+ title="A/B Compare — test two models side by side"
+ >
+ <GitCompareArrows size={13} />
+ <span className="font-medium">A/B</span>
+ </button>
+
{/* Agent Mode (Beta) */}
{FEATURE_FLAGS.AGENT_MODE && (
<div className={
diff --git a/src/components/chat/MarkdownRenderer.tsx b/src/components/chat/MarkdownRenderer.tsx
index a752052a..6f3087f5 100644
--- a/src/components/chat/MarkdownRenderer.tsx
+++ b/src/components/chat/MarkdownRenderer.tsx
@@ -1,5 +1,8 @@
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
+import remarkMath from 'remark-math'
+import rehypeKatex from 'rehype-katex'
+import 'katex/dist/katex.min.css'
import { CodeBlock } from './CodeBlock'
import type { Components } from 'react-markdown'
@@ -72,7 +75,7 @@ const components: Components = {
export function MarkdownRenderer({ content }: Props) {
return (
<div className="markdown-content text-gray-800 dark:text-gray-200">
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkMath]} rehypePlugins={[rehypeKatex]} components={components}>
{content}
</ReactMarkdown>
</div>
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
new file mode 100644
index 00000000..80357046
--- /dev/null
+++ b/src/components/chat/TokenCounter.tsx
@@ -0,0 +1,51 @@
+import { useState, useEffect } from 'react'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { estimateTokens, getModelMaxTokens } from '../../lib/context-compaction'
+
+export function TokenCounter() {
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const conversations = useChatStore((s) => s.conversations)
+ const activeModel = useModelStore((s) => s.activeModel)
+ const [maxTokens, setMaxTokens] = useState<number>(4096)
+
+ const conversation = conversations.find((c) => c.id === activeConversationId)
+ const messages = conversation?.messages || []
+
+ // Estimate used tokens from all messages
+ const usedTokens = messages.reduce((sum, m) => {
+ let tokens = estimateTokens(m.content)
+ if (m.thinking) tokens += estimateTokens(m.thinking)
+ if (m.toolCallSummary) tokens += estimateTokens(m.toolCallSummary)
+ tokens += 4 // role overhead
+ return sum + tokens
+ }, 0)
+
+ // Fetch max tokens when model changes
+ useEffect(() => {
+ if (!activeModel) return
+ getModelMaxTokens(activeModel).then(setMaxTokens).catch(() => setMaxTokens(4096))
+ }, [activeModel])
+
+ if (!activeConversationId || messages.length === 0) return null
+
+ const ratio = maxTokens > 0 ? usedTokens / maxTokens : 0
+ const color = ratio > 0.8 ? 'text-red-400' : ratio > 0.5 ? 'text-amber-400' : 'text-gray-500'
+ const barColor = ratio > 0.8 ? 'bg-red-500' : ratio > 0.5 ? 'bg-amber-500' : 'bg-gray-500'
+
+ const formatK = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
+
+ return (
+ <div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={`Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens`}>
+ <div className="w-12 h-1 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all duration-300 ${barColor}`}
+ style={{ width: `${Math.min(ratio * 100, 100)}%` }}
+ />
+ </div>
+ <span className="text-[0.55rem] font-mono tabular-nums">
+ {formatK(usedTokens)}/{formatK(maxTokens)}
+ </span>
+ </div>
+ )
+}
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index c4b6e2a7..89d2eb01 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -11,6 +11,8 @@ import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useProviderStore } from '../../stores/providerStore'
import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'
+import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'
+import { ShortcutsModal } from './ShortcutsModal'
export function AppShell() {
const { currentView } = useUIStore()
@@ -20,6 +22,8 @@ export function AppShell() {
const [detectedBackends, setDetectedBackends] = useState<DetectedBackend[]>([])
const [showSelector, setShowSelector] = useState(false)
+ useKeyboardShortcuts()
+
useEffect(() => {
document.documentElement.classList.toggle('dark', settings.theme === 'dark')
document.documentElement.classList.toggle('light', settings.theme === 'light')
@@ -82,6 +86,7 @@ export function AppShell() {
backends={detectedBackends}
onClose={() => setShowSelector(false)}
/>
+ <ShortcutsModal />
</div>
)
}
diff --git a/src/components/layout/ShortcutsModal.tsx b/src/components/layout/ShortcutsModal.tsx
new file mode 100644
index 00000000..936cfb4e
--- /dev/null
+++ b/src/components/layout/ShortcutsModal.tsx
@@ -0,0 +1,28 @@
+import { useState, useEffect } from 'react'
+import { SHORTCUTS } from '../../hooks/useKeyboardShortcuts'
+import { Modal } from '../ui/Modal'
+
+export function ShortcutsModal() {
+ const [open, setOpen] = useState(false)
+
+ useEffect(() => {
+ const handler = () => setOpen(true)
+ window.addEventListener('lu-show-shortcuts', handler)
+ return () => window.removeEventListener('lu-show-shortcuts', handler)
+ }, [])
+
+ return (
+ <Modal open={open} onClose={() => setOpen(false)} title="Keyboard Shortcuts">
+ <div className="space-y-1.5">
+ {SHORTCUTS.map(s => (
+ <div key={s.keys} className="flex items-center justify-between py-1.5">
+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-300">{s.description}</span>
+ <kbd className="text-[0.6rem] font-mono px-2 py-0.5 rounded bg-gray-100 dark:bg-white/10 text-gray-800 dark:text-gray-200 border border-gray-200 dark:border-white/15">
+ {s.keys}
+ </kbd>
+ </div>
+ ))}
+ </div>
+ </Modal>
+ )
+}
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index 7ca1a981..b0a4b969 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -4,6 +4,7 @@ import { Download, RefreshCw, ExternalLink, Search, Info, CheckCircle, XCircle,
import { Pause, Play, X } from 'lucide-react'
import {
fetchAbliteratedModels, searchOllamaModels, getImageBundles, getVideoBundles,
+ getUncensoredTextModels, getMainstreamTextModels,
startModelDownload, getDownloadProgress, searchCivitaiModels,
pauseDownload, cancelDownload, resumeDownload,
type DiscoverModel, type DownloadProgress, type ModelBundle, type CivitAIModelResult,
@@ -88,6 +89,105 @@ function VariantPullButton({ model, pullModel, isPulling, isInstalled }: {
)
}
+function ModelDiscoverCard({ model, index, isText, getModelDownloadState, pullModel, isPulling, isInstalled, handleDownload }: {
+ model: DiscoverModel
+ index: number
+ isText: boolean
+ getModelDownloadState: (m: DiscoverModel) => DownloadProgress | null
+ pullModel: (name: string) => void
+ isPulling: boolean
+ isInstalled: (name: string) => boolean
+ handleDownload: (m: DiscoverModel) => void
+}) {
+ const dlState = getModelDownloadState(model)
+ const isDownloading = dlState?.status === 'downloading' || dlState?.status === 'connecting'
+ const isComplete = dlState?.status === 'complete'
+ const isError = dlState?.status === 'error'
+ const canDirectDownload = !!model.downloadUrl && !!model.filename && !!model.subfolder
+
+ return (
+ <motion.div
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ delay: index * 0.03 }}
+ >
+ <GlassCard className="p-3">
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1 min-w-0">
+ <h3 className="text-sm font-medium text-gray-900 dark:text-white truncate flex items-center gap-1.5">
+ {model.hot && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-500 font-bold border border-orange-500/30 shrink-0">HOT</span>}
+ {model.agent && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-green-500/15 text-green-500 font-bold border border-green-500/30 shrink-0">AGENT</span>}
+ <span className="truncate">{model.name}</span>
+ </h3>
+ {model.description && (
+ <p className="text-xs text-gray-500 mt-0.5">{model.description}</p>
+ )}
+ <div className="flex items-center gap-2 mt-1.5 flex-wrap">
+ {model.tags.map((tag) => (
+ <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/5 text-gray-600 dark:text-gray-400">
+ {tag}
+ </span>
+ ))}
+ {model.sizeGB && (
+ <span className="text-[10px] text-gray-400">{model.sizeGB} GB</span>
+ )}
+ {model.pulls && (
+ <span className="text-[10px] text-gray-500">{model.pulls}</span>
+ )}
+ </div>
+
+ {isDownloading && dlState && (
+ <div className="mt-2 space-y-1">
+ <ProgressBar progress={dlState.total > 0 ? (dlState.progress / dlState.total) * 100 : 0} />
+ <div className="flex items-center justify-between text-[10px] text-gray-400">
+ <span>{dlState.total > 0 ? `${formatBytes(dlState.progress)} / ${formatBytes(dlState.total)}` : 'Connecting...'}</span>
+ {dlState.speed > 0 && <span>{formatBytes(dlState.speed)}/s</span>}
+ </div>
+ </div>
+ )}
+ {isError && dlState && (
+ <div className="mt-1 flex items-center gap-1 text-[10px] text-red-500">
+ <XCircle size={10} /> {dlState.error || 'Download failed'}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 shrink-0">
+ {isText ? (
+ <VariantPullButton model={model} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} />
+ ) : (
+ <>
+ {isComplete ? (
+ <span className="flex items-center gap-1 text-xs text-green-500 px-2 py-1">
+ <CheckCircle size={12} /> Installed
+ </span>
+ ) : isDownloading ? (
+ <span className="p-2 text-gray-400">
+ <Loader2 size={14} className="animate-spin" />
+ </span>
+ ) : canDirectDownload ? (
+ <button
+ onClick={() => handleDownload(model)}
+ className="p-2 rounded-lg bg-green-100 dark:bg-green-500/15 hover:bg-green-200 dark:hover:bg-green-500/25 text-green-700 dark:text-green-400 transition-all"
+ title={`Download ${model.sizeGB ? model.sizeGB + ' GB' : ''} to ComfyUI`}
+ >
+ <Download size={14} />
+ </button>
+ ) : null}
+ {model.url && (
+ <a href={model.url} target="_blank" rel="noopener noreferrer" className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 transition-all" title="View on website">
+ <ExternalLink size={14} />
+ </a>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </GlassCard>
+ </motion.div>
+ )
+}
+
export function DiscoverModels({ category }: Props) {
const [textModels, setTextModels] = useState<DiscoverModel[]>([])
const [civitaiResults, setCivitaiResults] = useState<CivitAIModelResult[]>([])
@@ -98,6 +198,7 @@ export function DiscoverModels({ category }: Props) {
const [downloads, setDownloads] = useState<Record<string, DownloadProgress>>({})
const [downloadMeta, setDownloadMeta] = useState<Record<string, { url: string; subfolder: string }>>({})
const [systemVRAM, setSystemVRAM] = useState<number | null>(null)
+ const [textSubTab, setTextSubTab] = useState<'uncensored' | 'mainstream'>('uncensored')
const { pullModel, isPulling, pullProgress, models: installedModels } = useModels()
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
@@ -288,9 +389,19 @@ export function DiscoverModels({ category }: Props) {
setLoading(false)
}
- const title = isText ? 'Uncensored Text Models' : isImage ? 'Image Models (ComfyUI)' : 'Video Models (ComfyUI)'
+ 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
+
+ const title = isText ? 'Discover LUncensored' : isImage ? 'Image Models (ComfyUI)' : 'Video Models (ComfyUI)'
const subtitle = isText
- ? 'Search the Ollama registry or browse curated abliterated models.'
+ ? 'Search the Ollama registry or browse curated models.'
: isImage
? 'Complete packages — each bundle includes everything you need to generate images.'
: 'Complete packages — each bundle includes Model + VAE + CLIP for video generation.'
@@ -580,113 +691,79 @@ export function DiscoverModels({ category }: Props) {
</GlassCard>
)}
+ {/* Sub-tabs for text: Uncensored / Mainstream — section header style, clickable */}
+ {isText && (
+ <div className="flex gap-4 mb-4">
+ <button
+ onClick={() => setTextSubTab('uncensored')}
+ className={`flex items-center gap-2 transition-all ${
+ textSubTab === 'uncensored' ? 'opacity-100' : 'opacity-40 hover:opacity-70'
+ }`}
+ >
+ <div className={`w-1 h-5 rounded-full ${textSubTab === 'uncensored' ? 'bg-red-500' : 'bg-red-500/50'}`} />
+ <span className="text-[0.75rem] font-semibold text-gray-900 dark:text-white uppercase tracking-wider">Uncensored</span>
+ <span className="text-[0.55rem] text-gray-500">No filters, no limits</span>
+ </button>
+ <button
+ onClick={() => setTextSubTab('mainstream')}
+ className={`flex items-center gap-2 transition-all ${
+ textSubTab === 'mainstream' ? 'opacity-100' : 'opacity-40 hover:opacity-70'
+ }`}
+ >
+ <div className={`w-1 h-5 rounded-full ${textSubTab === 'mainstream' ? 'bg-blue-500' : 'bg-blue-500/50'}`} />
+ <span className="text-[0.75rem] font-semibold text-gray-900 dark:text-white uppercase tracking-wider">Mainstream</span>
+ <span className="text-[0.55rem] text-gray-500">Tool calling + vision</span>
+ </button>
+ </div>
+ )}
+
{loading ? (
<div className="text-center py-8 text-gray-500">Loading models...</div>
+ ) : isText ? (
+ <>
+ {/* Active sub-tab content */}
+ {textSubTab === 'uncensored' && (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {filteredUncensored.map((model, i) => (
+ <ModelDiscoverCard key={model.name} model={model} index={i} isText={isText} getModelDownloadState={getModelDownloadState} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} handleDownload={handleDownload} />
+ ))}
+ {filteredUncensored.length === 0 && (
+ <p className="text-center text-gray-500 py-4 col-span-2">No uncensored models match your search</p>
+ )}
+ </div>
+ )}
+ {textSubTab === 'mainstream' && (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {filteredMainstream.map((model, i) => (
+ <ModelDiscoverCard key={model.name} model={model} index={i} isText={isText} getModelDownloadState={getModelDownloadState} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} handleDownload={handleDownload} />
+ ))}
+ {filteredMainstream.length === 0 && (
+ <p className="text-center text-gray-500 py-4 col-span-2">No mainstream models match your search</p>
+ )}
+ </div>
+ )}
+
+ {/* Search Results (only when searching, show extra results not in curated lists) */}
+ {search && filtered.filter(m => !uncensoredModels.some(u => u.name === m.name) && !mainstreamModels.some(u => u.name === m.name)).length > 0 && (
+ <div className="space-y-3 mt-6">
+ <h3 className="text-[0.7rem] font-semibold text-gray-500 uppercase tracking-wider">Search Results</h3>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {filtered.filter(m => !uncensoredModels.some(u => u.name === m.name) && !mainstreamModels.some(u => u.name === m.name)).map((model, i) => (
+ <ModelDiscoverCard key={model.name} model={model} index={i} isText={isText} getModelDownloadState={getModelDownloadState} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} handleDownload={handleDownload} />
+ ))}
+ </div>
+ </div>
+ )}
+ </>
) : !isVideo && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {filtered.map((model, i) => {
- const dlState = getModelDownloadState(model)
- const isDownloading = dlState?.status === 'downloading' || dlState?.status === 'connecting'
- const isComplete = dlState?.status === 'complete'
- const isError = dlState?.status === 'error'
- const canDirectDownload = !!model.downloadUrl && !!model.filename && !!model.subfolder
-
- return (
- <motion.div
- key={model.name}
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: i * 0.03 }}
- >
- <GlassCard className="p-3">
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <h3 className="text-sm font-medium text-gray-900 dark:text-white truncate flex items-center gap-1.5">
- {model.hot && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-500 font-bold border border-orange-500/30 shrink-0">HOT</span>}
- {model.agent && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-green-500/15 text-green-500 font-bold border border-green-500/30 shrink-0">AGENT</span>}
- <span className="truncate">{model.name}</span>
- </h3>
- {model.description && (
- <p className="text-xs text-gray-500 mt-0.5">{model.description}</p>
- )}
- <div className="flex items-center gap-2 mt-1.5 flex-wrap">
- {model.tags.map((tag) => (
- <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/5 text-gray-600 dark:text-gray-400">
- {tag}
- </span>
- ))}
- {model.sizeGB && (
- <span className="text-[10px] text-gray-400">{model.sizeGB} GB</span>
- )}
- {model.pulls && (
- <span className="text-[10px] text-gray-500">{model.pulls}</span>
- )}
- </div>
-
- {/* Download progress inline */}
- {isDownloading && dlState && (
- <div className="mt-2 space-y-1">
- <ProgressBar progress={dlState.total > 0 ? (dlState.progress / dlState.total) * 100 : 0} />
- <div className="flex items-center justify-between text-[10px] text-gray-400">
- <span>{dlState.total > 0 ? `${formatBytes(dlState.progress)} / ${formatBytes(dlState.total)}` : 'Connecting...'}</span>
- {dlState.speed > 0 && <span>{formatBytes(dlState.speed)}/s</span>}
- </div>
- </div>
- )}
- {isError && dlState && (
- <div className="mt-1 flex items-center gap-1 text-[10px] text-red-500">
- <XCircle size={10} /> {dlState.error || 'Download failed'}
- </div>
- )}
- </div>
-
- <div className="flex items-center gap-1 shrink-0">
- {isText ? (
- // Ollama: variant selector for multi-size models
- <VariantPullButton model={model} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} />
- ) : (
- // ComfyUI models
- <>
- {isComplete ? (
- <span className="flex items-center gap-1 text-xs text-green-500 px-2 py-1">
- <CheckCircle size={12} /> Installed
- </span>
- ) : isDownloading ? (
- <span className="p-2 text-gray-400">
- <Loader2 size={14} className="animate-spin" />
- </span>
- ) : canDirectDownload ? (
- <button
- onClick={() => handleDownload(model)}
- className="p-2 rounded-lg bg-green-100 dark:bg-green-500/15 hover:bg-green-200 dark:hover:bg-green-500/25 text-green-700 dark:text-green-400 transition-all"
- title={`Download ${model.sizeGB ? model.sizeGB + ' GB' : ''} to ComfyUI`}
- >
- <Download size={14} />
- </button>
- ) : null}
- {model.url && (
- <a
- href={model.url}
- target="_blank"
- rel="noopener noreferrer"
- className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 transition-all"
- title="View on website"
- >
- <ExternalLink size={14} />
- </a>
- )}
- </>
- )}
- </div>
- </div>
- </GlassCard>
- </motion.div>
- )
- })}
+ {filtered.map((model, i) => (
+ <ModelDiscoverCard key={model.name} model={model} index={i} isText={false} getModelDownloadState={getModelDownloadState} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} handleDownload={handleDownload} />
+ ))}
</div>
)}
- {!loading && filtered.length === 0 && filteredBundles.length === 0 && (
+ {!loading && filtered.length === 0 && filteredBundles.length === 0 && filteredUncensored.length === 0 && filteredMainstream.length === 0 && (
<p className="text-center text-gray-500 py-4">No models found</p>
)}
</div>
diff --git a/src/components/models/ModelBenchmark.tsx b/src/components/models/ModelBenchmark.tsx
new file mode 100644
index 00000000..ce19d410
--- /dev/null
+++ b/src/components/models/ModelBenchmark.tsx
@@ -0,0 +1,93 @@
+import { useBenchmarkStore, getAverageSpeed, getLeaderboard } from '../../stores/benchmarkStore'
+import { useBenchmark } from '../../hooks/useBenchmark'
+import { Zap, Play, Square, Trophy } from 'lucide-react'
+
+interface Props {
+ modelName: string
+}
+
+export function BenchmarkButton({ modelName }: Props) {
+ const { runBenchmark, stopBenchmark } = useBenchmark()
+ const isRunning = useBenchmarkStore((s) => s.isRunning)
+ const currentModel = useBenchmarkStore((s) => s.currentModel)
+ const currentStep = useBenchmarkStore((s) => s.currentStep)
+ const totalSteps = useBenchmarkStore((s) => s.totalSteps)
+ const results = useBenchmarkStore((s) => s.results)
+ const avgSpeed = getAverageSpeed(results, modelName)
+
+ const isThisRunning = isRunning && currentModel === modelName
+
+ return (
+ <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`}>
+ <Zap size={9} />
+ {avgSpeed} t/s
+ </span>
+ )}
+ {isThisRunning ? (
+ <button
+ onClick={stopBenchmark}
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-red-500/15 text-red-400 text-[0.55rem] hover:bg-red-500/25 transition-colors"
+ title="Stop benchmark"
+ >
+ <Square size={9} />
+ {currentStep}/{totalSteps}
+ </button>
+ ) : (
+ <button
+ onClick={() => runBenchmark(modelName)}
+ disabled={isRunning}
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-white/5 text-gray-400 text-[0.55rem] hover:bg-white/10 hover:text-gray-300 transition-colors disabled:opacity-30"
+ title="Run benchmark"
+ >
+ <Play size={9} />
+ Bench
+ </button>
+ )}
+ </div>
+ )
+}
+
+export function BenchmarkLeaderboard() {
+ const results = useBenchmarkStore((s) => s.results)
+ const leaderboard = getLeaderboard(results)
+
+ if (leaderboard.length === 0) return null
+
+ return (
+ <div className="mt-4 p-3 rounded-lg bg-white/[0.03] border border-white/5">
+ <h3 className="text-[0.7rem] font-semibold text-amber-400 flex items-center gap-1.5 mb-2">
+ <Trophy size={12} />
+ Benchmark Leaderboard
+ </h3>
+ <div className="space-y-1.5">
+ {leaderboard.map((entry, i) => {
+ const maxTps = leaderboard[0].avgTps
+ const barWidth = maxTps > 0 ? (entry.avgTps / maxTps) * 100 : 0
+
+ return (
+ <div key={entry.model} className="flex items-center gap-2">
+ <span className="text-[0.6rem] text-gray-500 w-4 text-right font-mono">{i + 1}.</span>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between mb-0.5">
+ <span className="text-[0.6rem] text-gray-300 truncate">{entry.model}</span>
+ <span className="text-[0.55rem] text-gray-400 font-mono shrink-0 ml-2">{entry.avgTps} t/s</span>
+ </div>
+ <div className="w-full h-1 rounded-full bg-white/5 overflow-hidden">
+ <div
+ className="h-full rounded-full bg-gray-500/60 transition-all duration-500"
+ style={{ width: `${barWidth}%` }}
+ />
+ </div>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ <p className="text-[0.5rem] text-gray-600 mt-2">
+ {leaderboard.reduce((s, e) => s + e.runs, 0)} total runs across {leaderboard.length} models
+ </p>
+ </div>
+ )
+}
diff --git a/src/components/models/ModelCard.tsx b/src/components/models/ModelCard.tsx
index 181c8949..2da3419d 100644
--- a/src/components/models/ModelCard.tsx
+++ b/src/components/models/ModelCard.tsx
@@ -1,5 +1,6 @@
import { Trash2, Info, MessageSquare, Image, Video } from 'lucide-react'
import { formatBytes } from '../../lib/formatters'
+import { BenchmarkButton } from './ModelBenchmark'
import type { AIModel } from '../../types/models'
interface Props {
@@ -54,6 +55,13 @@ export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDele
</div>
</div>
+ {/* Benchmark (always visible for text models) */}
+ {model.type === 'text' && (
+ <div className="shrink-0" onClick={(e) => e.stopPropagation()}>
+ <BenchmarkButton modelName={model.name} />
+ </div>
+ )}
+
{/* Actions (visible on hover) */}
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<button
diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsx
index dc3dd418..58449365 100644
--- a/src/components/models/ModelManager.tsx
+++ b/src/components/models/ModelManager.tsx
@@ -7,6 +7,7 @@ import { useProviderStore } from '../../stores/providerStore'
import { ModelCard } from './ModelCard'
import { PullModelDialog } from './PullModelDialog'
import { DiscoverModels } from './DiscoverModels'
+import { BenchmarkLeaderboard } from './ModelBenchmark'
import { Modal } from '../ui/Modal'
import { GlowButton } from '../ui/GlowButton'
import { showModel } from '../../api/ollama'
@@ -162,7 +163,7 @@ export function ModelManager() {
: 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-white'
}`}
>
- Discover Uncensored
+ Discover LUncensored
</button>
</div>
@@ -212,6 +213,8 @@ export function ModelManager() {
))}
</div>
+ <BenchmarkLeaderboard />
+
{filteredModels.length === 0 && (
<div className="text-center py-10">
<p className="text-[0.7rem] text-gray-500 mb-3">
@@ -223,7 +226,7 @@ export function ModelManager() {
onClick={() => setTab('discover')}
className="px-3 py-1.5 rounded-lg bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 hover:bg-white/10 transition-colors"
>
- Discover uncensored models
+ Discover models
</button>
</div>
)}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 2ab1e565..66e1ca9e 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -247,6 +247,54 @@ export function SettingsPage() {
</Section>
)}
+ {/* ── Search Provider ────────────────────────── */}
+ {FEATURE_FLAGS.AGENT_MODE && (
+ <Section title="Search Provider">
+ <div className="space-y-3">
+ <div>
+ <span className="text-[0.6rem] text-gray-500 block mb-1">Provider for Agent web_search</span>
+ <div className="flex gap-1.5">
+ {(['auto', 'brave', 'tavily'] as const).map(p => (
+ <button
+ key={p}
+ onClick={() => updateSettings({ searchProvider: p })}
+ className={`px-2.5 py-1 rounded-md text-[0.6rem] font-medium transition-all ${
+ settings.searchProvider === p
+ ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm border border-gray-200 dark:border-white/15'
+ : 'text-gray-500 hover:text-gray-700 dark:hover:text-white bg-gray-100 dark:bg-white/5'
+ }`}
+ >
+ {p === 'auto' ? 'Auto (SearXNG > DDG)' : p === 'brave' ? 'Brave Search' : 'Tavily'}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div>
+ <label className="text-[0.6rem] text-gray-500 block mb-1">Brave Search API Key</label>
+ <input
+ type="password"
+ value={settings.braveApiKey}
+ onChange={(e) => updateSettings({ braveApiKey: e.target.value })}
+ placeholder="BSA-..."
+ className="w-full px-2.5 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-[0.65rem] text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-gray-400 dark:focus:border-white/25"
+ />
+ <span className="text-[0.5rem] text-gray-500 mt-0.5 block">Free tier: 2000 queries/month. Get key at brave.com/search/api</span>
+ </div>
+ <div>
+ <label className="text-[0.6rem] text-gray-500 block mb-1">Tavily API Key</label>
+ <input
+ type="password"
+ value={settings.tavilyApiKey}
+ onChange={(e) => updateSettings({ tavilyApiKey: e.target.value })}
+ placeholder="tvly-..."
+ className="w-full px-2.5 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-[0.65rem] text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-gray-400 dark:focus:border-white/25"
+ />
+ <span className="text-[0.5rem] text-gray-500 mt-0.5 block">AI-optimized search. Free tier: 1000 queries/month. Get key at tavily.com</span>
+ </div>
+ </div>
+ </Section>
+ )}
+
{/* ── Memory ─────────────────────────────────── */}
{FEATURE_FLAGS.AGENT_MODE && (
<Section title="Agent Memory">
diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.ts
new file mode 100644
index 00000000..5a302823
--- /dev/null
+++ b/src/hooks/useABCompare.ts
@@ -0,0 +1,114 @@
+/**
+ * A/B Compare Hook — sends the same prompt to two models in parallel.
+ */
+
+import { useCallback, useRef } from 'react'
+import { useCompareStore } from '../stores/compareStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { getProviderForModel } from '../api/providers'
+import { v4 as uuid } from 'uuid'
+import type { ChatMessage } from '../api/providers/types'
+import type { Message } from '../types/chat'
+
+export function useABCompare() {
+ const store = useCompareStore()
+ const settings = useSettingsStore((s) => s.settings)
+ const abortA = useRef<AbortController | null>(null)
+ const abortB = useRef<AbortController | null>(null)
+
+ const sendCompare = useCallback(async (text: string) => {
+ const { modelA, modelB } = useCompareStore.getState()
+ if (!modelA || !modelB || !text.trim()) return
+
+ const userMessage: Message = {
+ id: uuid(),
+ role: 'user',
+ content: text.trim(),
+ timestamp: Date.now(),
+ }
+
+ store.startRound(userMessage)
+
+ // Build messages for the providers
+ const persona = useSettingsStore.getState().getActivePersona()
+ const chatMessages: ChatMessage[] = []
+ if (persona?.prompt) {
+ chatMessages.push({ role: 'system', content: persona.prompt })
+ }
+
+ // Include previous messages for context
+ const prevMessages = useCompareStore.getState().messagesA.slice(0, -1) // exclude the empty assistant msg
+ for (const m of prevMessages) {
+ chatMessages.push({ role: m.role as 'user' | 'assistant', content: m.content })
+ }
+
+ const opts = {
+ temperature: settings.temperature,
+ topP: settings.topP,
+ topK: settings.topK,
+ maxTokens: settings.maxTokens || undefined,
+ }
+
+ // Stream Model A
+ abortA.current = new AbortController()
+ const streamA = async () => {
+ const startTime = Date.now()
+ let fullContent = ''
+ let tokenCount = 0
+ try {
+ const { provider, modelId } = getProviderForModel(modelA)
+ const stream = provider.chatStream(modelId, chatMessages, { ...opts, signal: abortA.current!.signal })
+ for await (const chunk of stream) {
+ if (chunk.content) {
+ fullContent += chunk.content
+ tokenCount++
+ useCompareStore.getState().addContentA(chunk.content)
+ }
+ }
+ } catch { /* aborted or error */ }
+ const elapsed = Date.now() - startTime
+ useCompareStore.getState().finishA(fullContent, {
+ tokens: tokenCount,
+ timeMs: elapsed,
+ tokensPerSec: elapsed > 0 ? (tokenCount / elapsed) * 1000 : 0,
+ })
+ }
+
+ // Stream Model B
+ abortB.current = new AbortController()
+ const streamB = async () => {
+ const startTime = Date.now()
+ let fullContent = ''
+ let tokenCount = 0
+ try {
+ const { provider, modelId } = getProviderForModel(modelB)
+ const stream = provider.chatStream(modelId, chatMessages, { ...opts, signal: abortB.current!.signal })
+ for await (const chunk of stream) {
+ if (chunk.content) {
+ fullContent += chunk.content
+ tokenCount++
+ useCompareStore.getState().addContentB(chunk.content)
+ }
+ }
+ } catch { /* aborted or error */ }
+ const elapsed = Date.now() - startTime
+ useCompareStore.getState().finishB(fullContent, {
+ tokens: tokenCount,
+ timeMs: elapsed,
+ tokensPerSec: elapsed > 0 ? (tokenCount / elapsed) * 1000 : 0,
+ })
+ }
+
+ // Run both in parallel
+ await Promise.all([streamA(), streamB()])
+ }, [settings, store])
+
+ const stopCompare = useCallback(() => {
+ abortA.current?.abort()
+ abortB.current?.abort()
+ store.setStreamingA(false)
+ store.setStreamingB(false)
+ }, [store])
+
+ return { sendCompare, stopCompare }
+}
diff --git a/src/hooks/useBenchmark.ts b/src/hooks/useBenchmark.ts
new file mode 100644
index 00000000..6e1fffda
--- /dev/null
+++ b/src/hooks/useBenchmark.ts
@@ -0,0 +1,75 @@
+/**
+ * Benchmark Runner — runs standardized prompts against a model and measures performance.
+ */
+
+import { useCallback, useRef } from 'react'
+import { useBenchmarkStore } from '../stores/benchmarkStore'
+import { getProviderForModel } from '../api/providers'
+import { BENCHMARK_PROMPTS } from '../lib/benchmark-prompts'
+import type { ChatMessage } from '../api/providers/types'
+
+export function useBenchmark() {
+ const store = useBenchmarkStore()
+ const abortRef = useRef<AbortController | null>(null)
+
+ const runBenchmark = useCallback(async (modelName: string) => {
+ if (store.isRunning) return
+
+ store.setRunning(true, modelName, BENCHMARK_PROMPTS.length)
+
+ for (let i = 0; i < BENCHMARK_PROMPTS.length; i++) {
+ const prompt = BENCHMARK_PROMPTS[i]
+ store.setStep(i + 1)
+
+ abortRef.current = new AbortController()
+
+ try {
+ const { provider, modelId } = getProviderForModel(modelName)
+ const messages: ChatMessage[] = [
+ { role: 'user', content: prompt.prompt },
+ ]
+
+ const startTime = performance.now()
+ let firstTokenTime = 0
+ let tokenCount = 0
+
+ const stream = provider.chatStream(modelId, messages, {
+ temperature: 0.7,
+ signal: abortRef.current.signal,
+ })
+
+ for await (const chunk of stream) {
+ if (chunk.content) {
+ if (tokenCount === 0) {
+ firstTokenTime = performance.now() - startTime
+ }
+ tokenCount++
+ }
+ }
+
+ const totalTime = performance.now() - startTime
+
+ store.addResult({
+ modelName,
+ promptId: prompt.id,
+ tokensPerSec: totalTime > 0 ? (tokenCount / totalTime) * 1000 : 0,
+ timeToFirstToken: firstTokenTime,
+ totalTime,
+ totalTokens: tokenCount,
+ timestamp: Date.now(),
+ })
+ } catch {
+ // Aborted or error — skip this prompt
+ }
+ }
+
+ store.setRunning(false)
+ }, [store])
+
+ const stopBenchmark = useCallback(() => {
+ abortRef.current?.abort()
+ store.setRunning(false)
+ }, [store])
+
+ return { runBenchmark, stopBenchmark }
+}
diff --git a/src/hooks/useKeyboardShortcuts.ts b/src/hooks/useKeyboardShortcuts.ts
new file mode 100644
index 00000000..fb75225b
--- /dev/null
+++ b/src/hooks/useKeyboardShortcuts.ts
@@ -0,0 +1,84 @@
+/**
+ * Global keyboard shortcuts.
+ *
+ * Ctrl+N — New conversation
+ * Ctrl+L — Focus chat input
+ * Ctrl+E — Export chat
+ * Ctrl+/ — Show shortcuts help
+ * Ctrl+Shift+D — Toggle dark/light mode
+ * Escape — Close any open panel/modal
+ */
+
+import { useEffect, useCallback } from 'react'
+import { useChatStore } from '../stores/chatStore'
+import { useModelStore } from '../stores/modelStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { useUIStore } from '../stores/uiStore'
+import { exportConversation } from '../lib/chat-export'
+
+export function useKeyboardShortcuts() {
+ const handleKeyDown = useCallback((e: KeyboardEvent) => {
+ const isCtrl = e.ctrlKey || e.metaKey
+ const isShift = e.shiftKey
+ const tag = (e.target as HTMLElement).tagName
+
+ // Don't interfere with input fields (except for Escape)
+ const inInput = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement).isContentEditable
+ if (inInput && e.key !== 'Escape') return
+
+ // Ctrl+N — New conversation
+ if (isCtrl && e.key === 'n') {
+ e.preventDefault()
+ const model = useModelStore.getState().activeModel
+ const persona = useSettingsStore.getState().getActivePersona()
+ if (model) {
+ useChatStore.getState().createConversation(model, persona?.prompt || '')
+ }
+ useUIStore.getState().setView('chat')
+ }
+
+ // Ctrl+L — Focus chat input
+ if (isCtrl && e.key === 'l') {
+ e.preventDefault()
+ const input = document.querySelector<HTMLTextAreaElement>('textarea[placeholder*="Message"]')
+ input?.focus()
+ }
+
+ // Ctrl+E — Export chat
+ if (isCtrl && e.key === 'e') {
+ e.preventDefault()
+ const state = useChatStore.getState()
+ const conv = state.conversations.find(c => c.id === state.activeConversationId)
+ if (conv) exportConversation(conv, 'markdown')
+ }
+
+ // Ctrl+Shift+D — Toggle theme
+ if (isCtrl && isShift && e.key === 'D') {
+ e.preventDefault()
+ const settings = useSettingsStore.getState().settings
+ useSettingsStore.getState().updateSettings({
+ theme: settings.theme === 'dark' ? 'light' : 'dark',
+ })
+ }
+
+ // Ctrl+/ — Show shortcuts help (dispatches custom event)
+ if (isCtrl && e.key === '/') {
+ e.preventDefault()
+ window.dispatchEvent(new CustomEvent('lu-show-shortcuts'))
+ }
+ }, [])
+
+ useEffect(() => {
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [handleKeyDown])
+}
+
+export const SHORTCUTS = [
+ { keys: 'Ctrl+N', description: 'New conversation' },
+ { keys: 'Ctrl+L', description: 'Focus chat input' },
+ { keys: 'Ctrl+E', description: 'Export chat as Markdown' },
+ { keys: 'Ctrl+Shift+D', description: 'Toggle dark/light mode' },
+ { keys: 'Ctrl+/', description: 'Show keyboard shortcuts' },
+ { keys: 'Escape', description: 'Close panel or modal' },
+]
diff --git a/src/lib/__tests__/chat-export.test.ts b/src/lib/__tests__/chat-export.test.ts
new file mode 100644
index 00000000..334716f5
--- /dev/null
+++ b/src/lib/__tests__/chat-export.test.ts
@@ -0,0 +1,85 @@
+/**
+ * Chat Export Tests
+ * Run: npx vitest run src/lib/__tests__/chat-export.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { exportAsMarkdown, exportAsJSON } from '../chat-export'
+import type { Conversation } from '../../types/chat'
+
+const mockConversation: Conversation = {
+ id: 'test-123',
+ title: 'Test Chat',
+ model: 'hermes3:8b',
+ systemPrompt: 'You are a helpful assistant.',
+ createdAt: 1712160000000,
+ updatedAt: 1712160000000,
+ messages: [
+ { id: 'm1', role: 'user', content: 'Hello!', timestamp: 1712160001000 },
+ { id: 'm2', role: 'assistant', content: 'Hi there!', timestamp: 1712160002000, thinking: 'User said hello, I should greet back.' },
+ { id: 'm3', role: 'user', content: 'What is 2+2?', timestamp: 1712160003000 },
+ { id: 'm4', role: 'assistant', content: 'The answer is 4.', timestamp: 1712160004000, toolCallSummary: 'calculator(2+2) = 4', sources: [{ documentName: 'math.pdf', chunkIndex: 0, preview: 'Basic arithmetic' }] },
+ ],
+}
+
+describe('exportAsMarkdown', () => {
+ it('includes title and model', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('# Test Chat')
+ expect(md).toContain('hermes3:8b')
+ })
+
+ it('includes system prompt', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('## System Prompt')
+ expect(md).toContain('You are a helpful assistant.')
+ })
+
+ it('includes all messages with roles', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('### You')
+ expect(md).toContain('### Assistant')
+ expect(md).toContain('Hello!')
+ expect(md).toContain('Hi there!')
+ expect(md).toContain('The answer is 4.')
+ })
+
+ it('includes thinking blocks', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('Thinking')
+ expect(md).toContain('User said hello')
+ })
+
+ it('includes tool call summaries', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('calculator(2+2) = 4')
+ })
+
+ it('includes RAG sources', () => {
+ const md = exportAsMarkdown(mockConversation)
+ expect(md).toContain('math.pdf')
+ })
+
+ it('handles conversation without system prompt', () => {
+ const conv = { ...mockConversation, systemPrompt: '' }
+ const md = exportAsMarkdown(conv)
+ expect(md).not.toContain('## System Prompt')
+ })
+})
+
+describe('exportAsJSON', () => {
+ it('returns valid JSON', () => {
+ const json = exportAsJSON(mockConversation)
+ const parsed = JSON.parse(json)
+ expect(parsed.id).toBe('test-123')
+ expect(parsed.messages).toHaveLength(4)
+ })
+
+ it('preserves all fields', () => {
+ const json = exportAsJSON(mockConversation)
+ const parsed = JSON.parse(json)
+ expect(parsed.title).toBe('Test Chat')
+ expect(parsed.model).toBe('hermes3:8b')
+ expect(parsed.messages[1].thinking).toBe('User said hello, I should greet back.')
+ expect(parsed.messages[3].sources).toHaveLength(1)
+ })
+})
diff --git a/src/lib/benchmark-prompts.ts b/src/lib/benchmark-prompts.ts
new file mode 100644
index 00000000..72818ec9
--- /dev/null
+++ b/src/lib/benchmark-prompts.ts
@@ -0,0 +1,45 @@
+/**
+ * Standardized benchmark prompts for local model testing.
+ */
+
+export interface BenchmarkPrompt {
+ id: string
+ name: string
+ category: 'speed' | 'reasoning' | 'code'
+ prompt: string
+ expectedMinTokens: number
+}
+
+export const BENCHMARK_PROMPTS: BenchmarkPrompt[] = [
+ {
+ id: 'speed',
+ name: 'Speed Test',
+ category: 'speed',
+ prompt: 'List the numbers from 1 to 50, each on a new line. Just the numbers, nothing else.',
+ expectedMinTokens: 50,
+ },
+ {
+ id: 'reasoning',
+ name: 'Reasoning',
+ category: 'reasoning',
+ prompt: 'A farmer has 17 sheep. All but 9 run away. How many sheep does the farmer have left? Explain your reasoning step by step.',
+ expectedMinTokens: 30,
+ },
+ {
+ id: 'code',
+ name: 'Code Generation',
+ category: 'code',
+ prompt: 'Write a Python function called `fibonacci` that returns the nth Fibonacci number using dynamic programming. Include a docstring.',
+ expectedMinTokens: 40,
+ },
+]
+
+export interface BenchmarkResult {
+ modelName: string
+ promptId: string
+ tokensPerSec: number
+ timeToFirstToken: number
+ totalTime: number
+ totalTokens: number
+ timestamp: number
+}
diff --git a/src/lib/chat-export.ts b/src/lib/chat-export.ts
new file mode 100644
index 00000000..a9c64b81
--- /dev/null
+++ b/src/lib/chat-export.ts
@@ -0,0 +1,84 @@
+/**
+ * Chat Export — Markdown and JSON formats.
+ */
+
+import type { Conversation } from '../types/chat'
+
+export function exportAsMarkdown(conversation: Conversation): string {
+ const lines: string[] = []
+ lines.push(`# ${conversation.title}`)
+ lines.push(`_Model: ${conversation.model} | ${new Date(conversation.createdAt).toLocaleString()}_`)
+ lines.push('')
+
+ if (conversation.systemPrompt) {
+ lines.push('## System Prompt')
+ lines.push(conversation.systemPrompt)
+ lines.push('')
+ }
+
+ lines.push('---')
+ lines.push('')
+
+ for (const msg of conversation.messages) {
+ const role = msg.role === 'user' ? 'You' : msg.role === 'assistant' ? 'Assistant' : msg.role
+ lines.push(`### ${role}`)
+
+ if (msg.thinking) {
+ lines.push('')
+ lines.push('<details><summary>Thinking</summary>')
+ lines.push('')
+ lines.push(msg.thinking)
+ lines.push('')
+ lines.push('</details>')
+ }
+
+ if (msg.toolCallSummary) {
+ lines.push('')
+ lines.push(`> Tool: ${msg.toolCallSummary}`)
+ }
+
+ lines.push('')
+ lines.push(msg.content)
+ lines.push('')
+
+ if (msg.sources && msg.sources.length > 0) {
+ lines.push('**Sources:**')
+ for (const src of msg.sources) {
+ lines.push(`- ${src.documentName} (chunk ${src.chunkIndex})`)
+ }
+ lines.push('')
+ }
+
+ lines.push('---')
+ lines.push('')
+ }
+
+ return lines.join('\n')
+}
+
+export function exportAsJSON(conversation: Conversation): string {
+ return JSON.stringify(conversation, null, 2)
+}
+
+export function downloadFile(content: string, filename: string, type: string) {
+ const blob = new Blob([content], { type })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+}
+
+export function exportConversation(conversation: Conversation, format: 'markdown' | 'json') {
+ const safeTitle = conversation.title.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 50)
+ if (format === 'markdown') {
+ const content = exportAsMarkdown(conversation)
+ downloadFile(content, `${safeTitle}.md`, 'text/markdown')
+ } else {
+ const content = exportAsJSON(conversation)
+ downloadFile(content, `${safeTitle}.json`, 'application/json')
+ }
+}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 3e25d492..3ed7c19f 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -13,6 +13,9 @@ export const DEFAULT_SETTINGS: Settings = {
maxTokens: 0,
theme: 'dark',
onboardingDone: false,
+ searchProvider: 'auto',
+ braveApiKey: '',
+ tavilyApiKey: '',
}
export const BUILT_IN_PERSONAS: Persona[] = [
diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.ts
index baafe806..7111ce6e 100644
--- a/src/lib/model-compatibility.ts
+++ b/src/lib/model-compatibility.ts
@@ -19,7 +19,7 @@ const AGENT_COMPATIBLE = [
'phi-4', 'phi4',
'deepseek-v2.5', 'deepseek-v3',
'glm4', 'glm-4',
- 'gemma3',
+ 'gemma3', 'gemma4',
'nemotron',
]
@@ -71,6 +71,7 @@ export function getRecommendedAgentModels(): RecommendedModel[] {
return [
{ name: 'hermes3:8b', label: 'Hermes 3 8B', reason: 'Uncensored + native tool calling. THE agent model.', hot: true, provider: 'ollama' },
{ name: 'hermes3:70b', label: 'Hermes 3 70B', reason: 'Maximum power uncensored agent. Needs 48GB+.', hot: true, provider: 'ollama' },
+ { name: 'gemma4:26b', label: 'Gemma 4 26B MoE', reason: '26B brain, runs like 4B. Native tools + vision. Apache 2.0.', hot: true, provider: 'ollama' },
{ name: 'qwen2.5:7b', label: 'Qwen 2.5 7B', reason: 'Fast, reliable tool calling', provider: 'ollama' },
{ name: 'llama3.1:8b', label: 'Llama 3.1 8B', reason: 'Proven tool calling all-rounder', provider: 'ollama' },
{ name: 'openai::gpt-4o', label: 'GPT-4o', reason: 'Cloud: powerful tool calling', provider: 'openai' },
diff --git a/src/lib/systemCheck.ts b/src/lib/systemCheck.ts
index 30f6729f..2fa49aef 100644
--- a/src/lib/systemCheck.ts
+++ b/src/lib/systemCheck.ts
@@ -96,6 +96,12 @@ export function getRecommendations(tier: SystemTier): ModelRecommendation[] {
description: 'Lightweight & capable',
reason: 'Fits your system well — needs little VRAM',
},
+ {
+ name: 'gemma4:e2b',
+ label: 'Gemma 4 E2B',
+ description: 'Vision + native tools',
+ reason: '2.3B model with vision and tool calling. Apache 2.0.',
+ },
{
name: 'mannix/llama3.1-8b-abliterated:q5_K_M',
label: 'Llama 3.1 8B',
@@ -111,6 +117,12 @@ export function getRecommendations(tier: SystemTier): ModelRecommendation[] {
description: 'Fast & reliable',
reason: 'Perfect for your system — recommended as a starting point',
},
+ {
+ name: 'gemma4:e4b',
+ label: 'Gemma 4 E4B',
+ description: 'Vision + native tools',
+ reason: 'Native tool calling + vision. 128K context. Apache 2.0.',
+ },
{
name: 'huihui_ai/qwen3-abliterated:8b',
label: 'Qwen3 8B',
@@ -126,6 +138,12 @@ export function getRecommendations(tier: SystemTier): ModelRecommendation[] {
]
case 'high':
return [
+ {
+ name: 'gemma4:26b',
+ label: 'Gemma 4 26B MoE',
+ description: '26B brain, runs like 4B',
+ reason: 'Mixture of Experts — only 3.8B active params. Vision + tools. 256K context.',
+ },
{
name: 'richardyoung/qwen3-14b-abliterated:q4_K_M',
label: 'Qwen3 14B',
diff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.ts
new file mode 100644
index 00000000..6bef9130
--- /dev/null
+++ b/src/stores/benchmarkStore.ts
@@ -0,0 +1,65 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import type { BenchmarkResult } from '../lib/benchmark-prompts'
+
+interface BenchmarkState {
+ results: Record<string, BenchmarkResult[]>
+ isRunning: boolean
+ currentModel: string | null
+ currentStep: number
+ totalSteps: number
+ addResult: (result: BenchmarkResult) => void
+ setRunning: (running: boolean, model?: string, total?: number) => void
+ setStep: (step: number) => void
+}
+
+export const useBenchmarkStore = create<BenchmarkState>()(
+ persist(
+ (set) => ({
+ results: {},
+ isRunning: false,
+ currentModel: null,
+ currentStep: 0,
+ totalSteps: 0,
+
+ addResult: (result) => set((s) => {
+ const existing = s.results[result.modelName] || []
+ return {
+ results: {
+ ...s.results,
+ [result.modelName]: [...existing, result],
+ },
+ }
+ }),
+
+ setRunning: (running, model, total) => set({
+ isRunning: running,
+ currentModel: model || null,
+ totalSteps: total || 0,
+ currentStep: 0,
+ }),
+
+ setStep: (step) => set({ currentStep: step }),
+ }),
+ { name: 'lu-benchmark-store' }
+ )
+)
+
+/** Get average speed for a model (standalone, not a store method) */
+export function getAverageSpeed(results: Record<string, BenchmarkResult[]>, modelName: string): number | null {
+ const runs = results[modelName]
+ if (!runs || runs.length === 0) return null
+ const avg = runs.reduce((sum, r) => sum + r.tokensPerSec, 0) / runs.length
+ return Math.round(avg * 10) / 10
+}
+
+/** Get leaderboard sorted by avg tokens/sec */
+export function getLeaderboard(results: Record<string, BenchmarkResult[]>): { model: string; avgTps: number; runs: number }[] {
+ return Object.entries(results)
+ .map(([model, runs]) => ({
+ model,
+ avgTps: Math.round((runs.reduce((s, r) => s + r.tokensPerSec, 0) / runs.length) * 10) / 10,
+ runs: runs.length,
+ }))
+ .sort((a, b) => b.avgTps - a.avgTps)
+}
diff --git a/src/stores/compareStore.ts b/src/stores/compareStore.ts
new file mode 100644
index 00000000..45965d76
--- /dev/null
+++ b/src/stores/compareStore.ts
@@ -0,0 +1,104 @@
+import { create } from 'zustand'
+import type { Message } from '../types/chat'
+
+interface ModelStats {
+ tokens: number
+ timeMs: number
+ tokensPerSec: number
+}
+
+interface CompareState {
+ isComparing: boolean
+ modelA: string
+ modelB: string
+ messagesA: Message[]
+ messagesB: Message[]
+ statsA: ModelStats | null
+ statsB: ModelStats | null
+ isStreamingA: boolean
+ isStreamingB: boolean
+ setComparing: (on: boolean) => void
+ setModelA: (name: string) => void
+ setModelB: (name: string) => void
+ addContentA: (content: string) => void
+ addContentB: (content: string) => void
+ startRound: (userMessage: Message) => void
+ finishA: (content: string, stats: ModelStats) => void
+ finishB: (content: string, stats: ModelStats) => void
+ setStreamingA: (on: boolean) => void
+ setStreamingB: (on: boolean) => void
+ reset: () => void
+}
+
+export const useCompareStore = create<CompareState>()((set) => ({
+ isComparing: false,
+ modelA: '',
+ modelB: '',
+ messagesA: [],
+ messagesB: [],
+ statsA: null,
+ statsB: null,
+ isStreamingA: false,
+ isStreamingB: false,
+
+ setComparing: (on) => set({ isComparing: on }),
+ setModelA: (name) => set({ modelA: name }),
+ setModelB: (name) => set({ modelB: name }),
+
+ addContentA: (content) => set((s) => {
+ const msgs = [...s.messagesA]
+ const last = msgs[msgs.length - 1]
+ if (last && last.role === 'assistant') {
+ msgs[msgs.length - 1] = { ...last, content: last.content + content }
+ }
+ return { messagesA: msgs }
+ }),
+
+ addContentB: (content) => set((s) => {
+ const msgs = [...s.messagesB]
+ const last = msgs[msgs.length - 1]
+ if (last && last.role === 'assistant') {
+ msgs[msgs.length - 1] = { ...last, content: last.content + content }
+ }
+ return { messagesB: msgs }
+ }),
+
+ startRound: (userMessage) => set((s) => ({
+ messagesA: [...s.messagesA, userMessage, { id: `a-${Date.now()}`, role: 'assistant', content: '', timestamp: Date.now() }],
+ messagesB: [...s.messagesB, userMessage, { id: `b-${Date.now()}`, role: 'assistant', content: '', timestamp: Date.now() }],
+ statsA: null,
+ statsB: null,
+ isStreamingA: true,
+ isStreamingB: true,
+ })),
+
+ finishA: (content, stats) => set((s) => {
+ const msgs = [...s.messagesA]
+ const last = msgs[msgs.length - 1]
+ if (last && last.role === 'assistant') {
+ msgs[msgs.length - 1] = { ...last, content }
+ }
+ return { messagesA: msgs, statsA: stats, isStreamingA: false }
+ }),
+
+ finishB: (content, stats) => set((s) => {
+ const msgs = [...s.messagesB]
+ const last = msgs[msgs.length - 1]
+ if (last && last.role === 'assistant') {
+ msgs[msgs.length - 1] = { ...last, content }
+ }
+ return { messagesB: msgs, statsB: stats, isStreamingB: false }
+ }),
+
+ setStreamingA: (on) => set({ isStreamingA: on }),
+ setStreamingB: (on) => set({ isStreamingB: on }),
+
+ reset: () => set({
+ messagesA: [],
+ messagesB: [],
+ statsA: null,
+ statsB: null,
+ isStreamingA: false,
+ isStreamingB: false,
+ }),
+}))
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 36cfb122..a9aa800f 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -1,3 +1,5 @@
+export type SearchProvider = 'auto' | 'brave' | 'tavily'
+
export interface Settings {
apiEndpoint: string
temperature: number
@@ -6,6 +8,9 @@ export interface Settings {
maxTokens: number
theme: 'light' | 'dark'
onboardingDone: boolean
+ searchProvider: SearchProvider
+ braveApiKey: string
+ tavilyApiKey: string
}
export interface Persona {
diff --git a/vite.config.ts b/vite.config.ts
index a321ea61..f639a9f7 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -975,14 +975,14 @@ function comfyLauncher(): Plugin {
})()
})
- // API: Multi-tier web search (SearXNG > DDG Instant Answer API > Wikipedia)
+ // API: Multi-tier web search (Brave/Tavily > SearXNG > DDG > Wikipedia)
server.middlewares.use('/local-api/web-search', (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
let body = ''
req.on('data', (c: any) => { body += c })
req.on('end', () => {
try {
- const { query, count } = JSON.parse(body)
+ const { query, count, provider, braveApiKey, tavilyApiKey } = JSON.parse(body)
if (!query) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing query parameter' }))
@@ -1108,6 +1108,67 @@ function comfyLauncher(): Plugin {
})
}
+ // Tier: Brave Search API (needs API key)
+ const tryBrave = (): Promise<{ title: string; url: string; snippet: string }[]> => {
+ if (!braveApiKey) return Promise.reject(new Error('No Brave API key'))
+ const braveUrl = 'https://api.search.brave.com/res/v1/web/search?q=' + encodeURIComponent(query) + '&count=' + maxResults
+ return new Promise((resolve, reject) => {
+ const httpReq = https.get(braveUrl, {
+ headers: { 'Accept': 'application/json', 'Accept-Encoding': 'gzip', 'X-Subscription-Token': braveApiKey },
+ timeout: 8000,
+ }, (response) => {
+ if (response.statusCode !== 200) { response.resume(); reject(new Error('Brave HTTP ' + response.statusCode)); return }
+ let data = ''
+ response.on('data', (chunk: Buffer) => { data += chunk.toString() })
+ response.on('end', () => {
+ try {
+ const parsed = JSON.parse(data)
+ const results = (parsed.web?.results || []).slice(0, maxResults).map((r: any) => ({
+ title: r.title || '', url: r.url || '', snippet: r.description || '',
+ }))
+ if (results.length === 0) throw new Error('Brave returned no results')
+ console.log('[WebSearch] Brave returned ' + results.length + ' results')
+ resolve(results)
+ } catch (e) { reject(e) }
+ })
+ })
+ httpReq.on('error', reject)
+ httpReq.on('timeout', () => { httpReq.destroy(); reject(new Error('Brave timeout')) })
+ })
+ }
+
+ // Tier: Tavily Search API (needs API key, optimized for AI agents)
+ const tryTavily = (): Promise<{ title: string; url: string; snippet: string }[]> => {
+ if (!tavilyApiKey) return Promise.reject(new Error('No Tavily API key'))
+ return new Promise((resolve, reject) => {
+ const postData = JSON.stringify({ api_key: tavilyApiKey, query, max_results: maxResults, search_depth: 'basic' })
+ const httpReq = https.request({
+ hostname: 'api.tavily.com', path: '/search', method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) },
+ timeout: 10000,
+ }, (response) => {
+ if (response.statusCode !== 200) { response.resume(); reject(new Error('Tavily HTTP ' + response.statusCode)); return }
+ let data = ''
+ response.on('data', (chunk: Buffer) => { data += chunk.toString() })
+ response.on('end', () => {
+ try {
+ const parsed = JSON.parse(data)
+ const results = (parsed.results || []).slice(0, maxResults).map((r: any) => ({
+ title: r.title || '', url: r.url || '', snippet: r.content || '',
+ }))
+ if (results.length === 0) throw new Error('Tavily returned no results')
+ console.log('[WebSearch] Tavily returned ' + results.length + ' results')
+ resolve(results)
+ } catch (e) { reject(e) }
+ })
+ })
+ httpReq.on('error', reject)
+ httpReq.on('timeout', () => { httpReq.destroy(); reject(new Error('Tavily timeout')) })
+ httpReq.write(postData)
+ httpReq.end()
+ })
+ }
+
// Tier 3: Wikipedia API (always works)
const tryWikipedia = (): Promise<{ title: string; url: string; snippet: string }[]> => {
const wikiUrl = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + encodeURIComponent(query) + '&format=json&srlimit=' + maxResults + '&utf8=1'
@@ -1124,10 +1185,18 @@ function comfyLauncher(): Plugin {
})
}
- // Execute tiers in order
- trySearXNG()
- .catch(() => tryDDGHTML())
- .catch(() => tryWikipedia())
+ // Execute tiers based on provider setting
+ const searchChain = (): Promise<{ title: string; url: string; snippet: string }[]> => {
+ if (provider === 'brave') return tryBrave().catch(() => trySearXNG()).catch(() => tryDDGHTML()).catch(() => tryWikipedia())
+ if (provider === 'tavily') return tryTavily().catch(() => trySearXNG()).catch(() => tryDDGHTML()).catch(() => tryWikipedia())
+ // 'auto': SearXNG > Brave (if key) > Tavily (if key) > DDG > Wikipedia
+ return trySearXNG()
+ .catch(() => braveApiKey ? tryBrave() : Promise.reject(new Error('no brave key')))
+ .catch(() => tavilyApiKey ? tryTavily() : Promise.reject(new Error('no tavily key')))
+ .catch(() => tryDDGHTML())
+ .catch(() => tryWikipedia())
+ }
+ searchChain()
.then((results) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ results }))