~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: remove model type filtering and auto-selection issues
LearningCircuitca3986488bc0
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex b243d9b26d..53eddd51f7 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -192,8 +192,12 @@ class DatabaseManager:sqlcipher3 = get_sqlcipher_module()# Create tables directly with SQLCipher, bypassing SQLAlchemy DDL- # Use standard isolation_level for proper transaction handling- conn = sqlcipher3.connect(str(db_path), check_same_thread=False)+ # Use IMMEDIATE isolation level for proper write transaction handling+ conn = sqlcipher3.connect(+ str(db_path),+ isolation_level="IMMEDIATE",+ check_same_thread=False,+ )# Use centralized SQLCipher setupset_sqlcipher_key(conn, password)apply_sqlcipher_pragmas(conn, creation_mode=True)@@ -237,7 +241,11 @@ class DatabaseManager:def create_sqlcipher_connection():"""Create a properly initialized SQLCipher connection."""- conn = sqlcipher3.connect(str(db_path), check_same_thread=False)+ conn = sqlcipher3.connect(+ str(db_path),+ isolation_level="IMMEDIATE",+ check_same_thread=False,+ )cursor = conn.cursor()# Use centralized SQLCipher setup@@ -261,6 +269,8 @@ class DatabaseManager:poolclass=self._pool_class,echo=False,query_cache_size=1000, # Increased for complex queries with SQLCipher+ pool_size=10,+ max_overflow=30, # Increase overflow so we don't run out.)else:logger.warning(@@ -273,6 +283,8 @@ class DatabaseManager:poolclass=self._pool_class,echo=False,query_cache_size=1000, # Same optimization for unencrypted+ pool_size=10,+ max_overflow=30, # Increase overflow so we don't run out.)# For unencrypted databases, just apply pragmas@@ -336,7 +348,11 @@ class DatabaseManager:def create_sqlcipher_connection():"""Create a properly initialized SQLCipher connection."""- conn = sqlcipher3.connect(str(db_path), check_same_thread=False)+ conn = sqlcipher3.connect(+ str(db_path),+ isolation_level="IMMEDIATE",+ check_same_thread=False,+ )cursor = conn.cursor()# Use centralized SQLCipher setupdiff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex ef44b806cc..5886e35dd4 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -598,6 +598,51 @@ class RAGIndex(Base):return f"<RAGIndex(collection='{self.collection_name}', model='{self.embedding_model}', chunks={self.chunk_count})>"+class RagDocumentStatus(Base):+ """+ Tracks which documents have been indexed for RAG.+ Row existence = document is indexed. No row = not indexed.+ Simple and avoids ORM caching issues.+ """++ __tablename__ = "rag_document_status"++ # Composite primary key+ document_id = Column(+ String(36),+ ForeignKey("documents.id", ondelete="CASCADE"),+ primary_key=True,+ nullable=False,+ )+ collection_id = Column(+ String(36),+ ForeignKey("collections.id", ondelete="CASCADE"),+ primary_key=True,+ nullable=False,+ )++ # Which RAG index was used (tracks embedding model indirectly)+ rag_index_id = Column(+ Integer,+ ForeignKey("rag_indices.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )++ # Metadata+ chunk_count = Column(Integer, nullable=False)+ indexed_at = Column(UtcDateTime, nullable=False, default=utcnow())++ # Indexes for fast lookups+ __table_args__ = (+ Index("idx_rag_status_collection", "collection_id"),+ Index("idx_rag_status_index", "rag_index_id"),+ )++ def __repr__(self):+ return f"<RagDocumentStatus(doc='{self.document_id[:8]}...', coll='{self.collection_id[:8]}...', chunks={self.chunk_count})>"++class CollectionFolder(Base):"""Local folders linked to a collection for indexing.diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 48a7effd6b..73c04ff7b5 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -636,22 +636,35 @@ def get_documents():# Expire all cached objects to ensure we get fresh data from DBdb_session.expire_all()+ # Import RagDocumentStatus model+ from ...database.models.library import RagDocumentStatus+# Build base query - join Document with DocumentCollection for the collection- # Use inner join to only show documents that belong to this collection- query = db_session.query(Document, DocumentCollection).join(- DocumentCollection,- (DocumentCollection.document_id == Document.id)- & (DocumentCollection.collection_id == collection_id),+ # LEFT JOIN with rag_document_status to check indexed status+ query = (+ db_session.query(+ Document, DocumentCollection, RagDocumentStatus+ )+ .join(+ DocumentCollection,+ (DocumentCollection.document_id == Document.id)+ & (DocumentCollection.collection_id == collection_id),+ )+ .outerjoin(+ RagDocumentStatus,+ (RagDocumentStatus.document_id == Document.id)+ & (RagDocumentStatus.collection_id == collection_id),+ ))logger.debug(f"Base query for collection {collection_id}: {query}")- # Apply filters based on DocumentCollection.indexed+ # Apply filters based on rag_document_status existenceif filter_type == "indexed":- query = query.filter(DocumentCollection.indexed.is_(True))+ query = query.filter(RagDocumentStatus.document_id.isnot(None))elif filter_type == "unindexed":# Documents in collection but not indexed yet- query = query.filter(DocumentCollection.indexed.is_(False))+ query = query.filter(RagDocumentStatus.document_id.is_(None))# Get total count before paginationtotal_count = query.count()@@ -672,31 +685,26 @@ def get_documents():"id": doc.id,"title": doc.title,"original_url": doc.original_url,- "rag_indexed": doc_collection.indexed- if doc_collection- else False,- "chunk_count": doc_collection.chunk_count- if doc_collection- else 0,+ "rag_indexed": rag_status is not None,+ "chunk_count": rag_status.chunk_count if rag_status else 0,"created_at": doc.created_at.isoformat()if doc.created_atelse None,}- for doc, doc_collection in results+ for doc, doc_collection, rag_status in results]# Debug logging to help diagnose indexing status issuesindexed_count = sum(1 for d in documents if d["rag_indexed"])- # Additional debug: check all DocumentCollection entries for this collection- all_doc_collections = (- db_session.query(DocumentCollection)+ # Additional debug: check rag_document_status for this collection+ all_indexed_statuses = (+ db_session.query(RagDocumentStatus).filter_by(collection_id=collection_id).all())- indexed_in_db = sum(1 for dc in all_doc_collections if dc.indexed)logger.info(- f"DocumentCollection table shows: {indexed_in_db}/{len(all_doc_collections)} indexed for collection {collection_id}"+ f"rag_document_status table shows: {len(all_indexed_statuses)} documents indexed for collection {collection_id}")logger.info(diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 17f13199b5..fe938d5625 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -284,17 +284,19 @@ class LibraryRAGService:)return None- # Calculate actual counts from DocumentCollection (not from chunks)+ # Calculate actual counts from rag_document_status table+ from ...database.models.library import RagDocumentStatus+actual_chunk_count = (- session.query(func.sum(DocumentCollection.chunk_count))- .filter_by(collection_id=collection_id, indexed=True)+ session.query(func.sum(RagDocumentStatus.chunk_count))+ .filter_by(collection_id=collection_id).scalar()or 0)actual_doc_count = (- session.query(DocumentCollection)- .filter_by(collection_id=collection_id, indexed=True)+ session.query(RagDocumentStatus)+ .filter_by(collection_id=collection_id).count())@@ -496,21 +498,61 @@ class LibraryRAGService:f"Saved FAISS index to {index_path} with integrity tracking")- # Update DocumentCollection with RAG status using ORM- was_already_indexed = (- doc_collection.indexed- ) # Check BEFORE updating-from datetime import datetime, UTCfrom sqlalchemy import text- # Update using ORM- doc_collection.indexed = True- doc_collection.chunk_count = len(chunks)- doc_collection.last_indexed_at = datetime.now(UTC)+ # Check if document was already indexed (for stats update)+ was_already_indexed = (+ session.execute(+ text("""+ SELECT 1 FROM rag_document_status+ WHERE document_id = :doc_id AND collection_id = :coll_id+ LIMIT 1+ """),+ {"doc_id": document_id, "coll_id": collection_id},+ ).first()+ is not None+ )++ # Mark document as indexed using rag_document_status table+ # Row existence = indexed, simple and clean+ timestamp = datetime.now(UTC)+ session.execute(+ text("""+ INSERT OR REPLACE INTO rag_document_status+ (document_id, collection_id, rag_index_id, chunk_count, indexed_at)+ VALUES (:doc_id, :coll_id, :index_id, :chunk_count, :timestamp)+ """),+ {+ "doc_id": document_id,+ "coll_id": collection_id,+ "index_id": self.rag_index_record.id,+ "chunk_count": len(chunks),+ "timestamp": timestamp,+ },+ )++ logger.info(+ f"Marked document as indexed in rag_document_status: doc_id={document_id}, coll_id={collection_id}, chunks={len(chunks)}"+ )++ # Also update DocumentCollection table for backward compatibility+ session.execute(+ text("""+ UPDATE document_collections+ SET indexed = 1, chunk_count = :chunk_count, last_indexed_at = :timestamp+ WHERE document_id = :doc_id AND collection_id = :coll_id+ """),+ {+ "doc_id": document_id,+ "coll_id": collection_id,+ "chunk_count": len(chunks),+ "timestamp": timestamp,+ },+ )logger.info(- f"Marked DocumentCollection as indexed: doc_id={document_id}, coll_id={collection_id}, chunks={len(chunks)}"+ "Also updated DocumentCollection.indexed for backward compatibility")# Update RAGIndex statistics (only if not already indexed)@@ -527,24 +569,31 @@ class LibraryRAGService:f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1")+ # Flush ORM changes to database before commit+ session.flush()+ logger.info(f"Flushed ORM changes for document {document_id}")+# Commit the transactionsession.commit()- # Verify the update was persisted- session.expire_all()- verification = (- session.query(DocumentCollection)- .filter_by(- document_id=document_id, collection_id=collection_id- )- .first()- )+ # WAL checkpoint after commit to ensure persistence+ session.execute(text("PRAGMA wal_checkpoint(FULL)"))+logger.info(- f"Post-commit verification: doc={document_id}, indexed={verification.indexed if verification else 'NOT_FOUND'}, chunks={verification.chunk_count if verification else 0}"+ f"Committed and checkpointed changes for document {document_id}")- # WAL checkpoint after transaction commit to ensure persistence- session.execute(text("PRAGMA wal_checkpoint(FULL)"))+ # Verify the update was persisted+ verification = session.execute(+ text("""+ SELECT chunk_count FROM rag_document_status+ WHERE document_id = :doc_id AND collection_id = :coll_id+ """),+ {"doc_id": document_id, "coll_id": collection_id},+ ).first()+ logger.info(+ f"Post-commit verification: doc={document_id}, indexed={verification is not None}, chunks={verification[0] if verification else 0}"+ )logger.info(f"Indexed document {document_id} with {len(chunks)} chunks"@@ -836,17 +885,19 @@ class LibraryRAGService:.count())- # Count indexed documents+ # Count indexed documents from rag_document_status table+ from ...database.models.library import RagDocumentStatus+indexed_docs = (- session.query(DocumentCollection)- .filter_by(collection_id=collection_id, indexed=True)+ session.query(RagDocumentStatus)+ .filter_by(collection_id=collection_id).count())- # Count total chunks+ # Count total chunks from rag_document_status tabletotal_chunks = (- session.query(func.sum(DocumentCollection.chunk_count))- .filter_by(collection_id=collection_id, indexed=True)+ session.query(func.sum(RagDocumentStatus.chunk_count))+ .filter_by(collection_id=collection_id).scalar()or 0)diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex aa89ac58c7..5088420e8d 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -445,6 +445,9 @@ def register_blueprints(app):"llm_openai_endpoint_url": settings_manager.get_setting("llm.openai_endpoint.url", ""),+ "llm_ollama_url": settings_manager.get_setting(+ "llm.ollama.url", "http://localhost:11434"+ ),"search_tool": settings_manager.get_setting("search.tool", ""),diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 16495f06b9..2d473eae11 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -192,6 +192,17 @@ def start_research():logger.debug(f"No custom_endpoint in request, using database setting: {custom_endpoint}")++ # Get Ollama URL from request or settings+ ollama_url = data.get("ollama_url")+ if not ollama_url and model_provider == "OLLAMA":+ ollama_url = settings_manager.get_setting(+ "llm.ollama.url", "http://localhost:11434"+ )+ logger.debug(+ f"No ollama_url in request, using database setting: {ollama_url}"+ )+search_engine = data.get("search_engine") or data.get("search_tool")if not search_engine:search_engine = settings_manager.get_setting("search.tool", "searxng")diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 9dcdcdc4aa..edb2d0e217 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -13,6 +13,8 @@let modelProviderSelect = null;let customEndpointInput = null;let endpointContainer = null;+ let ollamaUrlInput = null;+ let ollamaUrlContainer = null;let modelInput = null;let modelDropdown = null;let modelDropdownList = null;@@ -95,6 +97,8 @@modelProviderSelect = document.getElementById('model_provider');customEndpointInput = document.getElementById('custom_endpoint');endpointContainer = document.getElementById('endpoint_container');+ ollamaUrlInput = document.getElementById('ollama_url');+ ollamaUrlContainer = document.getElementById('ollama_url_container');// Custom dropdown elementsmodelInput = document.getElementById('model');@@ -609,8 +613,14 @@endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ // Show Ollama URL input if Ollama is selected+ if (ollamaUrlContainer) {+ ollamaUrlContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';+ }+// Update model options based on provider- updateModelOptionsForProvider(provider, true);+ // Don't reset model selection - preserve it if valid for new provider+ updateModelOptionsForProvider(provider, false);// Save provider change to databasesaveProviderSetting(provider);@@ -744,6 +754,12 @@console.warn('Endpoint container not found');}+ // Show Ollama URL input if Ollama is selected+ if (ollamaUrlContainer) {+ const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();+ ollamaUrlContainer.style.display = selectedProvider === 'OLLAMA' ? 'block' : 'none';+ }+// Initial update of model optionsconst providerToUpdate = modelProviderSelect.value || initialProvider.toUpperCase();updateModelOptionsForProvider(providerToUpdate);@@ -1075,9 +1091,9 @@}}- // Select first available model if no selection and models are available+ // Select model from database if availableif ((!selectedModelValue || selectedModelValue === '') && modelOptions.length > 0 && modelInput) {- // Try to find last used model first+ // Try to find last used model from databaseif (lastSelectedModel) {const matchingModel = modelOptions.find(model => model.value === lastSelectedModel);if (matchingModel) {@@ -1099,21 +1115,9 @@}}- // If no match found, select first available- modelInput.value = modelOptions[0].label;- selectedModelValue = modelOptions[0].value;- console.log('Auto-selected first available model:', selectedModelValue);-- // Update any hidden input if it exists- const hiddenInput = document.getElementById('model_hidden');- if (hiddenInput) {- hiddenInput.value = selectedModelValue;- }-- // Only save to settings if we're not initializing- if (!isInitializing) {- saveModelSettings(selectedModelValue);- }+ // Don't auto-select first model - wait for database settings to load+ // or let user manually select a model+ console.log('No saved model found, waiting for user selection');}}@@ -1314,6 +1318,12 @@endpointContainer.style.display =providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';}++ // Display Ollama URL container if using Ollama+ if (ollamaUrlContainer) {+ ollamaUrlContainer.style.display =+ providerValue === 'OLLAMA' ? 'block' : 'none';+ }}// Update the custom endpoint URl if we have one.@@ -1324,6 +1334,15 @@customEndpointInput.disabled = !customEndpointUrlSetting.editable;}+ // Update the Ollama URL if we have one+ const ollamaUrlSetting = settingsByKey['llm.ollama.url'];+ if (ollamaUrlSetting && ollamaUrlInput) {+ const ollamaUrlValue = ollamaUrlSetting.value;+ console.log('Current Ollama URL:', ollamaUrlValue);+ ollamaUrlInput.value = ollamaUrlValue;+ ollamaUrlInput.disabled = !ollamaUrlSetting.editable;+ }+// Load model options based on the current providerconst currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';updateModelOptionsForProvider(currentProvider, false).then(() => {@@ -1491,6 +1510,11 @@endpointContainer.style.display =provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ // Show/hide Ollama URL input if needed+ if (ollamaUrlContainer) {+ ollamaUrlContainer.style.display =+ provider === 'OLLAMA' ? 'block' : 'none';+ }}const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';@@ -2060,6 +2084,7 @@// Get other form valuesconst customEndpoint = customEndpointInput ? customEndpointInput.value : '';+ const ollamaUrl = ollamaUrlInput ? ollamaUrlInput.value : '';const enableNotifications = notificationToggle ? notificationToggle.checked : true;// Get strategy value@@ -2095,6 +2120,7 @@model_provider: modelProvider,model: model,custom_endpoint: customEndpoint,+ ollama_url: ollamaUrl,search_engine: searchEngine,strategy: strategy,iterations: iterations,diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex b6947f4b9a..c47c20ce0d 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -37,11 +37,17 @@ document.addEventListener('DOMContentLoaded', function() {// Setup provider change handlerdocument.getElementById('embedding-provider').addEventListener('change', function() {updateModelOptions();+ toggleOllamaUrlField();});// Setup model change handlerdocument.getElementById('embedding-model').addEventListener('change', updateModelDescription);+ // Setup Ollama URL change handler+ document.getElementById('ollama-url').addEventListener('input', function() {+ // Mark as changed if needed+ });+// Setup config form submissiondocument.getElementById('rag-config-form').addEventListener('submit', handleConfigSubmit);});@@ -110,6 +116,12 @@ async function loadCurrentSettings() {if (settings.chunk_overlap) {document.getElementById('chunk-overlap').value = settings.chunk_overlap;}++ // Load Ollama URL from global settings+ loadOllamaUrl();++ // Show/hide Ollama URL field based on provider+ toggleOllamaUrlField();}} catch (error) {console.error('Error loading current settings:', error);@@ -310,8 +322,19 @@ async function handleConfigSubmit(event) {event.preventDefault();console.log('🚀 Configuration form submitted!');+ const provider = document.getElementById('embedding-provider').value;++ // Save Ollama URL first if provider is ollama+ if (provider === 'ollama') {+ const ollamaUrlSaved = await saveOllamaUrl();+ if (!ollamaUrlSaved) {+ showError('Failed to save Ollama URL');+ return;+ }+ }+const formData = {- embedding_provider: document.getElementById('embedding-provider').value,+ embedding_provider: provider,embedding_model: document.getElementById('embedding-model').value,chunk_size: parseInt(document.getElementById('chunk-size').value),chunk_overlap: parseInt(document.getElementById('chunk-overlap').value)@@ -497,3 +520,65 @@ function escapeHtml(text) {div.textContent = text;return div.innerHTML;}++/**+ * Toggle Ollama URL field visibility based on selected provider+ */+function toggleOllamaUrlField() {+ const provider = document.getElementById('embedding-provider').value;+ const ollamaUrlGroup = document.getElementById('ollama-url-group');++ if (provider === 'ollama') {+ ollamaUrlGroup.style.display = 'block';+ } else {+ ollamaUrlGroup.style.display = 'none';+ }+}++/**+ * Load Ollama URL from settings+ */+async function loadOllamaUrl() {+ try {+ const response = await safeFetch('/settings/api/embeddings.ollama.url');+ const data = await response.json();++ if (data && data.value) {+ document.getElementById('ollama-url').value = data.value;+ }+ } catch (error) {+ console.error('Error loading Ollama URL:', error);+ }+}++/**+ * Save Ollama URL to settings+ */+async function saveOllamaUrl() {+ const ollamaUrl = document.getElementById('ollama-url').value.trim();++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');++ const response = await safeFetch('/settings/api/embeddings.ollama.url', {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({+ value: ollamaUrl+ })+ });++ const data = await response.json();+ if (data.error) {+ console.error('Failed to save Ollama URL:', data.error);+ return false;+ }+ return true;+ } catch (error) {+ console.error('Error saving Ollama URL:', error);+ return false;+ }+}diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.jsindex bbb5650588..0018361cf9 100644--- a/src/local_deep_research/web/static/js/rag_manager.js+++ b/src/local_deep_research/web/static/js/rag_manager.js@@ -56,12 +56,16 @@ document.addEventListener('DOMContentLoaded', function() {// Setup provider change handlerdocument.getElementById('embedding-provider').addEventListener('change', function() {updateModelOptions();+ toggleOllamaUrlField();checkSettingsMismatch();});// Setup model change handlerdocument.getElementById('embedding-model').addEventListener('change', checkSettingsMismatch);+ // Setup Ollama URL change handler+ document.getElementById('ollama-url').addEventListener('input', checkSettingsMismatch);+// Setup chunk size/overlap change handlersdocument.getElementById('chunk-size').addEventListener('input', checkSettingsMismatch);document.getElementById('chunk-overlap').addEventListener('input', checkSettingsMismatch);@@ -159,6 +163,12 @@ async function loadCurrentSettings() {if (settings.chunk_overlap) {document.getElementById('chunk-overlap').value = settings.chunk_overlap;}++ // Load Ollama URL from global settings+ loadOllamaUrl();++ // Show/hide Ollama URL field based on provider+ toggleOllamaUrlField();}} catch (error) {console.error('Error loading current settings:', error);@@ -458,8 +468,18 @@ async function handleConfigSubmit(event) {return;}+ // Save Ollama URL first if provider is ollama+ const provider = document.getElementById('embedding-provider').value;+ if (provider === 'ollama') {+ const ollamaUrlSaved = await saveOllamaUrl();+ if (!ollamaUrlSaved) {+ showError('Failed to save Ollama URL');+ return;+ }+ }+const formData = {- embedding_provider: document.getElementById('embedding-provider').value,+ embedding_provider: provider,embedding_model: document.getElementById('embedding-model').value,chunk_size: parseInt(document.getElementById('chunk-size').value),chunk_overlap: parseInt(document.getElementById('chunk-overlap').value),@@ -999,3 +1019,65 @@ function escapeHtml(text) {div.textContent = text;return div.innerHTML;}++/**+ * Toggle Ollama URL field visibility based on selected provider+ */+function toggleOllamaUrlField() {+ const provider = document.getElementById('embedding-provider').value;+ const ollamaUrlGroup = document.getElementById('ollama-url-group');++ if (provider === 'ollama') {+ ollamaUrlGroup.style.display = 'block';+ } else {+ ollamaUrlGroup.style.display = 'none';+ }+}++/**+ * Load Ollama URL from settings+ */+async function loadOllamaUrl() {+ try {+ const response = await safeFetch('/settings/api/embeddings.ollama.url');+ const data = await response.json();++ if (data && data.value) {+ document.getElementById('ollama-url').value = data.value;+ }+ } catch (error) {+ console.error('Error loading Ollama URL:', error);+ }+}++/**+ * Save Ollama URL to settings+ */+async function saveOllamaUrl() {+ const ollamaUrl = document.getElementById('ollama-url').value.trim();++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');++ const response = await safeFetch('/settings/api/embeddings.ollama.url', {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({+ value: ollamaUrl+ })+ });++ const data = await response.json();+ if (data.error) {+ console.error('Failed to save Ollama URL:', data.error);+ return false;+ }+ return true;+ } catch (error) {+ console.error('Error saving Ollama URL:', error);+ return false;+ }+}diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.htmlindex 9c6aa731fb..98e53b2094 100644--- a/src/local_deep_research/web/templates/pages/embedding_settings.html+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html@@ -38,6 +38,14 @@</select></div>+ <div class="ldr-form-group" id="ollama-url-group" style="display: none;">+ <label for="ollama-url">Ollama URL</label>+ <input type="text" id="ollama-url" class="ldr-form-control" placeholder="http://localhost:11434">+ <small class="ldr-form-text ldr-text-muted">+ URL of the Ollama server for embedding models. Leave empty to use the default LLM Ollama URL.+ </small>+ </div>+<div class="ldr-form-group"><label for="embedding-model">Model</label><select id="embedding-model" class="ldr-form-control">diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 771cece6ba..17b30e7674 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -68,18 +68,15 @@<div class="status-item"><span class="status-label">PDF Storage:</span>- <span class="badge {% if enable_pdf_storage %}badge-success{% else %}badge-secondary{% endif %}">+ <button class="badge badge-button {% if enable_pdf_storage %}badge-success{% else %}badge-warning{% endif %}"+ onclick="togglePDFStorage({{ 'true' if enable_pdf_storage else 'false' }})"+ title="Click to {% if enable_pdf_storage %}disable{% else %}enable{% endif %} PDF storage">{% if enable_pdf_storage %}- <i class="fas fa-check-circle"></i> Enabled+ <i class="fas fa-check-circle"></i> Enabled - Click to Disable{% else %}- <i class="fas fa-times-circle"></i> Disabled+ <i class="fas fa-exclamation-circle"></i> Disabled - Click to Enable{% endif %}- </span>- {% if not enable_pdf_storage %}- <span class="status-hint" title="PDF downloads are disabled for privacy. Enable in settings if needed.">- <i class="fas fa-info-circle"></i>- </span>- {% endif %}+ </button></div><div class="status-item">@@ -368,6 +365,47 @@</div></div>+<!-- PDF Storage Toggle Confirmation Modal -->+<div id="pdf-storage-modal" class="modal" style="display: none;">+ <div class="modal-content" style="max-width: 600px;">+ <div class="modal-header">+ <h2><i class="fas fa-exclamation-triangle" style="color: #ff9800;"></i> <span id="pdf-modal-title">Enable PDF Storage?</span></h2>+ <button class="close" onclick="closePDFStorageModal()">×</button>+ </div>+ <div class="modal-body">+ <div id="pdf-enable-warning" class="pdf-storage-warning">+ <div class="ldr-security-warning" style="background: var(--warning-bg, #3d3313); padding: 15px; border-radius: 8px; border-left: 4px solid #ff9800; margin-bottom: 15px;">+ <i class="fas fa-exclamation-triangle" style="color: #ff9800; font-size: 1.5em; margin-right: 10px;"></i>+ <strong style="color: #ff9800;">PRIVACY WARNING</strong>+ <p style="margin-top: 10px;">Enabling PDF storage will save research PDFs <strong>unencrypted to the server's hard drive</strong>. This means:</p>+ <ul style="margin: 10px 0; padding-left: 30px;">+ <li>Anyone with filesystem access can see your downloaded PDFs</li>+ <li>Your research interests will be exposed</li>+ <li>Files are stored wherever LDR is running (not encrypted)</li>+ </ul>+ <p style="margin-top: 10px;">Currently, only encrypted metadata is stored in your database. Enable PDF storage only if you need PDF files for external tools or offline reading.</p>+ </div>+ <p><strong>Are you sure you want to enable PDF storage?</strong></p>+ </div>+ <div id="pdf-disable-warning" class="pdf-storage-warning" style="display: none;">+ <p>Disabling PDF storage will:</p>+ <ul style="margin: 10px 0; padding-left: 30px;">+ <li>Prevent new PDFs from being downloaded to disk</li>+ <li>Keep existing PDFs on disk (not deleted)</li>+ <li>Maintain encrypted metadata in your database</li>+ </ul>+ <p style="margin-top: 10px;"><strong>Are you sure you want to disable PDF storage?</strong></p>+ </div>+ </div>+ <div class="modal-footer">+ <button id="pdf-storage-confirm-btn" class="btn btn-primary" onclick="confirmPDFStorageToggle()">+ <i class="fas fa-check"></i> <span id="pdf-confirm-text">Yes, Enable</span>+ </button>+ <button class="btn btn-secondary" onclick="closePDFStorageModal()">Cancel</button>+ </div>+ </div>+</div>+<!-- Sync Library Modal --><div id="sync-library-modal" class="modal" style="display: none;"><div class="modal-content" style="max-width: 600px;">@@ -475,11 +513,29 @@}.library-status-bar .badge {- padding: 4px 10px;+ padding: 6px 12px;font-size: 13px;display: inline-flex;align-items: center;- gap: 4px;+ gap: 6px;+ border-radius: 6px;+}++.library-status-bar .badge-button {+ border: none;+ cursor: pointer;+ transition: all 0.2s ease;+ font-weight: 500;+}++.library-status-bar .badge-button:hover {+ transform: translateY(-1px);+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);+ filter: brightness(1.1);+}++.library-status-bar .badge-button:active {+ transform: translateY(0);}.library-status-bar .badge-secondary {@@ -493,8 +549,8 @@}.library-status-bar .badge-warning {- background: #ffc107;- color: #212529;+ background: #ff9800;+ color: white;}.library-status-bar .status-hint {@@ -939,6 +995,27 @@margin-bottom: 20px;}+.modal-header .close {+ background: none;+ border: none;+ font-size: 28px;+ color: var(--text-secondary, #999);+ cursor: pointer;+ padding: 0;+ width: 30px;+ height: 30px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ transition: all 0.2s;+}++.modal-header .close:hover {+ background: rgba(255, 255, 255, 0.1);+ color: var(--text-primary, #e4e4e4);+}+/* Enhanced PDF Viewer Modal */.pdf-modal {display: none;@@ -1733,5 +1810,80 @@ document.querySelectorAll('.view-toggle button').forEach(btn => {}});});++// PDF Storage Toggle Functions+let pendingPDFStorageState = false;++function togglePDFStorage(currentState) {+ pendingPDFStorageState = !currentState;++ // Update modal content based on what we're doing+ if (pendingPDFStorageState) {+ // Enabling PDF storage+ document.getElementById('pdf-modal-title').textContent = 'Enable PDF Storage?';+ document.getElementById('pdf-enable-warning').style.display = 'block';+ document.getElementById('pdf-disable-warning').style.display = 'none';+ document.getElementById('pdf-confirm-text').textContent = 'Yes, Enable';+ document.getElementById('pdf-storage-confirm-btn').className = 'btn btn-primary';+ } else {+ // Disabling PDF storage+ document.getElementById('pdf-modal-title').textContent = 'Disable PDF Storage?';+ document.getElementById('pdf-enable-warning').style.display = 'none';+ document.getElementById('pdf-disable-warning').style.display = 'block';+ document.getElementById('pdf-confirm-text').textContent = 'Yes, Disable';+ document.getElementById('pdf-storage-confirm-btn').className = 'btn btn-danger';+ }++ // Show modal+ document.getElementById('pdf-storage-modal').style.display = 'block';+}++function closePDFStorageModal() {+ document.getElementById('pdf-storage-modal').style.display = 'none';+}++async function confirmPDFStorageToggle() {+ const btn = document.getElementById('pdf-storage-confirm-btn');+ const originalContent = btn.innerHTML;+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';+ btn.disabled = true;++ try {+ // Get CSRF token+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';++ // Update the setting via settings manager endpoint+ const response = await fetch('/settings/save_all_settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({+ 'research_library.enable_pdf_storage': pendingPDFStorageState+ })+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const result = await response.json();++ if (result.status === 'success') {+ // Close modal and reload page to reflect changes+ closePDFStorageModal();+ location.reload();+ } else {+ throw new Error(result.message || 'Failed to update setting');+ }++ } catch (error) {+ console.error('Failed to toggle PDF storage:', error);+ alert('Failed to update PDF storage setting. Please try again or use the Settings page.');+ btn.innerHTML = originalContent;+ btn.disabled = false;+ }+}</script>{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/rag_manager.html b/src/local_deep_research/web/templates/pages/rag_manager.htmlindex 552e972cbb..3009107b64 100644--- a/src/local_deep_research/web/templates/pages/rag_manager.html+++ b/src/local_deep_research/web/templates/pages/rag_manager.html@@ -45,6 +45,14 @@</select></div>+ <div class="ldr-form-group" id="ollama-url-group" style="display: none;">+ <label for="ollama-url">Ollama URL</label>+ <input type="text" id="ollama-url" class="ldr-form-control" placeholder="http://localhost:11434">+ <small class="ldr-form-text ldr-text-muted">+ URL of the Ollama server for embedding models. Leave empty to use the default LLM Ollama URL.+ </small>+ </div>+<div class="ldr-form-group"><label for="embedding-model">Model</label><select id="embedding-model" class="ldr-form-control">diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex bc9818b023..563288c66d 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -94,6 +94,13 @@<input type="text" id="custom_endpoint" name="custom_endpoint" class="ldr-form-control" placeholder="https://your-endpoint-url/v1" value="{{ settings.llm_openai_endpoint_url }}"><span class="ldr-input-help">Enter the OpenAI-compatible API endpoint URL</span></div>++ <!-- Ollama URL (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="ollama_url_container" style="display: none;">+ <label for="ollama_url">Ollama Endpoint</label>+ <input type="text" id="ollama_url" name="ollama_url" class="ldr-form-control" placeholder="http://localhost:11434" value="{{ settings.llm_ollama_url }}">+ <span class="ldr-input-help">Enter the Ollama endpoint URL</span>+ </div></div><div class="ldr-form-row">diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pyindex 39eee9fc84..cc652d39b5 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -9,8 +9,11 @@ from loguru import loggerfrom ..search_engine_base import BaseSearchEnginefrom ...research_library.services.library_rag_service import LibraryRAGService+from ...research_library.services.library_service import LibraryServicefrom ...config.thread_settings import get_setting_from_snapshotfrom ...utilities.llm_utils import get_server_url+from ...database.models.library import RAGIndex+from ...database.session_context import get_user_db_sessionclass LibraryRAGSearchEngine(BaseSearchEngine):@@ -100,28 +103,105 @@ class LibraryRAGSearchEngine(BaseSearchEngine):return []try:- # Initialize RAG service- rag_service = LibraryRAGService(- username=self.username,- embedding_model=self.embedding_model,- embedding_provider=self.embedding_provider,- chunk_size=self.chunk_size,- chunk_overlap=self.chunk_overlap,- )+ # Initialize services+ library_service = LibraryService(username=self.username)- # Get RAG stats to check if there are any indexed documents- stats = rag_service.get_rag_stats()- if stats.get("indexed_documents", 0) == 0:- logger.info("No documents indexed in library RAG")+ # Get all collections for this user+ collections = library_service.get_all_collections()+ if not collections:+ logger.info("No collections found for user")return []- # Load the FAISS index- vector_store = rag_service.load_or_create_faiss_index()+ # Search across all collections and merge results+ all_docs_with_scores = []+ for collection in collections:+ collection_id = collection.get("id")+ if not collection_id:+ continue- # Use FAISS vector store's built-in similarity search- docs_with_scores = vector_store.similarity_search_with_score(- query, k=limit- )+ try:+ # Get the RAG index for this collection to find embedding settings+ with get_user_db_session(self.username) as session:+ collection_name = f"collection_{collection_id}"+ rag_index = (+ session.query(RAGIndex)+ .filter_by(+ collection_name=collection_name,+ is_current=True,+ )+ .first()+ )++ if not rag_index:+ logger.debug(+ f"No RAG index found for collection {collection_id}"+ )+ continue++ # Get embedding settings from the RAG index+ embedding_model = rag_index.embedding_model+ embedding_provider = (+ rag_index.embedding_model_type.value+ )+ chunk_size = rag_index.chunk_size or self.chunk_size+ chunk_overlap = (+ rag_index.chunk_overlap or self.chunk_overlap+ )++ # Create RAG service with the collection's embedding settings+ rag_service = LibraryRAGService(+ username=self.username,+ embedding_model=embedding_model,+ embedding_provider=embedding_provider,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ )++ # Get RAG stats to check if there are any indexed documents+ stats = rag_service.get_rag_stats(collection_id)+ if stats.get("indexed_documents", 0) == 0:+ logger.debug(+ f"No documents indexed in collection {collection_id}"+ )+ continue++ # Load the FAISS index for this collection+ vector_store = rag_service.load_or_create_faiss_index(+ collection_id+ )++ # Search this collection's index+ docs_with_scores = (+ vector_store.similarity_search_with_score(+ query, k=limit+ )+ )++ # Add collection info to metadata and append to results+ for doc, score in docs_with_scores:+ if not doc.metadata:+ doc.metadata = {}+ doc.metadata["collection_id"] = collection_id+ doc.metadata["collection_name"] = collection.get(+ "name", "Unknown"+ )+ all_docs_with_scores.append((doc, score))++ except Exception as e:+ logger.warning(+ f"Error searching collection {collection_id}: {e}"+ )+ continue++ # Sort all results by score (lower is better for distance)+ all_docs_with_scores.sort(key=lambda x: x[1])++ # Take top results across all collections+ docs_with_scores = all_docs_with_scores[:limit]++ if not docs_with_scores:+ logger.info("No results found across any collections")+ return []# Convert Document objects to search results formatresults = []diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex 42de4e48c0..9abc03e480 100644--- a/src/local_deep_research/web_search_engines/search_engines_config.py+++ b/src/local_deep_research/web_search_engines/search_engines_config.py@@ -224,8 +224,9 @@ def search_config("module_path": "local_deep_research.web_search_engines.engines.search_engine_library","class_name": "LibraryRAGSearchEngine","requires_llm": True,+ "display_name": "Library (All Collections)","default_params": {},- "description": "Search your personal research library documents using semantic search",+ "description": "Search across all collections in your personal research library using semantic search","strengths": ["Searches your curated library of research papers and documents","Uses semantic search for better relevance",@@ -258,12 +259,14 @@ def search_config(for collection in collections:engine_id = f"collection_{collection.id}"+ # Add suffix to distinguish from the all-collections search+ display_name = f"{collection.name} (Collection)"search_engines[engine_id] = {"module_path": "local_deep_research.web_search_engines.engines.search_engine_collection","class_name": "CollectionSearchEngine","requires_llm": True,"is_local": True,- "display_name": collection.name,+ "display_name": display_name,"default_params": {"collection_id": collection.id,"collection_name": collection.name,@@ -271,7 +274,7 @@ def search_config("description": (collection.descriptionif collection.description- else f"Search documents in {collection.name} collection"+ else f"Search documents in {collection.name} collection only"),"strengths": [f"Searches only documents in {collection.name}",