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.

feat: add semantic search over research history (#1475)

LearningCircuit40b885e2f2d1
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 451d58dccf..d96f05554c 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -140,14 +140,17 @@ paths = [
# RAG routes and services use db_password variable names (not actual secrets)
'''src/local_deep_research/research_library/routes/rag_routes\.py$''',
'''src/local_deep_research/research_library/services/library_rag_service\.py$''',
- # SQLCipher utilities use key derivation functions (not actual secrets)
- '''src/local_deep_research/database/sqlcipher_utils\.py$''',
+ # RAG service factory passes db_password variable names (not actual secrets)
+ '''src/local_deep_research/research_library/services/rag_service_factory\.py$''',
# Encrypted DB manager uses key derivation and password parameters (not actual secrets)
'''src/local_deep_research/database/encrypted_db\.py$''',
# Metrics search tracker uses password variable names for DB credentials (not actual secrets)
'''src/local_deep_research/metrics/search_tracker\.py$''',
# Auto-generated configuration docs reference env var names like ENCRYPTION_KEY (not actual secrets)
- '''docs/CONFIGURATION\.md$'''
+ '''docs/CONFIGURATION\.md$''',
+ '''src/local_deep_research/research_library/services/research_history_indexer\.py$''',
+ '''src/local_deep_research/research_library/search/services/research_history_indexer\.py$''',
+ '''src/local_deep_research/web/queue/processor_v2\.py$'''
]
files = [
"\\.env\\.example$",
@@ -264,6 +267,7 @@ regexes = [
'''db_password\s*=\s*session_password_store\.get_session_password''',
'''db_password\s*=\s*db_password''',
'''db_password=db_password''',
+ '''db_password=user_password''',
'''db_password:\s*Optional\[str\]''',
'''self\._db_password\s*=\s*db_password''',
'''embedding_manager\.db_password\s*=\s*db_password''',
diff --git a/.gitleaksignore b/.gitleaksignore
index a4c8fc96f7..f796140f15 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -551,3 +551,19 @@ src/local_deep_research/followup_research/routes.py:generic-secret:222
src/local_deep_research/web/auth/password_utils.py:generic-secret:32
src/local_deep_research/web/auth/password_utils.py:generic-secret:45
src/local_deep_research/followup_research/routes.py:generic-secret:206
+
+# Semantic search routes — db_password variable names (false positives)
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:49
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:94
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:141
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:200
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:217
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:295
+src/local_deep_research/research_library/search/services/research_history_indexer.py:generic-secret:46
+src/local_deep_research/research_library/search/services/research_history_indexer.py:generic-secret:52
+src/local_deep_research/research_library/search/services/research_history_indexer.py:generic-secret:55
+src/local_deep_research/research_library/search/routes/search_routes.py:generic-secret:293
+
+# Auto-conversion hook — db_password variable name (false positive)
+src/local_deep_research/web/queue/processor_v2.py:generic-secret:357
+src/local_deep_research/web/queue/processor_v2.py:generic-secret:358
diff --git a/docs/architecture/DATABASE_SCHEMA.md b/docs/architecture/DATABASE_SCHEMA.md
index f2878bef30..4142c7891c 100644
--- a/docs/architecture/DATABASE_SCHEMA.md
+++ b/docs/architecture/DATABASE_SCHEMA.md
@@ -273,7 +273,7 @@ Documents in the research library.
|--------|------|-------------|
| `id` | Integer | Primary key |
| `title` | String(500) | Document title |
-| `source_type` | Enum | SourceType (upload, url, api) |
+| `source_type` | FK → SourceType | Source type (see SourceType table) |
| `source_url` | Text | Original source URL |
| `file_path` | Text | Local file path |
| `file_hash` | String(64) | Content hash |
@@ -284,7 +284,7 @@ Documents in the research library.
| `created_at` | DateTime | When added |
| `indexed_at` | DateTime | When indexed for RAG |
-**Enum SourceType:** upload, url, doi, arxiv, pubmed, semantic_scholar
+**SourceType** (normalized table): research_download, user_upload, manual_entry, research_report, research_source
#### Collection
@@ -635,5 +635,6 @@ Failed verification attempts.
## See Also
- [Architecture Overview](./OVERVIEW.md) - System architecture
+- [Semantic Search](./SEMANTIC_SEARCH.md) - How Document/Collection models enable semantic search
- [Extension Guide](../developing/EXTENDING.md) - Adding custom components
- [Troubleshooting](../troubleshooting.md) - Common issues
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index c73e0a33dd..78f4e07485 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -465,5 +465,6 @@ src/local_deep_research/
## See Also
- [Database Schema](./DATABASE_SCHEMA.md) - Detailed data model documentation
+- [Semantic Search](./SEMANTIC_SEARCH.md) - Indexing pipeline, search modes, and three-tier merge algorithm
- [Extension Guide](../developing/EXTENDING.md) - How to add custom components
- [Troubleshooting](../troubleshooting.md) - Common issues and solutions
diff --git a/docs/architecture/SEMANTIC_SEARCH.md b/docs/architecture/SEMANTIC_SEARCH.md
new file mode 100644
index 0000000000..81804f81b8
--- /dev/null
+++ b/docs/architecture/SEMANTIC_SEARCH.md
@@ -0,0 +1,167 @@
+# Semantic Search
+
+Semantic search lets users find research by meaning, not just title keywords. It indexes completed research reports and their sources into FAISS vector stores, then offers three search modes -- Hybrid (default), Text-Only, and AI-Only -- with a three-tier ranked merge algorithm for hybrid results.
+
+## Table of Contents
+
+- [Indexing Pipeline](#indexing-pipeline)
+- [Search Pipeline](#search-pipeline)
+- [Three-Tier Merge Algorithm](#three-tier-merge-algorithm)
+- [File Structure](#file-structure)
+- [API Routes](#api-routes)
+- [Reusing on Other Pages](#reusing-on-other-pages)
+- [See Also](#see-also)
+
+---
+
+## Indexing Pipeline
+
+```mermaid
+flowchart LR
+ RH[ResearchHistory<br/>report + sources] --> RHI[ResearchHistoryIndexer<br/>converts to Documents]
+ RHI --> DOC[Document rows<br/>+ DocumentCollection links]
+ DOC --> FACTORY[RAGServiceFactory<br/>resolves settings]
+ FACTORY --> RAG[LibraryRAGService<br/>chunk + embed]
+ RAG --> FAISS[(FAISS Index<br/>on disk)]
+```
+
+**Steps:**
+
+1. `ResearchHistoryIndexer` reads completed `ResearchHistory` rows and their `ResearchResource` sources.
+2. Each report becomes a `Document` (source\_type `research_report`). Each source with sufficient content becomes a `Document` (source\_type `research_source`).
+3. Documents are linked to the History `Collection` via `DocumentCollection`.
+4. `RAGServiceFactory` creates a `LibraryRAGService` with the collection's embedding settings.
+5. `LibraryRAGService` chunks each document, generates embeddings, and writes the FAISS index to disk.
+
+Bulk indexing uses **SSE streaming** -- the `/index` endpoint yields progress events (`start`, `progress`, `complete`, `error`) so the frontend can show a real-time progress bar.
+
+---
+
+## Search Pipeline
+
+```mermaid
+flowchart LR
+ Q[User query] --> MODE{Search Mode}
+ MODE -->|Text-Only| TF[Title filter<br/>instant, client-side]
+ MODE -->|AI-Only| API
+ MODE -->|Hybrid| TF & API
+
+ API[POST /library/api/collections/:id/search] --> CSE[CollectionSearchEngine]
+ CSE --> FAISS[(FAISS Index)]
+ FAISS --> ENRICH[Enrich metadata<br/>report/source type]
+ ENRICH --> JSON[JSON response]
+
+ TF --> RENDER
+ JSON --> MERGE[buildTieredResults<br/>three-tier merge]
+ MERGE --> RENDER[Render cards]
+```
+
+**Text filter** runs instantly on the client against cached history items. **Semantic search** is an async `POST` to the collection search endpoint, which delegates to `CollectionSearchEngine` for FAISS similarity search. In **Hybrid mode**, text results render immediately while the semantic call runs in the background; once it resolves, `buildTieredResults` merges both result sets into three tiers and re-renders.
+
+---
+
+## Three-Tier Merge Algorithm
+
+Implemented in `semantic_search.js :: buildTieredResults()`.
+
+| Tier | Contents | Sort Order |
+|------|----------|------------|
+| **Tier 1** | Matched both text filter AND semantic search | Similarity score DESC |
+| **Tier 2** | Text-only matches (no semantic hit) | Original order (recency) |
+| **Tier 3** | Semantic-only matches (below a visual divider) | Similarity score DESC |
+
+The merge groups semantic results by `research_id` (keeping the best similarity per research), then classifies each text result as Tier 1 or Tier 2 based on whether a corresponding semantic match exists. Remaining semantic-only results become Tier 3.
+
+---
+
+## File Structure
+
+### Backend
+
+```
+research_library/
+├── search/ # Semantic search subpackage
+│ ├── __init__.py # Exports search_bp, ResearchHistoryIndexer
+│ ├── routes/
+│ │ └── search_routes.py # 4 endpoints + _enrich helper
+│ └── services/
+│ └── research_history_indexer.py # Converts ResearchHistory -> Documents -> RAG
+├── services/
+│ ├── rag_service_factory.py # Creates LibraryRAGService with collection settings
+│ └── library_rag_service.py # FAISS indexing, chunking, embedding management
+```
+
+### Frontend
+
+```
+js/components/
+├── semantic_search.js # Shared module (window.SemanticSearch):
+│ # renderSnippet, buildTieredResults,
+│ # createSemanticResultCard, isSafeExternalUrl
+├── history.js # Page controller: mode switching, hybrid merge, rendering
+└── history_search.js # Indexing UI, semantic API calls, collection ID caching
+
+js/config/
+└── constants.js # LDR_CONSTANTS.SEARCH_MODE: HYBRID | TEXT | SEMANTIC
+
+css/components/
+└── semantic-search.css # All semantic search styles (badges, cards, dividers)
+```
+
+---
+
+## API Routes
+
+All routes require `@login_required`. Blueprint prefix: `/library`.
+
+| Method | Path | Purpose |
+|--------|------|---------|
+| `GET` | `/api/research-history/collection` | Get collection ID and indexing status (auto-converts unconverted entries) |
+| `POST` | `/api/research-history/convert-all` | Convert all completed research to Documents |
+| `POST` | `/api/research/<id>/add-to-collection` | Add research to a custom collection |
+| `POST` | `/api/collections/<id>/search` | Semantic search any collection (generic) |
+
+The search endpoint is **collection-agnostic** -- it works for any collection type. For `research_history` collections, results are enriched with report/source type metadata.
+
+---
+
+## Reusing on Other Pages
+
+The `semantic_search.js` shared module is designed for reuse on library or collection pages.
+
+1. **Load the shared assets** in your template (order matters):
+ ```html
+ <link rel="stylesheet" href="/static/css/components/semantic-search.css">
+ <script defer src="/static/js/components/semantic_search.js"></script>
+ ```
+
+2. **Call the search endpoint** with `POST /library/api/collections/<collection_id>/search`:
+ ```javascript
+ const response = await fetch(`/library/api/collections/${collectionId}/search`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ query: 'your search', limit: 10 }),
+ });
+ const { results } = await response.json();
+ ```
+
+3. **Render results** using the shared utilities:
+ ```javascript
+ for (const result of results) {
+ container.appendChild(SemanticSearch.createSemanticResultCard(result));
+ }
+
+ // Or for hybrid mode with text + semantic merge:
+ const tiered = SemanticSearch.buildTieredResults(textResults, semanticResults);
+ // tiered.tier1, tiered.tier2, tiered.tier3
+ ```
+
+No backend changes needed -- the search route and `CollectionSearchEngine` already support any collection type.
+
+---
+
+## See Also
+
+- [Architecture Overview](./OVERVIEW.md) -- System architecture
+- [Database Schema](./DATABASE_SCHEMA.md) -- Document, Collection, and DocumentCollection models
+- [Library & RAG Guide](../library-and-rag.md) -- User-facing guide to library and search features
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index 30811819c5..fd214efed7 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -78,3 +78,13 @@ FILE_PATH_SENTINELS = (
# --- Snippet / truncation lengths ---
SNIPPET_LENGTH_SHORT = 250
SNIPPET_LENGTH_LONG = 500
+
+# --- Research history collection ---
+RESEARCH_HISTORY_COLLECTION_NAME = "History"
+RESEARCH_HISTORY_COLLECTION_DESCRIPTION = (
+ "Your research history indexed for AI-powered semantic search. "
+ "Indexing converts past research reports and their sources into "
+ "searchable content, enabling natural-language queries across all "
+ "your previous research. Used by the History page search when in "
+ "AI or Hybrid mode."
+)
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index 4017e0d0cd..457829a76a 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -13,6 +13,10 @@ from sqlalchemy.exc import IntegrityError
from .models import SourceType, Collection
from .session_context import get_user_db_session
+from ..constants import (
+ RESEARCH_HISTORY_COLLECTION_NAME,
+ RESEARCH_HISTORY_COLLECTION_DESCRIPTION,
+)
def seed_source_types(username: str, password: str = None) -> None:
@@ -42,6 +46,18 @@ def seed_source_types(username: str, password: str = None) -> None:
"description": "Documents manually created or entered",
"icon": "edit",
},
+ {
+ "name": "research_report",
+ "display_name": "Research Report",
+ "description": "Generated research reports (markdown) for semantic search",
+ "icon": "file-alt",
+ },
+ {
+ "name": "research_source",
+ "display_name": "Research Source",
+ "description": "Sources discovered during research with content for semantic search",
+ "icon": "link",
+ },
]
try:
@@ -114,10 +130,60 @@ def ensure_default_library_collection(
raise
+def ensure_research_history_collection(
+ username: str, password: str = None
+) -> str:
+ """
+ Ensure the "Research History" collection exists for a user.
+ This collection is used for semantic search over research reports and sources.
+ Creates it if it doesn't exist.
+
+ Args:
+ username: User to check/create collection for
+ password: User's password (optional, uses session context)
+
+ Returns:
+ UUID of the Research History collection
+ """
+ try:
+ with get_user_db_session(username, password) as session:
+ # Check if research history collection exists
+ collection = (
+ session.query(Collection)
+ .filter_by(collection_type="research_history")
+ .first()
+ )
+
+ if collection:
+ logger.debug(
+ f"Research History collection exists: {collection.id}"
+ )
+ return collection.id
+
+ # Create Research History collection
+ collection_id = str(uuid.uuid4())
+ collection = Collection(
+ id=collection_id,
+ name=RESEARCH_HISTORY_COLLECTION_NAME,
+ description=RESEARCH_HISTORY_COLLECTION_DESCRIPTION,
+ collection_type="research_history",
+ is_default=False,
+ )
+ session.add(collection)
+ session.commit()
+
+ logger.info(f"Created Research History collection: {collection_id}")
+ return collection_id
+
+ except Exception:
+ logger.exception("Error ensuring Research History collection")
+ raise
+
+
def initialize_library_for_user(username: str, password: str = None) -> dict:
"""
Complete initialization of library system for a user.
- Seeds source types and ensures default Library collection exists.
+ Seeds source types and ensures default Library and Research History collections exist.
Args:
username: User to initialize for
@@ -129,6 +195,7 @@ def initialize_library_for_user(username: str, password: str = None) -> dict:
results = {
"source_types_seeded": False,
"library_collection_id": None,
+ "research_history_collection_id": None,
"success": False,
}
@@ -141,6 +208,12 @@ def initialize_library_for_user(username: str, password: str = None) -> dict:
library_id = ensure_default_library_collection(username, password)
results["library_collection_id"] = library_id
+ # Ensure Research History collection
+ research_history_id = ensure_research_history_collection(
+ username, password
+ )
+ results["research_history_collection_id"] = research_history_id
+
results["success"] = True
logger.info(f"Library initialization complete for user: {username}")
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index 2891f0ee95..d3fd103c12 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -64,6 +64,8 @@ from .library import (
CollectionFolder,
CollectionFolderFile,
RAGIndexStatus,
+ # RAG document status
+ RagDocumentStatus,
)
# Note: Text content is now directly in Document.text_content field
@@ -161,6 +163,7 @@ __all__ = [
"RAGIndexStatus",
"CollectionFolder",
"CollectionFolderFile",
+ "RagDocumentStatus",
# Download Tracker Models
"DownloadTracker",
"DownloadDuplicates",
diff --git a/src/local_deep_research/research_library/__init__.py b/src/local_deep_research/research_library/__init__.py
index ca24b474fe..42562f0890 100644
--- a/src/local_deep_research/research_library/__init__.py
+++ b/src/local_deep_research/research_library/__init__.py
@@ -14,6 +14,7 @@ from .services.library_rag_service import LibraryRAGService
from .routes.library_routes import library_bp
from .routes.rag_routes import rag_bp
from .deletion.routes import delete_bp
+from .search import search_bp
__all__ = [
"DownloadService",
@@ -22,4 +23,5 @@ __all__ = [
"library_bp",
"rag_bp",
"delete_bp",
+ "search_bp",
]
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 d023c549bf..c925c49509 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -36,7 +36,6 @@ from ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLY
from ...security.decorators import require_json_body
from ...web.auth.decorators import login_required
from ...utilities.db_utils import get_settings_manager
-from ...utilities.type_utils import to_bool
from ..services.library_rag_service import LibraryRAGService
from ...settings.manager import SettingsManager
from ...security.path_validator import PathValidator
@@ -96,139 +95,32 @@ def get_rag_service(
"""
Get RAG service instance with appropriate settings.
- If collection_id is provided:
- - Uses collection's stored settings if they exist (unless use_defaults=True)
- - Uses current defaults for new collections (and stores them)
-
- If no collection_id:
- - Uses current default settings
+ Delegates to rag_service_factory.get_rag_service() with the current
+ Flask session username. For non-Flask contexts, use the factory directly.
Args:
+ collection_id: Optional collection UUID to load stored settings from
use_defaults: When True, ignore stored collection settings and use
- current defaults. Pass True on force-reindex so that the new
+ current defaults. Pass True on force-reindex so that the new
default embedding model is picked up.
"""
- from ...database.session_context import get_user_db_session
-
- settings = get_settings_manager()
- username = session["username"]
-
- # Get current default settings
- default_embedding_model = settings.get_setting(
- "local_search_embedding_model", "all-MiniLM-L6-v2"
- )
- default_embedding_provider = settings.get_setting(
- "local_search_embedding_provider", "sentence_transformers"
- )
- default_chunk_size = int(
- settings.get_setting("local_search_chunk_size", 1000)
- )
- default_chunk_overlap = int(
- settings.get_setting("local_search_chunk_overlap", 200)
- )
-
- # Get new advanced configuration settings (Issue #1054)
- import json
-
- default_splitter_type = settings.get_setting(
- "local_search_splitter_type", "recursive"
- )
- default_text_separators = settings.get_setting(
- "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
- )
- # Parse JSON string to list
- if isinstance(default_text_separators, str):
- try:
- default_text_separators = json.loads(default_text_separators)
- except json.JSONDecodeError:
- logger.warning(
- f"Invalid JSON for local_search_text_separators setting: {default_text_separators!r}. "
- "Using default separators."
- )
- default_text_separators = ["\n\n", "\n", ". ", " ", ""]
- default_distance_metric = settings.get_setting(
- "local_search_distance_metric", "cosine"
- )
- # Get normalize_vectors as a proper boolean
- default_normalize_vectors = settings.get_bool_setting(
- "local_search_normalize_vectors", True
+ from ..services.rag_service_factory import (
+ get_rag_service as _get_rag_service,
)
- default_index_type = settings.get_setting("local_search_index_type", "flat")
-
- # If collection_id provided, check for stored settings
- if collection_id:
- with get_user_db_session(username) as db_session:
- collection = (
- db_session.query(Collection).filter_by(id=collection_id).first()
- )
-
- if collection and collection.embedding_model and not use_defaults:
- # Use collection's stored settings
- logger.info(
- f"Using stored settings for collection {collection_id}: "
- f"{collection.embedding_model_type.value}/{collection.embedding_model}"
- )
- # Handle normalize_vectors - may be stored as string in some cases
- coll_normalize = collection.normalize_vectors
- if coll_normalize is not None:
- coll_normalize = to_bool(coll_normalize)
- else:
- coll_normalize = default_normalize_vectors
-
- return LibraryRAGService(
- username=username,
- embedding_model=collection.embedding_model,
- embedding_provider=collection.embedding_model_type.value,
- chunk_size=collection.chunk_size or default_chunk_size,
- chunk_overlap=collection.chunk_overlap
- or default_chunk_overlap,
- splitter_type=collection.splitter_type
- or default_splitter_type,
- text_separators=collection.text_separators
- or default_text_separators,
- distance_metric=collection.distance_metric
- or default_distance_metric,
- normalize_vectors=coll_normalize,
- index_type=collection.index_type or default_index_type,
- )
- elif collection:
- # New collection - use defaults and store them
- logger.info(
- f"New collection {collection_id}, using and storing default settings"
- )
-
- # Create service with defaults
- service = LibraryRAGService(
- username=username,
- embedding_model=default_embedding_model,
- embedding_provider=default_embedding_provider,
- chunk_size=default_chunk_size,
- chunk_overlap=default_chunk_overlap,
- splitter_type=default_splitter_type,
- text_separators=default_text_separators,
- distance_metric=default_distance_metric,
- normalize_vectors=default_normalize_vectors,
- index_type=default_index_type,
- )
+ from ...database.session_passwords import session_password_store
- # Store settings on collection (will be done during indexing)
- # Note: We don't store here because we don't have embedding_dimension yet
- # It will be stored in index_collection when first document is indexed
-
- return service
-
- # No collection or fallback - use current defaults
- return LibraryRAGService(
- username=username,
- embedding_model=default_embedding_model,
- embedding_provider=default_embedding_provider,
- chunk_size=default_chunk_size,
- chunk_overlap=default_chunk_overlap,
- splitter_type=default_splitter_type,
- text_separators=default_text_separators,
- distance_metric=default_distance_metric,
- normalize_vectors=default_normalize_vectors,
- index_type=default_index_type,
+ username = session["username"]
+ session_id = session.get("session_id")
+ db_password = None
+ if session_id:
+ db_password = session_password_store.get_session_password(
+ username, session_id
+ )
+ return _get_rag_service(
+ username,
+ collection_id,
+ use_defaults=use_defaults,
+ db_password=db_password,
)
@@ -1950,8 +1842,6 @@ def index_collection(collection_id):
# Create RAG service — on force reindex use current default model
rag_service = get_rag_service(collection_id, use_defaults=force_reindex)
- # Set password for thread access
- rag_service.db_password = db_password
logger.info(
f"RAG service created: provider={rag_service.embedding_provider}"
)
@@ -2172,138 +2062,26 @@ def _get_rag_service_for_thread(
) -> LibraryRAGService:
"""
Create RAG service for use in background threads (no Flask context).
+
+ Delegates settings resolution to the shared rag_service_factory, then
+ propagates db_password to the embedding manager for thread-safe DB access.
"""
- from ...database.session_context import get_user_db_session
- from ...web_search_engines.engines.local_embedding_manager import (
- LocalEmbeddingManager,
+ from ..services.rag_service_factory import (
+ get_rag_service as _get_rag_service,
)
- import json
-
- with get_user_db_session(username, db_password) as db_session:
- settings_manager = SettingsManager(db_session)
-
- # Get default settings
- default_embedding_model = settings_manager.get_setting(
- "local_search_embedding_model", "all-MiniLM-L6-v2"
- )
- default_embedding_provider = settings_manager.get_setting(
- "local_search_embedding_provider", "sentence_transformers"
- )
- default_chunk_size = int(
- settings_manager.get_setting("local_search_chunk_size", 1000)
- )
- default_chunk_overlap = int(
- settings_manager.get_setting("local_search_chunk_overlap", 200)
- )
- default_splitter_type = settings_manager.get_setting(
- "local_search_splitter_type", "recursive"
- )
- default_text_separators = settings_manager.get_setting(
- "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
- )
- if isinstance(default_text_separators, str):
- try:
- default_text_separators = json.loads(default_text_separators)
- except json.JSONDecodeError:
- logger.warning(
- f"Invalid JSON for local_search_text_separators setting: {default_text_separators!r}. "
- "Using default separators."
- )
- default_text_separators = ["\n\n", "\n", ". ", " ", ""]
- default_distance_metric = settings_manager.get_setting(
- "local_search_distance_metric", "cosine"
- )
- default_normalize_vectors = settings_manager.get_bool_setting(
- "local_search_normalize_vectors", True
- )
- default_index_type = settings_manager.get_setting(
- "local_search_index_type", "flat"
- )
-
- # Get settings snapshot for embedding manager
- settings_snapshot = settings_manager.get_settings_snapshot()
- settings_snapshot["_username"] = username
-
- # Check for collection's stored settings
- collection = (
- db_session.query(Collection).filter_by(id=collection_id).first()
- )
-
- if collection and collection.embedding_model and not use_defaults:
- # Use collection's stored settings
- embedding_model = collection.embedding_model
- embedding_provider = collection.embedding_model_type.value
- chunk_size = collection.chunk_size or default_chunk_size
- chunk_overlap = collection.chunk_overlap or default_chunk_overlap
- splitter_type = collection.splitter_type or default_splitter_type
- text_separators = (
- collection.text_separators or default_text_separators
- )
- distance_metric = (
- collection.distance_metric or default_distance_metric
- )
- index_type = collection.index_type or default_index_type
-
- coll_normalize = collection.normalize_vectors
- if coll_normalize is not None:
- if isinstance(coll_normalize, str):
- coll_normalize = coll_normalize.lower() in (
- "true",
- "1",
- "yes",
- )
- else:
- coll_normalize = bool(coll_normalize)
- else:
- coll_normalize = default_normalize_vectors
- normalize_vectors = coll_normalize
- else:
- # Use default settings
- embedding_model = default_embedding_model
- embedding_provider = default_embedding_provider
- chunk_size = default_chunk_size
- chunk_overlap = default_chunk_overlap
- splitter_type = default_splitter_type
- text_separators = default_text_separators
- distance_metric = default_distance_metric
- normalize_vectors = default_normalize_vectors
- index_type = default_index_type
-
- # Update settings snapshot with embedding config
- settings_snapshot.update(
- {
- "embeddings.provider": embedding_provider,
- f"embeddings.{embedding_provider}.model": embedding_model,
- "local_search_chunk_size": chunk_size,
- "local_search_chunk_overlap": chunk_overlap,
- }
- )
-
- # Create embedding manager (to avoid database access in LibraryRAGService.__init__)
- embedding_manager = LocalEmbeddingManager(
- embedding_model=embedding_model,
- embedding_model_type=embedding_provider,
- settings_snapshot=settings_snapshot,
- )
- embedding_manager.db_password = db_password
-
- # Create RAG service with pre-built embedding manager and db_password
- rag_service = LibraryRAGService(
- username=username,
- embedding_model=embedding_model,
- embedding_provider=embedding_provider,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- splitter_type=splitter_type,
- text_separators=text_separators,
- distance_metric=distance_metric,
- normalize_vectors=normalize_vectors,
- index_type=index_type,
- embedding_manager=embedding_manager,
- db_password=db_password,
- )
- return rag_service
+ service = _get_rag_service(
+ username,
+ collection_id,
+ use_defaults=use_defaults,
+ db_password=db_password,
+ )
+ # The factory passes db_password to LibraryRAGService, but __init__ stores
+ # it in the backing field (_db_password) without propagating to sub-managers.
+ # Re-assign via the property setter to propagate to embedding_manager and
+ # integrity_manager, which need it for thread-safe session access.
+ service.db_password = db_password
+ return service
def trigger_auto_index(
@@ -2902,3 +2680,7 @@ def cancel_indexing(collection_id):
"error": "Failed to cancel indexing. Please try again.",
}
), 500
+
+
+# Research History Semantic Search Routes have been moved to
+# research_library.search.routes.search_routes
diff --git a/src/local_deep_research/research_library/search/__init__.py b/src/local_deep_research/research_library/search/__init__.py
new file mode 100644
index 0000000000..1679a90e58
--- /dev/null
+++ b/src/local_deep_research/research_library/search/__init__.py
@@ -0,0 +1,12 @@
+"""
+Semantic Search subpackage
+
+Provides semantic search over research history and library collections:
+- Routes for indexing and searching collections
+- ResearchHistoryIndexer for converting research into searchable documents
+"""
+
+from .routes import search_bp
+from .services.research_history_indexer import ResearchHistoryIndexer
+
+__all__ = ["search_bp", "ResearchHistoryIndexer"]
diff --git a/src/local_deep_research/research_library/search/routes/__init__.py b/src/local_deep_research/research_library/search/routes/__init__.py
new file mode 100644
index 0000000000..7fa7a4ceb4
--- /dev/null
+++ b/src/local_deep_research/research_library/search/routes/__init__.py
@@ -0,0 +1,3 @@
+from .search_routes import search_bp
+
+__all__ = ["search_bp"]
diff --git a/src/local_deep_research/research_library/search/routes/search_routes.py b/src/local_deep_research/research_library/search/routes/search_routes.py
new file mode 100644
index 0000000000..6feebcb7ea
--- /dev/null
+++ b/src/local_deep_research/research_library/search/routes/search_routes.py
@@ -0,0 +1,395 @@
+"""
+Semantic Search Routes
+
+Provides endpoints for:
+- Research history collection management and indexing
+- Semantic search across any library collection
+"""
+
+from flask import (
+ Blueprint,
+ jsonify,
+ request,
+ session,
+)
+from loguru import logger
+
+from ....database.models.library import Collection, Document
+from ....security.decorators import require_json_body
+from ....web.auth.decorators import login_required
+from ...utils import handle_api_error
+
+search_bp = Blueprint("search", __name__, url_prefix="/library")
+
+# =============================================================================
+# Research History Collection & Indexing
+# =============================================================================
+
+
+@search_bp.route("/api/research-history/collection", methods=["GET"])
+@login_required
+def get_research_history_collection():
+ """
+ Get the Research History collection info and indexing status.
+
+ Returns collection ID and statistics about indexed vs total research.
+ Counts are derived from DocumentCollection membership (matching the
+ collection page) rather than source_type_id filtering.
+ """
+ from ....constants import ResearchStatus
+ from ....database.models.library import DocumentCollection
+ from ....database.models.research import ResearchHistory
+ from ....database.session_context import get_user_db_session
+ from ....database.session_passwords import session_password_store
+ from ..services.research_history_indexer import ResearchHistoryIndexer
+
+ username = session["username"]
+ session_id = session.get("session_id")
+
+ db_password = None
+ if session_id:
+ db_password = session_password_store.get_session_password(
+ username, session_id
+ )
+
+ try:
+ indexer = ResearchHistoryIndexer(username, db_password)
+ collection_id = indexer.get_or_create_collection()
+
+ # Auto-convert any unconverted research entries to Documents.
+ # This is a lightweight DB-only operation (no FAISS) that ensures
+ # the collection page and history page always show consistent counts.
+ try:
+ indexer.convert_all_research(force=False)
+ except Exception:
+ logger.warning(
+ "Auto-conversion of research entries failed", exc_info=True
+ )
+
+ with get_user_db_session(username, db_password) as db_session:
+ # Total completed research with report content
+ total_research = (
+ db_session.query(ResearchHistory)
+ .filter(ResearchHistory.status == ResearchStatus.COMPLETED)
+ .filter(ResearchHistory.report_content.isnot(None))
+ .filter(ResearchHistory.report_content != "")
+ .count()
+ )
+
+ # Research entries represented in this collection
+ # (via Document → DocumentCollection join, matching collection page)
+ indexed_research = (
+ db_session.query(Document.research_id)
+ .join(
+ DocumentCollection,
+ DocumentCollection.document_id == Document.id,
+ )
+ .filter(DocumentCollection.collection_id == collection_id)
+ .filter(Document.research_id.isnot(None))
+ .distinct()
+ .count()
+ )
+
+ # Document counts in collection
+ total_documents = (
+ db_session.query(DocumentCollection)
+ .filter(DocumentCollection.collection_id == collection_id)
+ .count()
+ )
+ indexed_documents = (
+ db_session.query(DocumentCollection)
+ .filter(DocumentCollection.collection_id == collection_id)
+ .filter(DocumentCollection.indexed == True) # noqa: E712
+ .count()
+ )
+
+ return jsonify(
+ {
+ "success": True,
+ "collection_id": collection_id,
+ "total_research": total_research,
+ "indexed_research": indexed_research,
+ "total_documents": total_documents,
+ "indexed_documents": indexed_documents,
+ }
+ )
+
+ except Exception as e:
+ return handle_api_error("getting research history collection", e)
+
+
+@search_bp.route("/api/research-history/convert-all", methods=["POST"])
+@login_required
+def convert_all_research():
+ """
+ Convert all completed research entries into library Documents.
+
+ Unlike the SSE index endpoint this is a synchronous JSON endpoint that
+ creates Document rows (and DocumentCollection memberships) without
+ triggering FAISS / RAG indexing. Call this before the SSE index endpoint
+ to avoid nested-session problems on SQLite.
+
+ Request JSON (optional):
+ force: If true, re-convert even already-converted entries (default false)
+
+ Returns:
+ JSON with converted, skipped, failed counts and collection_id
+ """
+ from ....database.session_passwords import session_password_store
+ from ..services.research_history_indexer import ResearchHistoryIndexer
+
+ username = session["username"]
+ session_id = session.get("session_id")
+
+ db_password = None
+ if session_id:
+ db_password = session_password_store.get_session_password(
+ username, session_id
+ )
+
+ data = request.get_json() or {}
+ force = data.get("force", False)
+
+ try:
+ indexer = ResearchHistoryIndexer(username, db_password)
+ result = indexer.convert_all_research(force=force)
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("converting all research", e)
+
+
+@search_bp.route(
+ "/api/research/<string:research_id>/add-to-collection", methods=["POST"]
+)
+@login_required
+@require_json_body(error_format="success")
+def add_research_to_collection(research_id):
+ """
+ Add a research entry to a specific collection.
+
+ This allows users to organize research into custom collections
+ in addition to the default Research History collection.
+
+ Args:
+ research_id: UUID of the research to add
+
+ Request JSON:
+ collection_id: UUID of the target collection (required)
+ """
+ from ....database.session_context import get_user_db_session
+ from ....database.session_passwords import session_password_store
+ from ..services.research_history_indexer import ResearchHistoryIndexer
+
+ username = session["username"]
+ session_id = session.get("session_id")
+
+ db_password = None
+ if session_id:
+ db_password = session_password_store.get_session_password(
+ username, session_id
+ )
+
+ data = request.get_json()
+ collection_id = data.get("collection_id")
+
+ if not collection_id:
+ return jsonify(
+ {
+ "success": False,
+ "error": "collection_id is required",
+ }
+ ), 400
+
+ try:
+ # Verify collection exists
+ with get_user_db_session(username, db_password) as db_session:
+ collection = (
+ db_session.query(Collection)
+ .filter(Collection.id == collection_id)
+ .first()
+ )
+ if not collection:
+ return jsonify(
+ {
+ "success": False,
+ "error": "Collection not found",
+ }
+ ), 404
+
+ collection_name = collection.name
+
+ indexer = ResearchHistoryIndexer(username, db_password)
+ result = indexer.index_research(
+ research_id,
+ collection_id=collection_id,
+ )
+
+ if result["status"] == "error":
+ return jsonify(
+ {
+ "success": False,
+ "error": result.get("error", "Operation failed."),
+ }
+ ), 400
+
+ result["collection_name"] = collection_name
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("adding research to collection", e)
+
+
+# =============================================================================
+# Collection Search (generic — works for any collection type)
+# =============================================================================
+
+
+@search_bp.route(
+ "/api/collections/<string:collection_id>/search", methods=["POST"]
+)
+@login_required
+@require_json_body(error_format="success")
+def search_collection(collection_id):
+ """Search any collection using semantic similarity.
+
+ Delegates to CollectionSearchEngine instead of reimplementing FAISS search.
+
+ Request JSON:
+ query: Search query string
+ limit: Maximum number of results (default 10)
+ """
+ from ....database.session_context import get_user_db_session
+ from ....database.session_passwords import session_password_store
+ from ....web_search_engines.engines.search_engine_collection import (
+ CollectionSearchEngine,
+ )
+
+ username = session["username"]
+ session_id = session.get("session_id")
+
+ db_password = None
+ if session_id:
+ db_password = session_password_store.get_session_password(
+ username, session_id
+ )
+
+ data = request.get_json()
+ query = data.get("query", "").strip()
+
+ if len(query) > 10000:
+ return jsonify(
+ {"success": False, "error": "Query too long (max 10000 characters)"}
+ ), 400
+
+ try:
+ limit = max(1, min(int(data.get("limit", 10)), 50))
+ except (TypeError, ValueError):
+ limit = 10
+
+ if not query:
+ return jsonify({"success": False, "error": "Query is required"}), 400
+
+ try:
+ # Verify collection exists and get its type
+ with get_user_db_session(username, db_password) as db_session:
+ collection = (
+ db_session.query(Collection).filter_by(id=collection_id).first()
+ )
+ if not collection:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+ collection_type = collection.collection_type
+ collection_name = collection.name
+
+ # Delegate to CollectionSearchEngine
+ engine = CollectionSearchEngine(
+ collection_id=collection_id,
+ collection_name=collection_name,
+ max_results=limit * 2,
+ settings_snapshot={"_username": username},
+ )
+ raw_results = engine.search(query, limit=limit * 2)
+
+ # Transform CollectionSearchEngine format -> API format
+ results = []
+ for r in raw_results:
+ meta = r.get("metadata", {})
+ results.append(
+ {
+ "document_id": meta.get("document_id")
+ or meta.get("source_id"),
+ "title": r.get("title", "Untitled"),
+ "snippet": r.get("snippet", ""),
+ "similarity": round(r.get("relevance_score", 0) * 100, 1),
+ "url": meta.get("source"),
+ }
+ )
+ if len(results) >= limit:
+ break
+
+ # For research_history collections, enrich with report/source type
+ if collection_type == "research_history":
+ _enrich_with_research_metadata(results, username, db_password)
+
+ return jsonify({"success": True, "results": results, "query": query})
+
+ except Exception as e:
+ return handle_api_error("searching collection", e)
+
+
+def _enrich_with_research_metadata(results, username, db_password):
+ """Add report/source type and research context to search results."""
+ from ....database.models.library import SourceType
+ from ....database.models.research import ResearchHistory
+ from ....database.session_context import get_user_db_session
+
+ doc_ids = [r["document_id"] for r in results if r.get("document_id")]
+ if not doc_ids:
+ return
+
+ with get_user_db_session(username, db_password) as db_session:
+ rows = (
+ db_session.query(
+ Document.id.label("document_id"),
+ SourceType.name.label("source_type_name"),
+ ResearchHistory.title.label("research_title"),
+ ResearchHistory.query.label("research_query"),
+ ResearchHistory.created_at.label("research_created_at"),
+ Document.research_id,
+ )
+ .outerjoin(SourceType, Document.source_type_id == SourceType.id)
+ .outerjoin(
+ ResearchHistory,
+ Document.research_id == ResearchHistory.id,
+ )
+ .filter(Document.id.in_(doc_ids))
+ .all()
+ )
+ lookup = {row.document_id: row for row in rows}
+
+ for result in results:
+ row = lookup.get(result.get("document_id"))
+ if row:
+ result["type"] = (
+ "report"
+ if row.source_type_name == "research_report"
+ else "source"
+ )
+ result["research_id"] = row.research_id
+ result["research_title"] = row.research_title or (
+ row.research_query[:100] if row.research_query else ""
+ )
+ result["research_query"] = row.research_query
+ result["research_created_at"] = (
+ str(row.research_created_at)
+ if row.research_created_at
+ else None
+ )
+ else:
+ result["type"] = "source"
+ result["research_id"] = None
+ result["research_title"] = ""
+ result["research_query"] = None
+ result["research_created_at"] = None
diff --git a/src/local_deep_research/research_library/search/services/__init__.py b/src/local_deep_research/research_library/search/services/__init__.py
new file mode 100644
index 0000000000..0e9844d315
--- /dev/null
+++ b/src/local_deep_research/research_library/search/services/__init__.py
@@ -0,0 +1,6 @@
+from .research_history_indexer import (
+ ResearchHistoryIndexer,
+ auto_convert_research,
+)
+
+__all__ = ["ResearchHistoryIndexer", "auto_convert_research"]
diff --git a/src/local_deep_research/research_library/search/services/research_history_indexer.py b/src/local_deep_research/research_library/search/services/research_history_indexer.py
new file mode 100644
index 0000000000..cfb75a35b4
--- /dev/null
+++ b/src/local_deep_research/research_library/search/services/research_history_indexer.py
@@ -0,0 +1,377 @@
+"""
+Research History Indexer Service
+
+Enables semantic search over research history by:
+- Converting ResearchHistory reports into indexable Documents
+- Linking documents to the Research History collection
+- Triggering RAG indexing via LibraryRAGService
+"""
+
+import hashlib
+import uuid
+from datetime import datetime, UTC
+from typing import Any, Dict, Optional
+
+from loguru import logger
+from sqlalchemy.exc import IntegrityError
+
+from ....constants import ResearchStatus
+from ....database.library_init import ensure_research_history_collection
+from ....database.models.library import (
+ Document,
+ DocumentCollection,
+ DocumentStatus,
+ SourceType,
+)
+from ....database.models.research import ResearchHistory
+from ....database.session_context import get_user_db_session
+
+
+class ResearchHistoryIndexer:
+ """
+ Service for indexing research history into a searchable collection.
+
+ Converts research reports into Documents that can be indexed for
+ semantic search using the existing RAG infrastructure.
+ """
+
+ # Source type names used in the database
+ SOURCE_TYPE_REPORT = "research_report"
+ COLLECTION_TYPE = "research_history"
+
+ def __init__(self, username: str, db_password: Optional[str] = None):
+ """
+ Initialize the indexer for a user.
+
+ Args:
+ username: Username for database access
+ db_password: Optional database password for encrypted DB access
+ """
+ self.username = username
+ self.db_password = db_password
+
+ def get_or_create_collection(self) -> str:
+ """
+ Get or create the Research History collection for this user.
+
+ Returns:
+ UUID of the Research History collection
+ """
+ return ensure_research_history_collection(
+ self.username, self.db_password
+ )
+
+ def index_research(
+ self,
+ research_id: str,
+ collection_id: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Convert a single research entry into a Document and add it to a
+ collection. Idempotent — safe to call multiple times.
+
+ Args:
+ research_id: UUID of the research to index
+ collection_id: Target collection UUID (defaults to Research History)
+
+ Returns:
+ Dict with status and document count
+ """
+ if collection_id is None:
+ collection_id = self.get_or_create_collection()
+
+ with get_user_db_session(self.username, self.db_password) as session:
+ research = (
+ session.query(ResearchHistory)
+ .filter(ResearchHistory.id == research_id)
+ .first()
+ )
+
+ if not research:
+ return {"status": "error", "error": "Research not found"}
+
+ if research.status != ResearchStatus.COMPLETED:
+ return {
+ "status": "error",
+ "error": "Research is not yet completed",
+ }
+
+ if not research.report_content:
+ return {
+ "status": "error",
+ "error": "Research has no report content",
+ }
+
+ try:
+ report_doc = self._create_document_from_report(
+ research, collection_id, session
+ )
+ if report_doc is None:
+ return {
+ "status": "error",
+ "error": "SourceType 'research_report' not found. "
+ "Run library initialization.",
+ }
+ logger.info(
+ f"Created/found document for research: {research_id[:8]}"
+ )
+ except Exception:
+ logger.exception("Error creating report document")
+ return {
+ "status": "error",
+ "error": "Failed to create report document",
+ }
+
+ try:
+ session.commit()
+ except IntegrityError:
+ session.rollback()
+ logger.info(
+ f"DocumentCollection already exists for research "
+ f"{research_id[:8]} (concurrent insert)"
+ )
+
+ return {
+ "status": "success",
+ "research_id": research_id,
+ "collection_id": collection_id,
+ "documents_added": 1,
+ }
+
+ def convert_all_research(self, force: bool = False) -> Dict[str, Any]:
+ """
+ Convert all completed research entries into Documents (without RAG indexing).
+
+ Unlike index_all_research / index_research, this method operates within a
+ single DB session and calls the private helpers directly, avoiding the
+ nested-session issues that arise on SQLite when index_research opens its
+ own session inside a loop.
+
+ Args:
+ force: If True, process all entries even if already converted.
+ If False (default), skip entries that already have a report
+ Document.
+
+ Returns:
+ Dict with:
+ - converted: Number of research entries successfully converted
+ - skipped: Number of entries skipped (already converted)
+ - failed: Number of entries that raised an exception
+ - collection_id: UUID of the Research History collection
+
+ Only report Documents are created; source documents are not indexed.
+ """
+ collection_id = self.get_or_create_collection()
+
+ with get_user_db_session(self.username, self.db_password) as session:
+ # Resolve the report SourceType — required to create report Documents
+ report_type = (
+ session.query(SourceType)
+ .filter_by(name=self.SOURCE_TYPE_REPORT)
+ .first()
+ )
+ if report_type is None:
+ logger.warning(
+ f"SourceType '{self.SOURCE_TYPE_REPORT}' not found. "
+ "Run library initialization to seed source types before "
+ "converting research history."
+ )
+ return {
+ "converted": 0,
+ "skipped": 0,
+ "failed": 0,
+ "collection_id": collection_id,
+ }
+
+ # Build subquery of research IDs that already have a report Document
+ already_converted_subquery = (
+ session.query(Document.research_id)
+ .filter(Document.source_type_id == report_type.id)
+ .filter(Document.research_id.isnot(None))
+ .distinct()
+ .subquery()
+ )
+
+ # Count total eligible research entries (before filtering)
+ total_eligible = (
+ session.query(ResearchHistory)
+ .filter(ResearchHistory.status == ResearchStatus.COMPLETED)
+ .filter(ResearchHistory.report_content.isnot(None))
+ .filter(ResearchHistory.report_content != "")
+ .count()
+ )
+
+ # Fetch candidates — optionally excluding already-converted entries
+ query = (
+ session.query(ResearchHistory)
+ .filter(ResearchHistory.status == ResearchStatus.COMPLETED)
+ .filter(ResearchHistory.report_content.isnot(None))
+ .filter(ResearchHistory.report_content != "")
+ .order_by(ResearchHistory.created_at.desc())
+ )
+ if not force:
+ query = query.filter(
+ ResearchHistory.id.notin_(already_converted_subquery)
+ )
+
+ research_entries = query.all()
+
+ converted = 0
+ skipped = total_eligible - len(research_entries) if not force else 0
+ failed = 0
+
+ for research in research_entries:
+ try:
+ # Create (or reuse) report Document
+ report_doc = self._create_document_from_report(
+ research,
+ collection_id,
+ session,
+ report_type_id=report_type.id,
+ )
+ if report_doc is None:
+ # SourceType missing inside helper (already warned)
+ failed += 1
+ continue
+
+ # Commit each entry individually so a rollback on failure
+ # only loses the failing entry, not the whole batch.
+ session.commit()
+ converted += 1
+
+ except Exception:
+ logger.exception(f"Error converting research {research.id}")
+ session.rollback()
+ failed += 1
+
+ logger.info(
+ f"convert_all_research complete — converted={converted}, "
+ f"skipped={skipped}, failed={failed}"
+ )
+ return {
+ "converted": converted,
+ "skipped": skipped,
+ "failed": failed,
+ "collection_id": collection_id,
+ }
+
+ def _create_document_from_report(
+ self,
+ research: ResearchHistory,
+ collection_id: str,
+ session,
+ report_type_id: Optional[str] = None,
+ ) -> Optional[Document]:
+ """
+ Create a Document from a research report.
+
+ Args:
+ research: ResearchHistory entry
+ collection_id: Target collection UUID
+ session: Database session
+ report_type_id: Pre-resolved SourceType ID (avoids N+1 queries
+ when called in a loop from convert_all_research)
+
+ Returns:
+ Created Document or None if skipped
+ """
+ # Resolve report SourceType (cached ID avoids per-entry query)
+ if report_type_id is None:
+ report_type = (
+ session.query(SourceType)
+ .filter_by(name=self.SOURCE_TYPE_REPORT)
+ .first()
+ )
+ if report_type is None:
+ logger.warning(
+ f"SourceType '{self.SOURCE_TYPE_REPORT}' not found for research "
+ f"{research.id}. Cannot create document — run library initialization "
+ "to seed source types."
+ )
+ return None
+ report_type_id = report_type.id
+ existing_doc = (
+ session.query(Document)
+ .filter(Document.research_id == research.id)
+ .filter(Document.source_type_id == report_type_id)
+ .first()
+ )
+
+ if existing_doc:
+ # Ensure it's in the collection
+ self._ensure_in_collection(existing_doc.id, collection_id, session)
+ return existing_doc
+
+ # Create document or reuse existing one with same content hash
+ # (document_hash has a unique constraint, so identical content
+ # must share a Document row — research_id points to the first creator)
+ content = research.report_content
+ doc_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()
+
+ document = (
+ session.query(Document)
+ .filter(Document.document_hash == doc_hash)
+ .first()
+ )
+
+ if document is None:
+ doc_id = str(uuid.uuid4())
+ document = Document(
+ id=doc_id,
+ source_type_id=report_type_id,
+ research_id=research.id,
+ document_hash=doc_hash,
+ file_size=len(content.encode("utf-8")),
+ file_type="markdown",
+ mime_type="text/markdown",
+ title=research.title
+ or (research.query[:100] if research.query else "Untitled"),
+ text_content=content,
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ character_count=len(content),
+ word_count=len(content.split()),
+ )
+ session.add(document)
+ session.flush()
+
+ self._ensure_in_collection(document.id, collection_id, session)
+ return document
+
+ def _ensure_in_collection(
+ self, document_id: str, collection_id: str, session
+ ) -> None:
+ """Add document to collection if not already there."""
+ existing = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=document_id, collection_id=collection_id)
+ .first()
+ )
+ if not existing:
+ session.add(
+ DocumentCollection(
+ document_id=document_id,
+ collection_id=collection_id,
+ indexed=False,
+ )
+ )
+
+
+def auto_convert_research(
+ username: str, research_id: str, db_password: str | None = None
+):
+ """Auto-convert a completed research entry to a document in the History collection.
+
+ Safe to call from any context — exceptions are caught and logged.
+ """
+ try:
+ indexer = ResearchHistoryIndexer(username, db_password=db_password)
+ result = indexer.index_research(research_id)
+ logger.info(
+ f"Auto-converted research {research_id} for user {username}: "
+ f"{result.get('status')}"
+ )
+ except Exception:
+ logger.exception(
+ f"Failed to auto-convert research {research_id} for user {username}"
+ )
diff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.py
new file mode 100644
index 0000000000..7fa271d4c6
--- /dev/null
+++ b/src/local_deep_research/research_library/services/rag_service_factory.py
@@ -0,0 +1,179 @@
+"""
+RAG Service Factory
+
+Provides get_rag_service() for creating LibraryRAGService instances
+with appropriate settings. Extracted from rag_routes.py to avoid
+circular imports (service → routes).
+"""
+
+import json
+from typing import Optional
+
+from loguru import logger
+
+from ...database.models.library import Collection
+from ...database.session_context import get_user_db_session
+from ...utilities.db_utils import get_settings_manager
+from ...utilities.type_utils import to_bool
+from ..services.library_rag_service import LibraryRAGService
+
+
+def get_rag_service(
+ username: str,
+ collection_id: Optional[str] = None,
+ use_defaults: bool = False,
+ db_password: Optional[str] = None,
+) -> LibraryRAGService:
+ """
+ Get RAG service instance with appropriate settings.
+
+ Args:
+ username: Username for database access and settings lookup
+ collection_id: Optional collection UUID to load stored settings from
+ use_defaults: When True, ignore stored collection settings and use
+ current defaults. Pass True on force-reindex so that the new
+ default embedding model is picked up.
+ db_password: Optional database password for encrypted databases
+
+ If collection_id is provided:
+ - Uses collection's stored settings if they exist (unless use_defaults=True)
+ - Uses current defaults for new collections (and stores them)
+
+ If no collection_id:
+ - Uses current default settings
+ """
+ settings = get_settings_manager(username=username)
+
+ # Get current default settings.
+ # The local_search_* keys are written by the embedding-settings page and
+ # have no JSON defaults file yet, so explicit fallbacks are required to
+ # avoid TypeError / None propagation on fresh installs.
+ default_embedding_model = (
+ settings.get_setting("local_search_embedding_model")
+ or "all-MiniLM-L6-v2"
+ )
+ default_embedding_provider = (
+ settings.get_setting("local_search_embedding_provider")
+ or "sentence_transformers"
+ )
+ default_chunk_size = int(
+ settings.get_setting("local_search_chunk_size") or 1000
+ )
+ default_chunk_overlap = int(
+ settings.get_setting("local_search_chunk_overlap") or 200
+ )
+ default_splitter_type = (
+ settings.get_setting("local_search_splitter_type") or "recursive"
+ )
+ default_text_separators = settings.get_setting(
+ "local_search_text_separators"
+ )
+ # Parse JSON string to list
+ if isinstance(default_text_separators, str):
+ try:
+ default_text_separators = json.loads(default_text_separators)
+ except json.JSONDecodeError:
+ logger.warning(
+ "Invalid JSON for local_search_text_separators: %r — "
+ "using default separators",
+ default_text_separators,
+ )
+ default_text_separators = ["\n\n", "\n", ". ", " ", ""]
+ elif default_text_separators is None:
+ default_text_separators = ["\n\n", "\n", ". ", " ", ""]
+ default_distance_metric = (
+ settings.get_setting("local_search_distance_metric") or "cosine"
+ )
+ default_normalize_vectors = settings.get_bool_setting(
+ "local_search_normalize_vectors"
+ )
+ default_index_type = (
+ settings.get_setting("local_search_index_type") or "Flat"
+ )
+
+ # If collection_id provided, check for stored settings
+ if collection_id:
+ with get_user_db_session(username, db_password) as db_session:
+ collection = (
+ db_session.query(Collection).filter_by(id=collection_id).first()
+ )
+
+ if collection and collection.embedding_model and not use_defaults:
+ # Use collection's stored settings
+ logger.info(
+ f"Using stored settings for collection {collection_id}: "
+ f"{collection.embedding_model_type.value if collection.embedding_model_type else 'unknown'}/{collection.embedding_model}"
+ )
+ # Handle normalize_vectors - may be stored as string in some cases
+ coll_normalize = collection.normalize_vectors
+ if coll_normalize is not None:
+ coll_normalize = to_bool(coll_normalize)
+ else:
+ coll_normalize = default_normalize_vectors
+
+ def _col(stored, default):
+ """Use stored collection value if not None, else default."""
+ return stored if stored is not None else default
+
+ return LibraryRAGService(
+ username=username,
+ embedding_model=collection.embedding_model,
+ embedding_provider=collection.embedding_model_type.value,
+ chunk_size=_col(collection.chunk_size, default_chunk_size),
+ chunk_overlap=_col(
+ collection.chunk_overlap, default_chunk_overlap
+ ),
+ splitter_type=_col(
+ collection.splitter_type, default_splitter_type
+ ),
+ text_separators=_col(
+ collection.text_separators, default_text_separators
+ ),
+ distance_metric=_col(
+ collection.distance_metric, default_distance_metric
+ ),
+ normalize_vectors=coll_normalize,
+ index_type=_col(collection.index_type, default_index_type),
+ db_password=db_password,
+ )
+ elif collection:
+ # New collection - use defaults and store them
+ logger.info(
+ f"New collection {collection_id}, using and storing default settings"
+ )
+
+ # Create service with defaults
+ service = LibraryRAGService(
+ username=username,
+ embedding_model=default_embedding_model,
+ embedding_provider=default_embedding_provider,
+ chunk_size=default_chunk_size,
+ chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
+ db_password=db_password,
+ )
+
+ # Store settings on collection (will be done during indexing)
+ # Note: We don't store here because we don't have embedding_dimension yet
+ # It will be stored in index_collection when first document is indexed
+
+ return service
+
+ # No collection or fallback - use current defaults
+ return LibraryRAGService(
+ username=username,
+ embedding_model=default_embedding_model,
+ embedding_provider=default_embedding_provider,
+ chunk_size=default_chunk_size,
+ chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
+ db_password=db_password,
+ )
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 2bde39459b..c084e2c717 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -761,6 +761,12 @@ def register_blueprints(app):
app.register_blueprint(delete_bp) # Already has url_prefix='/library/api'
logger.info("Deletion Management routes registered successfully")
+ # Register Semantic Search blueprint
+ from ..research_library.search import search_bp
+
+ app.register_blueprint(search_bp) # url_prefix='/library'
+ logger.info("Semantic Search routes registered successfully")
+
# Register Document Scheduler blueprint
from ..research_scheduler.routes import scheduler_bp
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 2dcb02d07c..155864634d 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -346,6 +346,15 @@ class QueueProcessorV2:
f"Failed to update completion status for {username}"
)
+ # Auto-convert research to document in History collection.
+ # Documents only — FAISS indexing is triggered separately by the user
+ # via "Index All" on the History page.
+ from ...research_library.search.services.research_history_indexer import (
+ auto_convert_research,
+ )
+
+ auto_convert_research(username, research_id, db_password=user_password)
+
def notify_research_failed(
self,
username: str,
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index d72e3b6400..fccfabeebc 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -305,13 +305,18 @@ def run_research_process(research_id, query, mode, **kwargs):
if not username:
logger.error("No username provided to research thread")
raise ValueError("Username is required for research process")
+ # Extract user_password early so it's available for all cleanup paths
+ user_password = kwargs.get("user_password")
+
try:
# Check if this research has been terminated before we even start
if is_termination_requested(research_id):
logger.info(
f"Research {research_id} was terminated before starting"
)
- cleanup_research_resources(research_id, username)
+ cleanup_research_resources(
+ research_id, username, user_password=user_password
+ )
return
logger.info(
@@ -374,8 +379,7 @@ def run_research_process(research_id, query, mode, **kwargs):
set_settings_context(settings_context)
- # Get user password if provided
- user_password = kwargs.get("user_password")
+ # user_password already extracted above (before termination check)
# Create shared research context that can be updated during research
shared_research_context = {
@@ -1175,7 +1179,9 @@ def run_research_process(research_id, query, mode, **kwargs):
logger.info(
"Cleaning up resources for research_id: %s", research_id
)
- cleanup_research_resources(research_id, username)
+ cleanup_research_resources(
+ research_id, username, user_password=user_password
+ )
logger.info(
"Resources cleaned up for research_id: %s", research_id
)
@@ -1421,7 +1427,9 @@ def run_research_process(research_id, query, mode, **kwargs):
)
# Clean up resources
- cleanup_research_resources(research_id, username)
+ cleanup_research_resources(
+ research_id, username, user_password=user_password
+ )
except ResearchTerminatedException:
logger.info(f"Research {research_id} terminated by user")
@@ -1612,7 +1620,9 @@ def run_research_process(research_id, query, mode, **kwargs):
logger.exception("Error in error handler")
# Clean up resources
- cleanup_research_resources(research_id, username)
+ cleanup_research_resources(
+ research_id, username, user_password=user_password
+ )
finally:
# RESOURCE CLEANUP: Close search engine HTTP sessions.
@@ -1649,7 +1659,7 @@ def run_research_process(research_id, query, mode, **kwargs):
safe_close(use_llm, "research LLM")
-def cleanup_research_resources(research_id, username=None):
+def cleanup_research_resources(research_id, username=None, user_password=None):
"""
Clean up resources for a completed research.
@@ -1686,7 +1696,9 @@ def cleanup_research_resources(research_id, username=None):
from ..queue.processor_v2 import queue_processor
if username:
- queue_processor.notify_research_completed(username, research_id)
+ queue_processor.notify_research_completed(
+ username, research_id, user_password=user_password
+ )
logger.info(
f"Notified queue processor of completion for research {research_id} (user: {username})"
)
diff --git a/src/local_deep_research/web/static/css/components/history-icons.css b/src/local_deep_research/web/static/css/components/history-icons.css
index 4e9c716ac8..ea97bfbadb 100644
--- a/src/local_deep_research/web/static/css/components/history-icons.css
+++ b/src/local_deep_research/web/static/css/components/history-icons.css
@@ -99,6 +99,15 @@
color: var(--text-secondary); /* Ensure text/icons are visible */
}
+/* Active state for toggle buttons (e.g. semantic search mode) */
+.ldr-btn-outline.active {
+ background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
+ color: var(--text-on-accent, white);
+ border-color: var(--accent-primary);
+}
+
+/* Semantic search styles moved to semantic-search.css */
+
/* Mobile responsive adjustments */
@media (max-width: 767px) {
.ldr-history-item-actions {
diff --git a/src/local_deep_research/web/static/css/components/semantic-search.css b/src/local_deep_research/web/static/css/components/semantic-search.css
new file mode 100644
index 0000000000..ed30c4cf38
--- /dev/null
+++ b/src/local_deep_research/web/static/css/components/semantic-search.css
@@ -0,0 +1,179 @@
+/* Semantic Search — Shared Styles
+ * Used by history, library, and collection pages for search results.
+ */
+
+/* Tier divider between text and semantic results */
+.ldr-hybrid-divider {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin: 1rem 0;
+ color: var(--text-secondary);
+ font-size: 0.85rem;
+}
+.ldr-hybrid-divider::before,
+.ldr-hybrid-divider::after {
+ content: '';
+ flex: 1;
+ border-top: 1px solid var(--border-color);
+}
+
+/* Tier 1 & Tier 3: card matched via semantic search */
+.ldr-history-item--semantic {
+ border-left: 3px solid var(--primary-color);
+}
+
+/* Tier 3: semantic-only result (slightly dimmed) */
+.ldr-history-item--semantic-only {
+ border-left: 3px solid var(--primary-color);
+ opacity: 0.95;
+}
+
+/* AI match indicator row (Tier 1 and Tier 3 cards) */
+.ldr-history-item-ai-match {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin-bottom: 0.5rem;
+}
+
+.ldr-ai-match-badge {
+ font-size: 0.8rem;
+ color: var(--primary-color);
+ font-weight: 500;
+}
+
+.ldr-ai-match-badge i {
+ margin-right: 0.25rem;
+}
+
+/* Snippet preview (2-line clamp, rendered markdown) */
+.ldr-history-item-snippet {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+ line-height: 1.5;
+ margin-bottom: 0.5rem;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.ldr-history-item-snippet strong {
+ color: var(--text-primary);
+ font-weight: 600;
+}
+.ldr-history-item-snippet code {
+ font-size: 0.8rem;
+ padding: 0.1em 0.3em;
+ background: var(--bg-secondary);
+ border-radius: 3px;
+}
+
+/* Brief opacity transition during re-render */
+.ldr-results-settling {
+ opacity: 0.6;
+ transition: opacity 150ms ease;
+}
+
+/* Hybrid search loading indicator */
+.ldr-hybrid-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ padding: 0.75rem;
+ color: var(--text-secondary);
+ font-size: 0.85rem;
+}
+
+/* Semantic result card (used by createSemanticResultCard) */
+.ldr-semantic-result {
+ padding: 1rem;
+ margin-bottom: 0.75rem;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ border-left: 3px solid var(--primary-color);
+ cursor: pointer;
+}
+.ldr-semantic-result:hover {
+ background: var(--bg-tertiary, var(--bg-secondary));
+}
+
+.ldr-semantic-result-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 0.5rem;
+}
+
+.ldr-semantic-type-badge {
+ font-size: 0.75rem;
+ margin-right: 0.5rem;
+}
+
+.ldr-semantic-result-date {
+ color: var(--text-secondary);
+ font-size: 0.8rem;
+}
+
+.ldr-semantic-result-title {
+ margin: 0 0 0.5rem 0;
+ font-size: 1rem;
+}
+.ldr-semantic-result-title a {
+ color: var(--text-primary);
+ text-decoration: none;
+}
+.ldr-semantic-result-title a:hover {
+ text-decoration: underline;
+}
+
+.ldr-semantic-result-source {
+ margin: 0.5rem 0 0 0;
+}
+.ldr-semantic-result-source a {
+ font-size: 0.8rem;
+ color: var(--primary-color);
+}
+
+/* AI Search panel layout */
+.ldr-semantic-panel-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ cursor: pointer;
+}
+.ldr-semantic-panel-header h3 {
+ margin: 0;
+}
+.ldr-semantic-panel-description {
+ margin: 0 0 0.75rem 0;
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+}
+.ldr-indexing-status {
+ padding: 0.75rem;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+}
+.ldr-indexing-status-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+.ldr-progress-track {
+ background: var(--bg-tertiary);
+ border-radius: 4px;
+ height: 8px;
+ overflow: hidden;
+}
+.ldr-progress-bar {
+ background: var(--primary-color);
+ height: 100%;
+ transition: width 0.3s;
+}
+.ldr-search-row {
+ display: flex;
+ gap: 0.5rem;
+ flex: 1;
+}
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index af7e8f0a85..f96c6b4782 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -12,12 +12,20 @@
// Component state
let historyItems = [];
let filteredItems = [];
- let searchDebounceTimer = null;
+ let inputDebounceTimer = null;
+ let semanticDebounceTimer = null;
+ const SM = (typeof LDR_CONSTANTS !== 'undefined' && LDR_CONSTANTS.SEARCH_MODE) || { HYBRID: 'hybrid', TEXT: 'text', SEMANTIC: 'semantic' };
+ let searchMode = SM.HYBRID;
+ let hybridSearchId = 0;
+ let semanticSearchId = 0;
// Security: local escapeHtml to prevent XSS in innerHTML assignments
// bearer:disable javascript_lang_manual_html_sanitization
const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
+ // Shared semantic search utilities (from semantic_search.js)
+ const renderSnippet = (window.SemanticSearch && window.SemanticSearch.renderSnippet) || (md => esc(md || ''));
+
// Fallback UI utilities in case main UI utils aren't loaded
const uiUtils = {
showSpinner: function(container, message) {
@@ -100,7 +108,7 @@
// Fallback implementation
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(`/api/delete/${researchId}`, {
+ const response = await fetch(URLBuilder.deleteResearch(researchId), {
method: 'DELETE',
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
@@ -174,8 +182,36 @@
// Debounced search input
if (searchInput) {
searchInput.addEventListener('input', () => {
- clearTimeout(searchDebounceTimer);
- searchDebounceTimer = setTimeout(handleSearchInput, 250);
+ clearTimeout(inputDebounceTimer);
+ inputDebounceTimer = setTimeout(handleSearchInput, 250);
+ });
+ }
+
+ // Search mode dropdown
+ const modeMenu = document.getElementById('search-mode-menu');
+ if (modeMenu) {
+ modeMenu.addEventListener('click', (e) => {
+ const item = e.target.closest('.dropdown-item');
+ if (!item) return;
+ e.preventDefault();
+
+ const mode = item.dataset.mode;
+ if (!mode || mode === searchMode) return;
+
+ searchMode = mode;
+
+ // Update active state
+ modeMenu.querySelectorAll('.dropdown-item').forEach(el => el.classList.remove('active'));
+ item.classList.add('active');
+
+ // Update button label
+ const btn = document.getElementById('search-mode-btn');
+ const labels = { hybrid: '<i class="fas fa-brain"></i> Hybrid', text: '<i class="fas fa-font"></i> Text Only', semantic: '<i class="fas fa-brain"></i> AI Only' };
+ const placeholders = { hybrid: 'Search titles + content...', text: 'Filter history by title...', semantic: 'Search content with AI...' };
+ if (btn) btn.innerHTML = labels[mode];
+ if (searchInput) searchInput.placeholder = placeholders[mode];
+
+ handleSearchInput();
});
}
@@ -190,15 +226,22 @@
const itemEl = e.target.closest('.ldr-history-item');
if (!itemEl) return;
const itemId = itemEl.dataset.id;
- const itemData = historyItems.find(h => h.id === itemId);
- if (!itemData) return;
+ const itemData = historyItems.find(h => String(h.id) === itemId);
+
+ // For semantic-only items not in historyItems, handle View + item click
+ if (!itemData) {
+ if (e.target.closest('.ldr-view-btn') || !e.target.closest('button')) {
+ URLValidator.safeAssign(window.location, 'href', URLBuilder.resultsPage(itemId));
+ }
+ return;
+ }
if (e.target.closest('.ldr-delete-item-btn')) {
handleDeleteItem(itemId);
} else if (e.target.closest('.ldr-view-btn')) {
URLValidator.safeAssign(window.location, 'href', URLBuilder.resultsPage(itemId));
} else if (e.target.closest('.ldr-library-btn')) {
- URLValidator.safeAssign(window.location, 'href', `/library/?research=${itemId}`);
+ URLValidator.safeAssign(window.location, 'href', `${URLS.PAGES.LIBRARY}?research=${encodeURIComponent(itemId)}`);
} else if (e.target.closest('.ldr-subscribe-btn')) {
handleSubscribe(itemData);
} else if (e.target.closest('.ldr-rerun-btn')) {
@@ -346,11 +389,13 @@
/**
* Create a history item element
* @param {Object} item - The history item data
+ * @param {Object|null} semanticMatch - Optional semantic match data {similarity, snippet}
* @returns {HTMLElement} The history item element
*/
- function createHistoryItemElement(item) {
+ function createHistoryItemElement(item, semanticMatch) {
const itemEl = document.createElement('div');
itemEl.className = 'ldr-history-item';
+ if (semanticMatch) itemEl.classList.add('ldr-history-item--semantic');
itemEl.dataset.id = item.id;
// Format date
@@ -365,12 +410,21 @@
// Check if this is a news-related research
const isNewsItem = item.metadata && item.metadata.is_news_search;
+ // AI match badge + snippet rows (for Tier 1 items)
+ const aiMatchHtml = semanticMatch ? `
+ <div class="ldr-history-item-ai-match">
+ <span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(String(semanticMatch.similarity))}% match</span>
+ </div>
+ ${semanticMatch.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticMatch.snippet)}</div>` : ''}
+ ` : '';
+
// bearer:disable javascript_lang_dangerous_insert_html
itemEl.innerHTML = `
<div class="ldr-history-item-header">
<div class="ldr-history-item-title">${esc(displayTitle)}</div>
<div class="ldr-history-item-status ldr-status-${esc(statusClass)}">${esc(formatStatus(item.status))}</div>
</div>
+ ${aiMatchHtml}
<div class="ldr-history-item-meta">
<div class="ldr-history-item-date">${esc(formattedDate)}</div>
<div class="ldr-history-item-mode">${esc(formatMode(item.mode))}</div>
@@ -379,19 +433,19 @@
<div class="ldr-history-item-actions">
${item.status === 'completed' ?
`<button class="btn btn-sm ldr-btn-outline ldr-view-btn">
- <i class="fas fa-eye"></i> View
+ <i class="fas fa-eye"></i><span> View</span>
</button>` : ''}
${item.status === 'completed' && item.document_count > 0 ?
- `<button class="btn btn-sm btn-outline ldr-library-btn">
- <i class="fas fa-book"></i> Library (${item.document_count})
+ `<button class="btn btn-sm ldr-btn-outline ldr-library-btn">
+ <i class="fas fa-book"></i><span> Library (${esc(String(item.document_count))})</span>
</button>` : ''}
${isNewsItem && item.status === 'completed' ?
`<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${esc(item.id)}" data-query="${esc(encodeURIComponent(item.query))}">
- <i class="fas fa-bell"></i> Subscribe
+ <i class="fas fa-bell"></i><span> Subscribe</span>
</button>` : ''}
${item.status === 'completed' ?
`<button class="btn btn-sm ldr-btn-outline ldr-rerun-btn" title="Re-run this research">
- <i class="fas fa-redo"></i> Re-run
+ <i class="fas fa-redo"></i><span> Re-run</span>
</button>` : ''}
<button class="btn btn-sm ldr-btn-outline ldr-delete-item-btn">
<i class="fas fa-trash-alt"></i>
@@ -402,6 +456,120 @@
return itemEl;
}
+ /**
+ * Create a semantic-only item element (Tier 3).
+ * Tries to find the full history item; if found, renders full card with semantic badge.
+ * Otherwise renders a simplified card with View button only.
+ */
+ function createSemanticOnlyElement(semanticResult) {
+ const historyItem = historyItems.find(h => String(h.id) === String(semanticResult.research_id));
+ const semanticMatch = {
+ similarity: semanticResult.similarity,
+ snippet: semanticResult.snippet || ''
+ };
+
+ if (historyItem) {
+ return createHistoryItemElement(historyItem, semanticMatch);
+ }
+
+ // Simplified card — no full history data available
+ const itemEl = document.createElement('div');
+ itemEl.className = 'ldr-history-item ldr-history-item--semantic-only';
+ itemEl.dataset.id = semanticResult.research_id;
+
+ const displayTitle = semanticResult.research_title || semanticResult.title || 'Untitled Research';
+ let dateStr = '';
+ if (semanticResult.research_created_at) {
+ try {
+ dateStr = new Date(semanticResult.research_created_at).toLocaleDateString();
+ } catch (e) {
+ dateStr = '';
+ }
+ }
+
+ // bearer:disable javascript_lang_dangerous_insert_html
+ itemEl.innerHTML = `
+ <div class="ldr-history-item-header">
+ <div class="ldr-history-item-title">${esc(displayTitle)}</div>
+ </div>
+ <div class="ldr-history-item-ai-match">
+ <span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(String(semanticResult.similarity))}% match</span>
+ </div>
+ ${semanticResult.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticResult.snippet)}</div>` : ''}
+ <div class="ldr-history-item-meta">
+ ${dateStr ? `<div class="ldr-history-item-date">${esc(dateStr)}</div>` : ''}
+ </div>
+ <div class="ldr-history-item-actions">
+ <button class="btn btn-sm ldr-btn-outline ldr-view-btn">
+ <i class="fas fa-eye"></i><span> View</span>
+ </button>
+ </div>
+ `;
+
+ return itemEl;
+ }
+
+ // Shared tiered merge from semantic_search.js
+ const buildTieredResults = (window.SemanticSearch && window.SemanticSearch.buildTieredResults) || function() { return { tier1: [], tier2: [], tier3: [] }; };
+
+ /**
+ * Render merged tiered results into the history container.
+ */
+ function renderMergedResults(tiered) {
+ if (!historyContainer) return;
+
+ const { tier1, tier2, tier3 } = tiered;
+ const totalCount = tier1.length + tier2.length + tier3.length;
+
+ if (totalCount === 0) {
+ historyContainer.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-history ldr-empty-icon"></i>
+ <p>No research history found.</p>
+ <p>Try adjusting your search query.</p>
+ </div>
+ `;
+ return;
+ }
+
+ // Brief settling transition
+ historyContainer.classList.add('ldr-results-settling');
+
+ const fragment = document.createDocumentFragment();
+
+ // Tier 1: both text + semantic
+ for (const entry of tier1) {
+ fragment.appendChild(createHistoryItemElement(entry.historyItem, entry.semanticMatch));
+ }
+
+ // Tier 2: text-only
+ for (const entry of tier2) {
+ fragment.appendChild(createHistoryItemElement(entry.historyItem));
+ }
+
+ // Tier 3: semantic-only (with divider)
+ if (tier3.length > 0) {
+ const divider = document.createElement('div');
+ divider.className = 'ldr-hybrid-divider';
+ divider.textContent = 'Also found in content';
+ fragment.appendChild(divider);
+
+ for (const entry of tier3) {
+ fragment.appendChild(createSemanticOnlyElement(entry.semanticResult));
+ }
+ }
+
+ historyContainer.innerHTML = '';
+ historyContainer.appendChild(fragment);
+
+ // Remove settling class after browser has painted the 0.6 opacity frame
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ historyContainer.classList.remove('ldr-results-settling');
+ });
+ });
+ }
+
/**
* Handle subscribe button click
* @param {Object} item - The research item
@@ -461,33 +629,145 @@
}
/**
- * Handle search input
+ * Run text filter on historyItems and return the filtered list
+ */
+ function runTextFilter(searchTerm) {
+ const lowerTerm = searchTerm.toLowerCase();
+ return historyItems.filter(item => {
+ const titleMatch = item.title ?
+ item.title.toLowerCase().includes(lowerTerm) :
+ false;
+ const queryMatch = item.query ?
+ item.query.toLowerCase().includes(lowerTerm) :
+ false;
+ return titleMatch || queryMatch;
+ });
+ }
+
+ /**
+ * Handle search input — text, semantic, or hybrid depending on mode
*/
function handleSearchInput() {
- const searchTerm = searchInput.value.trim().toLowerCase();
+ if (!searchInput) return;
+ // Clean up stale hybrid loading indicator on any mode change/re-entry
+ const staleIndicator = document.getElementById('hybrid-loading-indicator');
+ if (staleIndicator) staleIndicator.remove();
+ const searchTerm = searchInput.value.trim();
if (!searchTerm) {
- // Reset to show all items
filteredItems = [...historyItems];
- } else {
- // Filter items based on search term
- filteredItems = historyItems.filter(item => {
- // Search in title if available, otherwise in query
- const titleMatch = item.title ?
- item.title.toLowerCase().includes(searchTerm) :
- false;
-
- // Always search in query
- const queryMatch = item.query ?
- item.query.toLowerCase().includes(searchTerm) :
- false;
-
- return titleMatch || queryMatch;
- });
+ renderHistoryItems();
+ return;
}
- // Render filtered items
- renderHistoryItems();
+ if (searchMode === SM.TEXT) {
+ filteredItems = runTextFilter(searchTerm);
+ renderHistoryItems();
+
+ } else if (searchMode === SM.SEMANTIC) {
+ clearTimeout(semanticDebounceTimer);
+ const currentSemanticId = ++semanticSearchId;
+ semanticDebounceTimer = setTimeout(async () => {
+ if (!window.HistorySearch ||
+ typeof window.HistorySearch.semanticSearchHistory !== 'function' ||
+ typeof window.HistorySearch.renderSemanticResults !== 'function') {
+ if (historyContainer) {
+ historyContainer.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-exclamation-triangle"></i>
+ <p>Semantic search is loading. Please try again.</p>
+ </div>
+ `;
+ }
+ return;
+ }
+ if (historyContainer) {
+ historyContainer.innerHTML = '<div class="ldr-loading-spinner ldr-centered"><div class="ldr-spinner"></div></div>';
+ }
+ try {
+ const results = await window.HistorySearch.semanticSearchHistory(searchTerm);
+ if (currentSemanticId !== semanticSearchId) return; // stale
+ if (searchMode !== SM.SEMANTIC) return; // mode changed
+ if (results && results.needsIndexing) {
+ historyContainer.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-brain"></i>
+ <p>No research indexed yet. Use the "Index All" button above to enable semantic search.</p>
+ </div>
+ `;
+ return;
+ }
+ window.HistorySearch.renderSemanticResults(results);
+ } catch (error) {
+ SafeLogger.error('Semantic search failed:', error);
+ if (historyContainer) {
+ historyContainer.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-exclamation-triangle"></i>
+ <p>Search failed. Please try again.</p>
+ </div>
+ `;
+ }
+ }
+ }, 500);
+
+ } else if (searchMode === SM.HYBRID) {
+ // 1. Instant text filter — render as Tier 2 immediately
+ const textResults = runTextFilter(searchTerm);
+ filteredItems = textResults;
+ renderHistoryItems();
+
+ // 2. Check if semantic search is available
+ if (!window.HistorySearch ||
+ typeof window.HistorySearch.getSemanticCollectionId !== 'function' ||
+ !window.HistorySearch.getSemanticCollectionId()) {
+ return; // Not indexed — text results only, no indicator
+ }
+ if (typeof window.HistorySearch.semanticSearchHistory !== 'function') {
+ return;
+ }
+
+ // 3. Append loading indicator (remove stale one first)
+ const existingIndicator = document.getElementById('hybrid-loading-indicator');
+ if (existingIndicator) existingIndicator.remove();
+ const loadingDiv = document.createElement('div');
+ loadingDiv.className = 'ldr-hybrid-loading';
+ loadingDiv.id = 'hybrid-loading-indicator';
+ loadingDiv.innerHTML = '<div class="ldr-spinner" style="width: 16px; height: 16px; border-width: 2px;"></div> Searching content...';
+ if (historyContainer) historyContainer.appendChild(loadingDiv);
+
+ // 4. Race-condition guard
+ const currentSearchId = ++hybridSearchId;
+
+ // 5. Debounced semantic call (separate timer from input debounce)
+ clearTimeout(semanticDebounceTimer);
+ semanticDebounceTimer = setTimeout(async () => {
+ try {
+ const results = await window.HistorySearch.semanticSearchHistory(searchTerm);
+ if (currentSearchId !== hybridSearchId) return; // stale
+ if (searchMode !== SM.HYBRID) {
+ const indicator = document.getElementById('hybrid-loading-indicator');
+ if (indicator) indicator.remove();
+ return;
+ }
+
+ // Remove loading indicator
+ const indicator = document.getElementById('hybrid-loading-indicator');
+ if (indicator) indicator.remove();
+
+ if (results && results.needsIndexing) return;
+
+ // Build tiered merge and re-render
+ const semanticResults = Array.isArray(results) ? results : [];
+ const tiered = buildTieredResults(textResults, semanticResults);
+ renderMergedResults(tiered);
+ } catch (error) {
+ SafeLogger.error('Hybrid semantic search failed:', error);
+ const indicator = document.getElementById('hybrid-loading-indicator');
+ if (indicator) indicator.remove();
+ }
+ }, 500);
+ }
}
/**
@@ -504,14 +784,14 @@
await apiUtils.deleteResearch(itemId);
// Remove from arrays
- historyItems = historyItems.filter(item => item.id != itemId);
- filteredItems = filteredItems.filter(item => item.id != itemId);
+ historyItems = historyItems.filter(item => String(item.id) !== itemId);
+ filteredItems = filteredItems.filter(item => String(item.id) !== itemId);
// Show success message
uiUtils.showMessage('Research deleted successfully');
- // Re-render history items
- renderHistoryItems();
+ // Re-render via handleSearchInput to preserve hybrid/semantic state
+ handleSearchInput();
} catch (error) {
SafeLogger.error('Error deleting research:', error);
uiUtils.showError('Error deleting research: ' + error.message);
diff --git a/src/local_deep_research/web/static/js/components/history_search.js b/src/local_deep_research/web/static/js/components/history_search.js
new file mode 100644
index 0000000000..dfe2b49e00
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/history_search.js
@@ -0,0 +1,470 @@
+/**
+ * History Semantic Search Component
+ *
+ * Provides semantic search functionality over research history:
+ * - Load indexing status
+ * - Trigger indexing with progress
+ * - Perform semantic search (called from history.js toggle)
+ * - Display results with snippets and scores
+ */
+(function() {
+
+// URL validation: isSafeUrl provided by SemanticSearch (semantic_search.js)
+// Use shared escapeHtml from xss-protection.js (loaded via base.html),
+// with a safe fallback if not available.
+const escapeHtml = window.escapeHtml || function(text) {
+ if (text === null || text === undefined) return '';
+ const div = document.createElement('div');
+ div.textContent = String(text);
+ return div.innerHTML;
+};
+
+// State
+let isIndexing = false;
+let semanticPanelExpanded = true;
+let cachedCollectionId = null;
+let indexingPollInterval = null;
+let pollErrorCount = 0;
+
+/**
+ * Initialize the semantic search component
+ */
+async function initSemanticSearch() {
+ // Load initial indexing status (also caches collection ID)
+ await loadIndexingStatus();
+ // Resume polling if indexing was already in progress
+ await checkAndResumeIndexing();
+}
+
+/**
+ * Toggle the semantic search panel visibility
+ */
+function toggleSemanticPanel() {
+ const content = document.getElementById('semantic-panel-content');
+ const toggle = document.getElementById('semantic-panel-toggle');
+ const header = document.getElementById('semantic-panel-header');
+
+ if (content && toggle) {
+ semanticPanelExpanded = !semanticPanelExpanded;
+ content.style.display = semanticPanelExpanded ? 'block' : 'none';
+ toggle.className = semanticPanelExpanded
+ ? 'fas fa-chevron-down'
+ : 'fas fa-chevron-right';
+ if (header) {
+ header.setAttribute('aria-expanded', semanticPanelExpanded ? 'true' : 'false');
+ }
+ }
+}
+
+/**
+ * Load indexing status from the API
+ */
+async function loadIndexingStatus() {
+ try {
+ const response = await fetch(URLS.LIBRARY_API.RESEARCH_HISTORY_COLLECTION);
+ if (!response.ok) {
+ throw new Error(`Server returned ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (data.success) {
+ cachedCollectionId = data.collection_id || null;
+
+ const indexedCountEl = document.getElementById('indexed-count');
+ const totalCountEl = document.getElementById('total-count');
+ if (indexedCountEl) indexedCountEl.textContent = data.indexed_documents || 0;
+ if (totalCountEl) totalCountEl.textContent = data.total_documents || 0;
+
+ // Update button state
+ const indexBtn = document.getElementById('index-all-btn');
+ if (indexBtn) {
+ const allIndexed = data.indexed_documents >= data.total_documents;
+ indexBtn.disabled = allIndexed && data.total_documents > 0;
+ if (allIndexed && data.total_documents > 0) {
+ indexBtn.innerHTML = '<i class="fas fa-check"></i> All Indexed';
+ }
+ }
+ }
+ } catch (error) {
+ SafeLogger.error('Failed to load indexing status:', error);
+ }
+}
+
+/**
+ * Trigger indexing of all research history
+ */
+async function triggerIndexing() {
+ if (isIndexing) return;
+ isIndexing = true; // Set immediately to prevent double-click race
+
+ const indexBtn = document.getElementById('index-all-btn');
+ const progressDiv = document.getElementById('indexing-progress');
+ const progressBar = document.getElementById('indexing-progress-bar');
+ const progressText = document.getElementById('indexing-progress-text');
+
+ if (!cachedCollectionId) {
+ await loadIndexingStatus();
+ }
+ if (!cachedCollectionId) {
+ if (progressText) {
+ progressText.textContent = 'Collection not available. Please refresh the page.';
+ progressText.style.color = 'var(--danger)';
+ }
+ isIndexing = false;
+ return;
+ }
+
+ // Show progress UI
+ if (indexBtn) {
+ indexBtn.disabled = true;
+ indexBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Indexing...';
+ }
+ if (progressDiv) progressDiv.style.display = 'block';
+ if (progressBar) progressBar.style.width = '0%';
+ if (progressText) {
+ progressText.textContent = 'Starting...';
+ progressText.style.color = ''; // reset from any prior error styling
+ }
+
+ const csrfToken = (window.api && window.api.getCsrfToken)
+ ? window.api.getCsrfToken()
+ : (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');
+
+ // Step 1: Convert any unconverted research entries to documents (fast, synchronous)
+ try {
+ if (progressText) progressText.textContent = 'Converting research to documents...';
+
+ const convertResp = await fetch(URLS.LIBRARY_API.RESEARCH_HISTORY_CONVERT_ALL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken,
+ },
+ body: JSON.stringify({}),
+ });
+
+ if (!convertResp.ok) {
+ SafeLogger.warn('Convert-all returned ' + convertResp.status);
+ } else {
+ const convertData = await convertResp.json();
+ if (convertData.converted > 0) {
+ SafeLogger.log('Converted ' + convertData.converted + ' research entries to documents');
+ }
+ }
+ } catch (convertError) {
+ // Non-fatal: conversion may have already happened via auto-hook
+ SafeLogger.warn('Convert-all request failed, proceeding to indexing:', convertError);
+ }
+
+ // Step 2: Start background indexing via POST
+ if (progressText) progressText.textContent = 'Starting indexing...';
+
+ try {
+ const startResp = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_START, cachedCollectionId), {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken,
+ },
+ body: JSON.stringify({ force_reindex: false }),
+ });
+
+ if (!startResp.ok && startResp.status !== 409) {
+ throw new Error(`Server returned ${startResp.status}`);
+ }
+
+ let startData;
+ try {
+ startData = await startResp.json();
+ } catch (parseError) {
+ throw new Error(`Server returned ${startResp.status}: unable to parse response`);
+ }
+
+ if (!startData.success && startResp.status !== 409) {
+ throw new Error(startData.error || 'Failed to start indexing');
+ }
+
+ // 409 means already running — just start polling
+ SafeLogger.log('Indexing started, beginning polling');
+ } catch (startError) {
+ SafeLogger.error('Error starting indexing:', startError);
+ isIndexing = false;
+ if (progressText) {
+ progressText.textContent = `Error: ${startError.message}`;
+ progressText.style.color = 'var(--danger)';
+ }
+ if (indexBtn) {
+ indexBtn.disabled = false;
+ indexBtn.innerHTML = '<i class="fas fa-sync"></i> Index All';
+ }
+ return;
+ }
+
+ // Step 3: Poll for status every 2 seconds
+ startPolling();
+}
+
+/**
+ * Start polling the index status endpoint every 2 seconds
+ */
+function startPolling() {
+ // Reset error counter for this new polling session
+ pollErrorCount = 0;
+
+ // Clear any existing interval
+ if (indexingPollInterval) {
+ clearInterval(indexingPollInterval);
+ }
+
+ const indexBtn = document.getElementById('index-all-btn');
+ const progressDiv = document.getElementById('indexing-progress');
+ const progressBar = document.getElementById('indexing-progress-bar');
+ const progressText = document.getElementById('indexing-progress-text');
+
+ indexingPollInterval = setInterval(async () => {
+ try {
+ const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
+ if (!response.ok) {
+ throw new Error(`Status endpoint returned ${response.status}`);
+ }
+ const data = await response.json();
+
+ // Reset error counter on every successful response
+ pollErrorCount = 0;
+
+ // Update progress bar
+ if (data.progress_total > 0) {
+ const percent = Math.round((data.progress_current / data.progress_total) * 100);
+ if (progressBar) progressBar.style.width = percent + '%';
+ }
+ if (data.progress_message && progressText) {
+ progressText.textContent = data.progress_message;
+ }
+
+ // Stop polling on terminal states
+ if (['completed', 'failed', 'cancelled', 'idle'].includes(data.status)) {
+ clearInterval(indexingPollInterval);
+ indexingPollInterval = null;
+ isIndexing = false;
+
+ if (data.status === 'completed') {
+ if (progressBar) progressBar.style.width = '100%';
+ if (progressText) progressText.textContent = data.progress_message || 'Indexing complete!';
+ } else if (data.status === 'failed') {
+ if (progressText) {
+ progressText.textContent = `Indexing failed: ${data.error_message || 'Unknown error'}`;
+ progressText.style.color = 'var(--danger)';
+ }
+ } else if (data.status === 'cancelled') {
+ if (progressText) progressText.textContent = 'Indexing was cancelled.';
+ }
+
+ setTimeout(() => {
+ if (progressDiv) progressDiv.style.display = 'none';
+ if (progressText) progressText.style.color = '';
+ loadIndexingStatus();
+ if (indexBtn) {
+ indexBtn.disabled = false;
+ indexBtn.innerHTML = '<i class="fas fa-sync"></i> Index All';
+ }
+ }, 2000);
+ }
+ } catch (error) {
+ SafeLogger.error('Error polling indexing status:', error);
+ pollErrorCount++;
+ if (pollErrorCount >= 5) {
+ clearInterval(indexingPollInterval);
+ indexingPollInterval = null;
+ isIndexing = false;
+ if (progressText) {
+ progressText.textContent = 'Lost connection to server. Please try again.';
+ progressText.style.color = 'var(--danger)';
+ }
+ if (indexBtn) {
+ indexBtn.disabled = false;
+ indexBtn.innerHTML = '<i class="fas fa-sync"></i> Index All';
+ }
+ }
+ }
+ }, 2000);
+}
+
+/**
+ * Check if indexing is already in progress on page load and resume UI
+ */
+async function checkAndResumeIndexing() {
+ if (!cachedCollectionId) return;
+
+ try {
+ const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
+ if (!response.ok) {
+ SafeLogger.warn('Index status check returned ' + response.status);
+ return;
+ }
+ const data = await response.json();
+
+ if (data.status === 'processing') {
+ SafeLogger.log('Active indexing task found, resuming UI');
+ const indexBtn = document.getElementById('index-all-btn');
+ const progressDiv = document.getElementById('indexing-progress');
+ const progressBar = document.getElementById('indexing-progress-bar');
+ const progressText = document.getElementById('indexing-progress-text');
+
+ isIndexing = true;
+ if (indexBtn) {
+ indexBtn.disabled = true;
+ indexBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Indexing...';
+ }
+ if (progressDiv) progressDiv.style.display = 'block';
+ if (progressBar) progressBar.style.width = '0%';
+ if (progressText) progressText.style.color = '';
+
+ // Apply current progress immediately
+ if (data.progress_total > 0) {
+ const percent = Math.round((data.progress_current / data.progress_total) * 100);
+ if (progressBar) progressBar.style.width = percent + '%';
+ }
+ if (data.progress_message && progressText) {
+ progressText.textContent = data.progress_message;
+ }
+
+ startPolling();
+ }
+ } catch (error) {
+ SafeLogger.error('Error checking indexing status:', error);
+ }
+}
+
+/**
+ * Perform semantic search against the generic collection search endpoint.
+ * Called from history.js when in semantic mode.
+ *
+ * @param {string} query - Search query
+ * @returns {Promise<Array>} Search results
+ */
+async function semanticSearchHistory(query) {
+ if (!query) return [];
+
+ // Use cached collection ID, or fetch it
+ if (!cachedCollectionId) {
+ await loadIndexingStatus();
+ }
+ if (!cachedCollectionId) {
+ return { needsIndexing: true };
+ }
+
+ const csrfToken = (window.api && window.api.getCsrfToken)
+ ? window.api.getCsrfToken()
+ : (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');
+
+ const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_SEARCH, cachedCollectionId), {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken,
+ },
+ body: JSON.stringify({ query, limit: 20 }),
+ });
+
+ if (!response.ok) {
+ if (response.status === 404) {
+ cachedCollectionId = null;
+ }
+ throw new Error(`Server returned ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (!data.success) {
+ throw new Error(data.error || 'Search failed');
+ }
+
+ return data.results || [];
+}
+
+/**
+ * Render semantic search results into the history-items container.
+ * Uses shared createSemanticResultCard from semantic_search.js.
+ */
+function renderSemanticResults(results) {
+ const container = document.getElementById('history-items');
+
+ if (!container) return;
+
+ if (!results || results.length === 0) {
+ container.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-search"></i>
+ <p>No matching results found. Try indexing more research or using different keywords.</p>
+ </div>
+ `;
+ return;
+ }
+
+ const fragment = document.createDocumentFragment();
+ for (const result of results) {
+ if (window.SemanticSearch && window.SemanticSearch.createSemanticResultCard) {
+ fragment.appendChild(window.SemanticSearch.createSemanticResultCard(result));
+ }
+ }
+ container.innerHTML = '';
+ container.appendChild(fragment);
+}
+
+/**
+ * Return the cached collection ID (or null if not indexed).
+ * Used by history.js hybrid mode to check indexing status.
+ */
+function getSemanticCollectionId() {
+ return cachedCollectionId;
+}
+
+// Expose functions needed by history.js under a single namespace
+window.HistorySearch = {
+ toggleSemanticPanel,
+ triggerIndexing,
+ semanticSearchHistory,
+ renderSemanticResults,
+ getSemanticCollectionId,
+};
+
+/**
+ * Set up event listeners for panel header and index button
+ */
+function setupEventListeners() {
+ const header = document.getElementById('semantic-panel-header');
+ if (header) {
+ header.addEventListener('click', toggleSemanticPanel);
+ header.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleSemanticPanel();
+ }
+ });
+ }
+
+ const indexBtn = document.getElementById('index-all-btn');
+ if (indexBtn) {
+ indexBtn.addEventListener('click', triggerIndexing);
+ }
+}
+
+// Clean up polling interval on page unload
+window.addEventListener('beforeunload', () => {
+ if (indexingPollInterval) {
+ clearInterval(indexingPollInterval);
+ indexingPollInterval = null;
+ }
+});
+
+// Initialize on page load
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', () => {
+ setupEventListeners();
+ initSemanticSearch();
+ });
+} else {
+ setupEventListeners();
+ initSemanticSearch();
+}
+
+})();
diff --git a/src/local_deep_research/web/static/js/components/save_to_collection.js b/src/local_deep_research/web/static/js/components/save_to_collection.js
new file mode 100644
index 0000000000..10f3fa2db1
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/save_to_collection.js
@@ -0,0 +1,235 @@
+/**
+ * Save to Collection Component
+ *
+ * Allows users to save research (report + sources) to user collections
+ * for semantic search.
+ */
+(function() {
+ // URL security: This component uses centralized URLS.LIBRARY_API constants for API endpoints.
+ // External URL validation is available via URLValidator.isSafeUrl if needed.
+
+ // Use shared escapeHtml from xss-protection.js (loaded via base.html),
+ // with a safe fallback if not available.
+ const escapeHtml = window.escapeHtml || function(text) {
+ if (text === null || text === undefined) return '';
+ const div = document.createElement('div');
+ div.textContent = String(text);
+ return div.innerHTML;
+ };
+
+ let modal = null;
+ let researchId = null;
+
+ /**
+ * Initialize the save to collection component
+ */
+ function initSaveToCollection() {
+ const saveBtn = document.getElementById('save-to-collection-btn');
+ if (!saveBtn) return;
+
+ // Get research ID from URL
+ researchId = getResearchIdFromUrl();
+ if (!researchId) {
+ saveBtn.disabled = true;
+ saveBtn.title = 'Research ID not found';
+ return;
+ }
+
+ // Set up click handler
+ saveBtn.addEventListener('click', showCollectionModal);
+ }
+
+ /**
+ * Get research ID from URL
+ */
+ function getResearchIdFromUrl() {
+ return URLBuilder.extractResearchIdFromPattern('results');
+ }
+
+ /**
+ * Show the collection selection modal
+ */
+ async function showCollectionModal() {
+ // Initialize modal if not already
+ const modalElement = document.getElementById('saveToCollectionModal');
+ if (!modalElement) {
+ SafeLogger.error('Save to collection modal not found');
+ return;
+ }
+
+ if (typeof bootstrap === 'undefined' || !bootstrap.Modal) {
+ SafeLogger.error('Bootstrap Modal not available');
+ return;
+ }
+ modal = bootstrap.Modal.getOrCreateInstance(modalElement);
+ modal.show();
+
+ // Reset UI state
+ document.getElementById('collection-list-loading').style.display = 'block';
+ document.getElementById('collection-list').style.display = 'none';
+ document.getElementById('collection-error').style.display = 'none';
+ document.getElementById('collection-success').style.display = 'none';
+
+ // Load collections
+ await loadCollections();
+ }
+
+ /**
+ * Load available collections
+ */
+ async function loadCollections() {
+ try {
+ const response = await fetch(URLS.LIBRARY_API.COLLECTIONS);
+ if (!response.ok) {
+ throw new Error(`Server returned ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (!data.success) {
+ throw new Error(data.error || 'Failed to load collections');
+ }
+
+ renderCollections(data.collections);
+
+ } catch (error) {
+ SafeLogger.error('Error loading collections:', error);
+ document.getElementById('collection-list-loading').style.display = 'none';
+ const errorDiv = document.getElementById('collection-error');
+ errorDiv.textContent = 'Failed to load collections: ' + error.message;
+ errorDiv.style.display = 'block';
+ }
+ }
+
+ /**
+ * Render the collection list
+ */
+ function renderCollections(collections) {
+ const loadingDiv = document.getElementById('collection-list-loading');
+ const listDiv = document.getElementById('collection-list');
+ const itemsDiv = document.getElementById('collection-items');
+
+ loadingDiv.style.display = 'none';
+
+ if (!collections || collections.length === 0) {
+ itemsDiv.innerHTML = `
+ <div class="text-center text-muted py-3">
+ <i class="fas fa-folder-open"></i>
+ <p class="mt-2">No collections found. Create a collection in the Library first.</p>
+ </div>
+ `;
+ listDiv.style.display = 'block';
+ return;
+ }
+
+ // Build collection items
+ const html = collections.map(col => `
+ <button type="button" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
+ data-collection-id="${escapeHtml(col.id)}"
+ data-collection-name="${escapeHtml(col.name)}">
+ <div>
+ <i class="fas fa-folder me-2"></i>
+ <strong>${escapeHtml(col.name)}</strong>
+ ${col.description ? `<br><small class="text-muted">${escapeHtml(col.description)}</small>` : ''}
+ </div>
+ <i class="fas fa-chevron-right text-muted"></i>
+ </button>
+ `).join('');
+
+ itemsDiv.innerHTML = html;
+
+ // Attach click listeners via event delegation (avoids XSS from inline handlers)
+ itemsDiv.querySelectorAll('button[data-collection-id]').forEach(btn => {
+ btn.addEventListener('click', () => {
+ saveToCollection(btn.dataset.collectionId, btn.dataset.collectionName);
+ });
+ });
+
+ listDiv.style.display = 'block';
+ }
+
+ /**
+ * Save research to the selected collection
+ */
+ async function saveToCollection(collectionId, collectionName) {
+ const itemsDiv = document.getElementById('collection-items');
+ const errorDiv = document.getElementById('collection-error');
+ const successDiv = document.getElementById('collection-success');
+
+ // Find and disable the clicked button (save original HTML for error recovery)
+ const buttons = itemsDiv.querySelectorAll('button');
+ let originalBtnHtml = null;
+ buttons.forEach(btn => {
+ btn.disabled = true;
+ if (btn.dataset.collectionId === collectionId) {
+ originalBtnHtml = btn.innerHTML;
+ btn.innerHTML = `
+ <div>
+ <i class="fas fa-spinner fa-spin me-2"></i>
+ <strong>Saving...</strong>
+ </div>
+ `;
+ }
+ });
+
+ errorDiv.style.display = 'none';
+ successDiv.style.display = 'none';
+
+ try {
+ // Get CSRF token
+ const csrfToken = (window.api && window.api.getCsrfToken)
+ ? window.api.getCsrfToken()
+ : (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');
+
+ const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.RESEARCH_ADD_TO_COLLECTION, researchId), {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ collection_id: collectionId })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Server returned ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (!data.success) {
+ throw new Error(data.error || 'Failed to save to collection');
+ }
+
+ // Show success message
+ successDiv.innerHTML = `
+ <i class="fas fa-check-circle"></i>
+ Saved to <strong>${escapeHtml(collectionName)}</strong>!
+ <br><small>${escapeHtml(String(data.documents_added || 0))} documents added.</small>
+ `;
+ successDiv.style.display = 'block';
+
+ // Re-enable buttons after a delay
+ setTimeout(() => {
+ loadCollections();
+ }, 2000);
+
+ } catch (error) {
+ SafeLogger.error('Error saving to collection:', error);
+ errorDiv.textContent = error.message;
+ errorDiv.style.display = 'block';
+
+ // Re-enable buttons and restore original HTML
+ buttons.forEach(btn => {
+ btn.disabled = false;
+ if (btn.dataset.collectionId === collectionId && originalBtnHtml) {
+ btn.innerHTML = originalBtnHtml;
+ }
+ });
+ }
+ }
+
+ // Initialize when DOM is ready
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initSaveToCollection);
+ } else {
+ initSaveToCollection();
+ }
+})();
diff --git a/src/local_deep_research/web/static/js/components/semantic_search.js b/src/local_deep_research/web/static/js/components/semantic_search.js
new file mode 100644
index 0000000000..60b295087e
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/semantic_search.js
@@ -0,0 +1,182 @@
+/**
+ * Semantic Search — Shared Module
+ *
+ * Reusable functions for semantic search across any page:
+ * - renderSnippet: markdown-to-HTML for search snippets
+ * - buildTieredResults: three-tier merge of text + semantic results
+ * - createSemanticResultCard: standalone card element for a semantic match
+ * - isSafeExternalUrl: URL scheme validation
+ *
+ * Exposed via window.SemanticSearch
+ */
+(function() {
+
+// bearer:disable javascript_lang_manual_html_sanitization
+const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
+
+/**
+ * Render a markdown snippet as sanitized inline HTML.
+ * Falls back to escapeHtml when marked/DOMPurify are not loaded.
+ */
+function renderSnippet(md) {
+ if (!md) return '';
+ if (window.marked && window.DOMPurify) {
+ const html = window.marked.parseInline(String(md));
+ return window.DOMPurify.sanitize(html, {
+ ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'a', 'code', 'br', 'p', 'ul', 'ol', 'li'],
+ ALLOWED_ATTR: ['href', 'title'],
+ ALLOW_DATA_ATTR: false,
+ });
+ }
+ return esc(md);
+}
+
+/**
+ * Three-tier merge of text-filtered and semantic search results.
+ *
+ * Tier 1: items matching both text + semantic (sorted by similarity DESC)
+ * Tier 2: text-only matches (original order, typically recency)
+ * Tier 3: semantic-only matches (sorted by similarity DESC)
+ *
+ * @param {Array} textResults - items from text filter (must have .id)
+ * @param {Array} semanticResults - results from semantic API (must have .research_id, .similarity)
+ * @returns {{ tier1: Array, tier2: Array, tier3: Array }}
+ */
+function buildTieredResults(textResults, semanticResults) {
+ // Group semantic results by research_id, keep best per research
+ const semanticMap = new Map();
+ for (const sr of semanticResults) {
+ if (!sr.research_id) continue;
+ const rid = String(sr.research_id);
+ const existing = semanticMap.get(rid);
+ if (!existing || sr.similarity > existing.similarity) {
+ semanticMap.set(rid, sr);
+ }
+ }
+
+ // Classify text results
+ const tier1 = [];
+ const tier2 = [];
+ const matchedSemanticIds = new Set();
+
+ for (const textItem of textResults) {
+ const rid = String(textItem.id);
+ const sr = semanticMap.get(rid);
+ if (sr) {
+ tier1.push({
+ historyItem: textItem,
+ semanticMatch: { similarity: sr.similarity, snippet: sr.snippet || '' }
+ });
+ matchedSemanticIds.add(rid);
+ } else {
+ tier2.push({ historyItem: textItem });
+ }
+ }
+
+ // Collect semantic-only results
+ const tier3 = [];
+ for (const [rid, sr] of semanticMap) {
+ if (!matchedSemanticIds.has(rid)) {
+ tier3.push({ semanticResult: sr });
+ }
+ }
+
+ // Sort within tiers
+ tier1.sort((a, b) => b.semanticMatch.similarity - a.semanticMatch.similarity);
+ tier3.sort((a, b) => b.semanticResult.similarity - a.semanticResult.similarity);
+
+ return { tier1, tier2, tier3 };
+}
+
+/**
+ * Create a self-contained semantic result card element.
+ *
+ * @param {Object} result - semantic search result with: similarity, snippet, title,
+ * research_id, research_title, research_created_at, type, url
+ * @returns {HTMLElement}
+ */
+function createSemanticResultCard(result) {
+ const card = document.createElement('div');
+ card.className = 'ldr-semantic-result';
+ card.dataset.id = result.research_id || '';
+
+ const displayTitle = result.research_title || result.title || 'Untitled';
+ const similarity = result.similarity != null ? String(result.similarity) : '';
+
+ let dateStr = '';
+ if (result.research_created_at) {
+ try {
+ dateStr = new Date(result.research_created_at).toLocaleDateString();
+ } catch (e) {
+ dateStr = '';
+ }
+ }
+
+ const typeIcon = result.type === 'report' ? 'file-alt' : 'link';
+ const typeLabel = result.type === 'report' ? 'Report' : 'Source';
+
+ const resultsUrl = typeof URLBuilder !== 'undefined' && result.research_id
+ ? URLBuilder.resultsPage(result.research_id)
+ : '#';
+
+ // bearer:disable javascript_lang_dangerous_insert_html
+ card.innerHTML = `
+ <div class="ldr-semantic-result-header">
+ <div>
+ <span class="badge badge-sm ldr-semantic-type-badge">
+ <i class="fas fa-${esc(typeIcon)}"></i> ${esc(typeLabel)}
+ </span>
+ ${similarity ? `<span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(similarity)}% match</span>` : ''}
+ </div>
+ ${dateStr ? `<small class="ldr-semantic-result-date">${esc(dateStr)}</small>` : ''}
+ </div>
+ <h4 class="ldr-semantic-result-title">
+ <a href="${esc(resultsUrl)}">${esc(displayTitle)}</a>
+ </h4>
+ ${result.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(result.snippet)}</div>` : ''}
+ ${result.url && isSafeExternalUrl(result.url) ? `
+ <p class="ldr-semantic-result-source">
+ <a href="${esc(result.url)}" target="_blank" rel="noopener noreferrer">
+ <i class="fas fa-external-link-alt"></i> View Source
+ </a>
+ </p>
+ ` : ''}
+ `;
+
+ // Click handler — navigate to results page
+ card.addEventListener('click', (e) => {
+ if (!e.target.closest('a') && result.research_id && typeof URLValidator !== 'undefined') {
+ URLValidator.safeAssign(window.location, 'href', resultsUrl);
+ }
+ });
+
+ return card;
+}
+
+/**
+ * Validate external URL for safe rendering.
+ */
+function isSafeExternalUrl(url) {
+ if (!url || typeof url !== 'string') return false;
+
+ if (typeof URLValidator !== 'undefined' && URLValidator.isSafeUrl) {
+ return URLValidator.isSafeUrl(url, { allowMailto: false });
+ }
+
+ const trimmedUrl = url.trim().toLowerCase();
+ const unsafeSchemes = ['javascript:', 'data:', 'vbscript:', 'about:', 'blob:', 'file:'];
+ for (const scheme of unsafeSchemes) {
+ if (trimmedUrl.startsWith(scheme)) return false;
+ }
+ return trimmedUrl.startsWith('http://') || trimmedUrl.startsWith('https://');
+}
+
+// Expose shared API
+window.SemanticSearch = {
+ renderSnippet,
+ buildTieredResults,
+ createSemanticResultCard,
+ isSafeExternalUrl,
+};
+
+})();
diff --git a/src/local_deep_research/web/static/js/config/constants.js b/src/local_deep_research/web/static/js/config/constants.js
new file mode 100644
index 0000000000..10f2b0c868
--- /dev/null
+++ b/src/local_deep_research/web/static/js/config/constants.js
@@ -0,0 +1,18 @@
+/**
+ * Shared constants for the Local Deep Research frontend.
+ * Loaded globally via base.html — available to all pages.
+ */
+
+if (typeof LDR_CONSTANTS !== 'undefined') {
+ if (typeof SafeLogger !== 'undefined') {
+ SafeLogger.warn('LDR_CONSTANTS already defined, skipping redeclaration');
+ }
+} else {
+ window.LDR_CONSTANTS = {
+ SEARCH_MODE: {
+ HYBRID: 'hybrid',
+ TEXT: 'text',
+ SEMANTIC: 'semantic',
+ },
+ };
+}
diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.js
index a7935bd490..e4f74d1261 100644
--- a/src/local_deep_research/web/static/js/config/urls.js
+++ b/src/local_deep_research/web/static/js/config/urls.js
@@ -111,6 +111,8 @@ if (typeof URLS !== 'undefined') {
COLLECTION_DOCUMENTS: '/library/api/collections/{id}/documents',
COLLECTION_UPLOAD: '/library/api/collections/{id}/upload',
COLLECTION_INDEX: '/library/api/collections/{id}/index',
+ COLLECTION_INDEX_START: '/library/api/collections/{id}/index/start',
+ COLLECTION_INDEX_STATUS: '/library/api/collections/{id}/index/status',
// RAG management
RAG_CONFIG: '/library/api/rag/config',
@@ -119,7 +121,13 @@ if (typeof URLS !== 'undefined') {
RAG_DOCUMENTS: '/library/api/rag/documents',
// Config
- SUPPORTED_FORMATS: '/library/api/config/supported-formats'
+ SUPPORTED_FORMATS: '/library/api/config/supported-formats',
+
+ // Semantic search
+ RESEARCH_HISTORY_COLLECTION: '/library/api/research-history/collection',
+ RESEARCH_HISTORY_CONVERT_ALL: '/library/api/research-history/convert-all',
+ COLLECTION_SEARCH: '/library/api/collections/{id}/search',
+ RESEARCH_ADD_TO_COLLECTION: '/library/api/research/{id}/add-to-collection'
}
};
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index bd959ba154..99b241785c 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -133,7 +133,8 @@
<!-- Safe Logger (must load first — theme.js, keyboard.js, help.js call SafeLogger at exec time) -->
<script defer src="/static/js/security/safe-logger.js"></script>
- <!-- URL Configuration -->
+ <!-- Constants and URL Configuration -->
+ <script defer src="/static/js/config/constants.js"></script>
<script defer src="/static/js/config/urls.js"></script>
<!-- Logo click handler -->
diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.html
index 4cafd38a11..f249089b73 100644
--- a/src/local_deep_research/web/templates/pages/history.html
+++ b/src/local_deep_research/web/templates/pages/history.html
@@ -4,9 +4,9 @@
{% block title %}Research History - Deep Research System{% endblock %}
-{% block styles %}
-{{ super() }}
+{% block extra_head %}
<link rel="stylesheet" href="/static/css/components/history-icons.css">
+<link rel="stylesheet" href="/static/css/components/semantic-search.css">
{% endblock %}
{% block content %}
@@ -14,10 +14,64 @@
<div class="ldr-page-header">
<h1>Research History</h1>
</div>
+
+ <!-- AI Search Indexing Panel -->
+ <div class="ldr-card" id="semantic-search-panel" style="margin-bottom: 1rem;">
+ <div class="ldr-card-header ldr-semantic-panel-header" id="semantic-panel-header" role="button" tabindex="0" aria-expanded="true" aria-controls="semantic-panel-content">
+ <h3><i class="fas fa-brain"></i> AI Search</h3>
+ <i class="fas fa-chevron-down" id="semantic-panel-toggle" aria-hidden="true"></i>
+ </div>
+ <div class="ldr-card-content" id="semantic-panel-content">
+ <p class="ldr-semantic-panel-description">
+ Index your completed research to enable <strong>Hybrid</strong> and <strong>AI Only</strong> search modes.
+ Hybrid (default) shows instant title matches, then appends AI content matches.
+ </p>
+ <!-- Indexing Status -->
+ <div id="indexing-status" class="ldr-indexing-status">
+ <div class="ldr-indexing-status-row">
+ <span>
+ <i class="fas fa-database"></i>
+ <span id="indexed-count">0</span> / <span id="total-count">0</span> documents indexed
+ </span>
+ <button id="index-all-btn" class="btn btn-sm btn-primary">
+ <i class="fas fa-sync"></i> Index All
+ </button>
+ </div>
+ <!-- Progress bar (hidden by default) -->
+ <div id="indexing-progress" style="display: none; margin-top: 0.75rem;">
+ <div class="ldr-progress-track">
+ <div id="indexing-progress-bar" class="ldr-progress-bar" style="width: 0%;"></div>
+ </div>
+ <small id="indexing-progress-text" style="color: var(--text-secondary);" aria-live="polite">Starting...</small>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- History List -->
<div class="ldr-card">
<div class="ldr-card-content">
<div class="ldr-search-controls" style="margin-bottom: 1rem;">
- <input type="text" id="history-search" placeholder="Search history..." class="ldr-search-input">
+ <div class="ldr-search-row">
+ <input type="text" id="history-search" placeholder="Search titles + content..." class="ldr-search-input" style="flex: 1;">
+ <div class="dropdown d-inline-block">
+ <button class="btn btn-sm ldr-btn-outline dropdown-toggle" type="button"
+ id="search-mode-btn" data-bs-toggle="dropdown" aria-expanded="false">
+ <i class="fas fa-brain"></i> Hybrid
+ </button>
+ <ul class="dropdown-menu" aria-labelledby="search-mode-btn" id="search-mode-menu">
+ <li><a class="dropdown-item active" href="#" data-mode="hybrid">
+ <i class="fas fa-brain"></i> Hybrid <small class="text-muted">— titles + content</small>
+ </a></li>
+ <li><a class="dropdown-item" href="#" data-mode="text">
+ <i class="fas fa-font"></i> Text Only <small class="text-muted">— titles only</small>
+ </a></li>
+ <li><a class="dropdown-item" href="#" data-mode="semantic">
+ <i class="fas fa-brain"></i> AI Only <small class="text-muted">— content search</small>
+ </a></li>
+ </ul>
+ </div>
+ </div>
<button id="clear-history-btn" class="btn btn-danger" style="display: none;">
<i class="fas fa-trash-alt"></i> Clear All
</button>
@@ -43,5 +97,7 @@
{% block page_scripts %}
<!-- formatting.js, api.js, urls.js already loaded by base.html -->
+<script defer src="/static/js/components/semantic_search.js"></script>
<script defer src="/static/js/components/history.js"></script>
+<script defer src="/static/js/components/history_search.js"></script>
{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index a63e73a6f4..7decade391 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -27,6 +27,7 @@
<li><a class="dropdown-item" href="#" id="export-ris-btn"><i class="fas fa-file-export"></i> RIS (Zotero)</a></li>
</ul>
</div>
+ <button class="btn ldr-btn-outline" id="save-to-collection-btn" title="Save this research to a collection for future reference"><i class="fas fa-folder-plus"></i> Save to Collection</button>
<button class="btn ldr-btn-outline" id="report-issue-btn" title="Report bugs, suggest features, or get help from the community"><i class="fas fa-hands-helping"></i> Help Improve</button>
<button class="btn ldr-btn-outline" id="back-to-history"><i class="fas fa-arrow-left"></i> Back to History</button>
</div>
@@ -118,6 +119,31 @@
</div>
</div>
</div>
+
+ <!-- Save to Collection Modal -->
+ <div class="modal fade" id="saveToCollectionModal" tabindex="-1" aria-labelledby="saveToCollectionModalLabel" aria-hidden="true" style="z-index: 10000;">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title" id="saveToCollectionModalLabel"><i class="fas fa-folder-plus"></i> Save to Collection</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+ </div>
+ <div class="modal-body">
+ <p class="text-muted mb-3">Save this research (report and sources) to a collection for semantic search.</p>
+ <div id="collection-list-loading" class="text-center py-3">
+ <i class="fas fa-spinner fa-spin"></i> Loading collections...
+ </div>
+ <div id="collection-list" style="display: none;">
+ <div class="list-group" id="collection-items">
+ <!-- Collection items will be populated here -->
+ </div>
+ </div>
+ <div id="collection-error" class="alert alert-danger" style="display: none;"></div>
+ <div id="collection-success" class="alert alert-success" style="display: none;"></div>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
{% endblock %}
@@ -137,4 +163,6 @@
<!-- Report Issue / Feedback component -->
<script defer src="/static/js/components/report_issue.js"></script>
+<!-- Save to Collection component -->
+<script defer src="/static/js/components/save_to_collection.js"></script>
{% endblock %}
diff --git a/tests/database/test_library_init.py b/tests/database/test_library_init.py
index c140ef8188..b256d86103 100644
--- a/tests/database/test_library_init.py
+++ b/tests/database/test_library_init.py
@@ -19,6 +19,7 @@ add_src_to_path()
from local_deep_research.database.library_init import ( # noqa: E402
seed_source_types,
ensure_default_library_collection,
+ ensure_research_history_collection,
initialize_library_for_user,
get_default_library_id,
get_source_type_id,
@@ -33,7 +34,7 @@ class TestSeedSourceTypes:
def test_creates_all_predefined_types_when_none_exist(
self, mock_uuid, mock_get_session
):
- """Should create research_download, user_upload, manual_entry types."""
+ """Should create all predefined source types."""
mock_session = MagicMock()
mock_get_session.return_value.__enter__.return_value = mock_session
# Simulate no existing types
@@ -42,8 +43,9 @@ class TestSeedSourceTypes:
seed_source_types("testuser", "testpass")
- # Should have queried for each type and added 3 new ones
- assert mock_session.add.call_count == 3
+ # Should have queried for each type and added 5 new ones
+ # (research_download, user_upload, manual_entry, research_report, research_source)
+ assert mock_session.add.call_count == 5
mock_session.commit.assert_called_once()
@patch("local_deep_research.database.library_init.get_user_db_session")
@@ -200,29 +202,84 @@ class TestEnsureDefaultLibraryCollection:
ensure_default_library_collection("testuser")
+class TestEnsureResearchHistoryCollection:
+ """Tests for ensure_research_history_collection function."""
+
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ @patch("local_deep_research.database.library_init.uuid.uuid4")
+ def test_creates_collection_when_none_exists(
+ self, mock_uuid, mock_get_session
+ ):
+ """Should create Research History collection when none exists."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+ mock_uuid.return_value = "new-history-uuid"
+
+ result = ensure_research_history_collection("testuser", "testpass")
+
+ assert result == "new-history-uuid"
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_called_once()
+
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_returns_existing_collection_id(self, mock_get_session):
+ """Should return ID of existing Research History collection."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_existing = MagicMock()
+ mock_existing.id = "existing-history-uuid"
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_existing
+
+ result = ensure_research_history_collection("testuser", "testpass")
+
+ assert result == "existing-history-uuid"
+ mock_session.add.assert_not_called()
+
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_reraises_exception(self, mock_get_session):
+ """Should re-raise exceptions from database operations."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_session.query.side_effect = RuntimeError("Database error")
+
+ with pytest.raises(RuntimeError, match="Database error"):
+ ensure_research_history_collection("testuser")
+
+
class TestInitializeLibraryForUser:
"""Tests for initialize_library_for_user function."""
+ @patch(
+ "local_deep_research.database.library_init.ensure_research_history_collection"
+ )
@patch(
"local_deep_research.database.library_init.ensure_default_library_collection"
)
@patch("local_deep_research.database.library_init.seed_source_types")
- def test_returns_success_result(self, mock_seed, mock_ensure):
+ def test_returns_success_result(self, mock_seed, mock_ensure, mock_history):
"""Should return dict with success=True on success."""
mock_ensure.return_value = "library-uuid-123"
+ mock_history.return_value = "history-uuid-456"
result = initialize_library_for_user("testuser", "testpass")
assert result["success"] is True
assert result["source_types_seeded"] is True
assert result["library_collection_id"] == "library-uuid-123"
+ assert result["research_history_collection_id"] == "history-uuid-456"
assert "error" not in result
+ @patch(
+ "local_deep_research.database.library_init.ensure_research_history_collection"
+ )
@patch(
"local_deep_research.database.library_init.ensure_default_library_collection"
)
@patch("local_deep_research.database.library_init.seed_source_types")
- def test_returns_error_on_seed_failure(self, mock_seed, mock_ensure):
+ def test_returns_error_on_seed_failure(
+ self, mock_seed, mock_ensure, mock_history
+ ):
"""Should include error message when seed_source_types fails."""
mock_seed.side_effect = RuntimeError("Seeding failed")
@@ -233,11 +290,16 @@ class TestInitializeLibraryForUser:
assert "error" in result
assert "Seeding failed" in result["error"]
+ @patch(
+ "local_deep_research.database.library_init.ensure_research_history_collection"
+ )
@patch(
"local_deep_research.database.library_init.ensure_default_library_collection"
)
@patch("local_deep_research.database.library_init.seed_source_types")
- def test_returns_error_on_ensure_failure(self, mock_seed, mock_ensure):
+ def test_returns_error_on_ensure_failure(
+ self, mock_seed, mock_ensure, mock_history
+ ):
"""Should include error message when ensure_default_library_collection fails."""
mock_ensure.side_effect = RuntimeError("Collection creation failed")
@@ -249,11 +311,16 @@ class TestInitializeLibraryForUser:
assert "error" in result
assert "Collection creation failed" in result["error"]
+ @patch(
+ "local_deep_research.database.library_init.ensure_research_history_collection"
+ )
@patch(
"local_deep_research.database.library_init.ensure_default_library_collection"
)
@patch("local_deep_research.database.library_init.seed_source_types")
- def test_calls_seed_and_ensure_in_order(self, mock_seed, mock_ensure):
+ def test_calls_seed_and_ensure_in_order(
+ self, mock_seed, mock_ensure, mock_history
+ ):
"""Should call both seed_source_types and ensure_default_library_collection."""
mock_ensure.return_value = "library-uuid"
call_order = []
diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.py
index 7d13f856be..ae44333abe 100644
--- a/tests/research_library/routes/test_rag_routes.py
+++ b/tests/research_library/routes/test_rag_routes.py
@@ -85,7 +85,7 @@ class TestGetRagService:
"local_search_chunk_size": "1000",
"local_search_chunk_overlap": "200",
"local_search_splitter_type": "recursive",
- "local_search_text_separators": '["\n\n", "\n", ". ", " ", ""]',
+ "local_search_text_separators": '["\\n\\n", "\\n", ". ", " ", ""]',
"local_search_distance_metric": "cosine",
"local_search_normalize_vectors": True,
"local_search_index_type": "flat",
@@ -99,7 +99,7 @@ class TestGetRagService:
)
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -107,7 +107,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -144,7 +144,7 @@ class TestGetRagService:
mock_query.first.return_value = mock_collection
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -152,7 +152,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.database.session_context.get_user_db_session"
+ "local_deep_research.research_library.services.rag_service_factory.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -160,7 +160,7 @@ class TestGetRagService:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -190,7 +190,7 @@ class TestGetRagService:
mock_query.first.return_value = mock_collection
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -198,7 +198,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.database.session_context.get_user_db_session"
+ "local_deep_research.research_library.services.rag_service_factory.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -206,7 +206,7 @@ class TestGetRagService:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -242,7 +242,7 @@ class TestGetRagService:
mock_query.first.return_value = mock_collection
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -250,7 +250,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.database.session_context.get_user_db_session"
+ "local_deep_research.research_library.services.rag_service_factory.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -258,7 +258,7 @@ class TestGetRagService:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -297,7 +297,7 @@ class TestGetRagService:
mock_query.first.return_value = mock_collection
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -305,7 +305,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.database.session_context.get_user_db_session"
+ "local_deep_research.research_library.services.rag_service_factory.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -313,7 +313,7 @@ class TestGetRagService:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -334,7 +334,7 @@ class TestGetRagService:
)
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -342,7 +342,7 @@ class TestGetRagService:
{"username": "testuser"},
):
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -353,8 +353,8 @@ class TestGetRagService:
call_kwargs = mock_rag.call_args[1]
assert isinstance(call_kwargs["text_separators"], list)
- def test_invalid_json_text_separators(self):
- """Test handling of invalid JSON text separators."""
+ def test_invalid_json_text_separators_falls_back(self):
+ """Invalid JSON text separators should log warning and use defaults."""
from local_deep_research.research_library.routes.rag_routes import (
get_rag_service,
)
@@ -372,26 +372,29 @@ class TestGetRagService:
"local_search_index_type": "flat",
}.get(key, default)
- with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
- return_value=mock_settings,
+ with (
+ patch(
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
+ return_value=mock_settings,
+ ),
+ patch(
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService",
+ ) as mock_rag,
):
with patch(
"local_deep_research.research_library.routes.rag_routes.session",
{"username": "testuser"},
):
- with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
- ) as mock_rag:
- mock_service = Mock()
- mock_rag.return_value = mock_service
-
- # Should not raise, should use default
- get_rag_service()
-
- call_kwargs = mock_rag.call_args[1]
- # Should have fallen back to default
- assert isinstance(call_kwargs["text_separators"], list)
+ get_rag_service()
+ # Should use default separators after warning
+ call_kwargs = mock_rag.call_args[1]
+ assert call_kwargs["text_separators"] == [
+ "\n\n",
+ "\n",
+ ". ",
+ " ",
+ "",
+ ]
class TestRagBlueprintImport:
@@ -433,7 +436,7 @@ class TestNormalizeVectorsHandling:
mock_settings.get_bool_setting.return_value = True
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -441,7 +444,7 @@ class TestNormalizeVectorsHandling:
{"username": "testuser"},
):
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -473,7 +476,7 @@ class TestNormalizeVectorsHandling:
mock_settings.get_bool_setting.return_value = False
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -481,7 +484,7 @@ class TestNormalizeVectorsHandling:
{"username": "testuser"},
):
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
@@ -2259,7 +2262,7 @@ class TestCollectionNormalizeVectors:
mock_query.first.return_value = mock_collection
with patch(
- "local_deep_research.research_library.routes.rag_routes.get_settings_manager",
+ "local_deep_research.research_library.services.rag_service_factory.get_settings_manager",
return_value=mock_settings,
):
with patch(
@@ -2267,7 +2270,7 @@ class TestCollectionNormalizeVectors:
{"username": "testuser"},
):
with patch(
- "local_deep_research.database.session_context.get_user_db_session"
+ "local_deep_research.research_library.services.rag_service_factory.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -2275,7 +2278,7 @@ class TestCollectionNormalizeVectors:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.research_library.routes.rag_routes.LibraryRAGService"
+ "local_deep_research.research_library.services.rag_service_factory.LibraryRAGService"
) as mock_rag:
mock_service = Mock()
mock_rag.return_value = mock_service
diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.py
index 025a3dfef1..1127f80637 100644
--- a/tests/research_library/routes/test_rag_routes_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_coverage.py
@@ -18,6 +18,7 @@ from local_deep_research.research_library.routes.rag_routes import rag_bp
# Module path shorthand for patching
_ROUTES = "local_deep_research.research_library.routes.rag_routes"
+_FACTORY = "local_deep_research.research_library.services.rag_service_factory"
# Source module paths for function-local imports
_DB_CTX = "local_deep_research.database.session_context"
@@ -2330,9 +2331,9 @@ class TestGetRagServiceFunction:
mock_sm = _make_settings_mock()
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service()
@@ -2364,12 +2365,12 @@ class TestGetRagServiceFunction:
yield mock_session
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
patch(
- f"{_DB_CTX}.get_user_db_session", side_effect=fake_db_session
+ f"{_FACTORY}.get_user_db_session", side_effect=fake_db_session
),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service(collection_id="coll-1")
@@ -2394,12 +2395,12 @@ class TestGetRagServiceFunction:
yield mock_session
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
patch(
- f"{_DB_CTX}.get_user_db_session", side_effect=fake_db_session
+ f"{_FACTORY}.get_user_db_session", side_effect=fake_db_session
),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service(collection_id="coll-1")
@@ -2416,9 +2417,9 @@ class TestGetRagServiceFunction:
)
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service()
@@ -2444,12 +2445,12 @@ class TestGetRagServiceFunction:
yield mock_session
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
patch(
- f"{_DB_CTX}.get_user_db_session", side_effect=fake_db_session
+ f"{_FACTORY}.get_user_db_session", side_effect=fake_db_session
),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service(collection_id="coll-1", use_defaults=True)
@@ -2482,12 +2483,12 @@ class TestGetRagServiceFunction:
yield mock_session
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
patch(
- f"{_DB_CTX}.get_user_db_session", side_effect=fake_db_session
+ f"{_FACTORY}.get_user_db_session", side_effect=fake_db_session
),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service(collection_id="coll-1")
@@ -2511,12 +2512,12 @@ class TestGetRagServiceFunction:
yield mock_session
with (
- patch(f"{_ROUTES}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
patch(f"{_ROUTES}.session", {"username": "testuser"}),
patch(
- f"{_DB_CTX}.get_user_db_session", side_effect=fake_db_session
+ f"{_FACTORY}.get_user_db_session", side_effect=fake_db_session
),
- patch(f"{_ROUTES}.LibraryRAGService") as mock_rag_cls,
+ patch(f"{_FACTORY}.LibraryRAGService") as mock_rag_cls,
):
mock_rag_cls.return_value = Mock()
get_rag_service(collection_id="nonexistent")
diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.py
index 35621008ad..dbee70d672 100644
--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py
@@ -40,6 +40,7 @@ from local_deep_research.research_library.routes.rag_routes import rag_bp
# ---------------------------------------------------------------------------
MODULE = "local_deep_research.research_library.routes.rag_routes"
+_FACTORY = "local_deep_research.research_library.services.rag_service_factory"
_DB_CTX = "local_deep_research.database.session_context"
_DB_PASS = "local_deep_research.database.session_passwords"
_DOC_LOADERS = "local_deep_research.document_loaders"
@@ -160,6 +161,11 @@ def _auth_client(
side_effect=fake_get_user_db_session,
),
patch(f"{MODULE}.get_settings_manager", return_value=mock_sm),
+ patch(f"{_FACTORY}.get_settings_manager", return_value=mock_sm),
+ patch(
+ f"{_FACTORY}.get_user_db_session",
+ side_effect=fake_get_user_db_session,
+ ),
patch(
"local_deep_research.utilities.db_utils.get_settings_manager",
return_value=mock_sm,
@@ -1220,7 +1226,7 @@ class TestGetRagServiceTextSeparatorsList:
mock_service.get_rag_stats.return_value = {}
rag_patch = patch(
- f"{MODULE}.LibraryRAGService", return_value=mock_service
+ f"{_FACTORY}.LibraryRAGService", return_value=mock_service
)
with _auth_client(
@@ -1434,7 +1440,9 @@ class TestGetRagServiceNoCollection:
app,
mock_db_session=db_session,
extra_patches=[
- patch(f"{MODULE}.LibraryRAGService", return_value=mock_service),
+ patch(
+ f"{_FACTORY}.LibraryRAGService", return_value=mock_service
+ ),
patch(
"local_deep_research.database.library_init.get_default_library_id",
return_value="default-lib",
diff --git a/tests/research_library/search/__init__.py b/tests/research_library/search/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/research_library/search/routes/__init__.py b/tests/research_library/search/routes/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/research_library/search/routes/test_search_routes.py b/tests/research_library/search/routes/test_search_routes.py
new file mode 100644
index 0000000000..b5dc15c84b
--- /dev/null
+++ b/tests/research_library/search/routes/test_search_routes.py
@@ -0,0 +1,436 @@
+"""
+Tests for collection search and research history routes.
+
+Uses the Flask test client with mocked authentication.
+"""
+
+import json
+from contextlib import contextmanager
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+TEST_COLLECTION_ID = "test-collection-id-123"
+
+
+def auth_client(app):
+ """Create a test client that bypasses the login_required checks."""
+ # Mock db_manager.connections to have an entry for testuser
+ mock_connections = {"testuser": MagicMock()}
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.connections = mock_connections
+ client = app.test_client()
+
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+
+ yield client
+
+
+class TestSearchCollectionRoute:
+ """Tests for POST /library/api/collections/<collection_id>/search"""
+
+ def test_search_empty_query_400(self, auth_client):
+ """Empty query should return 400."""
+ response = auth_client.post(
+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",
+ data=json.dumps({"query": ""}),
+ content_type="application/json",
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "required" in data["error"].lower()
+
+ def test_search_missing_query_400(self, auth_client):
+ """Missing query field should return 400."""
+ response = auth_client.post(
+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",
+ data=json.dumps({}),
+ content_type="application/json",
+ )
+ assert response.status_code == 400
+
+ def test_collection_not_found_404(self, auth_client):
+ """Non-existent collection should return 404 with success=False."""
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = None
+ yield session
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ):
+ response = auth_client.post(
+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",
+ data=json.dumps({"query": "test"}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == 404
+ data = response.get_json()
+ assert data["success"] is False
+ assert "not found" in data["error"].lower()
+
+ def test_enrich_default_fields_when_document_not_in_db(self, auth_client):
+ """When the enrichment query finds no matching document rows,
+ results should receive default sentinel fields (type='source',
+ research_id=None, research_title='', etc.)."""
+
+ mock_collection = MagicMock()
+ mock_collection.collection_type = "research_history"
+ mock_collection.name = "Test"
+
+ call_count = 0
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ nonlocal call_count
+ call_count += 1
+ db_session = MagicMock()
+ if call_count == 1:
+ # First call: collection lookup
+ db_session.query.return_value.filter_by.return_value.first.return_value = mock_collection
+ else:
+ # Second call (inside _enrich_with_research_metadata):
+ # complex join query → no rows found
+ db_session.query.return_value.join.return_value.outerjoin.return_value.filter.return_value.all.return_value = []
+ yield db_session
+
+ fake_results = [
+ {
+ "title": "Some Source",
+ "snippet": "snippet text",
+ "relevance_score": 0.85,
+ "metadata": {
+ "document_id": "doc-id-not-in-db",
+ "source": "https://example.com",
+ },
+ }
+ ]
+
+ mock_engine = MagicMock()
+ mock_engine.search.return_value = fake_results
+
+ with (
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_collection.CollectionSearchEngine",
+ return_value=mock_engine,
+ ),
+ ):
+ response = auth_client.post(
+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",
+ data=json.dumps({"query": "test query"}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+ assert len(data["results"]) == 1
+ result = data["results"][0]
+ assert result["type"] == "source"
+ assert result["research_id"] is None
+ assert result["research_title"] == ""
+ assert result["research_query"] is None
+ assert result["research_created_at"] is None
+
+ def test_exception_response_generic(self, auth_client):
+ """Exception responses should not leak internal details."""
+ # Mock the db session to raise when querying Collection
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=RuntimeError("secret DB connection string"),
+ ):
+ response = auth_client.post(
+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",
+ data=json.dumps({"query": "test query"}),
+ content_type="application/json",
+ )
+ assert response.status_code == 500
+ data = response.get_json()
+ assert data["success"] is False
+ # Must NOT contain the exception message
+ assert "secret" not in data["error"]
+ assert "DB connection" not in data["error"]
+ # Should contain generic message from handle_api_error
+ assert "internal error" in data["error"].lower()
+
+
+PATCH_INDEXER = "local_deep_research.research_library.search.services.research_history_indexer.ResearchHistoryIndexer"
+
+
+class TestGetResearchHistoryCollectionRoute:
+ """Tests for GET /library/api/research-history/collection"""
+
+ def test_happy_path_200(self, auth_client):
+ """Returns 200 with collection_id and status fields on success."""
+ fake_uuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+
+ mock_indexer = MagicMock()
+ mock_indexer.get_or_create_collection.return_value = fake_uuid
+
+ # Mock the DB session for the inline counting queries
+ mock_query = MagicMock()
+ # Chain: .query().filter().filter().filter().count() → total_research
+ # Chain: .query().join().filter().filter().distinct().count() → indexed_research
+ # Chain: .query().filter().count() → total_documents
+ # Chain: .query().filter().filter().count() → indexed_documents
+ mock_query.count.return_value = 5
+ mock_query.filter.return_value = mock_query
+ mock_query.filter_by.return_value = mock_query
+ mock_query.join.return_value = mock_query
+ mock_query.distinct.return_value = mock_query
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value = mock_query
+ yield session
+
+ with (
+ patch(PATCH_INDEXER, return_value=mock_indexer),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ),
+ ):
+ response = auth_client.get(
+ "/library/api/research-history/collection"
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+ assert data["collection_id"] == fake_uuid
+ # All counts come from the same mock returning 5
+ assert data["total_research"] == 5
+ assert data["indexed_research"] == 5
+ assert data["total_documents"] == 5
+ assert data["indexed_documents"] == 5
+
+ def test_auto_convert_called(self, auth_client):
+ """GET endpoint should auto-convert unconverted research entries."""
+ fake_uuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+ mock_indexer = MagicMock()
+ mock_indexer.get_or_create_collection.return_value = fake_uuid
+
+ mock_query = MagicMock()
+ mock_query.count.return_value = 0
+ mock_query.filter.return_value = mock_query
+ mock_query.filter_by.return_value = mock_query
+ mock_query.join.return_value = mock_query
+ mock_query.distinct.return_value = mock_query
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value = mock_query
+ yield session
+
+ with (
+ patch(PATCH_INDEXER, return_value=mock_indexer),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ),
+ ):
+ response = auth_client.get(
+ "/library/api/research-history/collection"
+ )
+
+ assert response.status_code == 200
+ mock_indexer.convert_all_research.assert_called_once_with(force=False)
+
+ def test_auto_convert_failure_does_not_prevent_200(self, auth_client):
+ """A crash in convert_all_research should not surface as a 500."""
+ fake_uuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+ mock_indexer = MagicMock()
+ mock_indexer.get_or_create_collection.return_value = fake_uuid
+ mock_indexer.convert_all_research.side_effect = RuntimeError(
+ "DB exploded"
+ )
+
+ mock_query = MagicMock()
+ mock_query.count.return_value = 0
+ mock_query.filter.return_value = mock_query
+ mock_query.filter_by.return_value = mock_query
+ mock_query.join.return_value = mock_query
+ mock_query.distinct.return_value = mock_query
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value = mock_query
+ yield session
+
+ with (
+ patch(PATCH_INDEXER, return_value=mock_indexer),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ),
+ ):
+ response = auth_client.get(
+ "/library/api/research-history/collection"
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+
+ def test_exception_returns_500(self, auth_client):
+ """Unhandled exception in indexer → 500 with generic error."""
+ mock_indexer = MagicMock()
+ mock_indexer.get_or_create_collection.side_effect = RuntimeError(
+ "secret internal error"
+ )
+
+ with patch(PATCH_INDEXER, return_value=mock_indexer):
+ response = auth_client.get(
+ "/library/api/research-history/collection"
+ )
+
+ assert response.status_code == 500
+ data = response.get_json()
+ assert data["success"] is False
+ assert "secret" not in data["error"]
+
+
+class TestConvertAllRoute:
+ """Tests for POST /library/api/research-history/convert-all"""
+
+ def test_happy_path_200(self, auth_client):
+ """Successful convert-all returns 200 with success=True and counts."""
+ mock_indexer = MagicMock()
+ mock_indexer.convert_all_research.return_value = {
+ "converted": 3,
+ "skipped": 1,
+ "failed": 0,
+ "collection_id": "col-abc",
+ }
+
+ with patch(PATCH_INDEXER, return_value=mock_indexer):
+ response = auth_client.post(
+ "/library/api/research-history/convert-all",
+ data=json.dumps({"force": False}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+ assert data["converted"] == 3
+ assert data["skipped"] == 1
+ assert data["failed"] == 0
+ assert data["collection_id"] == "col-abc"
+ mock_indexer.convert_all_research.assert_called_once_with(force=False)
+
+ def test_exception_returns_500(self, auth_client):
+ """Unhandled exception → 500 with generic error message."""
+ mock_indexer = MagicMock()
+ mock_indexer.convert_all_research.side_effect = RuntimeError(
+ "secret db error"
+ )
+
+ with patch(PATCH_INDEXER, return_value=mock_indexer):
+ response = auth_client.post(
+ "/library/api/research-history/convert-all",
+ data=json.dumps({}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == 500
+ data = response.get_json()
+ assert data["success"] is False
+ assert "secret" not in data["error"]
+ assert "internal error" in data["error"].lower()
+
+
+class TestAddToCollectionRoute:
+ """Tests for POST /library/api/research/<id>/add-to-collection"""
+
+ def test_missing_collection_id_400(self, auth_client):
+ """Missing collection_id should return 400."""
+ response = auth_client.post(
+ "/library/api/research/some-research-id/add-to-collection",
+ data=json.dumps({}),
+ content_type="application/json",
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "collection_id" in data["error"].lower()
+
+ def test_collection_not_found_404(self, auth_client):
+ """Non-existent collection should return 404."""
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value.filter.return_value.first.return_value = None
+ yield session
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ):
+ response = auth_client.post(
+ "/library/api/research/some-id/add-to-collection",
+ data=json.dumps({"collection_id": "nonexistent-id"}),
+ content_type="application/json",
+ )
+ assert response.status_code == 404
+ data = response.get_json()
+ assert data["success"] is False
+ assert "not found" in data["error"].lower()
+
+ def test_success_returns_200(self, auth_client):
+ """Successful add-to-collection returns 200 with result fields."""
+ mock_collection = MagicMock()
+ mock_collection.name = "My Collection"
+
+ @contextmanager
+ def mock_session(*_args, **_kwargs):
+ session = MagicMock()
+ session.query.return_value.filter.return_value.first.return_value = mock_collection
+ yield session
+
+ mock_indexer = MagicMock()
+ mock_indexer.index_research.return_value = {
+ "status": "success",
+ "documents_added": 3,
+ "sources_indexed": 2,
+ }
+
+ with (
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_session,
+ ),
+ patch(PATCH_INDEXER, return_value=mock_indexer),
+ ):
+ response = auth_client.post(
+ "/library/api/research/some-id/add-to-collection",
+ data=json.dumps({"collection_id": "coll-123"}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+ assert data["collection_name"] == "My Collection"
+ assert data["documents_added"] == 3
diff --git a/tests/research_library/search/services/__init__.py b/tests/research_library/search/services/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/research_library/search/services/test_research_history_indexer.py b/tests/research_library/search/services/test_research_history_indexer.py
new file mode 100644
index 0000000000..b8096e9081
--- /dev/null
+++ b/tests/research_library/search/services/test_research_history_indexer.py
@@ -0,0 +1,457 @@
+"""
+Tests for ResearchHistoryIndexer service.
+"""
+
+import uuid
+from contextlib import contextmanager
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentCollection,
+ SourceType,
+)
+from local_deep_research.database.models.research import (
+ ResearchHistory,
+ ResearchResource,
+)
+from local_deep_research.research_library.search.services.research_history_indexer import (
+ ResearchHistoryIndexer,
+)
+
+# Module path for patching imports within the indexer
+INDEXER_MODULE = "local_deep_research.research_library.search.services.research_history_indexer"
+
+
+def research_source_types(library_session):
+ """Create source types needed for research history indexing."""
+ report_type = SourceType(
+ id=str(uuid.uuid4()),
+ name="research_report",
+ display_name="Research Report",
+ description="Research report documents",
+ icon="fas fa-file-alt",
+ )
+ source_type = SourceType(
+ id=str(uuid.uuid4()),
+ name="research_source",
+ display_name="Research Source",
+ description="Research source documents",
+ icon="fas fa-link",
+ )
+ library_session.add_all([report_type, source_type])
+ library_session.commit()
+ return report_type, source_type
+
+
+def research_collection(library_session):
+ """Create a Research History collection."""
+ collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Research History",
+ description="Auto-indexed research history",
+ is_default=False,
+ collection_type="research_history",
+ )
+ library_session.add(collection)
+ library_session.commit()
+ return collection
+
+
+def sample_research(library_session):
+ """Create a sample completed research entry."""
+ research = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="What is quantum computing?",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-01-15T10:00:00",
+ report_content="# Quantum Computing\n\nQuantum computing uses qubits...",
+ title="Quantum Computing Overview",
+ )
+ library_session.add(research)
+ library_session.commit()
+ return research
+
+
+def sample_resource(library_session, sample_research):
+ """Create a sample research resource with content."""
+ resource = ResearchResource(
+ research_id=sample_research.id,
+ url="https://example.com/quantum",
+ title="Quantum Computing Primer",
+ source_type="web_search",
+ content_preview="A" * 200, # Must exceed MIN_SOURCE_CONTENT_LENGTH
+ created_at="2025-01-15T10:00:00",
+ )
+ library_session.add(resource)
+ library_session.commit()
+ return resource
+
+
+def mock_session_ctx(library_session):
+ """Mock get_user_db_session at the indexer's import location."""
+
+ @contextmanager
+ def _mock_session(*args, **kwargs):
+ yield library_session
+
+ with patch(f"{INDEXER_MODULE}.get_user_db_session", _mock_session):
+ yield library_session
+
+
+def indexer(mock_session_ctx):
+ """Create an indexer with mocked DB session."""
+ return ResearchHistoryIndexer("testuser", db_password=None)
+
+
+class TestGetOrCreateCollection:
+ def test_creates_collection(self, indexer):
+ """get_or_create_collection should return a valid collection ID."""
+ with patch(
+ f"{INDEXER_MODULE}.ensure_research_history_collection",
+ return_value=str(uuid.uuid4()),
+ ) as mock_ensure:
+ collection_id = indexer.get_or_create_collection()
+ assert collection_id is not None
+ mock_ensure.assert_called_once_with("testuser", None)
+
+
+class TestIndexResearch:
+ def test_index_research_not_found(self, indexer):
+ """Should return error for non-existent research ID."""
+ with patch.object(
+ indexer, "get_or_create_collection", return_value=str(uuid.uuid4())
+ ):
+ result = indexer.index_research("nonexistent-id")
+ assert result["status"] == "error"
+ assert "not found" in result["error"].lower()
+
+ def test_index_research_creates_documents(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ sample_resource,
+ research_source_types,
+ research_collection,
+ ):
+ """Should create a Document entry for the research report."""
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result = indexer.index_research(sample_research.id)
+
+ assert result["status"] == "success"
+ assert result["documents_added"] == 1 # report only, no sources
+
+ # Verify document was created with correct research_id
+ docs = (
+ mock_session_ctx.query(Document)
+ .filter(Document.research_id == sample_research.id)
+ .all()
+ )
+ assert len(docs) == 1
+
+ # Verify report document has correct source type
+ report_doc = next(
+ (
+ d
+ for d in docs
+ if d.source_type_id == research_source_types[0].id
+ ),
+ None,
+ )
+ assert report_doc is not None
+
+ def test_index_research_retries_unindexed_documents(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ research_source_types,
+ research_collection,
+ ):
+ """Second call should retry when DocumentCollection.indexed is False."""
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ # First call: create documents
+ result1 = indexer.index_research(sample_research.id)
+ assert result1["status"] == "success"
+
+ # Verify DocumentCollection rows exist but are NOT marked indexed
+ doc_collections = (
+ mock_session_ctx.query(DocumentCollection)
+ .filter(
+ DocumentCollection.collection_id == research_collection.id
+ )
+ .all()
+ )
+ assert len(doc_collections) > 0
+ for dc in doc_collections:
+ assert dc.indexed is False
+
+ # Second call: documents exist but indexed=False, so retry needed
+ result2 = indexer.index_research(sample_research.id)
+ assert result2["status"] == "success", (
+ "Should retry for unindexed docs, not return 'skipped'"
+ )
+
+ def test_index_research_idempotent(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ research_source_types,
+ research_collection,
+ ):
+ """Calling index_research twice should not duplicate documents."""
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result1 = indexer.index_research(sample_research.id)
+ assert result1["status"] == "success"
+
+ result2 = indexer.index_research(sample_research.id)
+ assert result2["status"] == "success"
+
+ # Should still have only 1 report document
+ report_docs = (
+ mock_session_ctx.query(Document)
+ .filter(
+ Document.research_id == sample_research.id,
+ Document.source_type_id == research_source_types[0].id,
+ )
+ .all()
+ )
+ assert len(report_docs) == 1
+
+
+class TestHashCollisionReuse:
+ def test_identical_content_reuses_document(
+ self,
+ indexer,
+ mock_session_ctx,
+ research_source_types,
+ research_collection,
+ ):
+ """Two research entries with identical report_content should share one Document."""
+ shared_content = (
+ "# Shared Report\n\nIdentical content for both entries."
+ )
+
+ research1 = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="First query",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-01-15T10:00:00",
+ report_content=shared_content,
+ title="Research One",
+ )
+ research2 = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="Second query",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-01-16T10:00:00",
+ report_content=shared_content,
+ title="Research Two",
+ )
+ mock_session_ctx.add_all([research1, research2])
+ mock_session_ctx.commit()
+
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result1 = indexer.index_research(research1.id)
+ assert result1["status"] == "success"
+
+ result2 = indexer.index_research(research2.id)
+ assert result2["status"] == "success"
+
+ # Only 1 Document should exist (same content hash)
+ docs = mock_session_ctx.query(Document).all()
+ assert len(docs) == 1
+
+
+class TestConvertAllResearch:
+ def test_converts_unconverted_research(
+ self,
+ indexer,
+ mock_session_ctx,
+ research_source_types,
+ research_collection,
+ ):
+ """convert_all_research should create Documents for all completed entries."""
+ r1 = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="Convert query one",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-03-01T10:00:00",
+ report_content="# Convert Report One\n\nContent for r1.",
+ title="Convert One",
+ )
+ r2 = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="Convert query two",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-03-02T10:00:00",
+ report_content="# Convert Report Two\n\nContent for r2.",
+ title="Convert Two",
+ )
+ mock_session_ctx.add_all([r1, r2])
+ mock_session_ctx.commit()
+
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result = indexer.convert_all_research(force=False)
+
+ assert result["converted"] == 2
+ assert result["skipped"] == 0
+ assert result["failed"] == 0
+ assert result["collection_id"] == research_collection.id
+
+ # Verify Documents were created
+ docs = mock_session_ctx.query(Document).all()
+ assert len(docs) == 2
+
+ def test_skips_already_converted_when_force_false(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ research_source_types,
+ research_collection,
+ ):
+ """When force=False, entries that already have a report Document are excluded."""
+ # First pass — convert sample_research
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result1 = indexer.convert_all_research(force=False)
+
+ assert result1["converted"] == 1
+
+ # Add a second research entry
+ r2 = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="New query",
+ mode="detailed_report",
+ status="completed",
+ created_at="2025-04-01T10:00:00",
+ report_content="# New report content that is unique.",
+ title="New Research",
+ )
+ mock_session_ctx.add(r2)
+ mock_session_ctx.commit()
+
+ # Second pass — only the new entry should be converted
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result2 = indexer.convert_all_research(force=False)
+
+ assert result2["converted"] == 1 # only r2
+ assert result2["failed"] == 0
+
+ # Total Documents: 1 (sample_research report) + 1 (r2 report) = 2
+ all_docs = mock_session_ctx.query(Document).all()
+ assert len(all_docs) == 2
+
+ def test_force_true_reconverts_all(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ research_source_types,
+ research_collection,
+ ):
+ """When force=True, all entries are processed even if already converted."""
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result1 = indexer.convert_all_research(force=False)
+ assert result1["converted"] == 1
+
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result2 = indexer.convert_all_research(force=True)
+
+ # The entry is re-processed (document reuse via hash — no duplicate created)
+ assert result2["converted"] == 1
+ assert result2["failed"] == 0
+
+ def test_returns_early_when_source_type_missing(
+ self,
+ indexer,
+ mock_session_ctx,
+ research_collection,
+ ):
+ """If research_report SourceType doesn't exist, return early with zeros."""
+ # No source types seeded in this test
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result = indexer.convert_all_research(force=False)
+
+ assert result["converted"] == 0
+ assert result["skipped"] == 0
+ assert result["failed"] == 0
+ assert result["collection_id"] == research_collection.id
+
+ def test_converts_report_only_no_sources(
+ self,
+ indexer,
+ mock_session_ctx,
+ sample_research,
+ sample_resource,
+ research_source_types,
+ research_collection,
+ ):
+ """Only research reports are converted, not individual sources."""
+ with patch.object(
+ indexer,
+ "get_or_create_collection",
+ return_value=research_collection.id,
+ ):
+ result = indexer.convert_all_research(force=False)
+
+ assert result["converted"] == 1
+ # Only 1 report document, no source documents
+ all_docs = mock_session_ctx.query(Document).all()
+ assert len(all_docs) == 1