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(citations): keep a fetched page title in the Sources block (#7173)

Ehsan3c29e1c63d53
diff --git a/changelog.d/6024.bugfix.md b/changelog.d/6024.bugfix.md
new file mode 100644
index 0000000000..372eae19a6
--- /dev/null
+++ b/changelog.d/6024.bugfix.md
@@ -0,0 +1,6 @@
+The report's `## Sources` block now shows a page's own title for a source
+the agent found by search and then read, instead of the long title a search
+engine scraped out of its result listing. The citation's stored title is not
+overwritten: the page title is recorded beside it and preferred at render
+time, both in the live report and in one reloaded from history. Sources
+saved before this change keep the title they were stored with.
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 75218e10ee..972ce85f52 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -48,6 +48,7 @@ from ...utilities.search_utilities import (
from ...utilities.thread_context import get_search_context, search_context
from ...utilities.url_utils import (
CHUNK_DISPLAY_KEY,
+ FETCHED_TITLE_KEY,
canonical_url_key,
library_display_url,
preferred_chunk_display,
@@ -421,6 +422,15 @@ class SearchResultsCollector:
# must keep its number.
self._pair_to_index: dict[tuple[str, str], str] = {}
self._index_to_result: dict[str, dict] = {}
+ # Canonical URL -> the page's own title, once a fetch has read it.
+ # A ``<title>`` belongs to the document, not to one citation of it,
+ # so it is kept here and applied to every entry for that URL: one
+ # document can own several indices (distinct excerpts) and several
+ # dicts (a later subsection re-cites it with a fresh copy), and
+ # annotating only the indexed one left the listing title rendering
+ # whenever the report dropped or replaced that particular entry.
+ # Persists across ``reset()``, like the dedup maps above.
+ self._doc_fetched_title: dict[str, str] = {}
# Highest seeded citation index — used by ``add_results`` and
# ``find_or_add_result`` so newly-allocated indices never collide
# with sparse seeded indices.
@@ -436,6 +446,7 @@ class SearchResultsCollector:
# wins at the readers AND blocks the collector's own anchor,
# because _prefer_anchored_link uses setdefault.
r.pop(CHUNK_DISPLAY_KEY, None)
+ r.pop(FETCHED_TITLE_KEY, None)
# ...and the fragment, for the same reason and by the same
# helper the other two paths use. Normalising the producer key
# here while leaving an unusable ``#chunk-``/other fragment was
@@ -544,6 +555,9 @@ class SearchResultsCollector:
# of reader-side validation each closed one route and
# missed the next.
r.pop(CHUNK_DISPLAY_KEY, None)
+ # The fetched title is written and preferred the same way,
+ # so it takes the same boundary strip.
+ r.pop(FETCHED_TITLE_KEY, None)
r["source_engine"] = engine_name
# Normalise URL key — citation handler expects "link"
if "link" not in r and "url" in r:
@@ -675,6 +689,12 @@ class SearchResultsCollector:
# at the other ``_sources.append``.
self._sources.append(_sanitize_sources_field(link))
self._sources_seen.add(key)
+ # After the ingest strip above, so a producer value is
+ # still dropped and only the collector's own observation
+ # is restored here. A later subsection re-citing a fetched
+ # document reuses its index but appends THIS fresh dict,
+ # which the earlier fetch could not have annotated.
+ self._apply_doc_fetched_title(r)
self._results.append(r)
self._count_result_locked()
indexed.append(r)
@@ -765,6 +785,129 @@ class SearchResultsCollector:
return
stored.setdefault(CHUNK_DISPLAY_KEY, display)
+ def _prefer_fetched_title(
+ self, index: str, url: str, title: object
+ ) -> None:
+ """Record the page's own title ALONGSIDE the stored citation.
+
+ The fetch path carries the ``<title>`` of the page it just read,
+ while the entry it folds onto was indexed from a search hit whose
+ title the engine scraped out of a result listing. Both paths already
+ share a per-field merge rule for the link; the title had none, so a
+ document cited from search and then fetched kept the listing
+ spelling everywhere ``## Sources`` is rendered.
+
+ Additive and ``setdefault``, for the reasons set out in
+ ``_prefer_anchored_link``: readers prefer this key, so overwriting
+ ``title`` would put that method's destructive write back on a field
+ two render paths read.
+
+ Only ``find_or_add_result`` calls this. ``add_results`` is the
+ search path, so a title arriving there is the spelling this rule
+ exists to improve on, not a page's own.
+
+ Callers must hold ``_lock``.
+ """
+ if not isinstance(title, str):
+ return
+ title = title.strip()
+ if not title:
+ return
+ stored = self._index_to_result.get(index)
+ if stored is None:
+ return
+ current = stored.get("link") or stored.get("url") or ""
+ if not isinstance(current, str):
+ return
+ # Confirm the entry owns this citation, exactly as
+ # ``_prefer_anchored_link`` does: the two index maps are filled by
+ # independent guards, so they can name different documents.
+ if _citation_dedup_key(current) != _citation_dedup_key(url):
+ return
+ doc_key = self._record_doc_fetched_title(url, title)
+ if not doc_key:
+ return
+ # Stamp from the MAP, never from ``title``: the first fetched
+ # title for a document is the one that sticks, so a later fetch
+ # cannot displace it and leave a rendered title that disagrees
+ # with the one stored on the entry.
+ #
+ # Every entry for the document, not just the indexed one: a
+ # distinct excerpt owns its own index, and a report citing only
+ # that index drops this entry before the renderer groups.
+ for entry in self._entries_for_doc(doc_key):
+ self._apply_doc_fetched_title(entry)
+
+ def _record_doc_fetched_title(self, url: str, title: object) -> str:
+ """Record a page's own title for its document. Returns the doc key.
+
+ First non-empty wins, matching the readers. Returns ``""`` when
+ the title is unusable or the URL cannot be keyed, so a caller can
+ tell "recorded" from "nothing to record".
+
+ Callers must hold ``_lock``.
+ """
+ if not isinstance(title, str):
+ return ""
+ title = title.strip()
+ if not title:
+ return ""
+ doc_key = _citation_dedup_key(url)
+ if not doc_key:
+ return ""
+ self._doc_fetched_title.setdefault(doc_key, title)
+ return doc_key
+
+ def _entries_for_doc(self, doc_key: str):
+ """Every live entry whose link canonicalizes to ``doc_key``.
+
+ All three lists, because no two of them contain the third: a
+ reused index echoes a fresh dict into ``_results`` only, a seeded
+ entry starts out in ``_all_links`` only, and ``_index_to_result``
+ is the only one keyed by citation index. ``_results`` is what the
+ caller feeds to ``_format_citations``, so a copy missing here
+ renders the current subsection against the listing spelling while
+ the global bibliography shows the page's own title.
+ Identity-dedup rather than value-dedup, since entries are
+ unhashable dicts and the same object appears in more than one.
+
+ Callers must hold ``_lock``.
+ """
+ seen: set[int] = set()
+ for entry in (
+ list(self._index_to_result.values())
+ + list(self._all_links)
+ + list(self._results)
+ ):
+ if not isinstance(entry, dict) or id(entry) in seen:
+ continue
+ seen.add(id(entry))
+ link = entry.get("link") or entry.get("url") or ""
+ if _citation_dedup_key(link) == doc_key:
+ yield entry
+
+ def _apply_doc_fetched_title(self, entry: dict) -> None:
+ """Stamp the recorded page title onto one entry for that document.
+
+ Used where a dict is built after the fetch that read the title:
+ the per-subsection copies, which the annotating pass cannot reach
+ because they do not exist yet.
+
+ Callers must hold ``_lock``.
+ """
+ if not isinstance(entry, dict):
+ return
+ link = entry.get("link") or entry.get("url") or ""
+ doc_key = _citation_dedup_key(link)
+ if not doc_key:
+ return
+ title = self._doc_fetched_title.get(doc_key)
+ # Nothing to add when the entry already carries that spelling as
+ # its own title, same guard as above.
+ if not title or entry.get("title") == title:
+ return
+ entry.setdefault(FETCHED_TITLE_KEY, title)
+
def find_or_add_result(
self,
result: dict,
@@ -910,6 +1053,7 @@ class SearchResultsCollector:
# unmapped left the producer key in place for exactly
# the entries that skip the branch below.
tracked.pop(CHUNK_DISPLAY_KEY, None)
+ tracked.pop(FETCHED_TITLE_KEY, None)
if idx_str not in self._index_to_result:
self._index_to_result[idx_str] = tracked
reused_key = idx_str
@@ -920,6 +1064,12 @@ class SearchResultsCollector:
# does, so it must upgrade the stored spelling too or the
# anchor loss survives on this branch.
self._prefer_anchored_link(str(reused), url)
+ # Same shape, for the field that had no merge rule.
+ # ``reused_key`` keyed, not ``str(reused)``: a padded seeded
+ # index does not round-trip through ``int``.
+ self._prefer_fetched_title(
+ reused_key or str(reused), url, result.get("title")
+ )
if first_here:
# Record the citation in ``_results`` even though no
# new entry was allocated. ``_results`` is what the
@@ -935,10 +1085,14 @@ class SearchResultsCollector:
# The reuse branch builds its own copy, so it needs
# the same producer-key strip as the allocate branch.
echoed.pop(CHUNK_DISPLAY_KEY, None)
+ echoed.pop(FETCHED_TITLE_KEY, None)
echoed["index"] = reused_key or str(reused)
echoed["source_engine"] = engine_name
if "link" not in echoed and "url" in echoed:
echoed["link"] = echoed["url"]
+ # Built after the annotating pass above, so it needs
+ # the document's title stamped on rather than copied.
+ self._apply_doc_fetched_title(echoed)
self._results.append(echoed)
self._count_result_locked()
return reused
@@ -951,6 +1105,7 @@ class SearchResultsCollector:
tracked.pop(
CHUNK_DISPLAY_KEY, None
) # producer-supplied: see add_results
+ tracked.pop(FETCHED_TITLE_KEY, None) # same
# Same unvalidated-fragment strip ``add_results`` applies. This
# branch is the fetch path: ``library_resolver`` returns the
# agent's raw ``fetch_content(url)`` argument as the citation
@@ -968,14 +1123,35 @@ class SearchResultsCollector:
self._count_result_locked()
if key:
self._pair_to_index[(key, snippet_key)] = str(index)
+ # Read BEFORE the ``setdefault`` below: an already-cited
+ # document groups both entries on its canonical URL and the
+ # bibliography renders the title of the earlier one.
+ first_idx = self._url_to_index.get(key)
# ``setdefault`` for the same reason as in
# ``add_results``: the first index a URL got is the one
# ``find_by_url`` keeps answering with.
self._url_to_index.setdefault(key, str(index))
+ if first_idx is not None:
+ self._prefer_fetched_title(
+ first_idx, url, result.get("title")
+ )
+ else:
+ # First citation of this document, and it arrived by
+ # fetch, so ``tracked["title"]`` already IS the page's
+ # own title and no key was written. Record it anyway:
+ # a second fetch would otherwise ``setdefault`` ITS
+ # title here, and the renderer prefers the key, so the
+ # later fetch displaced the earlier one and the
+ # rendered title stopped matching the stored one.
+ self._record_doc_fetched_title(url, result.get("title"))
# ``_sources`` was already recorded above, before the
# dedup branches.
self._index_to_result[str(index)] = tracked
self._all_links.append(tracked)
+ # Registered after the annotating pass above, so the loop
+ # there could not see it. This is the distinct-excerpt entry:
+ # a report citing only this index renders it alone.
+ self._apply_doc_fetched_title(tracked)
return index
def find_by_url(self, url: str) -> int | None:
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index a38a85b52c..470326c2d0 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -9,6 +9,7 @@ from local_deep_research.text_optimization.citation_formatter import (
)
from .url_utils import (
CHUNK_DISPLAY_KEY,
+ FETCHED_TITLE_KEY,
canonical_url_key,
library_display_url,
preferred_chunk_display,
@@ -211,6 +212,11 @@ def extract_links_from_search_results(search_results: List[Dict]) -> List[Dict]:
"is_open_access",
"abstract",
"metadata",
+ # The collector's own page title. This rebuild drops
+ # every key not named here, so the live report path
+ # (``_format_citations`` -> here -> the renderer) lost
+ # it while a direct render kept it.
+ FETCHED_TITLE_KEY,
):
val = result.get(key)
if val is not None:
@@ -952,6 +958,12 @@ def format_links_to_markdown(
# and credentials stay out of the report.
url_to_indices: dict[tuple[str, str], list] = {}
group_to_title: dict[tuple[str, str], str] = {}
+ # Keyed by canonical URL alone, unlike its neighbours. A document
+ # cited through both its chunk anchor and its bare URL renders one
+ # line per group, and its page title is the same on both; keying
+ # this by the group left whichever line did not hold the key
+ # showing the search listing's spelling.
+ doc_to_fetched_title: dict[str, str] = {}
group_to_quality: dict[tuple[str, str], int] = {}
group_to_collection: dict[tuple[str, str], str] = {}
group_to_display: dict[tuple[str, str], str] = {}
@@ -986,6 +998,13 @@ def format_links_to_markdown(
url_to_indices.setdefault(key, []).append(link.get("index", ""))
group_to_title.setdefault(key, link.get("title", "Untitled"))
+ # A page's own title, recorded by the fetch ingest path beside a
+ # citation whose stored title a search engine scraped. First
+ # non-empty wins, as for quality and collection below.
+ if canon not in doc_to_fetched_title:
+ fetched = link.get(FETCHED_TITLE_KEY)
+ if isinstance(fetched, str) and fetched.strip():
+ doc_to_fetched_title[canon] = fetched.strip()
# Prefer /pdf over bare /library/document/<id> for unanchored display
curr_disp = group_to_display.get(key)
if curr_disp is None or (
@@ -1024,7 +1043,7 @@ def format_links_to_markdown(
key = (canon, chunk_disp) if chunk_disp else (canon, "")
if key in seen:
continue
- title = group_to_title[key]
+ title = doc_to_fetched_title.get(canon) or group_to_title[key]
# Coerced for the same reason the url is skipped: it comes
# from the same engine dict, and ``.replace`` below raises on
# a non-str, taking the whole Sources block with it.
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index 87adea8a22..cbc8d129c7 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -369,6 +369,11 @@ def is_valid_chunk_fragment(fragment: str) -> bool:
# only add an ignored hint rather than corrupt a citation URL.
CHUNK_DISPLAY_KEY = "chunk_display_url"
+# Result-dict key holding the page's own ``<title>``, recorded alongside a
+# citation whose stored title came from a search engine's result listing. A
+# separate key for the same reason as ``CHUNK_DISPLAY_KEY``: never an overwrite.
+FETCHED_TITLE_KEY = "fetched_title"
+
def preferred_chunk_display(raw: str) -> str | None:
"""Return the display URL when *raw* is a library route WITH a valid
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 75c656ac34..f63b985b7a 100644
--- a/src/local_deep_research/web/services/report_assembly_service.py
+++ b/src/local_deep_research/web/services/report_assembly_service.py
@@ -36,7 +36,7 @@ from ...utilities.search_utilities import (
format_links_to_markdown,
resolve_uncited_sources_mode,
)
-from ...utilities.url_utils import canonical_url_key
+from ...utilities.url_utils import FETCHED_TITLE_KEY, canonical_url_key
# Line-anchored regexes for the legacy-row guard. See `assemble_full_report`
# for why a substring `in body` check is too loose. A Sources heading alone is
@@ -260,6 +260,10 @@ def _build_sources_markdown(
"title": str(r.title) if r.title else "Untitled",
"index": index,
"journal_quality": original.get("journal_quality"),
+ # ``title`` above is the column, which the search hit wrote.
+ # Rows saved before this key existed return None, which the
+ # renderer ignores.
+ FETCHED_TITLE_KEY: original.get(FETCHED_TITLE_KEY),
}
)
diff --git a/tests/advanced_search_system/strategies/test_base_strategy.py b/tests/advanced_search_system/strategies/test_base_strategy.py
index c068352b51..2db84eb11e 100644
--- a/tests/advanced_search_system/strategies/test_base_strategy.py
+++ b/tests/advanced_search_system/strategies/test_base_strategy.py
@@ -17,6 +17,7 @@ from typing import Dict
from local_deep_research.advanced_search_system.strategies.base_strategy import (
BaseSearchStrategy,
)
+from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
class ConcreteStrategy(BaseSearchStrategy):
@@ -443,6 +444,29 @@ class TestFormatCitations:
assert out == "No citations here."
+ def test_format_citations_keeps_a_fetched_page_title(self):
+ """This path runs the results through
+ ``extract_links_from_search_results`` first, and that rebuilds each
+ link from a fixed key list. The page title a fetch recorded was not
+ on it, so the live report kept rendering the search listing's
+ spelling while a direct render of the same entry showed the clean
+ one (#6024).
+ """
+ strategy = ConcreteStrategy()
+ results = [
+ {
+ "title": "Listing title | SEO suffix",
+ "link": "https://cited.test/a",
+ "index": "1",
+ FETCHED_TITLE_KEY: "Page title",
+ }
+ ]
+
+ out = strategy._format_citations("Findings [1].", results)
+
+ assert "Page title" in out
+ assert "SEO suffix" not in out
+
def test_format_citations_empty_results_unchanged(self):
strategy = ConcreteStrategy()
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index e3b587c28b..28183eeade 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -1471,3 +1471,42 @@ def test_read_max_fetches_setting_clamping():
)
== DEFAULT_MAX_FETCHES_PER_TOPIC
)
+
+
+def test_full_mode_fetch_puts_the_page_title_in_the_bibliography():
+ """The whole production chain for #6024, entered at the tool and with
+ only the HTTP fetcher stubbed: a source the agent found by search and
+ then read keeps the title the search engine scraped out of its result
+ listing, because ``find_or_add_result`` folds the fetch onto the existing
+ citation and upgrades only the link spelling.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+
+ listing_title = (
+ "Caste in India: a comprehensive guide to its origins, Vedic "
+ "foundations, Manusmriti and modern implications | 2026 | Archive"
+ )
+ page_title = "Caste system in India - Wikipedia"
+ url = "http://example.com/caste"
+
+ all_links = []
+ collector = SearchResultsCollector(all_links)
+ collector.add_results(
+ [{"title": listing_title, "link": url, "snippet": "paradigmatic"}],
+ engine_name="searxng",
+ )
+
+ tool = build_fetch_tool("full", collector)
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher",
+ return_value=_fetcher_cm(title=page_title, content="Body text"),
+ ):
+ tool.invoke({"url": url})
+
+ rendered = format_links_to_markdown(all_links)
+ assert page_title in rendered
+ assert "comprehensive guide" not in rendered
+ # Recorded alongside: the stored citation title is untouched.
+ assert all_links[0]["title"] == listing_title
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 42c49c2ef5..36638ceed2 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -19,10 +19,12 @@ from unittest.mock import ANY, MagicMock, patch
import pytest
from local_deep_research.utilities.search_utilities import (
+ extract_links_from_search_results,
format_links_to_markdown,
)
from local_deep_research.utilities.url_utils import (
CHUNK_DISPLAY_KEY,
+ FETCHED_TITLE_KEY,
canonical_url_key,
)
@@ -579,6 +581,326 @@ class TestSearchResultsCollector:
)
assert anchored in format_links_to_markdown(all_links)
+ SEARCH_TITLE = (
+ "The caste system in India: a comprehensive guide to its historical "
+ "origins, Vedic foundations, Manusmriti, and modern implications | "
+ "2026 | Caste History Archive"
+ )
+ PAGE_TITLE = "Caste system in India - Wikipedia"
+ DOC_URL = "https://en.wikipedia.org/wiki/Caste_system_in_India"
+ SEARCH_SNIPPET = "The caste system in India is the paradigmatic example"
+
+ def _search_then_fetch(self, fetch_snippet):
+ """Index one search hit, then fetch the same URL. Returns
+ ``(all_links, collector)``.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ collector.add_results(
+ [
+ {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ "snippet": self.SEARCH_SNIPPET,
+ }
+ ],
+ engine_name="searxng",
+ )
+ collector.find_or_add_result(
+ {
+ "title": self.PAGE_TITLE,
+ "link": self.DOC_URL,
+ "snippet": fetch_snippet,
+ },
+ engine_name="fetch",
+ )
+ return all_links, collector
+
+ @pytest.mark.parametrize(
+ "fetch_snippet",
+ ["", SEARCH_SNIPPET, "Caste is a fixed social group one is born into"],
+ ids=["content-free", "same-as-search", "distinct-evidence"],
+ )
+ def test_fetched_page_title_reaches_the_bibliography(self, fetch_snippet):
+ """The fetch path carries the page's own ``<title>``; the entry it
+ folds onto carries the one a search engine scraped. The reuse branch
+ upgraded the stored link spelling and dropped the title, and a
+ distinct fetch excerpt allocates a second entry whose clean title the
+ canonical-URL grouping then discards first-wins. All three shapes
+ rendered the listing spelling.
+ """
+ all_links, collector = self._search_then_fetch(fetch_snippet)
+
+ for links in (all_links, collector.results):
+ rendered = format_links_to_markdown(links)
+ assert self.PAGE_TITLE in rendered
+ assert "comprehensive guide" not in rendered
+
+ def test_fetched_page_title_does_not_overwrite_the_stored_title(self):
+ """Recorded alongside, never over ``title``. The overwrite is the
+ write ``_prefer_anchored_link`` was walked back from, and this field
+ is read by the bibliography and by the saved-report path.
+ """
+ all_links, _ = self._search_then_fetch("")
+
+ assert all_links[0]["title"] == self.SEARCH_TITLE
+ assert all_links[0][FETCHED_TITLE_KEY] == self.PAGE_TITLE
+
+ def test_fetched_page_title_is_refused_for_another_document(self):
+ """``_url_to_index`` and ``_index_to_result`` are filled by
+ independent "if not already present" guards, so they can name
+ different documents. A title the reader prefers over the entry's own
+ would then put one document's name on another's citation.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ collector.add_results(
+ [{"title": "Other doc", "link": "https://other.test/p"}],
+ engine_name="searxng",
+ )
+ # Point the URL map at the other document's entry, which is what the
+ # independent guards can produce.
+ collector._url_to_index[canonical_url_key(self.DOC_URL)] = "1"
+ collector.find_or_add_result(
+ {"title": self.PAGE_TITLE, "link": self.DOC_URL},
+ engine_name="fetch",
+ )
+
+ assert FETCHED_TITLE_KEY not in all_links[0]
+ assert "Other doc" in format_links_to_markdown(all_links)
+
+ @pytest.mark.parametrize(
+ "fetched_title",
+ ["", " ", None, 7],
+ ids=["empty", "blank", "none", "int"],
+ )
+ def test_unusable_fetched_title_leaves_the_citation_alone(
+ self, fetched_title
+ ):
+ """A fetch can come back with no title. Recording one anyway would
+ make the renderer, which prefers this key, fall through to
+ ``"Untitled"``.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ collector.add_results(
+ [{"title": self.SEARCH_TITLE, "link": self.DOC_URL}],
+ engine_name="searxng",
+ )
+ collector.find_or_add_result(
+ {"title": fetched_title, "link": self.DOC_URL},
+ engine_name="fetch",
+ )
+
+ assert FETCHED_TITLE_KEY not in all_links[0]
+ assert self.SEARCH_TITLE in format_links_to_markdown(all_links)
+
+ def test_fetched_page_title_survives_a_later_subsection(self):
+ """``reset()`` clears ``_results`` and keeps the dedup maps, so a
+ later subsection citing the same URL and snippet reuses the index
+ but appends a FRESH dict. The fetch had annotated the entry held in
+ ``_index_to_result``, which this copy is not, so rendering that
+ subsection's own results went back to the listing title.
+ """
+ all_links, collector = self._search_then_fetch(self.SEARCH_SNIPPET)
+ collector.reset()
+ collector.add_results(
+ [
+ {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ "snippet": self.SEARCH_SNIPPET,
+ }
+ ],
+ engine_name="searxng",
+ )
+
+ section = collector.results
+ assert len(section) == 1
+ rendered = format_links_to_markdown(section)
+ assert self.PAGE_TITLE in rendered
+ assert "comprehensive guide" not in rendered
+ # The index the first subsection allocated is the one kept.
+ assert section[0]["index"] == "1"
+ assert section[0]["title"] == self.SEARCH_TITLE
+
+ @pytest.mark.parametrize(
+ "prose", [None, "Only this [1]."], ids=["unfiltered", "cites-first"]
+ )
+ @pytest.mark.parametrize(
+ "same_pair", [False, True], ids=["allocate-branch", "reuse-branch"]
+ )
+ def test_fetched_page_title_reaches_a_copy_made_before_the_fetch(
+ self, prose, same_pair
+ ):
+ """The subsection copy can predate the fetch, not only follow it.
+ ``reset()`` then a repeat search appends a fresh dict to
+ ``_results`` while the dedup maps still point at the first entry,
+ and the fetch after it annotated only the entries the traversal
+ reached, which did not include ``_results``. The subsection
+ rendered the listing spelling while the bibliography rendered the
+ page's own.
+
+ Both dedup outcomes are covered because they take different
+ branches of ``find_or_add_result``: a snippet the search hit did
+ not carry allocates a second entry, while the search snippet
+ itself reuses the first and allocates nothing. The third render
+ goes through ``extract_links_from_search_results``, the live
+ report path, which rebuilds every link dict from a fixed key
+ list and so has to name the title key to keep it.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ hit = {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ "snippet": self.SEARCH_SNIPPET,
+ }
+ collector.add_results([dict(hit)], engine_name="searxng")
+ collector.reset()
+ collector.add_results([dict(hit)], engine_name="searxng")
+ before = len(all_links)
+ collector.find_or_add_result(
+ {
+ "title": self.PAGE_TITLE,
+ "link": self.DOC_URL,
+ "snippet": self.SEARCH_SNIPPET
+ if same_pair
+ else "Caste is a fixed social group one is born into",
+ },
+ engine_name="fetch",
+ )
+ # Pinned so a dedup change cannot route both ids down one branch
+ # and leave the other spelling of this case silently uncovered.
+ assert len(all_links) == before + (0 if same_pair else 1)
+
+ for links in (
+ collector.results,
+ all_links,
+ extract_links_from_search_results(collector.results),
+ ):
+ rendered = format_links_to_markdown(links, prose=prose)
+ assert self.PAGE_TITLE in rendered
+ assert "comprehensive guide" not in rendered
+
+ def test_fetched_page_title_survives_citation_filtering(self):
+ """Two search excerpts of one document own two indices, and the
+ fetch annotates only the first. A report citing just the second
+ drops the annotated entry before the renderer groups by canonical
+ URL, which restored the listing title in the global bibliography.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ collector.add_results(
+ [
+ {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ "snippet": self.SEARCH_SNIPPET,
+ },
+ {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ "snippet": "A second excerpt from the same page",
+ },
+ ],
+ engine_name="searxng",
+ )
+ collector.find_or_add_result(
+ {
+ "title": self.PAGE_TITLE,
+ "link": self.DOC_URL,
+ "snippet": "Caste is a fixed social group one is born into",
+ },
+ engine_name="fetch",
+ )
+
+ assert [link["index"] for link in all_links] == ["1", "2", "3"]
+ rendered = format_links_to_markdown(all_links, prose="Only this [2].")
+ assert self.PAGE_TITLE in rendered
+ assert "comprehensive guide" not in rendered
+
+ def test_first_fetched_title_wins_on_a_fetch_only_document(self):
+ """A document reached by fetch with no search hit first keeps the
+ page title as its own ``title``, so no key is written. A second
+ fetch then had nothing to lose to and recorded ITS title, which
+ the renderer prefers, so the later read displaced the earlier one
+ and the rendered title stopped matching the stored one. That also
+ let a degraded re-fetch (a challenge or consent shell) take over a
+ good first read.
+
+ Carried to a third read and across a subsection boundary, which
+ are the two ways "first wins" can be lost after it is won: a
+ recovered third title is as able to displace the first as the
+ degraded second one was, and the subsection list that a later
+ fetch rebuilds has to render the first title rather than the
+ title of the read that rebuilt it.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ for title, snippet in (
+ ("Page title v1", "first fetch body"),
+ ("Page title v2", "second fetch, different body"),
+ ("Page title v3", "third fetch, recovered body"),
+ ):
+ collector.find_or_add_result(
+ {"title": title, "link": self.DOC_URL, "snippet": snippet},
+ engine_name="fetch",
+ )
+
+ assert all_links[0]["title"] == "Page title v1"
+ assert FETCHED_TITLE_KEY not in all_links[0]
+ assert all_links[1][FETCHED_TITLE_KEY] == "Page title v1"
+ assert all_links[2][FETCHED_TITLE_KEY] == "Page title v1"
+ rendered = format_links_to_markdown(all_links)
+ assert "Page title v1" in rendered
+ assert "Page title v2" not in rendered
+ assert "Page title v3" not in rendered
+
+ collector.reset()
+ collector.find_or_add_result(
+ {
+ "title": "Page title v3",
+ "link": self.DOC_URL,
+ "snippet": "a fetch in the next subsection",
+ },
+ engine_name="fetch",
+ )
+ section = collector.results
+ assert len(section) == 1
+ assert section[0]["title"] == "Page title v3"
+ assert section[0][FETCHED_TITLE_KEY] == "Page title v1"
+ rendered = format_links_to_markdown(section)
+ assert "Page title v1" in rendered
+ assert "Page title v3" not in rendered
+
+ def test_producer_supplied_fetched_title_is_stripped_at_ingest(self):
+ """Written by the collector and preferred by the renderer, so an
+ engine dict setting it would choose the bibliography's title and,
+ because the write is a ``setdefault``, lock out the real one.
+ """
+ all_links = []
+ collector, _ = self._make_collector(all_links)
+ collector.add_results(
+ [
+ {
+ "title": self.SEARCH_TITLE,
+ "link": self.DOC_URL,
+ FETCHED_TITLE_KEY: "Engine chose this",
+ }
+ ],
+ engine_name="searxng",
+ )
+
+ assert FETCHED_TITLE_KEY not in all_links[0]
+
+ collector.find_or_add_result(
+ {"title": self.PAGE_TITLE, "link": self.DOC_URL},
+ engine_name="fetch",
+ )
+
+ assert all_links[0][FETCHED_TITLE_KEY] == self.PAGE_TITLE
+
def test_find_or_add_result_still_finds_externally_appended_entries(self):
"""The fallback scan is skipped when ``_url_to_index`` accounts for
every entry — it canonicalises the whole list under the lock, which
diff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.py
index 614fa644b8..0d3344a0d8 100644
--- a/tests/utilities/test_search_utilities_formatting.py
+++ b/tests/utilities/test_search_utilities_formatting.py
@@ -2078,3 +2078,158 @@ class TestFilterCitedLinks:
for mode in ("fallback", "strict"):
kept = self._filter(self._links(), prose, mode=mode)
assert [link["index"] for link in kept] == ["1", "2"], mode
+
+
+def test_format_links_prefers_a_recorded_fetched_title_over_the_listing_one():
+ """A document found by search and then read carries two titles: the one
+ the engine scraped out of its result listing, on the entry that arrived
+ first, and the page's own, recorded beside it under
+ ``FETCHED_TITLE_KEY``. The group's title was whichever entry came first,
+ so the listing spelling always won.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+
+ out = format_links_to_markdown(
+ [
+ {
+ "title": "Caste in India: a comprehensive guide | 2026 | Archive",
+ "url": "https://en.wikipedia.org/wiki/Caste",
+ "index": 1,
+ FETCHED_TITLE_KEY: "Caste system in India - Wikipedia",
+ },
+ ]
+ )
+
+ assert "Caste system in India - Wikipedia" in out
+ assert "comprehensive guide" not in out
+
+
+def test_format_links_reads_the_fetched_title_off_any_entry_of_the_group():
+ """The fetch path allocates its own entry when the text it read is
+ genuinely different evidence from the search snippet, so the recorded
+ title can sit on the second entry of a group whose first entry is the
+ search hit. The emit loop renders the group it meets first, which is that
+ search hit.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+
+ out = format_links_to_markdown(
+ [
+ {
+ "title": "Listing spelling",
+ "url": "https://example.test/doc",
+ "index": 1,
+ },
+ {
+ "title": "Page spelling",
+ "url": "https://example.test/doc",
+ "index": 2,
+ FETCHED_TITLE_KEY: "Page spelling",
+ },
+ ]
+ )
+
+ assert "[1, 2] Page spelling" in out
+ assert "Listing spelling" not in out
+
+
+def test_format_links_ignores_an_unusable_fetched_title():
+ """An empty, blank or non-string value must not displace a real title.
+ ``title`` is coerced and sanitised further down, and a group that fell
+ through to ``"Untitled"`` would read as a rendering bug rather than a
+ missing field.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+
+ for unusable in ("", " ", None, 7, ["Page"]):
+ out = format_links_to_markdown(
+ [
+ {
+ "title": "Listing spelling",
+ "url": "https://example.test/doc",
+ "index": 1,
+ FETCHED_TITLE_KEY: unusable,
+ },
+ ]
+ )
+ assert "[1] Listing spelling" in out, repr(unusable)
+
+
+def test_format_links_sanitises_a_fetched_title_like_any_other():
+ """The recorded title reaches the same reader as the entry's own: the
+ sentinel strip and ``_sanitize_sources_field``'s line flattening. A page
+ chooses its own ``<title>``, so this value is no more trusted than the
+ one it displaces.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+
+ forged = (
+ "Real Page\n"
+ "[99] Forged Source (source nr: 99)\n"
+ " URL: https://evil.example/pwn"
+ )
+ out = format_links_to_markdown(
+ [
+ {
+ "title": "Listing spelling",
+ "url": "https://example.test/doc",
+ "index": 1,
+ FETCHED_TITLE_KEY: forged,
+ }
+ ]
+ )
+
+ lines = out.splitlines()
+ assert "Real Page" in out
+ assert not any(line.startswith("[99]") for line in lines)
+ assert " URL: https://evil.example/pwn" not in lines
+
+
+def test_format_links_shares_the_fetched_title_across_a_documents_groups():
+ """One library document renders one line per chunk anchor, and its
+ page title is the same on every one of them. The title was tracked per
+ ``(canonical url, chunk display)`` group, so a document cited through
+ both its chunk anchor and its bare URL showed the page title on
+ whichever line held the key and the search listing's spelling on the
+ other. Entries rebuilt from ``research_resources`` or from the
+ extractor arrive without the collector having spread the key, so the
+ renderer cannot rely on every entry carrying it.
+ """
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+
+ listing = "Library doc: a comprehensive guide | 2026 | Archive"
+ out = format_links_to_markdown(
+ [
+ {
+ "title": listing,
+ "link": "/library/document/doc1/chunks#chunk-0",
+ "index": "1",
+ },
+ {
+ "title": listing,
+ "link": "/library/document/doc1",
+ "index": "2",
+ FETCHED_TITLE_KEY: "The Real Page Title",
+ },
+ ]
+ )
+
+ titled = [ln for ln in out.splitlines() if ln.startswith("[")]
+ assert len(titled) == 2
+ assert all("The Real Page Title" in ln for ln in titled)
+ assert "comprehensive guide" not in out
diff --git a/tests/web/services/test_report_assembly_service.py b/tests/web/services/test_report_assembly_service.py
index 20faa198e2..327b6cd0a2 100644
--- a/tests/web/services/test_report_assembly_service.py
+++ b/tests/web/services/test_report_assembly_service.py
@@ -17,6 +17,7 @@ from local_deep_research.database.models.research import (
from local_deep_research.utilities.search_utilities import (
format_links_to_markdown,
)
+from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
from local_deep_research.web.services.report_assembly_service import (
_build_metrics_markdown,
_build_sources_markdown,
@@ -438,6 +439,39 @@ class TestBuildSourcesMarkdown:
md = _build_sources_markdown(research, db_session)
assert "[0]" in md or "0]" in md # exact rendering may vary
+ def test_saved_row_renders_the_fetched_page_title(self, db_session):
+ """The ``title`` column holds the spelling the search engine
+ scraped; the page's own is in ``original_data``, where the collector
+ recorded it. Rendering from the row took the column.
+ """
+ research = _mk_research(db_session)
+ listing = "A comprehensive guide to X | 2026 | Archive"
+ _mk_resource(
+ db_session,
+ research.id,
+ url="https://x.test/doc",
+ title=listing,
+ resource_metadata={
+ "original_data": {
+ "index": "1",
+ "url": "https://x.test/doc",
+ "title": listing,
+ FETCHED_TITLE_KEY: "X - Wikipedia",
+ }
+ },
+ )
+ md = _build_sources_markdown(research, db_session)
+ assert "X - Wikipedia" in md
+ assert "comprehensive guide" not in md
+
+ def test_saved_row_without_the_key_keeps_its_title(self, db_session):
+ """Which is every row written before this change."""
+ research = _mk_research(db_session)
+ _mk_resource(
+ db_session, research.id, url="https://y.test/d", title="Y title"
+ )
+ assert "Y title" in _build_sources_markdown(research, db_session)
+
# ---------------------------------------------------------------------------
# get_research_source_links