Skip to content

~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.

optimizations to design and bugfixing

LearningCircuit9a00301ade50
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 1fff042afe..19f2217e02 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -192,10 +192,8 @@ class DatabaseManager:
sqlcipher3 = get_sqlcipher_module()
# Create tables directly with SQLCipher, bypassing SQLAlchemy DDL
- # Use isolation_level=None to prevent locking issues
- conn = sqlcipher3.connect(
- str(db_path), isolation_level=None, check_same_thread=False
- )
+ # Use DEFERRED isolation level for proper transaction handling
+ conn = sqlcipher3.connect(str(db_path), check_same_thread=False)
# Use centralized SQLCipher setup
set_sqlcipher_key(conn, password)
apply_sqlcipher_pragmas(conn, creation_mode=True)
@@ -239,9 +237,7 @@ class DatabaseManager:
def create_sqlcipher_connection():
"""Create a properly initialized SQLCipher connection."""
- conn = sqlcipher3.connect(
- str(db_path), isolation_level=None, check_same_thread=False
- )
+ conn = sqlcipher3.connect(str(db_path), check_same_thread=False)
cursor = conn.cursor()
# Use centralized SQLCipher setup
@@ -340,9 +336,7 @@ class DatabaseManager:
def create_sqlcipher_connection():
"""Create a properly initialized SQLCipher connection."""
- conn = sqlcipher3.connect(
- str(db_path), isolation_level=None, check_same_thread=False
- )
+ conn = sqlcipher3.connect(str(db_path), check_same_thread=False)
cursor = conn.cursor()
# Use centralized SQLCipher setup
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 035aab01c6..613d378604 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -21,7 +21,6 @@ from loguru import logger
import json
import uuid
from typing import Optional
-from datetime import datetime, timezone
from ...web.auth.decorators import login_required
from ...utilities.db_utils import get_settings_manager
@@ -243,10 +242,17 @@ def get_index_info():
@rag_bp.route("/api/rag/stats", methods=["GET"])
@login_required
def get_rag_stats():
- """Get RAG statistics for the library."""
+ """Get RAG statistics for a collection."""
+ from ...database.library_init import get_default_library_id
+
try:
+ # Get collection_id from request or use default Library collection
+ collection_id = request.args.get("collection_id")
+ if not collection_id:
+ collection_id = get_default_library_id(session["username"])
+
rag_service = get_rag_service()
- stats = rag_service.get_rag_stats()
+ stats = rag_service.get_rag_stats(collection_id)
return jsonify({"success": True, "stats": stats})
except Exception as e:
@@ -259,19 +265,28 @@ def get_rag_stats():
@rag_bp.route("/api/rag/index-document", methods=["POST"])
@login_required
def index_document():
- """Index a single document."""
+ """Index a single document in a collection."""
+ from ...database.library_init import get_default_library_id
+
try:
data = request.get_json()
text_doc_id = data.get("text_doc_id")
force_reindex = data.get("force_reindex", False)
+ collection_id = data.get("collection_id")
if not text_doc_id:
return jsonify(
{"success": False, "error": "text_doc_id is required"}
), 400
+ # Get collection_id from request or use default Library collection
+ if not collection_id:
+ collection_id = get_default_library_id(session["username"])
+
rag_service = get_rag_service()
- result = rag_service.index_document(text_doc_id, force_reindex)
+ result = rag_service.index_document(
+ text_doc_id, collection_id, force_reindex
+ )
if result["status"] == "error":
return jsonify(
@@ -289,18 +304,27 @@ def index_document():
@rag_bp.route("/api/rag/remove-document", methods=["POST"])
@login_required
def remove_document():
- """Remove a document from RAG."""
+ """Remove a document from RAG in a collection."""
+ from ...database.library_init import get_default_library_id
+
try:
data = request.get_json()
text_doc_id = data.get("text_doc_id")
+ collection_id = data.get("collection_id")
if not text_doc_id:
return jsonify(
{"success": False, "error": "text_doc_id is required"}
), 400
+ # Get collection_id from request or use default Library collection
+ if not collection_id:
+ collection_id = get_default_library_id(session["username"])
+
rag_service = get_rag_service()
- result = rag_service.remove_document_from_rag(text_doc_id)
+ result = rag_service.remove_document_from_rag(
+ text_doc_id, collection_id
+ )
if result["status"] == "error":
return jsonify(
@@ -345,13 +369,17 @@ def index_research():
@rag_bp.route("/api/rag/index-all", methods=["GET"])
@login_required
def index_all():
- """Index all documents in the Library collection with Server-Sent Events progress."""
+ """Index all documents in a collection with Server-Sent Events progress."""
from ...database.session_context import get_user_db_session
from ...database.library_init import get_default_library_id
force_reindex = request.args.get("force_reindex", "false").lower() == "true"
username = session["username"]
- library_id = get_default_library_id(username)
+
+ # Get collection_id from request or use default Library collection
+ collection_id = request.args.get("collection_id")
+ if not collection_id:
+ collection_id = get_default_library_id(username)
# Create RAG service in request context before generator runs
rag_service = get_rag_service()
@@ -364,11 +392,14 @@ def index_all():
# Get document IDs to index from DocumentCollection
with get_user_db_session(username) as db_session:
- # Query Document joined with DocumentCollection for the Library
+ # Query Document joined with DocumentCollection for the collection
query = (
db_session.query(Document.id, Document.title)
- .join(DocumentCollection, Document.id == DocumentCollection.document_id)
- .filter(DocumentCollection.collection_id == library_id)
+ .join(
+ DocumentCollection,
+ Document.id == DocumentCollection.document_id,
+ )
+ .filter(DocumentCollection.collection_id == collection_id)
)
if not force_reindex:
@@ -397,7 +428,7 @@ def index_all():
# Process batch with collection_id
batch_results = rag_service.index_documents_batch(
- batch, library_id, force_reindex
+ batch, collection_id, force_reindex
)
# Process results and send progress updates
@@ -524,17 +555,21 @@ def get_documents():
cleanup_current_thread()
username = session["username"]
- library_id = get_default_library_id(username)
+
+ # Get collection_id from request or use default Library collection
+ collection_id = request.args.get("collection_id")
+ if not collection_id:
+ collection_id = get_default_library_id(username)
with get_user_db_session(username) as db_session:
- # Build base query - join Document with DocumentCollection for the Library
- query = (
- db_session.query(Document, DocumentCollection)
- .outerjoin(
- DocumentCollection,
- (DocumentCollection.document_id == Document.id) &
- (DocumentCollection.collection_id == library_id)
- )
+ # Expire all cached objects to ensure we get fresh data from DB
+ db_session.expire_all()
+
+ # Build base query - join Document with DocumentCollection for the collection
+ query = db_session.query(Document, DocumentCollection).outerjoin(
+ DocumentCollection,
+ (DocumentCollection.document_id == Document.id)
+ & (DocumentCollection.collection_id == collection_id),
)
# Apply filters based on DocumentCollection.indexed
@@ -543,8 +578,8 @@ def get_documents():
elif filter_type == "unindexed":
# Documents in library but not indexed, or not in DocumentCollection yet
query = query.filter(
- (DocumentCollection.indexed.is_(False)) |
- (DocumentCollection.id.is_(None))
+ (DocumentCollection.indexed.is_(False))
+ | (DocumentCollection.id.is_(None))
)
# Get total count before pagination
@@ -563,8 +598,12 @@ 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": doc_collection.indexed
+ if doc_collection
+ else False,
+ "chunk_count": doc_collection.chunk_count
+ if doc_collection
+ else 0,
"created_at": doc.created_at.isoformat()
if doc.created_at
else None,
@@ -729,6 +768,9 @@ def get_collections():
if coll.created_at
else None,
"collection_type": coll.collection_type,
+ "is_default": coll.is_default
+ if hasattr(coll, "is_default")
+ else False,
"document_count": len(coll.user_documents)
if hasattr(coll, "user_documents")
else 0,
@@ -777,9 +819,7 @@ def create_collection():
username = session["username"]
with get_user_db_session(username) as db_session:
# Check if collection with this name already exists in this user's database
- existing = (
- db_session.query(Collection).filter_by(name=name).first()
- )
+ existing = db_session.query(Collection).filter_by(name=name).first()
if existing:
return jsonify(
@@ -835,9 +875,7 @@ def update_collection(collection_id):
with get_user_db_session(username) as db_session:
# No need to filter by username - each user has their own database
collection = (
- db_session.query(Collection)
- .filter_by(id=collection_id)
- .first()
+ db_session.query(Collection).filter_by(id=collection_id).first()
)
if not collection:
@@ -907,9 +945,7 @@ def delete_collection(collection_id):
with get_user_db_session(username) as db_session:
# No need to filter by username - each user has their own database
collection = (
- db_session.query(Collection)
- .filter_by(id=collection_id)
- .first()
+ db_session.query(Collection).filter_by(id=collection_id).first()
)
if not collection:
@@ -1088,9 +1124,7 @@ def upload_to_collection(collection_id):
with get_user_db_session(username) as db_session:
# Verify collection exists in this user's database
collection = (
- db_session.query(Collection)
- .filter_by(id=collection_id)
- .first()
+ db_session.query(Collection).filter_by(id=collection_id).first()
)
if not collection:
@@ -1265,9 +1299,7 @@ def get_collection_documents(collection_id):
with get_user_db_session(username) as db_session:
# Verify collection exists in this user's database
collection = (
- db_session.query(Collection)
- .filter_by(id=collection_id)
- .first()
+ db_session.query(Collection).filter_by(id=collection_id).first()
)
if not collection:
@@ -1291,8 +1323,8 @@ def get_collection_documents(collection_id):
"filename": doc.filename,
"file_type": doc.file_type,
"file_size": doc.file_size,
- "uploaded_at": doc.uploaded_at.isoformat()
- if doc.uploaded_at
+ "uploaded_at": doc.created_at.isoformat()
+ if doc.created_at
else None,
"indexed": link.indexed,
"chunk_count": link.chunk_count,
@@ -1380,9 +1412,7 @@ def index_collection(collection_id):
query = (
db_session.query(DocumentCollection, Document)
.join(Document)
- .filter(
- DocumentCollection.collection_id == collection_id
- )
+ .filter(DocumentCollection.collection_id == collection_id)
)
if not force_reindex:
@@ -1414,7 +1444,7 @@ def index_collection(collection_id):
result = rag_service.index_document(
document_id=doc.id,
collection_id=collection_id,
- force_reindex=force_reindex
+ force_reindex=force_reindex,
)
if result.get("status") == "success":
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.py
index 7d9651a8a7..d0f2b733d5 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
@@ -9,7 +9,6 @@ Handles indexing and searching library documents using RAG:
- Track RAG status in library
"""
-from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -225,7 +224,9 @@ class LibraryRAGService:
)
return faiss_index
- def get_current_index_info(self, collection_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ def get_current_index_info(
+ self, collection_id: Optional[str] = None
+ ) -> Optional[Dict[str, Any]]:
"""
Get information about the current RAG index for a collection.
@@ -235,11 +236,16 @@ class LibraryRAGService:
with get_user_db_session(self.username) as session:
# Get collection name
if collection_id:
- collection = session.query(Collection).filter_by(id=collection_id).first()
+ collection = (
+ session.query(Collection)
+ .filter_by(id=collection_id)
+ .first()
+ )
collection_name = collection.name if collection else "unknown"
else:
# Default to Library collection
from ...database.library_init import get_default_library_id
+
collection_id = get_default_library_id(self.username)
collection_name = "Library"
@@ -256,7 +262,8 @@ class LibraryRAGService:
actual_chunk_count = (
session.query(func.sum(DocumentCollection.chunk_count))
.filter_by(collection_id=collection_id, indexed=True)
- .scalar() or 0
+ .scalar()
+ or 0
)
actual_doc_count = (
@@ -294,9 +301,7 @@ class LibraryRAGService:
with get_user_db_session(self.username) as session:
# Get the document
document = (
- session.query(LibraryDocument)
- .filter_by(id=document_id)
- .first()
+ session.query(LibraryDocument).filter_by(id=document_id).first()
)
if not document:
@@ -366,7 +371,11 @@ class LibraryRAGService:
)
# Get collection name for chunk storage
- collection = session.query(Collection).filter_by(id=collection_id).first()
+ collection = (
+ session.query(Collection)
+ .filter_by(id=collection_id)
+ .first()
+ )
collection_name = collection.name if collection else "unknown"
# Store chunks in database using embedding manager
@@ -446,11 +455,29 @@ class LibraryRAGService:
f"Saved FAISS index to {index_path} with integrity tracking"
)
- # Update DocumentCollection with RAG status
- was_already_indexed = doc_collection.indexed # Check BEFORE updating
- doc_collection.indexed = True
- doc_collection.chunk_count = len(chunks)
- doc_collection.last_indexed_at = datetime.now(UTC)
+ # Update DocumentCollection with RAG status using direct SQL
+ # (Direct SQL is used to ensure immediate persistence with encrypted DB + WAL mode)
+ was_already_indexed = (
+ doc_collection.indexed
+ ) # Check BEFORE updating
+
+ from sqlalchemy import text
+ from datetime import datetime, UTC
+
+ # Use direct SQL UPDATE to bypass ORM caching issues with SQLCipher+WAL
+ now = datetime.now(UTC).isoformat()
+ session.execute(
+ text(
+ "UPDATE document_collections SET indexed = 1, chunk_count = :chunks, last_indexed_at = :now "
+ "WHERE document_id = :doc_id AND collection_id = :coll_id"
+ ),
+ {
+ "chunks": len(chunks),
+ "now": now,
+ "doc_id": document_id,
+ "coll_id": collection_id,
+ },
+ )
# Update RAGIndex statistics (only if not already indexed)
rag_index_obj = (
@@ -466,8 +493,12 @@ class LibraryRAGService:
f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1"
)
- # Commit the changes
+ # Commit and checkpoint WAL to ensure persistence
session.commit()
+ session.execute(text("PRAGMA wal_checkpoint(FULL)"))
+ logger.info(
+ f"Indexed document {document_id} with {len(chunks)} chunks"
+ )
logger.info(
f"Successfully indexed document {document_id} for collection {collection_id} "
@@ -514,7 +545,10 @@ class LibraryRAGService:
}
def index_all_documents(
- self, collection_id: str, force_reindex: bool = False, progress_callback=None
+ self,
+ collection_id: str,
+ force_reindex: bool = False,
+ progress_callback=None,
) -> Dict[str, Any]:
"""
Index all documents in a collection into RAG.
@@ -529,7 +563,9 @@ class LibraryRAGService:
"""
with get_user_db_session(self.username) as session:
# Get all DocumentCollection entries for this collection
- query = session.query(DocumentCollection).filter_by(collection_id=collection_id)
+ query = session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ )
if not force_reindex:
# Only index documents that haven't been indexed yet
@@ -551,10 +587,16 @@ class LibraryRAGService:
for idx, doc_collection in enumerate(doc_collections, 1):
# Get the document for title info
- document = session.query(LibraryDocument).filter_by(id=doc_collection.document_id).first()
+ document = (
+ session.query(LibraryDocument)
+ .filter_by(id=doc_collection.document_id)
+ .first()
+ )
title = document.title if document else "Unknown"
- result = self.index_document(doc_collection.document_id, collection_id, force_reindex)
+ result = self.index_document(
+ doc_collection.document_id, collection_id, force_reindex
+ )
if result["status"] == "success":
results["successful"] += 1
@@ -583,7 +625,9 @@ class LibraryRAGService:
return results
- def remove_document_from_rag(self, document_id: str, collection_id: str) -> Dict[str, Any]:
+ def remove_document_from_rag(
+ self, document_id: str, collection_id: str
+ ) -> Dict[str, Any]:
"""
Remove a document's chunks from RAG for a specific collection.
@@ -603,11 +647,18 @@ class LibraryRAGService:
)
if not doc_collection:
- return {"status": "error", "error": "Document not found in collection"}
+ return {
+ "status": "error",
+ "error": "Document not found in collection",
+ }
try:
# Get collection name
- collection = session.query(Collection).filter_by(id=collection_id).first()
+ collection = (
+ session.query(Collection)
+ .filter_by(id=collection_id)
+ .first()
+ )
collection_name = collection.name if collection else "unknown"
# Delete chunks from database
@@ -638,7 +689,10 @@ class LibraryRAGService:
}
def index_documents_batch(
- self, doc_info: List[tuple], collection_id: str, force_reindex: bool = False
+ self,
+ doc_info: List[tuple],
+ collection_id: str,
+ force_reindex: bool = False,
) -> Dict[str, Dict[str, Any]]:
"""
Index multiple documents in a batch for a specific collection.
@@ -671,11 +725,13 @@ class LibraryRAGService:
session.query(DocumentCollection)
.filter(
DocumentCollection.document_id.in_(doc_ids),
- DocumentCollection.collection_id == collection_id
+ DocumentCollection.collection_id == collection_id,
)
.all()
)
- doc_collection_lookup = {dc.document_id: dc for dc in doc_collections}
+ doc_collection_lookup = {
+ dc.document_id: dc for dc in doc_collections
+ }
# Process each document in the batch
for doc_id, title in doc_info:
@@ -690,7 +746,11 @@ class LibraryRAGService:
# Check if already indexed via DocumentCollection
doc_collection = doc_collection_lookup.get(doc_id)
- if doc_collection and doc_collection.indexed and not force_reindex:
+ if (
+ doc_collection
+ and doc_collection.indexed
+ and not force_reindex
+ ):
results[doc_id] = {
"status": "skipped",
"message": "Document already indexed for this collection",
@@ -708,10 +768,14 @@ class LibraryRAGService:
# Index the document
try:
- result = self.index_document(doc_id, collection_id, force_reindex)
+ result = self.index_document(
+ doc_id, collection_id, force_reindex
+ )
results[doc_id] = result
except Exception as e:
- logger.exception(f"Error indexing document {doc_id} in batch")
+ logger.exception(
+ f"Error indexing document {doc_id} in batch"
+ )
results[doc_id] = {
"status": "error",
"error": f"Indexing failed: {type(e).__name__}",
@@ -719,7 +783,9 @@ class LibraryRAGService:
return results
- def get_rag_stats(self, collection_id: Optional[str] = None) -> Dict[str, Any]:
+ def get_rag_stats(
+ self, collection_id: Optional[str] = None
+ ) -> Dict[str, Any]:
"""
Get RAG statistics for a collection.
@@ -733,6 +799,7 @@ class LibraryRAGService:
# Get collection ID (default to Library)
if not collection_id:
from ...database.library_init import get_default_library_id
+
collection_id = get_default_library_id(self.username)
# Count total documents in collection
@@ -753,11 +820,14 @@ class LibraryRAGService:
total_chunks = (
session.query(func.sum(DocumentCollection.chunk_count))
.filter_by(collection_id=collection_id, indexed=True)
- .scalar() or 0
+ .scalar()
+ or 0
)
# Get collection name
- collection = session.query(Collection).filter_by(id=collection_id).first()
+ collection = (
+ session.query(Collection).filter_by(id=collection_id).first()
+ )
collection_name = collection.name if collection else "library"
# Get embedding model info from chunks
diff --git a/src/local_deep_research/web/static/css/collection_details.css b/src/local_deep_research/web/static/css/collection_details.css
index 5b00b1a7a9..37ba009ff7 100644
--- a/src/local_deep_research/web/static/css/collection_details.css
+++ b/src/local_deep_research/web/static/css/collection_details.css
@@ -3,22 +3,36 @@
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
- animation: fadeInUp 0.6s ease;
+ background: #f7fafc !important;
+ min-height: 100vh;
+ color: #2d3748 !important;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-rag-manager-container {
+ animation: fadeInUp 0.6s ease;
+ }
}
/* Header Section */
.ldr-rag-header {
- background: transparent;
+ background: #ffffff !important;
border-radius: 16px;
padding: 30px;
margin-bottom: 25px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- border: 1px solid rgba(255, 255, 255, 0.2);
- animation: slideDown 0.6s ease-out;
+ border: 1px solid #e2e8f0;
+ color: #2d3748 !important;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-rag-header {
+ animation: slideDown 0.6s ease-out;
+ }
}
.ldr-rag-header h1 {
- color: #2d3748;
+ color: #2d3748 !important;
font-size: 2.5rem;
font-weight: 700;
margin: 15px 0;
@@ -32,7 +46,7 @@
}
.ldr-subtitle {
- color: #718096;
+ color: #4a5568;
font-size: 1.1rem;
margin: 10px 0 0 0;
font-style: italic;
@@ -40,19 +54,24 @@
/* Section Styling */
.ldr-rag-section {
- background: transparent;
+ background: #ffffff;
border-radius: 16px;
padding: 25px;
margin-bottom: 25px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- border: 1px solid rgba(255, 255, 255, 0.2);
- animation: fadeInUp 0.8s ease-out;
+ border: 1px solid #e2e8f0;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
-.ldr-rag-section:hover {
- transform: translateY(-2px);
- box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-rag-section {
+ animation: fadeInUp 0.8s ease-out;
+ }
+
+ .ldr-rag-section:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
+ }
}
.ldr-section-header {
@@ -608,6 +627,29 @@
}
}
+/* Accessibility: Reduced Motion Support */
+@media (prefers-reduced-motion: reduce) {
+ *,
+ *::before,
+ *::after {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ scroll-behavior: auto !important;
+ }
+
+ .ldr-rag-section:hover,
+ .ldr-btn-collections:hover,
+ .ldr-stat-card:hover,
+ .ldr-document-item:hover {
+ transform: none !important;
+ }
+
+ .ldr-progress-fill::after {
+ animation: none !important;
+ }
+}
+
/* Dark Theme Support */
@media (prefers-color-scheme: dark) {
.ldr-rag-manager-container {
@@ -727,7 +769,7 @@
color: #007bff;
}
-/* Modal Styles */
+/* Modal Styles - Optimized for performance */
.ldr-modal {
display: none;
position: fixed;
@@ -736,21 +778,41 @@
top: 0;
width: 100%;
height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- backdrop-filter: blur(5px);
- animation: fadeIn 0.3s ease;
+ background-color: rgba(0, 0, 0, 0.75);
+ /* Removed backdrop-filter for better performance - use darker overlay instead */
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-modal {
+ animation: fadeIn 0.3s ease;
+ }
+}
+
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
}
.ldr-modal-content {
- background: rgba(255, 255, 255, 0.1);
+ background: #ffffff;
margin: 5% auto;
- border: 1px solid rgba(255, 255, 255, 0.2);
+ border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 16px;
width: 90%;
max-width: 500px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
- animation: slideInDown 0.3s ease;
overflow: hidden;
+ /* Removed backdrop-filter for better performance */
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-modal-content {
+ animation: slideInDown 0.3s ease;
+ }
}
@keyframes slideInDown {
@@ -810,8 +872,8 @@
.ldr-form-group label {
display: block;
margin-bottom: 0.5rem;
- font-weight: 500;
- color: #718096;
+ font-weight: 600;
+ color: #2d3748;
font-size: 0.95rem;
}
@@ -821,7 +883,7 @@
padding: 0.75rem 1rem;
border: 2px solid #e2e8f0;
border-radius: 10px;
- background-color: rgba(255, 255, 255, 0.1);
+ background-color: #ffffff;
color: #2d3748;
font-family: inherit;
font-size: 1rem;
@@ -851,7 +913,7 @@
}
.ldr-form-help {
- color: #718096;
+ color: #4a5568;
font-size: 0.9rem;
margin-top: 0.5rem;
font-style: italic;
@@ -882,24 +944,27 @@
border: 3px solid #667eea;
}
-/* Special styling for upload button to make it stand out */
-#upload-files-btn.ldr-btn-collections-primary {
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- color: white;
+/* Featured button styling (extracted from inline styles) */
+.ldr-btn-featured {
+ text-decoration: none;
+ font-size: 1.1rem;
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
- border: 3px solid #667eea;
- animation: pulse 2s infinite;
+ font-weight: 600;
}
-@keyframes pulse {
- 0% {
+/* Subtle pulse animation - only for users who haven't disabled motion */
+@media (prefers-reduced-motion: no-preference) {
+ .ldr-btn-featured:hover {
+ animation: gentle-pulse 2s ease-in-out;
+ }
+}
+
+@keyframes gentle-pulse {
+ 0%, 100% {
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
50% {
- box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
- }
- 100% {
- box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
+ box-shadow: 0 8px 25px rgba(102, 126, 234, 0.5);
}
}
@@ -998,13 +1063,13 @@
color: white !important;
}
-/* Embedding Settings Card */
+/* Embedding Settings Card - Optimized */
.ldr-embedding-settings-card {
- background: rgba(255, 255, 255, 0.1);
+ background: rgba(247, 250, 252, 0.95);
border-radius: 12px;
padding: 20px;
- border: 1px solid rgba(255, 255, 255, 0.2);
- backdrop-filter: blur(10px);
+ border: 1px solid rgba(226, 232, 240, 0.8);
+ /* Removed backdrop-filter for better performance */
}
.ldr-embedding-info h4 {
@@ -1041,3 +1106,163 @@
.ldr-embedding-info .ldr-info-value {
color: #2d3748;
}
+
+/* Performance Optimizations */
+@media (prefers-reduced-motion: no-preference) {
+ /* Hint to browser which properties will change for better optimization */
+ .ldr-btn-collections,
+ .ldr-stat-card,
+ .ldr-document-item {
+ will-change: transform, box-shadow;
+ }
+
+ .ldr-progress-fill {
+ will-change: width;
+ }
+
+ /* Remove will-change after hover to free up resources */
+ .ldr-btn-collections:not(:hover),
+ .ldr-stat-card:not(:hover),
+ .ldr-document-item:not(:hover) {
+ will-change: auto;
+ }
+}
+
+/* GPU acceleration for smooth animations */
+.ldr-modal-content,
+.ldr-btn-collections,
+.ldr-stat-card {
+ transform: translateZ(0);
+ backface-visibility: hidden;
+}
+
+/* Utility Classes for Common Patterns */
+.ldr-flex-row {
+ display: flex;
+ align-items: center;
+ gap: 15px;
+ margin-bottom: 10px;
+}
+
+.ldr-featured-section {
+ background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
+ background-color: #ffffff;
+ border: 2px solid #667eea;
+}
+
+.ldr-char-counter {
+ font-size: 0.875rem;
+ color: #718096;
+ margin-top: 0.25rem;
+}
+
+.ldr-content-padding {
+ padding: 1rem;
+}
+
+.ldr-text-center-muted {
+ text-align: center;
+ color: #718096;
+ font-style: italic;
+ margin-bottom: 1rem;
+}
+
+.ldr-link-button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ text-decoration: none;
+ padding: 1rem 2rem;
+}
+
+.ldr-section-footer {
+ margin-top: 2rem;
+}
+
+.ldr-hidden {
+ display: none;
+}
+
+/* Guidelines styling */
+.ldr-content-padding h3 {
+ color: #2d3748;
+ font-size: 1.1rem;
+ font-weight: 600;
+ margin-top: 1.5rem;
+ margin-bottom: 0.75rem;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.ldr-content-padding h3:first-child {
+ margin-top: 0;
+}
+
+.ldr-content-padding h3 i {
+ color: #667eea;
+}
+
+.ldr-content-padding ul {
+ list-style: none;
+ padding-left: 0;
+ margin-bottom: 1.5rem;
+}
+
+.ldr-content-padding li {
+ padding: 0.5rem 0;
+ padding-left: 1.5rem;
+ position: relative;
+ color: #2d3748;
+ line-height: 1.6;
+}
+
+.ldr-content-padding li::before {
+ content: "→";
+ position: absolute;
+ left: 0;
+ color: #667eea;
+ font-weight: bold;
+}
+
+/* Info Text */
+.ldr-info-text {
+ font-size: 1rem;
+ color: #2d3748;
+ margin-bottom: 1rem;
+ line-height: 1.6;
+}
+
+/* Quick Tips Styling */
+.ldr-quick-tips {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ margin: 1.5rem 0;
+}
+
+.ldr-tip-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 1rem;
+ padding: 1rem;
+ background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
+ border-left: 3px solid #667eea;
+ border-radius: 8px;
+}
+
+.ldr-tip-item i {
+ color: #667eea;
+ font-size: 1.25rem;
+ margin-top: 0.125rem;
+ flex-shrink: 0;
+}
+
+.ldr-tip-item div {
+ color: #2d3748;
+ line-height: 1.6;
+}
+
+.ldr-tip-item strong {
+ color: #667eea;
+}
diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.js
index 16c08c2583..b6e54fd760 100644
--- a/src/local_deep_research/web/static/js/rag_manager.js
+++ b/src/local_deep_research/web/static/js/rag_manager.js
@@ -27,20 +27,31 @@ let currentFilter = 'all';
let currentPage = 1;
let totalPages = 1;
const perPage = 50;
+let currentCollectionId = null; // Currently selected collection
/**
* Initialize the page
*/
document.addEventListener('DOMContentLoaded', function() {
- // Load available models first, then settings
- loadAvailableModels().then(() => {
- // After models are loaded, load current settings
- loadCurrentSettings();
+ // Load collections first, then everything else
+ loadCollections().then(() => {
+ // After collection is selected, load the rest
+ loadAvailableModels().then(() => {
+ loadCurrentSettings();
+ });
+ loadCurrentIndexInfo();
+ loadStats();
+ loadDocuments();
});
- loadCurrentIndexInfo();
- loadStats();
- loadDocuments();
+ // Setup collection selector change handler
+ document.getElementById('collection-selector').addEventListener('change', function() {
+ currentCollectionId = this.value;
+ // Reload everything when collection changes
+ loadCurrentIndexInfo();
+ loadStats();
+ loadDocuments();
+ });
// Setup provider change handler
document.getElementById('embedding-provider').addEventListener('change', function() {
@@ -59,6 +70,35 @@ document.addEventListener('DOMContentLoaded', function() {
document.getElementById('rag-config-form').addEventListener('submit', handleConfigSubmit);
});
+/**
+ * Load available collections
+ */
+async function loadCollections() {
+ try {
+ const response = await safeFetch('/library/api/collections');
+ const data = await response.json();
+
+ if (data.success && data.collections) {
+ const selector = document.getElementById('collection-selector');
+ selector.innerHTML = '';
+
+ data.collections.forEach(collection => {
+ const option = document.createElement('option');
+ option.value = collection.id;
+ option.textContent = collection.name;
+ if (collection.is_default) {
+ option.selected = true;
+ currentCollectionId = collection.id;
+ }
+ selector.appendChild(option);
+ });
+ }
+ } catch (error) {
+ console.error('Error loading collections:', error);
+ showError('Failed to load collections');
+ }
+}
+
/**
* Load available embedding providers and models
*/
@@ -351,10 +391,12 @@ function checkSettingsMismatch() {
* Load RAG statistics
*/
async function loadStats() {
+ if (!currentCollectionId) return;
+
const statsContainer = document.getElementById('rag-stats');
try {
- const response = await safeFetch('/library/api/rag/stats');
+ const response = await safeFetch(`/library/api/rag/stats?collection_id=${currentCollectionId}`);
const data = await response.json();
if (data.success) {
@@ -458,6 +500,11 @@ async function handleConfigSubmit(event) {
* Index all documents
*/
async function indexAllDocuments(forceReindex) {
+ if (!currentCollectionId) {
+ showError('Please select a collection first');
+ return;
+ }
+
const progressContainer = document.getElementById('progress-container');
const progressBar = document.getElementById('progress-bar');
const progressLog = document.getElementById('progress-log');
@@ -478,7 +525,7 @@ async function indexAllDocuments(forceReindex) {
function createEventSource() {
try {
- eventSource = new EventSource(`/library/api/rag/index-all?force_reindex=${forceReindex}`);
+ eventSource = new EventSource(`/library/api/rag/index-all?force_reindex=${forceReindex}&collection_id=${currentCollectionId}`);
eventSource.onmessage = function(event) {
// Reset reconnect attempts on successful message
@@ -516,9 +563,10 @@ async function indexAllDocuments(forceReindex) {
progressBar.textContent = '100%';
progressBar.classList.remove('ldr-progress-bar-animated');
- // Refresh stats
+ // Refresh stats and document list
setTimeout(() => {
refreshStats();
+ loadDocuments();
}, 1000);
closeEventSource();
@@ -634,11 +682,13 @@ function showError(message) {
* Load documents list with pagination
*/
async function loadDocuments(page = 1) {
+ if (!currentCollectionId) return;
+
const documentsContainer = document.getElementById('documents-list');
try {
const response = await safeFetch(
- `/library/api/rag/documents?page=${page}&per_page=${perPage}&filter=${currentFilter}`
+ `/library/api/rag/documents?page=${page}&per_page=${perPage}&filter=${currentFilter}&collection_id=${currentCollectionId}`
);
const data = await response.json();
@@ -819,6 +869,11 @@ function filterDocuments(filter) {
* Index a single document
*/
async function indexDocument(docId, title) {
+ if (!currentCollectionId) {
+ showError('Please select a collection first');
+ return;
+ }
+
try {
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
const response = await safeFetch('/library/api/rag/index-document', {
@@ -829,6 +884,7 @@ async function indexDocument(docId, title) {
},
body: JSON.stringify({
text_doc_id: docId,
+ collection_id: currentCollectionId,
force_reindex: false
})
});
@@ -851,6 +907,11 @@ async function indexDocument(docId, title) {
* Re-index a document
*/
async function reindexDocument(docId, title) {
+ if (!currentCollectionId) {
+ showError('Please select a collection first');
+ return;
+ }
+
try {
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
const response = await safeFetch('/library/api/rag/index-document', {
@@ -861,6 +922,7 @@ async function reindexDocument(docId, title) {
},
body: JSON.stringify({
text_doc_id: docId,
+ collection_id: currentCollectionId,
force_reindex: true
})
});
@@ -883,6 +945,11 @@ async function reindexDocument(docId, title) {
* Remove a document from RAG
*/
async function removeDocument(docId, title) {
+ if (!currentCollectionId) {
+ showError('Please select a collection first');
+ return;
+ }
+
if (!confirm(`Are you sure you want to remove "${title}" from the RAG index?`)) {
return;
}
@@ -896,7 +963,8 @@ async function removeDocument(docId, title) {
'X-CSRFToken': csrfToken
},
body: JSON.stringify({
- text_doc_id: docId
+ text_doc_id: docId,
+ collection_id: currentCollectionId
})
});
diff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.html
index bc741fdefa..17d7a24a1d 100644
--- a/src/local_deep_research/web/templates/pages/collection_create.html
+++ b/src/local_deep_research/web/templates/pages/collection_create.html
@@ -10,7 +10,7 @@
<div class="ldr-rag-manager-container">
<!-- Header -->
<div class="ldr-rag-header">
- <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 10px;">
+ <div class="ldr-flex-row">
<a href="/library/collections" class="ldr-btn-collections ldr-btn-collections-secondary">
<i class="fas fa-arrow-left"></i> Back to Collections
</a>
@@ -20,7 +20,7 @@
</div>
<!-- Create Collection Form -->
- <div class="ldr-rag-section" style="background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border: 2px solid #667eea;">
+ <div class="ldr-rag-section ldr-featured-section">
<div class="ldr-section-header">
<h2><i class="fas fa-plus-circle"></i> Collection Details</h2>
</div>
@@ -32,7 +32,7 @@
placeholder="Enter a descriptive name for your collection"
maxlength="100">
<div class="ldr-form-help">Choose a name that clearly describes what documents will be in this collection (e.g., "Research Papers on AI Ethics", "Product Documentation 2025")</div>
- <div id="name-counter" style="font-size: 0.875rem; color: #718096; margin-top: 0.25rem;">100 characters remaining</div>
+ <div id="name-counter" class="ldr-char-counter">100 characters remaining</div>
</div>
<div class="ldr-form-group">
@@ -46,52 +46,46 @@
<button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" onclick="window.location.href='/library/collections'">
<i class="fas fa-times"></i> Cancel
</button>
- <button type="submit" class="ldr-btn-collections ldr-btn-collections-primary ldr-btn-lg" id="create-collection-btn" style="font-size: 1.2rem; padding: 1rem 2rem; min-width: 200px;">
- <i class="fas fa-folder-plus"></i> 🚀 Create Collection
+ <button type="submit" class="ldr-btn-collections ldr-btn-collections-primary ldr-btn-lg ldr-btn-featured" id="create-collection-btn">
+ <i class="fas fa-folder-plus"></i> Create Collection
</button>
</div>
</form>
<!-- Results display area -->
- <div id="create-results" style="display: none;"></div>
+ <div id="create-results" class="ldr-hidden"></div>
</div>
- <!-- Instructions Section -->
+ <!-- Quick Info Section -->
<div class="ldr-rag-section">
<div class="ldr-section-header">
- <h2><i class="fas fa-info-circle"></i> Collection Guidelines</h2>
+ <h2><i class="fas fa-info-circle"></i> What's Next?</h2>
</div>
- <div style="padding: 1rem;">
- <h3>📝 Naming Your Collection</h3>
- <ul>
- <li><strong>Be Specific</strong> - Use descriptive names like "Q4 2024 Marketing Research" instead of generic names</li>
- <li><strong>Include Time Period</strong> - Add years or quarters to help with organization (e.g., "Customer Feedback 2024", "Technical Documentation v2.1")</li>
- <li><strong>Consider Purpose</strong> - Think about how you'll use the collection (research, reference, documentation, etc.)</li>
- <li><strong>Use Descriptive Keywords</strong> - Include terms that will help you find content later</li>
- </ul>
+ <div class="ldr-content-padding">
+ <p class="ldr-info-text">
+ After creating your collection, you can upload documents and index them for semantic search.
+ Collections help you organize documents by topic, project, or time period.
+ </p>
- <h3>💡 Upload Strategy</h3>
- <ul>
- <li><strong>Start Small</strong> - Create focused collections rather than dumping everything into one large collection</li>
- <li><strong>Group by Topic</strong> - Related documents work better together (e.g., separate collections for different projects)</li>
- <li><strong>Plan for Growth</strong> - Leave room to add more documents as your needs evolve</li>
- </ul>
-
- <h3>📋 Best Practices</h3>
- <ul>
- <li><strong>Regular Organization</strong> - Keep collections manageable and well-organized</li>
- <li><strong>Clear Descriptions</strong> - Always include clear descriptions for better searchability</li>
- <li><strong>Consistent Naming</strong> - Use a standard naming convention across collections</li>
- <li><strong>Backup Important</strong> - Create separate collections for critical or frequently accessed documents</li>
- </ul>
+ <div class="ldr-quick-tips">
+ <div class="ldr-tip-item">
+ <i class="fas fa-lightbulb"></i>
+ <div>
+ <strong>Tip:</strong> Use descriptive names like "AI Research 2024" instead of generic names
+ </div>
+ </div>
+ <div class="ldr-tip-item">
+ <i class="fas fa-folder"></i>
+ <div>
+ <strong>Tip:</strong> Group related documents together for better semantic search results
+ </div>
+ </div>
+ </div>
- <div style="margin-top: 2rem;">
- <p style="text-align: center; color: #718096; font-style: italic; margin-bottom: 1rem;">
- After creating your collection, you can immediately start uploading documents using the dedicated upload interface.
- </p>
- <a href="/library/collections" class="ldr-btn-collections ldr-btn-collections-primary" style="display: inline-flex; align-items: center; justify-content: center; text-decoration: none; padding: 1rem 2rem;">
- <i class="fas fa-folder-open"></i> 📁 View All Collections
+ <div class="ldr-section-footer">
+ <a href="/library/collections" class="ldr-btn-collections ldr-btn-collections-secondary ldr-link-button">
+ <i class="fas fa-arrow-left"></i> Back to Collections
</a>
</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
index 55550229a2..ca359fa71d 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -26,8 +26,8 @@
</div>
<div class="ldr-collection-actions-grid">
- <a href="/library/collections/{{ collection_id }}/upload" class="ldr-btn-collections ldr-btn-collections-primary ldr-btn-lg" style="text-decoration: none; display: inline-flex; align-items: center; justify-content: center; font-size: 1.3rem; padding: 1.25rem 2.5rem; min-width: 250px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: 3px solid #667eea; box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5); animation: pulse 2s infinite;">
- <i class="fas fa-upload"></i> 🚀 Upload Files
+ <a href="/library/collections/{{ collection_id }}/upload" class="ldr-btn-collections ldr-btn-collections-primary ldr-btn-lg ldr-btn-featured">
+ <i class="fas fa-upload"></i> Upload Files
</a>
<button id="index-collection-btn" class="ldr-btn-collections ldr-btn-collections-success ldr-btn-lg">
<i class="fas fa-sync"></i> Index All Documents
diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.html
index e56b183d0b..9c6aa731fb 100644
--- a/src/local_deep_research/web/templates/pages/embedding_settings.html
+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html
@@ -468,6 +468,5 @@
}
</style>
-<script src="/static/js/security/url-validator.js"></script>
<script src="/static/js/embedding_settings.js"></script>
{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.html
index d41ffa6736..ed151ff45e 100644
--- a/src/local_deep_research/web/templates/pages/history.html
+++ b/src/local_deep_research/web/templates/pages/history.html
@@ -47,7 +47,6 @@
<script src="/static/js/services/formatting.js"></script>
<script src="/static/js/services/api.js"></script>
<!-- Load URL utilities -->
-<script src="/static/js/security/url-validator.js"></script>
<script src="/static/js/config/urls.js"></script>
<!-- Then load the component -->
<script src="/static/js/components/history.js"></script>
diff --git a/src/local_deep_research/web/templates/pages/rag_manager.html b/src/local_deep_research/web/templates/pages/rag_manager.html
index d4f9f0cd30..552e972cbb 100644
--- a/src/local_deep_research/web/templates/pages/rag_manager.html
+++ b/src/local_deep_research/web/templates/pages/rag_manager.html
@@ -9,6 +9,16 @@
<p class="ldr-subtitle">Manage semantic search indexing for your library documents</p>
</div>
+ <!-- Collection Selector -->
+ <div class="ldr-rag-collection-selector ldr-mb-4">
+ <div class="ldr-form-group">
+ <label for="collection-selector"><i class="fas fa-folder"></i> Select Collection</label>
+ <select id="collection-selector" class="ldr-form-control ldr-form-control-lg">
+ <option value="">Loading collections...</option>
+ </select>
+ </div>
+ </div>
+
<!-- Configuration Panel -->
<div class="ldr-rag-config-panel">
<h2><i class="fas fa-cog"></i> Configuration</h2>
@@ -505,6 +515,5 @@
}
</style>
-<script src="/static/js/security/url-validator.js"></script>
<script src="/static/js/rag_manager.js"></script>
{% endblock %}