The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat: add RAG document chat, Voice STT/TTS, AI Agents
PurpleDoubleDda90b59341ee
diff --git a/MARKET_RESEARCH_2026-03-31.md b/MARKET_RESEARCH_2026-03-31.mdnew file mode 100644index 00000000..d2e9a224--- /dev/null+++ b/MARKET_RESEARCH_2026-03-31.md@@ -0,0 +1,115 @@+# Locally Uncensored - Market Research (31.03.2026)++Quellen: Reddit (r/LocalLLaMA, r/selfhosted, r/comfyui, r/OpenWebUI), YouTube Kommentare (David Bombal, Tier List Videos), GitHub Issues (Open WebUI, Jan.ai, SillyTavern, AnythingLLM), Hacker News++## Die 7 groessten Pain Points der User++### 1. ALLES IST ZU KOMPLIZIERT+- "Local AI in 2026 feels like Linux in 2005. Powerful but only usable by enthusiasts. We need the Ubuntu moment." (4.1k Likes, YouTube)+- "Followed every step and got CUDA errors. Spent 3 hours on Stack Overflow. Local AI is not for normal people yet." (2.1k Likes)+- "Why does every local AI project insist on Docker? Regular people don't know what Docker is" (2.8k Likes)+- LU Vorteil: Portable Mode, kein Docker, kein Terminal noetig++### 2. OPEN WEBUI IST AUFGEBLASEN+- Docker Image von 2GB auf 8GB gewachsen+- Updates breaken staendig bestehende Setups+- 4GB+ RAM nur fuer die Web UI+- "I miss when this was just 'ollama-webui' and it did one thing well"+- "Every time I update, something breaks. I've stopped updating."+- Leute wechseln aktiv zu Msty, LM Studio, Chatbox+- LU Chance: Leichtgewichtige Alternative die einfach funktioniert++### 3. JEDER WILL EIN ALL-IN-ONE TOOL+- Meistgelikter YouTube Kommentar (4.5k Likes): "My ideal tool: one installer, bundles Ollama, clean chat UI, built-in RAG, Stable Diffusion, voice. All configurable through GUI. No terminal."+- "My dream: Ollama + automatic model updates + built-in GUI + RAG + image gen. One app." (2.7k Likes)+- "I just want ONE tool that handles text gen, image gen, voice, and RAG without needing a PhD in DevOps"+- "Someone needs to make the 'Spotify of local AI'"+- LU ist das EINZIGE Tool das Text + Image + Video in einer App vereint++### 4. COMFYUI UX IST HORROR+- "I tried to help my artist friend get started and they literally cried." (r/comfyui)+- "ComfyUI getting an F tier for UX is generous honestly" (2.1k Likes)+- "I have 47 custom nodes installed and I'm afraid to update any of them"+- Custom Nodes breaken bei jedem Update, keine Fehlermeldungen+- LU Vorteil: One-Click ComfyUI Setup Wizard abstrahiert die Komplexitaet++### 5. RAG FUNKTIONIERT NIRGENDS GUT+- "Tried to set up a RAG pipeline with local models. Gave up after 2 days. Went back to ChatGPT."+- "Been running local LLMs for a year. Still can't get reliable RAG working."+- "LlamaIndex, LangChain, Haystack... they all work great in demos and fall apart with real documents."+- Wer RAG als erstes sauber loest in einem All-in-One Tool, gewinnt++### 6. LEUTE WOLLEN LOCAL AI AGENTS+- "Please do a video on running AI agents locally. That's the next frontier but there's zero good tools for it" (1.3k Likes)+- "Local AI agents that can actually DO things - browse the web, manage files, write and execute code"+- "Local agents are going to be the next big thing but right now every 'agent framework' is just prompt chaining with extra steps"+- Noch NIEMAND hat das sauber geloest++### 7. LEUTE WUERDEN ZAHLEN+- "I'd pay $50/month for a properly maintained, all-in-one local AI platform that just works." (Reddit r/LocalLLaMA)+- "The 'free but broken' options are costing me more in time."+- Zahlungsbereitschaft existiert, besonders bei Leuten die Zeit > Geld werten++---++## Konkurrenz-Schwaechen++### Open WebUI+- Bloated (8GB Docker Image)+- Updates breaken alles+- Feature Creep - versucht alles, macht nichts gut+- Docker-Pflicht+- Kein nativer Desktop Client+- Top GitHub Issues: Chat-Ordner (#1438), Multi-Model Vergleich (#5765), MCP Support (#8828), Performance (#9563)++### Jan.ai+- Langsame Entwicklung+- Linux-Stabilitaet schlecht+- Kein Image/Video Gen++### LM Studio+- Closed Source+- Nur Model Management + Chat, keine Image Gen+- Kein RAG++### SillyTavern+- Nische (Roleplay/Creative)+- Komplexe Einrichtung+- Kein Image Gen Integration++### AnythingLLM+- RAG-fokussiert aber UI veraltet+- Keine Image/Video Gen++---++## Feature-Roadmap Empfehlung (nach User-Demand sortiert)++### Phase 1 - Sofort umsetzbar (USP staerken)+- [ ] GitHub Sponsors + Donation Links einrichten+- [ ] "Pro" Roadmap im README andeuten+- [ ] Model Router (automatisch bestes Model pro Task waehlen)++### Phase 2 - Hohes Demand (naechste 1-3 Monate)+- [ ] RAG / Document Chat (DER meistgeforderte Feature)+- [ ] Mobile App (verbindet sich zum Home-Server)+- [ ] Voice Integration (STT + TTS lokal)+- [ ] Besseres Model Management (Vergleich, Benchmarks, Notizen)++### Phase 3 - Differenzierung (3-6 Monate)+- [ ] Local AI Agents (File Management, Code Execution, Web Browse)+- [ ] Fine-Tuning GUI fuer Non-Experts+- [ ] Plugin/Extension System+- [ ] Enterprise Features (Multi-User, Admin, Usage Tracking)++### Monetarisierung+- Freemium: Basis kostenlos, Pro-Features ($9-29/mo oder Einmalzahlung)+- Pro Candidates: RAG, Agents, Fine-Tuning GUI, Cloud Sync, Model Router, Priority Support+- Enterprise: Multi-User, Admin Panel, SSO, Usage Analytics++---++## Killer-Zitat fuer Marketing+"My ideal tool: one installer, bundles Ollama, clean chat UI, built-in RAG, Stable Diffusion, voice. All configurable through GUI. No terminal. Someone build this please." - YouTube User (4.5k Likes)++Das beschreibt GENAU was Locally Uncensored werden soll.diff --git a/PROMOTION_PLAN.md b/PROMOTION_PLAN.mdnew file mode 100644index 00000000..139c1a56--- /dev/null+++ b/PROMOTION_PLAN.md@@ -0,0 +1,90 @@+# Locally Uncensored - Promotion Plan (31.03.2026)++## Research Summary++### Unique Selling Point+LU is the ONLY tool that combines Ollama LLM chat + ComfyUI image/video gen in one desktop app with portable mode. No competitor does this. That's the pitch.++### What worked for competitors+- r/LocalLLaMA is THE launchpad for every local AI tool+- HN front page = thousands of stars overnight+- YouTube tutorials are massive growth drivers+- "Censorship events" on cloud platforms drive waves of users to local tools+- Easy install (one-click/portable) is the #1 adoption driver+- SillyTavern grew every time CharacterAI added restrictions++---++## ACTION PLAN (Priority Order)++### TIER 1 - Highest Impact++#### 1. YouTuber Outreach+Target channels that review local AI tools:+- **Zen van Riel** - "Ultimate Local AI Tier List 2026" (26k views, 2 weeks ago). Makes tool tier lists. PERFECT fit.+- **David Bombal** - "Private & Uncensored Local LLMs" (592k views). Verified, huge audience.+- **Fireship** - "7 new open source AI tools" (742k views, 2 weeks ago). Massive reach but harder to get.+- **Alex Ziskind** - "Llama.cpp vs Ollama" (215k views). Verified, does tool comparisons.+- **NetworkChuck** - Local AI content, massive subscriber base+- **Matt Wolfe** - Runs futuretools.io, covers AI tools on YouTube+- **SuccessPursuitZone** - "How to run uncensored AI locally" (72k views)+- **Josiah Golden** - "How to Run Private Uncensored AI" (50k views)+- **Savage Reviews** - Multiple Ollama comparison videos (70k+ views)+- **The West Reviews** - Smaller but niche local AI content++**Approach**: Short email/DM: "Hey, built an open source app that combines Ollama + ComfyUI in one desktop app. Portable mode, no install needed. Might be interesting for your audience. Here's the repo: [link]"++#### 2. AI Tool Directories (submit to all)+- AlternativeTo (alternative to ChatGPT, Midjourney)+- There Is An AI For That (theresanaiforthat.com)+- Futurepedia+- Future Tools (futuretools.io)+- Toolify.ai+- TopAI.tools+- SaaSHub+- OpenSourceAlternative.to++#### 3. Community Posts+- Ollama Discord (showcase channel)+- ComfyUI Discord+- r/LocalLLaMA (if not already posted)+- r/comfyui+- r/privacy / r/degoogle (privacy angle)++### TIER 2 - Medium Impact++#### 4. Software Directories+- SourceForge project page+- Fosshub+- Flathub (Linux AppImage already exists)+- G2, Capterra (credibility)++#### 5. Content+- Dev.to launch article+- Blog post: "How I built an all-in-one local AI app"++#### 6. Product Hunt Launch+- Prepare proper assets, schedule for Tuesday-Thursday++### TIER 3 - Long-term++#### 7. SEO Content+- Target "best ollama gui", "local ai app", "uncensored ai tool"+- Comparison pages already exist, keep updating++---++## EXECUTION STATUS++- [ ] YouTuber outreach emails drafted and sent+- [ ] AlternativeTo listing+- [ ] TIAFT listing+- [ ] Futurepedia listing+- [ ] Future Tools listing+- [ ] Toolify listing+- [ ] OpenSourceAlternative.to listing+- [ ] SaaSHub listing+- [ ] Ollama Discord post+- [ ] ComfyUI Discord post+- [ ] Product Hunt prep+- [ ] HN Show HN (scheduled 14:30 today)diff --git a/docs/blog/best-local-ai-apps-2026.html b/docs/blog/best-local-ai-apps-2026.htmlindex 7d20385f..c544b8df 100644--- a/docs/blog/best-local-ai-apps-2026.html+++ b/docs/blog/best-local-ai-apps-2026.html@@ -4,8 +4,8 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Best Local AI Apps in 2026 — Run AI on Your Own Hardware</title>-<meta name="description" content="The best local AI desktop apps in 2026 for running LLMs, image generation, and video generation on your own hardware. Honest comparison of GPT4All, Open WebUI, LM Studio, Locally Uncensored, Jan, Kobold.cpp, SillyTavern, and Msty.">-<meta name="keywords" content="best local ai apps 2026, run ai locally, local llm apps, ollama frontend, best ai desktop app, local ai chat, local image generation, gpt4all alternative, open webui alternative, lm studio alternative, privacy ai">+<meta name="description" content="The best local AI desktop apps in 2026 for running LLMs, image generation, and video generation on your own hardware. Honest comparison of GPT4All, Open WebUI, LM Studio, Locally Uncensored, Jan, Kobold.cpp, SillyTavern, text-generation-webui, and Msty.">+<meta name="keywords" content="best local ai apps 2026, run ai locally, local llm apps, ollama frontend, best ai desktop app, local ai chat, local image generation, gpt4all alternative, open webui alternative, lm studio alternative, text-generation-webui, oobabooga, privacy ai"><meta property="og:title" content="Best Local AI Apps in 2026 — Run AI on Your Own Hardware"><meta property="og:description" content="Complete comparison of the best local AI desktop apps for running LLMs, generating images, and creating videos on your own hardware in 2026."><meta property="og:url" content="https://purpledoubled.github.io/locally-uncensored/blog/best-local-ai-apps-2026.html">@@ -72,6 +72,7 @@ ul{margin:12px 0 16px 24px;color:#ccc}li{margin-bottom:8px;font-size:15px}<tr><td>Jan.ai</td><td><span class="check">Yes</span></td><td><span class="cross">No</span></td><td><span class="cross">No</span></td><td>AGPL v3</td><td>Electron</td></tr><tr><td>Kobold.cpp</td><td><span class="check">Yes</span></td><td><span class="check">Basic</span></td><td><span class="cross">No</span></td><td>AGPL v3</td><td>Web</td></tr><tr><td>SillyTavern</td><td><span class="check">Yes</span></td><td><span class="cross">No</span></td><td><span class="cross">No</span></td><td>AGPL v3</td><td>Web (Node)</td></tr>+<tr><td>text-generation-webui</td><td><span class="check">Yes</span></td><td><span class="check">Yes</span></td><td><span class="cross">No</span></td><td>AGPL v3</td><td>Web (Gradio)</td></tr><tr><td>Msty</td><td><span class="check">Yes</span></td><td><span class="cross">No</span></td><td><span class="cross">No</span></td><td>Proprietary</td><td>Electron</td></tr></tbody></table>@@ -133,7 +134,15 @@ ul{margin:12px 0 16px 24px;color:#ccc}li{margin-bottom:8px;font-size:15px}</div><div class="app-card">-<h3>8. Msty — Best Multi-Provider Hub</h3>+<h3>8. text-generation-webui (oobabooga) — Best for Advanced Users</h3>+<span class="tag">LLM Chat</span><span class="tag">Image Gen</span><span class="tag">Training</span><span class="tag">Extensions</span><span class="tag">AGPL v3</span>+<p style="margin-top:12px">Also known as "oobabooga," text-generation-webui is the Swiss Army knife of local AI tools. It is a Gradio-based web UI that supports virtually every model format (GGUF, GPTQ, AWQ, EXL2, HQQ) and every inference backend (llama.cpp, ExLlamaV2, Transformers, AutoGPTQ). It also supports image generation via stable-diffusion-webui integration and has an extension system for LoRA training, multimodal input, and more. The tradeoff is complexity -- setup and configuration require more technical knowledge than any other app on this list.</p>+<p><strong>Best for:</strong> Advanced users who want maximum flexibility, multi-backend support, and fine-tuning capabilities.</p>+<p><a href="https://github.com/oobabooga/text-generation-webui">GitHub</a></p>+</div>++<div class="app-card">+<h3>9. Msty — Best Multi-Provider Hub</h3><span class="tag">LLM Chat</span><span class="tag">Knowledge Stacks</span><span class="tag">Multi-Provider</span><span class="tag">Proprietary</span><p style="margin-top:12px">Msty connects to the most AI providers of any desktop app: Ollama, LM Studio, OpenAI, Anthropic, Google, Mistral, and more. Knowledge Stacks let you chat with documents, and side-by-side comparison helps evaluate models. The catch: it is proprietary with some features behind a paywall.</p><p><strong>Best for:</strong> Power users who work across many AI providers and want one unified interface.</p>diff --git a/docs/blog/locally-uncensored-vs-jan.html b/docs/blog/locally-uncensored-vs-jan.htmlindex 11a5a1ef..9b2dddde 100644--- a/docs/blog/locally-uncensored-vs-jan.html+++ b/docs/blog/locally-uncensored-vs-jan.html@@ -4,17 +4,20 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Locally Uncensored vs Jan.ai — Which Local AI App Is Better?</title>-<meta name="description" content="Locally Uncensored vs Jan.ai comparison. Which local AI desktop app gives you more features? Text, image, and video generation vs polished chat interface.">-<meta name="keywords" content="locally uncensored vs jan, jan.ai alternative, local ai app, ollama desktop app, jan ai alternative, best local ai chat">+<meta name="description" content="Locally Uncensored vs Jan.ai comparison. Which local AI desktop app gives you more features? Text, image, and video generation vs polished chat interface with cloud API support.">+<meta name="keywords" content="locally uncensored vs jan, jan.ai alternative, local ai app, ollama desktop app, jan ai alternative, best local ai chat, jan ai comparison"><meta property="og:title" content="Locally Uncensored vs Jan.ai — Which Local AI App Is Better?">-<meta property="og:description" content="Locally Uncensored vs Jan.ai comparison. Which local AI desktop app gives you more features? Text, image, and video generation vs polished chat interface.">+<meta property="og:description" content="Locally Uncensored vs Jan.ai comparison. Which local AI desktop app gives you more features? Text, image, and video generation vs polished chat interface with cloud API support."><meta property="og:url" content="https://purpledoubled.github.io/locally-uncensored/blog/locally-uncensored-vs-jan.html"><meta property="og:type" content="article"><link rel="canonical" href="https://purpledoubled.github.io/locally-uncensored/blog/locally-uncensored-vs-jan.html"><meta name="robots" content="index, follow"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><script type="application/ld+json">-{"@context":"https://schema.org","@type":"Article","headline":"Locally Uncensored vs Jan.ai","author":{"@type":"Person","name":"PurpleDoubleD"},"datePublished":"2026-03-30","publisher":{"@type":"Organization","name":"Locally Uncensored"}}+{"@context":"https://schema.org","@type":"Article","headline":"Locally Uncensored vs Jan.ai — Which Local AI App Is Better?","author":{"@type":"Person","name":"PurpleDoubleD"},"datePublished":"2026-03-30","publisher":{"@type":"Organization","name":"Locally Uncensored"}}+</script>+<script type="application/ld+json">+{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Is Locally Uncensored better than Jan.ai?","acceptedAnswer":{"@type":"Answer","text":"It depends on your priorities. Locally Uncensored is better if you want text chat, image generation, and video generation in one app with a permissive MIT license. Jan.ai is better if you need cloud API support alongside local models and prefer a polished ChatGPT-like interface."}},{"@type":"Question","name":"Does Jan.ai support image generation?","acceptedAnswer":{"@type":"Answer","text":"No. Jan.ai focuses on text-based LLM chat and cloud API integration. For local image and video generation, you need a tool like Locally Uncensored which integrates ComfyUI for Stable Diffusion, FLUX, and Wan 2.1 support."}},{"@type":"Question","name":"Is Jan.ai open source?","acceptedAnswer":{"@type":"Answer","text":"Jan.ai is released under the AGPL v3 license, which is open source but has copyleft requirements. Locally Uncensored uses the more permissive MIT license, which allows unrestricted use, modification, and distribution."}},{"@type":"Question","name":"Which uses less memory, Locally Uncensored or Jan?","acceptedAnswer":{"@type":"Answer","text":"Locally Uncensored uses Tauri (Rust + system webview) which typically consumes 50-100MB of RAM for the app shell. Jan uses Electron which bundles a full Chromium instance and often consumes 300-500MB or more. Actual model inference memory depends on the model size, not the app."}}]}</script><style>*{margin:0;padding:0;box-sizing:border-box}@@ -38,6 +41,8 @@ td{padding:12px;border-bottom:1px solid #1a1a1a}.verdict{background:#161616;border:1px solid #222;border-radius:12px;padding:24px;margin:32px 0}.verdict h3{margin:0 0 8px;color:#8b5cf6}ul{margin:12px 0 16px 24px;color:#ccc}li{margin-bottom:8px;font-size:15px}+.faq{margin-top:48px}.faq h3{color:#ededed}.faq p{font-size:15px}+.related{margin-top:48px;padding-top:32px;border-top:1px solid #222}.related h3{margin-bottom:16px;color:#ededed}.related a{display:block;margin-bottom:10px;font-size:15px}@media(max-width:768px){article{padding:80px 16px 40px}h1{font-size:28px}}</style></head>@@ -50,8 +55,11 @@ ul{margin:12px 0 16px 24px;color:#ccc}li{margin-bottom:8px;font-size:15px}<h1>Locally Uncensored vs Jan.ai</h1><div class="meta">Published March 30, 2026 · 6 min read</div>-<p>Jan.ai has earned a reputation for having one of the most polished, ChatGPT-like interfaces among local AI apps. It supports both local models and cloud APIs, making it a hybrid solution for users who want flexibility.</p>-<p>Locally Uncensored focuses on being a complete local AI creative suite. While Jan excels at being a clean chat interface with cloud API support, Locally Uncensored brings image and video generation capabilities that Jan does not offer.</p>+<p>Jan.ai has earned a reputation as one of the most polished, ChatGPT-like interfaces among local AI apps. Built on Electron with a clean design, it supports both local models and cloud APIs from providers like OpenAI, Anthropic, and Google. For users who want a single chat interface that bridges local and cloud AI, Jan is an appealing option.</p>++<p><a href="https://purpledoubled.github.io/locally-uncensored/">Locally Uncensored</a> takes a fundamentally different approach. Rather than trying to be a universal chat client, it focuses on being a complete local AI creative suite. It combines LLM chat via Ollama with image generation and video generation via ComfyUI -- capabilities that Jan does not offer at all. If you are exploring the <a href="best-local-ai-apps-2026.html">best local AI apps in 2026</a>, these two represent very different philosophies about what a local AI app should be.</p>++<p>Both apps run on Windows, macOS, and Linux. Both let you chat with local models on your own hardware. But the similarities end there. This comparison breaks down exactly where each app excels and where it falls short.</p><h2>Feature Comparison</h2><table>@@ -60,37 +68,74 @@ ul{margin:12px 0 16px 24px;color:#ccc}li{margin-bottom:8px;font-size:15px}<tr><td>LLM Chat</td><td><span class="check">Yes (Ollama)</span></td><td><span class="check">Yes (Cortex/llama.cpp)</span></td></tr><tr><td>Image Generation</td><td><span class="check hl">Yes (ComfyUI)</span></td><td><span class="cross">No</span></td></tr><tr><td>Video Generation</td><td><span class="check hl">Yes (ComfyUI)</span></td><td><span class="cross">No</span></td></tr>-<tr><td>Cloud API Support</td><td><span class="cross">No</span></td><td><span class="check">Yes (OpenAI, Anthropic, etc.)</span></td></tr>-<tr><td>Custom Personas</td><td><span class="check hl">Yes</span></td><td><span class="cross">No</span></td></tr>+<tr><td>Cloud API Support</td><td><span class="cross">No (local only)</span></td><td><span class="check">Yes (OpenAI, Anthropic, etc.)</span></td></tr>+<tr><td>Custom Personas</td><td><span class="check hl">25+ built-in</span></td><td><span class="cross">No</span></td></tr><tr><td>Extension System</td><td><span class="cross">No</span></td><td><span class="check">Yes</span></td></tr>+<tr><td>Uncensored by Default</td><td><span class="check hl">Yes</span></td><td><span class="cross">No</span></td></tr><tr><td>License</td><td><span class="check">MIT</span></td><td>AGPL v3</td></tr>-<tr><td>UI Framework</td><td>Tauri + React</td><td>Electron</td></tr>-<tr><td>Memory Usage</td><td><span class="check hl">Low (Tauri)</span></td><td>High (Electron)</td></tr>+<tr><td>UI Framework</td><td>Tauri (Rust)</td><td>Electron (Chromium)</td></tr>+<tr><td>App Memory Usage</td><td><span class="check hl">Low (50-100 MB)</span></td><td>High (300-500 MB)</td></tr><tr><td>HuggingFace Browser</td><td><span class="cross">No</span></td><td><span class="check">Yes</span></td></tr>-+<tr><td>Model Management</td><td><span class="check">Built-in (Ollama)</span></td><td><span class="check">Built-in + HF</span></td></tr>+<tr><td>Docker Required</td><td><span class="check">No</span></td><td><span class="check">No</span></td></tr></tbody></table><h2>Where Locally Uncensored Wins</h2><ul>-<li><strong>Image + Video Generation</strong> — Full ComfyUI integration for local image and video generation. Jan is text-only.</li>-<li><strong>Lightweight App</strong> — Tauri uses a fraction of the memory compared to Jan's Electron-based app. Better performance on lower-end hardware.</li>-<li><strong>MIT License</strong> — More permissive than Jan's AGPL v3 license. Fork it, modify it, do whatever you want.</li>-<li><strong>Custom Personas</strong> — Switch between different AI personalities instantly for different tasks and creative scenarios.</li>+<li><strong>Image and Video Generation</strong> -- This is the single biggest differentiator. Locally Uncensored integrates ComfyUI for full image generation (Stable Diffusion XL, FLUX.1 Schnell, Pony Diffusion, Juggernaut XL) and video generation (Wan 2.1, AnimateDiff). Jan has no visual generation capabilities whatsoever. If you need anything beyond text chat, this alone justifies the switch.</li>+<li><strong>Lightweight Runtime</strong> -- Locally Uncensored is built with Tauri, which uses Rust and your system's native webview. This typically means 50-100 MB of RAM for the app shell. Jan uses Electron, which bundles an entire Chromium browser and routinely consumes 300-500 MB before you even load a model. On machines with limited RAM, that difference matters for model inference headroom. This is similar to the advantage over <a href="locally-uncensored-vs-lm-studio.html">other Electron-based apps like LM Studio</a>.</li>+<li><strong>MIT License</strong> -- Locally Uncensored uses the permissive MIT license. Jan uses AGPL v3, which requires you to share source code of any modifications and has stricter redistribution terms. For developers building on top of these tools, the MIT license offers significantly more freedom.</li>+<li><strong>Custom Personas</strong> -- 25+ built-in AI personas let you switch between different personalities instantly without writing system prompts. Jan provides a blank chat window with no persona system.</li>+<li><strong>Uncensored by Default</strong> -- Ships with abliterated model recommendations and no content filters on text, images, or video. Jan does not specifically cater to uncensored use cases.</li></ul><h2>Where Jan.ai Wins</h2><ul>-<li><strong>Cloud API Support</strong> — Connect to OpenAI, Anthropic, Google, Mistral, and more alongside local models. Great if you want one app for everything.</li>-<li><strong>Polished Chat UI</strong> — One of the cleanest, most intuitive chat interfaces among local AI apps. Feels like ChatGPT.</li>-<li><strong>Extension System</strong> — Plugin architecture allows community extensions to add new features.</li>-<li><strong>HuggingFace Integration</strong> — Browse and download models directly from HuggingFace within the app.</li>+<li><strong>Cloud API Support</strong> -- Jan connects to OpenAI, Anthropic, Google, Mistral, and other cloud providers alongside local models. If you want a single interface for both local and cloud AI, Jan is one of the few apps that does this well. Locally Uncensored is purely local by design.</li>+<li><strong>Polished Chat Interface</strong> -- Jan has one of the cleanest, most intuitive chat UIs among local AI apps. It genuinely feels like a local version of ChatGPT. The conversation management, threading, and overall design are excellent.</li>+<li><strong>Extension System</strong> -- Jan supports a plugin architecture that lets the community build and install extensions for additional functionality. Locally Uncensored does not currently have an extension system.</li>+<li><strong>HuggingFace Integration</strong> -- Browse, search, and download models directly from HuggingFace within Jan. You can filter by quantization level and see model sizes before downloading. Locally Uncensored handles model management through Ollama's built-in model library.</li>+<li><strong>Self-Contained Inference</strong> -- Jan bundles its own inference engine via Cortex, so it does not depend on an external process like Ollama. Locally Uncensored requires Ollama to be installed and running for text chat.</li></ul>+<h2>Architecture Differences</h2>+<p>The architectural differences between these two apps reflect their different priorities. Jan is built with Electron and ships with its own Cortex inference engine based on llama.cpp. This makes it a self-contained package, but the Electron runtime adds significant memory overhead.</p>+<p>Locally Uncensored uses Tauri (Rust backend with native system webview) and delegates inference to Ollama for text and ComfyUI for image/video. This modular approach means a lighter app footprint and the ability to leverage each backend's full feature set, but it does require those backends to be installed separately. The setup script automates this process.</p>+<p>For users who already have Ollama installed, Locally Uncensored adds zero redundant inference engines. For users who want everything in one package with no external dependencies, Jan's self-contained approach is more convenient.</p>+<div class="verdict"><h3>The Verdict</h3>-<p><strong>Choose Jan.ai</strong> if you want a polished ChatGPT-like interface that supports both local models and cloud APIs like OpenAI and Anthropic.</p>-<p><strong>Choose Locally Uncensored</strong> if you want a lightweight, fully local AI app with text, image, and video generation capabilities and a permissive MIT license.</p>+<p><strong>Choose Jan.ai</strong> if you want a polished ChatGPT-like interface that supports both local models and cloud APIs like OpenAI and Anthropic. Jan is the right choice if text chat is all you need and you value a clean UI with HuggingFace model browsing.</p>+<p><strong>Choose Locally Uncensored</strong> if you want a lightweight, fully local AI app with text, image, and video generation capabilities. The MIT license, Tauri runtime, uncensored defaults, and ComfyUI integration make it the better choice for users who want a complete creative AI suite on their own hardware.</p>+</div>++<div class="faq">+<h2>Frequently Asked Questions</h2>++<h3>Is Locally Uncensored better than Jan.ai?</h3>+<p>It depends on your priorities. Locally Uncensored is better if you want text chat, image generation, and video generation in one app with a permissive MIT license. Jan.ai is better if you need cloud API support alongside local models and prefer a polished ChatGPT-like interface.</p>++<h3>Does Jan.ai support image generation?</h3>+<p>No. Jan.ai focuses on text-based LLM chat and cloud API integration. For local image and video generation, you need a tool like Locally Uncensored which integrates ComfyUI for Stable Diffusion, FLUX, and Wan 2.1 support.</p>++<h3>Is Jan.ai open source?</h3>+<p>Jan.ai is released under the AGPL v3 license, which is open source but has copyleft requirements. Locally Uncensored uses the more permissive MIT license, which allows unrestricted use, modification, and distribution.</p>++<h3>Which uses less memory -- Locally Uncensored or Jan?</h3>+<p>Locally Uncensored uses Tauri (Rust + system webview) which typically consumes 50-100 MB of RAM for the app shell. Jan uses Electron which bundles a full Chromium instance and often consumes 300-500 MB or more. Actual model inference memory depends on the model size, not the app.</p>+</div>++<div class="related">+<h3>Related Comparisons</h3>+<a href="locally-uncensored-vs-open-webui.html">Locally Uncensored vs Open WebUI</a>+<a href="locally-uncensored-vs-lm-studio.html">Locally Uncensored vs LM Studio</a>+<a href="locally-uncensored-vs-gpt4all.html">Locally Uncensored vs GPT4All</a>+<a href="locally-uncensored-vs-koboldcpp.html">Locally Uncensored vs Kobold.cpp</a>+<a href="locally-uncensored-vs-sillytavern.html">Locally Uncensored vs SillyTavern</a>+<a href="locally-uncensored-vs-msty.html">Locally Uncensored vs Msty</a>+<a href="best-local-ai-apps-2026.html">Best Local AI Apps in 2026</a>+<a href="run-uncensored-ai-locally.html">How to Run Uncensored AI Locally</a></div><div class="cta">diff --git a/docs/index.html b/docs/index.htmlindex 91914996..3662909c 100644--- a/docs/index.html+++ b/docs/index.html@@ -177,6 +177,7 @@ footer a:hover{color:var(--text)}<a href="#compare">Compare</a><a href="#models">Models</a><a href="#faq">FAQ</a>+ <a href="blog/">Blog</a><a href="https://github.com/PurpleDoubleD/locally-uncensored" target="_blank">Docs</a></div></div>@@ -395,6 +396,21 @@ footer a:hover{color:var(--text)}</div></section>+<section class="faq reveal" id="blog" style="padding:80px 0">+ <div class="section-label">Blog</div>+ <h2 class="section-heading">Guides and comparisons.</h2>+ <div class="faq-list">+ <div class="faq-item"><h3><a href="blog/best-local-ai-apps-2026.html" style="color:#ededed">Best Local AI Apps in 2026</a></h3><p>Complete comparison of GPT4All, Open WebUI, LM Studio, Jan, Kobold.cpp, SillyTavern, text-generation-webui, and Locally Uncensored.</p></div>+ <div class="faq-item"><h3><a href="blog/run-uncensored-ai-locally.html" style="color:#ededed">How to Run Uncensored AI Locally</a></h3><p>A complete guide to running AI locally without restrictions. Setup, models, and why local beats cloud.</p></div>+ <div class="faq-item"><h3><a href="blog/locally-uncensored-vs-gpt4all.html" style="color:#ededed">Locally Uncensored vs GPT4All</a></h3><p>All-in-one AI creative suite vs the most popular local chatbot with document RAG.</p></div>+ <div class="faq-item"><h3><a href="blog/locally-uncensored-vs-jan.html" style="color:#ededed">Locally Uncensored vs Jan.ai</a></h3><p>Lightweight Tauri app with image/video gen vs polished Electron chat client with cloud API support.</p></div>+ <div class="faq-item"><h3><a href="blog/locally-uncensored-vs-open-webui.html" style="color:#ededed">Locally Uncensored vs Open WebUI</a></h3><p>Both are MIT-licensed Ollama frontends. Only one combines chat, image gen, and video generation.</p></div>+ <div class="faq-item"><h3><a href="blog/locally-uncensored-vs-lm-studio.html" style="color:#ededed">Locally Uncensored vs LM Studio</a></h3><p>Open source all-in-one vs polished closed-source chat client.</p></div>+ <div class="faq-item"><h3><a href="blog/locally-uncensored-vs-sillytavern.html" style="color:#ededed">Locally Uncensored vs SillyTavern</a></h3><p>Both run uncensored AI locally. One is built for roleplay, the other for everything else.</p></div>+ <div class="faq-item" style="border-bottom:none;text-align:center;padding-top:16px"><a href="blog/" style="font-size:14px">View all posts</a></div>+ </div>+</section>+<section class="cta reveal"><h2>Run your own uncensored AI stack.</h2><p>Free, open source, and yours to keep. No sign-up required.</p>diff --git a/marketing/discord-targets.md b/marketing/discord-targets.mdnew file mode 100644index 00000000..3542394f--- /dev/null+++ b/marketing/discord-targets.md@@ -0,0 +1,89 @@+# Discord Communities — Locally Uncensored Outreach++Target servers where local AI, self-hosting, or the underlying tools are discussed.++---++## Primary Targets (Directly Relevant)++### 1. Ollama Discord+- **Relevance:** Core integration — LU uses Ollama as its LLM backend+- **Invite:** https://discord.gg/ollama+- **Where to post:** #showcase or #community-projects+- **Angle:** "Built a desktop app that provides a chat UI for Ollama + ComfyUI image gen in one place"++### 2. ComfyUI Discord+- **Relevance:** Core integration — LU uses ComfyUI for image/video generation+- **Invite:** https://discord.gg/comfyui+- **Where to post:** #share-your-work or #custom-nodes+- **Angle:** "Desktop app that integrates ComfyUI workflows alongside LLM chat via Ollama"++### 3. Stable Diffusion (Official / Stability AI)+- **Relevance:** Image generation community, ComfyUI users overlap heavily+- **Invite:** https://discord.gg/stablediffusion+- **Where to post:** #tools-and-resources or #showcase+- **Angle:** "Open-source app combining SD image gen (via ComfyUI) with local LLM chat"++### 4. AUTOMATIC1111 / Stable Diffusion WebUI+- **Relevance:** Local image gen community — many migrating to ComfyUI+- **Invite:** https://discord.gg/stable-diffusion (community server)+- **Where to post:** #other-tools or #showcase+- **Angle:** "If you're exploring ComfyUI, this app bundles it with Ollama chat in one UI"++---++## Secondary Targets (Adjacent Communities)++### 5. Tauri Discord+- **Relevance:** Built with Tauri v2 — good case study for the framework+- **Invite:** https://discord.gg/tauri+- **Where to post:** #showcase+- **Angle:** "Built a Tauri v2 + React app for local AI (Ollama + ComfyUI). Here's what we learned"++### 6. r/LocalLLaMA Discord+- **Relevance:** Largest local LLM community+- **Invite:** https://discord.gg/localllama+- **Where to post:** #projects or #showcase+- **Angle:** "Desktop app that gives Ollama a proper UI and adds ComfyUI image gen"++### 7. r/SelfHosted Discord+- **Relevance:** Self-hosting enthusiasts, privacy-focused audience+- **Invite:** https://discord.gg/selfhosted (community-run)+- **Where to post:** #showcase or #new-projects+- **Angle:** "Fully local AI desktop app — chat + image gen, nothing leaves your machine"++### 8. Hugging Face Discord+- **Relevance:** ML/AI community, model enthusiasts+- **Invite:** https://discord.gg/huggingface+- **Where to post:** #showcase or #general+- **Angle:** "Open-source desktop app for running local models (Ollama + ComfyUI)"++### 9. FOSS / Open Source Communities+- **Relevance:** MIT-licensed, open source+- **Invite:** Various — search for "open source" or "FOSS" Discord servers+- **Angle:** "MIT-licensed local AI app, built with Tauri + React"++### 10. AI Image Generation Communities+- **Relevance:** Flux, SDXL, image gen enthusiasts+- **Servers:** Various community servers for Flux, Civitai Discord+- **Civitai Discord:** https://discord.gg/civitai+- **Angle:** "Desktop app with ComfyUI integration for image gen + LLM chat"++---++## Posting Guidelines++- **Read the rules first.** Most servers have #rules or pinned messages with self-promo policies.+- **Post in the right channel.** Use #showcase, #projects, or #share-your-work — never #general unless invited.+- **Be genuine.** Share what you built and why, not a sales pitch. Engage with questions.+- **Include a screenshot or short video.** Visual posts get far more engagement.+- **Stick around.** Answer questions, take feedback, be part of the community.+- **Don't spam.** One post per server. Follow up only if there's genuine discussion.++---++## Notes++- Invite links may expire or change. Verify before clicking.+- Some servers require account age or verification before posting.+- Best time to post: weekday afternoons (US time zones) for maximum visibility.diff --git a/marketing/newsletter-pitches.md b/marketing/newsletter-pitches.mdindex c475707e..154cfcf5 100644--- a/marketing/newsletter-pitches.md+++ b/marketing/newsletter-pitches.md@@ -1,174 +1,118 @@-# Newsletter Pitch Emails - Locally Uncensored--Generated: March 30, 2026+# Newsletter Pitches - Locally Uncensored----## 1. selfh.st (Self-Host Weekly)--**Status: SUBMITTED via API on March 30, 2026**-Submission ID: cmndkrigg002xo501746l2r1q-Category: Project Launch--**Subject:** New self-hosted project: Locally Uncensored — run AI (text + image + video) entirely on your own hardware--**Body:**+## 1. selfh.st Newsletter-Hi Ethan,+**Subject:** Locally Uncensored — self-hosted AI chat + image gen in one desktop app-Wanted to share a new open-source project that fits the self-hosted community well.+Hi,-Locally Uncensored is a desktop app that lets you run AI entirely on your own hardware — no cloud, no accounts, no data leaving your machine. It's built with Tauri + React and integrates two backends:+I built Locally Uncensored, an open-source desktop app that combines LLM chat (via Ollama) and image/video generation (via ComfyUI) in a single interface. Everything runs locally — no API keys, no cloud, no data leaving your machine.-- Ollama for local LLMs (chat, coding, writing)-- ComfyUI for local image and video generation+Built with Tauri v2 + React, so it's lightweight (~15 MB) compared to Electron alternatives. MIT licensed.-The key thing for self-hosters: it's a single app that handles the setup of both backends. One-click install on Windows, Mac, and Linux. No Docker, no CLI config, no port forwarding needed (though it works alongside existing Ollama/ComfyUI installs too).--It supports uncensored models out of the box, which matters for users who want full control over their AI stack without content filtering decided by a third party.+Why it fits selfh.st: it's a genuine self-hosted AI workflow — chat and image gen unified, with zero external dependencies once set up.GitHub: https://github.com/PurpleDoubleD/locally-uncensored-Website: https://purpledoubled.github.io/locally-uncensored/-License: Open source-Platforms: Windows, macOS, Linux--Thanks for considering it for Self-Host Weekly.----+Happy to provide screenshots or answer any questions.-## 2. Console.dev (Developer Tools)+Thanks-**Submit via:** https://console.dev/submit/ (web form)+----**Subject:** Locally Uncensored — open-source Tauri app combining Ollama + ComfyUI in one developer-friendly desktop tool+## 2. Console.dev ([email protected])-**Body:**+**Subject:** Locally Uncensored — open-source Tauri app combining Ollama + ComfyUIHi Console team,-Locally Uncensored is an open-source desktop application built with Tauri (Rust backend) and React that gives developers a unified interface for running AI models locally.+Locally Uncensored is an open-source desktop app (Tauri v2 + React) that gives developers a single interface for local LLM chat and image/video generation. It connects to Ollama for language models and ComfyUI for Stable Diffusion workflows.-What it does:-- Integrates Ollama for LLM inference (chat, code generation, text tasks)-- Integrates ComfyUI for image and video generation via Stable Diffusion workflows-- Bundles everything into a single cross-platform desktop app--Why developers would care:-- Built with Tauri + React — lightweight, fast, native-feeling-- No cloud dependencies — runs fully offline, useful for air-gapped or privacy-sensitive environments-- One-click setup handles Ollama and ComfyUI installation automatically-- Supports uncensored/unfiltered models for unrestricted local experimentation-- Cross-platform: Windows, macOS, Linux--It solves the friction of juggling multiple local AI tools. Instead of separately installing Ollama, setting up ComfyUI with Python dependencies, and switching between browser tabs, developers get one app.+What makes it different:+- Combines two distinct local AI tools (chat + image gen) in one app+- No data leaves your machine — fully offline capable+- Tauri v2 means native performance at ~15 MB (not another Electron app)+- MIT license, actively maintainedGitHub: https://github.com/PurpleDoubleD/locally-uncensored-Website: https://purpledoubled.github.io/locally-uncensored/-Stack: Tauri, React, Rust, Ollama, ComfyUI------## 3. The Rundown AI+Thanks for considering it.-**Submit via:** [email protected] or https://therundown.ai/submit (check current process)+----**Subject:** Open-source app runs LLMs + image/video AI locally in one desktop tool — no cloud needed+## 3. The Rundown AI ([email protected])-**Body:**+**Subject:** Open-source desktop app for local AI: chat + image gen, zero cloud dependencyHi Rundown team,-There's a new open-source project worth a look: Locally Uncensored is a desktop app that combines text AI (via Ollama) and image/video generation (via ComfyUI) into a single local-first application.--The pitch is simple: instead of paying for API access or using cloud AI services, users run everything on their own GPU. Text generation, image creation, and video generation — all offline, all private, all uncensored.--Key details:-- Integrates Ollama (Llama, Mistral, etc.) for text/chat AI-- Integrates ComfyUI (Stable Diffusion, Flux, etc.) for image and video generation-- One-click installer handles all dependencies — no technical setup required-- Works on Windows, Mac, and Linux-- Fully open source (Tauri + React)-- Supports uncensored models with no content filtering+Quick pitch: Locally Uncensored is a free, open-source desktop app that runs AI chat and image/video generation entirely on your hardware. It connects to Ollama (LLMs like Llama, Mistral, etc.) and ComfyUI (Stable Diffusion image gen) through one clean interface.-This matters because most local AI tools handle either text OR images. Locally Uncensored combines both in one app with a consumer-friendly interface, lowering the barrier for non-technical users to run AI privately.+The angle for your readers: as AI privacy concerns grow, this lets anyone run capable AI locally with no accounts, no API costs, and no data leaving their machine. Built with Tauri + React, MIT licensed.GitHub: https://github.com/PurpleDoubleD/locally-uncensored-Website: https://purpledoubled.github.io/locally-uncensored/------## 4. TLDR Newsletter+Happy to provide more details.-**Submit via:** https://tldr.tech/submit (or [email protected])+----**Subject:** Locally Uncensored: open-source desktop app that runs LLMs + image/video AI locally with one-click setup+## 4. TLDR ([email protected])-**Body:**+**Subject:** Locally Uncensored — local AI chat + image gen desktop app (open source)Hi TLDR team,-Locally Uncensored is an open-source desktop app that bundles local AI into a single install: LLM chat (via Ollama) plus image and video generation (via ComfyUI), all running on-device with no cloud.--Quick facts:-- One app, one installer — sets up Ollama and ComfyUI automatically-- Text AI: run Llama, Mistral, Qwen, and other open models locally-- Image/video AI: Stable Diffusion and Flux via ComfyUI integration-- Privacy-first: nothing leaves your machine-- Supports uncensored/unfiltered models-- Built with Tauri + React, cross-platform (Win/Mac/Linux)-- Open source on GitHub+Locally Uncensored is an open-source desktop app that combines local LLM chat (Ollama) and image/video generation (ComfyUI) in one interface. Nothing leaves your machine.-The gap it fills: there are plenty of LLM UIs and plenty of image gen tools, but few apps combine both in a single desktop experience with automated setup. Locally Uncensored does that.+Key details:+- Tauri v2 + React (lightweight, cross-platform)+- Connects to Ollama for chat, ComfyUI for image/video gen+- MIT license+- No API keys, no accounts, no cloudGitHub: https://github.com/PurpleDoubleD/locally-uncensored-Website: https://purpledoubled.github.io/locally-uncensored/----+Would love to be featured in TLDR or TLDR AI. Let me know if you need anything.-## 5. Changelog (open source)+Thanks-**Submit via:** https://changelog.com/submit or [email protected]+----**Subject:** Locally Uncensored — open-source Tauri app unifying local LLMs and image gen in one desktop tool+## 5. AI Tool Report ([email protected])-**Body:**+**Subject:** Free local AI desktop app — chat + image generation, fully offline-Hi Changelog team,+Hi AI Tool Report team,-Locally Uncensored is an open-source desktop application that brings together two major categories of local AI — language models and image/video generation — into a single, installable app.+I'd like to share Locally Uncensored — a free, open-source desktop app for running AI completely locally. It unifies two workflows most people handle separately:-The project:-- Built with Tauri (Rust) + React-- Integrates Ollama for running LLMs locally (Llama, Mistral, Qwen, etc.)-- Integrates ComfyUI for Stable Diffusion / Flux image and video generation-- One-click setup handles dependency installation across Windows, macOS, and Linux-- Privacy-first: fully offline, no telemetry, no cloud-- Supports uncensored models — users control what runs on their hardware+1. LLM chat (via Ollama — supports Llama, Mistral, Phi, and dozens more)+2. Image/video generation (via ComfyUI — Stable Diffusion, Flux, etc.)-From an open-source perspective, it's interesting because it stitches together two existing open-source ecosystems (Ollama and ComfyUI) into a unified desktop experience. The Tauri + React stack keeps it lightweight compared to Electron alternatives.+The pitch for your audience: get ChatGPT-like chat + Midjourney-like image gen with zero subscription costs and full privacy. Everything runs on your own hardware.-The project is early (11 GitHub stars, actively developed) but functional and growing. It's the kind of tool that makes local AI accessible to people who don't want to manage Python environments and terminal commands.+Built with Tauri v2 + React. MIT licensed. Cross-platform.GitHub: https://github.com/PurpleDoubleD/locally-uncensored-Website: https://purpledoubled.github.io/locally-uncensored/-License: Open source++Thanks for considering it.----## Submission Tracking+## 6. Changelog (changelog.com)++**Subject:** Locally Uncensored — Tauri v2 app bridging Ollama and ComfyUI for local AI++Hi Changelog team,-| Newsletter | Method | Status | Date |-|---|---|---|---|-| selfh.st | API submission | SUBMITTED (ID: cmndkrigg002xo501746l2r1q) | 2026-03-30 |-| Console.dev | Web form at console.dev/submit | DRAFT READY | - |-| The Rundown AI | Email / web form | DRAFT READY | - |-| TLDR Newsletter | Email / web form | DRAFT READY | - |-| Changelog | Email / web form | DRAFT READY | - |+Locally Uncensored is an open-source desktop app that connects Ollama (local LLMs) and ComfyUI (local image/video gen) into a single interface. Built with Tauri v2 and React.-## Notes+The technical story: rather than building yet another chat wrapper, we wanted to solve the fragmented local AI experience. Most people alt-tab between a chat UI and ComfyUI — this unifies both. Tauri v2 keeps it native and small (~15 MB vs Electron bloat). Everything stays local.++MIT license. Active development. Would be a good fit for Changelog News or the podcast.++GitHub: https://github.com/PurpleDoubleD/locally-uncensored-- selfh.st was submitted directly via their public form API (Project Launch category)-- Other newsletters require manual submission via their respective web forms or email addresses-- Pitches are tailored to each audience: self-hosting, dev tools, AI news, general tech, open source-- All pitches kept factual — no hyperbole, just what the project actually does-- Consider following up if no response after 1-2 weeks+Thanksdiff --git a/marketing/producthunt-draft.md b/marketing/producthunt-draft.mdindex 49d9138f..79e7faab 100644--- a/marketing/producthunt-draft.md+++ b/marketing/producthunt-draft.md@@ -1,196 +1,57 @@# Product Hunt Launch Draft — Locally Uncensored-> IMPORTANT: Product Hunt launches must be done manually via browser.-> Go to: https://producthunt.com/posts/new-> Log in with the maker account, fill in the fields below, and submit.-----## Product Name--Locally Uncensored+## Tagline (60 chars max)-## URL+Local AI chat + image gen in one desktop app. No cloud.-https://github.com/PurpleDoubleD/locally-uncensored+(55 characters)----## Tagline (max 60 chars)--"Chat, images & video with uncensored AI — 100% offline"+## Description (260 chars max)-(57 characters)+Locally Uncensored is a free, open-source desktop app that combines LLM chat (Ollama) and image/video generation (ComfyUI) in one interface. Everything runs on your hardware — no API keys, no accounts, no data leaving your machine. Built with Tauri + React.-Alternatives if needed:-- "One app for uncensored AI chat, images & video — offline" (57 chars)-- "Run uncensored AI locally: chat + images + video in one app" (59 chars)+(259 characters)----## Description (max 260 chars)--"Open-source desktop app that runs uncensored AI models entirely on your machine. Chat with 25+ personas, generate images and videos via ComfyUI, one-click model install, beautiful dark/light UI. No cloud, no data collection, no restrictions. Fully private."--(258 characters)-------## Maker Comment (post this as the maker right after launch)--Hey Product Hunt! I'm the maker of Locally Uncensored.+## Maker Comment (first comment after launch)-I built this because I was tired of juggling Ollama for chat, ComfyUI for images, and yet another tool for video — all with clunky setup processes. I wanted one beautiful app that does it all, runs fully offline, and doesn't tell me what I can or can't ask.+Hey Product Hunt! I built Locally Uncensored because I was tired of switching between separate apps for local AI chat and image generation.-What makes it different:-- It's the only local AI app combining chat + image gen + video gen in a single UI-- One-click setup: the app installs Ollama models and ComfyUI for you-- 25+ built-in personas (from Helpful Assistant to Roast Master)-- Portable mode — run it from a USB drive, no install needed-- MIT licensed, fully open source+The idea is simple: one app that talks to Ollama for LLM chat and ComfyUI for image/video gen. No cloud services, no API costs — just your hardware doing the work.-It runs on Windows, macOS, and Linux. You just need a decent GPU (6GB+ VRAM for chat, 8GB+ for images/video).+Tech stack: Tauri v2 + React. The whole app is about 15 MB (thanks to Tauri instead of Electron). MIT licensed, so you can fork and modify however you want.-I'd love your feedback — what features would you want to see next? RAG/document chat and audio generation are on the roadmap.+I'd love feedback on what features matter most to you. What would make this your go-to local AI app?GitHub: https://github.com/PurpleDoubleD/locally-uncensored----## First Comment (post from a different account or have a supporter post this)+## Key Features-Just tried this out — the one-click ComfyUI installation is genuinely impressive. Normally setting up image generation locally is a nightmare of Python environments and model downloads. This app literally does it all for you inside the UI. The persona system is fun too. Roast Master had me laughing. Starred on GitHub!+1. **Local LLM Chat** — Connect to Ollama and chat with Llama, Mistral, Phi, Gemma, and dozens of other models. All running on your hardware.------## Topics / Tags+2. **Image & Video Generation** — Built-in ComfyUI integration for Stable Diffusion, Flux, and other generative models. Create images without leaving the app.-Select these on Product Hunt (pick up to 3 for primary, the rest appear as additional):+3. **Complete Privacy** — Zero cloud dependencies. No accounts, no telemetry, no API keys. Your data never leaves your machine.-PRIMARY (pick 3):-1. Artificial Intelligence-2. Open Source-3. Privacy+4. **Lightweight & Native** — Built with Tauri v2 (~15 MB), not Electron. Fast startup, low memory footprint, cross-platform (macOS, Windows, Linux).-ADDITIONAL / RELATED:-4. Developer Tools-5. Tech-6. Productivity-7. Design Tools (for image/video generation angle)--Also search for and add these if available:-- Local AI-- LLM-- Generative AI-- Desktop App+5. **Open Source (MIT)** — Fully open source. Inspect the code, contribute, or fork it for your own use.----## Gallery Images (upload 5-8 images, 1270x760px recommended)--Prepare these images from existing screenshots + new assets:--### Image 1 — Hero / Thumbnail (THIS IS THE MOST IMPORTANT ONE)-Source: docs/screenshots/marketing_01_hero.png-Description: App landing/hero view showing the Locally Uncensored branding. This is the main thumbnail shown in the PH feed — make it pop.-Overlay text suggestion: "Chat + Images + Video — All Local, All Private"--### Image 2 — Chat with Personas-Source: docs/screenshots/marketing_03_chat_personas.png-Description: The chat interface showing a conversation with an AI persona. Demonstrates the clean UI and persona system.-Overlay text suggestion: "25+ Built-in Personas — From Coding Expert to Creative Writer"--### Image 3 — Image & Video Creation-Source: docs/screenshots/marketing_06_create_view.png-Description: The Create tab showing image/video generation interface with ComfyUI integration.-Overlay text suggestion: "Generate Images & Videos — Powered by ComfyUI"--### Image 4 — Model Manager-Source: docs/screenshots/marketing_07_model_manager.png-Description: The model manager showing one-click install for text, image, and video models.-Overlay text suggestion: "One-Click Model Install — Browse, Download, Run"--### Image 5 — Light Mode-Source: docs/screenshots/marketing_09_light_mode.png-Description: The app in light mode, showing the glassmorphism UI design.-Overlay text suggestion: "Beautiful Dark & Light Themes"--### Image 6 — Settings-Source: docs/screenshots/marketing_08_settings.png-Description: Settings panel showing temperature, top-p, top-k controls.-Overlay text suggestion: "Full Control Over AI Parameters"--### Image 7 — Comparison Table (CREATE THIS)-Description: A clean graphic showing the feature comparison table from the README — Locally Uncensored vs Open WebUI vs LM Studio vs SillyTavern. All checkmarks for Locally Uncensored, gaps for others. This is a powerful visual differentiator.--### Image 8 — Architecture / How It Works (CREATE THIS)-Description: Simple diagram showing: Your Computer → Locally Uncensored App → Ollama (Chat) + ComfyUI (Images/Video). Emphasize "No Cloud" with a crossed-out cloud icon.-------## Launch Day Checklist--### 2 Weeks Before-- [ ] Finalize all gallery images (1270x760px, PNG)-- [ ] Add overlay text to screenshots using Figma/Canva-- [ ] Create the comparison table graphic (Image 7)-- [ ] Create the architecture diagram (Image 8)-- [ ] Record a short demo GIF or video (30-60 seconds) showing chat → image gen → video gen flow-- [ ] Ensure GitHub README is polished and has a clear "Getting Started" section (DONE)-- [ ] Get 5-10 supporters lined up to upvote and comment on launch day-- [ ] Draft tweets / social posts for launch day--### 1 Week Before-- [ ] Create the Product Hunt post as a draft (producthunt.com/posts/new)-- [ ] Upload all gallery images-- [ ] Set the launch date (Tuesday-Thursday recommended, 12:01 AM PT)-- [ ] Fill in tagline, description, maker comment-- [ ] Add the GitHub link and any other relevant links-- [ ] Test that the GitHub repo is presentable (pinned issues, clean README)-- [ ] Prepare an email to any mailing list / Discord members about the launch--### Launch Day (12:01 AM Pacific Time)-- [ ] Publish the Product Hunt post (it goes live at 12:01 AM PT)-- [ ] Post the maker comment immediately after launch-- [ ] Have a supporter post the first comment within 30 minutes-- [ ] Share on Twitter/X with the PH link + "We're live on Product Hunt!"-- [ ] Share on Reddit: r/LocalLLaMA, r/selfhosted, r/opensource, r/StableDiffusion-- [ ] Post on Hacker News (Show HN)-- [ ] Share in relevant Discord servers (Ollama, ComfyUI, local AI communities)-- [ ] Respond to EVERY comment on PH within 1 hour — engagement is critical for ranking-- [ ] Post progress updates throughout the day ("We hit #5!", etc.)--### Day After-- [ ] Thank everyone who supported the launch-- [ ] Screenshot the final ranking and share it-- [ ] Add "Featured on Product Hunt" badge to the GitHub README if applicable-- [ ] Write a retrospective: what worked, what to do differently next time-------## Tips for Maximizing PH Performance--1. **Launch on Tuesday, Wednesday, or Thursday** — highest traffic days-2. **12:01 AM PT start** — you get the full 24-hour voting window-3. **First 4 hours are critical** — front-load your upvotes and comments-4. **Don't ask for upvotes directly** — say "check us out on Product Hunt" (PH penalizes vote-begging)-5. **Reply to every single comment** — PH algorithm rewards engagement-6. **Gallery thumbnail matters most** — make Image 1 irresistible-7. **Short demo video/GIF > walls of text** — people scroll fast-8. **Hunter vs Maker** — if possible, get a well-known PH hunter to submit your product (they have followers who get notified)-------## Optional: Product Hunt Embed Badge--After launch, add this to the GitHub README:--```html-<a href="https://www.producthunt.com/posts/locally-uncensored?utm_source=badge-featured" target="_blank">- <img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=POST_ID&theme=light"- alt="Locally Uncensored - Chat, images & video with uncensored AI — 100% offline | Product Hunt"- width="250" height="54" />-</a>-```+## Topics / Tags-(Replace POST_ID with the actual ID after launching)+- Artificial Intelligence+- Open Source+- Privacy+- Developer Tools+- Desktop Apps+- Self-Hosted+- Techdiff --git a/marketing/x-launch-thread.md b/marketing/x-launch-thread.mdnew file mode 100644index 00000000..fef3a44e--- /dev/null+++ b/marketing/x-launch-thread.md@@ -0,0 +1,87 @@+# X/Twitter Launch Thread — Locally Uncensored++---++**Tweet 1 (Hook)**++I built an open-source desktop app that combines local LLM chat and image generation in one interface.++No cloud. No API keys. No data leaves your machine.++It's called Locally Uncensored, and it's free.++github.com/PurpleDoubleD/locally-uncensored++🧵 Here's what it does:++---++**Tweet 2 (The Problem)**++Running local AI right now means juggling multiple tools:++- Ollama or llama.cpp for chat+- ComfyUI or A1111 for image gen+- Different UIs, different configs, different windows++Locally Uncensored puts both behind one interface. One app, two backends.++---++**Tweet 3 (How It Works)**++Under the hood:++→ Chat connects to Ollama (Llama, Mistral, Phi, Gemma, etc.)+→ Image/video gen connects to ComfyUI (Stable Diffusion, Flux, etc.)+→ Built with Tauri v2 + React+→ ~15 MB install (not Electron)+→ Runs on macOS, Windows, Linux++---++**Tweet 4 (Privacy)**++Everything runs on your hardware.++No accounts. No telemetry. No server calls. Your prompts, your images, your conversations — they stay on your machine.++This is what "local AI" should actually mean.++---++**Tweet 5 (Tech Stack)**++For the devs wondering about the stack:++- Tauri v2 (Rust backend, webview frontend)+- React + TypeScript+- Communicates with Ollama and ComfyUI via their local APIs+- MIT licensed — fork it, modify it, ship it++PRs welcome.++---++**Tweet 6 (What's Next)**++Currently working on:+- Workflow templates for ComfyUI+- Better model management+- More customization options++If you're into local AI, self-hosting, or just want an alternative to cloud AI tools — give it a try.++⭐ github.com/PurpleDoubleD/locally-uncensored++---++**Tweet 7 (CTA)**++If this is useful to you:++→ Star it on GitHub (helps visibility)+→ Try it and open issues (helps quality)+→ Share it with someone who runs Ollama or ComfyUI++Building in the open. Feedback welcome.diff --git a/package-lock.json b/package-lock.jsonindex 3268fd53..ba8a95c5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "locally-uncensored",- "version": "1.0.0",+ "version": "1.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "locally-uncensored",- "version": "1.0.0",+ "version": "1.2.0","license": "MIT","dependencies": {"@react-three/drei": "^10.7.7",@@ -17,6 +17,8 @@"dotenv": "^17.3.1","framer-motion": "^12.38.0","lucide-react": "^1.0.1",+ "mammoth": "^1.12.0",+ "pdfjs-dist": "^5.6.205","react": "^19.2.4","react-dom": "^19.2.4","react-markdown": "^10.1.0",@@ -602,6 +604,256 @@"three": ">= 0.159.0"}},+ "node_modules/@napi-rs/canvas": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.97.tgz",+ "integrity": "sha512-8cFniXvrIEnVwuNSRCW9wirRZbHvrD3JVujdS2P5n5xiJZNZMOZcfOvJ1pb66c7jXMKHHglJEDVJGbm8XWFcXQ==",+ "license": "MIT",+ "optional": true,+ "workspaces": [+ "e2e/*"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ },+ "optionalDependencies": {+ "@napi-rs/canvas-android-arm64": "0.1.97",+ "@napi-rs/canvas-darwin-arm64": "0.1.97",+ "@napi-rs/canvas-darwin-x64": "0.1.97",+ "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.97",+ "@napi-rs/canvas-linux-arm64-gnu": "0.1.97",+ "@napi-rs/canvas-linux-arm64-musl": "0.1.97",+ "@napi-rs/canvas-linux-riscv64-gnu": "0.1.97",+ "@napi-rs/canvas-linux-x64-gnu": "0.1.97",+ "@napi-rs/canvas-linux-x64-musl": "0.1.97",+ "@napi-rs/canvas-win32-arm64-msvc": "0.1.97",+ "@napi-rs/canvas-win32-x64-msvc": "0.1.97"+ }+ },+ "node_modules/@napi-rs/canvas-android-arm64": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.97.tgz",+ "integrity": "sha512-V1c/WVw+NzH8vk7ZK/O8/nyBSCQimU8sfMsB/9qeSvdkGKNU7+mxy/bIF0gTgeBFmHpj30S4E9WHMSrxXGQuVQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-darwin-arm64": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.97.tgz",+ "integrity": "sha512-ok+SCEF4YejcxuJ9Rm+WWunHHpf2HmiPxfz6z1a/NFQECGXtsY7A4B8XocK1LmT1D7P174MzwPF9Wy3AUAwEPw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-darwin-x64": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.97.tgz",+ "integrity": "sha512-PUP6e6/UGlclUvAQNnuXCcnkpdUou6VYZfQOQxExLp86epOylmiwLkqXIvpFmjoTEDmPmXrI+coL/9EFU1gKPA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.97.tgz",+ "integrity": "sha512-XyXH2L/cic8eTNtbrXCcvqHtMX/nEOxN18+7rMrAM2XtLYC/EB5s0wnO1FsLMWmK+04ZSLN9FBGipo7kpIkcOw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.97.tgz",+ "integrity": "sha512-Kuq/M3djq0K8ktgz6nPlK7Ne5d4uWeDxPpyKWOjWDK2RIOhHVtLtyLiJw2fuldw7Vn4mhw05EZXCEr4Q76rs9w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm64-musl": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.97.tgz",+ "integrity": "sha512-kKmSkQVnWeqg7qdsiXvYxKhAFuHz3tkBjW/zyQv5YKUPhotpaVhpBGv5LqCngzyuRV85SXoe+OFj+Tv0a0QXkQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.97.tgz",+ "integrity": "sha512-Jc7I3A51jnEOIAXeLsN/M/+Z28LUeakcsXs07FLq9prXc0eYOtVwsDEv913Gr+06IRo34gJJVgT0TXvmz+N2VA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-x64-gnu": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.97.tgz",+ "integrity": "sha512-iDUBe7AilfuBSRbSa8/IGX38Mf+iCSBqoVKLSQ5XaY2JLOaqz1TVyPFEyIck7wT6mRQhQt5sN6ogfjIDfi74tg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-x64-musl": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.97.tgz",+ "integrity": "sha512-AKLFd/v0Z5fvgqBDqhvqtAdx+fHMJ5t9JcUNKq4FIZ5WH+iegGm8HPdj00NFlCSnm83Fp3Ln8I2f7uq1aIiWaA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-win32-arm64-msvc": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.97.tgz",+ "integrity": "sha512-u883Yr6A6fO7Vpsy9YE4FVCIxzzo5sO+7pIUjjoDLjS3vQaNMkVzx5bdIpEL+ob+gU88WDK4VcxYMZ6nmnoX9A==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-win32-x64-msvc": {+ "version": "0.1.97",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.97.tgz",+ "integrity": "sha512-sWtD2EE3fV0IzN+iiQUqr/Q1SwqWhs2O1FKItFlxtdDkikpEj5g7DKQpY3x55H/MAOnL8iomnlk3mcEeGiUMoQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz",@@ -1973,6 +2225,15 @@"integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==","license": "BSD-3-Clause"},+ "node_modules/@xmldom/xmldom": {+ "version": "0.8.12",+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.12.tgz",+ "integrity": "sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ }+ },"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",@@ -2095,6 +2356,12 @@"require-from-string": "^2.0.2"}},+ "node_modules/bluebird": {+ "version": "3.4.7",+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz",+ "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==",+ "license": "MIT"+ },"node_modules/brace-expansion": {"version": "1.1.12","resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",@@ -2319,6 +2586,12 @@"dev": true,"license": "MIT"},+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "license": "MIT"+ },"node_modules/cross-env": {"version": "7.0.3","resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",@@ -2434,6 +2707,12 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/dingbat-to-unicode": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dingbat-to-unicode/-/dingbat-to-unicode-1.0.1.tgz",+ "integrity": "sha512-98l0sW87ZT58pU4i61wa2OHwxbiYSbuxsCBozaVnYX2iCnr3bLM3fIes1/ej7h1YdOKuKt/MLs706TVnALA65w==",+ "license": "BSD-2-Clause"+ },"node_modules/dotenv": {"version": "17.3.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",@@ -2452,6 +2731,15 @@"integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==","license": "Apache-2.0"},+ "node_modules/duck": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/duck/-/duck-0.1.12.tgz",+ "integrity": "sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg==",+ "license": "BSD",+ "dependencies": {+ "underscore": "^1.13.1"+ }+ },"node_modules/electron-to-chromium": {"version": "1.5.322","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.322.tgz",@@ -3091,6 +3379,12 @@"node": ">=0.8.19"}},+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",@@ -3182,6 +3476,12 @@"integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==","license": "MIT"},+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "license": "MIT"+ },"node_modules/isexe": {"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",@@ -3276,6 +3576,18 @@"node": ">=6"}},+ "node_modules/jszip": {+ "version": "3.10.1",+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",+ "license": "(MIT OR GPL-3.0-or-later)",+ "dependencies": {+ "lie": "~3.3.0",+ "pako": "~1.0.2",+ "readable-stream": "~2.3.6",+ "setimmediate": "^1.0.5"+ }+ },"node_modules/keyv": {"version": "4.5.4","resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",@@ -3591,6 +3903,17 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/lop": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/lop/-/lop-0.4.2.tgz",+ "integrity": "sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "duck": "^0.1.12",+ "option": "~0.2.1",+ "underscore": "^1.13.1"+ }+ },"node_modules/lowlight": {"version": "1.20.0","resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz",@@ -3643,6 +3966,39 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/mammoth": {+ "version": "1.12.0",+ "resolved": "https://registry.npmjs.org/mammoth/-/mammoth-1.12.0.tgz",+ "integrity": "sha512-cwnK1RIcRdDMi2HRx2EXGYlxqIEh0Oo3bLhorgnsVJi2UkbX1+jKxuBNR9PC5+JaX7EkmJxFPmo6mjLpqShI2w==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "@xmldom/xmldom": "^0.8.6",+ "argparse": "~1.0.3",+ "base64-js": "^1.5.1",+ "bluebird": "~3.4.0",+ "dingbat-to-unicode": "^1.0.1",+ "jszip": "^3.7.1",+ "lop": "^0.4.2",+ "path-is-absolute": "^1.0.0",+ "underscore": "^1.13.1",+ "xmlbuilder": "^10.0.0"+ },+ "bin": {+ "mammoth": "bin/mammoth"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/mammoth/node_modules/argparse": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",+ "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",+ "license": "MIT",+ "dependencies": {+ "sprintf-js": "~1.0.2"+ }+ },"node_modules/markdown-table": {"version": "3.0.4","resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",@@ -4572,6 +4928,13 @@"dev": true,"license": "MIT"},+ "node_modules/node-readable-to-web-readable-stream": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/node-readable-to-web-readable-stream/-/node-readable-to-web-readable-stream-0.4.2.tgz",+ "integrity": "sha512-/cMZNI34v//jUTrI+UIo4ieHAB5EZRY/+7OmXZgBxaWBMcW2tGdceIw06RFxWxrKZ5Jp3sI2i5TsRo+CBhtVLQ==",+ "license": "MIT",+ "optional": true+ },"node_modules/node-releases": {"version": "2.0.36","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz",@@ -4579,6 +4942,12 @@"dev": true,"license": "MIT"},+ "node_modules/option": {+ "version": "0.2.4",+ "resolved": "https://registry.npmjs.org/option/-/option-0.2.4.tgz",+ "integrity": "sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A==",+ "license": "BSD-2-Clause"+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",@@ -4629,6 +4998,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/pako": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",+ "license": "(MIT AND Zlib)"+ },"node_modules/parent-module": {"version": "1.0.1","resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",@@ -4677,6 +5052,15 @@"node": ">=8"}},+ "node_modules/path-is-absolute": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",+ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/path-key": {"version": "3.1.1","resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",@@ -4686,6 +5070,19 @@"node": ">=8"}},+ "node_modules/pdfjs-dist": {+ "version": "5.6.205",+ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.6.205.tgz",+ "integrity": "sha512-tlUj+2IDa7G1SbvBNN74UHRLJybZDWYom+k6p5KIZl7huBvsA4APi6mKL+zCxd3tLjN5hOOEE9Tv7VdzO88pfg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=20.19.0 || >=22.13.0 || >=24"+ },+ "optionalDependencies": {+ "@napi-rs/canvas": "^0.1.96",+ "node-readable-to-web-readable-stream": "^0.4.2"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -4757,6 +5154,12 @@"node": ">=6"}},+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "license": "MIT"+ },"node_modules/promise-worker-transferable": {"version": "1.0.4","resolved": "https://registry.npmjs.org/promise-worker-transferable/-/promise-worker-transferable-1.0.4.tgz",@@ -4870,6 +5273,21 @@}}},+ "node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },"node_modules/refractor": {"version": "5.0.0","resolved": "https://registry.npmjs.org/refractor/-/refractor-5.0.0.tgz",@@ -5010,6 +5428,12 @@"integrity": "sha512-xQO9vbwBecJRv9EUcQ/y0dzSTJgA7Q6UVN7xp6B81+tBGSLVAK03yJ9NkJaUA7JFD91kbjxRSC/mDnmvXzbHoQ==","license": "MIT"},+ "node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "license": "MIT"+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@ -5026,6 +5450,12 @@"semver": "bin/semver.js"}},+ "node_modules/setimmediate": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",+ "license": "MIT"+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",@@ -5066,6 +5496,12 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/sprintf-js": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",+ "license": "BSD-3-Clause"+ },"node_modules/stats-gl": {"version": "2.4.2","resolved": "https://registry.npmjs.org/stats-gl/-/stats-gl-2.4.2.tgz",@@ -5092,6 +5528,15 @@"integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==","license": "MIT"},+ "node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },"node_modules/stringify-entities": {"version": "4.0.4","resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",@@ -5389,6 +5834,12 @@"typescript": ">=4.8.4 <6.0.0"}},+ "node_modules/underscore": {+ "version": "1.13.8",+ "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz",+ "integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==",+ "license": "MIT"+ },"node_modules/undici-types": {"version": "7.16.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",@@ -5533,6 +5984,12 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },"node_modules/utility-types": {"version": "3.11.0","resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",@@ -5696,6 +6153,15 @@"node": ">=0.10.0"}},+ "node_modules/xmlbuilder": {+ "version": "10.1.1",+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-10.1.1.tgz",+ "integrity": "sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg==",+ "license": "MIT",+ "engines": {+ "node": ">=4.0"+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/package.json b/package.jsonindex 1e270621..14b50bdc 100644--- a/package.json+++ b/package.json@@ -39,6 +39,8 @@"dotenv": "^17.3.1","framer-motion": "^12.38.0","lucide-react": "^1.0.1",+ "mammoth": "^1.12.0",+ "pdfjs-dist": "^5.6.205","react": "^19.2.4","react-dom": "^19.2.4","react-markdown": "^10.1.0",diff --git a/src/api/agents.ts b/src/api/agents.tsnew file mode 100644index 00000000..35103258--- /dev/null+++ b/src/api/agents.ts@@ -0,0 +1,349 @@+import type { Tool, ToolName, ToolCall, AgentLogEntry } from "../types/agents";++export const AGENT_TOOLS: Tool[] = [+ {+ name: "web_search",+ description:+ "Search the web for information. Returns relevant search results with titles, snippets, and URLs.",+ parameters: [+ {+ name: "query",+ type: "string",+ description: "The search query string",+ required: true,+ },+ {+ name: "maxResults",+ type: "number",+ description: "Maximum number of results to return (default: 5)",+ required: false,+ },+ ],+ requiresApproval: false,+ },+ {+ name: "file_read",+ description:+ "Read the contents of a file from the local filesystem within the agent workspace.",+ parameters: [+ {+ name: "path",+ type: "string",+ description: "Relative path to the file within the workspace",+ required: true,+ },+ ],+ requiresApproval: false,+ },+ {+ name: "file_write",+ description:+ "Write content to a file in the agent workspace. Creates the file if it does not exist, overwrites if it does.",+ parameters: [+ {+ name: "path",+ type: "string",+ description: "Relative path to the file within the workspace",+ required: true,+ },+ {+ name: "content",+ type: "string",+ description: "The content to write to the file",+ required: true,+ },+ ],+ requiresApproval: true,+ },+ {+ name: "code_execute",+ description:+ "Execute code in a sandboxed environment. Supports Python and shell commands. Returns stdout, stderr, and exit code.",+ parameters: [+ {+ name: "code",+ type: "string",+ description: "The code to execute",+ required: true,+ },+ {+ name: "language",+ type: "string",+ description: 'Programming language: "python" or "shell" (default: "python")',+ required: false,+ },+ ],+ requiresApproval: true,+ },+ {+ name: "image_generate",+ description:+ "Generate an image from a text description. Delegates to the Create tab for image generation.",+ parameters: [+ {+ name: "prompt",+ type: "string",+ description: "Text description of the image to generate",+ required: true,+ },+ {+ name: "negativePrompt",+ type: "string",+ description: "Things to avoid in the generated image",+ required: false,+ },+ ],+ requiresApproval: false,+ },+];++export function buildReActPrompt(+ goal: string,+ tools: Tool[],+ history: AgentLogEntry[]+): string {+ const toolDescriptions = tools+ .map((t) => {+ const params = t.parameters+ .map(+ (p) =>+ ` - ${p.name} (${p.type}${p.required ? ", required" : ", optional"}): ${p.description}`+ )+ .join("\n");+ return ` ${t.name}: ${t.description}\n Parameters:\n${params}`;+ })+ .join("\n\n");++ const historyText = history+ .map((entry) => {+ switch (entry.type) {+ case "thought":+ return `Thought: ${entry.content}`;+ case "action":+ return `Action: ${entry.content}`;+ case "observation":+ return `Observation: ${entry.content}`;+ case "error":+ return `Error: ${entry.content}`;+ case "user_input":+ return `User: ${entry.content}`;+ default:+ return entry.content;+ }+ })+ .join("\n");++ const codeBlockOpen = "``" + "`json";+ const codeBlockClose = "``" + "`";++ return `You are an autonomous AI agent. Your goal is: ${goal}++You have access to the following tools:++${toolDescriptions}++You must respond with a JSON object in one of these two formats:++To use a tool:+${codeBlockOpen}+{"thought": "your reasoning about what to do next", "action": "tool_name", "args": {"param1": "value1"}}+${codeBlockClose}++To finish the task:+${codeBlockOpen}+{"thought": "your final reasoning", "action": "finish", "answer": "your final answer or summary of what was accomplished"}+${codeBlockClose}++Rules:+- Always include a "thought" explaining your reasoning+- Use exactly one action per response+- Only use tools from the list above+- If a tool returns an error, try a different approach+- When the goal is accomplished, use the "finish" action+- Be concise and efficient++${historyText ? `\nPrevious steps:\n${historyText}\n\nContinue from where you left off.` : "Begin working on the goal now."}`;+}++/**+ * Build a simplified retry prompt when the LLM failed to produce valid JSON.+ */+export function buildJsonRetryPrompt(originalResponse: string): string {+ return `Your previous response could not be parsed as valid JSON. Please respond with ONLY a valid JSON object, no other text.++Your previous (unparsable) response was:+${originalResponse.slice(0, 500)}++Respond with ONLY a JSON object in this exact format:+{"thought": "your reasoning", "action": "tool_name", "args": {"param": "value"}}++Or to finish:+{"thought": "your reasoning", "action": "finish", "answer": "your answer"}`;+}++/**+ * Robustly parse an LLM agent response into structured thought/action/args.+ *+ * Handles:+ * 1. JSON in code blocks+ * 2. Multiple JSON objects (takes the first)+ * 3. Partial/broken JSON via regex fallback+ * 4. No JSON at all (treats as thought with action "continue")+ * 5. Action name casing normalization+ * 6. Alternative field names (thinking, reasoning, tool, arguments, parameters, etc.)+ */+export function parseAgentResponse(response: string): {+ thought: string;+ action: string;+ args?: Record<string, any>;+ answer?: string;+} {+ // 1. Try to find JSON in code blocks first+ const codeBlockMatch = response.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);+ const jsonCandidate = codeBlockMatch ? codeBlockMatch[1] : response;++ // 2. Try to find a JSON object+ const jsonMatch = jsonCandidate.match(/\{[\s\S]*\}/);+ if (jsonMatch) {+ try {+ const parsed = JSON.parse(jsonMatch[0]);+ return {+ thought: parsed.thought || parsed.thinking || parsed.reasoning || "",+ action: (parsed.action || parsed.tool || "continue").toLowerCase().trim(),+ args: parsed.args || parsed.arguments || parsed.parameters || parsed.input || {},+ answer: parsed.answer || parsed.final_answer || parsed.response || undefined,+ };+ } catch {+ // JSON parse failed - if there is a nested object, try the first one+ const firstObjMatch = jsonCandidate.match(/\{[^{}]*\}/);+ if (firstObjMatch && firstObjMatch[0] !== jsonMatch[0]) {+ try {+ const parsed = JSON.parse(firstObjMatch[0]);+ return {+ thought: parsed.thought || parsed.thinking || parsed.reasoning || "",+ action: (parsed.action || parsed.tool || "continue").toLowerCase().trim(),+ args: parsed.args || parsed.arguments || parsed.parameters || parsed.input || {},+ answer: parsed.answer || parsed.final_answer || parsed.response || undefined,+ };+ } catch {+ // Fall through to regex+ }+ }+ }+ }++ // 3. Regex fallback for individual fields+ const thoughtMatch = response.match(/["']?(?:thought|thinking|reasoning)["']?\s*[:=]\s*["']([^"']+)["']/i);+ const actionMatch = response.match(/["']?(?:action|tool)["']?\s*[:=]\s*["']([^"']+)["']/i);+ const answerMatch = response.match(/["']?(?:answer|final_answer|response)["']?\s*[:=]\s*["']([^"']+)["']/i);++ if (actionMatch) {+ return {+ thought: thoughtMatch?.[1] || "",+ action: actionMatch[1].toLowerCase().trim(),+ args: {},+ answer: answerMatch?.[1],+ };+ }++ // 4. Total fallback: treat entire response as a thought+ return {+ thought: response.slice(0, 500),+ action: "continue",+ args: {},+ };+}++export async function executeTool(+ tool: ToolName,+ args: Record<string, any>+): Promise<string> {+ switch (tool) {+ case "code_execute": {+ const res = await fetch("/local-api/execute-code", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ code: args.code,+ language: args.language || "python",+ }),+ });+ if (!res.ok) throw new Error(`code_execute failed: ${res.statusText}`);+ const data = await res.json();+ return `Exit code: ${data.exitCode ?? 0}\nStdout:\n${data.stdout || ""}\nStderr:\n${data.stderr || ""}`;+ }++ case "file_read": {+ const res = await fetch("/local-api/file-read", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ path: args.path }),+ });+ if (!res.ok) throw new Error(`file_read failed: ${res.statusText}`);+ const data = await res.json();+ return data.content || "";+ }++ case "file_write": {+ const res = await fetch("/local-api/file-write", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ path: args.path, content: args.content }),+ });+ if (!res.ok) throw new Error(`file_write failed: ${res.statusText}`);+ const data = await res.json();+ return data.message || "File written successfully";+ }++ case "web_search": {+ const res = await fetch("/local-api/web-search", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: args.query,+ maxResults: args.maxResults || 5,+ }),+ });+ if (!res.ok) throw new Error(`web_search failed: ${res.statusText}`);+ const data = await res.json();+ if (Array.isArray(data.results)) {+ return data.results+ .map(+ (r: any, i: number) =>+ `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`+ )+ .join("\n\n");+ }+ return JSON.stringify(data);+ }++ case "image_generate": {+ return "Image generation delegated to Create tab";+ }++ default:+ throw new Error(`Unknown tool: ${tool}`);+ }+}++export async function chatNonStreaming(+ model: string,+ messages: { role: string; content: string }[]+): Promise<string> {+ const res = await fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model,+ messages,+ stream: false,+ }),+ });++ if (!res.ok) {+ throw new Error(`Chat API error: ${res.status} ${res.statusText}`);+ }++ const data = await res.json();+ return data.message?.content || data.response || "";+}diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex d02b266d..6309b2e7 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -1,61 +1,74 @@-import type { OllamaModel } from '../types/models'+import type { OllamaModel } from "../types/models"export async function listModels(): Promise<OllamaModel[]> {- const res = await fetch('/api/tags')- if (!res.ok) throw new Error('Failed to fetch models')+ const res = await fetch("/api/tags")+ if (!res.ok) throw new Error("Failed to fetch models")const data = await res.json()- return (data.models || []).map((m: any) => ({ ...m, type: 'text' as const }))+ return (data.models || []).map((m: any) => ({ ...m, type: "text" as const }))}export async function showModel(name: string) {- const res = await fetch('/api/show', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ const res = await fetch("/api/show", {+ method: "POST",+ headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),})- if (!res.ok) throw new Error('Failed to show model')+ if (!res.ok) throw new Error("Failed to show model")return res.json()}+export async function getModelContext(name: string): Promise<number> {+ try {+ const info = await showModel(name)+ return (+ info?.model_info?.["general.context_length"] ||+ info?.parameters?.num_ctx ||+ 2048+ )+ } catch {+ return 2048+ }+}+export async function chatStream(model: string,messages: { role: string; content: string }[],options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},signal?: AbortSignal): Promise<Response> {- const res = await fetch('/api/chat', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ const res = await fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },body: JSON.stringify({ model, messages, options, stream: true }),signal,})- if (!res.ok) throw new Error('Failed to start chat')+ if (!res.ok) throw new Error("Failed to start chat")return res}export async function pullModel(name: string, signal?: AbortSignal): Promise<Response> {- const res = await fetch('/api/pull', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ const res = await fetch("/api/pull", {+ method: "POST",+ headers: { "Content-Type": "application/json" },body: JSON.stringify({ name, stream: true }),signal,})- if (!res.ok) throw new Error('Failed to pull model')+ if (!res.ok) throw new Error("Failed to pull model")return res}export async function deleteModel(name: string): Promise<void> {- const res = await fetch('/api/delete', {- method: 'DELETE',- headers: { 'Content-Type': 'application/json' },+ const res = await fetch("/api/delete", {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),})- if (!res.ok) throw new Error('Failed to delete model')+ if (!res.ok) throw new Error("Failed to delete model")}export async function checkConnection(): Promise<boolean> {try {- await fetch('/api/tags')+ await fetch("/api/tags")return true} catch {return falsediff --git a/src/api/rag.ts b/src/api/rag.tsnew file mode 100644index 00000000..55f2d8ef--- /dev/null+++ b/src/api/rag.ts@@ -0,0 +1,192 @@+import { v4 as uuid } from "uuid"+import type { DocumentMeta, TextChunk, RAGContext, VectorSearchResult } from "../types/rag"++export async function extractText(file: File): Promise<string> {+ const ext = file.name.split(".").pop()?.toLowerCase()+ if (ext === "pdf") return extractTextFromPDF(file)+ if (ext === "docx") return extractTextFromDOCX(file)+ return file.text()+}++async function extractTextFromPDF(file: File): Promise<string> {+ const pdfjsLib = await import("pdfjs-dist")+ pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`+ const arrayBuffer = await file.arrayBuffer()+ const doc = await pdfjsLib.getDocument({ data: arrayBuffer }).promise+ const pages: string[] = []+ for (let i = 1; i <= doc.numPages; i++) {+ const page = await doc.getPage(i)+ const textContent = await page.getTextContent()+ pages.push(textContent.items.map((item: any) => item.str).join(" "))+ }+ return pages.join("\n\n")+}++async function extractTextFromDOCX(file: File): Promise<string> {+ const mammoth = await import("mammoth")+ const arrayBuffer = await file.arrayBuffer()+ const result = await mammoth.extractRawText({ arrayBuffer })+ return result.value+}++export function chunkText(+ text: string,+ chunkSize = 500,+ overlap = 50+): string[] {+ const chunks: string[] = []+ const sentences = text.split(/(?<=[.!?])\s+/)+ let current = ""++ for (const sentence of sentences) {+ if ((current + " " + sentence).length > chunkSize && current) {+ chunks.push(current.trim())+ const words = current.split(" ")+ const overlapWords = words.slice(-Math.ceil(overlap / 5))+ current = overlapWords.join(" ") + " " + sentence+ } else {+ current += (current ? " " : "") + sentence+ }+ }+ if (current.trim()) chunks.push(current.trim())+ return chunks.filter((c) => c.length > 20)+}++export async function generateEmbeddings(+ texts: string[],+ model = "nomic-embed-text"+): Promise<number[][]> {+ const res = await fetch("/api/embed", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model, input: texts }),+ })+ if (!res.ok) throw new Error("Embedding failed — is the model pulled?")+ const data = await res.json()+ return data.embeddings+}++function cosineSimilarity(a: number[], b: number[]): number {+ let dot = 0,+ magA = 0,+ magB = 0+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i]+ magA += a[i] * a[i]+ magB += b[i] * b[i]+ }+ return dot / (Math.sqrt(magA) * Math.sqrt(magB) || 1)+}++function bm25Score(query: string, document: string): number {+ const queryTerms = query.toLowerCase().split(/\s+/)+ const docTerms = document.toLowerCase().split(/\s+/)+ const docLen = docTerms.length+ const avgDl = 200+ const k1 = 1.2+ const b = 0.75++ let score = 0+ for (const term of queryTerms) {+ const tf = docTerms.filter((t) => t === term).length+ const idf = Math.log(1 + 1)+ score += idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + (b * docLen) / avgDl)))+ }+ return score+}++function hybridSearch(+ queryEmbedding: number[],+ query: string,+ chunks: TextChunk[],+ topK = 5+): VectorSearchResult[] {+ // Get vector scores+ const vectorResults = chunks.map((chunk) => ({+ chunk,+ vectorScore: cosineSimilarity(queryEmbedding, chunk.embedding),+ }))++ // Get BM25 scores+ const bm25Results = chunks.map((chunk) => ({+ chunk,+ bm25Score: bm25Score(query, chunk.content),+ }))++ // Normalize both score sets to 0-1+ const maxVector = Math.max(...vectorResults.map((r) => r.vectorScore), 0.001)+ const maxBm25 = Math.max(...bm25Results.map((r) => r.bm25Score), 0.001)++ // Combine with 0.7 vector + 0.3 BM25 weighting+ const combined = chunks.map((chunk, i) => ({+ chunk,+ score:+ 0.7 * (vectorResults[i].vectorScore / maxVector) ++ 0.3 * (bm25Results[i].bm25Score / maxBm25),+ }))++ return combined.sort((a, b) => b.score - a.score).slice(0, topK)+}++export function searchVectors(+ queryEmbedding: number[],+ chunks: TextChunk[],+ topK = 5+): VectorSearchResult[] {+ return chunks+ .map((chunk) => ({ chunk, score: cosineSimilarity(queryEmbedding, chunk.embedding) }))+ .sort((a, b) => b.score - a.score)+ .slice(0, topK)+}++export async function indexDocument(+ file: File,+ embeddingModel = "nomic-embed-text"+): Promise<{ meta: DocumentMeta; chunks: TextChunk[] }> {+ const text = await extractText(file)+ const rawChunks = chunkText(text)+ const embeddings = await generateEmbeddings(rawChunks, embeddingModel)++ const docId = uuid()+ const chunks: TextChunk[] = rawChunks.map((content, index) => ({+ id: uuid(),+ documentId: docId,+ content,+ embedding: embeddings[index],+ index,+ }))++ const meta: DocumentMeta = {+ id: docId,+ name: file.name,+ type: file.name.split(".").pop()?.toLowerCase() as "pdf" | "docx" | "txt",+ size: file.size,+ addedAt: Date.now(),+ chunkCount: chunks.length,+ }++ return { meta, chunks }+}++export interface RetrieveResult {+ context: RAGContext+ scoredChunks: VectorSearchResult[]+}++export async function retrieveContext(+ query: string,+ chunks: TextChunk[],+ embeddingModel = "nomic-embed-text",+ topK = 5+): Promise<RetrieveResult> {+ const [queryEmb] = await generateEmbeddings([query], embeddingModel)+ const results = hybridSearch(queryEmb, query, chunks, topK)+ return {+ context: {+ chunks: results.map((r) => r.chunk),+ query,+ documentIds: [...new Set(results.map((r) => r.chunk.documentId))],+ },+ scoredChunks: results,+ }+}diff --git a/src/api/voice.ts b/src/api/voice.tsnew file mode 100644index 00000000..523e3d44--- /dev/null+++ b/src/api/voice.ts@@ -0,0 +1,247 @@+/**+ * Voice API wrapper for Speech Recognition and Speech Synthesis+ */++export function isSpeechRecognitionSupported(): boolean {+ return !!(+ (window as any).SpeechRecognition ||+ (window as any).webkitSpeechRecognition+ );+}++export function isSpeechSynthesisSupported(): boolean {+ return !!window.speechSynthesis;+}++export function getAvailableVoices(): SpeechSynthesisVoice[] {+ if (!isSpeechSynthesisSupported()) return [];++ let voices = window.speechSynthesis.getVoices();++ if (voices.length === 0) {+ // Voices may load asynchronously; trigger the load+ window.speechSynthesis.onvoiceschanged = () => {};+ voices = window.speechSynthesis.getVoices();+ }++ return voices;+}++export function getVoicesAsync(): Promise<SpeechSynthesisVoice[]> {+ return new Promise((resolve) => {+ if (!isSpeechSynthesisSupported()) {+ resolve([]);+ return;+ }++ const voices = window.speechSynthesis.getVoices();+ if (voices.length > 0) {+ resolve(voices);+ return;+ }++ window.speechSynthesis.onvoiceschanged = () => {+ resolve(window.speechSynthesis.getVoices());+ };++ // Fallback timeout in case onvoiceschanged never fires+ setTimeout(() => {+ resolve(window.speechSynthesis.getVoices());+ }, 1000);+ });+}++export function speak(+ text: string,+ voice?: SpeechSynthesisVoice,+ rate: number = 1.0,+ pitch: number = 1.0+): Promise<void> {+ return new Promise((resolve, reject) => {+ if (!isSpeechSynthesisSupported()) {+ reject(new Error("Speech synthesis not supported"));+ return;+ }++ // Cancel any ongoing speech+ window.speechSynthesis.cancel();++ const utterance = new SpeechSynthesisUtterance(text);+ if (voice) utterance.voice = voice;+ utterance.rate = rate;+ utterance.pitch = pitch;++ utterance.onend = () => resolve();+ utterance.onerror = (event) => {+ if (event.error === "canceled" || event.error === "interrupted") {+ resolve();+ } else {+ reject(new Error(`Speech synthesis error: ${event.error}`));+ }+ };++ window.speechSynthesis.speak(utterance);+ });+}++/**+ * Speak text sentence by sentence for streaming-style playback.+ * Each sentence is spoken sequentially, allowing early interruption+ * via stopSpeaking() between sentences.+ */+export async function speakStreaming(+ text: string,+ voice?: SpeechSynthesisVoice,+ rate?: number,+ pitch?: number+): Promise<void> {+ if (!isSpeechSynthesisSupported()) return;+ stopSpeaking();++ // Split into sentences (keeping the punctuation)+ const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];++ for (const sentence of sentences) {+ const trimmed = sentence.trim();+ if (!trimmed) continue;++ // Check if speech was cancelled between sentences+ if (!window.speechSynthesis) return;++ await new Promise<void>((resolve, reject) => {+ const utterance = new SpeechSynthesisUtterance(trimmed);+ if (voice) utterance.voice = voice;+ if (rate !== undefined) utterance.rate = rate;+ if (pitch !== undefined) utterance.pitch = pitch;++ utterance.onend = () => resolve();+ utterance.onerror = (event) => {+ if (event.error === "canceled" || event.error === "interrupted") {+ resolve();+ } else {+ reject(new Error(`Speech synthesis error: ${event.error}`));+ }+ };++ window.speechSynthesis.speak(utterance);+ });+ }+}++export function stopSpeaking(): void {+ if (isSpeechSynthesisSupported()) {+ window.speechSynthesis.cancel();+ }+}++interface AudioRecorder {+ start: () => Promise<void>;+ stop: () => Promise<{ blob: Blob; transcript: string }>;+ isRecording: () => boolean;+}++export function createAudioRecorder(): AudioRecorder {+ let mediaRecorder: MediaRecorder | null = null;+ let recognition: any = null;+ let audioChunks: Blob[] = [];+ let currentTranscript = "";+ let recording = false;++ return {+ start: async () => {+ audioChunks = [];+ currentTranscript = "";++ // Start MediaRecorder for audio blob+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ mediaRecorder = new MediaRecorder(stream, {+ mimeType: MediaRecorder.isTypeSupported("audio/webm;codecs=opus")+ ? "audio/webm;codecs=opus"+ : "audio/webm",+ });++ mediaRecorder.ondataavailable = (event) => {+ if (event.data.size > 0) {+ audioChunks.push(event.data);+ }+ };++ mediaRecorder.start(250); // Collect data every 250ms++ // Start SpeechRecognition in parallel for transcript+ const SpeechRecognition =+ (window as any).SpeechRecognition ||+ (window as any).webkitSpeechRecognition;++ if (SpeechRecognition) {+ recognition = new SpeechRecognition();+ recognition.continuous = true;+ recognition.interimResults = true;+ recognition.lang = "en-US";++ recognition.onresult = (event: any) => {+ let interim = "";+ let final = "";+ for (let i = 0; i < event.results.length; i++) {+ const result = event.results[i];+ if (result.isFinal) {+ final += result[0].transcript;+ } else {+ interim += result[0].transcript;+ }+ }+ currentTranscript = final || interim;+ };++ recognition.onerror = (event: any) => {+ // Silently handle recognition errors — audio blob still captures+ console.warn("SpeechRecognition error:", event.error);+ };++ recognition.start();+ }++ recording = true;+ },++ stop: () => {+ return new Promise((resolve) => {+ recording = false;++ // Stop recognition+ if (recognition) {+ try {+ recognition.stop();+ } catch {+ // Already stopped+ }+ recognition = null;+ }++ // Stop media recorder and collect blob+ if (mediaRecorder && mediaRecorder.state !== "inactive") {+ mediaRecorder.onstop = () => {+ const blob = new Blob(audioChunks, {+ type: mediaRecorder?.mimeType || "audio/webm",+ });++ // Stop all tracks on the stream+ mediaRecorder?.stream.getTracks().forEach((track) => track.stop());+ mediaRecorder = null;++ resolve({ blob, transcript: currentTranscript });+ };++ mediaRecorder.stop();+ } else {+ resolve({+ blob: new Blob([], { type: "audio/webm" }),+ transcript: currentTranscript,+ });+ }+ });+ },++ isRecording: () => recording,+ };+}diff --git a/src/components/agents/AgentLog.tsx b/src/components/agents/AgentLog.tsxnew file mode 100644index 00000000..73b0abc7--- /dev/null+++ b/src/components/agents/AgentLog.tsx@@ -0,0 +1,92 @@+import { useEffect, useRef } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { ScrollText } from 'lucide-react'+import { ToolCallCard } from './ToolCallCard'+import type { AgentLogEntry } from '../../types/agents'++const typeStyles: Record<AgentLogEntry['type'], { badge: string; bg: string; text: string }> = {+ thought: { badge: 'bg-indigo-500/20 text-indigo-300', bg: 'border-l-indigo-500/40', text: 'text-indigo-200' },+ action: { badge: 'bg-amber-500/20 text-amber-300', bg: 'border-l-amber-500/40', text: 'text-amber-200' },+ observation: { badge: 'bg-green-500/20 text-green-300', bg: 'border-l-green-500/40', text: 'text-green-200' },+ error: { badge: 'bg-red-500/20 text-red-300', bg: 'border-l-red-500/40', text: 'text-red-200' },+ user_input: { badge: 'bg-blue-500/20 text-blue-300', bg: 'border-l-blue-500/40', text: 'text-blue-200' },+}++const typeLabels: Record<AgentLogEntry['type'], string> = {+ thought: 'Thought',+ action: 'Action',+ observation: 'Result',+ error: 'Error',+ user_input: 'Goal',+}++function formatTimestamp(ts: number): string {+ const d = new Date(ts)+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })+}++interface Props {+ entries: AgentLogEntry[]+ onApprove?: (toolCallId: string) => void+ onReject?: (toolCallId: string) => void+}++export function AgentLog({ entries, onApprove, onReject }: Props) {+ const scrollRef = useRef<HTMLDivElement>(null)+ const endRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ endRef.current?.scrollIntoView({ behavior: 'smooth' })+ }, [entries.length])++ return (+ <div className="flex flex-col h-full min-h-0">+ <div className="flex items-center gap-1.5 text-[0.75rem] text-gray-400 mb-2 font-medium flex-shrink-0">+ <ScrollText size={13} />+ Agent Log ({entries.length})+ </div>+ <div ref={scrollRef} className="flex-1 overflow-y-auto space-y-1.5 min-h-0 scrollbar-thin pr-1">+ <AnimatePresence initial={false}>+ {entries.map((entry) => {+ const style = typeStyles[entry.type]+ return (+ <motion.div+ key={entry.id}+ initial={{ opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.15 }}+ className={`border-l-2 ${style.bg} pl-3 py-1.5`}+ >+ <div className="flex items-center gap-2 mb-0.5">+ <span className={`text-[0.6rem] px-1.5 py-0.5 rounded-full font-medium ${style.badge}`}>+ {typeLabels[entry.type]}+ </span>+ <span className="text-[0.6rem] text-gray-500">+ {formatTimestamp(entry.timestamp)}+ </span>+ </div>+ <div+ className={`text-[0.8rem] leading-relaxed whitespace-pre-wrap break-words ${+ entry.type === 'observation' ? 'font-mono text-[0.75rem]' : ''+ } ${style.text}`}+ >+ {entry.content}+ </div>+ {entry.toolCall && entry.toolCall.status === 'pending' && onApprove && onReject && (+ <div className="mt-1.5">+ <ToolCallCard+ toolCall={entry.toolCall}+ onApprove={() => onApprove(entry.toolCall!.id)}+ onReject={() => onReject(entry.toolCall!.id)}+ />+ </div>+ )}+ </motion.div>+ )+ })}+ </AnimatePresence>+ <div ref={endRef} />+ </div>+ </div>+ )+}diff --git a/src/components/agents/AgentView.tsx b/src/components/agents/AgentView.tsxnew file mode 100644index 00000000..967999c9--- /dev/null+++ b/src/components/agents/AgentView.tsx@@ -0,0 +1,201 @@+import { useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { Bot, Play, Square, Trash2, Clock } from 'lucide-react'+import { GlowButton } from '../ui/GlowButton'+import { GlassCard } from '../ui/GlassCard'+import { TaskBreakdown } from './TaskBreakdown'+import { AgentLog } from './AgentLog'+import { useAgent } from '../../hooks/useAgent'+import { useAgentStore } from '../../stores/agentStore'+import { useModelStore } from '../../stores/modelStore'+import type { AgentRun } from '../../types/agents'++function formatTime(ts: number): string {+ const d = new Date(ts)+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })+}++function statusColor(status: AgentRun['status']): string {+ switch (status) {+ case 'completed': return 'text-green-400'+ case 'failed': return 'text-red-400'+ case 'executing': case 'planning': return 'text-blue-400'+ case 'paused': return 'text-amber-400'+ default: return 'text-gray-400'+ }+}++function statusLabel(status: AgentRun['status']): string {+ switch (status) {+ case 'completed': return 'Done'+ case 'failed': return 'Failed'+ case 'executing': return 'Running'+ case 'planning': return 'Planning'+ case 'paused': return 'Paused'+ default: return 'Idle'+ }+}++export function AgentView() {+ const [goal, setGoal] = useState('')+ const [selectedModel, setSelectedModel] = useState<string | null>(null)+ const { activeRun, isRunning, startAgent, stopAgent, approveToolCall, rejectToolCall } = useAgent()+ const { runs, setActiveRun, deleteRun } = useAgentStore()+ const { models, activeModel } = useModelStore()++ const currentModel = selectedModel || activeModel || ''++ const handleRun = () => {+ if (!goal.trim() || !currentModel) return+ startAgent(goal.trim(), currentModel)+ setGoal('')+ }++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault()+ handleRun()+ }+ }++ return (+ <div className="flex flex-col h-full gap-3 p-4">+ {/* Goal Input Area */}+ <GlassCard className="flex-shrink-0">+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2 text-[0.8rem] text-gray-400">+ <Bot size={16} />+ <span>Agent Goal</span>+ </div>+ <div className="flex gap-3 items-end">+ <textarea+ value={goal}+ onChange={(e) => setGoal(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Describe what you want the agent to accomplish..."+ className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-[0.85rem] text-white placeholder-gray-500 resize-none focus:outline-none focus:border-white/20 transition-colors min-h-[60px] max-h-[120px]"+ rows={2}+ />+ <div className="flex flex-col gap-2">+ <select+ value={currentModel}+ onChange={(e) => setSelectedModel(e.target.value)}+ className="bg-white/5 border border-white/10 rounded-lg px-2 py-1.5 text-[0.75rem] text-gray-300 focus:outline-none focus:border-white/20 min-w-[140px]"+ >+ {models.map((m) => (+ <option key={m.name} value={m.name} className="bg-[#1a1a1a]">+ {m.name}+ </option>+ ))}+ </select>+ {isRunning ? (+ <GlowButton variant="danger" onClick={stopAgent} className="text-[0.75rem] py-1.5">+ <Square size={14} className="inline mr-1" />+ Stop+ </GlowButton>+ ) : (+ <GlowButton+ onClick={handleRun}+ disabled={!goal.trim() || !currentModel}+ className="text-[0.75rem] py-1.5"+ >+ <Play size={14} className="inline mr-1" />+ Run Agent+ </GlowButton>+ )}+ </div>+ </div>+ </div>+ </GlassCard>++ {/* Main Content */}+ <div className="flex-1 flex gap-3 min-h-0 overflow-hidden">+ {/* Run History Sidebar */}+ <GlassCard className="w-[250px] flex-shrink-0 flex flex-col overflow-hidden">+ <div className="text-[0.75rem] text-gray-400 mb-2 font-medium flex items-center gap-1.5">+ <Clock size={13} />+ Run History+ </div>+ <div className="flex-1 overflow-y-auto space-y-1.5 min-h-0 scrollbar-thin">+ <AnimatePresence>+ {runs.length === 0 && (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ className="text-[0.75rem] text-gray-500 text-center py-6"+ >+ No runs yet+ </motion.div>+ )}+ {[...runs].reverse().map((run) => (+ <motion.div+ key={run.id}+ initial={{ opacity: 0, x: -10 }}+ animate={{ opacity: 1, x: 0 }}+ exit={{ opacity: 0, x: -10 }}+ onClick={() => setActiveRun(run.id)}+ className={`group flex items-start gap-2 p-2 rounded-lg cursor-pointer transition-colors text-[0.75rem] ${+ activeRun?.id === run.id+ ? 'bg-white/10 border border-white/15'+ : 'hover:bg-white/5 border border-transparent'+ }`}+ >+ <div className="flex-1 min-w-0">+ <div className="text-white truncate leading-tight">+ {run.goal.length > 50 ? run.goal.slice(0, 50) + '...' : run.goal}+ </div>+ <div className="flex items-center gap-2 mt-1">+ <span className={`${statusColor(run.status)} text-[0.65rem]`}>+ {statusLabel(run.status)}+ </span>+ <span className="text-gray-500 text-[0.65rem]">+ {formatTime(run.createdAt)}+ </span>+ </div>+ </div>+ <button+ onClick={(e) => { e.stopPropagation(); deleteRun(run.id) }}+ className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-red-400 transition-all p-0.5"+ >+ <Trash2 size={12} />+ </button>+ </motion.div>+ ))}+ </AnimatePresence>+ </div>+ </GlassCard>++ {/* Active Run Details */}+ <div className="flex-1 flex flex-col gap-3 min-h-0 overflow-hidden">+ {activeRun ? (+ <>+ {/* Task Breakdown */}+ <GlassCard className="flex-shrink-0 max-h-[40%] overflow-y-auto">+ <TaskBreakdown tasks={activeRun.tasks} />+ </GlassCard>++ {/* Agent Log */}+ <GlassCard className="flex-1 min-h-0 overflow-hidden flex flex-col">+ <AgentLog+ entries={activeRun.log}+ onApprove={activeRun.status === 'paused' ? (toolCallId) => approveToolCall(activeRun.id, toolCallId) : undefined}+ onReject={activeRun.status === 'paused' ? (toolCallId) => rejectToolCall(activeRun.id, toolCallId) : undefined}+ />+ </GlassCard>+ </>+ ) : (+ <GlassCard className="flex-1 flex items-center justify-center">+ <div className="text-center text-gray-500">+ <Bot size={48} className="mx-auto mb-3 opacity-30" />+ <div className="text-[0.85rem]">No active run</div>+ <div className="text-[0.7rem] mt-1">+ Enter a goal above and click Run Agent to start+ </div>+ </div>+ </GlassCard>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/src/components/agents/TaskBreakdown.tsx b/src/components/agents/TaskBreakdown.tsxnew file mode 100644index 00000000..0f6a0f66--- /dev/null+++ b/src/components/agents/TaskBreakdown.tsx@@ -0,0 +1,118 @@+import { useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { Circle, Loader2, CheckCircle2, XCircle, ChevronDown, ChevronRight, Wrench } from 'lucide-react'+import { ToolCallCard } from './ToolCallCard'+import type { AgentTask, TaskStatus } from '../../types/agents'++function StatusIcon({ status }: { status: TaskStatus }) {+ switch (status) {+ case 'pending':+ return <Circle size={16} className="text-gray-500 flex-shrink-0" />+ case 'running':+ return <Loader2 size={16} className="text-blue-400 animate-spin flex-shrink-0" />+ case 'completed':+ return <CheckCircle2 size={16} className="text-green-400 flex-shrink-0" />+ case 'failed':+ return <XCircle size={16} className="text-red-400 flex-shrink-0" />+ case 'skipped':+ return <Circle size={16} className="text-gray-600 flex-shrink-0" />+ default:+ return <Circle size={16} className="text-gray-500 flex-shrink-0" />+ }+}++interface Props {+ tasks: AgentTask[]+}++export function TaskBreakdown({ tasks }: Props) {+ const [expanded, setExpanded] = useState<Set<string>>(new Set())++ const toggle = (taskId: string) => {+ setExpanded((prev) => {+ const next = new Set(prev)+ if (next.has(taskId)) next.delete(taskId)+ else next.add(taskId)+ return next+ })+ }++ if (tasks.length === 0) {+ return (+ <div className="text-[0.75rem] text-gray-500 py-2">+ <div className="flex items-center gap-1.5 text-gray-400 mb-2 font-medium">+ <Wrench size={13} />+ Tasks+ </div>+ <div className="text-center py-3">No tasks yet — the agent will create them as it works</div>+ </div>+ )+ }++ return (+ <div>+ <div className="flex items-center gap-1.5 text-[0.75rem] text-gray-400 mb-2 font-medium">+ <Wrench size={13} />+ Tasks ({tasks.filter((t) => t.status === 'completed').length}/{tasks.length})+ </div>+ <div className="space-y-1.5">+ <AnimatePresence initial={false}>+ {tasks.map((task) => (+ <motion.div+ key={task.id}+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.2 }}+ >+ <div+ onClick={() => task.toolCalls.length > 0 && toggle(task.id)}+ className={`flex items-start gap-2 p-2 rounded-lg transition-colors text-[0.8rem] ${+ task.toolCalls.length > 0 ? 'cursor-pointer hover:bg-white/5' : ''+ }`}+ >+ <StatusIcon status={task.status} />+ <div className="flex-1 min-w-0">+ <div className={`leading-tight ${task.status === 'completed' ? 'text-gray-400' : 'text-white'}`}>+ {task.description}+ </div>+ {task.reasoning && (+ <div className="text-[0.7rem] text-gray-500 mt-0.5 truncate">+ {task.reasoning}+ </div>+ )}+ </div>+ {task.toolCalls.length > 0 && (+ <div className="flex items-center gap-1 text-[0.65rem] text-gray-500 flex-shrink-0">+ <span>{task.toolCalls.length} call{task.toolCalls.length !== 1 ? 's' : ''}</span>+ {expanded.has(task.id) ? (+ <ChevronDown size={12} />+ ) : (+ <ChevronRight size={12} />+ )}+ </div>+ )}+ </div>++ <AnimatePresence>+ {expanded.has(task.id) && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.15 }}+ className="ml-6 space-y-1.5 pb-1"+ >+ {task.toolCalls.map((tc) => (+ <ToolCallCard key={tc.id} toolCall={tc} />+ ))}+ </motion.div>+ )}+ </AnimatePresence>+ </motion.div>+ ))}+ </AnimatePresence>+ </div>+ </div>+ )+}diff --git a/src/components/agents/ToolCallCard.tsx b/src/components/agents/ToolCallCard.tsxnew file mode 100644index 00000000..35cd4bb6--- /dev/null+++ b/src/components/agents/ToolCallCard.tsx@@ -0,0 +1,101 @@+import { motion } from 'framer-motion'+import { Loader2, Check, X } from 'lucide-react'+import { GlowButton } from '../ui/GlowButton'+import type { ToolCall } from '../../types/agents'++interface Props {+ toolCall: ToolCall+ onApprove?: () => void+ onReject?: () => void+}++function formatArgs(args: Record<string, any>): string {+ try {+ return JSON.stringify(args, null, 2)+ } catch {+ return String(args)+ }+}++export function ToolCallCard({ toolCall, onApprove, onReject }: Props) {+ const isPending = toolCall.status === 'pending'+ const isRunning = toolCall.status === 'running' || toolCall.status === 'approved'+ const isCompleted = toolCall.status === 'completed'+ const isFailed = toolCall.status === 'failed' || toolCall.status === 'rejected'++ return (+ <motion.div+ initial={{ opacity: 0, scale: 0.97 }}+ animate={{ opacity: 1, scale: 1 }}+ transition={{ duration: 0.15 }}+ className="glass-card rounded-lg p-3 dark:bg-[#2a2a2a] border border-white/5"+ >+ {/* Tool Name */}+ <div className="flex items-center justify-between mb-2">+ <span className="text-[0.8rem] font-bold text-white">+ {toolCall.tool}+ </span>+ {isRunning && (+ <Loader2 size={14} className="text-blue-400 animate-spin" />+ )}+ {isCompleted && (+ <span className="text-[0.65rem] text-green-400 bg-green-500/10 px-1.5 py-0.5 rounded-full">+ completed+ </span>+ )}+ {isFailed && (+ <span className="text-[0.65rem] text-red-400 bg-red-500/10 px-1.5 py-0.5 rounded-full">+ {toolCall.status === 'rejected' ? 'rejected' : 'failed'}+ </span>+ )}+ {isPending && (+ <span className="text-[0.65rem] text-amber-400 bg-amber-500/10 px-1.5 py-0.5 rounded-full">+ awaiting approval+ </span>+ )}+ </div>++ {/* Arguments */}+ {Object.keys(toolCall.args).length > 0 && (+ <pre className="text-[0.7rem] font-mono bg-black/30 rounded-md p-2 mb-2 overflow-x-auto text-gray-300 whitespace-pre-wrap break-words max-h-[120px] overflow-y-auto scrollbar-thin">+ {formatArgs(toolCall.args)}+ </pre>+ )}++ {/* Result (completed) */}+ {isCompleted && toolCall.result && (+ <pre className="text-[0.7rem] font-mono bg-green-500/5 border border-green-500/10 rounded-md p-2 overflow-x-auto text-green-300 whitespace-pre-wrap break-words max-h-[150px] overflow-y-auto scrollbar-thin">+ {toolCall.result}+ </pre>+ )}++ {/* Error (failed) */}+ {isFailed && toolCall.error && (+ <pre className="text-[0.7rem] font-mono bg-red-500/5 border border-red-500/10 rounded-md p-2 overflow-x-auto text-red-300 whitespace-pre-wrap break-words max-h-[150px] overflow-y-auto scrollbar-thin">+ {toolCall.error}+ </pre>+ )}++ {/* Duration */}+ {toolCall.duration !== undefined && (+ <div className="text-[0.6rem] text-gray-500 mt-1">+ {(toolCall.duration / 1000).toFixed(1)}s+ </div>+ )}++ {/* Approval Buttons */}+ {isPending && onApprove && onReject && (+ <div className="flex gap-2 mt-2">+ <GlowButton onClick={onApprove} className="text-[0.7rem] py-1 px-3 bg-green-500/10 border-green-500/30 text-green-300 hover:bg-green-500/20">+ <Check size={12} className="inline mr-1" />+ Approve+ </GlowButton>+ <GlowButton variant="danger" onClick={onReject} className="text-[0.7rem] py-1 px-3">+ <X size={12} className="inline mr-1" />+ Reject+ </GlowButton>+ </div>+ )}+ </motion.div>+ )+}diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex 4c624f16..6abf4bcd 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -1,6 +1,8 @@import { useState, useRef, useEffect } from 'react'import { motion } from 'framer-motion'import { Send, Square } from 'lucide-react'+import { VoiceButton } from './VoiceButton'+import { useVoiceStore } from '../../stores/voiceStore'interface Props {onSend: (content: string) => void@@ -39,6 +41,17 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {return (<div className="p-3 border-t border-gray-200 dark:border-white/5"><div className="flex items-end gap-2.5 glass-card rounded-xl px-3 py-2.5">+ <VoiceButton+ onTranscript={(text) => {+ const autoSend = useVoiceStore.getState().autoSendOnTranscribe+ if (autoSend) {+ onSend(text)+ } else {+ setInput(text)+ }+ }}+ disabled={isGenerating}+ /><textarearef={textareaRef}value={input}diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex ceee3bdf..acb109bf 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -1,17 +1,20 @@+import { useState } from 'react'import { useChat } from '../../hooks/useChat'import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'import { MessageList } from './MessageList'import { ChatInput } from './ChatInput'+import { RAGPanel } from './RAGPanel'import { PersonaPanel } from '../personas/PersonaPanel'import { ModelRecommendation } from '../models/ModelRecommendation'-import { Cpu } from 'lucide-react'+import { Cpu, FileText } from 'lucide-react'export function ChatView() {const { sendMessage, stopGeneration, isGenerating } = useChat()const activeConversationId = useChatStore((s) => s.activeConversationId)const activeModel = useModelStore((s) => s.activeModel)const models = useModelStore((s) => s.models)+ const [ragPanelOpen, setRagPanelOpen] = useState(false)// Check if current conversation has user messagesconst conversation = useChatStore((s) => {@@ -51,9 +54,26 @@ export function ChatView() {}return (- <div className="h-full flex flex-col">- <MessageList isGenerating={isGenerating} />- <ChatInput onSend={sendMessage} onStop={stopGeneration} isGenerating={isGenerating} />+ <div className="h-full flex">+ <div className="flex-1 flex flex-col min-w-0">+ <div className="flex items-center justify-end px-3 pt-1">+ <button+ onClick={() => setRagPanelOpen(!ragPanelOpen)}+ className={+ 'p-1.5 rounded-lg transition-colors ' ++ (ragPanelOpen+ ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300'+ : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-400')+ }+ title="Document Chat (RAG)"+ >+ <FileText size={16} />+ </button>+ </div>+ <MessageList isGenerating={isGenerating} />+ <ChatInput onSend={sendMessage} onStop={stopGeneration} isGenerating={isGenerating} />+ </div>+ {ragPanelOpen && <RAGPanel conversationId={activeConversationId} />}</div>)}diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex 5aa44561..3b5338a1 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -3,6 +3,7 @@ import { User, Bot, Copy, Check } from 'lucide-react'import { useState } from 'react'import { MarkdownRenderer } from './MarkdownRenderer'import { ThinkingBlock } from './ThinkingBlock'+import { SpeakerButton } from './SpeakerButton'import type { Message } from '../../types/chat'interface Props {@@ -21,16 +22,18 @@ export function MessageBubble({ message }: Props) {return (<motion.div- className={`flex gap-2.5 px-3 py-2 group ${isUser ? 'flex-row-reverse' : ''}`}+ className={'flex gap-2.5 px-3 py-2 group ' + (isUser ? 'flex-row-reverse' : '')}initial={{ opacity: 0, y: 10 }}animate={{ opacity: 1, y: 0 }}transition={{ duration: 0.2 }}><div- className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${isUser+ className={+ 'w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ' ++ (isUser? 'bg-gray-200 dark:bg-white/10 border border-gray-300 dark:border-white/15'- : 'bg-gray-100 dark:bg-[#2f2f2f] border border-gray-200 dark:border-white/10'- }`}+ : 'bg-gray-100 dark:bg-[#2f2f2f] border border-gray-200 dark:border-white/10')+ }>{isUser ? <User size={13} className="text-gray-600 dark:text-gray-300" /> : <Bot size={13} className="text-gray-500 dark:text-gray-400" />}</div>@@ -43,10 +46,12 @@ export function MessageBubble({ message }: Props) {{/* Main answer bubble */}<div- className={`rounded-xl px-3 py-2 relative ${isUser+ className={+ 'rounded-xl px-3 py-2 relative ' ++ (isUser? 'bg-gray-100 dark:bg-[#2f2f2f] border border-gray-200 dark:border-white/10'- : 'bg-white dark:bg-[#2a2a2a] border border-gray-200 dark:border-white/5'- }`}+ : 'bg-white dark:bg-[#2a2a2a] border border-gray-200 dark:border-white/5')+ }>{isUser ? (<p className="text-[0.8rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{message.content}</p>@@ -56,13 +61,28 @@ export function MessageBubble({ message }: Props) {</div>)}- <button- onClick={handleCopy}- className="absolute top-1.5 right-1.5 p-0.5 rounded opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-white transition-all"- >- {copied ? <Check size={12} /> : <Copy size={12} />}- </button>+ <div className="absolute top-1.5 right-1.5 flex items-center gap-0.5">+ <button+ onClick={handleCopy}+ className="p-0.5 rounded opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-white transition-all"+ >+ {copied ? <Check size={12} /> : <Copy size={12} />}+ </button>+ {!isUser && <SpeakerButton text={message.content} />}+ </div></div>++ {/* Sources section for RAG citations */}+ {!isUser && message.sources && message.sources.length > 0 && (+ <div className="mt-2 pt-2 border-t border-gray-100 dark:border-white/5">+ <p className="text-[0.6rem] text-gray-400 mb-1">Sources:</p>+ {message.sources.map((s, i) => (+ <p key={i} className="text-[0.6rem] text-gray-500 dark:text-gray-400 truncate">+ [{i + 1}] {s.documentName} — {s.preview.slice(0, 60)}...+ </p>+ ))}+ </div>+ )}</div></motion.div>)diff --git a/src/components/chat/RAGPanel.tsx b/src/components/chat/RAGPanel.tsxnew file mode 100644index 00000000..7a29ceb7--- /dev/null+++ b/src/components/chat/RAGPanel.tsx@@ -0,0 +1,347 @@+import { useState, useCallback, useRef } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import {+ FileText,+ File,+ Upload,+ Trash2,+ ToggleLeft,+ ToggleRight,+ Loader2,+ AlertCircle,+ ChevronDown,+ ChevronRight,+ AlertTriangle,+} from 'lucide-react'+import { useRAG } from '../../hooks/useRAG'+import { useRAGStore } from '../../stores/ragStore'++interface Props {+ conversationId: string | null+}++const ACCEPT = '.pdf,.docx,.txt'++function ScoreBadge({ score }: { score: number }) {+ const color =+ score > 0.8+ ? 'bg-green-500/20 text-green-400 border-green-500/30'+ : score > 0.6+ ? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'+ : 'bg-red-500/20 text-red-400 border-red-500/30'++ return (+ <span+ className={'inline-flex items-center px-1.5 py-0.5 rounded text-[0.55rem] font-mono font-medium border ' + color}+ >+ {score.toFixed(3)}+ </span>+ )+}++export function RAGPanel({ conversationId }: Props) {+ const {+ documents,+ isEnabled,+ isIndexing,+ indexingProgress,+ contextWarning,+ uploadDocument,+ removeDocument,+ toggleRAG,+ } = useRAG(conversationId)++ const embeddingModel = useRAGStore((s) => s.embeddingModel)+ const lastRetrievedChunks = useRAGStore((s) => s.lastRetrievedChunks)+ const [isDragging, setIsDragging] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [chunksExpanded, setChunksExpanded] = useState(false)+ const fileInputRef = useRef<HTMLInputElement>(null)++ const handleFiles = useCallback(+ async (files: FileList | File[]) => {+ setError(null)+ const fileArray = Array.from(files)++ for (const file of fileArray) {+ const ext = file.name.split('.').pop()?.toLowerCase()+ if (!ext || !['pdf', 'docx', 'txt'].includes(ext)) {+ setError('Unsupported file type: .' + ext)+ continue+ }+ try {+ await uploadDocument(file)+ } catch (err) {+ setError('Failed to index ' + file.name)+ }+ }+ },+ [uploadDocument]+ )++ const handleDragOver = useCallback((e: React.DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ setIsDragging(true)+ }, [])++ const handleDragLeave = useCallback((e: React.DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ setIsDragging(false)+ }, [])++ const handleDrop = useCallback(+ (e: React.DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ setIsDragging(false)+ if (e.dataTransfer.files.length > 0) {+ handleFiles(e.dataTransfer.files)+ }+ },+ [handleFiles]+ )++ const handleFileSelect = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ if (e.target.files && e.target.files.length > 0) {+ handleFiles(e.target.files)+ e.target.value = ''+ }+ },+ [handleFiles]+ )++ const typeIcon = (type: string) => {+ if (type === 'txt') return <FileText size={14} className="text-blue-400" />+ return <File size={14} className="text-orange-400" />+ }++ const getDocName = (documentId: string): string => {+ for (const doc of documents) {+ if (doc.id === documentId) return doc.name+ }+ return 'Unknown'+ }++ if (!conversationId) return null++ const progressPercent = indexingProgress+ ? String((indexingProgress.current / indexingProgress.total) * 100) + '%'+ : '0%'++ return (+ <motion.div+ className="w-[280px] shrink-0 h-full border-l border-gray-200 dark:border-white/5 bg-white dark:bg-[#2a2a2a] flex flex-col"+ initial={{ width: 0, opacity: 0 }}+ animate={{ width: 280, opacity: 1 }}+ exit={{ width: 0, opacity: 0 }}+ transition={{ duration: 0.2 }}+ >+ {/* Header with toggle */}+ <div className="px-3 py-2.5 border-b border-gray-200 dark:border-white/5 flex items-center justify-between">+ <span className="text-xs font-medium text-gray-700 dark:text-gray-200">Document Chat</span>+ <button+ onClick={toggleRAG}+ className="flex items-center gap-1 text-xs"+ title={isEnabled ? 'Disable RAG' : 'Enable RAG'}+ >+ {isEnabled ? (+ <ToggleRight size={20} className="text-green-500" />+ ) : (+ <ToggleLeft size={20} className="text-gray-400" />+ )}+ </button>+ </div>++ {/* Context window warning */}+ <AnimatePresence>+ {contextWarning && (+ <motion.div+ className="px-3 py-2"+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ >+ <div className="flex items-start gap-1.5 p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/20">+ <AlertTriangle size={12} className="text-yellow-500 shrink-0 mt-0.5" />+ <span className="text-[0.6rem] text-yellow-400 leading-tight">+ {contextWarning}+ </span>+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {/* Drop zone */}+ <div className="px-3 pt-3 pb-1">+ <div+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ onClick={() => fileInputRef.current?.click()}+ className={+ 'border-2 border-dashed rounded-lg p-4 flex flex-col items-center justify-center gap-1.5 cursor-pointer transition-colors ' ++ (isDragging+ ? 'border-green-400 bg-green-50 dark:bg-green-500/10'+ : 'border-gray-200 dark:border-white/10 hover:border-gray-300 dark:hover:border-white/20')+ }+ >+ <Upload size={18} className={isDragging ? 'text-green-500' : 'text-gray-400'} />+ <span className="text-[0.65rem] text-gray-500 dark:text-gray-400 text-center">+ Drop files here or click to upload+ </span>+ <span className="text-[0.55rem] text-gray-400 dark:text-gray-500">+ PDF, DOCX, TXT+ </span>+ </div>+ <input+ ref={fileInputRef}+ type="file"+ accept={ACCEPT}+ multiple+ className="hidden"+ onChange={handleFileSelect}+ />+ </div>++ {/* Indexing progress */}+ <AnimatePresence>+ {isIndexing && indexingProgress && (+ <motion.div+ className="px-3 py-2"+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ >+ <div className="flex items-center gap-1.5 mb-1">+ <Loader2 size={12} className="text-green-500 animate-spin" />+ <span className="text-[0.6rem] text-gray-500 dark:text-gray-400">+ Indexing... {indexingProgress.current}/{indexingProgress.total}+ </span>+ </div>+ <div className="w-full h-1 bg-gray-100 dark:bg-white/5 rounded-full overflow-hidden">+ <motion.div+ className="h-full bg-green-500 rounded-full"+ initial={{ width: 0 }}+ animate={{ width: progressPercent }}+ transition={{ duration: 0.3 }}+ />+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {/* Error */}+ <AnimatePresence>+ {error && (+ <motion.div+ className="px-3 py-1.5"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ >+ <div className="flex items-center gap-1.5 text-[0.6rem] text-red-500">+ <AlertCircle size={11} />+ <span>{error}</span>+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {/* Document list */}+ <div className="flex-1 overflow-y-auto px-3 py-2 space-y-1 scrollbar-thin">+ <AnimatePresence>+ {documents.map((doc) => (+ <motion.div+ key={doc.id}+ className="flex items-center gap-2 px-2 py-1.5 rounded-lg bg-gray-50 dark:bg-white/5 group"+ initial={{ opacity: 0, x: 20 }}+ animate={{ opacity: 1, x: 0 }}+ exit={{ opacity: 0, x: -20 }}+ transition={{ duration: 0.15 }}+ >+ {typeIcon(doc.type)}+ <div className="flex-1 min-w-0">+ <p className="text-[0.65rem] text-gray-700 dark:text-gray-200 truncate">+ {doc.name}+ </p>+ <p className="text-[0.55rem] text-gray-400">+ {doc.chunkCount} chunks+ </p>+ </div>+ <button+ onClick={() => removeDocument(doc.id)}+ className="p-0.5 rounded opacity-0 group-hover:opacity-100 hover:bg-red-100 dark:hover:bg-red-500/15 text-gray-400 hover:text-red-500 transition-all"+ >+ <Trash2 size={12} />+ </button>+ </motion.div>+ ))}+ </AnimatePresence>++ {documents.length === 0 && !isIndexing && (+ <p className="text-[0.6rem] text-gray-400 text-center py-4">+ No documents added yet+ </p>+ )}+ </div>++ {/* Retrieved Chunks section */}+ {lastRetrievedChunks.length > 0 && isEnabled && (+ <div className="border-t border-gray-200 dark:border-white/5">+ <button+ onClick={() => setChunksExpanded(!chunksExpanded)}+ className="w-full px-3 py-2 flex items-center gap-1.5 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors"+ >+ {chunksExpanded ? (+ <ChevronDown size={12} className="text-gray-400" />+ ) : (+ <ChevronRight size={12} className="text-gray-400" />+ )}+ <span className="text-[0.6rem] font-medium text-gray-600 dark:text-gray-300">+ Retrieved Chunks ({lastRetrievedChunks.length})+ </span>+ </button>++ <AnimatePresence>+ {chunksExpanded && (+ <motion.div+ className="px-3 pb-2 space-y-1.5 max-h-[200px] overflow-y-auto scrollbar-thin"+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ >+ {lastRetrievedChunks.map((result, idx) => (+ <div+ key={result.chunk.id + '-' + idx}+ className="p-2 rounded-lg bg-gray-50 dark:bg-white/5 space-y-1"+ >+ <div className="flex items-center gap-1.5">+ <ScoreBadge score={result.score} />+ <span className="text-[0.55rem] text-gray-500 dark:text-gray-400 truncate">+ {getDocName(result.chunk.documentId)}+ </span>+ </div>+ <p className="text-[0.55rem] text-gray-600 dark:text-gray-300 leading-relaxed">+ {result.chunk.content.slice(0, 80)}+ {result.chunk.content.length > 80 ? '...' : ''}+ </p>+ </div>+ ))}+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ )}++ {/* Footer: embedding model */}+ <div className="px-3 py-2 border-t border-gray-200 dark:border-white/5">+ <p className="text-[0.55rem] text-gray-400 dark:text-gray-500 truncate">+ Embedding: {embeddingModel}+ </p>+ </div>+ </motion.div>+ )+}diff --git a/src/components/chat/SpeakerButton.tsx b/src/components/chat/SpeakerButton.tsxnew file mode 100644index 00000000..0ec3106f--- /dev/null+++ b/src/components/chat/SpeakerButton.tsx@@ -0,0 +1,30 @@+import { Volume2, VolumeX } from "lucide-react"+import { useVoice } from "../../hooks/useVoice"++interface Props {+ text: string+}++export function SpeakerButton({ text }: Props) {+ const { isSpeaking, ttsSupported, speakTextStreaming, stopSpeaking } = useVoice()++ if (!ttsSupported) return null++ const handleClick = () => {+ if (isSpeaking) {+ stopSpeaking()+ } else {+ speakTextStreaming(text)+ }+ }++ return (+ <button+ onClick={handleClick}+ className="p-0.5 rounded opacity-0 group-hover:opacity-100 hover:bg-gray-200 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-white transition-all"+ title={isSpeaking ? "Stop speaking" : "Read aloud"}+ >+ {isSpeaking ? <VolumeX size={12} /> : <Volume2 size={12} />}+ </button>+ )+}diff --git a/src/components/chat/VoiceButton.tsx b/src/components/chat/VoiceButton.tsxnew file mode 100644index 00000000..7335df18--- /dev/null+++ b/src/components/chat/VoiceButton.tsx@@ -0,0 +1,63 @@+import { motion } from "framer-motion"+import { Mic, MicOff } from "lucide-react"+import { useVoice } from "../../hooks/useVoice"++interface Props {+ onTranscript: (text: string) => void+ disabled?: boolean+}++export function VoiceButton({ onTranscript, disabled }: Props) {+ const { isRecording, sttSupported, startRecording, stopRecording } = useVoice()++ const handleClick = async () => {+ if (disabled) return++ if (isRecording) {+ const transcript = await stopRecording()+ if (transcript.trim()) {+ onTranscript(transcript.trim())+ }+ } else {+ await startRecording()+ }+ }++ if (!sttSupported) {+ return (+ <div className="relative group/mic">+ <button+ disabled+ className="p-2 rounded-lg text-gray-300 dark:text-gray-600 cursor-not-allowed shrink-0"+ >+ <MicOff size={15} />+ </button>+ <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-800 dark:bg-gray-700 text-white text-[0.6rem] rounded whitespace-nowrap opacity-0 group-hover/mic:opacity-100 transition-opacity pointer-events-none">+ Speech recognition not supported+ </div>+ </div>+ )+ }++ return (+ <motion.button+ onClick={handleClick}+ disabled={disabled}+ className={`p-2 rounded-lg transition-all shrink-0 relative ${+ isRecording+ ? "bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/40 text-red-600 dark:text-red-400"+ : "hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"+ } disabled:opacity-30 disabled:cursor-not-allowed`}+ whileTap={{ scale: 0.9 }}+ >+ {isRecording && (+ <motion.span+ className="absolute inset-0 rounded-lg border-2 border-red-500 dark:border-red-400"+ animate={{ scale: [1, 1.15, 1], opacity: [1, 0.4, 1] }}+ transition={{ duration: 1.2, repeat: Infinity, ease: "easeInOut" }}+ />+ )}+ <Mic size={15} />+ </motion.button>+ )+}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex f0284929..98ea6317 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -5,6 +5,7 @@ import { ChatView } from '../chat/ChatView'import { ModelManager } from '../models/ModelManager'import { SettingsPage } from '../settings/SettingsPage'import { CreateView } from '../create/CreateView'+import { AgentView } from '../agents/AgentView'import { Onboarding } from '../onboarding/Onboarding'import { useUIStore } from '../../stores/uiStore'import { useSettingsStore } from '../../stores/settingsStore'@@ -34,6 +35,7 @@ export function AppShell() {{currentView === 'models' && <ModelManager />}{currentView === 'settings' && <SettingsPage />}{currentView === 'create' && <CreateView />}+ {currentView === 'agents' && <AgentView />}</main></div></div>diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 6a2d3608..16e2aea5 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -1,4 +1,4 @@-import { Menu, Settings, Cpu, Sun, Moon, MessageSquare, Film, Layers } from 'lucide-react'+import { Menu, Settings, Cpu, Sun, Moon, MessageSquare, Film, Layers, Bot } from 'lucide-react'import { useUIStore } from '../../stores/uiStore'import { useSettingsStore } from '../../stores/settingsStore'import { useChatStore } from '../../stores/chatStore'@@ -60,6 +60,13 @@ export function Header() {><Film size={18} /></button>+ <button+ onClick={() => setView('agents')}+ className={`p-2 rounded-lg transition-colors ${currentView === 'agents' ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}+ title="AI Agents"+ >+ <Bot size={18} />+ </button><buttononClick={() => setView('models')}className={`p-2 rounded-lg transition-colors ${currentView === 'models' ? 'bg-blue-100 dark:bg-blue-500/15 text-blue-600 dark:text-blue-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}diff --git a/src/hooks/useAgent.ts b/src/hooks/useAgent.tsnew file mode 100644index 00000000..e6876417--- /dev/null+++ b/src/hooks/useAgent.ts@@ -0,0 +1,433 @@+import { useCallback, useRef } from "react";+import { useAgentStore } from "../stores/agentStore";+import {+ AGENT_TOOLS,+ buildReActPrompt,+ buildJsonRetryPrompt,+ parseAgentResponse,+ executeTool,+ chatNonStreaming,+} from "../api/agents";+import type {+ AgentRun,+ AgentLogEntry,+ ToolCall,+ ToolName,+} from "../types/agents";++function generateId(): string {+ return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;+}++const MAX_CONSECUTIVE_ERRORS = 3;++export function useAgent() {+ const store = useAgentStore();+ const abortRef = useRef<AbortController | null>(null);+ const loopRef = useRef<boolean>(false);++ const activeRun = store.getActiveRun();+ const isRunning =+ activeRun?.status === "planning" || activeRun?.status === "executing";++ const runReActLoop = useCallback(+ async (runId: string, model: string) => {+ const maxIter = store.maxIterations;+ let consecutiveErrors = 0;++ while (loopRef.current) {+ const currentRun = store.runs.find((r) => r.id === runId);+ if (!currentRun || currentRun.currentIteration >= maxIter) {+ store.updateRun(runId, {+ status: currentRun?.currentIteration! >= maxIter ? "failed" : "completed",+ });+ if (currentRun?.currentIteration! >= maxIter) {+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `Max iterations (${maxIter}) reached`,+ timestamp: Date.now(),+ });+ }+ break;+ }++ // Check abort+ if (abortRef.current?.signal.aborted) {+ store.updateRun(runId, { status: "failed" });+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: "Agent run cancelled by user",+ timestamp: Date.now(),+ });+ break;+ }++ // Check consecutive errors - pause and ask user+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {+ store.updateRun(runId, { status: "paused" });+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `${MAX_CONSECUTIVE_ERRORS} consecutive tool errors occurred. Agent paused. Please review the errors and resume or stop the agent.`,+ timestamp: Date.now(),+ });+ break;+ }++ const iteration = currentRun.currentIteration + 1;+ store.updateRun(runId, {+ currentIteration: iteration,+ status: "executing",+ });++ try {+ // Build prompt with full history+ const freshRun = store.runs.find((r) => r.id === runId)!;+ const systemPrompt = buildReActPrompt(+ freshRun.goal,+ AGENT_TOOLS,+ freshRun.log+ );++ // Call LLM+ let response = await chatNonStreaming(model, [+ { role: "system", content: systemPrompt },+ { role: "user", content: freshRun.goal },+ ]);++ // Parse response+ let parsed = parseAgentResponse(response);++ // If parse totally failed (action === 'continue'), retry once with simpler prompt+ if (parsed.action === "continue" && !parsed.answer) {+ store.addLogEntry(runId, {+ id: generateId(),+ type: "thought",+ content: "[JSON parse failed, retrying with simplified prompt]",+ timestamp: Date.now(),+ });++ const retryPrompt = buildJsonRetryPrompt(response);+ const retryResponse = await chatNonStreaming(model, [+ { role: "system", content: systemPrompt },+ { role: "user", content: retryPrompt },+ ]);++ const retryParsed = parseAgentResponse(retryResponse);+ // Only use retry result if it actually produced a real action+ if (retryParsed.action !== "continue") {+ parsed = retryParsed;+ }+ }++ // Log the thought+ store.addLogEntry(runId, {+ id: generateId(),+ type: "thought",+ content: parsed.thought,+ timestamp: Date.now(),+ });++ // Check if finished+ if (parsed.action === "finish") {+ store.addLogEntry(runId, {+ id: generateId(),+ type: "observation",+ content: parsed.answer || "Task completed",+ timestamp: Date.now(),+ });+ store.updateRun(runId, { status: "completed" });+ consecutiveErrors = 0;+ break;+ }++ // If still 'continue' after retry, log and loop again+ if (parsed.action === "continue") {+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: "LLM failed to produce valid JSON after retry. Continuing to next iteration.",+ timestamp: Date.now(),+ });+ consecutiveErrors++;+ continue;+ }++ // Validate tool+ const toolDef = AGENT_TOOLS.find((t) => t.name === parsed.action);+ if (!toolDef) {+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `Unknown tool: ${parsed.action}`,+ timestamp: Date.now(),+ });+ consecutiveErrors++;+ continue;+ }++ const toolCall: ToolCall = {+ id: generateId(),+ tool: parsed.action as ToolName,+ args: parsed.args || {},+ status: "pending",+ timestamp: Date.now(),+ };++ // Log the action+ store.addLogEntry(runId, {+ id: generateId(),+ type: "action",+ content: `${parsed.action}(${JSON.stringify(parsed.args || {})})`,+ timestamp: Date.now(),+ toolCall,+ });++ // Check if tool requires approval+ if (toolDef.requiresApproval) {+ // Create a task for tracking and pause+ const taskId = generateId();+ const task = {+ id: taskId,+ description: `${parsed.action}: ${JSON.stringify(parsed.args || {})}`,+ status: "pending" as const,+ toolCalls: [toolCall],+ reasoning: parsed.thought,+ order: iteration,+ };++ store.updateRun(runId, {+ status: "paused",+ tasks: [...(store.runs.find((r) => r.id === runId)?.tasks || []), task],+ });++ store.addLogEntry(runId, {+ id: generateId(),+ type: "observation",+ content: `Tool "${parsed.action}" requires approval. Agent paused.`,+ timestamp: Date.now(),+ });++ // Break loop - will be resumed via approveToolCall+ break;+ }++ // Execute tool directly+ const startTime = Date.now();+ try {+ const result = await executeTool(+ parsed.action as ToolName,+ parsed.args || {}+ );+ const duration = Date.now() - startTime;++ store.addLogEntry(runId, {+ id: generateId(),+ type: "observation",+ content: result,+ timestamp: Date.now(),+ toolCall: { ...toolCall, status: "completed", result, duration },+ });++ // Tool succeeded, reset consecutive error counter+ consecutiveErrors = 0;+ } catch (err: any) {+ const duration = Date.now() - startTime;+ const errorMsg = err?.message || String(err);++ consecutiveErrors++;++ // Include the error in the log so the LLM sees it in the next iteration+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `Tool "${parsed.action}" failed (attempt ${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}): ${errorMsg}`,+ timestamp: Date.now(),+ toolCall: {+ ...toolCall,+ status: "failed",+ error: errorMsg,+ duration,+ },+ });+ }+ } catch (err: any) {+ const errorMsg = err?.message || String(err);+ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `LLM error: ${errorMsg}`,+ timestamp: Date.now(),+ });+ store.updateRun(runId, { status: "failed" });+ break;+ }+ }++ loopRef.current = false;+ },+ [store]+ );++ const startAgent = useCallback(+ async (goal: string, model: string) => {+ const runId = generateId();+ const run: AgentRun = {+ id: runId,+ goal,+ model,+ status: "planning",+ tasks: [],+ log: [],+ createdAt: Date.now(),+ updatedAt: Date.now(),+ maxIterations: store.maxIterations,+ currentIteration: 0,+ };++ store.createRun(run);++ abortRef.current = new AbortController();+ loopRef.current = true;++ store.addLogEntry(runId, {+ id: generateId(),+ type: "user_input",+ content: goal,+ timestamp: Date.now(),+ });++ // Run the loop (not awaited to avoid blocking)+ runReActLoop(runId, model).catch((err) => {+ console.error("Agent loop crashed:", err);+ store.updateRun(runId, { status: "failed" });+ });+ },+ [store, runReActLoop]+ );++ const stopAgent = useCallback(() => {+ loopRef.current = false;+ if (abortRef.current) {+ abortRef.current.abort();+ abortRef.current = null;+ }+ if (activeRun && isRunning) {+ store.updateRun(activeRun.id, { status: "failed" });+ store.addLogEntry(activeRun.id, {+ id: generateId(),+ type: "error",+ content: "Agent stopped by user",+ timestamp: Date.now(),+ });+ }+ }, [activeRun, isRunning, store]);++ const approveToolCall = useCallback(+ async (runId: string, toolCallId: string) => {+ const run = store.runs.find((r) => r.id === runId);+ if (!run) return;++ // Find the pending tool call+ let pendingToolCall: ToolCall | undefined;+ for (const task of run.tasks) {+ const tc = task.toolCalls.find((tc) => tc.id === toolCallId);+ if (tc) {+ pendingToolCall = tc;+ break;+ }+ }++ if (!pendingToolCall) return;++ store.updateToolCallStatus(runId, toolCallId, "approved");++ // Execute the tool+ const startTime = Date.now();+ try {+ const result = await executeTool(pendingToolCall.tool, pendingToolCall.args);+ const duration = Date.now() - startTime;++ store.updateToolCallStatus(+ runId,+ toolCallId,+ "completed",+ result,+ undefined,+ duration+ );++ store.addLogEntry(runId, {+ id: generateId(),+ type: "observation",+ content: result,+ timestamp: Date.now(),+ });+ } catch (err: any) {+ const duration = Date.now() - startTime;+ const errorMsg = err?.message || String(err);++ store.updateToolCallStatus(+ runId,+ toolCallId,+ "failed",+ undefined,+ errorMsg,+ duration+ );++ store.addLogEntry(runId, {+ id: generateId(),+ type: "error",+ content: `Tool error: ${errorMsg}`,+ timestamp: Date.now(),+ });+ }++ // Resume the ReAct loop+ abortRef.current = new AbortController();+ loopRef.current = true;+ runReActLoop(runId, run.model).catch((err) => {+ console.error("Agent loop crashed after approval:", err);+ store.updateRun(runId, { status: "failed" });+ });+ },+ [store, runReActLoop]+ );++ const rejectToolCall = useCallback(+ async (runId: string, toolCallId: string) => {+ const run = store.runs.find((r) => r.id === runId);+ if (!run) return;++ store.updateToolCallStatus(runId, toolCallId, "rejected");++ store.addLogEntry(runId, {+ id: generateId(),+ type: "observation",+ content: "Tool call rejected by user. Continuing to next iteration.",+ timestamp: Date.now(),+ });++ // Resume the ReAct loop+ abortRef.current = new AbortController();+ loopRef.current = true;+ runReActLoop(runId, run.model).catch((err) => {+ console.error("Agent loop crashed after rejection:", err);+ store.updateRun(runId, { status: "failed" });+ });+ },+ [store, runReActLoop]+ );++ return {+ activeRun,+ isRunning,+ startAgent,+ stopAgent,+ approveToolCall,+ rejectToolCall,+ };+}diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex eff2d35a..c59389b8 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -1,10 +1,12 @@-import { useRef, useState, useCallback } from 'react'-import { v4 as uuid } from 'uuid'-import { chatStream } from '../api/ollama'-import { parseNDJSONStream } from '../api/stream'-import { useChatStore } from '../stores/chatStore'-import { useModelStore } from '../stores/modelStore'-import { useSettingsStore } from '../stores/settingsStore'+import { useRef, useState, useCallback } from "react"+import { v4 as uuid } from "uuid"+import { chatStream } from "../api/ollama"+import { parseNDJSONStream } from "../api/stream"+import { useChatStore } from "../stores/chatStore"+import { useModelStore } from "../stores/modelStore"+import { useSettingsStore } from "../stores/settingsStore"+import { useRAGStore } from "../stores/ragStore"+import { retrieveContext } from "../api/rag"interface ChatChunk {message?: { content: string }@@ -14,8 +16,8 @@ interface ChatChunk {export function useChat() {const [isGenerating, setIsGenerating] = useState(false)const abortRef = useRef<AbortController | null>(null)- const contentRef = useRef('')- const thinkingRef = useRef('')+ const contentRef = useRef("")+ const thinkingRef = useRef("")const isThinkingRef = useRef(false)const sendMessage = useCallback(async (content: string) => {@@ -28,12 +30,12 @@ export function useChat() {let convId = store.activeConversationIdif (!convId) {- convId = store.createConversation(activeModel, persona?.systemPrompt || '')+ convId = store.createConversation(activeModel, persona?.systemPrompt || "")}const userMessage = {id: uuid(),- role: 'user' as const,+ role: "user" as const,content,timestamp: Date.now(),}@@ -41,9 +43,9 @@ export function useChat() {const assistantMessage = {id: uuid(),- role: 'assistant' as const,- content: '',- thinking: '',+ role: "assistant" as const,+ content: "",+ thinking: "",timestamp: Date.now(),}useChatStore.getState().addMessage(convId, assistantMessage)@@ -51,16 +53,47 @@ export function useChat() {const conv = useChatStore.getState().conversations.find((c) => c.id === convId)if (!conv) return+ // RAG context injection+ let systemPrompt = conv.systemPrompt+ const ragState = useRAGStore.getState()+ const ragEnabled = ragState.ragEnabled[convId] ?? false++ if (ragEnabled) {+ const chunks = ragState.getConversationChunks(convId)+ if (chunks.length > 0) {+ try {+ const { context: ragContext, scoredChunks } = await retrieveContext(+ content,+ chunks,+ ragState.embeddingModel+ )++ // Store scored chunks for display in RAGPanel+ ragState.setLastRetrievedChunks(scoredChunks)++ if (ragContext.chunks.length > 0) {+ const contextBlock = ragContext.chunks+ .map((c, i) => `[Source ${i + 1}]\n${c.content}`)+ .join("\n\n")+ const ragPrefix = `Use the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---\n\n`+ systemPrompt = ragPrefix + (systemPrompt || "")+ }+ } catch (err) {+ console.error("RAG retrieval failed, continuing without context:", err)+ }+ }+ }+const messages = [- ...(conv.systemPrompt ? [{ role: 'system', content: conv.systemPrompt }] : []),+ ...(systemPrompt ? [{ role: "system", content: systemPrompt }] : []),...conv.messages.map((m) => ({ role: m.role, content: m.content })),]const abort = new AbortController()abortRef.current = abortsetIsGenerating(true)- contentRef.current = ''- thinkingRef.current = ''+ contentRef.current = ""+ thinkingRef.current = ""isThinkingRef.current = falsetry {@@ -81,20 +114,16 @@ export function useChat() {if (chunk.message?.content) {const text = chunk.message.content- // Parse <think> tags character by character as they stream infor (const char of text) {- // Check if we're entering a <think> blockif (!isThinkingRef.current) {contentRef.current += char- // Check if content ends with <think>- if (contentRef.current.endsWith('<think>')) {+ if (contentRef.current.endsWith("<think>")) {contentRef.current = contentRef.current.slice(0, -7)isThinkingRef.current = true}} else {thinkingRef.current += char- // Check if thinking ends with </think>- if (thinkingRef.current.endsWith('</think>')) {+ if (thinkingRef.current.endsWith("</think>")) {thinkingRef.current = thinkingRef.current.slice(0, -8)isThinkingRef.current = false}@@ -115,18 +144,22 @@ export function useChat() {}}if (chunk.done) {- useChatStore.getState().updateMessageContent(convId!, assistantMessage.id, contentRef.current)+ useChatStore+ .getState()+ .updateMessageContent(convId!, assistantMessage.id, contentRef.current)if (thinkingRef.current) {- useChatStore.getState().updateMessageThinking(convId!, assistantMessage.id, thinkingRef.current)+ useChatStore+ .getState()+ .updateMessageThinking(convId!, assistantMessage.id, thinkingRef.current)}}}} catch (err) {- if ((err as Error).name !== 'AbortError') {+ if ((err as Error).name !== "AbortError") {useChatStore.getState().updateMessageContent(convId!,assistantMessage.id,- contentRef.current + '\n\n⚠️ Error: Connection failed'+ contentRef.current + "\n\n⚠️ Error: Connection failed")}} finally {diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.tsnew file mode 100644index 00000000..0ee6dfff--- /dev/null+++ b/src/hooks/useRAG.ts@@ -0,0 +1,116 @@+import { useCallback, useEffect } from "react"+import { useRAGStore } from "../stores/ragStore"+import { indexDocument, retrieveContext } from "../api/rag"+import { getModelContext } from "../api/ollama"+import { useModelStore } from "../stores/modelStore"+import type { DocumentMeta, RAGContext } from "../types/rag"++export function useRAG(conversationId: string | null) {+ const documents = useRAGStore((s) =>+ conversationId ? s.documents[conversationId] || [] : []+ )+ const isEnabled = useRAGStore((s) =>+ conversationId ? s.ragEnabled[conversationId] ?? false : false+ )+ const isIndexing = useRAGStore((s) => s.isIndexing)+ const indexingProgress = useRAGStore((s) => s.indexingProgress)+ const contextWarning = useRAGStore((s) => s.contextWarning)++ // Check context window when RAG is toggled on or documents change+ useEffect(() => {+ if (!isEnabled || !conversationId) {+ useRAGStore.getState().setContextWarning(null)+ return+ }++ const checkContextWindow = async () => {+ const activeModel = useModelStore.getState().activeModel+ if (!activeModel) return++ try {+ const ctxLen = await getModelContext(activeModel)+ if (ctxLen <= 2048) {+ useRAGStore.getState().setContextWarning(+ `Your model's context window is only ${ctxLen} tokens. RAG works best with 4096+ tokens. Run: ollama run ${activeModel} /set parameter num_ctx 8192`+ )+ } else {+ useRAGStore.getState().setContextWarning(null)+ }+ } catch {+ // Silently fail context check+ }+ }++ checkContextWindow()+ }, [isEnabled, conversationId, documents.length])++ const uploadDocument = useCallback(+ async (file: File): Promise<DocumentMeta | null> => {+ if (!conversationId) return null++ const { embeddingModel, setIndexing, setIndexingProgress, addDocument, addChunks } =+ useRAGStore.getState()++ try {+ setIndexing(true)+ setIndexingProgress({ current: 0, total: 1 })++ const { meta, chunks } = await indexDocument(file, embeddingModel)++ addDocument(conversationId, meta)+ addChunks(chunks)+ setIndexingProgress({ current: 1, total: 1 })++ return meta+ } catch (err) {+ console.error("Failed to index document:", err)+ throw err+ } finally {+ setIndexing(false)+ setIndexingProgress(null)+ }+ },+ [conversationId]+ )++ const removeDoc = useCallback(+ (docId: string) => {+ if (!conversationId) return+ useRAGStore.getState().removeDocument(conversationId, docId)+ },+ [conversationId]+ )++ const toggleRAG = useCallback(() => {+ if (!conversationId) return+ const { ragEnabled, setRagEnabled } = useRAGStore.getState()+ setRagEnabled(conversationId, !ragEnabled[conversationId])+ }, [conversationId])++ const getContextForQuery = useCallback(+ async (query: string): Promise<RAGContext | null> => {+ if (!conversationId) return null++ const { getConversationChunks, embeddingModel } = useRAGStore.getState()+ const chunks = getConversationChunks(conversationId)++ if (chunks.length === 0) return null++ const { context } = await retrieveContext(query, chunks, embeddingModel)+ return context+ },+ [conversationId]+ )++ return {+ documents,+ isEnabled,+ isIndexing,+ indexingProgress,+ contextWarning,+ uploadDocument,+ removeDocument: removeDoc,+ toggleRAG,+ getContextForQuery,+ }+}diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.tsnew file mode 100644index 00000000..05d2b819--- /dev/null+++ b/src/hooks/useVoice.ts@@ -0,0 +1,116 @@+import { useCallback, useRef } from "react";+import { useVoiceStore } from "../stores/voiceStore";+import {+ isSpeechRecognitionSupported,+ isSpeechSynthesisSupported,+ speak,+ speakStreaming,+ stopSpeaking as stopSpeakingApi,+ getVoicesAsync,+ createAudioRecorder,+} from "../api/voice";++export function useVoice() {+ const store = useVoiceStore();+ const recorderRef = useRef<ReturnType<typeof createAudioRecorder> | null>(null);++ const sttSupported = isSpeechRecognitionSupported();+ const ttsSupported = isSpeechSynthesisSupported();++ const startRecording = useCallback(async () => {+ if (recorderRef.current?.isRecording()) return;++ const recorder = createAudioRecorder();+ recorderRef.current = recorder;++ try {+ await recorder.start();+ store.setRecording(true);+ store.setTranscript("");+ } catch (err) {+ console.error("Failed to start recording:", err);+ recorderRef.current = null;+ }+ }, [store]);++ const stopRecording = useCallback(async (): Promise<string> => {+ if (!recorderRef.current) return "";++ try {+ const { transcript } = await recorderRef.current.stop();+ store.setRecording(false);+ store.setTranscript(transcript);+ recorderRef.current = null;+ return transcript;+ } catch (err) {+ console.error("Failed to stop recording:", err);+ store.setRecording(false);+ recorderRef.current = null;+ return "";+ }+ }, [store]);++ const speakText = useCallback(+ async (text: string) => {+ if (!ttsSupported || !store.ttsEnabled) return;++ store.setSpeaking(true);++ try {+ let voice: SpeechSynthesisVoice | undefined;+ if (store.ttsVoice) {+ const voices = await getVoicesAsync();+ voice = voices.find((v) => v.name === store.ttsVoice);+ }++ await speak(text, voice, store.ttsRate, store.ttsPitch);+ } catch (err) {+ console.error("Speech synthesis error:", err);+ } finally {+ store.setSpeaking(false);+ }+ },+ [store, ttsSupported]+ );++ const speakTextStreaming = useCallback(+ async (text: string) => {+ if (!ttsSupported || !store.ttsEnabled) return;++ store.setSpeaking(true);++ try {+ let voice: SpeechSynthesisVoice | undefined;+ if (store.ttsVoice) {+ const voices = await getVoicesAsync();+ voice = voices.find((v) => v.name === store.ttsVoice);+ }++ await speakStreaming(text, voice, store.ttsRate, store.ttsPitch);+ } catch (err) {+ console.error("Speech synthesis streaming error:", err);+ } finally {+ store.setSpeaking(false);+ }+ },+ [store, ttsSupported]+ );++ const stopSpeaking = useCallback(() => {+ stopSpeakingApi();+ store.setSpeaking(false);+ }, [store]);++ return {+ isRecording: store.isRecording,+ isSpeaking: store.isSpeaking,+ transcript: store.transcript,+ sttSupported,+ ttsSupported,+ startRecording,+ stopRecording,+ speakText,+ speakTextStreaming,+ stopSpeaking,+ };+}diff --git a/src/stores/agentStore.ts b/src/stores/agentStore.tsnew file mode 100644index 00000000..6ad352c8--- /dev/null+++ b/src/stores/agentStore.ts@@ -0,0 +1,145 @@+import { create } from "zustand";+import { persist } from "zustand/middleware";+import type {+ AgentRun,+ AgentStatus,+ AgentLogEntry,+ ToolCall,+} from "../types/agents";++interface AgentState {+ runs: AgentRun[];+ activeRunId: string | null;+ maxIterations: number;+ workspacePath: string;++ // Actions+ createRun: (run: AgentRun) => void;+ updateRun: (+ runId: string,+ updates: Partial<+ Pick<+ AgentRun,+ "status" | "tasks" | "currentIteration" | "updatedAt" | "log"+ >+ >+ ) => void;+ addLogEntry: (runId: string, entry: AgentLogEntry) => void;+ addToolCall: (runId: string, taskId: string, toolCall: ToolCall) => void;+ updateToolCallStatus: (+ runId: string,+ toolCallId: string,+ status: ToolCall["status"],+ result?: string,+ error?: string,+ duration?: number+ ) => void;+ setActiveRun: (runId: string | null) => void;+ deleteRun: (runId: string) => void;+ getActiveRun: () => AgentRun | undefined;+}++export const useAgentStore = create<AgentState>()(+ persist(+ (set, get) => ({+ runs: [],+ activeRunId: null,+ maxIterations: 20,+ workspacePath: "~/agent-workspace",++ createRun: (run) =>+ set((state) => ({+ runs: [...state.runs, run],+ activeRunId: run.id,+ })),++ updateRun: (runId, updates) =>+ set((state) => ({+ runs: state.runs.map((r) =>+ r.id === runId+ ? { ...r, ...updates, updatedAt: Date.now() }+ : r+ ),+ })),++ addLogEntry: (runId, entry) =>+ set((state) => ({+ runs: state.runs.map((r) =>+ r.id === runId+ ? {+ ...r,+ log: [...r.log, entry],+ updatedAt: Date.now(),+ }+ : r+ ),+ })),++ addToolCall: (runId, taskId, toolCall) =>+ set((state) => ({+ runs: state.runs.map((r) =>+ r.id === runId+ ? {+ ...r,+ tasks: r.tasks.map((t) =>+ t.id === taskId+ ? { ...t, toolCalls: [...t.toolCalls, toolCall] }+ : t+ ),+ updatedAt: Date.now(),+ }+ : r+ ),+ })),++ updateToolCallStatus: (runId, toolCallId, status, result, error, duration) =>+ set((state) => ({+ runs: state.runs.map((r) =>+ r.id === runId+ ? {+ ...r,+ tasks: r.tasks.map((t) => ({+ ...t,+ toolCalls: t.toolCalls.map((tc) =>+ tc.id === toolCallId+ ? {+ ...tc,+ status,+ ...(result !== undefined && { result }),+ ...(error !== undefined && { error }),+ ...(duration !== undefined && { duration }),+ }+ : tc+ ),+ })),+ updatedAt: Date.now(),+ }+ : r+ ),+ })),++ setActiveRun: (runId) => set({ activeRunId: runId }),++ deleteRun: (runId) =>+ set((state) => ({+ runs: state.runs.filter((r) => r.id !== runId),+ activeRunId:+ state.activeRunId === runId ? null : state.activeRunId,+ })),++ getActiveRun: () => {+ const state = get();+ return state.runs.find((r) => r.id === state.activeRunId);+ },+ }),+ {+ name: "locally-uncensored-agent",+ partialize: (state) => ({+ runs: state.runs,+ activeRunId: state.activeRunId,+ maxIterations: state.maxIterations,+ workspacePath: state.workspacePath,+ }),+ }+ )+);diff --git a/src/stores/ragStore.ts b/src/stores/ragStore.tsnew file mode 100644index 00000000..d8c8035a--- /dev/null+++ b/src/stores/ragStore.ts@@ -0,0 +1,106 @@+import { create } from "zustand"+import { persist } from "zustand/middleware"+import type { DocumentMeta, TextChunk, VectorSearchResult } from "../types/rag"++interface RAGState {+ documents: Record<string, DocumentMeta[]>+ chunks: TextChunk[]+ ragEnabled: Record<string, boolean>+ embeddingModel: string+ isIndexing: boolean+ indexingProgress: { current: number; total: number } | null+ lastRetrievedChunks: { chunk: TextChunk; score: number }[]+ contextWarning: string | null++ addDocument: (conversationId: string, meta: DocumentMeta) => void+ removeDocument: (conversationId: string, docId: string) => void+ addChunks: (newChunks: TextChunk[]) => void+ getConversationChunks: (conversationId: string) => TextChunk[]+ setRagEnabled: (conversationId: string, enabled: boolean) => void+ setEmbeddingModel: (model: string) => void+ setIndexing: (indexing: boolean) => void+ setIndexingProgress: (progress: { current: number; total: number } | null) => void+ clearConversationDocs: (conversationId: string) => void+ setLastRetrievedChunks: (chunks: { chunk: TextChunk; score: number }[]) => void+ setContextWarning: (warning: string | null) => void+}++export const useRAGStore = create<RAGState>()(+ persist(+ (set, get) => ({+ documents: {},+ chunks: [],+ ragEnabled: {},+ embeddingModel: "nomic-embed-text",+ isIndexing: false,+ indexingProgress: null,+ lastRetrievedChunks: [],+ contextWarning: null,++ addDocument: (conversationId, meta) =>+ set((state) => ({+ documents: {+ ...state.documents,+ [conversationId]: [...(state.documents[conversationId] || []), meta],+ },+ })),++ removeDocument: (conversationId, docId) =>+ set((state) => ({+ documents: {+ ...state.documents,+ [conversationId]: (state.documents[conversationId] || []).filter(+ (d) => d.id !== docId+ ),+ },+ chunks: state.chunks.filter((c) => c.documentId !== docId),+ })),++ addChunks: (newChunks) =>+ set((state) => ({+ chunks: [...state.chunks, ...newChunks],+ })),++ getConversationChunks: (conversationId) => {+ const { documents, chunks } = get()+ const docIds = (documents[conversationId] || []).map((d) => d.id)+ return chunks.filter((c) => docIds.includes(c.documentId))+ },++ setRagEnabled: (conversationId, enabled) =>+ set((state) => ({+ ragEnabled: { ...state.ragEnabled, [conversationId]: enabled },+ })),++ setEmbeddingModel: (model) => set({ embeddingModel: model }),++ setIndexing: (indexing) => set({ isIndexing: indexing }),++ setIndexingProgress: (progress) => set({ indexingProgress: progress }),++ clearConversationDocs: (conversationId) =>+ set((state) => {+ const docIds = (state.documents[conversationId] || []).map((d) => d.id)+ return {+ documents: {+ ...state.documents,+ [conversationId]: [],+ },+ chunks: state.chunks.filter((c) => !docIds.includes(c.documentId)),+ }+ }),++ setLastRetrievedChunks: (chunks) => set({ lastRetrievedChunks: chunks }),++ setContextWarning: (warning) => set({ contextWarning: warning }),+ }),+ {+ name: "rag-store",+ partialize: (state) => ({+ documents: state.documents,+ ragEnabled: state.ragEnabled,+ embeddingModel: state.embeddingModel,+ }),+ }+ )+)diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.tsindex 33a84832..59a68461 100644--- a/src/stores/uiStore.ts+++ b/src/stores/uiStore.ts@@ -1,6 +1,6 @@import { create } from 'zustand'-export type View = 'chat' | 'models' | 'settings' | 'create'+export type View = 'chat' | 'models' | 'settings' | 'create' | 'agents'interface UIState {currentView: Viewdiff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.tsnew file mode 100644index 00000000..98e04159--- /dev/null+++ b/src/stores/voiceStore.ts@@ -0,0 +1,77 @@+import { create } from "zustand";+import { persist } from "zustand/middleware";++interface VoiceState {+ // Transient state (not persisted)+ isRecording: boolean;+ isSpeaking: boolean;+ transcript: string;++ // Persisted settings+ sttEnabled: boolean;+ ttsEnabled: boolean;+ ttsVoice: string;+ ttsRate: number;+ ttsPitch: number;+ autoSendOnTranscribe: boolean;++ // Actions+ setRecording: (recording: boolean) => void;+ setSpeaking: (speaking: boolean) => void;+ setTranscript: (transcript: string) => void;+ updateVoiceSettings: (+ settings: Partial<{+ sttEnabled: boolean;+ ttsEnabled: boolean;+ ttsVoice: string;+ ttsRate: number;+ ttsPitch: number;+ autoSendOnTranscribe: boolean;+ }>+ ) => void;+ resetTransient: () => void;+}++export const useVoiceStore = create<VoiceState>()(+ persist(+ (set) => ({+ // Transient state+ isRecording: false,+ isSpeaking: false,+ transcript: "",++ // Persisted settings+ sttEnabled: true,+ ttsEnabled: false,+ ttsVoice: "",+ ttsRate: 1.0,+ ttsPitch: 1.0,+ autoSendOnTranscribe: true,++ // Actions+ setRecording: (recording) => set({ isRecording: recording }),+ setSpeaking: (speaking) => set({ isSpeaking: speaking }),+ setTranscript: (transcript) => set({ transcript }),++ updateVoiceSettings: (settings) => set((state) => ({ ...state, ...settings })),++ resetTransient: () =>+ set({+ isRecording: false,+ isSpeaking: false,+ transcript: "",+ }),+ }),+ {+ name: "locally-uncensored-voice",+ partialize: (state) => ({+ sttEnabled: state.sttEnabled,+ ttsEnabled: state.ttsEnabled,+ ttsVoice: state.ttsVoice,+ ttsRate: state.ttsRate,+ ttsPitch: state.ttsPitch,+ autoSendOnTranscribe: state.autoSendOnTranscribe,+ }),+ }+ )+);diff --git a/src/types/agents.ts b/src/types/agents.tsnew file mode 100644index 00000000..16aaa4f5--- /dev/null+++ b/src/types/agents.ts@@ -0,0 +1,82 @@+export type AgentStatus =+ | "idle"+ | "planning"+ | "executing"+ | "paused"+ | "completed"+ | "failed";++export type TaskStatus =+ | "pending"+ | "running"+ | "completed"+ | "failed"+ | "skipped";++export type ToolName =+ | "web_search"+ | "file_read"+ | "file_write"+ | "code_execute"+ | "image_generate";++export interface ToolParameter {+ name: string;+ type: string;+ description: string;+ required: boolean;+}++export interface Tool {+ name: ToolName;+ description: string;+ parameters: ToolParameter[];+ requiresApproval: boolean;+}++export interface ToolCall {+ id: string;+ tool: ToolName;+ args: Record<string, any>;+ result?: string;+ error?: string;+ status:+ | "pending"+ | "running"+ | "completed"+ | "failed"+ | "approved"+ | "rejected";+ timestamp: number;+ duration?: number;+}++export interface AgentTask {+ id: string;+ description: string;+ status: TaskStatus;+ toolCalls: ToolCall[];+ reasoning?: string;+ order: number;+}++export interface AgentLogEntry {+ id: string;+ type: "thought" | "action" | "observation" | "error" | "user_input";+ content: string;+ timestamp: number;+ toolCall?: ToolCall;+}++export interface AgentRun {+ id: string;+ goal: string;+ model: string;+ status: AgentStatus;+ tasks: AgentTask[];+ log: AgentLogEntry[];+ createdAt: number;+ updatedAt: number;+ maxIterations: number;+ currentIteration: number;+}diff --git a/src/types/chat.ts b/src/types/chat.tsindex 322a32e3..6194363f 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -6,6 +6,7 @@ export interface Message {content: stringthinking?: stringtimestamp: number+ sources?: { documentName: string; chunkIndex: number; preview: string }[]}export interface Conversation {diff --git a/src/types/rag.ts b/src/types/rag.tsnew file mode 100644index 00000000..cdb615bb--- /dev/null+++ b/src/types/rag.ts@@ -0,0 +1,27 @@+export interface DocumentMeta {+ id: string+ name: string+ type: 'pdf' | 'docx' | 'txt'+ size: number+ addedAt: number+ chunkCount: number+}++export interface TextChunk {+ id: string+ documentId: string+ content: string+ embedding: number[]+ index: number+}++export interface RAGContext {+ chunks: TextChunk[]+ query: string+ documentIds: string[]+}++export interface VectorSearchResult {+ chunk: TextChunk+ score: number+}diff --git a/src/types/settings.ts b/src/types/settings.tsindex 31db7596..36cfb122 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -15,3 +15,7 @@ export interface Persona {systemPrompt: stringisBuiltIn: boolean}++// Voice settings (sttEnabled, ttsEnabled, ttsVoice, ttsRate, ttsPitch,+// autoSendOnTranscribe) are managed in src/stores/voiceStore.ts via+// the dedicated Zustand voice store with persistence.diff --git a/vite.config.ts b/vite.config.tsindex 7c881a5d..f048ff33 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -496,6 +496,211 @@ function comfyLauncher(): Plugin {processAlive,}))})++ // --- Agent Tool Endpoints ---++ // API: Execute Python code+ server.middlewares.use('/local-api/execute-code', (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 { code, timeout: timeoutMs } = JSON.parse(body)+ if (!code) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Missing code parameter' }))+ return+ }++ const os = require('os')+ const fs = require('fs')+ const tmpDir = join(os.tmpdir(), 'agent-exec-' + Date.now())+ fs.mkdirSync(tmpDir, { recursive: true })++ const limit = timeoutMs || 30000+ let stdout = ''+ let stderr = ''+ let killed = false++ const proc = spawn('python3', ['-c', code], {+ cwd: tmpDir,+ stdio: ['ignore', 'pipe', 'pipe'],+ shell: false,+ })++ const timer = setTimeout(() => {+ killed = true+ try { proc.kill('SIGKILL') } catch { /* already dead */ }+ }, limit)++ proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString() })+ proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString() })++ proc.on('exit', (exitCode) => {+ clearTimeout(timer)+ try { fs.rmSync(tmpDir, { recursive: true, force: true }) } catch { /* ignore */ }++ if (killed) {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ stdout: '', stderr: 'Execution timed out', exitCode: 124 }))+ return+ }+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ stdout, stderr, exitCode: exitCode ?? 1 }))+ })++ proc.on('error', (err: Error) => {+ clearTimeout(timer)+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ stdout: '', stderr: err.message, exitCode: 1 }))+ })+ } catch (err) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: String(err) }))+ }+ })+ })++ // API: Read file from agent workspace+ server.middlewares.use('/local-api/file-read', (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 { path: filePath } = JSON.parse(body)+ if (!filePath || filePath.includes('..')) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Invalid path' }))+ return+ }++ const os = require('os')+ const fs = require('fs')+ const workspaceDir = join(os.homedir(), 'agent-workspace')+ if (!existsSync(workspaceDir)) mkdirSync(workspaceDir, { recursive: true })++ const resolvedPath = join(workspaceDir, filePath)+ try {+ const content = fs.readFileSync(resolvedPath, 'utf8')+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ content }))+ } catch {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'File not found' }))+ }+ } catch (err) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: String(err) }))+ }+ })+ })++ // API: Write file to agent workspace+ server.middlewares.use('/local-api/file-write', (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 { path: filePath, content } = JSON.parse(body)+ if (!filePath || filePath.includes('..')) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Invalid path' }))+ return+ }+ if (content === undefined) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Missing content parameter' }))+ return+ }++ const os = require('os')+ const fs = require('fs')+ const workspaceDir = join(os.homedir(), 'agent-workspace')+ const resolvedPath = join(workspaceDir, filePath)+ const parentDir = resolve(resolvedPath, '..')+ if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })++ fs.writeFileSync(resolvedPath, content, 'utf8')+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'ok', path: resolvedPath }))+ } catch (err) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: String(err) }))+ }+ })+ })++ // API: Web search via DuckDuckGo lite+ 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)+ if (!query) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Missing query parameter' }))+ return+ }++ const maxResults = count || 5+ const searchUrl = 'https://lite.duckduckgo.com/lite/?q=' + encodeURIComponent(query)++ https.get(searchUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.1' } }, (response) => {+ let html = ''+ response.on('data', (chunk: Buffer) => { html += chunk.toString() })+ response.on('end', () => {+ try {+ const results: { title: string; url: string; snippet: string }[] = []++ // Parse DuckDuckGo lite HTML results+ const linkRegex = /<a[^>]+class="result-link"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi+ const snippetRegex = /<td[^>]+class="result-snippet"[^>]*>([\s\S]*?)<\/td>/gi++ const links: { url: string; title: string }[] = []+ let linkMatch+ while ((linkMatch = linkRegex.exec(html)) !== null) {+ const linkUrl = linkMatch[1].replace(/&/g, '&')+ const title = linkMatch[2].replace(/<[^>]*>/g, '').trim()+ if (linkUrl && title) links.push({ url: linkUrl, title })+ }++ const snippets: string[] = []+ let snippetMatch+ while ((snippetMatch = snippetRegex.exec(html)) !== null) {+ snippets.push(snippetMatch[1].replace(/<[^>]*>/g, '').trim())+ }++ for (let i = 0; i < Math.min(links.length, maxResults); i++) {+ results.push({+ title: links[i].title,+ url: links[i].url,+ snippet: snippets[i] || '',+ })+ }++ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ results }))+ } catch (parseErr) {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ results: [], error: 'Failed to parse results' }))+ }+ })+ }).on('error', (err) => {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ results: [], error: err.message }))+ })+ } catch (err) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: String(err) }))+ }+ })+ })+},}}