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(report): honor legacy preferences and hide raw errors (#7165)

LearningCircuit2940c8cd8445
diff --git a/changelog.d/+error-report-disclosure.security.md b/changelog.d/+error-report-disclosure.security.md
new file mode 100644
index 0000000000..878161de2a
--- /dev/null
+++ b/changelog.d/+error-report-disclosure.security.md
@@ -0,0 +1 @@
+Keep raw provider and exception details out of saved research error reports and quick-mode synthesis fallbacks, including simultaneous synthesis and formatting failures, while retaining safe category hints even when every finding failed, worker error guidance, and non-error partial findings.
diff --git a/changelog.d/+legacy-research-error-metadata.security.md b/changelog.d/+legacy-research-error-metadata.security.md
new file mode 100644
index 0000000000..d2c44c7b42
--- /dev/null
+++ b/changelog.d/+legacy-research-error-metadata.security.md
@@ -0,0 +1 @@
+Replace untrusted persisted research error text with an authored message in API metadata and status guidance, so legacy exception strings cannot disclose server report paths while known safe failure reasons remain visible during polling. Support legacy JSON-string metadata and preserve cleared error values without reporting false failures.
diff --git a/changelog.d/+legacy-uncited-sources-preference.bugfix.md b/changelog.d/+legacy-uncited-sources-preference.bugfix.md
new file mode 100644
index 0000000000..573021d2bc
--- /dev/null
+++ b/changelog.d/+legacy-uncited-sources-preference.bugfix.md
@@ -0,0 +1 @@
+Saved reports with older settings snapshots now honor the user's current uncited-sources preference when the snapshot has no uncited-sources value.
diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.py
index 9cdf212dad..8c90b07a28 100644
--- a/src/local_deep_research/advanced_search_system/findings/repository.py
+++ b/src/local_deep_research/advanced_search_system/findings/repository.py
@@ -161,8 +161,10 @@ class FindingsRepository(BaseFindingsRepository):
return formatted_report
except Exception:
logger.exception("Error occurred during final report formatting")
- # Fallback: return just the synthesized content if formatting fails
- return f"Error during final formatting. Raw Synthesized Content:\n\n{synthesized_content}"
+ # Preserve the answer, including an "Error:" prefix when synthesis
+ # also failed. A wrapper hides that prefix from the worker's safe
+ # recovery path and can turn raw exception details into a report.
+ return synthesized_content
def synthesize_findings(
self,
diff --git a/src/local_deep_research/error_handling/error_messages.py b/src/local_deep_research/error_handling/error_messages.py
new file mode 100644
index 0000000000..89178a6603
--- /dev/null
+++ b/src/local_deep_research/error_handling/error_messages.py
@@ -0,0 +1,50 @@
+"""Authored research failure messages shared by reports and API responses."""
+
+TYPED_RESEARCH_ERROR_MESSAGES = {
+ "ollama_unavailable": "Ollama AI service is unavailable.",
+ "model_not_found": "The configured LLM model was not found.",
+ "connection_error": "Could not connect to the configured LLM server.",
+ "api_error": "The language model API rejected the request.",
+ "openai_connection_refused": "Could not connect to the configured LLM server.",
+ "openai_timeout": "The configured LLM server timed out.",
+ "openai_auth": "Authentication with the LLM provider failed.",
+ "openai_permission_denied": "The LLM provider denied access to the model.",
+ "openai_model_not_found": "The configured LLM model was not found.",
+ "openai_bad_request": "The LLM server rejected the request.",
+ "openai_unknown": "The configured LLM provider returned an error.",
+ "openai_rate_limit": "The LLM provider rate-limited the request.",
+}
+
+_SAFE_WORKER_MESSAGES = frozenset(TYPED_RESEARCH_ERROR_MESSAGES.values()) | {
+ "Ollama AI service is unavailable. Please check that Ollama is running properly on your system.",
+ "Required Ollama model not found. Please pull the model first.",
+ "Connection error with LLM service. Please check that your AI service is running.",
+ "Authentication with the configured LLM provider failed.",
+ "The configured LLM provider denied access to the model.",
+ "The configured model was not found on the LLM server.",
+ "There was a problem with the LLM configuration.",
+ "There was a problem with the search engine configuration.",
+ "Egress policy could not verify this run, so it was refused (fail-closed).",
+}
+
+
+def get_known_research_error_message(error_message: object) -> str | None:
+ """Return authored guidance, or None when the stored text is untrusted.
+
+ A worker message is safe only when it matches exactly: appended provider
+ details must not pass through. Policy refusals carry an internal reason
+ suffix, so replace those with fixed text rather than returning the input.
+ """
+ if not isinstance(error_message, str):
+ return None
+ message = error_message.removeprefix("Research failed: ")
+ if message in _SAFE_WORKER_MESSAGES:
+ return message
+ if message.startswith("Egress policy refused this run: a sensitive source"):
+ return (
+ "Egress policy refused this run: a sensitive source would "
+ "reach an exposing destination."
+ )
+ if message.startswith("Egress policy refused this run"):
+ return "Egress policy refused this run."
+ return None
diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.py
index 2dedfd5dc8..6387abb019 100644
--- a/src/local_deep_research/error_handling/report_generator.py
+++ b/src/local_deep_research/error_handling/report_generator.py
@@ -7,9 +7,19 @@ from typing import Any, Dict, Optional
from loguru import logger
+from .error_messages import (
+ TYPED_RESEARCH_ERROR_MESSAGES,
+ get_known_research_error_message,
+)
from .error_reporter import ErrorReporter
+_GENERIC_ERROR_MESSAGE = (
+ "Research failed due to an unexpected error. "
+ "Check the server logs for details."
+)
+
+
class ErrorReportGenerator:
"""
Generates comprehensive, user-friendly error reports
@@ -108,7 +118,7 @@ class ErrorReportGenerator:
logger.exception("Failed to generate error report")
return f"""# ⚠️ Research Failed
-**What happened:** {error_message}
+**What happened:** {_GENERIC_ERROR_MESSAGE}
## 💬 Get Help
We're here to help you get this working:
@@ -138,7 +148,11 @@ We're here to help you get this working:
# Current knowledge summary
if "current_knowledge" in partial_results:
knowledge = partial_results["current_knowledge"]
- if knowledge and len(knowledge.strip()) > 50:
+ if (
+ isinstance(knowledge, str)
+ and not knowledge.lstrip().lower().startswith("error:")
+ and len(knowledge.strip()) > 50
+ ):
formatted_parts.append("### Research Summary\n")
formatted_parts.append(
knowledge[:1000] + "..."
@@ -164,18 +178,26 @@ We're here to help you get this working:
if "findings" in partial_results:
findings = partial_results["findings"]
if findings:
- formatted_parts.append("### Research Findings\n")
- for i, finding in enumerate(findings[:3], 1): # Show top 3
+ valid_findings = [
+ (i, finding)
+ for i, finding in enumerate(findings[:3], 1)
+ if isinstance(finding.get("content"), str)
+ and finding["content"]
+ and not finding["content"]
+ .lstrip()
+ .lower()
+ .startswith("error:")
+ ]
+ if valid_findings:
+ formatted_parts.append("### Research Findings\n")
+ for i, finding in valid_findings:
content = finding.get("content", "")
- if content and not content.startswith("Error:"):
- phase = finding.get("phase", f"Finding {i}")
- formatted_parts.append(f"**{phase}:**")
- formatted_parts.append(
- content[:500] + "..."
- if len(content) > 500
- else content
- )
- formatted_parts.append("")
+ phase = finding.get("phase", f"Finding {i}")
+ formatted_parts.append(f"**{phase}:**")
+ formatted_parts.append(
+ content[:500] + "..." if len(content) > 500 else content
+ )
+ formatted_parts.append("")
if formatted_parts:
formatted_parts.append(
@@ -293,28 +315,29 @@ We're here to help you get this working:
error_message: The original technical error message
Returns:
- str: User-friendly error message, or original if no replacement found
+ str: User-friendly error message without raw exception details
"""
- # Messages carrying a SPECIFIC "(Error type: <code>)" token have already
- # been classified and rewritten into user-friendly text by upstream code
- # (openai_compat_errors, the Ollama/status-code branches in
- # research_service). Return those unchanged -- the regex patterns below
- # are meant for raw, unrewritten exceptions only, and would otherwise
- # clobber the tailored upstream message (e.g. the openai_connection_refused
- # message getting overwritten by the generic "Connection refused" hint).
- #
- # "(Error type: unknown)", however, is attached to a RAW exception string
- # that upstream could NOT classify (research_service appends the token to
- # str(exc) verbatim). Let those fall through to the replacement table
- # below -- it acts as a second-chance classifier and can only add help to
- # an otherwise-cryptic message, never clobber friendly text.
- if (
- re.search(r"\(Error type: \w+\)", error_message)
- and "(Error type: unknown)" not in error_message
- ):
- return error_message
+ worker_message = get_known_research_error_message(error_message)
+ if worker_message is not None:
+ return worker_message
+
+ # A typed upstream message can still contain a provider URL or a raw
+ # "| Details:" suffix. Select only authored text for its code. Unknown
+ # types fall through to the pattern table for a second classification.
+ typed_error = re.search(
+ r"\(Error type: (\w+)\)", error_message, re.IGNORECASE
+ )
+ if typed_error and typed_error.group(1).lower() != "unknown":
+ return TYPED_RESEARCH_ERROR_MESSAGES.get(
+ typed_error.group(1).lower(), _GENERIC_ERROR_MESSAGE
+ )
# Dictionary of technical errors to user-friendly messages
error_replacements = {
+ "Egress policy refused this run: a sensitive source": (
+ "Egress policy refused this run: a sensitive source would "
+ "reach an exposing destination."
+ ),
+ "Egress policy refused this run": "Egress policy refused this run.",
"max_workers must be greater than 0": (
"The LLM failed to generate search questions. This usually means the LLM service isn't responding properly.\n\n"
"**Try this:**\n"
@@ -451,7 +474,6 @@ We're here to help you get this working:
# Check each pattern and replace if found
for pattern, replacement in error_replacements.items():
if re.search(pattern, error_message, re.IGNORECASE):
- return f"{replacement}\n\nTechnical error: {error_message}"
+ return replacement
- # If no specific replacement found, return original message
- return error_message
+ return _GENERIC_ERROR_MESSAGE
diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.py
index 89d1dd1762..2f466ac393 100644
--- a/src/local_deep_research/security/data_sanitizer.py
+++ b/src/local_deep_research/security/data_sanitizer.py
@@ -11,6 +11,8 @@ from being sent to the frontend.
import json
from typing import Any, Set
+from ..error_handling.error_messages import get_known_research_error_message
+
# The placeholder a redacted value is replaced with. Single source of truth
# so that write-back guards (which must treat this sentinel as a no-op to
@@ -18,6 +20,11 @@ from typing import Any, Set
# cannot drift from what the redactor actually emits.
REDACTION_TEXT = "[REDACTED]"
+# Older research rows persisted str(exception) in research_meta["error"].
+# That value can include report paths and other server-side details. API
+# responses retain only known authored messages; other text is replaced.
+PUBLIC_RESEARCH_ERROR = "Research failed. Check the server logs for details."
+
# Unicode 16.0 DerivedCoreProperties.txt, Default_Ignorable_Code_Point.
# Most Unicode Default_Ignorable_Code_Point characters are non-printable and
# are removed by str.isprintable(). These exceptions are printable combining
@@ -660,17 +667,20 @@ def filter_research_metadata(research_meta: Any) -> dict:
def strip_settings_snapshot(research_meta: Any) -> dict:
- """Remove settings_snapshot from research_meta for API responses.
+ """Remove private fields from research_meta for API responses.
settings_snapshot contains all application settings including API keys.
- This strips it while preserving all other metadata fields that the
- frontend needs (phase, error_type, processed_query, mode, duration, etc.).
+ Legacy error strings can contain absolute report paths because older
+ writers persisted str(exception). Preserve the error field's shape for
+ clients, but allow only known authored messages through. Keep other
+ metadata fields that the frontend needs (phase, error_type,
+ processed_query, mode, duration, etc.).
Args:
research_meta: Raw research metadata (dict, JSON string, or None)
Returns:
- Copy of the dict with settings_snapshot removed
+ Copy of the dict with settings_snapshot removed and error masked
"""
try:
meta = research_meta or {}
@@ -678,6 +688,12 @@ def strip_settings_snapshot(research_meta: Any) -> dict:
meta = json.loads(meta)
if not isinstance(meta, dict):
return {}
- return {k: v for k, v in meta.items() if k != "settings_snapshot"}
+ public = {k: v for k, v in meta.items() if k != "settings_snapshot"}
+ if public.get("error"):
+ public["error"] = (
+ get_known_research_error_message(public["error"])
+ or PUBLIC_RESEARCH_ERROR
+ )
+ return public
except (json.JSONDecodeError, TypeError, AttributeError):
return {}
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index effb8e5986..0f1f7c9618 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -37,6 +37,7 @@ from typing import Optional, Annotated
# Security imports
from ...config.constants import DEFAULT_OLLAMA_URL
from ...exceptions import DuplicateResearchError, SystemAtCapacityError
+from ...error_handling.error_messages import get_known_research_error_message
from ...constants import HISTORY_LOGS_HARD_CAP, ResearchStatus
from ...security import (
FileUploadValidator,
@@ -74,6 +75,7 @@ from ...database.session_context import get_user_db_session
from ...llm.providers.base import normalize_provider
from ..auth.password_utils import resolve_user_password
from ..services.research_service import (
+ _parse_research_metadata,
clamp_user_max_concurrent,
export_report_to_memory,
run_research_process,
@@ -3273,12 +3275,14 @@ def get_research_status(
status = research.status
progress = research.progress
completed_at = research.completed_at
- metadata = research.research_meta or {}
+ metadata = _parse_research_metadata(research.research_meta)
+ filtered_metadata = strip_settings_snapshot(metadata)
# Extract and format error information for better UI display
error_info = {}
- if metadata and "error" in metadata:
- error_msg = metadata["error"]
+ if metadata.get("error"):
+ error_msg = str(metadata["error"])
+ known_message = get_known_research_error_message(error_msg)
error_type = "unknown"
# Detect specific error types
@@ -3327,17 +3331,24 @@ def get_research_status(
# Use the solution provided in metadata if available
error_info = {
"type": error_type,
- "message": error_msg,
+ "message": filtered_metadata["error"],
"suggestion": str(metadata.get("solution")),
}
else:
- # Generic error with the original message
+ # Legacy rows can contain str(exception), including
+ # absolute report paths. The stored detail stays private.
error_info = {
"type": error_type,
- "message": error_msg,
+ "message": filtered_metadata["error"],
"suggestion": "Try again with a different query or check the application logs.",
}
+ # The polling UI displays message alone. Preserve the worker's
+ # exact authored classification instead of replacing e.g. a
+ # missing-model message with a generic Ollama-service error.
+ if known_message is not None:
+ error_info["message"] = known_message
+
# Get the latest milestone log for this research
latest_milestone = None
try:
@@ -3369,7 +3380,6 @@ def get_research_status(
except Exception:
logger.warning("Error fetching latest milestone")
- filtered_metadata = strip_settings_snapshot(metadata)
if error_info:
filtered_metadata["error_info"] = error_info
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 a732057c5a..75c656ac34 100644
--- a/src/local_deep_research/web/services/report_assembly_service.py
+++ b/src/local_deep_research/web/services/report_assembly_service.py
@@ -87,6 +87,17 @@ def _current_user_uncited_mode(db_session: Session) -> Optional[str]:
return None
+def _research_metadata(research) -> Dict[str, Any]:
+ """Read metadata from current rows and legacy JSON-string rows."""
+ try:
+ meta = getattr(research, "research_meta", None)
+ if isinstance(meta, str):
+ meta = json.loads(meta)
+ return meta if isinstance(meta, dict) else {}
+ except (json.JSONDecodeError, TypeError):
+ return {}
+
+
def _research_settings_snapshot(research) -> Optional[Dict[str, Any]]:
"""Return the saved ``settings_snapshot`` for a research row, if any.
@@ -98,12 +109,7 @@ def _research_settings_snapshot(research) -> Optional[Dict[str, Any]]:
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")
+ snap = _research_metadata(research).get("settings_snapshot")
return snap if isinstance(snap, dict) else None
except Exception:
return None
@@ -124,12 +130,11 @@ def assemble_full_report(
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).
+ When ``None`` (default), a saved value in the research row's
+ snapshot is honored. Legacy snapshots without this setting use
+ the requesting user's current preference.
+ settings_snapshot: Explicit settings snapshot override. It takes
+ precedence over the row only when it contains this setting.
Returns:
``None`` when ``research`` is ``None`` (caller should map to
@@ -189,7 +194,7 @@ def _build_metrics_markdown(research: ResearchHistory) -> str:
Returns an empty string when nothing meaningful can be rendered.
"""
- meta = research.research_meta or {}
+ meta = _research_metadata(research)
iterations = meta.get("iterations")
generated_at = meta.get("generated_at") or research.completed_at
lines = []
@@ -220,10 +225,10 @@ def _build_sources_markdown(
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.
+ wins first, then an explicit snapshot containing this setting, then
+ the row's own snapshot containing it, then — for older rows that
+ lack this setting — the requesting user's current saved setting,
+ then the thread context.
"""
resources = (
db_session.query(ResearchResource)
@@ -291,21 +296,25 @@ def _resolve_saved_uncited_mode(
) -> 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"``.
+ Precedence: explicit ``uncited_mode`` > explicit snapshot value >
+ the row's own saved snapshot value > the requesting user's current
+ saved setting > thread context (which report routes never install) >
+ ``"fallback"``. A snapshot without this key is not an override.
"""
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 (
+ isinstance(settings_snapshot, dict)
+ and UNCITED_SOURCES_MODE_KEY in settings_snapshot
+ ):
+ return resolve_uncited_sources_mode(
+ None, settings_snapshot=settings_snapshot
+ )
+ row_snapshot = _research_settings_snapshot(research)
+ if row_snapshot is not None and UNCITED_SOURCES_MODE_KEY in row_snapshot:
+ return resolve_uncited_sources_mode(
+ None, settings_snapshot=row_snapshot
+ )
if db_session is not None:
current = _current_user_uncited_mode(db_session)
if current is not None:
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index fbb2a3a7a6..9282c4e7e8 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -312,6 +312,13 @@ def _merge_completion_metadata(
return metadata
+def _is_error_shaped_content(content: object) -> bool:
+ """Recognize strategy error text that must not become report content."""
+ return isinstance(content, str) and content.lstrip().lower().startswith(
+ "error:"
+ )
+
+
def _extract_synthesized_answer(results: dict) -> str:
"""Pull the LLM-synthesized answer out of a strategy result dict.
@@ -330,13 +337,16 @@ def _extract_synthesized_answer(results: dict) -> str:
2. ``current_knowledge`` (other strategies expose the answer
there).
3. Empty string — caller decides whether to fall back further.
+
+ Error-shaped content is not an answer and is skipped at both steps.
"""
for finding in results.get("findings") or []:
if finding.get("phase") == "Final synthesis":
content = finding.get("content") or ""
- if content:
+ if content and not _is_error_shaped_content(content):
return content
- return results.get("current_knowledge") or ""
+ knowledge = results.get("current_knowledge") or ""
+ return "" if _is_error_shaped_content(knowledge) else knowledge
def get_citation_formatter():
@@ -1949,13 +1959,8 @@ def run_research_process(research_id, query, mode, **kwargs):
raw_formatted_findings = results["formatted_findings"]
# Check if formatted_findings contains an error message
- if isinstance(
- raw_formatted_findings, str
- ) and raw_formatted_findings.startswith("Error:"):
- logger.error(
- "Detected error in formatted findings: {}",
- redact_and_bound_for_log(raw_formatted_findings, 100),
- )
+ if _is_error_shaped_content(raw_formatted_findings):
+ logger.error("Detected error in formatted findings")
# Determine error type for better user feedback
error_type = "unknown"
@@ -2055,9 +2060,8 @@ def run_research_process(research_id, query, mode, **kwargs):
break
# Use synthesized content as fallback
- if (
+ if synthesized_content and not _is_error_shaped_content(
synthesized_content
- and not synthesized_content.startswith("Error:")
):
logger.info(
"Using existing synthesized content as fallback"
@@ -2065,7 +2069,9 @@ def run_research_process(research_id, query, mode, **kwargs):
raw_formatted_findings = synthesized_content
# Or use current_knowledge as another fallback
- elif results.get("current_knowledge"):
+ elif results.get("current_knowledge") and not (
+ _is_error_shaped_content(results["current_knowledge"])
+ ):
logger.info("Using current_knowledge as fallback")
raw_formatted_findings = results["current_knowledge"]
@@ -2077,12 +2083,11 @@ def run_research_process(research_id, query, mode, **kwargs):
f"## {finding.get('phase', 'Finding')}\n\n{finding.get('content', '')}"
for finding in results.get("findings", [])
if finding.get("content")
- and not finding.get("content", "").startswith(
- "Error:"
+ and not _is_error_shaped_content(
+ finding.get("content")
)
]
- synthesis_error = raw_formatted_findings
if valid_findings:
raw_formatted_findings = (
"# Research Results (Fallback Mode)\n\n"
@@ -2090,20 +2095,11 @@ def run_research_process(research_id, query, mode, **kwargs):
raw_formatted_findings += "\n\n".join(
valid_findings
)
- raw_formatted_findings += (
- f"\n\n## Error Information\n{synthesis_error}"
- )
- else:
- # Last resort: use everything including errors
- raw_formatted_findings = (
- "# Research Results (Emergency Fallback)\n\n"
- )
- raw_formatted_findings += "The system encountered errors during final synthesis.\n\n"
- raw_formatted_findings += "\n\n".join(
- f"## {finding.get('phase', 'Finding')}\n\n{finding.get('content', '')}"
- for finding in results.get("findings", [])
- if finding.get("content")
- )
+ raw_formatted_findings += "\n\n*Final synthesis failed; showing partial findings.*"
+ # If every finding is error-shaped, keep the failure
+ # as private input to ErrorReportGenerator below. Its
+ # authored replacements retain useful category hints
+ # without echoing raw provider details into the report.
progress_callback(
f"Using fallback synthesis due to {error_type} error",
@@ -2121,9 +2117,7 @@ def run_research_process(research_id, query, mode, **kwargs):
try:
# Check if we have an error in the findings and use enhanced error handling
- if isinstance(
- raw_formatted_findings, str
- ) and raw_formatted_findings.startswith("Error:"):
+ if _is_error_shaped_content(raw_formatted_findings):
logger.info(
"Generating enhanced error report using ErrorReportGenerator"
)
diff --git a/tests/advanced_search_system/findings/test_findings_repository.py b/tests/advanced_search_system/findings/test_findings_repository.py
index 1d9c1afef6..086cd037cc 100644
--- a/tests/advanced_search_system/findings/test_findings_repository.py
+++ b/tests/advanced_search_system/findings/test_findings_repository.py
@@ -104,8 +104,7 @@ class TestFormatFindingsToText:
result = repo.format_findings_to_text([], "Content")
- assert "Error during final formatting" in result
- assert "Content" in result
+ assert result == "Content"
class TestSynthesizeFindings:
diff --git a/tests/advanced_search_system/findings/test_findings_repository_deep_coverage.py b/tests/advanced_search_system/findings/test_findings_repository_deep_coverage.py
index dd1c4abd9b..621fddb834 100644
--- a/tests/advanced_search_system/findings/test_findings_repository_deep_coverage.py
+++ b/tests/advanced_search_system/findings/test_findings_repository_deep_coverage.py
@@ -200,7 +200,7 @@ class TestFormatFindingsToText:
assert result == "formatted report"
mock_ff.assert_called_once()
- def test_exception_returns_fallback_message(self):
+ def test_exception_preserves_synthesized_content(self):
repo = _make_repo()
repo.questions_by_iteration = {}
@@ -210,5 +210,4 @@ class TestFormatFindingsToText:
synthesized_content="synthesis",
)
- assert "Error" in result
- assert "synthesis" in result
+ assert result == "synthesis"
diff --git a/tests/advanced_search_system/test_repository_logic.py b/tests/advanced_search_system/test_repository_logic.py
index 5d5669c414..c35d3bf448 100644
--- a/tests/advanced_search_system/test_repository_logic.py
+++ b/tests/advanced_search_system/test_repository_logic.py
@@ -151,15 +151,14 @@ class TestFormatFindingsToText:
@patch(
"local_deep_research.advanced_search_system.findings.repository.format_findings"
)
- def test_exception_returns_fallback_message(self, mock_format):
- """When format_findings raises, fallback error message is returned."""
+ def test_exception_preserves_synthesized_content(self, mock_format):
+ """Formatting failure preserves the answer without adding a wrapper."""
mock_format.side_effect = RuntimeError("formatting broke")
repo = _make_repo()
result = repo.format_findings_to_text([], "raw synthesis")
- assert "Error during final formatting" in result
- assert "raw synthesis" in result
+ assert result == "raw synthesis"
# ===========================================================================
diff --git a/tests/error_handling/test_error_handling_high_value.py b/tests/error_handling/test_error_handling_high_value.py
index b5803c0bb4..7fb9805a26 100644
--- a/tests/error_handling/test_error_handling_high_value.py
+++ b/tests/error_handling/test_error_handling_high_value.py
@@ -115,7 +115,7 @@ class TestUserFriendlyErrorMessages:
"max_workers must be greater than 0"
)
assert "LLM failed to generate search questions" in result
- assert "Technical error:" in result
+ assert "Technical error:" not in result
def test_connection_refused_replacement(self):
gen = ErrorReportGenerator()
@@ -148,11 +148,12 @@ class TestUserFriendlyErrorMessages:
)
assert "Permission issue" in result
- def test_unmatched_error_returns_original(self):
+ def test_unmatched_error_uses_generic_message(self):
gen = ErrorReportGenerator()
original = "Some completely unique error that doesn't match any pattern"
result = gen._make_error_user_friendly(original)
- assert result == original
+ assert "unexpected error" in result.lower()
+ assert original not in result
def test_no_search_results_replacement(self):
gen = ErrorReportGenerator()
diff --git a/tests/error_handling/test_report_generator.py b/tests/error_handling/test_report_generator.py
index 1e57b6444a..532a9d16ba 100644
--- a/tests/error_handling/test_report_generator.py
+++ b/tests/error_handling/test_report_generator.py
@@ -2,6 +2,7 @@
from unittest.mock import MagicMock
+import pytest
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
@@ -314,21 +315,66 @@ class TestMakeErrorUserFriendly:
# Should match docker pattern and suggest using host.docker.internal
assert "Docker" in result or "host.docker.internal" in result
- def test_returns_original_for_unknown(self, error_report_generator):
- """Should return original message for unknown errors."""
+ def test_uses_generic_message_for_unknown(self, error_report_generator):
+ """Should not expose the original message for unknown errors."""
original = "Some random error that has no pattern"
result = error_report_generator._make_error_user_friendly(original)
- assert result == original
+ assert "unexpected error" in result.lower()
+ assert original not in result
- def test_includes_technical_error_in_replacement(
+ @pytest.mark.parametrize("prefix", ["", "Research failed: "])
+ @pytest.mark.parametrize("separator", [" | Details: ", "\n"])
+ def test_worker_message_with_added_detail_is_not_trusted(
+ self, error_report_generator, prefix, separator
+ ):
+ marker = "/srv/private/provider-internals.txt"
+ message = (
+ f"{prefix}Authentication with the configured LLM provider failed."
+ f"{separator}{marker}"
+ )
+
+ report = error_report_generator.generate_error_report(message, "query")
+
+ assert marker not in report
+ assert "unexpected error" in report.lower()
+
+ @pytest.mark.parametrize(
+ "message, expected",
+ [
+ (
+ "Egress policy could not verify this run, so it was refused (fail-closed).",
+ "Egress policy could not verify this run",
+ ),
+ (
+ "Egress policy refused this run: a sensitive source would reach an exposing destination (sensitive_to_exposing_private_reason).",
+ "a sensitive source would reach an exposing destination.",
+ ),
+ (
+ "Egress policy refused this run (private_reason).",
+ "Egress policy refused this run.",
+ ),
+ ],
+ )
+ def test_worker_policy_refusal_keeps_safe_guidance(
+ self, error_report_generator, message, expected
+ ):
+ report = error_report_generator.generate_error_report(
+ f"Research failed: {message}", "query"
+ )
+
+ assert expected in report
+ assert "private_reason" not in report
+
+ def test_omits_technical_error_from_replacement(
self, error_report_generator
):
- """Should include technical error in replaced message."""
+ """Should keep technical details out of replaced messages."""
result = error_report_generator._make_error_user_friendly(
"max_workers must be greater than 0"
)
- assert "Technical error:" in result
- assert "max_workers" in result
+ assert "LLM failed to generate" in result
+ assert "Technical error:" not in result
+ assert "max_workers" not in result
def test_case_insensitive_matching(self, error_report_generator):
"""Should match patterns case-insensitively."""
diff --git a/tests/error_handling/test_report_generator_behavior.py b/tests/error_handling/test_report_generator_behavior.py
index f59acfdb38..5b4c7864c3 100644
--- a/tests/error_handling/test_report_generator_behavior.py
+++ b/tests/error_handling/test_report_generator_behavior.py
@@ -19,7 +19,7 @@ class TestMakeErrorUserFriendly:
"max_workers must be greater than 0"
)
assert "LLM failed to generate search questions" in result
- assert "Technical error:" in result
+ assert "Technical error:" not in result
def test_connection_refused_error_replaced(self):
from local_deep_research.error_handling.report_generator import (
@@ -92,7 +92,7 @@ class TestMakeErrorUserFriendly:
result = gen._make_error_user_friendly("No search results found")
assert "No search results were found" in result
- def test_unknown_error_returns_original(self):
+ def test_unknown_error_uses_generic_message(self):
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -100,7 +100,8 @@ class TestMakeErrorUserFriendly:
gen = ErrorReportGenerator()
msg = "Some completely unknown error xyz123"
result = gen._make_error_user_friendly(msg)
- assert result == msg
+ assert "unexpected error" in result.lower()
+ assert msg not in result
def test_case_insensitive_matching(self):
from local_deep_research.error_handling.report_generator import (
@@ -147,8 +148,8 @@ class TestMakeErrorUserFriendly:
)
assert "SearXNG configuration" in result
- def test_replaced_message_includes_technical_error(self):
- """All replaced messages should include the original technical error."""
+ def test_replaced_message_omits_technical_error(self):
+ """A recognized error should not echo its raw technical detail."""
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -156,7 +157,8 @@ class TestMakeErrorUserFriendly:
gen = ErrorReportGenerator()
original = "max_workers must be greater than 0"
result = gen._make_error_user_friendly(original)
- assert original in result
+ assert "LLM failed to generate search questions" in result
+ assert original not in result
def test_model_dump_pattern_replaced(self):
# Issue #3897: surface a multi-cause "Try this" hint when the agent
@@ -175,9 +177,9 @@ class TestMakeErrorUserFriendly:
assert "proxy/shim" in result
assert "Try this" in result
assert "issue #3897" in result
- assert "Technical error:" in result
+ assert "Technical error:" not in result
- def test_unrelated_attribute_error_passes_through(self):
+ def test_unrelated_attribute_error_uses_generic_message(self):
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -186,8 +188,9 @@ class TestMakeErrorUserFriendly:
msg = "AttributeError: 'NoneType' object has no attribute 'foo'"
result = gen._make_error_user_friendly(msg)
- # No model_dump match → original message returned verbatim, no hint.
- assert result == msg
+ # No model_dump match: no specialized hint or raw exception.
+ assert "unexpected error" in result.lower()
+ assert msg not in result
def test_model_dump_pattern_matches_dict_variant(self):
# langchain-ai/langchain#31391 documents the same bug class with
@@ -220,26 +223,21 @@ class TestMakeErrorUserFriendly:
)
result = gen._make_error_user_friendly(msg)
- assert result == msg
+ assert "unexpected error" in result.lower()
+ assert msg not in result
class TestErrorTypeTokenShortCircuit:
- """Tests for the ``(Error type: <code>)`` short-circuit in
+ """Tests for the ``(Error type: <code>)`` mapping in
``_make_error_user_friendly()`` (PR #4087).
- Upstream code (``openai_compat_errors``, the status-code/Ollama branches in
- ``research_service``) emits already-friendly messages carrying a
- ``(Error type: <code>)`` token. The replacement table must NOT clobber those
- -- but the ``unknown`` token is attached to a RAW exception string upstream
- could not classify, so it must still fall through to the table.
+ Upstream can attach a raw Details suffix or endpoint even to typed
+ messages, so use only authored text for known codes. The unknown token
+ still falls through to the pattern table for another classification.
"""
- def test_specific_token_message_returned_verbatim(self):
- # The actual #4087 bug: friendly_openai_compatible_error() builds a
- # message that names the provider/URL/model AND happens to contain the
- # substrings "Connection refused" / the Docker hint, which the generic
- # replacement patterns matched and overwrote. With the short-circuit it
- # must be returned untouched.
+ def test_specific_token_message_uses_safe_category(self):
+ # A typed provider message can include an internal URL and raw Details.
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -255,9 +253,9 @@ class TestErrorTypeTokenShortCircuit:
)
result = gen._make_error_user_friendly(msg)
- # Returned verbatim -- the tailored message survives.
- assert result == msg
- # And specifically NOT replaced by either generic hint.
+ assert "Could not connect to the configured LLM server" in result
+ assert "http://localhost:1234" not in result
+ assert "Details:" not in result
assert "Cannot connect to the LLM service" not in result
assert "Docker networking issue" not in result
@@ -272,14 +270,13 @@ class TestErrorTypeTokenShortCircuit:
result = gen._make_error_user_friendly("Connection refused [Errno 111]")
assert "Cannot connect to the LLM service" in result
- assert "Technical error:" in result
+ assert "Technical error:" not in result
def test_unknown_token_falls_through_to_replacement_table(self):
# The #4087 follow-up fix: "(Error type: unknown)" is appended by
# research_service to a RAW str(exc) it could not classify (e.g. the
# LLM generated no questions -> ThreadPoolExecutor(max_workers=0)).
- # It must still get the friendly replacement, with the original message
- # (token included) preserved in the technical-error suffix.
+ # It must still get the friendly replacement without the raw suffix.
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -289,12 +286,11 @@ class TestErrorTypeTokenShortCircuit:
result = gen._make_error_user_friendly(msg)
assert "LLM failed to generate search questions" in result
- assert "Technical error:" in result
- assert "(Error type: unknown)" in result
+ assert "Technical error:" not in result
+ assert "(Error type: unknown)" not in result
- def test_unknown_token_with_no_match_returns_original(self):
- # Falling through is safe when nothing matches: an unclassifiable
- # "unknown" message is returned as-is, exactly as before.
+ def test_unknown_token_with_no_match_uses_generic_message(self):
+ # An unclassifiable unknown message must not be echoed to the user.
from local_deep_research.error_handling.report_generator import (
ErrorReportGenerator,
)
@@ -303,7 +299,8 @@ class TestErrorTypeTokenShortCircuit:
msg = "Totally novel failure xyz123 (Error type: unknown)"
result = gen._make_error_user_friendly(msg)
- assert result == msg
+ assert "unexpected error" in result.lower()
+ assert msg not in result
class TestBroadPatternTightening:
@@ -356,7 +353,8 @@ class TestBroadPatternTightening:
msg = "Model file could not be found at /models/x.gguf"
result = gen._make_error_user_friendly(msg)
- assert result == msg
+ assert "unexpected error" in result.lower()
+ assert msg not in result
assert "Search engine configuration problem" not in result
def test_search_engine_errors_still_matched(self):
@@ -387,7 +385,8 @@ class TestBroadPatternTightening:
)
result = gen._make_error_user_friendly(msg)
- assert result == msg
+ assert "unexpected error" in result.lower()
+ assert msg not in result
assert "Model configuration issue" not in result
def test_nonetype_context_comparison_still_matched(self):
diff --git a/tests/error_handling/test_report_generator_disclosure.py b/tests/error_handling/test_report_generator_disclosure.py
new file mode 100644
index 0000000000..034a6640aa
--- /dev/null
+++ b/tests/error_handling/test_report_generator_disclosure.py
@@ -0,0 +1,71 @@
+"""Exception details must stay out of reports saved for research users."""
+
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.error_handling.report_generator import (
+ ErrorReportGenerator,
+)
+
+
+ ("error_message", "expected_hint"),
+ [
+ pytest.param(
+ "Unexpected failure at /srv/private/provider-internals.txt",
+ "unexpected error",
+ id="unknown",
+ ),
+ pytest.param(
+ "Connection refused at /srv/private/provider-internals.txt",
+ "Cannot connect to the LLM service",
+ id="recognized",
+ ),
+ pytest.param(
+ "Cannot reach provider at /srv/private/provider-internals.txt "
+ "(Error type: openai_connection_refused) | Details: private endpoint",
+ "configured LLM server",
+ id="typed",
+ ),
+ ],
+)
+def test_report_excludes_raw_exception_details(error_message, expected_hint):
+ report = ErrorReportGenerator().generate_error_report(
+ error_message, "research query"
+ )
+
+ assert expected_hint.lower() in report.lower()
+ assert "/srv/private/provider-internals.txt" not in report
+ assert "private endpoint" not in report
+ assert "Technical error:" not in report
+
+
+def test_report_fallback_excludes_raw_exception_details():
+ generator = ErrorReportGenerator()
+ generator.error_reporter.analyze_error = Mock(
+ side_effect=RuntimeError("report analysis failed")
+ )
+
+ report = generator.generate_error_report(
+ "Failure at /srv/private/provider-internals.txt", "research query"
+ )
+
+ assert "Research Failed" in report
+ assert "/srv/private/provider-internals.txt" not in report
+
+
+def test_report_skips_error_shaped_partial_knowledge():
+ marker = "/srv/private/provider-internals.txt"
+ report = ErrorReportGenerator().generate_error_report(
+ f"Error: provider failed at {marker}",
+ "research query",
+ partial_results={
+ "current_knowledge": f"Error: provider failed at {marker}",
+ "findings": [
+ {"phase": "Final synthesis", "content": f"Error: {marker}"}
+ ],
+ },
+ )
+
+ assert marker not in report
diff --git a/tests/security/test_data_sanitizer.py b/tests/security/test_data_sanitizer.py
index e35aea189e..82a81140aa 100644
--- a/tests/security/test_data_sanitizer.py
+++ b/tests/security/test_data_sanitizer.py
@@ -2,6 +2,8 @@
Tests for DataSanitizer security module.
"""
+import pytest
+
from local_deep_research.security.data_sanitizer import (
DataSanitizer,
filter_research_metadata,
@@ -491,6 +493,12 @@ class TestFilterResearchMetadata:
class TestStripSettingsSnapshot:
"""Tests for strip_settings_snapshot() helper."""
+ @pytest.mark.parametrize("empty_error", [None, "", False, 0, [], {}])
+ def test_empty_error_does_not_become_a_failure(self, empty_error):
+ metadata = {"phase": "complete", "error": empty_error}
+
+ assert strip_settings_snapshot(metadata) == metadata
+
def test_none_input(self):
"""None returns empty dict."""
assert strip_settings_snapshot(None) == {}
@@ -503,6 +511,82 @@ class TestStripSettingsSnapshot:
}
assert strip_settings_snapshot(meta) == {"phase": "complete"}
+ def test_persisted_error_is_not_returned_to_api_clients(self):
+ """Old rows can hold str(OSError), including a private report path."""
+ raw = (
+ "[Errno 13] Permission denied: '/srv/ldr/users/alice/reports/5.md'"
+ )
+ meta = {
+ "phase": "error",
+ "error": raw,
+ "settings_snapshot": {"api_key": "sk-secret"},
+ }
+
+ public = strip_settings_snapshot(meta)
+
+ assert public == {
+ "phase": "error",
+ "error": "Research failed. Check the server logs for details.",
+ }
+ assert meta["error"] == raw
+
+ @pytest.mark.parametrize("prefix", ["", "Research failed: "])
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Authentication with the configured LLM provider failed.",
+ "The configured LLM server timed out.",
+ "There was a problem with the search engine configuration.",
+ ],
+ )
+ def test_known_worker_message_is_preserved(self, message, prefix):
+ public = strip_settings_snapshot({"error": prefix + message})
+
+ assert public["error"] == message
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ "Authentication with the configured LLM provider failed. | Details: /srv/private/key",
+ "Authentication with the configured LLM provider failed.\n/srv/private/key",
+ "/srv/private/key: Authentication with the configured LLM provider failed.",
+ {
+ "message": "The configured LLM server timed out.",
+ "path": "/srv/private/key",
+ },
+ ],
+ )
+ def test_safe_message_does_not_authorize_appended_details(self, error):
+ public = strip_settings_snapshot({"error": error})
+
+ assert public["error"] == (
+ "Research failed. Check the server logs for details."
+ )
+
+ @pytest.mark.parametrize(
+ "message,expected",
+ [
+ (
+ "Egress policy could not verify this run, so it was refused (fail-closed).",
+ "Egress policy could not verify this run, so it was refused (fail-closed).",
+ ),
+ (
+ "Egress policy refused this run: a sensitive source would reach an exposing destination (sensitive_to_exposing_private_reason).",
+ "Egress policy refused this run: a sensitive source would reach an exposing destination.",
+ ),
+ (
+ "Egress policy refused this run (private_reason).",
+ "Egress policy refused this run.",
+ ),
+ ],
+ )
+ def test_policy_message_keeps_category_without_internal_reason(
+ self, message, expected
+ ):
+ public = strip_settings_snapshot({"error": message})
+
+ assert public["error"] == expected
+
def test_no_op_when_absent(self):
"""Returns same dict when settings_snapshot absent."""
meta = {"phase": "error", "error_type": "timeout"}
diff --git a/tests/security/test_status_payload_server_path_disclosure.py b/tests/security/test_status_payload_server_path_disclosure.py
index b295ef6bcc..bc229f5643 100644
--- a/tests/security/test_status_payload_server_path_disclosure.py
+++ b/tests/security/test_status_payload_server_path_disclosure.py
@@ -179,6 +179,58 @@ def test_research_report_omits_report_path(authenticated_client, db):
assert data["content"] == "The answer."
+ "module,url",
+ [
+ (_API, "/research/api/status/legacy-error"),
+ (_RESEARCH, "/api/research/legacy-error"),
+ (_RESEARCH, "/api/research/legacy-error/status"),
+ (_RESEARCH, "/api/report/legacy-error"),
+ ],
+)
+ "json_encoded", [False, True], ids=["dict", "json-string"]
+)
[email protected]("error_kind", ["legacy", "known", "appended-detail"])
+def test_error_metadata_preserves_only_safe_messages(
+ authenticated_client, db, module, url, json_encoded, error_kind
+):
+ private_path = "/var/lib/ldr-private/reports/legacy-error.md"
+ known = "Authentication with the configured LLM provider failed."
+ errors = {
+ "legacy": f"[Errno 13] Permission denied: '{private_path}'",
+ "known": known,
+ "appended-detail": f"{known} | Details: {private_path}",
+ }
+ research_meta = {
+ "phase": "error",
+ "error": errors[error_kind],
+ }
+ row = _add_research(
+ db,
+ "legacy-error",
+ report_content="The answer.",
+ research_meta=json.dumps(research_meta)
+ if json_encoded
+ else research_meta,
+ )
+ row.status = "failed"
+ db.commit()
+
+ with _patch_session(module, db):
+ response = authenticated_client.get(url)
+
+ assert response.status_code == 200, response.text[:300]
+ assert private_path not in response.text
+ metadata = response.get_json()["metadata"]
+ assert metadata["error"] == (
+ known
+ if error_kind == "known"
+ else "Research failed. Check the server logs for details."
+ )
+ assert metadata["phase"] == "error"
+
+
def test_history_status_sanitizes_legacy_text_progress_log(
authenticated_client, db
):
diff --git a/tests/web/routers/test_research_status_error_guidance.py b/tests/web/routers/test_research_status_error_guidance.py
index 1d344ca8b6..3cb236c3ad 100644
--- a/tests/web/routers/test_research_status_error_guidance.py
+++ b/tests/web/routers/test_research_status_error_guidance.py
@@ -105,6 +105,26 @@ def _error_info(response):
return response["metadata"]["error_info"]
+ "legacy_error",
+ [
+ "[Errno 13] Permission denied: '/srv/ldr/users/alice/reports/5.md'",
+ r"[Errno 2] No such file or directory: 'C:\Users\Alice\LDR\report.md'",
+ ],
+)
+def test_legacy_error_path_is_not_exposed_by_status(legacy_error):
+ response = _call_status({"phase": "error", "error": legacy_error})
+
+ rendered = json.dumps(response, default=str)
+ assert legacy_error not in rendered
+ assert response["metadata"]["error"] == (
+ "Research failed. Check the server logs for details."
+ )
+ assert _error_info(response)["message"] == (
+ "Research failed. Check the server logs for details."
+ )
+
+
class TestNoFailureMeansNoGuidance:
"""Positive control, asserted before any negative case.
@@ -112,6 +132,17 @@ class TestNoFailureMeansNoGuidance:
onto every response would satisfy several assertions below.
"""
+ @pytest.mark.parametrize("empty_error", [None, "", False, 0, [], {}])
+ def test_cleared_error_does_not_create_failure_guidance(self, empty_error):
+ response = _call_status(
+ {"phase": "complete", "error": empty_error}, status="completed"
+ )
+
+ assert response["metadata"] == {
+ "phase": "complete",
+ "error": empty_error,
+ }
+
def test_a_completed_research_gets_no_error_info_block(self):
response = _call_status(
{"phase": "complete", "duration": 42}, status="completed"
@@ -206,7 +237,7 @@ CLASSIFICATIONS = [
pytest.param(
"Something went wrong",
"unknown",
- "Something went wrong",
+ "Research failed. Check the server logs for details.",
"Try again with a different query or check the application logs.",
id="unclassified",
),
@@ -254,13 +285,14 @@ class TestFailureGuidance:
continue
assert info["suggestion"] != other
- def test_the_unclassified_case_echoes_the_raw_error_text(self):
- """The generic arm is the only one that surfaces the raw text; the
- classified arms replace it with a written message."""
+ def test_the_unclassified_case_withholds_the_raw_error_text(self):
+ """The generic arm must not expose a legacy exception message."""
raw = "ValueError: unhashable type in strategy adapter"
info = _error_info(_call_status({"phase": "error", "error": raw}))
- assert info["message"] == raw
+ assert info["message"] == (
+ "Research failed. Check the server logs for details."
+ )
assert (
info["suggestion"]
== "Try again with a different query or check the application logs."
@@ -283,7 +315,9 @@ class TestFailureGuidance:
)
assert info["type"] == "unknown"
- assert info["message"] == "Model 'mistral' not found on the server"
+ assert info["message"] == (
+ "Research failed. Check the server logs for details."
+ )
assert info["suggestion"] == (
"Run 'ollama pull mistral' to download the required model."
)
diff --git a/tests/web/routes/test_report_api_contract.py b/tests/web/routes/test_report_api_contract.py
index 07d89e8314..6ed5e10d09 100644
--- a/tests/web/routes/test_report_api_contract.py
+++ b/tests/web/routes/test_report_api_contract.py
@@ -22,6 +22,7 @@ with that dependency overridden and ``get_user_db_session`` pointed at a seeded
SQLite file.
"""
+import json
from contextlib import contextmanager
from datetime import datetime, UTC
from unittest.mock import patch
@@ -31,7 +32,7 @@ from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
-from local_deep_research.database.models import Base
+from local_deep_research.database.models import Base, Setting, SettingType
from local_deep_research.database.models.chat import (
ChatMessage,
ChatMessageType,
@@ -201,7 +202,7 @@ def seeded_db(tmp_path):
_fake_user_db,
),
):
- yield
+ yield SessionLocal
engine.dispose()
@@ -271,6 +272,53 @@ def test_export_latex_content_includes_sources_and_metrics(client, seeded_db):
assert "src1.example" in body
+ "route",
+ ["history/report", "history/markdown", "api/report", "export/latex"],
+)
[email protected]("mode", ["disabled", "strict"])
[email protected]("json_encoded", [False, True])
+def test_legacy_snapshot_uses_saved_mode_on_view_and_export(
+ client, seeded_db, route, mode, json_encoded
+):
+ """HTTP requests honor current preferences when the old snapshot lacks them."""
+ with seeded_db() as db:
+ db.add(
+ Setting(
+ key="report.uncited_sources_mode",
+ value=mode,
+ type=SettingType.REPORT,
+ name="Uncited sources mode",
+ ui_element="select",
+ )
+ )
+ research = db.get(ResearchHistory, RESEARCH_ID)
+ if json_encoded:
+ research.research_meta = json.dumps(research.research_meta)
+ if mode == "strict":
+ # No citations distinguishes strict from fallback, which keeps all.
+ research.report_content = "No citations."
+ db.commit()
+
+ if route == "export/latex":
+ csrf = client.get("/auth/csrf-token").json()["csrf_token"]
+ resp = client.post(
+ f"/api/v1/research/{RESEARCH_ID}/export/latex",
+ headers={"X-CSRFToken": csrf},
+ )
+ assert resp.status_code == 200, resp.text
+ content = resp.text
+ else:
+ resp = client.get(f"/{route}/{RESEARCH_ID}")
+ assert resp.status_code == 200, resp.text
+ content = resp.json()["content"]
+
+ # Sources 3-5 have no prose citations. Disabled must keep all five;
+ # strict with no citations must omit all five, across every route.
+ for index in range(1, N_SOURCES + 1):
+ assert (f"src{index}.example" in content) == (mode == "disabled")
+
+
# ---------------------------------------------------------------------------
# Fix A regression fence: /api/report sources field from research_resources
# ---------------------------------------------------------------------------
diff --git a/tests/web/services/conftest.py b/tests/web/services/conftest.py
new file mode 100644
index 0000000000..7bbfc4868b
--- /dev/null
+++ b/tests/web/services/conftest.py
@@ -0,0 +1,33 @@
+"""Shared database fixture for persisted research-report regressions."""
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+from sqlalchemy.pool import StaticPool
+
+from local_deep_research.database.models import Base, ResearchHistory
+
+
+def report_db():
+ engine = create_engine(
+ "sqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ try:
+ Base.metadata.create_all(engine)
+ with Session(engine) as db:
+ db.add(
+ ResearchHistory(
+ id="report-errors",
+ query="test query",
+ mode="quick",
+ status="in_progress",
+ created_at="2026-10-06T00:00:00+00:00",
+ )
+ )
+ db.commit()
+ yield db
+ finally:
+ engine.dispose()
diff --git a/tests/web/services/test_findings_formatting_fallback.py b/tests/web/services/test_findings_formatting_fallback.py
new file mode 100644
index 0000000000..623390f13f
--- /dev/null
+++ b/tests/web/services/test_findings_formatting_fallback.py
@@ -0,0 +1,190 @@
+"""Formatter failures must not hide synthesis errors from the worker."""
+
+from contextlib import ExitStack
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.advanced_search_system.findings.repository import (
+ FindingsRepository,
+)
+from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+)
+from local_deep_research.database.models import ResearchHistory
+from local_deep_research.error_handling.report_generator import (
+ ErrorReportGenerator,
+)
+from local_deep_research.storage.database import DatabaseReportStorage
+from tests.web.services.helpers import (
+ MODULE,
+ _base_run_patches,
+ _egress_and_search_patches,
+ _get_raw_run_research_process,
+)
+
+
[email protected]("formatting_fails", [False, True])
[email protected]("outcome", ["answer", "partial", "all_errors"])
+def test_worker_saves_safe_content_after_formatting(
+ report_db, formatting_fails, outcome
+):
+ marker = "/srv/private/provider-internals.txt"
+ answer = "A complete and useful synthesized answer."
+ partial = "Useful safe partial finding."
+ synthesized = (
+ answer
+ if outcome == "answer"
+ else f"Error: Failed to synthesize final answer. LLM error: {marker}"
+ )
+ findings = []
+ if outcome == "partial":
+ findings.append(
+ {"phase": "Search", "content": partial, "search_results": []}
+ )
+ findings.append(
+ {
+ "phase": "Final synthesis",
+ "content": synthesized,
+ "search_results": [],
+ }
+ )
+ repository = FindingsRepository(MagicMock())
+ # Exercise the real formatter's failure path with a malformed question
+ # group. Mocking formatted_findings missed the old prefix-changing wrapper.
+ repository.set_questions_by_iteration(
+ {1: None} if formatting_fails else {1: ["test question"]}
+ )
+ formatted = repository.format_findings_to_text(findings, synthesized)
+ system = MagicMock()
+ system.analyze_topic.return_value = {
+ "findings": findings,
+ "iterations": 1,
+ "formatted_findings": formatted,
+ "current_knowledge": synthesized,
+ }
+ system.all_links_of_system = []
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(return_value=system)
+ patches[f"{MODULE}.ErrorReportGenerator"] = ErrorReportGenerator
+
+ # Keep the real worker, error renderer, citation formatter and storage.
+ # Read the committed row so this checks the report actually saved for users.
+ with ExitStack() as stack:
+ for cm in _egress_and_search_patches():
+ stack.enter_context(cm)
+ for name, value in patches.items():
+ stack.enter_context(patch(name, value))
+ stack.enter_context(
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=DatabaseReportStorage(report_db),
+ )
+ )
+ _get_raw_run_research_process()(
+ "report-errors",
+ "test query",
+ "quick",
+ username="user1",
+ search_engine="searxng",
+ settings_snapshot={
+ "llm.provider": "ollama",
+ "llm.model": "m",
+ "search.tool": "searxng",
+ },
+ )
+
+ report_db.expire_all()
+ report = report_db.get(ResearchHistory, "report-errors").report_content
+ assert report
+ assert marker not in report
+ if outcome == "answer":
+ assert report == answer
+ elif outcome == "partial":
+ assert partial in report
+ assert "Fallback Mode" in report
+ else:
+ assert "Research Failed" in report
+ assert "What happened:" in report
+
+
+ "failure,expected_hint,expected_category",
+ [
+ (
+ "Connection refused [Errno 111]",
+ "Cannot connect to the LLM service",
+ "Connection Issue",
+ ),
+ (
+ "No auth credentials found",
+ "API key is missing",
+ "LLM Service Error",
+ ),
+ (
+ "database is locked",
+ "database is temporarily locked",
+ "File System Error",
+ ),
+ ],
+)
+def test_all_error_results_keep_safe_category_and_hint(
+ report_db, failure, expected_hint, expected_category
+):
+ marker = "/srv/private/provider-internals.txt"
+ strategy = SourceBasedSearchStrategy(
+ search=MagicMock(),
+ model=MagicMock(),
+ citation_handler=MagicMock(),
+ use_cross_engine_filter=False,
+ include_text_content=False,
+ max_iterations=1,
+ questions_per_iteration=1,
+ settings_snapshot={"app.max_user_query_length": 300},
+ )
+ # Let the real strategy create its error result from a failed LLM call.
+ with patch(
+ "local_deep_research.advanced_search_system.questions.standard_question.invoke_llm_sync",
+ side_effect=RuntimeError(f"{failure}: {marker}"),
+ ):
+ results = strategy.analyze_topic("test query")
+ assert results["findings"][0]["phase"] == "Error"
+ assert failure in results["formatted_findings"]
+
+ system = MagicMock()
+ system.analyze_topic.return_value = results
+ system.all_links_of_system = []
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(return_value=system)
+ patches[f"{MODULE}.ErrorReportGenerator"] = ErrorReportGenerator
+ with ExitStack() as stack:
+ for cm in _egress_and_search_patches():
+ stack.enter_context(cm)
+ for name, value in patches.items():
+ stack.enter_context(patch(name, value))
+ stack.enter_context(
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=DatabaseReportStorage(report_db),
+ )
+ )
+ _get_raw_run_research_process()(
+ "report-errors",
+ "test query",
+ "quick",
+ username="user1",
+ search_engine="searxng",
+ settings_snapshot={
+ "llm.provider": "ollama",
+ "llm.model": "m",
+ "search.tool": "searxng",
+ },
+ )
+
+ report_db.expire_all()
+ report = report_db.get(ResearchHistory, "report-errors").report_content
+ assert expected_hint in report
+ assert f"**Error Type:** {expected_category}" in report
+ assert marker not in report
diff --git a/tests/web/services/test_report_assembly_service.py b/tests/web/services/test_report_assembly_service.py
index 65f9717dee..20faa198e2 100644
--- a/tests/web/services/test_report_assembly_service.py
+++ b/tests/web/services/test_report_assembly_service.py
@@ -1,5 +1,6 @@
"""Tests for the report_assembly_service module."""
+import json
from datetime import datetime, UTC
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -377,10 +378,14 @@ class TestAssembleFullReport:
class TestBuildMetricsMarkdown:
- def test_renders_iterations_and_generated_at(self, db_session):
+ @pytest.mark.parametrize("json_encoded", [False, True])
+ def test_renders_iterations_and_generated_at(
+ self, db_session, json_encoded
+ ):
+ metadata = {"iterations": 5, "generated_at": "2026-01-01"}
research = _mk_research(
db_session,
- research_meta={"iterations": 5, "generated_at": "2026-01-01"},
+ research_meta=json.dumps(metadata) if json_encoded else metadata,
)
md = _build_metrics_markdown(research)
assert "Search Iterations: 5" in md
@@ -397,9 +402,10 @@ class TestBuildMetricsMarkdown:
md = _build_metrics_markdown(research)
assert "Generated at: 2026-02-02T00:00:00+00:00" in md
- def test_returns_empty_when_no_data(self, db_session):
+ @pytest.mark.parametrize("metadata", [None, "not-json", "[]", [], True])
+ def test_returns_empty_when_no_data(self, db_session, metadata):
research = _mk_research(
- db_session, research_meta=None, completed_at=None
+ db_session, research_meta=metadata, completed_at=None
)
assert _build_metrics_markdown(research) == ""
@@ -921,13 +927,13 @@ def _mk_setting(db_session, key, value, ui_element="select"):
class TestLegacySnapshotlessRows:
- """Snapshot-less rows honor the requester's current setting (#6747).
+ """Legacy rows without a saved mode use the requester's setting.
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``.
+ recovered for those rows. Older snapshots may also lack this newer
+ setting. View/export resolves both from the requesting user's current
+ saved preference instead of silently rendering ``fallback``.
"""
def test_snapshotless_row_honors_current_saved_strict(self, db_session):
@@ -962,6 +968,101 @@ class TestLegacySnapshotlessRows:
assert "## Sources" not in out
assert "https://cited.test/a" not in out
+ @pytest.mark.parametrize(
+ "snapshot",
+ [{}, {"llm.model": {"value": "old-model"}}],
+ ids=["empty", "unrelated-setting"],
+ )
+ @pytest.mark.parametrize("current_mode", ["disabled", "strict"])
+ def test_legacy_snapshot_without_mode_uses_current_preference(
+ self, db_session, snapshot, current_mode
+ ):
+ """A pre-setting snapshot is not an override for this setting."""
+ from local_deep_research.config.thread_settings import (
+ clear_settings_context,
+ )
+
+ clear_settings_context()
+ _mk_setting(db_session, "report.uncited_sources_mode", current_mode)
+ research = _mk_research(
+ db_session,
+ report_content=(
+ "Cited claim [1]."
+ if current_mode == "disabled"
+ else "No citations here."
+ ),
+ research_meta={"settings_snapshot": snapshot},
+ )
+ _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)
+
+ if current_mode == "disabled":
+ assert "https://uncited.test/b" in out
+ else:
+ assert "## Sources" not in out
+
+ def test_explicit_snapshot_without_mode_preserves_row_mode(
+ self, db_session
+ ):
+ """An unrelated caller snapshot must not hide a stored mode."""
+ _mk_setting(db_session, "report.uncited_sources_mode", "disabled")
+ 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")
+
+ out = assemble_full_report(
+ research,
+ db_session,
+ settings_snapshot={"llm.model": {"value": "new-model"}},
+ )
+
+ assert "## Sources" not in out
+
+ def test_explicit_snapshot_mode_overrides_row_and_current(self, db_session):
+ """A caller that actually supplies the mode keeps highest priority."""
+ _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": "strict"}
+ }
+ },
+ )
+ _mk_resource(db_session, research.id, url="https://cited.test/a")
+
+ out = assemble_full_report(
+ research,
+ db_session,
+ settings_snapshot={
+ "report.uncited_sources_mode": {"value": "disabled"}
+ },
+ )
+
+ assert "https://cited.test/a" in out
+
def test_snapshotless_row_without_saved_setting_renders_fallback(
self, db_session
):
diff --git a/tests/web/services/test_research_error_report_guidance.py b/tests/web/services/test_research_error_report_guidance.py
new file mode 100644
index 0000000000..9efa82f102
--- /dev/null
+++ b/tests/web/services/test_research_error_report_guidance.py
@@ -0,0 +1,136 @@
+"""Safe worker messages must survive saved reports and HTTP status polling."""
+
+from contextlib import ExitStack, contextmanager
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from local_deep_research.database.models import ResearchHistory
+from local_deep_research.error_handling.report_generator import (
+ ErrorReportGenerator,
+)
+from local_deep_research.storage.database import DatabaseReportStorage
+from local_deep_research.web.dependencies.auth import require_auth
+from local_deep_research.web.routers.research import router
+from tests.web.services.helpers import (
+ MODULE,
+ QUEUE_PROC_MOD,
+ _base_run_patches,
+ _egress_and_search_patches,
+ _get_raw_run_research_process,
+)
+
+
+ "target, raw_error, expected_hint",
+ [
+ (
+ "get_llm",
+ "Error type: ollama_unavailable",
+ "Ollama AI service is unavailable",
+ ),
+ ("get_llm", "Error type: model_not_found", "model not found"),
+ ("get_llm", "Error type: connection_error", "Connection error"),
+ ("get_llm", "Error type: api_error", "API rejected"),
+ (
+ "get_llm",
+ "Error type: openai_connection_refused",
+ "Could not connect",
+ ),
+ ("get_llm", "Error type: openai_timeout", "timed out"),
+ ("get_llm", "Error type: openai_auth", "Authentication"),
+ ("get_llm", "Error type: openai_permission_denied", "denied access"),
+ (
+ "get_llm",
+ "Error type: openai_model_not_found",
+ "model was not found",
+ ),
+ ("get_llm", "Error type: openai_bad_request", "rejected the request"),
+ ("get_llm", "Error type: openai_unknown", "returned an error"),
+ ("get_llm", "Error type: openai_rate_limit", "rate-limited"),
+ ("get_llm", "model path does not exist", "LLM configuration"),
+ ("get_search", "api_key not configured", "search engine configuration"),
+ ],
+)
+def test_worker_persists_specific_safe_error_report(
+ report_db, target, raw_error, expected_hint
+):
+ marker = "/srv/private/provider-internals.txt"
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.get_search"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.{target}"] = MagicMock(
+ side_effect=RuntimeError(f"{raw_error} {marker}")
+ )
+ # Keep the real renderer in the real worker path. Earlier tests mocked
+ # this boundary and only checked the safe message before it was rendered.
+ patches[f"{MODULE}.ErrorReportGenerator"] = ErrorReportGenerator
+
+ with ExitStack() as stack:
+ for cm in _egress_and_search_patches():
+ stack.enter_context(cm)
+ for name, value in patches.items():
+ stack.enter_context(patch(name, value))
+ stack.enter_context(
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=DatabaseReportStorage(report_db),
+ )
+ )
+ _get_raw_run_research_process()(
+ "report-errors",
+ "research query",
+ "quick",
+ username="user1",
+ model="model-1",
+ model_provider="openai",
+ search_engine="searxng",
+ settings_snapshot={
+ "llm.provider": "openai",
+ "llm.model": "model-1",
+ "search.tool": "searxng",
+ },
+ )
+
+ report_db.expire_all()
+ row = report_db.get(ResearchHistory, "report-errors")
+ report = row.report_content
+ message = next(
+ line
+ for line in report.splitlines()
+ if line.startswith("**What happened:**")
+ )
+ assert expected_hint.lower() in message.lower()
+ assert marker not in report
+
+ # Apply the worker's queued failure metadata, then read it through HTTP.
+ # Polling UIs use error_info.message alone, not its separate suggestion.
+ queue = patches[f"{QUEUE_PROC_MOD}.queue_processor"].queue_error_update
+ queue.assert_called_once()
+ row.status = "failed"
+ row.research_meta = queue.call_args.kwargs["metadata"]
+ report_db.commit()
+
+ @contextmanager
+ def user_session(username):
+ assert username == "user1"
+ yield report_db
+
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[require_auth] = lambda: "user1"
+ with (
+ patch(
+ "local_deep_research.web.routers.research.get_user_db_session",
+ user_session,
+ ),
+ TestClient(app) as client,
+ ):
+ response = client.get("/api/research/report-errors/status")
+ assert response.status_code == 200, response.text
+ metadata = response.json()["metadata"]
+ assert expected_hint.lower() in metadata["error"].lower()
+ assert expected_hint.lower() in metadata["error_info"]["message"].lower()
+ assert marker not in response.text
diff --git a/tests/web/services/test_research_service_synthesis.py b/tests/web/services/test_research_service_synthesis.py
index 9fe6d2f29f..bebc2ed69e 100644
--- a/tests/web/services/test_research_service_synthesis.py
+++ b/tests/web/services/test_research_service_synthesis.py
@@ -100,21 +100,8 @@ class TestQuickModeSynthesis:
def test_quick_mode_synthesis_fallback_cascade_level_2(self):
"""A 'Final synthesis' finding that is ITSELF error-shaped is not
- usable as the Level-1 fallback, so the code correctly falls
- through to current_knowledge internally -- but the final
- persisted answer does not reflect that.
-
- ``_extract_synthesized_answer`` (called via
- ``clean_markdown = _extract_synthesized_answer(results) or
- raw_formatted_findings``) independently re-scans ``results`` for
- the 'Final synthesis' finding with NO error-prefix check, and
- returns its (error-shaped) content unconditionally when
- non-empty -- overriding the fallback that had already resolved
- ``raw_formatted_findings`` to current_knowledge. This is
- pre-existing behavior (not something this PR changes); pinning
- the ACTUAL output here rather than the original test's assumed
- one, so a future fix of this discrepancy shows up as an
- intentional test update instead of a silent regression.
+ usable as an answer. The saved report uses accumulated knowledge
+ rather than persisting raw synthesis error text.
"""
result = run_quick_mode_with_analyze_result(
{
@@ -129,7 +116,7 @@ class TestQuickModeSynthesis:
"iterations": 2,
}
)
- assert result == {"clean_markdown": "Error: synthesis failed"}
+ assert result == {"clean_markdown": "Accumulated knowledge from search"}
def test_quick_mode_synthesis_fallback_cascade_level_3(self):
"""Quick mode synthesis combines findings as last fallback."""
@@ -149,6 +136,46 @@ class TestQuickModeSynthesis:
assert "Finding 1" in markdown
assert "Finding 2" in markdown
+ @pytest.mark.parametrize("prefix", ["Error:", " error:"])
+ def test_quick_mode_partial_findings_omit_synthesis_error_detail(
+ self, prefix
+ ):
+ marker = "/srv/private/provider-internals.txt"
+ result = run_quick_mode_with_analyze_result(
+ {
+ "findings": [
+ {"content": "Useful finding", "phase": "search"},
+ {
+ "content": f"{prefix} provider failed at {marker}",
+ "phase": "synthesis",
+ },
+ ],
+ "formatted_findings": f"{prefix} provider failed at {marker}",
+ "current_knowledge": "",
+ "iterations": 1,
+ }
+ )
+
+ assert "Useful finding" in result["clean_markdown"]
+ assert marker not in result["clean_markdown"]
+
+ def test_quick_mode_all_error_findings_use_error_report(self):
+ result = run_quick_mode_with_analyze_result(
+ {
+ "findings": [
+ {
+ "content": "Error: provider failed at /srv/private/provider-internals.txt",
+ "phase": "Final synthesis",
+ }
+ ],
+ "formatted_findings": "Error: synthesis failed",
+ "current_knowledge": "",
+ "iterations": 1,
+ }
+ )
+
+ assert "error_report_message" in result
+
def test_quick_mode_synthesis_all_fallbacks_exhausted(self):
"""When there is nothing to fall back to at all (no findings, no
current_knowledge), the run reports failure via
diff --git a/tests/web/test_research_lifecycle_states.py b/tests/web/test_research_lifecycle_states.py
index a8079c1ec4..72e721e69b 100644
--- a/tests/web/test_research_lifecycle_states.py
+++ b/tests/web/test_research_lifecycle_states.py
@@ -886,6 +886,7 @@ def test_worker_failure_lands_a_terminal_failed_row_with_a_usable_error(
rounds = [
("stub blew up (Error type: connection_error)", "connection"),
("stub blew up (Error type: openai_timeout)", "timed out"),
+ ("stub blew up (Error type: openai_auth)", "authentication"),
]
messages = []
username = None
@@ -924,12 +925,14 @@ def test_worker_failure_lands_a_terminal_failed_row_with_a_usable_error(
)
messages.append(error_text)
- # The status endpoint must surface it, not just the raw column.
+ # Known authored messages must survive the API boundary. Legacy raw
+ # exception text is masked, but the polling UI needs this safe reason.
http = status_of(authenticated_client, rid).json()
assert http["status"] == "failed", http
- assert http["metadata"]["error"] == error_text, (
- f"status endpoint disagrees with the row: {http['metadata']} "
- f"vs {error_text!r}"
+ assert http["metadata"]["error"] == error_text
+ guidance = http["metadata"]["error_info"]
+ assert expected_fragment in guidance["message"].lower(), (
+ f"status endpoint lost useful error guidance: {http['metadata']}"
)
assert expected_fragment in error_text.lower(), (
f"error for {raw!r} was not classified: {error_text!r}"