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
fix: RAG document chat fully working — IndexedDB persistence, React 19 compat, better UX
PurpleDoubleD448ab57b9481
diff --git a/src/api/rag.ts b/src/api/rag.tsindex 34080a5a..0d352ca2 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -4,9 +4,15 @@ import { ollamaUrl, localFetch } from "./backend"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()+ try {+ if (ext === "pdf") return await extractTextFromPDF(file)+ if (ext === "docx") return await extractTextFromDOCX(file)+ return await file.text()+ } catch (err) {+ throw new Error(+ `Failed to extract text from "${file.name}": ${err instanceof Error ? err.message : String(err)}`+ )+ }}async function extractTextFromPDF(file: File): Promise<string> {@@ -58,12 +64,39 @@ export async function generateEmbeddings(texts: string[],model = "nomic-embed-text"): Promise<number[][]> {- const res = await localFetch(ollamaUrl("/embed"), {- method: "POST",- body: JSON.stringify({ model, input: texts }),- })- if (!res.ok) throw new Error("Embedding failed — is the model pulled?")+ let res: Response+ try {+ res = await localFetch(ollamaUrl("/embed"), {+ method: "POST",+ body: JSON.stringify({ model, input: texts }),+ })+ } catch (err) {+ throw new Error(+ `Cannot reach Ollama. Is it running? (${err instanceof Error ? err.message : String(err)})`+ )+ }++ if (!res.ok) {+ let detail = ""+ try {+ const body = await res.json()+ detail = body?.error || ""+ } catch { /* ignore parse errors */ }++ if (res.status === 404 || detail.includes("not found")) {+ throw new Error(+ `Embedding model "${model}" not found. Run: ollama pull ${model}`+ )+ }+ throw new Error(+ `Embedding failed (HTTP ${res.status}): ${detail || "Unknown error"}`+ )+ }+const data = await res.json()+ if (!data.embeddings || !Array.isArray(data.embeddings)) {+ throw new Error("Unexpected response from Ollama /embed endpoint")+ }return data.embeddings}diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 35b42abc..943419a7 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -3,11 +3,13 @@ import { AnimatePresence } from 'framer-motion'import { useChat } from '../../hooks/useChat'import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'+import { useRAGStore } from '../../stores/ragStore'import { MessageList } from './MessageList'import { ChatInput } from './ChatInput'import { RAGPanel } from './RAGPanel'import { PersonaPanel } from '../personas/PersonaPanel'import { ModelRecommendation } from '../models/ModelRecommendation'+import { ErrorBoundary } from '../ui/ErrorBoundary'import { Cpu, FileText } from 'lucide-react'export function ChatView() {@@ -17,6 +19,14 @@ export function ChatView() {const models = useModelStore((s) => s.models)const [ragPanelOpen, setRagPanelOpen] = useState(false)+ // Document count badge for RAG button+ const docCount = useRAGStore((s) =>+ activeConversationId ? (s.documents[activeConversationId] || []).length : 0+ )+ const ragEnabled = useRAGStore((s) =>+ activeConversationId ? s.ragEnabled[activeConversationId] ?? false : false+ )+// Check if current conversation has user messagesconst conversation = useChatStore((s) => {if (!s.activeConversationId) return undefined@@ -61,21 +71,36 @@ export function ChatView() {<buttononClick={() => setRagPanelOpen(!ragPanelOpen)}className={- 'p-1.5 rounded-lg transition-colors ' +- (ragPanelOpen+ 'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg transition-colors text-xs ' ++ (ragPanelOpen || ragEnabled? '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} />+ <FileText size={14} />+ <span className="font-medium">Documents</span>+ {docCount > 0 && (+ <span className={+ 'min-w-[18px] h-[18px] flex items-center justify-center rounded-full text-[0.6rem] font-bold ' ++ (ragEnabled+ ? 'bg-green-500 text-white'+ : 'bg-gray-200 dark:bg-white/15 text-gray-600 dark:text-gray-300')+ }>+ {docCount}+ </span>+ )}</button></div><MessageList isGenerating={isGenerating} /><ChatInput onSend={sendMessage} onStop={stopGeneration} isGenerating={isGenerating} /></div><AnimatePresence>- {ragPanelOpen && <RAGPanel conversationId={activeConversationId} />}+ {ragPanelOpen && (+ <ErrorBoundary fallbackClassName="w-[280px] shrink-0 h-full border-l border-white/5 bg-[#2a2a2a] flex flex-col items-center justify-center p-6 gap-3">+ <RAGPanel conversationId={activeConversationId} />+ </ErrorBoundary>+ )}</AnimatePresence></div>)diff --git a/src/components/chat/RAGPanel.tsx b/src/components/chat/RAGPanel.tsxindex cef918f9..da313671 100644--- a/src/components/chat/RAGPanel.tsx+++ b/src/components/chat/RAGPanel.tsx@@ -15,6 +15,7 @@ import {Download,MessageSquarePlus,} from 'lucide-react'+import { useShallow } from 'zustand/react/shallow'import { useRAG } from '../../hooks/useRAG'import { useRAGStore } from '../../stores/ragStore'@@ -74,12 +75,17 @@ function RAGPanelInner({ conversationId }: { conversationId: string }) {const indexingProgress = rag.indexingProgress ?? nullconst contextWarning = rag.contextWarning ?? nullconst pullingEmbeddingModel = rag.pullingEmbeddingModel ?? false+ const chunksLoaded = rag.chunksLoaded ?? falseconst uploadDocument = rag.uploadDocumentconst removeDocument = rag.removeDocumentconst toggleRAG = rag.toggleRAG- const embeddingModelReactive = useRAGStore((s) => s.embeddingModel)- const lastRetrievedChunksReactive = useRAGStore((s) => s.lastRetrievedChunks)+ const { embeddingModelReactive, lastRetrievedChunksReactive } = useRAGStore(+ useShallow((s) => ({+ embeddingModelReactive: s.embeddingModel,+ lastRetrievedChunksReactive: s.lastRetrievedChunks,+ }))+ )const [isDragging, setIsDragging] = useState(false)const [error, setError] = useState<string | null>(null)@@ -100,7 +106,8 @@ function RAGPanelInner({ conversationId }: { conversationId: string }) {try {await uploadDocument(file)} catch (err) {- setError('Failed to index ' + file.name)+ const msg = err instanceof Error ? err.message : String(err)+ setError(msg)}}},@@ -222,6 +229,27 @@ function RAGPanelInner({ conversationId }: { conversationId: string }) {)}</AnimatePresence>+ {/* RAG explanation when disabled */}+ {!isEnabled && documents.length === 0 && (+ <div className="px-3 pt-2">+ <div className="p-2 rounded-lg bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10">+ <p className="text-[0.6rem] text-gray-500 dark:text-gray-400 leading-relaxed">+ Upload documents and enable the toggle to chat with your files. The AI will use document content to answer your questions.+ </p>+ </div>+ </div>+ )}++ {/* Loading chunks from IndexedDB */}+ {documents.length > 0 && !chunksLoaded && (+ <div className="px-3 py-2">+ <div className="flex items-center gap-1.5 p-2 rounded-lg bg-blue-500/10 border border-blue-500/20">+ <Loader2 size={12} className="text-blue-400 animate-spin" />+ <span className="text-[0.6rem] text-blue-400">Loading indexed documents...</span>+ </div>+ </div>+ )}+{/* Drop zone */}<div className="px-3 pt-3 pb-1"><divdiff --git a/src/components/ui/ErrorBoundary.tsx b/src/components/ui/ErrorBoundary.tsxnew file mode 100644index 00000000..3753c721--- /dev/null+++ b/src/components/ui/ErrorBoundary.tsx@@ -0,0 +1,51 @@+import { Component, type ReactNode } from 'react'+import { AlertCircle, RefreshCw } from 'lucide-react'++interface Props {+ children: ReactNode+ fallbackClassName?: string+}++interface State {+ hasError: boolean+ error: Error | null+}++export class ErrorBoundary extends Component<Props, State> {+ state: State = { hasError: false, error: null }++ static getDerivedStateFromError(error: Error): State {+ return { hasError: true, error }+ }++ componentDidCatch(error: Error, info: React.ErrorInfo) {+ console.error('ErrorBoundary caught:', error, info.componentStack)+ }++ handleReset = () => {+ this.setState({ hasError: false, error: null })+ }++ render() {+ if (this.state.hasError) {+ return (+ <div className={this.props.fallbackClassName || 'flex flex-col items-center justify-center p-6 gap-3'}>+ <AlertCircle size={24} className="text-red-400" />+ <p className="text-sm text-red-400 text-center">Something went wrong</p>+ <p className="text-xs text-gray-500 text-center max-w-[200px] break-words">+ {this.state.error?.message || 'Unknown error'}+ </p>+ <button+ onClick={this.handleReset}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs bg-white/5 border border-white/10 text-gray-300 hover:bg-white/10 transition-colors"+ >+ <RefreshCw size={12} />+ Retry+ </button>+ </div>+ )+ }++ return this.props.children+ }+}diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 44d91d3c..13841962 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -61,6 +61,9 @@ export function useChat() {const ragEnabled = ragState.ragEnabled[convId] ?? falseif (ragEnabled) {+ // Ensure chunks are loaded from IndexedDB before retrieval+ await ragState.loadChunksFromDB(convId)+const chunks = ragState.getConversationChunks(convId)if (chunks.length > 0) {try {diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.tsindex 5e5e61af..7083fea6 100644--- a/src/hooks/useRAG.ts+++ b/src/hooks/useRAG.ts@@ -1,26 +1,52 @@-import { useCallback, useEffect } from "react"+import { useCallback, useEffect, useRef } from "react"+import { useShallow } from "zustand/react/shallow"import { useRAGStore } from "../stores/ragStore"import { indexDocument, retrieveContext } from "../api/rag"-import { getModelContext, listModels, pullModel } from "../api/ollama"+import { getModelContext, listModels, pullModel, checkConnection } from "../api/ollama"import { useModelStore } from "../stores/modelStore"import type { DocumentMeta, RAGContext } from "../types/rag"+const EMPTY_DOCS: DocumentMeta[] = []+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 {+ documents,+ isEnabled,+ isIndexing,+ indexingProgress,+ contextWarning,+ pullingEmbeddingModel,+ chunksLoaded,+ } = useRAGStore(+ useShallow((s) => ({+ documents: conversationId ? s.documents[conversationId] ?? EMPTY_DOCS : EMPTY_DOCS,+ isEnabled: conversationId ? s.ragEnabled[conversationId] ?? false : false,+ isIndexing: s.isIndexing,+ indexingProgress: s.indexingProgress,+ contextWarning: s.contextWarning,+ pullingEmbeddingModel: s.pullingEmbeddingModel,+ chunksLoaded: s.chunksLoaded,+ })))- const isIndexing = useRAGStore((s) => s.isIndexing)- const indexingProgress = useRAGStore((s) => s.indexingProgress)- const contextWarning = useRAGStore((s) => s.contextWarning)- const pullingEmbeddingModel = useRAGStore((s) => s.pullingEmbeddingModel)++ // Track which conversations we've already loaded chunks for+ const loadedRef = useRef<Set<string>>(new Set())++ // Auto-load chunks from IndexedDB when conversation has documents+ useEffect(() => {+ if (!conversationId || documents.length === 0) return+ if (loadedRef.current.has(conversationId)) return+ loadedRef.current.add(conversationId)+ useRAGStore.getState().loadChunksFromDB(conversationId)+ }, [conversationId, documents.length])// Check context window when RAG is toggled on or documents changeuseEffect(() => {if (!isEnabled || !conversationId) {- useRAGStore.getState().setContextWarning(null)+ // Only clear if there's actually a warning set+ if (useRAGStore.getState().contextWarning !== null) {+ useRAGStore.getState().setContextWarning(null)+ }return}@@ -34,7 +60,7 @@ export function useRAG(conversationId: string | null) {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 {+ } else if (useRAGStore.getState().contextWarning !== null) {useRAGStore.getState().setContextWarning(null)}} catch {@@ -52,6 +78,14 @@ export function useRAG(conversationId: string | null) {const { embeddingModel, setIndexing, setIndexingProgress, addDocument, addChunks, setPullingEmbeddingModel } =useRAGStore.getState()+ // Pre-flight: check Ollama is reachable+ const ollamaUp = await checkConnection()+ if (!ollamaUp) {+ throw new Error(+ "Ollama is not running. Please start Ollama first, then try again."+ )+ }+try {// Check if embedding model exists, auto-pull if missingconst models = await listModels()@@ -64,7 +98,9 @@ export function useRAG(conversationId: string | null) {`The embedding model "${embeddingModel}" is not installed. Download it now? (~274MB)`)if (!shouldPull) {- throw new Error("Embedding model not available")+ throw new Error(+ `Embedding model "${embeddingModel}" is required but not installed.`+ )}setPullingEmbeddingModel(true)@@ -76,7 +112,6 @@ export function useRAG(conversationId: string | null) {while (true) {const { done, value } = await reader.read()if (done) break- // Parse streaming pull progress (for logging)const text = decoder.decode(value, { stream: true })for (const line of text.split("\n").filter(Boolean)) {try {@@ -96,6 +131,12 @@ export function useRAG(conversationId: string | null) {const { meta, chunks } = await indexDocument(file, embeddingModel)+ if (chunks.length === 0) {+ throw new Error(+ "No text could be extracted from this file. The document may be empty or contain only images."+ )+ }+addDocument(conversationId, meta)addChunks(chunks)setIndexingProgress({ current: 1, total: 1 })@@ -148,6 +189,7 @@ export function useRAG(conversationId: string | null) {indexingProgress,contextWarning,pullingEmbeddingModel,+ chunksLoaded,uploadDocument,removeDocument: removeDoc,toggleRAG,diff --git a/src/lib/ragDB.ts b/src/lib/ragDB.tsnew file mode 100644index 00000000..1d1a3cf5--- /dev/null+++ b/src/lib/ragDB.ts@@ -0,0 +1,88 @@+/**+ * IndexedDB persistence for RAG chunks (embeddings).+ *+ * localStorage is too small for embedding vectors (768 floats × N chunks).+ * IndexedDB has no practical size limit and works identically in Tauri WebView.+ *+ * Schema:+ * DB: "locally-uncensored-rag" (v1)+ * ObjectStore: "chunks" — key: documentId, value: TextChunk[]+ */++import type { TextChunk } from "../types/rag"++const DB_NAME = "locally-uncensored-rag"+const DB_VERSION = 1+const STORE_NAME = "chunks"++let dbPromise: Promise<IDBDatabase> | null = null++function openDB(): Promise<IDBDatabase> {+ if (dbPromise) return dbPromise++ dbPromise = new Promise((resolve, reject) => {+ const request = indexedDB.open(DB_NAME, DB_VERSION)++ request.onupgradeneeded = () => {+ const db = request.result+ if (!db.objectStoreNames.contains(STORE_NAME)) {+ db.createObjectStore(STORE_NAME)+ }+ }++ request.onsuccess = () => resolve(request.result)+ request.onerror = () => {+ dbPromise = null+ reject(request.error)+ }+ })++ return dbPromise+}++function tx(mode: IDBTransactionMode): Promise<IDBObjectStore> {+ return openDB().then((db) => {+ const transaction = db.transaction(STORE_NAME, mode)+ return transaction.objectStore(STORE_NAME)+ })+}++function idbRequest<T>(req: IDBRequest<T>): Promise<T> {+ return new Promise((resolve, reject) => {+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => reject(req.error)+ })+}++/** Save chunks for a document (overwrites if exists) */+export async function saveChunks(documentId: string, chunks: TextChunk[]): Promise<void> {+ const store = await tx("readwrite")+ await idbRequest(store.put(chunks, documentId))+}++/** Load chunks for specific document IDs */+export async function loadChunks(documentIds: string[]): Promise<TextChunk[]> {+ if (documentIds.length === 0) return []++ const store = await tx("readonly")+ const results: TextChunk[] = []++ for (const docId of documentIds) {+ const chunks = await idbRequest(store.get(docId)) as TextChunk[] | undefined+ if (chunks) results.push(...chunks)+ }++ return results+}++/** Delete chunks for a document */+export async function deleteChunks(documentId: string): Promise<void> {+ const store = await tx("readwrite")+ await idbRequest(store.delete(documentId))+}++/** Delete all chunks (e.g., when clearing all data) */+export async function clearAllChunks(): Promise<void> {+ const store = await tx("readwrite")+ await idbRequest(store.clear())+}diff --git a/src/stores/ragStore.ts b/src/stores/ragStore.tsindex 710f115c..4e0c2d20 100644--- a/src/stores/ragStore.ts+++ b/src/stores/ragStore.ts@@ -1,6 +1,7 @@import { create } from "zustand"import { persist } from "zustand/middleware"-import type { DocumentMeta, TextChunk, VectorSearchResult } from "../types/rag"+import type { DocumentMeta, TextChunk } from "../types/rag"+import { saveChunks, loadChunks, deleteChunks } from "../lib/ragDB"interface RAGState {documents: Record<string, DocumentMeta[]>@@ -12,11 +13,13 @@ interface RAGState {lastRetrievedChunks: { chunk: TextChunk; score: number }[]contextWarning: string | nullpullingEmbeddingModel: boolean+ chunksLoaded: booleanaddDocument: (conversationId: string, meta: DocumentMeta) => voidremoveDocument: (conversationId: string, docId: string) => voidaddChunks: (newChunks: TextChunk[]) => voidgetConversationChunks: (conversationId: string) => TextChunk[]+ loadChunksFromDB: (conversationId: string) => Promise<void>setRagEnabled: (conversationId: string, enabled: boolean) => voidsetEmbeddingModel: (model: string) => voidsetIndexing: (indexing: boolean) => void@@ -39,6 +42,7 @@ export const useRAGStore = create<RAGState>()(lastRetrievedChunks: [],contextWarning: null,pullingEmbeddingModel: false,+ chunksLoaded: false,addDocument: (conversationId, meta) =>set((state) => ({@@ -48,7 +52,11 @@ export const useRAGStore = create<RAGState>()(},})),- removeDocument: (conversationId, docId) =>+ removeDocument: (conversationId, docId) => {+ // Delete from IndexedDB (fire-and-forget, non-blocking)+ deleteChunks(docId).catch((err) =>+ console.error("Failed to delete chunks from IndexedDB:", err)+ )set((state) => ({documents: {...state.documents,@@ -57,12 +65,27 @@ export const useRAGStore = create<RAGState>()(),},chunks: state.chunks.filter((c) => c.documentId !== docId),- })),+ }))+ },++ addChunks: (newChunks) => {+ // Persist to IndexedDB grouped by documentId+ const byDoc = new Map<string, TextChunk[]>()+ for (const chunk of newChunks) {+ const existing = byDoc.get(chunk.documentId) || []+ existing.push(chunk)+ byDoc.set(chunk.documentId, existing)+ }+ for (const [docId, chunks] of byDoc) {+ saveChunks(docId, chunks).catch((err) =>+ console.error("Failed to save chunks to IndexedDB:", err)+ )+ }- addChunks: (newChunks) =>set((state) => ({chunks: [...state.chunks, ...newChunks],- })),+ }))+ },getConversationChunks: (conversationId) => {const { documents, chunks } = get()@@ -70,6 +93,38 @@ export const useRAGStore = create<RAGState>()(return chunks.filter((c) => docIds.includes(c.documentId))},+ loadChunksFromDB: async (conversationId) => {+ const { documents, chunks, chunksLoaded: alreadyLoaded } = get()+ const docs = documents[conversationId] || []+ if (docs.length === 0) return++ // Only load docs whose chunks aren't already in memory+ const loadedDocIds = new Set(chunks.map((c) => c.documentId))+ const missingDocIds = docs+ .map((d) => d.id)+ .filter((id) => !loadedDocIds.has(id))++ if (missingDocIds.length === 0) {+ if (!alreadyLoaded) set({ chunksLoaded: true })+ return+ }++ try {+ const restored = await loadChunks(missingDocIds)+ if (restored.length > 0) {+ set((state) => ({+ chunks: [...state.chunks, ...restored],+ chunksLoaded: true,+ }))+ } else if (!alreadyLoaded) {+ set({ chunksLoaded: true })+ }+ } catch (err) {+ console.error("Failed to load chunks from IndexedDB:", err)+ if (!alreadyLoaded) set({ chunksLoaded: true })+ }+ },+setRagEnabled: (conversationId, enabled) =>set((state) => ({ragEnabled: { ...state.ragEnabled, [conversationId]: enabled },@@ -81,17 +136,22 @@ export const useRAGStore = create<RAGState>()(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)),- }- }),+ clearConversationDocs: (conversationId) => {+ const docIds = (get().documents[conversationId] || []).map((d) => d.id)+ // Delete all from IndexedDB+ for (const docId of docIds) {+ deleteChunks(docId).catch((err) =>+ console.error("Failed to delete chunks from IndexedDB:", err)+ )+ }+ set((state) => ({+ documents: {+ ...state.documents,+ [conversationId]: [],+ },+ chunks: state.chunks.filter((c) => !docIds.includes(c.documentId)),+ }))+ },setLastRetrievedChunks: (chunks) => set({ lastRetrievedChunks: chunks }),