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.

refactor: address PR review feedback for Research Library

LearningCircuit8b130206b16b
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index cb2cfe777c..873826fd72 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -55,6 +55,7 @@ from .library import (
LibraryCollectionDocument,
LibraryDownloadQueue,
LibraryStatistics,
+ LibraryTextDocument,
)
from .download_tracker import (
DownloadTracker,
@@ -134,6 +135,7 @@ __all__ = [
"LibraryCollectionDocument",
"LibraryDownloadQueue",
"LibraryStatistics",
+ "LibraryTextDocument",
# Download Tracker Models
"DownloadTracker",
"DownloadDuplicates",
diff --git a/src/local_deep_research/database/models/download_tracker.py b/src/local_deep_research/database/models/download_tracker.py
index cbd8774278..91842295fc 100644
--- a/src/local_deep_research/database/models/download_tracker.py
+++ b/src/local_deep_research/database/models/download_tracker.py
@@ -46,9 +46,7 @@ class DownloadTracker(Base):
file_path = Column(
Text, nullable=True
) # Relative path from library root (e.g., "2024/12/arxiv_2401_12345.pdf")
- file_absolute_path = Column(
- Text, nullable=True
- ) # Full absolute path for quick access
+ # NOTE: Absolute path removed - will be computed at runtime from library root + relative path
file_name = Column(
String(255), nullable=True, index=True
) # Just the filename for searching
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index 3929469eb2..3f19e5341c 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -7,6 +7,7 @@ from sqlalchemy import (
JSON,
Boolean,
Column,
+ Date,
ForeignKey,
Index,
Integer,
@@ -62,7 +63,7 @@ class LibraryDocument(Base):
# Metadata
title = Column(Text) # Document title
authors = Column(JSON) # List of authors if available
- published_date = Column(String(50)) # Publication date if known
+ published_date = Column(Date, nullable=True) # Publication date if known
# Academic identifiers
doi = Column(String(255), nullable=True, index=True)
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index 3d75cc9b42..ac1cf8d21c 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -7,6 +7,12 @@ from typing import Optional, Dict, Any, NamedTuple
from enum import Enum
import requests
from loguru import logger
+from tenacity import (
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
class ContentType(Enum):
@@ -150,7 +156,7 @@ class BaseDownloader(ABC):
self, url: str, headers: Optional[Dict[str, str]] = None
) -> Optional[bytes]:
"""
- Helper method to download PDF with error handling.
+ Helper method to download PDF with error handling and retry logic.
Args:
url: The URL to download
@@ -159,7 +165,19 @@ class BaseDownloader(ABC):
Returns:
PDF content as bytes, or None if download failed
"""
- try:
+
+ @retry(
+ stop=stop_after_attempt(3),
+ wait=wait_exponential(multiplier=1, min=2, max=10),
+ retry=retry_if_exception_type(
+ (
+ requests.exceptions.Timeout,
+ requests.exceptions.ConnectionError,
+ )
+ ),
+ reraise=True,
+ )
+ def _download_with_retry():
if headers:
request_headers = self.session.headers.copy()
request_headers.update(headers)
@@ -172,6 +190,13 @@ class BaseDownloader(ABC):
timeout=self.timeout,
allow_redirects=True,
)
+ return response
+
+ try:
+ logger.debug(
+ f"Downloading PDF from {url} with retry logic (max 3 attempts)"
+ )
+ response = _download_with_retry()
if response.status_code == 200:
if self._is_pdf_content(response):
@@ -187,7 +212,11 @@ class BaseDownloader(ABC):
)
except requests.exceptions.Timeout:
- logger.exception(f"Timeout downloading from {url}")
+ logger.exception(f"Timeout downloading from {url} after 3 retries")
+ except requests.exceptions.ConnectionError:
+ logger.exception(
+ f"Connection error downloading from {url} after 3 retries"
+ )
except requests.exceptions.RequestException:
logger.exception(f"Error downloading from {url}")
except Exception:
@@ -197,7 +226,8 @@ class BaseDownloader(ABC):
def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:
"""
- Extract text from PDF content.
+ Extract text from PDF content using Langchain's document loader.
+ This ensures consistency with local search functionality.
Args:
pdf_content: PDF file content as bytes
@@ -207,31 +237,59 @@ class BaseDownloader(ABC):
"""
try:
import io
+ import tempfile
+ from pathlib import Path
try:
- # Try pypdf (new package name)
- from pypdf import PdfReader
+ # Use Langchain's UnstructuredFileLoader for consistency with local search
+ from langchain_community.document_loaders import (
+ UnstructuredFileLoader,
+ )
+
+ # Create a temporary file to load from
+ with tempfile.NamedTemporaryFile(
+ suffix=".pdf", delete=False
+ ) as tmp_file:
+ tmp_file.write(pdf_content)
+ tmp_path = tmp_file.name
+
+ try:
+ # Load and extract text using UnstructuredFileLoader
+ loader = UnstructuredFileLoader(tmp_path)
+ documents = loader.load()
+
+ # Combine all content from the documents
+ full_text = "\n\n".join(
+ [doc.page_content for doc in documents]
+ )
+ return full_text if full_text.strip() else None
+
+ finally:
+ # Clean up temporary file
+ Path(tmp_path).unlink(missing_ok=True)
+
except ImportError:
- # Fallback to PyPDF2 (old package name)
- from PyPDF2 import PdfReader
+ # Fallback to pypdf if Langchain is not available
+ logger.warning(
+ "langchain_community not available, falling back to pypdf"
+ )
+ try:
+ from pypdf import PdfReader
+ except ImportError:
+ from PyPDF2 import PdfReader
- pdf_file = io.BytesIO(pdf_content)
- pdf_reader = PdfReader(pdf_file)
+ pdf_file = io.BytesIO(pdf_content)
+ pdf_reader = PdfReader(pdf_file)
- text_content = []
- for page in pdf_reader.pages:
- text = page.extract_text()
- if text:
- text_content.append(text)
+ text_content = []
+ for page in pdf_reader.pages:
+ text = page.extract_text()
+ if text:
+ text_content.append(text)
- full_text = "\n".join(text_content)
- return full_text if full_text.strip() else None
+ full_text = "\n".join(text_content)
+ return full_text if full_text.strip() else None
- except ImportError:
- logger.warning(
- "pypdf/PyPDF2 not installed, cannot extract text from PDF"
- )
- return None
except Exception:
logger.exception("Failed to extract text from PDF")
return None
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 7917773e75..b88fba0ee5 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -28,6 +28,7 @@ from ...database.models.research import ResearchResource
from ...database.models.library import LibraryDocument, LibraryDownloadQueue
from ..services.download_service import DownloadService
from ..services.library_service import LibraryService
+from ..utils import open_file_location
from ...security.path_validator import PathValidator
from ...utilities.db_utils import get_settings_manager
@@ -346,20 +347,9 @@ def open_folder():
{"success": False, "error": "Invalid or non-existent path"}
)
- folder = str(validated_path.parent)
-
- import sys
- import subprocess
-
- if sys.platform == "win32":
- import os
-
- os.startfile(folder)
- elif sys.platform == "darwin":
- subprocess.run(["open", folder])
- else:
- subprocess.run(["xdg-open", folder])
- return jsonify({"success": True})
+ # Use centralized file location opener
+ success = open_file_location(str(validated_path))
+ return jsonify({"success": success})
except ValueError as e:
logger.warning(f"Path validation failed: {e}")
return jsonify({"success": False, "error": "Invalid path"})
@@ -377,8 +367,17 @@ def download_single_resource(resource_id):
username = session.get("username")
service = DownloadService(username)
- success = service.download_resource(resource_id)
- return jsonify({"success": success})
+ success, error = service.download_resource(resource_id)
+ if success:
+ return jsonify({"success": True})
+ else:
+ logger.warning(f"Download failed for resource {resource_id}: {error}")
+ return jsonify(
+ {
+ "success": False,
+ "error": "Download failed. Please try again or contact support.",
+ }
+ ), 500
@library_bp.route("/api/download-text/<int:resource_id>", methods=["POST"])
@@ -801,3 +800,191 @@ def queue_all_undownloaded():
"skipped": skipped_count,
}
)
+
+
+@library_bp.route("/api/get-research-sources/<research_id>", methods=["GET"])
+@login_required
+def get_research_sources(research_id):
+ """Get all sources for a research with snippets."""
+ username = session.get("username")
+
+ sources = []
+ with get_user_db_session(username) as db_session:
+ # Get all resources for this research
+ resources = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id)
+ .order_by(ResearchResource.created_at)
+ .all()
+ )
+
+ for idx, resource in enumerate(resources, 1):
+ # Check if document exists
+ document = (
+ db_session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
+
+ # Get domain from URL
+ domain = ""
+ if resource.url:
+ try:
+ from urllib.parse import urlparse
+
+ domain = urlparse(resource.url).hostname or ""
+ except:
+ pass
+
+ source_data = {
+ "number": idx,
+ "resource_id": resource.id,
+ "url": resource.url,
+ "title": resource.title or f"Source {idx}",
+ "snippet": resource.content_preview or "",
+ "domain": domain,
+ "relevance_score": getattr(resource, "relevance_score", None),
+ "downloaded": False,
+ "document_id": None,
+ "file_type": None,
+ }
+
+ if document and document.download_status == "completed":
+ source_data.update(
+ {
+ "downloaded": True,
+ "document_id": document.id,
+ "file_type": document.file_type,
+ "download_date": document.created_at.isoformat()
+ if document.created_at
+ else None,
+ }
+ )
+
+ sources.append(source_data)
+
+ return jsonify({"success": True, "sources": sources, "total": len(sources)})
+
+
+@library_bp.route("/api/check-downloads", methods=["POST"])
+@login_required
+def check_downloads():
+ """Check download status for a list of URLs."""
+ username = session.get("username")
+ data = request.json
+ research_id = data.get("research_id")
+ urls = data.get("urls", [])
+
+ if not research_id or not urls:
+ return jsonify({"error": "Missing research_id or urls"}), 400
+
+ download_status = {}
+
+ with get_user_db_session(username) as db_session:
+ # Get all resources for this research
+ resources = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id)
+ .filter(ResearchResource.url.in_(urls))
+ .all()
+ )
+
+ for resource in resources:
+ # Check if document exists
+ document = (
+ db_session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
+
+ if document and document.download_status == "completed":
+ download_status[resource.url] = {
+ "downloaded": True,
+ "document_id": document.id,
+ "file_path": document.file_path,
+ "file_type": document.file_type,
+ "title": document.title or resource.title,
+ }
+ else:
+ download_status[resource.url] = {
+ "downloaded": False,
+ "resource_id": resource.id,
+ }
+
+ return jsonify({"download_status": download_status})
+
+
+@library_bp.route("/api/download-source", methods=["POST"])
+@login_required
+def download_source():
+ """Download a single source from a research."""
+ username = session.get("username")
+ data = request.json
+ research_id = data.get("research_id")
+ url = data.get("url")
+
+ if not research_id or not url:
+ return jsonify({"error": "Missing research_id or url"}), 400
+
+ # Check if URL is downloadable
+ if not is_downloadable_domain(url):
+ return jsonify({"error": "URL is not from a downloadable domain"}), 400
+
+ with get_user_db_session(username) as db_session:
+ # Find the resource
+ resource = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id, url=url)
+ .first()
+ )
+
+ if not resource:
+ return jsonify({"error": "Resource not found"}), 404
+
+ # Check if already downloaded
+ existing = (
+ db_session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
+
+ if existing and existing.download_status == "completed":
+ return jsonify(
+ {
+ "success": True,
+ "message": "Already downloaded",
+ "document_id": existing.id,
+ }
+ )
+
+ # Add to download queue
+ queue_entry = (
+ db_session.query(LibraryDownloadQueue)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
+
+ if not queue_entry:
+ queue_entry = LibraryDownloadQueue(
+ resource_id=resource.id,
+ research_id=resource.research_id,
+ priority=1, # Higher priority for manual downloads
+ status="pending",
+ )
+ db_session.add(queue_entry)
+ else:
+ queue_entry.status = "pending"
+ queue_entry.priority = 1
+
+ db_session.commit()
+
+ # Start download immediately
+ service = DownloadService(username)
+ success, message = service.download_pdf(resource.id)
+
+ if success:
+ return jsonify({"success": True, "message": "Download completed"})
+ else:
+ return jsonify(
+ {"success": False, "message": message or "Download failed"}
+ )
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 9930b43f9e..b04f879ed5 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -35,6 +35,10 @@ from ...database.models.research import ResearchResource
from ...database.session_context import get_user_db_session
from ...utilities.db_utils import get_settings_manager
from ...security.path_validator import PathValidator
+from ..utils import (
+ get_url_hash,
+ get_absolute_path_from_settings,
+)
# Import our modular downloaders
from ..downloaders import (
@@ -106,7 +110,7 @@ class DownloadService:
def _get_url_hash(self, url: str) -> str:
"""Generate SHA256 hash of normalized URL."""
normalized = self._normalize_url(url)
- return hashlib.sha256(normalized.encode()).hexdigest()
+ return get_url_hash(normalized)
def is_already_downloaded(self, url: str) -> Tuple[bool, Optional[str]]:
"""
@@ -124,10 +128,13 @@ class DownloadService:
.first()
)
- if tracker and tracker.file_absolute_path:
- # Verify file still exists
- if Path(tracker.file_absolute_path).exists():
- return True, tracker.file_absolute_path
+ if tracker and tracker.file_path:
+ # Compute absolute path and verify file still exists
+ absolute_path = get_absolute_path_from_settings(
+ tracker.file_path
+ )
+ if absolute_path.exists():
+ return True, str(absolute_path)
else:
# File was deleted, mark as not downloaded
tracker.is_downloaded = False
@@ -411,11 +418,16 @@ class DownloadService:
file_path = self._save_pdf(resource, pdf_content)
# Update tracker
+ import hashlib
+
tracker.file_hash = hashlib.sha256(pdf_content).hexdigest()
tracker.file_path = str(
Path(file_path).relative_to(self.library_root)
)
- tracker.file_absolute_path = file_path
+ # Store only relative path
+ tracker.file_path = str(
+ Path(file_path).relative_to(self.library_root)
+ )
tracker.file_name = Path(file_path).name
tracker.file_size = len(pdf_content)
tracker.is_downloaded = True
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index ff7d75e8de..a5a9ff8619 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -8,8 +8,6 @@ Handles querying and managing the downloaded document library:
- Handle file operations
"""
-import subprocess
-import sys
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import urlparse
@@ -22,6 +20,11 @@ from ...database.models.library import LibraryDocument, LibraryTextDocument
from ...database.models.research import ResearchHistory, ResearchResource
from ...database.models.metrics import ResearchRating
from ...database.session_context import get_user_db_session
+from ..utils import (
+ get_url_hash,
+ open_file_location,
+ get_absolute_path_from_settings,
+)
class LibraryService:
@@ -257,7 +260,11 @@ class LibraryService:
"pmid": doc.pmid,
# File info
"file_path": doc.file_path,
- "file_absolute_path": tracker.file_absolute_path
+ "file_absolute_path": str(
+ get_absolute_path_from_settings(tracker.file_path)
+ )
+ if tracker.file_path
+ else None
if tracker
else None,
"file_name": tracker.file_name
@@ -477,14 +484,14 @@ class LibraryService:
)
# Delete physical file
- if tracker and tracker.file_absolute_path:
+ if tracker and tracker.file_path:
try:
- file_path = Path(tracker.file_absolute_path)
+ file_path = get_absolute_path_from_settings(
+ tracker.file_path
+ )
if file_path.exists():
file_path.unlink()
- logger.info(
- f"Deleted file: {tracker.file_absolute_path}"
- )
+ logger.info(f"Deleted file: {file_path}")
except Exception:
logger.exception("Failed to delete file")
@@ -492,7 +499,7 @@ class LibraryService:
if tracker:
tracker.is_downloaded = False
tracker.file_path = None
- tracker.file_absolute_path = None
+ tracker.file_path = None
# Delete database entry
session.delete(doc)
@@ -513,20 +520,12 @@ class LibraryService:
.first()
)
- if tracker and tracker.file_absolute_path:
- folder = str(Path(tracker.file_absolute_path).parent)
-
- # Platform-specific folder opening
- if sys.platform == "win32":
- import os
-
- os.startfile(folder)
- elif sys.platform == "darwin": # macOS
- subprocess.run(["open", folder])
- else: # Linux
- subprocess.run(["xdg-open", folder])
-
- return True
+ if tracker and tracker.file_path:
+ absolute_path = get_absolute_path_from_settings(
+ tracker.file_path
+ )
+ # Use centralized file location opener with absolute path
+ return open_file_location(str(absolute_path))
return False
@@ -577,7 +576,6 @@ class LibraryService:
def _get_url_hash(self, url: str) -> str:
"""Generate hash for URL."""
- import hashlib
import re
# Normalize URL
@@ -585,7 +583,7 @@ class LibraryService:
url = re.sub(r"^www\.", "", url)
url = url.rstrip("/")
- return hashlib.sha256(url.lower().encode()).hexdigest()
+ return get_url_hash(url)
def _get_storage_path(self) -> str:
"""Get library storage path from settings."""
@@ -645,9 +643,11 @@ class LibraryService:
.first()
)
- if tracker and tracker.file_absolute_path:
+ if tracker and tracker.file_path:
# Check if file exists
- file_path = Path(tracker.file_absolute_path)
+ file_path = get_absolute_path_from_settings(
+ tracker.file_path
+ )
if file_path.exists():
stats["files_found"] += 1
else:
@@ -657,7 +657,7 @@ class LibraryService:
{
"id": doc.id,
"title": doc.title,
- "path": tracker.file_absolute_path,
+ "path": str(file_path),
"url": doc.original_url,
"type": "pdf",
}
@@ -665,7 +665,7 @@ class LibraryService:
# Reset tracker
tracker.is_downloaded = False
- tracker.file_absolute_path = None
+ tracker.file_path = None
tracker.file_path = None
# Delete the document entry so it can be re-queued
@@ -742,7 +742,7 @@ class LibraryService:
if tracker:
tracker.is_downloaded = False
- tracker.file_absolute_path = None
+ tracker.file_path = None
tracker.file_path = None
# Mark document as pending
diff --git a/src/local_deep_research/research_library/utils.py b/src/local_deep_research/research_library/utils.py
new file mode 100644
index 0000000000..255e835b7e
--- /dev/null
+++ b/src/local_deep_research/research_library/utils.py
@@ -0,0 +1,123 @@
+"""Shared utility functions for the Research Library."""
+
+import hashlib
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+from loguru import logger
+
+
+def get_url_hash(url: str) -> str:
+ """
+ Generate a SHA256 hash of a URL.
+
+ Args:
+ url: The URL to hash
+
+ Returns:
+ The SHA256 hash of the URL
+ """
+ return hashlib.sha256(url.lower().encode()).hexdigest()
+
+
+def get_library_storage_path(username: str) -> Path:
+ """
+ Get the storage path for a user's library.
+
+ Args:
+ username: The username
+
+ Returns:
+ Path to the user's library storage directory
+ """
+ base_dir = (
+ Path.home() / "Documents" / "LocalDeepResearch" / "Library" / username
+ )
+ base_dir.mkdir(parents=True, exist_ok=True)
+ return base_dir
+
+
+def open_file_location(file_path: str) -> bool:
+ """
+ Open the file location in the system file manager.
+
+ Args:
+ file_path: Path to the file
+
+ Returns:
+ True if successful, False otherwise
+ """
+ try:
+ folder = str(Path(file_path).parent)
+ if sys.platform == "win32":
+ os.startfile(folder)
+ elif sys.platform == "darwin": # macOS
+ subprocess.run(["open", folder])
+ else: # Linux
+ subprocess.run(["xdg-open", folder])
+ return True
+ except Exception:
+ logger.exception("Failed to open file location")
+ return False
+
+
+def get_relative_library_path(absolute_path: str, username: str) -> str:
+ """
+ Get the relative path from the library root.
+
+ Args:
+ absolute_path: The absolute file path
+ username: The username
+
+ Returns:
+ The relative path from the library root
+ """
+ try:
+ library_root = get_library_storage_path(username)
+ return str(Path(absolute_path).relative_to(library_root))
+ except ValueError:
+ # Path is not relative to library root
+ return Path(absolute_path).name
+
+
+def get_absolute_library_path(relative_path: str, username: str) -> Path:
+ """
+ Get the absolute path from a relative library path.
+
+ Args:
+ relative_path: The relative path from library root
+ username: The username
+
+ Returns:
+ The absolute path
+ """
+ library_root = get_library_storage_path(username)
+ return library_root / relative_path
+
+
+def get_absolute_path_from_settings(relative_path: str) -> Path:
+ """
+ Get absolute path using settings manager for library root.
+
+ Args:
+ relative_path: The relative path from library root
+
+ Returns:
+ The absolute path
+ """
+ from ..utilities.db_utils import get_settings_manager
+
+ settings = get_settings_manager()
+ library_root = Path(
+ settings.get_setting(
+ "research_library.storage_path",
+ "~/.local-deep-research/library",
+ )
+ ).expanduser()
+
+ if not relative_path:
+ return library_root
+
+ return library_root / relative_path
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 3cd1ab5d17..2918f349b7 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -447,15 +447,10 @@ def register_blueprints(app):
app.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'
# Register Research Library blueprint
- try:
- from ..research_library import library_bp
+ from ..research_library import library_bp
- app.register_blueprint(library_bp) # Already has url_prefix='/library'
- logger.info("Research Library routes registered successfully")
- except ImportError:
- logger.warning(
- "Research Library module not found - skipping registration"
- )
+ app.register_blueprint(library_bp) # Already has url_prefix='/library'
+ logger.info("Research Library routes registered successfully")
# After registration, update CSRF exemptions
if hasattr(app, "extensions") and "csrf" in app.extensions:
diff --git a/src/local_deep_research/web/static/css/components/sources-slider.css b/src/local_deep_research/web/static/css/components/sources-slider.css
new file mode 100644
index 0000000000..c62fe0a04d
--- /dev/null
+++ b/src/local_deep_research/web/static/css/components/sources-slider.css
@@ -0,0 +1,338 @@
+/* Sources Slider Styles */
+.ldr-sources-slider {
+ position: fixed !important;
+ right: -500px;
+ top: 60px;
+ width: 500px;
+ height: calc(100vh - 60px);
+ background: var(--card-bg, #1a1a1a) !important;
+ border-left: 1px solid var(--border-color, #333) !important;
+ box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3) !important;
+ transition: right 0.3s ease;
+ z-index: 99998 !important;
+ display: flex !important;
+ flex-direction: column !important;
+ color: var(--text-primary, #e0e0e0) !important;
+}
+
+.ldr-sources-slider.active {
+ right: 0;
+}
+
+/* Toggle button */
+.ldr-sources-toggle {
+ position: fixed !important;
+ right: 0 !important;
+ top: 50% !important;
+ transform: translateY(-50%) !important;
+ background: #007bff !important;
+ color: white !important;
+ border: none !important;
+ border-radius: 8px 0 0 8px !important;
+ padding: 15px 10px !important;
+ cursor: pointer !important;
+ z-index: 99999 !important;
+ transition: all 0.3s ease !important;
+ writing-mode: vertical-rl !important;
+ text-orientation: mixed !important;
+ font-size: 14px !important;
+ font-weight: 600 !important;
+ box-shadow: -2px 0 8px rgba(0, 0, 0, 0.3) !important;
+ display: block !important;
+ visibility: visible !important;
+}
+
+.ldr-sources-toggle:hover {
+ background: var(--primary-hover);
+ padding-left: 15px;
+}
+
+.ldr-sources-toggle.active {
+ right: 400px;
+ border-radius: 4px;
+ writing-mode: horizontal-tb;
+ padding: 10px 15px;
+}
+
+/* Slider header */
+.ldr-sources-header {
+ padding: 20px;
+ border-bottom: 1px solid var(--border-color, #333);
+ background: var(--bg-color, #0f0f0f);
+ color: var(--text-primary, #e0e0e0);
+}
+
+.ldr-sources-header h3 {
+ margin: 0 0 10px 0;
+ color: var(--text-primary);
+ font-size: 18px;
+ font-weight: 600;
+}
+
+.ldr-sources-stats {
+ display: flex;
+ gap: 20px;
+ font-size: 14px;
+ color: var(--text-secondary);
+}
+
+.ldr-sources-stat {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+}
+
+.ldr-sources-stat i {
+ color: var(--primary-color);
+}
+
+/* Sources filter */
+.ldr-sources-filter {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-color);
+ background: var(--bg-color);
+}
+
+.ldr-sources-search {
+ width: 100%;
+ padding: 8px 12px;
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ background: var(--card-bg);
+ color: var(--text-primary);
+ font-size: 14px;
+}
+
+.ldr-sources-search:focus {
+ outline: none;
+ border-color: var(--primary-color);
+}
+
+/* Sources list */
+.ldr-sources-list {
+ flex: 1;
+ overflow-y: auto;
+ padding: 20px;
+}
+
+.ldr-source-item {
+ background: var(--bg-color, #0f0f0f);
+ border: 1px solid var(--border-color, #333);
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 20px;
+ transition: all 0.2s ease;
+ cursor: pointer;
+ color: var(--text-primary, #e0e0e0);
+}
+
+.ldr-source-item:hover {
+ border-color: var(--primary-color);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+ transform: translateY(-1px);
+}
+
+.ldr-source-item.downloaded {
+ border-left: 3px solid var(--success-color);
+}
+
+.ldr-source-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: start;
+ margin-bottom: 12px;
+}
+
+.ldr-source-number {
+ background: var(--primary-color);
+ color: white;
+ padding: 2px 8px;
+ border-radius: 12px;
+ font-size: 12px;
+ font-weight: 600;
+ min-width: 24px;
+ text-align: center;
+}
+
+.ldr-source-status {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.ldr-source-status i {
+ font-size: 16px;
+}
+
+.ldr-source-status .downloaded-icon {
+ color: var(--success-color);
+}
+
+.ldr-source-status .not-downloaded-icon {
+ color: var(--text-secondary);
+}
+
+.ldr-source-title {
+ font-weight: 600;
+ color: var(--text-primary, #e0e0e0);
+ margin-bottom: 10px;
+ font-size: 15px;
+ line-height: 1.5;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.ldr-source-snippet {
+ color: var(--text-secondary, #999) !important;
+ font-size: 14px !important;
+ line-height: 1.6 !important;
+ margin: 12px 0 !important;
+ padding: 12px !important;
+ background: rgba(255, 255, 255, 0.05) !important;
+ border-left: 3px solid var(--primary-color, #007bff) !important;
+ border-radius: 4px !important;
+ font-style: normal !important;
+ display: block !important;
+}
+
+.ldr-source-url {
+ color: var(--text-secondary);
+ font-size: 12px;
+ margin-bottom: 8px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ldr-source-domain {
+ display: inline-block;
+ background: var(--bg-color);
+ border: 1px solid var(--border-color);
+ padding: 2px 8px;
+ border-radius: 4px;
+ font-size: 11px;
+ color: var(--text-secondary);
+ margin-bottom: 8px;
+}
+
+.ldr-source-actions {
+ display: flex;
+ gap: 10px;
+ margin-top: 10px;
+}
+
+.ldr-source-btn {
+ flex: 1;
+ padding: 6px 12px;
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ background: var(--card-bg);
+ color: var(--text-primary);
+ font-size: 12px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ text-decoration: none;
+ text-align: center;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+}
+
+.ldr-source-btn:hover {
+ background: var(--primary-color);
+ color: white;
+ border-color: var(--primary-color);
+}
+
+.ldr-source-btn.primary {
+ background: var(--primary-color);
+ color: white;
+ border-color: var(--primary-color);
+}
+
+.ldr-source-btn.primary:hover {
+ background: var(--primary-hover);
+ border-color: var(--primary-hover);
+}
+
+/* Empty state */
+.ldr-sources-empty {
+ text-align: center;
+ padding: 40px 20px;
+ color: var(--text-secondary);
+}
+
+.ldr-sources-empty i {
+ font-size: 48px;
+ margin-bottom: 15px;
+ opacity: 0.5;
+}
+
+/* Loading state */
+.ldr-sources-loading {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 200px;
+ color: var(--text-secondary);
+}
+
+.ldr-sources-loading i {
+ font-size: 24px;
+ animation: spin 1s linear infinite;
+}
+
+@keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+}
+
+/* Responsive adjustments */
+@media (max-width: 768px) {
+ .ldr-sources-slider {
+ width: 100%;
+ right: -100%;
+ }
+
+ .ldr-sources-toggle.active {
+ right: calc(100% - 40px);
+ }
+
+ .ldr-sources-slider.active {
+ right: 0;
+ }
+}
+
+/* Dark theme adjustments */
+[data-theme="dark"] .ldr-sources-slider {
+ background: #1a1a1a;
+ border-left-color: #333;
+}
+
+[data-theme="dark"] .ldr-source-item {
+ background: #2a2a2a;
+ border-color: #333;
+}
+
+[data-theme="dark"] .ldr-source-item:hover {
+ border-color: var(--primary-color);
+}
+
+[data-theme="dark"] .ldr-sources-header,
+[data-theme="dark"] .ldr-sources-filter {
+ background: #1a1a1a;
+ border-bottom-color: #333;
+}
+
+[data-theme="dark"] .ldr-sources-search {
+ background: #2a2a2a;
+ border-color: #333;
+}
+
+[data-theme="dark"] .ldr-source-btn {
+ background: #2a2a2a;
+ border-color: #333;
+}
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 79ee69753e..90afbf8c4a 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -43,6 +43,17 @@
// Initialize star rating
initializeStarRating();
+ // Initialize sources panel (Bootstrap offcanvas)
+ // Add a small delay to ensure the panel script is loaded
+ setTimeout(() => {
+ if (window.sourcesPanel) {
+ console.log('Initializing sources panel...');
+ window.sourcesPanel.initialize(researchId);
+ } else {
+ console.log('Sources panel not available');
+ }
+ }, 100);
+
// Note: Log panel is now automatically initialized by logpanel.js
// No need to manually initialize it here
}
diff --git a/src/local_deep_research/web/static/js/components/sources-panel.js b/src/local_deep_research/web/static/js/components/sources-panel.js
new file mode 100644
index 0000000000..ec1defb3b7
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/sources-panel.js
@@ -0,0 +1,446 @@
+/**
+ * Sources Panel Component using Bootstrap Offcanvas
+ * A persistent panel that stays open like Mendeley's reference panel
+ */
+(function() {
+ let sources = [];
+ let researchId = null;
+ let offcanvas = null;
+
+ /**
+ * Initialize the sources panel
+ */
+ function initializeSourcesPanel(research_id) {
+ console.log('Initializing sources panel for research:', research_id);
+ researchId = research_id;
+
+ // Create the offcanvas HTML if it doesn't exist
+ if (!document.getElementById('sourcesOffcanvas')) {
+ createOffcanvasHTML();
+ }
+
+ // Initialize Bootstrap offcanvas
+ const offcanvasElement = document.getElementById('sourcesOffcanvas');
+ offcanvas = new bootstrap.Offcanvas(offcanvasElement, {
+ backdrop: false, // No backdrop so user can interact with main content
+ keyboard: false, // Don't close on ESC
+ scroll: true // Allow scrolling of main content
+ });
+
+ // Set up toggle button
+ setupToggleButton();
+
+ // Load sources
+ loadSources();
+
+ // Restore state from localStorage
+ restoreState();
+ }
+
+ /**
+ * Create the offcanvas HTML structure
+ */
+ function createOffcanvasHTML() {
+ const html = `
+ <!-- Toggle Button -->
+ <button class="btn btn-primary sources-panel-toggle"
+ id="sourcesToggle"
+ type="button"
+ title="Toggle Sources Panel">
+ <i class="fas fa-book"></i>
+ <span class="ms-1">Sources</span>
+ </button>
+
+ <!-- Offcanvas Panel -->
+ <div class="offcanvas offcanvas-end sources-offcanvas"
+ tabindex="-1"
+ id="sourcesOffcanvas"
+ data-bs-backdrop="false"
+ data-bs-scroll="true">
+ <div class="offcanvas-header">
+ <h5 class="offcanvas-title">Research Sources</h5>
+ <button type="button"
+ class="btn-close"
+ data-bs-dismiss="offcanvas"
+ aria-label="Close"></button>
+ </div>
+ <div class="offcanvas-body">
+ <!-- Search -->
+ <div class="mb-3">
+ <input type="text"
+ class="form-control"
+ id="sourcesSearch"
+ placeholder="Search sources...">
+ </div>
+
+ <!-- Stats -->
+ <div class="d-flex justify-content-between mb-3">
+ <small class="text-muted">
+ <i class="fas fa-file-alt"></i>
+ <span id="totalSources">0</span> sources
+ </small>
+ <small class="text-muted">
+ <i class="fas fa-download"></i>
+ <span id="downloadedSources">0</span> downloaded
+ </small>
+ </div>
+
+ <!-- Sources List -->
+ <div id="sourcesList" class="sources-list">
+ <div class="text-center p-4">
+ <div class="spinner-border text-primary" role="status">
+ <span class="visually-hidden">Loading...</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Add to body
+ document.body.insertAdjacentHTML('beforeend', html);
+
+ // Add custom styles
+ addCustomStyles();
+ }
+
+ /**
+ * Add custom styles for the sources panel
+ */
+ function addCustomStyles() {
+ const style = document.createElement('style');
+ style.textContent = `
+ .sources-panel-toggle {
+ position: fixed;
+ right: 20px;
+ bottom: 80px;
+ z-index: 1040;
+ border-radius: 50px;
+ padding: 10px 20px;
+ box-shadow: 0 2px 10px rgba(0,0,0,0.2);
+ }
+
+ .sources-offcanvas {
+ width: 450px !important;
+ background: var(--card-bg, #fff);
+ border-left: 1px solid var(--border-color, #dee2e6);
+ }
+
+ .sources-offcanvas .offcanvas-header {
+ background: var(--bg-color, #f8f9fa);
+ border-bottom: 1px solid var(--border-color, #dee2e6);
+ }
+
+ .source-card {
+ background: var(--bg-color, #f8f9fa);
+ border: 1px solid var(--border-color, #dee2e6);
+ border-radius: 8px;
+ padding: 15px;
+ margin-bottom: 15px;
+ transition: all 0.2s;
+ }
+
+ .source-card:hover {
+ border-color: var(--primary-color, #0d6efd);
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
+ }
+
+ .source-card.downloaded {
+ border-left: 3px solid var(--success-color, #198754);
+ }
+
+ .source-number {
+ display: inline-block;
+ background: var(--primary-color, #0d6efd);
+ color: white;
+ padding: 2px 8px;
+ border-radius: 12px;
+ font-size: 12px;
+ font-weight: 600;
+ margin-right: 8px;
+ }
+
+ .source-title {
+ font-weight: 600;
+ margin-bottom: 8px;
+ color: var(--text-primary, #212529);
+ }
+
+ .source-snippet {
+ font-size: 14px;
+ color: var(--text-secondary, #6c757d);
+ margin: 10px 0;
+ padding: 10px;
+ background: rgba(0,0,0,0.03);
+ border-left: 3px solid var(--primary-color, #0d6efd);
+ border-radius: 4px;
+ }
+
+ .source-domain {
+ display: inline-block;
+ font-size: 12px;
+ color: var(--text-secondary, #6c757d);
+ background: rgba(0,0,0,0.05);
+ padding: 2px 8px;
+ border-radius: 4px;
+ margin-bottom: 8px;
+ }
+
+ .source-url {
+ font-size: 12px;
+ color: var(--text-secondary, #6c757d);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-bottom: 10px;
+ }
+
+ .sources-list {
+ max-height: calc(100vh - 250px);
+ overflow-y: auto;
+ }
+
+ /* Dark theme adjustments */
+ [data-theme="dark"] .sources-offcanvas {
+ background: #1a1a1a;
+ color: #e0e0e0;
+ }
+
+ [data-theme="dark"] .source-card {
+ background: #2a2a2a;
+ border-color: #333;
+ }
+
+ [data-theme="dark"] .source-snippet {
+ background: rgba(255,255,255,0.05);
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ /**
+ * Set up toggle button event
+ */
+ function setupToggleButton() {
+ const toggleBtn = document.getElementById('sourcesToggle');
+ if (toggleBtn) {
+ toggleBtn.addEventListener('click', () => {
+ if (offcanvas) {
+ offcanvas.toggle();
+ // Save state
+ const isOpen = document.getElementById('sourcesOffcanvas').classList.contains('show');
+ localStorage.setItem('sourcesPanel_open', !isOpen);
+ }
+ });
+ }
+
+ // Set up search
+ const searchInput = document.getElementById('sourcesSearch');
+ if (searchInput) {
+ searchInput.addEventListener('input', handleSearch);
+ }
+ }
+
+ /**
+ * Load sources from the API
+ */
+ async function loadSources() {
+ try {
+ const response = await fetch(`/library/api/get-research-sources/${researchId}`);
+
+ if (!response.ok) {
+ throw new Error('Failed to fetch sources');
+ }
+
+ const data = await response.json();
+
+ if (data.success && data.sources) {
+ sources = data.sources;
+ console.log(`Loaded ${sources.length} sources from database`);
+ updateStats();
+ renderSources(sources);
+ }
+ } catch (error) {
+ console.error('Error loading sources:', error);
+ showError('Failed to load sources');
+ }
+ }
+
+ /**
+ * Update statistics
+ */
+ function updateStats() {
+ const totalEl = document.getElementById('totalSources');
+ const downloadedEl = document.getElementById('downloadedSources');
+
+ if (totalEl) totalEl.textContent = sources.length;
+ if (downloadedEl) {
+ const downloadedCount = sources.filter(s => s.downloaded).length;
+ downloadedEl.textContent = downloadedCount;
+ }
+ }
+
+ /**
+ * Render sources
+ */
+ function renderSources(sourcesToRender) {
+ const listEl = document.getElementById('sourcesList');
+ if (!listEl) return;
+
+ if (sourcesToRender.length === 0) {
+ listEl.innerHTML = `
+ <div class="text-center p-4 text-muted">
+ <i class="fas fa-inbox fa-3x mb-3"></i>
+ <p>No sources found</p>
+ </div>
+ `;
+ return;
+ }
+
+ listEl.innerHTML = sourcesToRender.map(source => `
+ <div class="source-card ${source.downloaded ? 'downloaded' : ''}">
+ <div class="d-flex justify-content-between align-items-start mb-2">
+ <div>
+ <span class="source-number">${source.number}</span>
+ ${source.downloaded ?
+ '<i class="fas fa-check-circle text-success" title="Downloaded"></i>' :
+ '<i class="fas fa-cloud-download-alt text-muted" title="Not downloaded"></i>'
+ }
+ </div>
+ </div>
+
+ <div class="source-title">${escapeHtml(source.title)}</div>
+
+ ${source.domain ? `<span class="source-domain">${escapeHtml(source.domain)}</span>` : ''}
+
+ ${source.snippet ? `
+ <div class="source-snippet">
+ ${escapeHtml(source.snippet).substring(0, 200)}${source.snippet.length > 200 ? '...' : ''}
+ </div>
+ ` : ''}
+
+ <div class="source-url" title="${escapeHtml(source.url)}">
+ ${escapeHtml(source.url)}
+ </div>
+
+ <div class="d-flex gap-2">
+ ${source.downloaded ? `
+ <a href="/library/view/${source.document_id}"
+ class="btn btn-sm btn-primary"
+ target="_blank">
+ <i class="fas fa-book-open"></i> View in Library
+ </a>
+ ` : `
+ <button class="btn btn-sm btn-outline-primary"
+ onclick="sourcesPanel.downloadSource('${escapeHtml(source.url)}')">
+ <i class="fas fa-download"></i> Download
+ </button>
+ <a href="${escapeHtml(source.url)}"
+ class="btn btn-sm btn-outline-secondary"
+ target="_blank">
+ <i class="fas fa-external-link-alt"></i> Open
+ </a>
+ `}
+ </div>
+ </div>
+ `).join('');
+ }
+
+ /**
+ * Handle search
+ */
+ function handleSearch(e) {
+ const query = e.target.value.toLowerCase();
+
+ if (!query) {
+ renderSources(sources);
+ } else {
+ const filtered = sources.filter(source =>
+ (source.title && source.title.toLowerCase().includes(query)) ||
+ (source.url && source.url.toLowerCase().includes(query)) ||
+ (source.domain && source.domain.toLowerCase().includes(query)) ||
+ (source.snippet && source.snippet.toLowerCase().includes(query))
+ );
+ renderSources(filtered);
+ }
+ }
+
+ /**
+ * Download a source
+ */
+ async function downloadSource(url) {
+ try {
+ const response = await fetch('/library/api/download-source', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ research_id: researchId,
+ url: url
+ })
+ });
+
+ if (response.ok) {
+ // Reload sources to update status
+ await loadSources();
+ showMessage('Download started');
+ } else {
+ showError('Failed to start download');
+ }
+ } catch (error) {
+ console.error('Error downloading source:', error);
+ showError('Failed to download source');
+ }
+ }
+
+ /**
+ * Restore panel state from localStorage
+ */
+ function restoreState() {
+ const isOpen = localStorage.getItem('sourcesPanel_open') === 'true';
+ if (isOpen && offcanvas) {
+ offcanvas.show();
+ }
+ }
+
+ /**
+ * Show error message
+ */
+ function showError(message) {
+ const listEl = document.getElementById('sourcesList');
+ if (listEl) {
+ listEl.innerHTML = `
+ <div class="alert alert-danger" role="alert">
+ ${message}
+ </div>
+ `;
+ }
+ }
+
+ /**
+ * Show success message
+ */
+ function showMessage(message) {
+ // You could use a toast notification here
+ console.log(message);
+ }
+
+ /**
+ * Escape HTML
+ */
+ function escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text || '';
+ return div.innerHTML;
+ }
+
+ // Export public methods
+ window.sourcesPanel = {
+ initialize: initializeSourcesPanel,
+ downloadSource: downloadSource,
+ reload: loadSources
+ };
+
+ console.log('Sources panel component loaded');
+})();
diff --git a/src/local_deep_research/web/static/js/components/sources-slider.js b/src/local_deep_research/web/static/js/components/sources-slider.js
new file mode 100644
index 0000000000..c63a05db87
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/sources-slider.js
@@ -0,0 +1,599 @@
+/**
+ * Sources Slider Component
+ * Displays research sources with links to downloaded documents
+ */
+(function() {
+ let sources = [];
+ let filteredSources = [];
+ let downloadStatus = {};
+ let researchId = null;
+ let isOpen = false;
+
+ /**
+ * Initialize the sources slider
+ */
+ function initializeSourcesSlider(research_id) {
+ console.log('Initializing sources slider for research:', research_id);
+ researchId = research_id;
+
+ // Create slider HTML if it doesn't exist
+ if (!document.getElementById('sources-slider')) {
+ console.log('Creating slider HTML');
+ createSliderHTML();
+ }
+
+ // Set up event listeners
+ setupEventListeners();
+
+ // Load sources
+ loadSources();
+ }
+
+ /**
+ * Create the slider HTML structure
+ */
+ function createSliderHTML() {
+ const sliderHTML = `
+ <button class="ldr-sources-toggle" id="sources-toggle">
+ <span class="ldr-toggle-text">Sources</span>
+ </button>
+
+ <div class="ldr-sources-slider" id="sources-slider">
+ <div class="ldr-sources-header">
+ <h3>Research Sources</h3>
+ <div class="ldr-sources-stats">
+ <div class="ldr-sources-stat">
+ <i class="fas fa-file-alt"></i>
+ <span id="total-sources">0</span> sources
+ </div>
+ <div class="ldr-sources-stat">
+ <i class="fas fa-download"></i>
+ <span id="downloaded-sources">0</span> downloaded
+ </div>
+ </div>
+ </div>
+
+ <div class="ldr-sources-filter">
+ <input type="text"
+ class="ldr-sources-search"
+ id="sources-search"
+ placeholder="Search sources...">
+ </div>
+
+ <div class="ldr-sources-list" id="sources-list">
+ <div class="ldr-sources-loading">
+ <i class="fas fa-spinner fa-spin"></i>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Add to body
+ document.body.insertAdjacentHTML('beforeend', sliderHTML);
+
+ // Verify elements were created
+ const toggle = document.getElementById('sources-toggle');
+ const slider = document.getElementById('sources-slider');
+ console.log('Toggle button created:', !!toggle);
+ console.log('Slider panel created:', !!slider);
+
+ // Apply inline styles to ensure they work
+ if (toggle) {
+ toggle.style.position = 'fixed';
+ toggle.style.right = '0';
+ toggle.style.top = '50%';
+ toggle.style.transform = 'translateY(-50%)';
+ toggle.style.zIndex = '99999';
+ toggle.style.background = '#007bff';
+ toggle.style.color = 'white';
+ toggle.style.padding = '15px 10px';
+ toggle.style.border = 'none';
+ toggle.style.borderRadius = '8px 0 0 8px';
+ toggle.style.cursor = 'pointer';
+ toggle.style.writingMode = 'vertical-rl';
+ toggle.style.fontSize = '14px';
+ toggle.style.fontWeight = '600';
+ toggle.style.boxShadow = '-2px 0 8px rgba(0, 0, 0, 0.3)';
+ console.log('Applied inline styles to toggle button');
+ }
+
+ if (slider) {
+ slider.style.position = 'fixed';
+ slider.style.right = '-500px';
+ slider.style.top = '60px';
+ slider.style.width = '500px';
+ slider.style.height = 'calc(100vh - 60px)';
+ slider.style.background = 'var(--card-bg, #1a1a1a)';
+ slider.style.borderLeft = '1px solid var(--border-color, #333)';
+ slider.style.boxShadow = '-2px 0 10px rgba(0, 0, 0, 0.3)';
+ slider.style.transition = 'right 0.3s ease';
+ slider.style.zIndex = '99998';
+ slider.style.display = 'flex';
+ slider.style.flexDirection = 'column';
+ slider.style.overflow = 'hidden';
+ console.log('Applied inline styles to slider');
+ }
+ }
+
+ /**
+ * Set up event listeners
+ */
+ function setupEventListeners() {
+ // Toggle button
+ const toggleBtn = document.getElementById('sources-toggle');
+ if (toggleBtn) {
+ toggleBtn.addEventListener('click', toggleSlider);
+ }
+
+ // Search input
+ const searchInput = document.getElementById('sources-search');
+ if (searchInput) {
+ searchInput.addEventListener('input', handleSearch);
+ }
+
+ // Close on escape key
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && isOpen) {
+ closeSlider();
+ }
+ });
+ }
+
+ /**
+ * Toggle the slider open/closed
+ */
+ function toggleSlider() {
+ if (isOpen) {
+ closeSlider();
+ } else {
+ openSlider();
+ }
+ }
+
+ /**
+ * Open the slider
+ */
+ function openSlider() {
+ const slider = document.getElementById('sources-slider');
+ const toggle = document.getElementById('sources-toggle');
+
+ if (slider && toggle) {
+ slider.classList.add('active');
+ toggle.classList.add('active');
+ toggle.innerHTML = '<i class="fas fa-times"></i>';
+
+ // Also apply inline style to ensure it slides out
+ slider.style.right = '0';
+
+ isOpen = true;
+ console.log('Slider opened');
+ }
+ }
+
+ /**
+ * Close the slider
+ */
+ function closeSlider() {
+ const slider = document.getElementById('sources-slider');
+ const toggle = document.getElementById('sources-toggle');
+
+ if (slider && toggle) {
+ slider.classList.remove('active');
+ toggle.classList.remove('active');
+ toggle.innerHTML = '<span class="ldr-toggle-text">Sources</span>';
+
+ // Also apply inline style to ensure it slides back
+ slider.style.right = '-500px';
+
+ isOpen = false;
+ console.log('Slider closed');
+ }
+ }
+
+ /**
+ * Load sources from the research report
+ */
+ async function loadSources() {
+ try {
+ // Fetch sources from the database
+ const response = await fetch(`/library/api/get-research-sources/${researchId}`);
+
+ if (!response.ok) {
+ throw new Error('Failed to fetch sources');
+ }
+
+ const data = await response.json();
+
+ if (data.success && data.sources) {
+ sources = data.sources;
+ console.log(`Loaded ${sources.length} sources from database`);
+
+ // Update download status is already included in the response
+ sources.forEach(source => {
+ if (source.downloaded) {
+ downloadStatus[source.url] = {
+ downloaded: true,
+ document_id: source.document_id,
+ file_type: source.file_type
+ };
+ }
+ });
+
+ // Update stats
+ updateStats();
+
+ // Render sources
+ filteredSources = [...sources];
+ renderSources();
+ } else {
+ // Fallback to extracting from report content
+ console.log('No sources from database, extracting from report');
+ sources = extractSourcesFromReport();
+ await checkDownloadStatus();
+ updateStats();
+ filteredSources = [...sources];
+ renderSources();
+ }
+
+ } catch (error) {
+ console.error('Error loading sources:', error);
+ // Fallback to extracting from report content
+ sources = extractSourcesFromReport();
+ await checkDownloadStatus();
+ updateStats();
+ filteredSources = [...sources];
+ renderSources();
+ }
+ }
+
+ /**
+ * Extract sources from the report content
+ */
+ function extractSourcesFromReport() {
+ const extractedSources = [];
+ const seenUrls = new Set();
+
+ // Look for citation links in the report
+ const reportContent = document.getElementById('results-content');
+ if (!reportContent) {
+ console.log('No results-content element found');
+ return extractedSources;
+ }
+ console.log('Extracting sources from report content');
+
+ // Find all links with citation markers [1], [2], etc.
+ const citationPattern = /\[(\d+)\]/g;
+ const links = reportContent.querySelectorAll('a[href]');
+
+ console.log(`Found ${links.length} total links in report`);
+
+ links.forEach(link => {
+ const url = link.href;
+ const text = link.textContent || '';
+
+ // Skip internal links, anchors, and duplicates
+ if (!url ||
+ url === '' ||
+ url === window.location.href ||
+ url.startsWith('#') ||
+ url.startsWith('javascript:') ||
+ url.startsWith('mailto:') ||
+ seenUrls.has(url)) {
+ return;
+ }
+
+ // Check if it's an external link
+ try {
+ const urlObj = new URL(url);
+ // Skip if it's the same domain as the current page
+ if (urlObj.hostname === window.location.hostname) {
+ return;
+ }
+ } catch (e) {
+ console.log('Invalid URL:', url);
+ return;
+ }
+
+ // Check if this looks like a citation link
+ const citationMatch = text.match(/\[(\d+)\]/);
+ let sourceNumber = extractedSources.length + 1;
+
+ if (citationMatch) {
+ sourceNumber = parseInt(citationMatch[1]);
+ }
+
+ seenUrls.add(url);
+
+ // Extract title - could be from link text, title attribute, or nearby text
+ let title = link.title || text.replace(/\[\d+\]/, '').trim();
+ if (!title || title.length < 3) {
+ // Try to get text from parent element
+ const parent = link.parentElement;
+ if (parent) {
+ title = parent.textContent.substring(0, 100).trim();
+ }
+ }
+ if (!title) {
+ title = 'Untitled Source';
+ }
+
+ extractedSources.push({
+ number: sourceNumber,
+ title: title,
+ url: url,
+ domain: new URL(url).hostname,
+ element: link
+ });
+
+ console.log(`Added source: ${title} - ${url}`);
+ });
+
+ // Also look for sources in a sources section if it exists
+ const sourcesSection = reportContent.querySelector('.sources-section, .references-section, #sources, #references');
+ if (sourcesSection) {
+ const sourceLinks = sourcesSection.querySelectorAll('a[href]');
+ sourceLinks.forEach((link, index) => {
+ const url = link.href;
+ if (!seenUrls.has(url) && !url.startsWith('#') && !url.startsWith('javascript:')) {
+ seenUrls.add(url);
+ extractedSources.push({
+ number: extractedSources.length + 1,
+ title: link.textContent || 'Untitled Source',
+ url: url,
+ domain: new URL(url).hostname,
+ element: link
+ });
+ }
+ });
+ }
+
+ // Sort by number
+ extractedSources.sort((a, b) => a.number - b.number);
+
+ console.log(`Found ${extractedSources.length} sources in report`);
+ return extractedSources;
+ }
+
+ /**
+ * Check download status for sources
+ */
+ async function checkDownloadStatus() {
+ try {
+ const response = await fetch('/library/api/check-downloads', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ research_id: researchId,
+ urls: sources.map(s => s.url)
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ downloadStatus = data.download_status || {};
+
+ // Add download info to sources
+ sources.forEach(source => {
+ const status = downloadStatus[source.url];
+ if (status) {
+ source.downloaded = status.downloaded;
+ source.documentId = status.document_id;
+ source.filePath = status.file_path;
+ }
+ });
+ }
+ } catch (error) {
+ console.error('Error checking download status:', error);
+ }
+ }
+
+ /**
+ * Update statistics
+ */
+ function updateStats() {
+ const totalSources = sources.length;
+ const downloadedSources = sources.filter(s => s.downloaded).length;
+
+ const totalEl = document.getElementById('total-sources');
+ const downloadedEl = document.getElementById('downloaded-sources');
+
+ if (totalEl) totalEl.textContent = totalSources;
+ if (downloadedEl) downloadedEl.textContent = downloadedSources;
+ }
+
+ /**
+ * Render sources list
+ */
+ function renderSources() {
+ const listEl = document.getElementById('sources-list');
+ if (!listEl) return;
+
+ if (filteredSources.length === 0) {
+ listEl.innerHTML = `
+ <div class="ldr-sources-empty">
+ <i class="fas fa-inbox"></i>
+ <p>No sources found</p>
+ </div>
+ `;
+ return;
+ }
+
+ listEl.innerHTML = filteredSources.map(source => `
+ <div class="ldr-source-item ${source.downloaded ? 'downloaded' : ''}"
+ data-url="${escapeHtml(source.url)}">
+ <div class="ldr-source-header">
+ <span class="ldr-source-number">${source.number}</span>
+ <div class="ldr-source-status">
+ ${source.downloaded ?
+ '<i class="fas fa-check-circle downloaded-icon" title="Downloaded"></i>' :
+ '<i class="fas fa-cloud-download-alt not-downloaded-icon" title="Not downloaded"></i>'
+ }
+ </div>
+ </div>
+
+ <div class="ldr-source-title" title="${escapeHtml(source.title)}">
+ ${escapeHtml(source.title)}
+ </div>
+
+ <div class="ldr-source-domain">${escapeHtml(source.domain || '')}</div>
+
+ ${source.snippet ? `
+ <div class="ldr-source-snippet" style="
+ color: #999;
+ font-size: 14px;
+ line-height: 1.6;
+ margin: 12px 0;
+ padding: 12px;
+ background: rgba(255, 255, 255, 0.05);
+ border-left: 3px solid #007bff;
+ border-radius: 4px;
+ display: block;
+ ">
+ ${escapeHtml(source.snippet).substring(0, 200)}${source.snippet.length > 200 ? '...' : ''}
+ </div>
+ ` : ''}
+
+ <div class="ldr-source-url" title="${escapeHtml(source.url)}">
+ ${escapeHtml(source.url)}
+ </div>
+
+ <div class="ldr-source-actions">
+ ${source.downloaded ? `
+ <a href="/library/view/${source.document_id || source.documentId}"
+ class="ldr-source-btn primary"
+ target="_blank">
+ <i class="fas fa-book-open"></i> View in Library
+ </a>
+ <button class="ldr-source-btn" onclick="sourcesSlider.scrollToSource('${escapeHtml(source.url)}')">
+ <i class="fas fa-arrow-right"></i> Go to Citation
+ </button>
+ ` : `
+ <button class="ldr-source-btn" onclick="sourcesSlider.downloadSource('${escapeHtml(source.url)}')">
+ <i class="fas fa-download"></i> Download
+ </button>
+ <a href="${escapeHtml(source.url)}"
+ class="ldr-source-btn"
+ target="_blank"
+ rel="noopener noreferrer">
+ <i class="fas fa-external-link-alt"></i> Open Source
+ </a>
+ `}
+ </div>
+ </div>
+ `).join('');
+ }
+
+ /**
+ * Handle search input
+ */
+ function handleSearch(e) {
+ const query = e.target.value.toLowerCase();
+
+ if (!query) {
+ filteredSources = [...sources];
+ } else {
+ filteredSources = sources.filter(source =>
+ source.title.toLowerCase().includes(query) ||
+ source.url.toLowerCase().includes(query) ||
+ source.domain.toLowerCase().includes(query)
+ );
+ }
+
+ renderSources();
+ }
+
+ /**
+ * Scroll to source in the report
+ */
+ function scrollToSource(url) {
+ const source = sources.find(s => s.url === url);
+ if (source && source.element) {
+ source.element.scrollIntoView({ behavior: 'smooth', block: 'center' });
+
+ // Highlight the citation
+ source.element.style.backgroundColor = 'yellow';
+ setTimeout(() => {
+ source.element.style.backgroundColor = '';
+ }, 2000);
+
+ // Close the slider
+ closeSlider();
+ }
+ }
+
+ /**
+ * Download a source
+ */
+ async function downloadSource(url) {
+ try {
+ const response = await fetch('/library/api/download-source', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ research_id: researchId,
+ url: url
+ })
+ });
+
+ if (response.ok) {
+ // Reload sources to update status
+ await loadSources();
+ showMessage('Download started');
+ } else {
+ showError('Failed to start download');
+ }
+ } catch (error) {
+ console.error('Error downloading source:', error);
+ showError('Failed to download source');
+ }
+ }
+
+ /**
+ * Show error message
+ */
+ function showError(message) {
+ // Use existing UI utilities if available
+ if (window.ui && window.ui.showError) {
+ window.ui.showError(message);
+ } else {
+ console.error(message);
+ }
+ }
+
+ /**
+ * Show success message
+ */
+ function showMessage(message) {
+ // Use existing UI utilities if available
+ if (window.ui && window.ui.showMessage) {
+ window.ui.showMessage(message);
+ } else {
+ console.log(message);
+ }
+ }
+
+ /**
+ * Escape HTML for safety
+ */
+ function escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+ }
+
+ // Export public methods
+ window.sourcesSlider = {
+ initialize: initializeSourcesSlider,
+ open: openSlider,
+ close: closeSlider,
+ toggle: toggleSlider,
+ scrollToSource: scrollToSource,
+ downloadSource: downloadSource,
+ reload: loadSources
+ };
+
+})();
diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index 96b5899920..7b103a317a 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -2,6 +2,10 @@
{% block title %}Research Results - Deep Research System{% endblock %}
+{% block styles %}
+{{ super() }}
+{% endblock %}
+
{% block content %}
<div class="page active" id="research-results">
<div class="page-header">
@@ -58,11 +62,6 @@
</div>
{% endblock %}
-{% block styles %}
-{{ super() }}
-<!-- Bootstrap CSS for modal -->
-{% endblock %}
-
{% block page_scripts %}
<!-- Bootstrap JS for modal functionality -->
<!-- Fallback utilities in case main services are not available -->
@@ -78,6 +77,9 @@
<!-- Results component -->
<script src="/static/js/components/results.js"></script>
+<!-- Sources panel component (Bootstrap Offcanvas) -->
+<script src="/static/js/components/sources-panel.js?v={{ range(1000, 9999) | random }}"></script>
+
<!-- Follow-up Research component -->
<script src="/static/js/followup.js"></script>
{% endblock %}