Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: add multi-collection download support

LearningCircuit3bec5dc58726
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 3b5c76fff6..dfd415c9f4 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -30,6 +30,7 @@ from ...database.models.library import (
Document as Document,
DocumentStatus,
DownloadQueue as LibraryDownloadQueue,
+ Collection,
)
from ...library.download_management import ResourceFilter
from ..services.download_service import DownloadService
@@ -285,6 +286,32 @@ def get_library_stats():
return jsonify(stats)
+@library_bp.route("/api/collections/list")
+@login_required
+def get_collections_list():
+ """Get list of all collections for dropdown selection."""
+ username = session.get("username")
+
+ with get_user_db_session(username) as db_session:
+ collections = (
+ db_session.query(Collection).order_by(Collection.name).all()
+ )
+
+ return jsonify(
+ {
+ "success": True,
+ "collections": [
+ {
+ "id": col.id,
+ "name": col.name,
+ "description": col.description,
+ }
+ for col in collections
+ ],
+ }
+ )
+
+
@library_bp.route("/api/documents")
@login_required
def get_documents():
@@ -630,7 +657,11 @@ def download_research_pdfs(research_id):
username = session.get("username")
service = DownloadService(username)
- queued = service.queue_research_downloads(research_id)
+ # Get optional collection_id from request body
+ data = request.json or {}
+ collection_id = data.get("collection_id")
+
+ queued = service.queue_research_downloads(research_id, collection_id)
# Start processing queue (in production, this would be a background task)
# For now, we'll process synchronously
@@ -647,6 +678,9 @@ def download_bulk():
data = request.json
research_ids = data.get("research_ids", [])
mode = data.get("mode", "pdf") # pdf or text_only
+ collection_id = data.get(
+ "collection_id"
+ ) # Optional: target collection for downloads
if not research_ids:
return jsonify({"error": "No research IDs provided"}), 400
@@ -724,7 +758,9 @@ def download_bulk():
# If no items queued yet, queue them now
if not queue_items:
try:
- download_service.queue_research_downloads(research_id)
+ download_service.queue_research_downloads(
+ research_id, collection_id
+ )
# Re-fetch queue items
queue_items = (
session.query(LibraryDownloadQueue)
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 808b50cd71..0afc5e12e8 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -216,15 +216,27 @@ class DownloadService:
logger.warning(f"Could not extract text for {url}")
return None
- def queue_research_downloads(self, research_id: str) -> int:
+ def queue_research_downloads(
+ self, research_id: str, collection_id: Optional[str] = None
+ ) -> int:
"""
Queue all downloadable PDFs from a research session.
+ Args:
+ research_id: The research session ID
+ collection_id: Optional target collection ID (defaults to Library if not provided)
+
Returns:
Number of items queued
"""
queued = 0
+ # Get default library collection if no collection_id provided
+ if not collection_id:
+ from ...database.library_init import get_default_library_id
+
+ collection_id = get_default_library_id(self.username)
+
with get_user_db_session(self.username, self.password) as session:
# Get all resources for this research
resources = (
@@ -268,12 +280,14 @@ class DownloadService:
# Reset the existing queue entry
any_queue.status = DocumentStatus.PENDING
any_queue.research_id = research_id
+ any_queue.collection_id = collection_id
queued += 1
else:
# Add new queue entry
queue_entry = LibraryDownloadQueue(
resource_id=resource.id,
research_id=research_id,
+ collection_id=collection_id,
priority=0,
status=DocumentStatus.PENDING,
)
@@ -281,7 +295,9 @@ class DownloadService:
queued += 1
session.commit()
- logger.info(f"Queued {queued} downloads for research {research_id}")
+ logger.info(
+ f"Queued {queued} downloads for research {research_id} to collection {collection_id}"
+ )
return queued
@@ -335,6 +351,18 @@ class DownloadService:
)
return True, None
+ # Get collection_id from queue entry if it exists
+ queue_entry = (
+ session.query(LibraryDownloadQueue)
+ .filter_by(resource_id=resource_id)
+ .first()
+ )
+ collection_id = (
+ queue_entry.collection_id
+ if queue_entry and queue_entry.collection_id
+ else None
+ )
+
# Create download tracker entry
url_hash = self._get_url_hash(resource.url)
tracker = (
@@ -354,7 +382,9 @@ class DownloadService:
session.commit()
# Attempt download
- result = self._download_pdf(resource, tracker, session)
+ result = self._download_pdf(
+ resource, tracker, session, collection_id
+ )
# Get skip reason if failed
skip_reason = None
@@ -408,10 +438,17 @@ class DownloadService:
resource: ResearchResource,
tracker: DownloadTracker,
session: Session,
+ collection_id: Optional[str] = None,
) -> Tuple[bool, Optional[str]]:
"""
Perform the actual PDF download.
+ Args:
+ resource: The research resource to download
+ tracker: Download tracker for this URL
+ session: Database session
+ collection_id: Optional target collection ID (defaults to Library if not provided)
+
Returns:
Tuple of (success: bool, skip_reason: Optional[str])
"""
@@ -529,8 +566,9 @@ class DownloadService:
source_type_id = get_source_type_id(
self.username, "research_download"
)
- library_collection_id = get_default_library_id(
- self.username
+ # Use provided collection_id or default to Library
+ library_collection_id = (
+ collection_id or get_default_library_id(self.username)
)
except Exception:
logger.exception(
diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.html
index cf6f655567..616fc6c241 100644
--- a/src/local_deep_research/web/templates/pages/download_manager.html
+++ b/src/local_deep_research/web/templates/pages/download_manager.html
@@ -10,6 +10,14 @@
<button class="btn btn-secondary" onclick="window.location.href='/library'">
<i class="fas fa-book"></i> Back to Library
</button>
+ <div class="ldr-collection-selector" style="margin: 0 15px;">
+ <label for="target-collection" style="font-size: 0.9em; color: var(--text-secondary, #999); margin-right: 8px;">
+ <i class="fas fa-folder"></i> Target Collection:
+ </label>
+ <select id="target-collection" class="form-control" style="width: 200px; display: inline-block;">
+ <option value="">Loading collections...</option>
+ </select>
+ </div>
<div class="ldr-btn-group ldr-download-buttons">
<button class="btn btn-success" id="download-pdfs" disabled
{% if not enable_pdf_storage %}
@@ -1014,6 +1022,45 @@
<script>
let selectedResearches = new Set();
+// Load collections for dropdown
+async function loadCollections() {
+ try {
+ const response = await fetch('/library/api/collections/list');
+ const data = await response.json();
+
+ const select = document.getElementById('target-collection');
+ select.innerHTML = ''; // Clear loading message
+
+ if (data.success && data.collections && data.collections.length > 0) {
+ data.collections.forEach(collection => {
+ const option = document.createElement('option');
+ option.value = collection.id;
+ option.textContent = collection.name;
+
+ // Select "Library" as default if it exists
+ if (collection.name === 'Library') {
+ option.selected = true;
+ }
+
+ select.appendChild(option);
+ });
+ } else {
+ // Fallback if no collections
+ const option = document.createElement('option');
+ option.value = '';
+ option.textContent = 'No collections available';
+ select.appendChild(option);
+ }
+ } catch (error) {
+ console.error('Error loading collections:', error);
+ const select = document.getElementById('target-collection');
+ select.innerHTML = '<option value="">Error loading collections</option>';
+ }
+}
+
+// Load collections on page load
+loadCollections();
+
// Handle checkbox selection
document.querySelectorAll('.ldr-research-select').forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
@@ -1093,6 +1140,10 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
// Get CSRF token from meta tag
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+ // Get selected collection_id
+ const collectionSelect = document.getElementById('target-collection');
+ const collectionId = collectionSelect ? collectionSelect.value : null;
+
// Create abort controller for cancellation
currentDownloadController = new AbortController();
@@ -1104,16 +1155,23 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
document.querySelector('#download-progress-modal h2').textContent = modalTitles[mode] || 'Processing';
try {
+ const requestBody = {
+ research_ids: researchIds,
+ mode: mode
+ };
+
+ // Add collection_id if selected
+ if (collectionId) {
+ requestBody.collection_id = collectionId;
+ }
+
const response = await fetch('/library/api/download-bulk', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
- body: JSON.stringify({
- research_ids: researchIds,
- mode: mode
- }),
+ body: JSON.stringify(requestBody),
signal: currentDownloadController.signal
});