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(report): add uncited-sources mode setting and wire prose filtering (#5379) (#6747)

S6e1348919e4f
diff --git a/changelog.d/6747.feature.md b/changelog.d/6747.feature.md
new file mode 100644
index 0000000000..3653b6a651
--- /dev/null
+++ b/changelog.d/6747.feature.md
@@ -0,0 +1 @@
+Adds a `report.uncited_sources_mode` setting so final source lists can retain only cited sources or all accumulated research hits.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 9ca0d6b6a7..99b6cbddf4 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -220,6 +220,7 @@ They are not available in the Web UI because they are needed to start the applic
| `report.max_context_chars` | `LDR_REPORT_MAX_CONTEXT_CHARS` | `4000` | Maximum character limit for previous section context when generating report sections. If accumulated context exceeds this, it is truncated at sentence boundaries. Lower values are safer for smaller local models. Default is 4000. | REPORT |
| `report.max_context_sections` | `LDR_REPORT_MAX_CONTEXT_SECTIONS` | `3` | Number of previously generated report sections to include as context when writing new sections. Helps the LLM avoid repeating content. Higher values increase context size but may exceed smaller model limits. Default is 3. | REPORT |
| `report.searches_per_section` | `LDR_REPORT_SEARCHES_PER_SECTION` | `2` | Number of web searches to perform per report section. Higher values increase research depth for each section but also increase search engine queries and processing time. Default is 2. | REPORT |
+| `report.uncited_sources_mode` | `LDR_REPORT_UNCITED_SOURCES_MODE` | `fallback` | Which sources appear in the final report bibliography. Cited only with fallback keeps sources cited in the report body and falls back to all sources when no citations are detected; strict keeps only cited sources; legacy lists every accumulated search hit. | REPORT |
| `research_library.auto_index_enabled` | `LDR_RESEARCH_LIBRARY_AUTO_INDEX_ENABLED` | `false` | Automatically index documents for RAG search when they are added to collections (via upload or download). Indexing runs in the background without blocking uploads. Disable to defer indexing and improve upload speed for large batches. | APP |
| `research_library.confirm_deletions` | `LDR_RESEARCH_LIBRARY_CONFIRM_DELETIONS` | `true` | Show confirmation dialogs before delete operations. Recommended to keep enabled to prevent accidental data loss. | APP |
| `research_library.max_pdf_size_mb` | `LDR_RESEARCH_LIBRARY_MAX_PDF_SIZE_MB` | `3072` | Maximum allowed PDF file size in megabytes for the research library. PDFs larger than this will not be stored. Uploads are also gated by the per-file upload cap (LDR_SECURITY_UPLOAD_MAX_FILE_SIZE_MB, default 3072 MB / 3 GB) — raising this value above that cap has no effect because uploads are rejected before they reach storage. | APP |
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
index 860240f56f..2a5370ee89 100644
--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
@@ -273,6 +273,8 @@ class BaseSearchStrategy(ABC):
Used by ``langgraph_agent_strategy`` (passes
``self.collector.results``); the other historical consumer,
``mcp_strategy``, has been removed.
+ Only sources cited in ``content`` are listed, honoring
+ ``report.uncited_sources_mode`` from the settings snapshot.
Returns ``content`` unchanged when no links can be extracted.
"""
if not search_results:
@@ -281,12 +283,18 @@ class BaseSearchStrategy(ABC):
from ...utilities.search_utilities import (
extract_links_from_search_results,
format_links_to_markdown,
+ resolve_uncited_sources_mode,
)
all_links = extract_links_from_search_results(search_results)
if not all_links:
return content
- sources_markdown = format_links_to_markdown(all_links)
+ mode = resolve_uncited_sources_mode(
+ self.get_setting("report.uncited_sources_mode")
+ )
+ sources_markdown = format_links_to_markdown(
+ all_links, prose=content, uncited_mode=mode
+ )
if not sources_markdown:
return content
return f"{content}\n\n## Sources\n\n{sources_markdown}"
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 9119304445..eafeb58731 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -352,6 +352,9 @@ def quick_summary(
"iterations": results.get("iterations", 0),
"questions": results.get("questions", {}),
"formatted_findings": results.get("formatted_findings", ""),
+ # Render-only by design: report.uncited_sources_mode shapes the
+ # rendered ## Sources block, not this array, which keeps the
+ # full accumulated set for API consumers.
"sources": results.get("all_links_of_system", []),
}
finally:
@@ -622,6 +625,9 @@ def detailed_research(
"iterations": results.get("iterations", 0),
"questions": results.get("questions", {}),
"formatted_findings": results.get("formatted_findings", ""),
+ # Render-only by design (see above): the uncited-sources mode
+ # shapes the rendered ## Sources block; this array keeps the
+ # full accumulated set.
"sources": results.get("all_links_of_system", []),
"metadata": {
"timestamp": datetime.now(UTC).isoformat(),
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index c1a922081c..fcc6bd92ab 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -890,6 +890,33 @@
"value": "number_hyperlinks",
"visible": true
},
+ "report.uncited_sources_mode": {
+ "category": "report_parameters",
+ "description": "Which sources appear in the final report bibliography. Cited only with fallback keeps sources cited in the report body and falls back to all sources when no citations are detected; strict keeps only cited sources; legacy lists every accumulated search hit.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Uncited Sources Mode",
+ "options": [
+ {
+ "value": "fallback",
+ "label": "Cited only, fall back to all if indeterminate"
+ },
+ {
+ "value": "strict",
+ "label": "Cited only"
+ },
+ {
+ "value": "disabled",
+ "label": "Legacy: all accumulated hits"
+ }
+ ],
+ "step": null,
+ "type": "REPORT",
+ "ui_element": "select",
+ "value": "fallback",
+ "visible": true
+ },
"report.export_formats": {
"category": "report_parameters",
"description": "Available export format options displayed in the user interface. Supported formats include Markdown (.md), LaTeX (.tex), Quarto (.qmd), and RIS bibliographic format.",
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index 62f1779a93..8be0d9a596 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -1677,11 +1677,25 @@ class IntegratedReportGenerator:
# Imported here for the same reason, and directly rather than off
# the module object above so the count is computed by the real
# grouping helper.
- from .utilities.search_utilities import count_distinct_sources
+ from .utilities.search_utilities import (
+ count_distinct_sources,
+ filter_cited_links,
+ resolve_uncited_sources_mode,
+ )
+ # Body prose BEFORE the Sources tail: citation indices/URLs are
+ # parsed from this, so uncited accumulated hits stay out of the
+ # bibliography. Honors report.uncited_sources_mode.
+ body_prose = "\n\n".join(report_parts)
+ mode = resolve_uncited_sources_mode()
+ visible_links = filter_cited_links(
+ self.search_system.all_links_of_system,
+ body_prose,
+ mode=mode,
+ )
formatted_all_links = (
utilities.search_utilities.format_links_to_markdown(
- all_links=self.search_system.all_links_of_system
+ all_links=visible_links,
)
)
@@ -1691,7 +1705,7 @@ class IntegratedReportGenerator:
# The DB save site (research_service.py) strips this Sources
# section via format_document_split before persisting, so the
# answer-only invariant on report_content still holds.
- final_report_content = "\n\n".join(report_parts)
+ final_report_content = body_prose
# Explicit "\n\n" separator: downstream regex consumers
# (_SOURCES_SECTION_PATTERNS in text_optimization/citation_formatter.py
# and _LEGACY_SOURCES_RE in web/services/report_assembly_service.py)
@@ -1721,15 +1735,13 @@ class IntegratedReportGenerator:
# Create metadata dictionary
metadata = {
"generated_at": datetime.now(UTC).isoformat(),
- # SOURCES, not entries. ``all_links_of_system`` holds one
- # entry per distinct (url, snippet) pair under the LangGraph
- # strategy, and raw un-deduped engine dicts under the others,
- # so its length counts occurrences. This number is reported
- # as "sources", so it must group the way the ## Sources block
- # above does.
- "initial_sources": count_distinct_sources(
- self.search_system.all_links_of_system
- ),
+ # Count the same visible, canonically grouped source set that
+ # the Sources block above renders. Document-level: one document
+ # cited via several chunk anchors still counts once even though
+ # it renders several bibliography lines (distinct sources <=
+ # bibliography lines <= citation indices) — so a count below
+ # the rendered line total is expected, not a bug.
+ "initial_sources": count_distinct_sources(visible_links),
"sections_researched": len(structure),
"searches_per_section": self.searches_per_section,
"query": query,
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 0d570a3b08..a38a85b52c 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -390,6 +390,39 @@ def _normalize_bare_library_prefix(candidate: str) -> str:
_URL_SENTENCE_PUNCT = ".,;:!?。、,!?;:「」『』、…·—–"
_URL_WRAPPER_PUNCT = "'\"`]}>"
+UNCITED_SOURCES_MODE_KEY = "report.uncited_sources_mode"
+UNCITED_SOURCES_MODES = ("fallback", "strict", "disabled")
+UNCITED_SOURCES_DEFAULT = "fallback"
+
+
+def resolve_uncited_sources_mode(raw=None, settings_snapshot=None) -> str:
+ """Normalize the ``report.uncited_sources_mode`` setting.
+
+ ``raw`` is an explicitly provided value (e.g. from a strategy's
+ settings snapshot, already unwrapped). ``None`` resolves from
+ ``settings_snapshot`` (when given) or the thread settings context,
+ defaulting to ``"fallback"`` when no context is bound. Unknown values
+ degrade to ``"fallback"`` so a stale or hand-edited setting can never
+ wipe out a bibliography. Settings lookup failures also degrade to the
+ default: rendering a report must never crash on a preference read.
+ """
+ if raw is None:
+ try:
+ from ..config.thread_settings import get_setting_from_snapshot
+
+ raw = get_setting_from_snapshot(
+ UNCITED_SOURCES_MODE_KEY,
+ UNCITED_SOURCES_DEFAULT,
+ settings_snapshot=settings_snapshot,
+ )
+ except Exception:
+ return UNCITED_SOURCES_DEFAULT
+ if isinstance(raw, dict):
+ raw = raw.get("value", UNCITED_SOURCES_DEFAULT)
+ if isinstance(raw, str) and raw.strip() in UNCITED_SOURCES_MODES:
+ return raw.strip()
+ return UNCITED_SOURCES_DEFAULT
+
def _strip_fence_prefix(s: str) -> str:
"""Strip Markdown quote/list prefixes from a line-start string.
@@ -799,7 +832,9 @@ def filter_cited_links(
is empty/indeterminate or nothing matches; ``strict`` returns only
matches (possibly empty); ``disabled`` returns ``all_links``.
Indeterminate input falls back to ``all_links`` in every mode.
+ ``None`` resolves from the ``report.uncited_sources_mode`` setting.
"""
+ mode = resolve_uncited_sources_mode(mode)
if not all_links:
return all_links
if mode == "disabled" or not prose or not prose.strip():
@@ -889,9 +924,10 @@ def count_distinct_sources(all_links: List[Dict]) -> int:
def format_links_to_markdown(
all_links: List[Dict],
prose: Optional[str] = None,
- uncited_mode: str = "fallback",
+ uncited_mode: Optional[str] = "fallback",
) -> str:
parts: list[str] = []
+ uncited_mode = resolve_uncited_sources_mode(uncited_mode)
if prose and uncited_mode != "disabled":
all_links = filter_cited_links(all_links, prose, mode=uncited_mode)
logger.info(f"Formatting {len(all_links)} links to markdown...")
@@ -1054,6 +1090,7 @@ def format_findings(
findings_list: List[Dict],
synthesized_content: str,
questions_by_iteration: Dict[int, List[str]],
+ uncited_mode: Optional[str] = None,
) -> str:
"""Format findings into a detailed text output.
@@ -1061,6 +1098,12 @@ def format_findings(
findings_list: List of finding dictionaries
synthesized_content: The synthesized content from the LLM.
questions_by_iteration: Dictionary mapping iteration numbers to lists of questions
+ uncited_mode: ``report.uncited_sources_mode`` override. ``None``
+ (default) resolves from settings. Only the global source
+ dumps (top list and ``## ALL SOURCES`` footer) are filtered,
+ using the synthesized content as the citation prose;
+ per-section ``SOURCES USED IN THIS SECTION`` lists stay
+ unfiltered.
Returns:
str: Formatted text output
@@ -1069,6 +1112,12 @@ def format_findings(
f"Inside format_findings utility. Findings count: {len(findings_list)}, Questions iterations: {len(questions_by_iteration)}"
)
parts: list[str] = []
+ mode = resolve_uncited_sources_mode(uncited_mode)
+ prose = (
+ synthesized_content
+ if isinstance(synthesized_content, str)
+ else str(synthesized_content or "")
+ )
# Extract all sources from findings
all_links = []
@@ -1084,8 +1133,12 @@ def format_findings(
# Start with the synthesized content (passed as synthesized_content)
parts.append(f"{synthesized_content}\n\n")
- # Add sources section after synthesized content if sources exist
- parts.append(format_links_to_markdown(all_links))
+ # Add sources section after synthesized content if sources exist.
+ # Filtered by the synthesized prose; per-section lists below stay
+ # unfiltered.
+ parts.append(
+ format_links_to_markdown(all_links, prose=prose, uncited_mode=mode)
+ )
parts.append("\n\n") # Separator after synthesized content
@@ -1201,10 +1254,12 @@ def format_findings(
else:
logger.warning("No detailed findings found to format.")
- # Add summary of all sources at the end
+ # Add summary of all sources at the end, filtered the same way.
if all_links:
parts.append("## ALL SOURCES:\n")
- parts.append(format_links_to_markdown(all_links))
+ parts.append(
+ format_links_to_markdown(all_links, prose=prose, uncited_mode=mode)
+ )
else:
logger.info("No unique sources found across all findings to list.")
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 431b6b9fc9..db29951776 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -2002,7 +2002,23 @@ class QueueProcessorV2:
elif op_type == "error_update":
research.status = op_data.get("status", "failed")
research.error_message = op_data.get("error_message")
- research.research_meta = op_data.get("metadata")
+ incoming_meta = op_data.get("metadata")
+ existing_meta = research.research_meta
+ if isinstance(existing_meta, dict) and isinstance(
+ incoming_meta, dict
+ ):
+ # Merge, never wholesale-replace: a bare
+ # {"terminated_at": ...} from handle_termination
+ # must not wipe the row's settings_snapshot (and
+ # submission block) that view/export rendering
+ # resolves report.uncited_sources_mode from.
+ # Callers that already merged (the failure path)
+ # are unaffected: re-merging is idempotent.
+ merged_meta = dict(existing_meta)
+ merged_meta.update(incoming_meta)
+ research.research_meta = merged_meta
+ else:
+ research.research_meta = incoming_meta
research.completed_at = op_data.get("completed_at")
report_path = op_data.get("report_path")
if report_path:
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index b5876dd5da..620394e6ca 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -1052,6 +1052,13 @@ async def send_message(
"message_id": message_id,
"research_mode": research_mode,
},
+ # Persist the run's settings snapshot so
+ # view/export (report_assembly_service) renders
+ # the same report.uncited_sources_mode the
+ # generation-time render used. Mirrors the
+ # main-form creation path; completion merge
+ # back-fills when missing.
+ "settings_snapshot": settings_snapshot,
}
research = ResearchHistory(
id=research_id,
@@ -1627,6 +1634,11 @@ async def retry_attempt(
"message_id": new_message_id,
"research_mode": research_mode,
},
+ # Persist the run's settings snapshot so
+ # view/export renders the same uncited-sources
+ # mode as generation. Mirrors the main-form path;
+ # completion merge back-fills when missing.
+ "settings_snapshot": settings_snapshot,
}
db_session.add(
ResearchHistory(
diff --git a/src/local_deep_research/web/routers/followup.py b/src/local_deep_research/web/routers/followup.py
index ce89cfe0d9..520d4f5141 100644
--- a/src/local_deep_research/web/routers/followup.py
+++ b/src/local_deep_research/web/routers/followup.py
@@ -383,6 +383,12 @@ def _start_followup_sync(data, username):
"question": data.get("question"),
"strategy": "contextual-followup",
},
+ # Persist the run's settings snapshot so view/export
+ # (report_assembly_service) renders the same
+ # report.uncited_sources_mode the generation-time render
+ # used. Mirrors the main-form creation path; completion
+ # merge back-fills when missing.
+ "settings_snapshot": settings_snapshot,
}
research = ResearchHistory(
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 50565df56c..a732057c5a 100644
--- a/src/local_deep_research/web/services/report_assembly_service.py
+++ b/src/local_deep_research/web/services/report_assembly_service.py
@@ -22,6 +22,7 @@ silently re-introduce the regex over-strip class of bugs that
answer-only storage avoids.
"""
+import json
import re
from typing import Any, Dict, List, Optional
@@ -29,7 +30,12 @@ from loguru import logger
from sqlalchemy.orm import Session
from ...database.models.research import ResearchHistory, ResearchResource
-from ...utilities.search_utilities import format_links_to_markdown
+from ...utilities.search_utilities import (
+ UNCITED_SOURCES_MODE_KEY,
+ UNCITED_SOURCES_MODES,
+ format_links_to_markdown,
+ resolve_uncited_sources_mode,
+)
from ...utilities.url_utils import canonical_url_key
# Line-anchored regexes for the legacy-row guard. See `assemble_full_report`
@@ -47,8 +53,67 @@ _LEGACY_SOURCES_RE = re.compile(
_LEGACY_METRICS_RE = re.compile(r"^## Research Metrics\b", re.MULTILINE)
+def _current_user_uncited_mode(db_session: Session) -> Optional[str]:
+ """Read the requesting user's CURRENT saved uncited-sources mode.
+
+ Covers legacy rows that completed before snapshots were persisted
+ (chat/follow-up research created and finished before #6747): those
+ rows carry only ``{"submission": ...}`` forever, so the row snapshot
+ cannot decide the render. The requesting user's current preference is
+ the best available signal — it is what a re-run would generate with.
+
+ Returns the validated mode, or ``None`` when the setting is missing,
+ malformed, or unreadable (caller falls through to the thread context
+ and then ``"fallback"``). Never raises: rendering a report must not
+ crash on a preference read.
+ """
+ try:
+ from ...settings.manager import SettingsManager
+
+ raw = SettingsManager(db_session).get_setting(
+ UNCITED_SOURCES_MODE_KEY, None
+ )
+ except Exception:
+ logger.debug(
+ "report assembly: current uncited-sources mode unreadable; "
+ "falling back",
+ exc_info=True,
+ )
+ return None
+ if isinstance(raw, dict):
+ raw = raw.get("value")
+ if isinstance(raw, str) and raw.strip() in UNCITED_SOURCES_MODES:
+ return raw.strip()
+ return None
+
+
+def _research_settings_snapshot(research) -> Optional[Dict[str, Any]]:
+ """Return the saved ``settings_snapshot`` for a research row, if any.
+
+ Report/history routes run without a research-worker settings context,
+ so resolving ``report.uncited_sources_mode`` from the thread context
+ alone always yields ``fallback`` — even when the user saved
+ ``disabled`` or ``strict``. The snapshot captured at research start
+ (``research_meta["settings_snapshot"]``) is the applicable saved
+ preference and must be passed explicitly.
+ """
+ try:
+ meta = getattr(research, "research_meta", None)
+ if isinstance(meta, str):
+ meta = json.loads(meta)
+ if not isinstance(meta, dict):
+ return None
+ snap = meta.get("settings_snapshot")
+ return snap if isinstance(snap, dict) else None
+ except Exception:
+ return None
+
+
def assemble_full_report(
- research: Optional[ResearchHistory], db_session: Session
+ research: Optional[ResearchHistory],
+ db_session: Session,
+ uncited_mode: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
) -> Optional[str]:
"""Reconstruct the legacy report shape from structured storage.
@@ -58,6 +123,13 @@ def assemble_full_report(
when accessing ``research.research_meta`` lazily.
db_session: Active SQLAlchemy session bound to the user DB.
Used to query ``research_resources`` for the sources block.
+ uncited_mode: Explicit ``report.uncited_sources_mode`` override.
+ When ``None`` (default) the saved ``settings_snapshot`` on
+ the research row is honored, falling back to the thread
+ settings context and then ``"fallback"``.
+ settings_snapshot: Explicit settings snapshot override (same
+ precedence as ``uncited_mode`` — callers that already have
+ the snapshot can pass it instead of re-reading the row).
Returns:
``None`` when ``research`` is ``None`` (caller should map to
@@ -86,7 +158,13 @@ def assemble_full_report(
# Let any failure propagate: the callers already wrap this in a
# try/except that returns HTTP 500. Swallowing it here would emit a
# report that looks complete but is silently missing all sources.
- sources_md = _build_sources_markdown(research, db_session)
+ sources_md = _build_sources_markdown(
+ research,
+ db_session,
+ body=body,
+ uncited_mode=uncited_mode,
+ settings_snapshot=settings_snapshot,
+ )
if sources_md:
parts.append("## Sources\n\n" + sources_md)
@@ -123,7 +201,11 @@ def _build_metrics_markdown(research: ResearchHistory) -> str:
def _build_sources_markdown(
- research: ResearchHistory, db_session: Session
+ research: ResearchHistory,
+ db_session: Session,
+ body: str = "",
+ uncited_mode: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
) -> str:
"""Render the Sources block from the ``research_resources`` table.
@@ -133,6 +215,15 @@ def _build_sources_markdown(
(assigned by the search system at search time, and the number the
inline ``[N]`` references in the saved answer point to). Falls
back to row order when the original index was lost on save.
+
+ Only resources cited in ``body`` (the saved answer) are listed,
+ honoring ``report.uncited_sources_mode``. The saved snapshot on
+ the research row wins over the thread-local worker context (which
+ report/history routes never install): an explicit ``uncited_mode``
+ wins first, then an explicit ``settings_snapshot``, then the row's
+ own ``research_meta["settings_snapshot"]``, then — for legacy rows
+ that completed before snapshots were persisted — the requesting
+ user's current saved setting, then the thread context.
"""
resources = (
db_session.query(ResearchResource)
@@ -180,7 +271,46 @@ def _build_sources_markdown(
len(resources),
)
- return format_links_to_markdown(all_links)
+ return format_links_to_markdown(
+ all_links,
+ prose=body,
+ uncited_mode=_resolve_saved_uncited_mode(
+ research,
+ uncited_mode=uncited_mode,
+ settings_snapshot=settings_snapshot,
+ db_session=db_session,
+ ),
+ )
+
+
+def _resolve_saved_uncited_mode(
+ research,
+ uncited_mode: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ db_session: Optional[Session] = None,
+) -> str:
+ """Resolve the effective uncited-sources mode for a saved research row.
+
+ Precedence: explicit ``uncited_mode`` > explicit ``settings_snapshot``
+ > the row's own ``research_meta["settings_snapshot"]`` > the
+ requesting user's current saved setting (legacy snapshot-less rows
+ only) > thread context (which report routes never install) >
+ ``"fallback"``.
+ """
+ if uncited_mode is not None:
+ return resolve_uncited_sources_mode(uncited_mode)
+ snap = (
+ settings_snapshot
+ if isinstance(settings_snapshot, dict)
+ else _research_settings_snapshot(research)
+ )
+ if snap is not None:
+ return resolve_uncited_sources_mode(None, settings_snapshot=snap)
+ if db_session is not None:
+ current = _current_user_uncited_mode(db_session)
+ if current is not None:
+ return current
+ return resolve_uncited_sources_mode(None, settings_snapshot=None)
def _format_source_link(row: ResearchResource) -> Optional[Dict[str, str]]:
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 21b8e4b53b..c7ecc8a74a 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -249,6 +249,52 @@ def _parse_research_metadata(research_meta) -> dict:
return {}
+def _ensure_settings_snapshot(metadata: dict, settings_snapshot) -> dict:
+ """Back-fill ``settings_snapshot`` into completion metadata when missing.
+
+ Chat-created (``web/routers/chat.py``) and follow-up-created
+ (``web/routers/followup.py``) rows store only ``{"submission": ...}``
+ at creation, while main-form and scheduler runs persist the full
+ snapshot. Without this, ``report_assembly_service`` view/export
+ rendering (which resolves ``report.uncited_sources_mode`` from the
+ row's snapshot) always falls back for those rows, diverging from
+ what the generation-time render used.
+
+ Only fills when the row lacks a dict snapshot; an existing snapshot
+ is preserved (creation-time is the faithful preference). No-op when
+ the worker has no usable snapshot.
+ """
+ if not isinstance(metadata, dict):
+ return metadata
+ existing = metadata.get("settings_snapshot")
+ if isinstance(existing, dict):
+ return metadata
+ if isinstance(settings_snapshot, dict) and settings_snapshot:
+ metadata["settings_snapshot"] = settings_snapshot
+ return metadata
+
+
+def _merge_completion_metadata(
+ research_meta, extra: dict, settings_snapshot
+) -> dict:
+ """Build the completion-time ``research_meta`` for quick + detailed runs.
+
+ Single choke point for both completion merges in
+ ``run_research_process``: preserves the row's existing metadata,
+ overlays the run's result values, and back-fills the run's settings
+ snapshot for creation paths (chat/follow-up) that store none — so
+ later view/export renders the same uncited-sources mode the
+ generation-time render used. Covered directly by
+ ``TestMergeCompletionMetadata``; removing the back-fill here fails
+ those tests.
+ """
+ metadata = _parse_research_metadata(research_meta)
+ if isinstance(extra, dict):
+ metadata.update(extra)
+ _ensure_settings_snapshot(metadata, settings_snapshot)
+ return metadata
+
+
def _extract_synthesized_answer(results: dict) -> str:
"""Pull the LLM-synthesized answer out of a strategy result dict.
@@ -2222,15 +2268,14 @@ def run_research_process(research_id, query, mode, **kwargs):
)
# Preserve existing metadata and update with new values
- metadata = _parse_research_metadata(
- research.research_meta
- )
-
- metadata.update(
+ # (snapshot back-fill included — see helper).
+ metadata = _merge_completion_metadata(
+ research.research_meta,
{
"iterations": results["iterations"],
"generated_at": datetime.now(UTC).isoformat(),
- }
+ },
+ settings_snapshot,
)
# Use the helper function for consistent duration calculation
@@ -2552,10 +2597,12 @@ def run_research_process(research_id, query, mode, **kwargs):
)
# Preserve existing metadata and merge with report metadata
- metadata = _parse_research_metadata(research.research_meta)
-
- metadata.update(final_report["metadata"])
- metadata["iterations"] = results["iterations"]
+ # (snapshot back-fill included — see helper).
+ completion_extra = dict(final_report["metadata"])
+ completion_extra["iterations"] = results["iterations"]
+ metadata = _merge_completion_metadata(
+ research.research_meta, completion_extra, settings_snapshot
+ )
# Use the helper function for consistent duration calculation
duration_seconds = calculate_duration(
diff --git a/tests/advanced_search_system/strategies/test_base_strategy.py b/tests/advanced_search_system/strategies/test_base_strategy.py
index 672e6f64fa..c068352b51 100644
--- a/tests/advanced_search_system/strategies/test_base_strategy.py
+++ b/tests/advanced_search_system/strategies/test_base_strategy.py
@@ -382,6 +382,73 @@ class TestStrategySubclassing:
assert result["param"] == "test_value"
+class TestFormatCitations:
+ """_format_citations forwards content prose so uncited hits leave
+ the Sources block (#5379)."""
+
+ def _results(self):
+ return [
+ {"title": "A", "link": "https://cited.test/a", "index": "1"},
+ {"title": "B", "link": "https://uncited.test/b", "index": "2"},
+ ]
+
+ def test_format_citations_forwards_body_to_filter(self, monkeypatch):
+ """Regression: dropping prose= would silently disable filtering."""
+ import local_deep_research.utilities.search_utilities as su
+
+ captured = {}
+
+ def mock_format(all_links, prose=None, uncited_mode="fallback"):
+ captured["prose"] = prose
+ captured["uncited_mode"] = uncited_mode
+ return "formatted"
+
+ monkeypatch.setattr(su, "format_links_to_markdown", mock_format)
+ strategy = ConcreteStrategy()
+
+ out = strategy._format_citations("Body text [1].", self._results())
+
+ assert "## Sources" in out
+ assert captured["prose"] == "Body text [1]."
+ assert captured["uncited_mode"] == "fallback"
+
+ def test_format_citations_filters_uncited_sources(self):
+ strategy = ConcreteStrategy()
+
+ out = strategy._format_citations(
+ "Findings show progress [1].", self._results()
+ )
+
+ assert "https://cited.test/a" in out
+ assert "https://uncited.test/b" not in out
+
+ def test_format_citations_disabled_snapshot_keeps_all(self):
+ strategy = ConcreteStrategy(
+ settings_snapshot={"report.uncited_sources_mode": "disabled"}
+ )
+
+ out = strategy._format_citations(
+ "Findings show progress [1].", self._results()
+ )
+
+ assert "https://cited.test/a" in out
+ assert "https://uncited.test/b" in out
+
+ def test_format_citations_strict_snapshot_drops_uncited(self):
+ strategy = ConcreteStrategy(
+ settings_snapshot={"report.uncited_sources_mode": "strict"}
+ )
+
+ out = strategy._format_citations("No citations here.", self._results())
+
+ assert out == "No citations here."
+
+ def test_format_citations_empty_results_unchanged(self):
+ strategy = ConcreteStrategy()
+
+ assert strategy._format_citations("Body [1].", []) == "Body [1]."
+
+
class TestFirstUsableText:
"""#6941: the centralized content-or-response predicate the three
strategy assembly sites share."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index bcc833c2ee..575f2f15cb 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -2688,6 +2688,33 @@
"value": 2,
"visible": true
},
+ "report.uncited_sources_mode": {
+ "category": "report_parameters",
+ "description": "Which sources appear in the final report bibliography. Cited only with fallback keeps sources cited in the report body and falls back to all sources when no citations are detected; strict keeps only cited sources; legacy lists every accumulated search hit.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Uncited Sources Mode",
+ "options": [
+ {
+ "label": "Cited only, fall back to all if indeterminate",
+ "value": "fallback"
+ },
+ {
+ "label": "Cited only",
+ "value": "strict"
+ },
+ {
+ "label": "Legacy: all accumulated hits",
+ "value": "disabled"
+ }
+ ],
+ "step": null,
+ "type": "REPORT",
+ "ui_element": "select",
+ "value": "fallback",
+ "visible": true
+ },
"research_library.auto_index_enabled": {
"category": "research_library",
"description": "Automatically index documents for RAG search when they are added to collections (via upload or download). Indexing runs in the background without blocking uploads. Disable to defer indexing and improve upload speed for large batches.",
diff --git a/tests/test_report_generator.py b/tests/test_report_generator.py
index abfe20e930..57772e0830 100644
--- a/tests/test_report_generator.py
+++ b/tests/test_report_generator.py
@@ -204,8 +204,11 @@ def test_format_final_report(report_generator, monkeypatch):
"Findings": "# Findings\n\n## Key Results\n\nKey results content here.",
}
- # Mock format_links_to_markdown
+ # Mock format_links_to_markdown after the visible source set is resolved.
+ seen = {}
+
def mock_format_links(all_links):
+ seen["all_links"] = all_links
return "1. [Source 1](https://example.com/1)\n2. [Source 2](https://example.com/2)"
monkeypatch.setattr(
@@ -234,6 +237,122 @@ def test_format_final_report(report_generator, monkeypatch):
assert "sections_researched" in report["metadata"]
assert report["metadata"]["sections_researched"] == 2
+ assert (
+ seen["all_links"] == report_generator.search_system.all_links_of_system
+ )
+
+
+def test_format_final_report_forwards_body_to_filter(
+ report_generator, monkeypatch
+):
+ """Regression: dropping prose= would silently disable filtering."""
+ import local_deep_research.utilities.search_utilities as su
+
+ captured = {}
+
+ def mock_filter(all_links, prose, mode):
+ captured["all_links"] = all_links
+ captured["prose"] = prose
+ captured["mode"] = mode
+ return all_links
+
+ monkeypatch.setattr(su, "filter_cited_links", mock_filter)
+ monkeypatch.setattr(
+ su,
+ "format_links_to_markdown",
+ lambda all_links: "formatted",
+ )
+ structure = [
+ {"name": "Intro", "subsections": [{"name": "B", "purpose": "p"}]}
+ ]
+ sections = {"Intro": "Body text with citation [1]."}
+
+ report_generator._format_final_report(sections, structure, "q")
+
+ assert (
+ captured["all_links"]
+ == report_generator.search_system.all_links_of_system
+ )
+ assert captured["prose"] == (
+ "# Table of Contents\n\n1. **Intro**\n\n\n\n"
+ "# Research Summary\n\n"
+ "This report was researched using an advanced search system.\n\n"
+ "Research included targeted searches for each section and subsection.\n\n"
+ "\n---\n\n\nBody text with citation [1].\n\n"
+ )
+ assert captured["mode"] == "fallback"
+
+
+def test_format_final_report_filters_uncited_sources(
+ report_generator, monkeypatch
+):
+ """End to end through the real filter: uncited hits leave Sources."""
+ monkeypatch.setattr(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ lambda key, default=None, **kwargs: default,
+ )
+ report_generator.search_system.all_links_of_system = [
+ {"title": "Cited", "link": "https://cited.test/a", "index": "1"},
+ {"title": "Uncited", "link": "https://uncited.test/b", "index": "2"},
+ ]
+ structure = [
+ {"name": "Intro", "subsections": [{"name": "B", "purpose": "p"}]}
+ ]
+ sections = {"Intro": "Findings show progress [1]."}
+
+ report = report_generator._format_final_report(sections, structure, "q")
+
+ assert "https://cited.test/a" in report["content"]
+ assert "https://uncited.test/b" not in report["content"]
+ assert report["metadata"]["initial_sources"] == 1
+
+
+def test_format_final_report_disabled_mode_keeps_all_sources(
+ report_generator, monkeypatch
+):
+ """report.uncited_sources_mode=disabled restores the legacy view."""
+ monkeypatch.setattr(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ lambda key, default=None, **kwargs: "disabled",
+ )
+ report_generator.search_system.all_links_of_system = [
+ {"title": "Cited", "link": "https://cited.test/a", "index": "1"},
+ {"title": "Uncited", "link": "https://uncited.test/b", "index": "2"},
+ ]
+ structure = [
+ {"name": "Intro", "subsections": [{"name": "B", "purpose": "p"}]}
+ ]
+ sections = {"Intro": "Findings show progress [1]."}
+
+ report = report_generator._format_final_report(sections, structure, "q")
+
+ assert "https://cited.test/a" in report["content"]
+ assert "https://uncited.test/b" in report["content"]
+ assert report["metadata"]["initial_sources"] == 2
+
+
+def test_format_final_report_strict_mode_drops_uncited_sources(
+ report_generator, monkeypatch
+):
+ monkeypatch.setattr(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ lambda key, default=None, **kwargs: "strict",
+ )
+ report_generator.search_system.all_links_of_system = [
+ {"title": "Cited", "link": "https://cited.test/a", "index": "1"},
+ {"title": "Uncited", "link": "https://uncited.test/b", "index": "2"},
+ ]
+ structure = [
+ {"name": "Intro", "subsections": [{"name": "B", "purpose": "p"}]}
+ ]
+ sections = {"Intro": "No citations here."}
+
+ report = report_generator._format_final_report(sections, structure, "q")
+
+ assert "https://cited.test/a" not in report["content"]
+ assert "https://uncited.test/b" not in report["content"]
+ assert report["metadata"]["initial_sources"] == 0
+
def test_generate_report(report_generator, sample_findings, monkeypatch):
"""Test the full report generation process."""
diff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.py
index 71dc882e45..614fa644b8 100644
--- a/tests/utilities/test_search_utilities_formatting.py
+++ b/tests/utilities/test_search_utilities_formatting.py
@@ -1397,6 +1397,83 @@ class TestSourceUrlField:
assert "elsewhere.test" not in rendered
+class TestFormatFindingsUncitedFilter:
+ """format_findings filters global dumps, not per-section lists (#5379)."""
+
+ def _findings(self):
+ return [
+ {
+ "phase": "Initial",
+ "content": "Section content.",
+ "search_results": [
+ {
+ "title": "Cited",
+ "link": "https://cited.test/a",
+ "index": "1",
+ },
+ {
+ "title": "Uncited",
+ "link": "https://uncited.test/b",
+ "index": "2",
+ },
+ ],
+ },
+ ]
+
+ def test_global_dumps_filtered_per_section_kept(self):
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ out = format_findings(
+ self._findings(),
+ "Synthesis cites the first source [1].",
+ {1: ["Q?"]},
+ )
+
+ head, _, tail = out.partition("## DETAILED FINDINGS")
+ assert "https://cited.test/a" in head
+ assert "https://uncited.test/b" not in head
+ assert "## ALL SOURCES:" in out
+ assert "https://uncited.test/b" not in tail.split("## ALL SOURCES:")[1]
+ # Per-section list is scoped to its own results: unfiltered.
+ assert "SOURCES USED IN THIS SECTION" in out
+ assert out.count("https://uncited.test/b") == 1
+
+ def test_disabled_mode_keeps_all(self):
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ out = format_findings(
+ self._findings(),
+ "Synthesis cites the first source [1].",
+ {1: ["Q?"]},
+ uncited_mode="disabled",
+ )
+
+ assert out.count("https://uncited.test/b") == 3
+
+ def test_strict_mode_drops_uncited_global_sources(self):
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ out = format_findings(
+ self._findings(),
+ "No citations here.",
+ {1: ["Q?"]},
+ uncited_mode="strict",
+ )
+
+ head, _, tail = out.partition("## DETAILED FINDINGS")
+ assert "https://cited.test/a" not in head
+ assert "https://uncited.test/b" not in head
+ assert "https://cited.test/a" not in tail.split("## ALL SOURCES:")[1]
+ assert "https://uncited.test/b" not in tail.split("## ALL SOURCES:")[1]
+ assert out.count("https://uncited.test/b") == 1
+
+
class TestFilterCitedLinks:
"""Uncited-source filter engine (#5379, PR1)."""
diff --git a/tests/web/queue/test_processor_v2.py b/tests/web/queue/test_processor_v2.py
index 53f80962b6..cd62356bac 100644
--- a/tests/web/queue/test_processor_v2.py
+++ b/tests/web/queue/test_processor_v2.py
@@ -413,3 +413,132 @@ class TestQueueProcessorV2DirectExecution:
# Should fall back to queue mode
mock_queue_instance.add_task_metadata.assert_called_once()
+
+
+class TestErrorUpdateMergesMetadata:
+ """error_update merges metadata instead of replacing it (#6747).
+
+ ``handle_termination`` queues a bare ``{"terminated_at": ...}``. A
+ wholesale replace would wipe the row's ``settings_snapshot`` (and
+ ``submission`` block) that view/export rendering resolves
+ ``report.uncited_sources_mode`` from — the same divergence class the
+ snapshot back-fill closed.
+ """
+
+ def test_termination_update_preserves_snapshot_and_submission(
+ self, tmp_path
+ ):
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.database.models import Base
+ from local_deep_research.database.models.research import (
+ ResearchHistory,
+ )
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ engine = create_engine(f"sqlite:///{tmp_path}/proc_merge_test.db")
+ Base.metadata.create_all(engine)
+ sess = sessionmaker(bind=engine)()
+ try:
+ snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
+ submission = {"chat_session_id": "sess"}
+ sess.add(
+ ResearchHistory(
+ id="r-term-1",
+ query="What is X?",
+ mode="quick",
+ status=ResearchStatus.IN_PROGRESS,
+ created_at="2026-01-01T00:00:00+00:00",
+ research_meta={
+ "submission": submission,
+ "settings_snapshot": snapshot,
+ },
+ )
+ )
+ sess.commit()
+
+ processor = QueueProcessorV2()
+ processor.queue_error_update(
+ username="testuser",
+ research_id="r-term-1",
+ status=ResearchStatus.SUSPENDED,
+ error_message="Research was terminated by user",
+ metadata={"terminated_at": "2026-01-01T00:05:00+00:00"},
+ completed_at="2026-01-01T00:05:00+00:00",
+ report_path=None,
+ )
+
+ assert (
+ processor.process_pending_operations_for_user("testuser", sess)
+ == 1
+ )
+
+ row = sess.query(ResearchHistory).filter_by(id="r-term-1").first()
+ assert row.status == ResearchStatus.SUSPENDED
+ assert (
+ row.research_meta["terminated_at"]
+ == "2026-01-01T00:05:00+00:00"
+ )
+ # Pre-existing keys survive the termination update.
+ assert row.research_meta["settings_snapshot"] == snapshot
+ assert row.research_meta["submission"] == submission
+ finally:
+ sess.close()
+ engine.dispose()
+
+ def test_error_update_still_applies_without_existing_meta(self, tmp_path):
+ """Rows with no prior meta degrade to the incoming dict."""
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.database.models import Base
+ from local_deep_research.database.models.research import (
+ ResearchHistory,
+ )
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ engine = create_engine(f"sqlite:///{tmp_path}/proc_nomerge_test.db")
+ Base.metadata.create_all(engine)
+ sess = sessionmaker(bind=engine)()
+ try:
+ sess.add(
+ ResearchHistory(
+ id="r-term-2",
+ query="What is Y?",
+ mode="quick",
+ status=ResearchStatus.IN_PROGRESS,
+ created_at="2026-01-01T00:00:00+00:00",
+ research_meta=None,
+ )
+ )
+ sess.commit()
+
+ processor = QueueProcessorV2()
+ processor.queue_error_update(
+ username="testuser",
+ research_id="r-term-2",
+ status=ResearchStatus.FAILED,
+ error_message="boom",
+ metadata={"phase": "error"},
+ completed_at="2026-01-01T00:05:00+00:00",
+ report_path=None,
+ )
+
+ assert (
+ processor.process_pending_operations_for_user("testuser", sess)
+ == 1
+ )
+
+ row = sess.query(ResearchHistory).filter_by(id="r-term-2").first()
+ assert row.status == ResearchStatus.FAILED
+ assert row.research_meta == {"phase": "error"}
+ finally:
+ sess.close()
+ engine.dispose()
diff --git a/tests/web/services/test_report_assembly_service.py b/tests/web/services/test_report_assembly_service.py
index 38944c49d3..65f9717dee 100644
--- a/tests/web/services/test_report_assembly_service.py
+++ b/tests/web/services/test_report_assembly_service.py
@@ -714,3 +714,364 @@ class TestSourceLinksNonStringValues:
rows = [_row(MagicMock()), _row("https://ok.com/x", title="OK")]
links = get_research_source_links("r1", _FakeSession(rows), limit=3)
assert links == [{"url": "https://ok.com/x", "title": "OK"}]
+
+
+class TestUncitedSourcesFiltering:
+ """assemble_full_report forwards the answer body so uncited rows
+ leave the Sources block (#5379)."""
+
+ def test_assemble_forwards_body_to_filter(self, db_session, monkeypatch):
+ """Regression: dropping body= would silently disable filtering."""
+ import local_deep_research.web.services.report_assembly_service as ras
+
+ captured = {}
+
+ def mock_format(all_links, prose=None, uncited_mode="fallback"):
+ captured["prose"] = prose
+ captured["uncited_mode"] = uncited_mode
+ return "formatted-sources"
+
+ monkeypatch.setattr(ras, "format_links_to_markdown", mock_format)
+ research = _mk_research(db_session, report_content="Answer [1].")
+ _mk_resource(db_session, research.id)
+
+ assemble_full_report(research, db_session)
+
+ assert captured["prose"] == "Answer [1]."
+ assert captured["uncited_mode"] == "fallback"
+
+ def test_assemble_filters_uncited_resource_from_body(
+ self, db_session, monkeypatch
+ ):
+ """End to end through the real filter."""
+ monkeypatch.setattr(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ lambda key, default=None, **kwargs: default,
+ )
+ research = _mk_research(db_session, report_content="Cited claim [1].")
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://uncited.test/b",
+ title="B",
+ index="2",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "https://cited.test/a" in out
+ assert "https://uncited.test/b" not in out
+
+ def test_assemble_disabled_mode_keeps_all(self, db_session):
+ """Saved ``disabled`` is honored with no worker settings context.
+
+ Previously ``_build_sources_markdown`` resolved the mode from the
+ thread context only, so a report viewed/exported outside the
+ research worker always fell back to filtering even when the user
+ saved ``disabled``. Mocking the settings getter (as before) masks
+ that gap, so this uses the row's own ``settings_snapshot``.
+ """
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ research = _mk_research(
+ db_session,
+ report_content="Cited claim [1].",
+ research_meta={
+ "settings_snapshot": {
+ "report.uncited_sources_mode": {"value": "disabled"}
+ }
+ },
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://uncited.test/b",
+ title="B",
+ index="2",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "https://cited.test/a" in out
+ assert "https://uncited.test/b" in out
+
+ def test_assemble_strict_mode_saved_drops_uncited(self, db_session):
+ """Saved ``strict`` is honored with no worker settings context.
+
+ ``No citations here.`` parses to nothing: ``fallback`` would keep
+ the full bibliography while ``strict`` drops it. Asserting the
+ drop proves the saved preference — not the thread-context
+ fallback — decided the render.
+ """
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={
+ "settings_snapshot": {
+ "report.uncited_sources_mode": {"value": "strict"}
+ }
+ },
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://uncited.test/b",
+ title="B",
+ index="2",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "https://cited.test/a" not in out
+ assert "https://uncited.test/b" not in out
+ assert "## Sources" not in out
+
+ def test_assemble_chat_row_backfilled_snapshot_honors_strict(
+ self, db_session
+ ):
+ """Chat/follow-up rows gain view/export parity via back-fill (#6747).
+
+ Those creation paths store only ``{"submission": ...}``; the
+ completion merge back-fills the run's snapshot. Simulating that
+ merge here proves a chat-shaped row renders ``strict`` instead
+ of the ``fallback`` it rendered before the fix.
+ """
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+ from local_deep_research.web.services.research_service import (
+ _ensure_settings_snapshot,
+ _parse_research_metadata,
+ )
+
+ clear_settings_context()
+ chat_meta = {
+ "submission": {
+ "chat_session_id": "sess",
+ "message_id": "msg",
+ "research_mode": "quick",
+ }
+ }
+ worker_snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
+ merged = _parse_research_metadata(chat_meta)
+ _ensure_settings_snapshot(merged, worker_snapshot)
+
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta=merged,
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "## Sources" not in out
+ assert "https://cited.test/a" not in out
+
+
+def _mk_setting(db_session, key, value, ui_element="select"):
+ """Insert one row into the ``settings`` table (user's current prefs)."""
+ from local_deep_research.database.models import Setting, SettingType
+
+ row = Setting(
+ key=key,
+ value=value,
+ type=SettingType.REPORT,
+ name="Test setting",
+ ui_element=ui_element,
+ )
+ db_session.add(row)
+ db_session.commit()
+ return row
+
+
+class TestLegacySnapshotlessRows:
+ """Snapshot-less rows honor the requester's current setting (#6747).
+
+ Chat/follow-up research created AND completed before the snapshot
+ back-fill keeps ``{"submission": ...}`` forever — no snapshot can be
+ recovered for those rows. View/export then resolves the mode from
+ the requesting user's current saved preference instead of silently
+ rendering ``fallback``.
+ """
+
+ def test_snapshotless_row_honors_current_saved_strict(self, db_session):
+ """Legacy row + saved ``strict`` drops uncited sources on view."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ _mk_setting(db_session, "report.uncited_sources_mode", "strict")
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={
+ "submission": {
+ "chat_session_id": "sess",
+ "message_id": "msg",
+ "research_mode": "quick",
+ }
+ },
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "## Sources" not in out
+ assert "https://cited.test/a" not in out
+
+ def test_snapshotless_row_without_saved_setting_renders_fallback(
+ self, db_session
+ ):
+ """No snapshot and no saved value keeps the legacy render."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ # Unrelated row: keeps the settings table non-empty (no default
+ # seeding) while leaving the mode itself unset.
+ _mk_setting(db_session, "report.citation_format", "number_hyperlinks")
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={"submission": {}},
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "## Sources" in out
+ assert "https://cited.test/a" in out
+
+ def test_row_snapshot_beats_current_saved_setting(self, db_session):
+ """A persisted snapshot stays generation-faithful over a newer pref."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ _mk_setting(db_session, "report.uncited_sources_mode", "strict")
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={
+ "settings_snapshot": {
+ "report.uncited_sources_mode": {"value": "disabled"}
+ }
+ },
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "## Sources" in out
+ assert "https://cited.test/a" in out
+
+ def test_malformed_current_setting_degrades_to_fallback(self, db_session):
+ """A hand-edited current value can never wipe a bibliography."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ _mk_setting(db_session, "report.uncited_sources_mode", "legacy")
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={"submission": {}},
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(research, db_session)
+
+ assert "## Sources" in out
+ assert "https://cited.test/a" in out
+
+ def test_explicit_mode_beats_current_saved_setting(self, db_session):
+ """Callers passing ``uncited_mode`` still win over the DB value."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ _mk_setting(db_session, "report.uncited_sources_mode", "strict")
+ research = _mk_research(
+ db_session,
+ report_content="No citations here.",
+ research_meta={"submission": {}},
+ )
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://cited.test/a",
+ title="A",
+ index="1",
+ )
+
+ out = assemble_full_report(
+ research, db_session, uncited_mode="disabled"
+ )
+
+ assert "## Sources" in out
+ assert "https://cited.test/a" in out
diff --git a/tests/web/services/test_research_service_helpers.py b/tests/web/services/test_research_service_helpers.py
index 5adf6d4995..7aeb61bce1 100644
--- a/tests/web/services/test_research_service_helpers.py
+++ b/tests/web/services/test_research_service_helpers.py
@@ -3,6 +3,8 @@ Tests for research_service helper functions.
Tests cover:
- _parse_research_metadata: dict/JSON/invalid input handling
+- _ensure_settings_snapshot: back-fill for chat/follow-up rows (#6747)
+- _merge_completion_metadata: shared quick/detailed completion merge (#6747)
- get_citation_formatter: citation mode mapping from settings
- export_report_to_memory: exporter registry integration
"""
@@ -12,6 +14,8 @@ from unittest.mock import MagicMock, patch
import pytest
from local_deep_research.web.services.research_service import (
+ _ensure_settings_snapshot,
+ _merge_completion_metadata,
_parse_research_metadata,
export_report_to_memory,
get_citation_formatter,
@@ -70,6 +74,131 @@ class TestParseResearchMetadata:
assert result == nested
+# ---------------------------------------------------------------------------
+# _ensure_settings_snapshot
+# ---------------------------------------------------------------------------
+
+
+class TestEnsureSettingsSnapshot:
+ """Back-fill for chat/follow-up rows created without a snapshot (#6747).
+
+ Chat (web/routers/chat.py) and follow-up (web/routers/followup.py)
+ rows store only ``{"submission": ...}`` at creation. The completion
+ merge must persist the run's effective snapshot so view/export
+ renders the same ``report.uncited_sources_mode`` generation used.
+ """
+
+ def test_fills_missing_snapshot_from_chat_like_row(self):
+ """A submission-only row gains the worker snapshot."""
+ metadata = {
+ "submission": {
+ "chat_session_id": "s",
+ "message_id": "m",
+ "research_mode": "quick",
+ }
+ }
+ snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
+ out = _ensure_settings_snapshot(metadata, snapshot)
+ assert out["settings_snapshot"] == snapshot
+ # Same object mutated (completion merge writes it back).
+ assert out is metadata
+
+ def test_preserves_existing_snapshot(self):
+ """A main-form row keeps its creation-time snapshot."""
+ existing = {"report.uncited_sources_mode": {"value": "disabled"}}
+ metadata = {"settings_snapshot": existing, "iterations": 2}
+ other = {"report.uncited_sources_mode": {"value": "strict"}}
+ out = _ensure_settings_snapshot(metadata, other)
+ assert out["settings_snapshot"] == existing
+
+ def test_noop_when_worker_has_no_snapshot(self):
+ """Missing worker snapshot leaves the row untouched."""
+ metadata = {"submission": {}}
+ assert _ensure_settings_snapshot(metadata, None) == {"submission": {}}
+ assert _ensure_settings_snapshot(metadata, {}) == {"submission": {}}
+ assert "settings_snapshot" not in metadata
+
+ def test_overwrites_non_dict_snapshot(self):
+ """A corrupted snapshot value is replaced by a good one."""
+ metadata = {"settings_snapshot": "legacy"}
+ snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
+ out = _ensure_settings_snapshot(metadata, snapshot)
+ assert out["settings_snapshot"] == snapshot
+
+
+# ---------------------------------------------------------------------------
+# _merge_completion_metadata
+# ---------------------------------------------------------------------------
+
+
+class TestMergeCompletionMetadata:
+ """Shared quick/detailed completion merge (#6747).
+
+ Both completion merges in ``run_research_process`` route through this
+ helper, so the snapshot back-fill lives in exactly one tested place:
+ removing it here fails these tests, and removing either call site
+ leaves a merge that no longer back-fills (caught by the assembly
+ regression for chat-shaped rows).
+ """
+
+ def test_backfills_snapshot_for_chat_like_row(self):
+ """Submission-only meta gains the run snapshot plus result values."""
+ research_meta = {
+ "submission": {
+ "chat_session_id": "s",
+ "message_id": "m",
+ "research_mode": "quick",
+ }
+ }
+ snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
+ out = _merge_completion_metadata(
+ research_meta, {"iterations": 3}, snapshot
+ )
+ assert out["iterations"] == 3
+ assert out["settings_snapshot"] == snapshot
+ assert out["submission"]["chat_session_id"] == "s"
+
+ def test_preserves_existing_snapshot_and_prior_keys(self):
+ """Creation-time snapshot wins; existing result keys survive."""
+ existing = {"report.uncited_sources_mode": {"value": "disabled"}}
+ research_meta = {
+ "settings_snapshot": existing,
+ "subscription_id": "sub-1",
+ }
+ other = {"report.uncited_sources_mode": {"value": "strict"}}
+ out = _merge_completion_metadata(
+ research_meta, {"iterations": 1}, other
+ )
+ assert out["settings_snapshot"] == existing
+ assert out["subscription_id"] == "sub-1"
+ assert out["iterations"] == 1
+
+ def test_noop_snapshot_without_worker_snapshot(self):
+ """Result values still merge when the worker has no snapshot."""
+ out = _merge_completion_metadata(
+ {"submission": {}}, {"iterations": 2}, None
+ )
+ assert out == {"submission": {}, "iterations": 2}
+
+ def test_parses_json_string_meta(self):
+ """String-typed rows merge like dict rows."""
+ out = _merge_completion_metadata(
+ '{"submission": {}}',
+ {"iterations": 4},
+ {"report.uncited_sources_mode": "strict"},
+ )
+ assert out["iterations"] == 4
+ assert out["settings_snapshot"] == {
+ "report.uncited_sources_mode": "strict"
+ }
+
+ def test_does_not_mutate_extra(self):
+ """The caller's result dict (e.g. final_report metadata) is copied."""
+ extra = {"iterations": 5}
+ _merge_completion_metadata({"a": 1}, extra, {"k": "v"})
+ assert extra == {"iterations": 5}
+
+
# ---------------------------------------------------------------------------
# get_citation_formatter
# ---------------------------------------------------------------------------