~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: enhance Research Library with download manager improvements
LearningCircuit14935b8d8f42
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 86461f571e..e2bbccb750 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -18,6 +18,7 @@ from flask import (send_file,stream_with_context,)+from loguru import loggerfrom ...web.auth.decorators import login_requiredfrom ...web.utils.templates import render_template_with_defaults@@ -197,19 +198,19 @@ def serve_pdf(doc_id):username = session.get("username")service = LibraryService(username)- documents = service.get_documents(limit=1)- if not documents:+ # Get the specific document by ID+ document = service.get_document_by_id(doc_id)+ if not document:return "Document not found", 404- doc = documents[0]- file_path = doc.get("file_absolute_path")+ file_path = document.get("file_absolute_path")if file_path and Path(file_path).exists():return send_file(file_path,mimetype="application/pdf",as_attachment=False,- download_name=doc.get("file_name", "document.pdf"),+ download_name=document.get("file_name", "document.pdf"),)return "PDF file not found", 404@@ -303,26 +304,80 @@ def download_bulk():# Process each researchfor research_id in research_ids:- # Queue downloads- queued = download_service.queue_research_downloads(research_id)-- # Process queue items (simplified - in production use background task)- # For demo, we'll just simulate progress- for i in range(queued):- current += 1- progress = int((current / total) * 100) if total > 0 else 100-- yield f"data: {- json.dumps(- {- 'progress': progress,- 'current': current,- 'total': total,- 'file': f'document_{i}.pdf',- 'status': 'success',- }+ # Get queued downloads for this research+ from ...database.models import (+ LibraryDownloadQueue,+ ResearchResource,+ )+ from ...database.session_context import get_user_db_session++ with get_user_db_session(username) as session:+ # Get pending queue items for this research+ queue_items = (+ session.query(LibraryDownloadQueue)+ .filter_by(research_id=research_id, status="pending")+ .all()+ )++ # If no items queued yet, queue them now+ if not queue_items:+ try:+ download_service.queue_research_downloads(research_id)+ # Re-fetch queue items+ queue_items = (+ session.query(LibraryDownloadQueue)+ .filter_by(+ research_id=research_id, status="pending"+ )+ .all()+ )+ except Exception as e:+ logger.exception(+ f"Error queueing downloads for research {research_id}: {str(e)}"+ )+ # Continue with empty queue_items+ queue_items = []++ # Process each queued item+ for queue_item in queue_items:+ current += 1+ progress = (+ int((current / total) * 100) if total > 0 else 100)- }\n\n"++ # Get resource info+ resource = session.query(ResearchResource).get(+ queue_item.resource_id+ )+ file_name = (+ resource.title[:50]+ if resource+ else f"document_{current}.pdf"+ )++ # Attempt actual download with error handling+ try:+ success = download_service.download_resource(+ queue_item.resource_id+ )+ status = "success" if success else "skipped"+ except Exception as e:+ # Log error but continue processing+ logger.exception(+ f"Download error for resource {queue_item.resource_id}: {str(e)}"+ )+ status = "failed"+ success = False++ # Send progress update+ update_data = {+ "progress": progress,+ "current": current,+ "total": total,+ "file": file_name,+ "status": status,+ }+ yield f"data: {json.dumps(update_data)}\n\n"yield f"data: {json.dumps({'progress': 100, 'current': total, 'total': total, 'complete': True})}\n\n"@@ -341,3 +396,30 @@ def get_research_list():service = LibraryService(username)research_list = service.get_research_list_with_stats()return jsonify({"research": research_list})+++@library_bp.route("/api/sync-library", methods=["POST"])+@login_required+def sync_library():+ """Sync library database with filesystem."""+ username = session.get("username")+ service = LibraryService(username)+ stats = service.sync_library_with_filesystem()+ return jsonify(stats)+++@library_bp.route("/api/mark-redownload", methods=["POST"])+@login_required+def mark_for_redownload():+ """Mark documents for re-download."""+ username = session.get("username")+ service = LibraryService(username)++ data = request.json+ document_ids = data.get("document_ids", [])++ if not document_ids:+ return jsonify({"error": "No document IDs provided"}), 400++ count = service.mark_for_redownload(document_ids)+ return jsonify({"success": True, "marked": count})diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 85ea113ca3..b8a8bf2c8f 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -10,6 +10,7 @@ Handles downloading PDFs from various academic sources with:import hashlibimport re+import timefrom datetime import datetime, UTCfrom pathlib import Pathfrom typing import Optional, Tuple@@ -50,10 +51,15 @@ class DownloadService:# Create directory structureself._setup_directories()+ # Rate limiting for PubMed (track last request time)+ self._last_pubmed_request = 0+ self._pubmed_delay = 1.0 # 1 second delay between PubMed requests+# Download strategies for different sourcesself.strategies = {"arxiv.org": self._download_arxiv,"ncbi.nlm.nih.gov": self._download_pubmed,+ "pubmed.ncbi.nlm.nih.gov": self._download_pubmed,"semanticscholar.org": self._download_semantic_scholar,"biorxiv.org": self._download_biorxiv,"medrxiv.org": self._download_medrxiv,@@ -61,11 +67,10 @@ class DownloadService:def _setup_directories(self):"""Create library directory structure."""+ # Only create the root and pdfs folder - flat structurepaths = [self.library_root,- str(Path(self.library_root) / "by_date"),- str(Path(self.library_root) / "by_domain"),- str(Path(self.library_root) / "by_research"),+ str(Path(self.library_root) / "pdfs"),]for path in paths:Path(path).mkdir(parents=True, exist_ok=True)@@ -136,23 +141,46 @@ class DownloadService:for resource in resources:if self._is_downloadable(resource):- # Check if already queued or downloaded- existing = (+ # Check if already queued+ existing_queue = (session.query(LibraryDownloadQueue)- .filter_by(resource_id=resource.id)+ .filter_by(resource_id=resource.id, status="pending")+ .first()+ )++ # Check if already downloaded (trust the database status)+ existing_doc = (+ session.query(LibraryDocument)+ .filter_by(+ resource_id=resource.id, download_status="completed"+ ).first())- if not existing:- # Add to queue- queue_entry = LibraryDownloadQueue(- resource_id=resource.id,- research_id=research_id,- priority=0,- status="pending",+ # Queue if not already queued and not marked as completed+ if not existing_queue and not existing_doc:+ # Check one more time if ANY queue entry exists (regardless of status)+ any_queue = (+ session.query(LibraryDownloadQueue)+ .filter_by(resource_id=resource.id)+ .first())- session.add(queue_entry)- queued += 1++ if any_queue:+ # Reset the existing queue entry+ any_queue.status = "pending"+ any_queue.research_id = research_id+ queued += 1+ else:+ # Add new queue entry+ queue_entry = LibraryDownloadQueue(+ resource_id=resource.id,+ research_id=research_id,+ priority=0,+ status="pending",+ )+ session.add(queue_entry)+ queued += 1session.commit()logger.info(f"Queued {queued} downloads for research {research_id}")@@ -167,12 +195,13 @@ class DownloadService:if url.endswith(".pdf"):return True- # Check for known academic sources+ # Check for known academic sources with downloadable PDFsdownloadable_domains = ["arxiv.org","biorxiv.org","medrxiv.org",- "ncbi.nlm.nih.gov/pmc",+ "ncbi.nlm.nih.gov/pmc", # PubMed Central has PDFs+ "pubmed.ncbi.nlm.nih.gov", # Try to find PMC version"semanticscholar.org","researchgate.net","academia.edu",@@ -193,10 +222,17 @@ class DownloadService:logger.error(f"Resource {resource_id} not found")return False- # Check if already downloaded- is_downloaded, file_path = self.is_already_downloaded(resource.url)- if is_downloaded:- logger.info(f"Resource already downloaded: {file_path}")+ # Check if already downloaded (trust the database after sync)+ existing_doc = (+ session.query(LibraryDocument)+ .filter_by(resource_id=resource_id, download_status="completed")+ .first()+ )++ if existing_doc:+ logger.info(+ "Resource already downloaded (according to database)"+ )return True# Create download tracker entry@@ -286,25 +322,39 @@ class DownloadService:tracker.is_downloaded = Truetracker.downloaded_at = datetime.now(UTC)- # Create library document entry- doc = LibraryDocument(- resource_id=resource.id,- research_id=resource.research_id,- document_hash=tracker.file_hash,- original_url=url,- file_path=tracker.file_path,- file_size=len(pdf_content),- file_type="pdf",- mime_type="application/pdf",- title=resource.title,- download_status="completed",- downloaded_at=datetime.now(UTC),+ # Check if library document already exists+ existing_doc = (+ session.query(LibraryDocument)+ .filter_by(resource_id=resource.id)+ .first())- # Extract domain for filtering- doc.domain = urlparse(url).netloc-- session.add(doc)+ if existing_doc:+ # Update existing document+ existing_doc.document_hash = tracker.file_hash+ existing_doc.file_path = tracker.file_path+ existing_doc.file_size = len(pdf_content)+ existing_doc.download_status = "completed"+ existing_doc.downloaded_at = datetime.now(UTC)+ existing_doc.domain = urlparse(url).netloc+ else:+ # Create new library document entry+ doc = LibraryDocument(+ resource_id=resource.id,+ research_id=resource.research_id,+ document_hash=tracker.file_hash,+ original_url=url,+ file_path=tracker.file_path,+ file_size=len(pdf_content),+ file_type="pdf",+ mime_type="application/pdf",+ title=resource.title,+ download_status="completed",+ downloaded_at=datetime.now(UTC),+ )+ # Extract domain for filtering+ doc.domain = urlparse(url).netloc+ session.add(doc)# Update attemptattempt.succeeded = True@@ -352,28 +402,15 @@ class DownloadService:safe_title = re.sub(r"[^\w\s-]", "", resource.title or "")[:50]filename = f"{domain}_{safe_title}_{resource.id}.pdf"- # Create directory structure- date_path = (- Path(self.library_root)- / "by_date"- / datetime.now(UTC).strftime("%Y")- / datetime.now(UTC).strftime("%m")- )- date_path.mkdir(parents=True, exist_ok=True)+ # Create simple flat directory structure - all PDFs in one folder+ pdf_path = Path(self.library_root) / "pdfs"+ pdf_path.mkdir(parents=True, exist_ok=True)- # Save file- file_path = str(date_path / filename)+ # Save file with unique name+ file_path = str(pdf_path / filename)with open(file_path, "wb") as f:f.write(content)- # Create symlink in by_domain directory- domain_path = Path(self.library_root) / "by_domain" / domain- domain_path.mkdir(parents=True, exist_ok=True)-- symlink_path = domain_path / filename- if not symlink_path.exists():- symlink_path.symlink_to(file_path)-return file_pathdef _download_generic(self, url: str) -> Optional[bytes]:@@ -414,9 +451,20 @@ class DownloadService:return Nonedef _download_pubmed(self, url: str) -> Optional[bytes]:- """Download from PubMed Central."""+ """Download from PubMed/PubMed Central with rate limiting."""try:- # Extract PMC ID and construct PDF URL+ # Apply rate limiting for PubMed requests+ current_time = time.time()+ time_since_last = current_time - self._last_pubmed_request+ if time_since_last < self._pubmed_delay:+ sleep_time = self._pubmed_delay - time_since_last+ logger.debug(+ f"Rate limiting: sleeping {sleep_time:.2f}s before PubMed request"+ )+ time.sleep(sleep_time)+ self._last_pubmed_request = time.time()++ # If it's already a PMC article, download directlyif "/articles/PMC" in url:pmc_match = re.search(r"(PMC\d+)", url)if pmc_match:@@ -424,6 +472,57 @@ class DownloadService:pdf_url = f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/"return self._download_generic(pdf_url)+ # If it's a regular PubMed URL, try to find PMC version+ elif "pubmed.ncbi.nlm.nih.gov" in url:+ # Extract PMID from URL+ pmid_match = re.search(r"/(\d+)/?", url)+ if pmid_match:+ pmid = pmid_match.group(1)+ logger.info(+ f"Attempting to find PMC version for PMID: {pmid}"+ )++ # Try to fetch the PubMed page to check for PMC availability+ # This is a simple approach - check if PMC link exists+ try:+ headers = {+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"+ }+ response = requests.get(+ url, headers=headers, timeout=10+ )+ if response.status_code == 200:+ # Look for PMC ID in the page+ pmc_match = re.search(r"PMC\d+", response.text)+ if pmc_match:+ pmc_id = pmc_match.group(0)+ logger.info(+ f"Found PMC ID: {pmc_id} for PMID: {pmid}"+ )+ pdf_url = f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/"++ # Add delay before downloading PDF+ time.sleep(self._pubmed_delay)++ pdf_content = self._download_generic(pdf_url)+ if pdf_content:+ return pdf_content+ else:+ logger.info(+ f"No PMC version found for PMID: {pmid}"+ )+ except requests.exceptions.HTTPError as e:+ if e.response.status_code == 429:+ logger.warning(+ "Rate limited by PubMed, increasing delay"+ )+ self._pubmed_delay = min(+ self._pubmed_delay * 2, 5.0+ ) # Max 5 seconds+ raise+ except Exception as e:+ logger.debug(f"Could not check for PMC version: {e}")+return self._download_generic(url)except Exception:logger.exception("PubMed download failed")diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex 11ca6e18f3..f7fd793832 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -14,7 +14,7 @@ from pathlib import Pathfrom typing import Dict, List, Optionalfrom loguru import logger-from sqlalchemy import and_, or_, func, Integer+from sqlalchemy import and_, or_, func, Integer, casefrom ...database.models.download_tracker import DownloadTrackerfrom ...database.models.library import LibraryDocument@@ -55,10 +55,38 @@ class LibraryService:func.count(func.distinct(LibraryDocument.research_id))).scalar()- # Get domain stats- domain_count = session.query(- func.count(func.distinct(LibraryDocument.domain))- ).scalar()+ # Get domain stats - count unique domains from URLs+ # Extract domain from original_url using SQL functions+ from sqlalchemy import case, func as sql_func++ # Count unique domains by extracting them from URLs+ domain_subquery = session.query(+ sql_func.distinct(+ case(+ (+ LibraryDocument.original_url.like("%arxiv.org%"),+ "arxiv.org",+ ),+ (+ LibraryDocument.original_url.like("%pubmed%"),+ "pubmed",+ ),+ (+ LibraryDocument.original_url.like(+ "%ncbi.nlm.nih.gov%"+ ),+ "pubmed",+ ),+ else_="other",+ )+ )+ ).subquery()++ domain_count = (+ session.query(sql_func.count())+ .select_from(domain_subquery)+ .scalar()+ )# Get download tracker statspending_downloads = (@@ -141,7 +169,10 @@ class LibraryService:))else:- query = query.filter(LibraryDocument.domain == domain)+ # For specific domain, filter by URL pattern+ query = query.filter(+ LibraryDocument.original_url.like(f"%{domain}%")+ )if file_type:query = query.filter(LibraryDocument.file_type == file_type)@@ -231,7 +262,12 @@ class LibraryService:session.query(ResearchHistory,func.count(ResearchResource.id).label("total_resources"),- func.count(LibraryDocument.id).label("downloaded_count"),+ func.count(+ case(+ (LibraryDocument.download_status == "completed", 1),+ else_=None,+ )+ ).label("downloaded_count"),func.sum(func.cast(ResearchResource.url.like("%.pdf")@@ -270,21 +306,21 @@ class LibraryService:.first())- # Get domain breakdown+ # Get domain breakdown - simplified version+ # Extract domain from URLs using SQL case statementsdomains = (session.query(- func.substring(- ResearchResource.url,- func.position("://" in ResearchResource.url) + 3,- func.position(- "/"- in func.substring(- ResearchResource.url,- func.position("://" in ResearchResource.url)- + 3,- )- )- - 1,+ case(+ (+ ResearchResource.url.like("%arxiv.org%"),+ "arxiv.org",+ ),+ (ResearchResource.url.like("%pubmed%"), "pubmed"),+ (+ ResearchResource.url.like("%ncbi.nlm.nih.gov%"),+ "pubmed",+ ),+ else_="other",).label("domain"),func.count().label("count"),)@@ -313,6 +349,74 @@ class LibraryService:return research_list+ def get_document_by_id(self, doc_id: int) -> Optional[Dict]:+ """+ Get a specific document by its ID.++ Returns document information with file path.+ """+ with get_user_db_session(self.username) as session:+ # Query for the specific document+ result = (+ session.query(+ LibraryDocument, ResearchResource, ResearchHistory+ )+ .join(+ ResearchResource,+ LibraryDocument.resource_id == ResearchResource.id,+ )+ .join(+ ResearchHistory,+ LibraryDocument.research_id == ResearchHistory.id,+ )+ .filter(LibraryDocument.id == doc_id)+ .first()+ )++ if not result:+ return None++ doc, resource, research = result++ # Get download tracker info+ tracker = (+ session.query(DownloadTracker)+ .filter_by(url_hash=self._get_url_hash(resource.url))+ .first()+ )++ return {+ "id": doc.id,+ "resource_id": doc.resource_id,+ "research_id": doc.research_id,+ "document_title": doc.title or resource.title,+ "original_url": doc.original_url or resource.url,+ "file_path": doc.file_path,+ "file_absolute_path": tracker.file_absolute_path+ if tracker+ else doc.file_path,+ "file_name": Path(doc.file_path).name+ if doc.file_path+ else None,+ "file_size": doc.file_size,+ "file_type": doc.file_type,+ "mime_type": doc.mime_type,+ "domain": self._extract_domain(resource.url),+ "download_status": doc.download_status,+ "downloaded_at": doc.downloaded_at.isoformat()+ if doc.downloaded_at and hasattr(doc.downloaded_at, "isoformat")+ else str(doc.downloaded_at)+ if doc.downloaded_at+ else None,+ "favorite": doc.favorite,+ "research_title": research.query[:100],+ "research_created_at": research.created_at+ if isinstance(research.created_at, str)+ else research.created_at.isoformat()+ if research.created_at+ else None,+ }+def toggle_favorite(self, document_id: int) -> bool:"""Toggle favorite status of a document."""with get_user_db_session(self.username) as session:@@ -393,10 +497,35 @@ class LibraryService:def get_unique_domains(self) -> List[str]:"""Get list of unique domains in library."""+ from sqlalchemy import case+with get_user_db_session(self.username) as session:+ # Extract domains from URLs using SQL case statementdomains = (- session.query(func.distinct(LibraryDocument.domain))- .filter(LibraryDocument.domain.isnot(None))+ session.query(+ func.distinct(+ case(+ (+ LibraryDocument.original_url.like(+ "%arxiv.org%"+ ),+ "arxiv.org",+ ),+ (+ LibraryDocument.original_url.like("%pubmed%"),+ "pubmed",+ ),+ (+ LibraryDocument.original_url.like(+ "%ncbi.nlm.nih.gov%"+ ),+ "pubmed",+ ),+ else_="other",+ )+ )+ )+ .filter(LibraryDocument.original_url.isnot(None)).all())@@ -436,3 +565,109 @@ class LibraryService:)).expanduser())++ def sync_library_with_filesystem(self) -> Dict:+ """+ Sync library database with filesystem.+ Check which files exist and update database accordingly.++ Returns:+ Statistics about the sync operation+ """+ with get_user_db_session(self.username) as session:+ # Get all documents marked as downloaded+ documents = (+ session.query(LibraryDocument)+ .filter_by(download_status="completed")+ .all()+ )++ stats = {+ "total_documents": len(documents),+ "files_found": 0,+ "files_missing": 0,+ "trackers_updated": 0,+ "missing_files": [],+ }++ for doc in documents:+ # Get download tracker+ tracker = (+ session.query(DownloadTracker)+ .filter_by(url_hash=self._get_url_hash(doc.original_url))+ .first()+ )++ if tracker and tracker.file_absolute_path:+ # Check if file exists+ file_path = Path(tracker.file_absolute_path)+ if file_path.exists():+ stats["files_found"] += 1+ else:+ # File missing - delete the document entry so it can be re-downloaded+ stats["files_missing"] += 1+ stats["missing_files"].append(+ {+ "id": doc.id,+ "title": doc.title,+ "path": tracker.file_absolute_path,+ "url": doc.original_url,+ }+ )++ # Reset tracker+ tracker.is_downloaded = False+ tracker.file_absolute_path = None+ tracker.file_path = None++ # Delete the document entry so it can be re-queued+ session.delete(doc)+ stats["trackers_updated"] += 1+ else:+ # No tracker or path - delete the document entry+ stats["files_missing"] += 1+ session.delete(doc)++ session.commit()+ logger.info(+ f"Library sync completed: {stats['files_found']} found, {stats['files_missing']} missing"+ )++ return stats++ def mark_for_redownload(self, document_ids: List[int]) -> int:+ """+ Mark specific documents for re-download.++ Args:+ document_ids: List of document IDs to mark for re-download++ Returns:+ Number of documents marked+ """+ with get_user_db_session(self.username) as session:+ count = 0+ for doc_id in document_ids:+ doc = session.query(LibraryDocument).get(doc_id)+ if doc:+ # Get tracker and reset it+ tracker = (+ session.query(DownloadTracker)+ .filter_by(+ url_hash=self._get_url_hash(doc.original_url)+ )+ .first()+ )++ if tracker:+ tracker.is_downloaded = False+ tracker.file_absolute_path = None+ tracker.file_path = None++ # Mark document as pending+ doc.download_status = "pending"+ count += 1++ session.commit()+ logger.info(f"Marked {count} documents for re-download")+ return countdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex c2d8a928d3..e1a3e5b453 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -955,7 +955,6 @@ def run_research_process("generated_at": datetime.now(UTC).isoformat(),})- logger.info(f"Metadata after update: {metadata}")# Use the helper function for consistent duration calculationduration_seconds = calculate_duration(diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.htmlindex 4572047803..1f54dbf9ea 100644--- a/src/local_deep_research/web/templates/pages/download_manager.html+++ b/src/local_deep_research/web/templates/pages/download_manager.html@@ -43,8 +43,8 @@<label>Research Mode</label><select id="filter-mode" class="form-control"><option value="">All Modes</option>- <option value="quick_summary">Quick Summary</option>- <option value="detailed_report">Detailed Report</option>+ <option value="quick">Quick</option>+ <option value="detailed">Detailed</option></select></div>@@ -97,7 +97,9 @@<div class="research-item" data-id="{{ research.id }}"data-mode="{{ research.mode }}"data-rating="{{ research.rating or 0 }}"- data-date="{{ research.created_at }}">+ data-date="{{ research.created_at }}"+ data-downloadable="{{ research.downloadable_count }}"+ data-downloaded="{{ research.downloaded_count }}"><!-- Checkbox and Basic Info --><div class="research-header">@@ -109,10 +111,10 @@<h3>{{ research.title or research.query[:80] }}</h3><div class="research-meta"><span class="meta-item">- <i class="fas fa-calendar"></i> {{ research.created_at|format_date }}+ <i class="fas fa-calendar"></i> <span class="research-date" data-date="{{ research.created_at }}">{{ research.created_at }}</span></span><span class="meta-item">- <i class="fas fa-clock"></i> {{ research.duration_seconds|format_duration }}+ <i class="fas fa-clock"></i> <span class="research-duration" data-seconds="{{ research.duration_seconds }}">{{ research.duration_seconds }}s</span></span><span class="meta-item mode-badge {{ research.mode }}">{{ research.mode|replace('_', ' ')|title }}@@ -446,50 +448,194 @@border-top: 1px solid var(--border-color);}+.research-actions .btn {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ color: var(--text-primary);+ padding: 6px 12px;+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.2s;+ font-size: 14px;+}++.research-actions .btn:hover {+ background: var(--primary-color);+ color: white;+ border-color: var(--primary-color);+}+.bulk-actions {display: flex;gap: 10px;margin-top: 10px;}+.bulk-actions button {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ color: var(--text-primary);+ padding: 6px 12px;+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.2s;+}++.bulk-actions button:hover {+ background: var(--primary-color);+ color: white;+ border-color: var(--primary-color);+}++/* Modal Styles */+.modal {+ position: fixed;+ z-index: 1000;+ left: 0;+ top: 0;+ width: 100%;+ height: 100%;+ background-color: rgba(0, 0, 0, 0.7);+ display: flex;+ align-items: center;+ justify-content: center;+}++.modal-content {+ background: var(--bg-primary);+ border-radius: 12px;+ width: 90%;+ max-width: 600px;+ max-height: 80vh;+ display: flex;+ flex-direction: column;+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border-color);+}++.modal-header {+ padding: 20px;+ border-bottom: 1px solid var(--border-color);+}++.modal-header h2 {+ margin: 0;+ color: var(--text-primary);+}++.modal-body {+ padding: 20px;+ flex: 1;+ overflow-y: auto;+}++.modal-footer {+ padding: 15px 20px;+ border-top: 1px solid var(--border-color);+ display: flex;+ justify-content: flex-end;+ gap: 10px;+}++.modal-footer .btn {+ padding: 8px 16px;+ border-radius: 6px;+ border: 1px solid var(--border-color);+ background: var(--bg-secondary);+ color: var(--text-primary);+ cursor: pointer;+ transition: all 0.2s;+}++.modal-footer .btn:hover {+ background: var(--primary-color);+ color: white;+}++.modal-footer .btn-danger {+ background: #dc3545;+ color: white;+ border-color: #dc3545;+}++.modal-footer .btn-danger:hover {+ background: #c82333;+ border-color: #bd2130;+}+/* Progress Modal */.overall-progress {- margin-bottom: 20px;+ margin-bottom: 25px;+}++.overall-progress p {+ text-align: center;+ margin-top: 10px;+ font-size: 14px;+ color: var(--text-secondary);}.progress-bar {- height: 30px;- background: var(--bg-secondary);- border-radius: 15px;+ height: 35px;+ background: #2a2a2a;+ border-radius: 20px;overflow: hidden;+ position: relative;+ border: 1px solid var(--border-color);}.progress-fill {height: 100%;- background: var(--primary-color);- transition: width 0.3s;+ background: linear-gradient(90deg, #4CAF50, #45a049);+ transition: width 0.3s ease;+ display: flex;+ align-items: center;+ justify-content: center;+ color: white;+ font-weight: bold;+ position: relative;+}++.progress-fill::after {+ content: attr(data-percent);+ position: absolute;+ right: 10px;+ color: white;+ font-size: 14px;}.download-log {max-height: 400px;overflow-y: auto;- padding: 10px;- background: var(--bg-secondary);+ padding: 15px;+ background: #1a1a1a;border-radius: 8px;+ border: 1px solid var(--border-color);}.download-entry {- padding: 8px;- margin-bottom: 5px;- border-left: 3px solid var(--border-color);+ padding: 10px 12px;+ margin-bottom: 8px;+ border-left: 4px solid var(--border-color);+ background: var(--bg-secondary);+ border-radius: 4px;+ font-size: 14px;+ color: var(--text-primary);}.download-entry.success {- border-color: var(--success-color);+ border-left-color: #4CAF50;+ background: rgba(76, 175, 80, 0.1);}.download-entry.error {- border-color: var(--danger-color);+ border-left-color: #f44336;+ background: rgba(244, 67, 54, 0.1);+}++.download-entry.cancelled {+ border-left-color: #ff9800;+ background: rgba(255, 152, 0, 0.1);}</style>@@ -553,29 +699,65 @@ document.getElementById('download-selected').addEventListener('click', () => {startBulkDownload(Array.from(selectedResearches));});-async function startBulkDownload(researchIds) {- const response = await fetch('/api/library/download-bulk', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({research_ids: researchIds})- });-- const reader = response.body.getReader();- const decoder = new TextDecoder();-- while (true) {- const {done, value} = await reader.read();- if (done) break;+let currentDownloadController = null;- const chunk = decoder.decode(value);- const lines = chunk.split('\n');-- for (const line of lines) {- if (line.startsWith('data: ')) {- const data = JSON.parse(line.slice(6));- updateProgress(data);+async function startBulkDownload(researchIds) {+ // Get CSRF token from meta tag+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');++ // Create abort controller for cancellation+ currentDownloadController = new AbortController();++ try {+ const response = await fetch('/library/api/download-bulk', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({research_ids: researchIds}),+ signal: currentDownloadController.signal+ });++ const reader = response.body.getReader();+ const decoder = new TextDecoder();++ while (true) {+ const {done, value} = await reader.read();+ if (done) break;++ const chunk = decoder.decode(value);+ const lines = chunk.split('\n');++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ const data = JSON.parse(line.slice(6));+ updateProgress(data);++ // Check if download is complete+ if (data.complete) {+ currentDownloadController = null;+ setTimeout(() => {+ closeProgressModal();+ location.reload();+ }, 2000);+ }+ }}}+ } catch (error) {+ if (error.name === 'AbortError') {+ console.log('Download cancelled by user');+ const log = document.getElementById('download-log');+ const entry = document.createElement('div');+ entry.className = 'download-entry cancelled';+ entry.innerHTML = '<strong>Download cancelled by user</strong>';+ log.appendChild(entry);+ } else {+ console.error('Download error:', error);+ }+ } finally {+ currentDownloadController = null;}}@@ -586,6 +768,7 @@ function updateProgress(data) {const log = document.getElementById('download-log');progressBar.style.width = `${data.progress}%`;+ progressBar.setAttribute('data-percent', `${data.progress}%`);currentCount.textContent = data.current;totalCount.textContent = data.total;@@ -609,7 +792,7 @@ function downloadResearch(researchId) {// Navigationfunction viewResearch(researchId) {- window.open(`/research/${researchId}`, '_blank');+ window.open(`/results/${researchId}`, '_blank');}function viewDownloaded(researchId) {@@ -625,6 +808,7 @@ document.getElementById('search-research').addEventListener('input', filterReseafunction filterResearch() {const mode = document.getElementById('filter-mode').value;const rating = document.getElementById('filter-rating').value;+ const pdfFilter = document.getElementById('filter-pdfs').value;const search = document.getElementById('search-research').value.toLowerCase();document.querySelectorAll('.research-item').forEach(item => {@@ -632,6 +816,17 @@ function filterResearch() {if (mode && item.dataset.mode !== mode) show = false;if (rating && parseInt(item.dataset.rating) < parseInt(rating)) show = false;++ // Handle PDF filter+ if (pdfFilter) {+ const downloadable = parseInt(item.dataset.downloadable || 0);+ const downloaded = parseInt(item.dataset.downloaded || 0);+ const availablePdfs = downloadable - downloaded;++ if (pdfFilter === 'yes' && availablePdfs <= 0) show = false;+ if (pdfFilter === 'no' && availablePdfs > 0) show = false;+ }+if (search && !item.textContent.toLowerCase().includes(search)) show = false;item.style.display = show ? '' : 'none';@@ -642,5 +837,68 @@ function filterResearch() {function closeProgressModal() {document.getElementById('download-progress-modal').style.display = 'none';}++// Cancel downloads+function cancelDownloads() {+ if (currentDownloadController) {+ currentDownloadController.abort();+ currentDownloadController = null;++ // Update UI to show cancellation+ const progressBar = document.getElementById('overall-progress');+ progressBar.style.backgroundColor = '#f44336';++ // Add cancellation message+ const log = document.getElementById('download-log');+ const entry = document.createElement('div');+ entry.className = 'download-entry cancelled';+ entry.innerHTML = '<strong style="color: #f44336;">Download process cancelled</strong>';+ log.appendChild(entry);++ // Close modal after a delay+ setTimeout(() => {+ closeProgressModal();+ location.reload();+ }, 1500);+ } else {+ // If no active download, just close modal+ closeProgressModal();+ }+}++// Format dates and durations on page load+document.addEventListener('DOMContentLoaded', function() {+ // Format dates+ document.querySelectorAll('.research-date').forEach(span => {+ const dateStr = span.dataset.date;+ if (dateStr) {+ const date = new Date(dateStr);+ if (!isNaN(date)) {+ span.textContent = date.toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ });+ }+ }+ });++ // Format durations+ document.querySelectorAll('.research-duration').forEach(span => {+ const seconds = parseInt(span.dataset.seconds);+ if (!isNaN(seconds)) {+ const hours = Math.floor(seconds / 3600);+ const minutes = Math.floor((seconds % 3600) / 60);+ const secs = seconds % 60;++ let duration = '';+ if (hours > 0) duration += hours + 'h ';+ if (minutes > 0) duration += minutes + 'm ';+ duration += secs + 's';++ span.textContent = duration;+ }+ });+});</script>{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 1ea753bf4c..870aa362e9 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -7,6 +7,9 @@<div class="library-header"><h1>Research Library</h1><div class="header-actions">+ <button class="btn btn-secondary" onclick="syncLibrary()" title="Check if files exist and sync with filesystem">+ <i class="fas fa-sync"></i> Sync Library+ </button><button class="btn btn-primary" onclick="window.location.href='/library/download-manager'"><i class="fas fa-download"></i> Download Manager</button>@@ -121,7 +124,7 @@<a href="#" onclick="openPDF({{ doc.id }})">Open PDF</a><a href="#" onclick="showFileLocation('{{ doc.file_absolute_path }}')">Show in Folder</a><a href="{{ doc.original_url }}" target="_blank">View Original</a>- <a href="/research/{{ doc.research_id }}">View Research</a>+ <a href="/results/{{ doc.research_id }}">View Research Results</a><hr><a href="#" onclick="deleteDocument({{ doc.id }})" class="text-danger">Delete</a></div>@@ -142,7 +145,7 @@<div class="doc-metadata"><span class="meta-item"><i class="fas fa-calendar"></i>- {{ doc.downloaded_at|format_date }}+ <span class="download-date" data-date="{{ doc.downloaded_at }}">{{ doc.downloaded_at }}</span></span><span class="meta-item"><i class="fas fa-file"></i>@@ -172,7 +175,7 @@<!-- Research Info --><div class="research-info"><span class="research-link">- From: <a href="/research/{{ doc.research_id }}" onclick="event.stopPropagation()">+ From: <a href="/results/{{ doc.research_id }}" onclick="event.stopPropagation()">{{ doc.research_title|truncate(40) }}</a></span>@@ -454,7 +457,7 @@<script>// Open PDF in modalfunction openPDF(docId) {- fetch(`/api/library/document/${docId}/pdf-url`)+ fetch(`/library/api/document/${docId}/pdf-url`).then(res => res.json()).then(data => {document.getElementById('pdf-viewer').src = data.url;@@ -472,7 +475,7 @@ function closePDFModal() {// Show file location in systemfunction showFileLocation(path) {// This would need platform-specific implementation- fetch('/api/library/open-folder', {+ fetch('/library/api/open-folder', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({path: path})@@ -487,7 +490,7 @@ function copyPath(path) {// Toggle favoritefunction toggleFavorite(docId) {- fetch(`/api/library/document/${docId}/favorite`, {+ fetch(`/library/api/document/${docId}/favorite`, {method: 'POST'}).then(() => {// Update UI@@ -497,7 +500,7 @@ function toggleFavorite(docId) {// Delete documentfunction deleteDocument(docId) {if (confirm('Delete this document from library?')) {- fetch(`/api/library/document/${docId}`, {+ fetch(`/library/api/document/${docId}`, {method: 'DELETE'}).then(() => {location.reload();@@ -533,6 +536,73 @@ function filterDocuments() {});}+// Sync library with filesystem+async function syncLibrary() {+ const btn = event.target.closest('button');+ const originalContent = btn.innerHTML;+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Syncing...';+ btn.disabled = true;++ try {+ // Get CSRF token+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');++ const response = await fetch('/library/api/sync-library', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ }+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const stats = await response.json();++ // Show results+ let message = `Sync Complete!\n\nFiles found: ${stats.files_found}\nFiles missing: ${stats.files_missing}`;++ if (stats.files_missing > 0) {+ message += `\n\n${stats.files_missing} files were marked as missing and can be re-downloaded.`;++ // Ask if user wants to re-download missing files+ if (confirm(message + '\n\nDo you want to go to Download Manager to re-download missing files?')) {+ window.location.href = '/library/download-manager';+ } else {+ location.reload();+ }+ } else {+ alert(message);+ }++ } catch (error) {+ console.error('Sync failed:', error);+ alert('Failed to sync library. Please try again.');+ } finally {+ btn.innerHTML = originalContent;+ btn.disabled = false;+ }+}++// Format dates on page load+document.addEventListener('DOMContentLoaded', function() {+ document.querySelectorAll('.download-date').forEach(span => {+ const dateStr = span.dataset.date;+ if (dateStr) {+ const date = new Date(dateStr);+ if (!isNaN(date)) {+ span.textContent = date.toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric'+ });+ }+ }+ });+});+// View toggledocument.querySelectorAll('.view-toggle button').forEach(btn => {btn.addEventListener('click', () => {