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(history): return 404 for missing log counts (#5386)

Ziyang Guo6a1f776425f4
diff --git a/changelog.d/+history-log-count-not-found.bugfix.md b/changelog.d/+history-log-count-not-found.bugfix.md
new file mode 100644
index 0000000000..2d830d8de5
--- /dev/null
+++ b/changelog.d/+history-log-count-not-found.bugfix.md
@@ -0,0 +1 @@
+Return HTTP 404 from the history log-count endpoint when the research does not exist.
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index dd4cf5bdd2..2894a8b164 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -444,6 +444,17 @@ def get_research_logs(research_id):
@login_required
def get_log_count(research_id):
"""Get the total number of logs for a specific research ID"""
+ username = session["username"]
+
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory.id)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if not research:
+ return _research_not_found(research_id)
+
# Get the total number of logs for this research ID
total_logs = get_total_logs_for_research(research_id)
diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.js
index e98b548e47..6f73b516b6 100644
--- a/src/local_deep_research/web/static/js/components/logpanel.js
+++ b/src/local_deep_research/web/static/js/components/logpanel.js
@@ -602,6 +602,17 @@
const generation = window._logPanelState._countRequestGen || 0;
try {
const response = await fetch(URLBuilder.historyLogCount(researchId));
+ if (response.ok === false) {
+ if (response.status === 404) {
+ SafeLogger.log('Log count unavailable: research not found');
+ } else {
+ SafeLogger.warn(
+ 'Log count request failed with status:',
+ response.status
+ );
+ }
+ return null;
+ }
const data = await response.json();
// Bail out if the user switched research while this fetch
// was in flight. The next load (for the new research) will
diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.js
index 6ecb7ac7e4..6e438b3cf5 100644
--- a/tests/js/components/logpanel.test.js
+++ b/tests/js/components/logpanel.test.js
@@ -1494,6 +1494,36 @@ describe('log count indicator — persisted total and Load older', () => {
expect(document.querySelector('.ldr-load-older')).toBeNull();
});
+ it('handles a missing research count without reporting malformed data', async () => {
+ const researchId = 'log-count-missing-research';
+ const indicator = addLogIndicator(researchId);
+ const countJson = vi.fn();
+ const errorSpy = vi.spyOn(SafeLogger, 'error');
+ globalThis.fetch = vi.fn((url) => {
+ if (url.endsWith('/log_count')) {
+ return Promise.resolve({
+ ok: false,
+ status: 404,
+ json: countJson,
+ });
+ }
+ return Promise.resolve({
+ ok: false,
+ status: 404,
+ json: () => Promise.resolve({ status: 'error' }),
+ });
+ });
+
+ await logPanel.loadLogs(researchId);
+
+ expect(indicator.textContent).toBe('0');
+ expect(countJson).not.toHaveBeenCalled();
+ expect(errorSpy).not.toHaveBeenCalledWith(
+ 'Invalid log count data received from API'
+ );
+ errorSpy.mockRestore();
+ });
+
it('reloads up to the hard cap and refreshes the badge after Load older', async () => {
const researchId = 'log-count-load-older';
const indicator = addLogIndicator(researchId);
diff --git a/tests/web/routes/test_history_routes.py b/tests/web/routes/test_history_routes.py
index 1d97575331..3cf13e0599 100644
--- a/tests/web/routes/test_history_routes.py
+++ b/tests/web/routes/test_history_routes.py
@@ -773,10 +773,23 @@ class TestGetLogCount:
def test_returns_log_count(self, authenticated_client):
"""Should return log count for research."""
- with patch(
- "local_deep_research.web.routes.history_routes.get_total_logs_for_research"
- ) as mock_total:
- mock_total.return_value = 15
+ with (
+ patch(
+ "local_deep_research.web.routes.history_routes.get_user_db_session"
+ ) as mock_session_ctx,
+ patch(
+ "local_deep_research.web.routes.history_routes.get_total_logs_for_research",
+ return_value=15,
+ ),
+ ):
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.filter_by.return_value.first.return_value = MagicMock()
response = authenticated_client.get(
f"{HISTORY_PREFIX}/log_count/test-id"
@@ -787,6 +800,54 @@ class TestGetLogCount:
assert data["status"] == "success"
assert data["total_logs"] == 15
+ def test_returns_404_for_nonexistent_research(self, authenticated_client):
+ """A missing research is distinct from an existing run with zero logs."""
+ with (
+ patch(
+ "local_deep_research.web.routes.history_routes.get_user_db_session"
+ ) as mock_session_ctx,
+ patch(
+ "local_deep_research.web.routes.history_routes.get_total_logs_for_research",
+ return_value=0,
+ ) as mock_total,
+ ):
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ response = authenticated_client.get(
+ f"{HISTORY_PREFIX}/log_count/nonexistent-id"
+ )
+
+ assert response.status_code == 404
+ assert response.get_json() == {
+ "status": "error",
+ "error": "Research not found",
+ "message": "Research not found",
+ }
+ mock_total.assert_not_called()
+
+ def test_propagates_database_session_failure(self, authenticated_client):
+ """A database failure must not fall through to the log-count query."""
+ with (
+ patch(
+ "local_deep_research.web.routes.history_routes.get_user_db_session",
+ side_effect=RuntimeError("database unavailable"),
+ ),
+ patch(
+ "local_deep_research.web.routes.history_routes.get_total_logs_for_research"
+ ) as mock_total,
+ ):
+ with pytest.raises(RuntimeError, match="database unavailable"):
+ authenticated_client.get(f"{HISTORY_PREFIX}/log_count/test-id")
+
+ mock_total.assert_not_called()
+
class TestGetHistoryMetadataParsing:
"""Tests for JSON metadata parsing in get_history (PR #2013).
diff --git a/tests/web/routes/test_history_routes_coverage.py b/tests/web/routes/test_history_routes_coverage.py
index 03c6c0a3e2..ec96a5dca8 100644
--- a/tests/web/routes/test_history_routes_coverage.py
+++ b/tests/web/routes/test_history_routes_coverage.py
@@ -953,8 +953,14 @@ class TestGetResearchLogsSuccess:
class TestGetLogCount:
def test_returns_total_log_count(self, client):
"""get_log_count returns the total number of logs for the research."""
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(_make_research())
with (
patch(AUTH_DB_MANAGER, _mock_db_manager()),
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
patch(f"{MODULE}.get_total_logs_for_research", return_value=17),
):
resp = _authed_get(client, "/history/log_count/test-id")
@@ -966,8 +972,14 @@ class TestGetLogCount:
def test_returns_zero_when_no_logs(self, client):
"""get_log_count returns 0 when there are no logs."""
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(_make_research())
with (
patch(AUTH_DB_MANAGER, _mock_db_manager()),
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
patch(f"{MODULE}.get_total_logs_for_research", return_value=0),
):
resp = _authed_get(client, "/history/log_count/empty-id")
diff --git a/tests/web/routes/test_history_routes_extended.py b/tests/web/routes/test_history_routes_extended.py
index 620bd0ccc0..1653aabfbf 100644
--- a/tests/web/routes/test_history_routes_extended.py
+++ b/tests/web/routes/test_history_routes_extended.py
@@ -320,7 +320,13 @@ class TestGetLogCount:
def test_returns_total_logs_count(self, app):
"""Should return the total number of logs for the research."""
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = MagicMock()
with (
+ patch(
+ f"{_HR}.get_user_db_session",
+ return_value=_make_db_session_ctx(mock_session),
+ ),
patch(f"{_HR}.get_total_logs_for_research", return_value=37),
patch(_AUTH_DB_MANAGER, _mock_auth_db_manager()),
):