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.

fix(library): correct download manager total counter (was "X / 0 files") (#4685)

LearningCircuit18e52b3deb65
diff --git a/changelog.d/4660.bugfix.md b/changelog.d/4660.bugfix.md
new file mode 100644
index 0000000000..69756c93c4
--- /dev/null
+++ b/changelog.d/4660.bugfix.md
@@ -0,0 +1 @@
+Fixed the download manager progress popup showing "X / 0 files" instead of the real total. The pending-item count is now taken after the queue is populated, so the denominator reflects the actual number of papers being downloaded. The download manager now also surfaces an explicit alert when there is nothing to download (e.g., all papers already downloaded) or when queueing fails for every selected research session, instead of silently completing with "0 / 0 files".
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 5bf362cd0f..23df1edda1 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -768,12 +768,31 @@ def download_bulk():
download_service = DownloadService(username, user_password)
try:
- # Count total pending queue items across all research IDs
total = 0
current = 0
+ queue_failures = 0
+
+ # Pre-queue and count in one merged loop. queue_research_downloads
+ # opens its own session, commits, and handles dedup internally:
+ # it skips resources that are already PENDING or already backed by
+ # a COMPLETED Document, and re-queues any remaining row (e.g. a
+ # prior FAILED attempt) back to PENDING. Calling it BEFORE counting
+ # ensures the total reflects what will actually be processed
+ # (issue #4660).
+ for research_id in research_ids:
+ try:
+ download_service.queue_research_downloads(
+ research_id, collection_id
+ )
+ except Exception:
+ queue_failures += 1
+ logger.exception(
+ f"Error queueing downloads for "
+ f"user={username} research={research_id} "
+ f"collection={collection_id}"
+ )
- with get_user_db_session(username) as session:
- for research_id in research_ids:
+ with get_user_db_session(username) as session:
count = (
session.query(LibraryDownloadQueue)
.filter_by(
@@ -782,21 +801,39 @@ def download_bulk():
)
.count()
)
- total += count
- logger.debug(
- f"[PROGRESS_DEBUG] Research {research_id}: {count} pending items in queue"
- )
+ total += count
+ logger.debug(
+ f"Research {research_id}: {count} pending items in queue"
+ )
- logger.info(
- f"[PROGRESS_DEBUG] Total pending downloads across all research: {total}"
- )
+ logger.info(f"Total pending downloads across all research: {total}")
yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"
+ # If the pre-pass yielded nothing to process, surface it as an
+ # error so the UI alerts instead of silently completing with
+ # "0 / 0 files" success. Distinguish queue failure from a
+ # legitimate "nothing left to download" state.
+ if total == 0:
+ if queue_failures > 0:
+ error_msg = (
+ f"Download failed to start: queueing failed for "
+ f"{queue_failures} of {len(research_ids)} "
+ f"research session(s). Check server logs."
+ )
+ else:
+ error_msg = (
+ "No new papers to download for the selected "
+ "research session(s)."
+ )
+ yield f"data: {json.dumps({'progress': 100, 'current': 0, 'total': 0, 'complete': True, 'error': error_msg})}\n\n"
+ return
+
# Process each research
for research_id in research_ids:
# Get queued downloads for this research
with get_user_db_session(username) as session:
- # Get pending queue items for this research
+ # Get pending queue items for this research (pre-pass
+ # above already ensured items are queued)
queue_items = (
session.query(LibraryDownloadQueue)
.filter_by(
@@ -806,50 +843,13 @@ def download_bulk():
.all()
)
- # If no items queued yet, queue them now
- if not queue_items:
- try:
- download_service.queue_research_downloads(
- research_id, collection_id
- )
- # Re-fetch queue items
- queue_items = (
- session.query(LibraryDownloadQueue)
- .filter_by(
- research_id=research_id, status="pending"
- )
- .all()
- )
- except Exception:
- logger.exception(
- f"Error queueing downloads for research {research_id}"
- )
- # Continue with empty queue_items
- queue_items = []
-
# Process each queued item
for queue_item in queue_items:
- logger.debug(
- f"[PROGRESS_DEBUG] Before increment: current={current} (type: {type(current)}), total={total} (type: {type(total)})"
- )
current += 1
- logger.debug(
- f"[PROGRESS_DEBUG] After increment: current={current} (type: {type(current)})"
- )
-
- # Check for division issues
- if total is None:
- logger.error(
- "[PROGRESS_DEBUG] ERROR: total is None! Setting to 0 to avoid crash"
- )
- total = 0
progress = (
int((current / total) * 100) if total > 0 else 100
)
- logger.debug(
- f"[PROGRESS_DEBUG] Calculated progress: {progress}%"
- )
# Get resource info
resource = session.query(ResearchResource).get(
@@ -971,10 +971,9 @@ def download_bulk():
f"Sending skip reason to UI: {skip_reason}"
)
- logger.info(f"Update data being sent: {update_data}")
yield f"data: {json.dumps(update_data)}\n\n"
- yield f"data: {json.dumps({'progress': 100, 'current': total, 'total': total, 'complete': True})}\n\n"
+ yield f"data: {json.dumps({'progress': 100, 'current': current, 'total': total, 'complete': True})}\n\n"
finally:
from ...utilities.resource_utils import safe_close
diff --git a/tests/research_library/routes/test_library_routes_extra_coverage.py b/tests/research_library/routes/test_library_routes_extra_coverage.py
index 5267ea0b0a..4f6bc88fa2 100644
--- a/tests/research_library/routes/test_library_routes_extra_coverage.py
+++ b/tests/research_library/routes/test_library_routes_extra_coverage.py
@@ -16,6 +16,7 @@ and test_library_routes_deep_coverage.py:
- get_research_sources: malformed URL falls back to empty domain
"""
+import json
from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
@@ -346,6 +347,15 @@ class TestDownloadAllTextSseStream:
class TestDownloadBulkSseStream:
"""Exercise the SSE generator in download_bulk with queue items present."""
+ @staticmethod
+ def _collect_sse_events(body):
+ """Parse 'data: <json>' SSE lines into a list of dicts."""
+ return [
+ json.loads(line[6:])
+ for line in body.split("\n")
+ if line.startswith("data: ")
+ ]
+
def test_auth_failure_in_bulk_yields_error_event(self, app):
"""When auth fails inside the generator, SSE error is emitted."""
from local_deep_research.web.exceptions import (
@@ -630,6 +640,246 @@ class TestDownloadBulkSseStream:
body = resp.data.decode()
assert "complete" in body
+ def test_initial_total_reflects_post_queue_count(self, app):
+ """Regression test for issue #4660.
+
+ Before the fix, `download_bulk` counted PENDING queue items BEFORE
+ the pre-queue pass populated them, so the initial SSE event carried
+ total=0 and the UI showed "X / 0 files". The fix moves the count
+ after `queue_research_downloads`; this test verifies both that the
+ initial event's total matches the post-queue count AND that
+ `queue_research_downloads` actually runs before the count query
+ (without the order check, a mock that always returns 3 from
+ `.count()` would satisfy the assertions even under the old code).
+ """
+ call_order = []
+
+ def _record_queue(*_args, **_kwargs):
+ call_order.append("queue")
+ return 3
+
+ def _record_count():
+ call_order.append("count")
+ return 3
+
+ queue_items = []
+ resources = []
+ for i in range(3):
+ item = Mock()
+ item.resource_id = 100 + i
+ queue_items.append(item)
+ resource = Mock()
+ resource.title = f"Paper {i}"
+ resources.append(resource)
+
+ db_session = Mock()
+ q = _build_mock_query(all_result=queue_items, count_result=3)
+ q.get.side_effect = resources
+ q.count.side_effect = _record_count
+ db_session.query = Mock(return_value=q)
+ db_session.commit = Mock()
+
+ dl_svc = Mock()
+ dl_svc.queue_research_downloads.side_effect = _record_queue
+ dl_svc.download_resource.return_value = (True, None)
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ download_service=dl_svc,
+ extra_patches=[
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close",
+ return_value=None,
+ ),
+ ],
+ ) as (client, _):
+ resp = client.post(
+ "/library/api/download-bulk",
+ json={"research_ids": ["r1"], "mode": "pdf"},
+ content_type="application/json",
+ )
+ body = resp.data.decode()
+
+ assert resp.status_code == 200, body
+ events = self._collect_sse_events(body)
+ assert events, f"No SSE events in body: {body[:500]}"
+
+ # The FIRST event is the initial progress emission. Its total must
+ # be the post-queue count (3), not 0 (which was the bug from
+ # issue #4660 — emitting total=0 because the count ran before
+ # queue_research_downloads populated the queue).
+ initial = events[0]
+ assert initial.get("total") == 3, (
+ f"Initial SSE event total should be 3 (post-queue count), "
+ f"got {initial.get('total')}. Initial event: {initial}"
+ )
+ assert initial.get("total") != 0, (
+ "Initial total=0 was the bug from issue #4660"
+ )
+ assert call_order == ["queue", "count"], (
+ f"queue_research_downloads must run BEFORE the count query "
+ f"(otherwise the count sees an empty queue and the UI shows "
+ f"'X / 0 files'). Got order: {call_order}"
+ )
+
+ def test_total_sums_across_multiple_research_ids(self, app):
+ """For multiple research_ids, total is the sum of per-research
+ PENDING counts (the `total += count` accumulator).
+ """
+ # r1 has 2 pending items, r2 has 3 pending items → total = 5.
+ r1_items = [Mock(), Mock()]
+ r2_items = [Mock(), Mock(), Mock()]
+ for i, item in enumerate(r1_items + r2_items):
+ item.resource_id = 100 + i
+ resource = Mock()
+ resource.title = "Paper"
+
+ db_session = Mock()
+ q = _build_mock_query()
+ # count() is called once per research_id in the pre-pass loop.
+ q.count.side_effect = [2, 3]
+ # all() is called once per research_id in the processing loop.
+ q.all.side_effect = [r1_items, r2_items]
+ # get() is called once per item across both researches.
+ q.get.return_value = resource
+ db_session.query = Mock(return_value=q)
+ db_session.commit = Mock()
+
+ dl_svc = Mock()
+ dl_svc.queue_research_downloads.return_value = 0
+ dl_svc.download_resource.return_value = (True, None)
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ download_service=dl_svc,
+ extra_patches=[
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close",
+ return_value=None,
+ ),
+ ],
+ ) as (client, _):
+ resp = client.post(
+ "/library/api/download-bulk",
+ json={"research_ids": ["r1", "r2"], "mode": "pdf"},
+ content_type="application/json",
+ )
+ body = resp.data.decode()
+
+ assert resp.status_code == 200, body
+ events = self._collect_sse_events(body)
+ # Initial event must carry the summed total (5), proving the
+ # accumulator works across research_ids.
+ assert events[0].get("total") == 5, (
+ f"Initial total should be 5 (2+3 from r1+r2). Events: {events[:3]}"
+ )
+ # queue_research_downloads called once per research_id.
+ assert dl_svc.queue_research_downloads.call_count == 2
+
+ def test_emits_error_when_all_queue_calls_fail(self, app):
+ """Regression for the silent-failure UX gap: if queue_research_downloads
+ raises for every research_id and nothing was already queued, the SSE
+ stream must include an error event so the UI alerts the user instead
+ of silently completing with "0 / 0 files" success.
+ """
+ db_session = Mock()
+ empty_q = _build_mock_query(all_result=[], count_result=0)
+ db_session.query = Mock(return_value=empty_q)
+ db_session.commit = Mock()
+
+ dl_svc = Mock()
+ dl_svc.queue_research_downloads.side_effect = RuntimeError("db locked")
+ dl_svc.download_resource.return_value = (True, None)
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ download_service=dl_svc,
+ extra_patches=[
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close",
+ return_value=None,
+ ),
+ ],
+ ) as (client, _):
+ resp = client.post(
+ "/library/api/download-bulk",
+ json={"research_ids": ["r1"], "mode": "pdf"},
+ content_type="application/json",
+ )
+ body = resp.data.decode()
+
+ assert resp.status_code == 200, body
+ events = self._collect_sse_events(body)
+ # The terminal event must carry `complete: True` AND `error`,
+ # so handleSSECompletion in the frontend fires alert(error).
+ terminal = events[-1]
+ assert terminal.get("complete") is True, (
+ f"Expected terminal event with complete=True. Events: {events}"
+ )
+ assert terminal.get("error"), (
+ f"Expected error message on total-queue-failure. Terminal: {terminal}"
+ )
+ assert "queueing failed" in terminal["error"], (
+ f"Error should mention queueing failure. Got: {terminal['error']}"
+ )
+ assert terminal.get("total") == 0
+
+ def test_emits_nothing_to_download_message_when_queue_empty(self, app):
+ """The legitimate "nothing left to download" path (e.g. all papers
+ already downloaded): queue_research_downloads succeeds but the
+ post-queue count stays 0. The terminal event must carry complete=True
+ with the "No new papers" message — and must NOT be framed as a
+ queueing failure (that wording is reserved for the exception path).
+ """
+ db_session = Mock()
+ empty_q = _build_mock_query(all_result=[], count_result=0)
+ db_session.query = Mock(return_value=empty_q)
+ db_session.commit = Mock()
+
+ dl_svc = Mock()
+ # Succeeds (no exception) but nothing ends up PENDING.
+ dl_svc.queue_research_downloads.return_value = 0
+ dl_svc.download_resource.return_value = (True, None)
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ download_service=dl_svc,
+ extra_patches=[
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close",
+ return_value=None,
+ ),
+ ],
+ ) as (client, _):
+ resp = client.post(
+ "/library/api/download-bulk",
+ json={"research_ids": ["r1"], "mode": "pdf"},
+ content_type="application/json",
+ )
+ body = resp.data.decode()
+
+ assert resp.status_code == 200, body
+ events = self._collect_sse_events(body)
+ terminal = events[-1]
+ assert terminal.get("complete") is True, (
+ f"Expected terminal event with complete=True. Events: {events}"
+ )
+ assert terminal.get("error"), (
+ f"Expected a 'nothing to download' message. Terminal: {terminal}"
+ )
+ assert "No new papers" in terminal["error"], (
+ f"Error should say no new papers. Got: {terminal['error']}"
+ )
+ # Must NOT be the queue-failure framing — this is a clean empty state.
+ assert "queueing failed" not in terminal["error"], (
+ f"Empty state misreported as a queue failure: {terminal['error']}"
+ )
+ assert terminal.get("total") == 0
+
# ---------------------------------------------------------------------------
# queue_all_undownloaded edge cases