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(api): /api/report sources from research_resources + chat session-route rate limits (#3665) (#4371)

LearningCircuita40be9536960
diff --git a/changelog.d/+chat-session-routes-rate-limit.security.md b/changelog.d/+chat-session-routes-rate-limit.security.md
new file mode 100644
index 0000000000..437b5d4795
--- /dev/null
+++ b/changelog.d/+chat-session-routes-rate-limit.security.md
@@ -0,0 +1 @@
+The chat `PATCH` (rename/archive) and `DELETE` session routes now carry the same per-user rate limit as the other state-changing chat endpoints. They were previously bounded only by the global limiter, leaving an uneven abuse surface across the session API.
diff --git a/changelog.d/+news-findings-answer-only.misc.md b/changelog.d/+news-findings-answer-only.misc.md
new file mode 100644
index 0000000000..50bdaeeac4
--- /dev/null
+++ b/changelog.d/+news-findings-answer-only.misc.md
@@ -0,0 +1 @@
+Documented that the News API `findings` field is the answer-only report content after the chat-mode-v2 refactor (intentional): structured top-N source links live in the separate `links` array rather than an embedded `## Sources` blob. No behavior change. (#3665)
diff --git a/changelog.d/+report-api-sources-from-resources.bugfix.md b/changelog.d/+report-api-sources-from-resources.bugfix.md
new file mode 100644
index 0000000000..680e38fb2f
--- /dev/null
+++ b/changelog.d/+report-api-sources-from-resources.bugfix.md
@@ -0,0 +1 @@
+`GET /api/report/<id>` now returns the `sources` field from the structured `research_resources` table instead of the dead `all_links_of_system` metadata key. After the chat-mode-v2 report refactor that key is never written, so the field returned an empty list for every research created since — even though the assembled `content` and the news feed already read sources from the table. (#3665)
diff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.py
index e63a577adc..b0db665432 100644
--- a/src/local_deep_research/chat/routes.py
+++ b/src/local_deep_research/chat/routes.py
@@ -476,6 +476,10 @@ def get_session(session_id):
@chat_bp.route("/api/chat/sessions/<session_id>", methods=["PATCH"])
@login_required
+# Per-user keying, like the other state-changing chat routes. Without a
+# per-route limit, rename/archive was bounded only by the global limiter,
+# leaving an uneven abuse surface across the session API.
[email protected]("30 per minute", key_func=_get_api_user_key)
@require_json_body(
error_format="success",
error_message="Request body must be a JSON object",
@@ -591,6 +595,9 @@ def update_session(session_id):
@chat_bp.route("/api/chat/sessions/<session_id>", methods=["DELETE"])
@login_required
+# Per-user keying, like the other state-changing chat routes. Caps bulk
+# delete attempts that the global limiter alone left under-constrained.
[email protected]("30 per minute", key_func=_get_api_user_key)
def delete_session(session_id):
"""Delete a chat session permanently."""
try:
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index 5e68f01814..80e254d888 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -91,7 +91,10 @@ def get_news_feed(
search_strategy: Override default recommendation strategy
Returns:
- Dictionary with news items and metadata
+ Dictionary with news items and metadata. Each item's ``findings``
+ field is the answer-only report content (post chat-mode-v2 refactor,
+ #3665 Fix B); structured top-N source links are in the separate
+ ``links`` array, not embedded in ``findings``.
"""
# Validate limit - allow any positive number
if limit < 1:
@@ -268,7 +271,13 @@ def get_news_feed(
# Process database content
lines = content.split("\n") if content else []
- # Use full content as findings
+ # `findings` is the answer-only report_content
+ # after the chat-mode-v2 refactor (#3665 Fix B,
+ # intentional). The legacy answer + ## Sources
+ # blob is gone: structured top-N source URLs live
+ # in the separate `links` array below, so snippet
+ # extraction is cleaner without Sources headers in
+ # the substrate.
findings = content
# Extract summary from first non-empty line
for line in lines:
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 050517a067..1aa8cfc3bf 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1334,6 +1334,7 @@ def get_research_report(research_id):
# research_resources + Metrics from research_meta) on demand.
from ..services.report_assembly_service import (
assemble_full_report,
+ get_research_source_links_batch,
)
content = assemble_full_report(research, db_session)
@@ -1342,6 +1343,18 @@ def get_research_report(research_id):
if content is None:
return jsonify({"error": "Report not found"}), 404
+ # Sources live in the research_resources table, not research_meta.
+ # The post-refactor save path never writes the legacy
+ # `all_links_of_system` metadata key, so reading it here returned
+ # [] for every research created since chat-mode-v2 (#3665). Read
+ # the structured table instead — the same source of truth the
+ # assembled `content` and the news feed already use. limit=None
+ # returns every source (this field was never top-N), matching the
+ # full list the assembled `content` renders for the same research.
+ sources = get_research_source_links_batch(
+ [research.id], db_session, limit=None
+ ).get(research.id, [])
+
# Return the report data with backwards-compatible fields
# Examples expect 'summary', 'sources', 'findings' at top level
safe_metadata = strip_settings_snapshot(metadata)
@@ -1350,7 +1363,7 @@ def get_research_report(research_id):
"content": content,
# Backwards-compatible fields for examples
"summary": content, # The markdown report is the summary
- "sources": safe_metadata.get("all_links_of_system", []),
+ "sources": sources,
"findings": safe_metadata.get("findings", []),
"metadata": {
"title": research.title if research.title else None,
diff --git a/src/local_deep_research/web/services/report_assembly_service.py b/src/local_deep_research/web/services/report_assembly_service.py
index 6fd6b21395..26d098fa51 100644
--- a/src/local_deep_research/web/services/report_assembly_service.py
+++ b/src/local_deep_research/web/services/report_assembly_service.py
@@ -203,7 +203,7 @@ def get_research_source_links(
def get_research_source_links_batch(
- research_ids: List[str], db_session: Session, limit: int = 3
+ research_ids: List[str], db_session: Session, limit: Optional[int] = 3
) -> Dict[str, List[Dict[str, str]]]:
"""Batched variant of :func:`get_research_source_links`.
@@ -212,6 +212,9 @@ def get_research_source_links_batch(
Python-side grouping. Returned dict maps each research_id to its
top-N links (same shape as :func:`get_research_source_links`).
Research ids with zero rows map to ``[]``.
+
+ ``limit=None`` returns every link for each research (no cap) — used by
+ the report API, which exposes the full source list rather than a top-N.
"""
result: Dict[str, List[Dict[str, str]]] = {rid: [] for rid in research_ids}
if not research_ids:
@@ -226,7 +229,7 @@ def get_research_source_links_batch(
)
for r in rows:
bucket = result.setdefault(r.research_id, [])
- if len(bucket) >= limit:
+ if limit is not None and len(bucket) >= limit:
continue
url = (r.url or "").strip()
if not url.startswith("http"):
diff --git a/tests/web/routes/test_report_api_contract.py b/tests/web/routes/test_report_api_contract.py
new file mode 100644
index 0000000000..b24d5b2139
--- /dev/null
+++ b/tests/web/routes/test_report_api_contract.py
@@ -0,0 +1,234 @@
+"""API contract tests for the report-content display routes.
+
+Locks the public shape of report content so a future change can't silently
+regress it (#3665):
+
+* ``content`` is the *assembled* legacy view — answer + ``## Sources`` (from
+ the ``research_resources`` table) + ``## Research Metrics`` (from
+ ``research_meta``) — across every display/export route.
+* ``GET /api/report/<id>`` exposes a ``sources`` field populated from
+ ``research_resources``. Before the fix it read the dead
+ ``all_links_of_system`` metadata key, which the post-refactor save path
+ never writes, so it returned ``[]`` for every new research (Fix A).
+
+These exercise the *real* assembly path (``assemble_full_report`` /
+``get_research_source_links_batch``) against real seeded rows; only auth and
+the per-user-DB plumbing are stubbed.
+"""
+
+from contextlib import contextmanager
+from datetime import datetime, UTC
+from unittest.mock import MagicMock, patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.research import (
+ ResearchHistory,
+ ResearchResource,
+)
+
+RESEARCH_ID = "contract-research-1"
+# Deliberately > the batch helper's default top-N (3): the report API must
+# return *every* source (no cap), so a reintroduced default limit would fail
+# test_api_report_sources_field_matches_research_resources_count.
+N_SOURCES = 5
+
+
[email protected](autouse=True)
+def mock_db_manager():
+ """Satisfy the auth middleware/decorators without a real encrypted DB.
+
+ Mirrors tests/test_followup_api.py: every module-level ``db_manager``
+ binding used by the Flask before_request middleware and ``login_required``
+ is mocked so an authenticated session passes. ``has_encryption=False``
+ skips the encrypted-DB password check.
+ """
+ with (
+ patch("local_deep_research.web.auth.decorators.db_manager") as mock_db,
+ patch("local_deep_research.database.encrypted_db.db_manager"),
+ patch("local_deep_research.web.auth.database_middleware.db_manager"),
+ patch("local_deep_research.web.auth.session_cleanup.db_manager"),
+ patch("local_deep_research.web.auth.queue_middleware.db_manager"),
+ ):
+ mock_db.connections = {"testuser": MagicMock()}
+ mock_db.has_encryption = False
+ mock_db.is_user_connected.return_value = True
+ yield mock_db
+
+
+def mock_auth_client(app):
+ """Test client authenticated via a mock session.
+
+ Uses the shared ``app`` fixture (tests/conftest.py) but authenticates by
+ seeding the session directly rather than a real register/login, because
+ auth is stubbed via ``mock_db_manager`` and the per-user DB is patched to
+ a seeded SQLite file (``seeded_db``). The real ``authenticated_client``
+ fixture would create a real encrypted DB we couldn't seed sources into.
+ """
+ client = app.test_client()
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["authenticated"] = True
+ return client
+
+
+def seeded_db(tmp_path):
+ """Real temp-file SQLite seeded with one completed research + sources.
+
+ Patches ``get_user_db_session`` in both route modules to yield a fresh
+ session bound to the seeded DB (a fresh session per request, like the
+ real per-request session). A file DB (not ``:memory:``) so every
+ ``SessionLocal()`` connection sees the same seeded rows.
+ """
+ engine = create_engine(f"sqlite:///{tmp_path / 'report_contract.db'}")
+ Base.metadata.create_all(engine)
+ SessionLocal = sessionmaker(bind=engine)
+
+ seed = SessionLocal()
+ seed.add(
+ ResearchHistory(
+ id=RESEARCH_ID,
+ query="What is X?",
+ mode="quick",
+ status="completed",
+ created_at="2026-04-25T12:00:00+00:00",
+ completed_at="2026-04-25T12:05:00+00:00",
+ report_content=(
+ "X is explained here, citing [1](https://src1.example) "
+ "and [2](https://src2.example)."
+ ),
+ research_meta={
+ "iterations": 2,
+ "generated_at": "2026-04-25T12:05:00+00:00",
+ },
+ )
+ )
+ for i in range(1, N_SOURCES + 1):
+ url = f"https://src{i}.example"
+ seed.add(
+ ResearchResource(
+ research_id=RESEARCH_ID,
+ title=f"Source {i}",
+ url=url,
+ source_type="web",
+ resource_metadata={
+ "original_data": {
+ "index": str(i),
+ "url": url,
+ "title": f"Source {i}",
+ }
+ },
+ created_at=datetime.now(UTC).isoformat(),
+ )
+ )
+ seed.commit()
+ seed.close()
+
+ @contextmanager
+ def _fake_user_db(username=None, password=None):
+ db = SessionLocal()
+ try:
+ yield db
+ finally:
+ db.close()
+
+ with (
+ patch(
+ "local_deep_research.web.routes.research_routes.get_user_db_session",
+ _fake_user_db,
+ ),
+ patch(
+ "local_deep_research.web.routes.history_routes.get_user_db_session",
+ _fake_user_db,
+ ),
+ ):
+ yield
+
+ engine.dispose()
+
+
+# ---------------------------------------------------------------------------
+# Assembled-view shape across display routes (locks the legacy report shape)
+# ---------------------------------------------------------------------------
+
+
+def test_history_report_includes_sources_and_metrics(
+ mock_auth_client, seeded_db
+):
+ resp = mock_auth_client.get(f"/history/report/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.data
+ content = resp.get_json()["content"]
+ assert "## Sources\n" in content
+ assert "## Research Metrics\n" in content
+ # Sources block references the structured resources.
+ assert "src1.example" in content
+
+
+def test_history_markdown_includes_sources_and_metrics(
+ mock_auth_client, seeded_db
+):
+ resp = mock_auth_client.get(f"/history/markdown/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.data
+ content = resp.get_json()["content"]
+ assert "## Sources\n" in content
+ assert "## Research Metrics\n" in content
+
+
+def test_api_report_content_includes_sources_and_metrics(
+ mock_auth_client, seeded_db
+):
+ resp = mock_auth_client.get(f"/api/report/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.data
+ content = resp.get_json()["content"]
+ assert "## Sources\n" in content
+ assert "## Research Metrics\n" in content
+
+
+def test_export_latex_content_includes_sources_and_metrics(
+ mock_auth_client, seeded_db
+):
+ # LaTeX is the registered plain-text export format (markdown is served by
+ # /history/markdown; quarto is a .zip; pdf/odt are binary). LaTeX
+ # conversion drops the markdown `##` prefix but keeps the header words and
+ # body text. "Research Metrics" / "Search Iterations" exist ONLY in the
+ # assembled view, never in the answer-only report_content, so finding them
+ # proves the export path goes through assemble_full_report.
+ resp = mock_auth_client.post(f"/api/v1/research/{RESEARCH_ID}/export/latex")
+ assert resp.status_code == 200, resp.data
+ body = resp.data.decode("utf-8")
+ assert "Research Metrics" in body
+ assert "Search Iterations" in body
+ assert "Sources" in body
+ assert "src1.example" in body
+
+
+# ---------------------------------------------------------------------------
+# Fix A regression fence: /api/report sources field from research_resources
+# ---------------------------------------------------------------------------
+
+
+def test_api_report_sources_field_populated_from_research_resources(
+ mock_auth_client, seeded_db
+):
+ resp = mock_auth_client.get(f"/api/report/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.data
+ sources = resp.get_json()["sources"]
+ assert isinstance(sources, list)
+ assert sources, "sources must not be empty (Fix A regression)"
+ for entry in sources:
+ assert entry.get("url")
+ assert entry.get("title")
+
+
+def test_api_report_sources_field_matches_research_resources_count(
+ mock_auth_client, seeded_db
+):
+ resp = mock_auth_client.get(f"/api/report/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.data
+ sources = resp.get_json()["sources"]
+ assert len(sources) == N_SOURCES