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(notifications): precise failure reason in completion log lines (#5082)

S8a3bd5cd0c9d
diff --git a/changelog.d/+notification-precise-reason.bugfix.md b/changelog.d/+notification-precise-reason.bugfix.md
new file mode 100644
index 0000000000..e1b74bdb40
--- /dev/null
+++ b/changelog.d/+notification-precise-reason.bugfix.md
@@ -0,0 +1,9 @@
+Notification completion / failure log lines now name the precise
+reason the message was dropped (`server_disabled`, `event_disabled`,
+`unconfigured`, `egress_denied`, `webhook_failed`, `exception`) instead
+of the generic `(disabled)`. Operators who configured all per-user
+toggles can now tell from the logs why a notification did not fire.
+`send_notification` returns a structured `NotificationResult`
+(`sent`/`reason`/`detail`); legacy `if manager.send_notification(...):`
+callers continue to work via `__bool__`. Rate-limit refusal still raises
+`RateLimitError` as before.
diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.py
index ee1b786d91..585e69d179 100644
--- a/src/local_deep_research/error_handling/error_reporter.py
+++ b/src/local_deep_research/error_handling/error_reporter.py
@@ -332,10 +332,29 @@ class ErrorReporter:
return
# Send notification
- notification_manager.send_notification(
+ result = notification_manager.send_notification(
event_type=event_type,
context=notification_context,
)
+ if not result:
+ # DEBUG so it doesn't pollute the default log, but operators
+ # enabling ``--log-level debug`` can see precisely why the
+ # error-notification didn't fire (e.g. server_disabled vs.
+ # unconfigured). Use ``reason.value`` so the enum renders
+ # as the clean string ("unconfigured") rather than
+ # "NotificationReason.UNCONFIGURED". Include ``detail``
+ # when present so the operator-facing explanation is not
+ # silently dropped. See issue #4877.
+ reason_value = getattr(
+ getattr(result, "reason", None), "value", None
+ )
+ detail = getattr(result, "detail", "") or ""
+ if reason_value is None:
+ reason_value = "dropped" if not bool(result) else "sent"
+ message = (
+ f"{reason_value}: {detail}" if detail else reason_value
+ )
+ logger.debug("Error notification not sent: {}", message)
except Exception as e:
logger.debug(f"Failed to send error notification: {e}")
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index 8458f68695..753d785df6 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -2,7 +2,9 @@
High-level notification manager with database integration.
"""
+from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
+from enum import Enum
from typing import Dict, Optional, Any
from collections import deque
import threading
@@ -17,6 +19,45 @@ from ..utilities.type_utils import unwrap_setting
from ..constants import DEFAULT_SEARCH_TOOL
+class NotificationReason(str, Enum):
+ """Precise reason a notification was (not) sent.
+
+ Surfaced in :class:`NotificationResult` so callers and log lines can
+ distinguish, for example, a per-user toggle being off from the
+ server-level master switch being unset — see issue #4877.
+
+ Note: rate-limit refusal is signalled via :class:`RateLimitError`
+ (preserved API for callers that catch it directly) rather than as a
+ ``NotificationResult`` value.
+ """
+
+ SENT = "sent"
+ SERVER_DISABLED = "server_disabled"
+ EVENT_DISABLED = "event_disabled"
+ UNCONFIGURED = "unconfigured"
+ EGRESS_DENIED = "egress_denied"
+ WEBHOOK_FAILED = "webhook_failed"
+ EXCEPTION = "exception"
+
+
+@dataclass(frozen=True)
+class NotificationResult:
+ """Structured outcome of :meth:`NotificationManager.send_notification`.
+
+ ``sent`` keeps the legacy bool contract (``if result:`` keeps working —
+ see ``__bool__``) while ``reason`` names the precise cause so the queue
+ helpers and error reporter can log a useful, non-misleading line.
+ ``detail`` is a short operator-facing explanation complementing reason.
+ """
+
+ sent: bool
+ reason: NotificationReason
+ detail: str = ""
+
+ def __bool__(self) -> bool:
+ return self.sent
+
+
class NotificationManager:
"""
High-level notification manager that uses settings snapshots for
@@ -172,7 +213,7 @@ class NotificationManager:
event_type: EventType,
context: Dict[str, Any],
force: bool = False,
- ) -> bool:
+ ) -> NotificationResult:
"""
Send a notification for an event.
@@ -185,7 +226,10 @@ class NotificationManager:
force: If True, bypass rate limiting
Returns:
- True if notification was sent successfully
+ :class:`NotificationResult` describing the outcome. The
+ dataclass is truthy iff the notification was actually sent,
+ so legacy ``if manager.send_notification(...):`` callers
+ continue to work without source changes.
Raises:
RateLimitError: If rate limit is exceeded and force=False
@@ -213,7 +257,11 @@ class NotificationManager:
event_type.value,
self._user_id,
)
- return False
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.SERVER_DISABLED,
+ detail="LDR_NOTIFICATIONS_ALLOW_OUTBOUND is not set",
+ )
# Check if notifications are enabled for this event type
should_notify = self._should_notify(event_type)
@@ -227,7 +275,11 @@ class NotificationManager:
f"Notifications disabled for event type: "
f"{event_type.value} (user: {self._user_id})"
)
- return False
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.EVENT_DISABLED,
+ detail=f"notifications.on_{event_type.value} is off",
+ )
# Check rate limit using the manager's user_id
rate_limit_ok = self._rate_limiter.is_allowed(self._user_id)
@@ -251,7 +303,11 @@ class NotificationManager:
f"No notification service URLs configured for user "
f"{self._user_id}"
)
- return False
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.UNCONFIGURED,
+ detail="notifications.service_url is not configured",
+ )
# Egress policy: gate each parsed webhook URL against the
# user's scope. Apprise URLs can be Slack/Discord/SMTP/HTTP —
@@ -265,35 +321,56 @@ class NotificationManager:
user=self._user_id,
event=event_type.value,
)
- return False
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.EGRESS_DENIED,
+ detail="all configured URLs refused by egress policy",
+ )
# Send notification with the allowed subset.
logger.debug(f"Calling service.send_event for {event_type.value}")
- result = self.service.send_event(
+ sent = self.service.send_event(
event_type, context, service_urls=allowed_urls
)
# Log to database if enabled
- if result:
+ if sent:
self._log_notification(event_type, context)
logger.info(
f"Notification sent: {event_type.value} to user "
f"{self._user_id}"
)
- else:
- logger.warning(
- f"Notification failed: {event_type.value} to user "
- f"{self._user_id}"
+ return NotificationResult(
+ sent=True,
+ reason=NotificationReason.SENT,
+ detail="",
)
+ logger.warning(
+ f"Notification failed: {event_type.value} to user "
+ f"{self._user_id}"
+ )
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.WEBHOOK_FAILED,
+ detail="Apprise dispatch returned False",
+ )
- return result
-
- except Exception:
+ except Exception as exc:
+ # The exception string may contain webhook URLs with embedded
+ # tokens, SMTP credentials, or payload content. Log the raw
+ # exception for operators via logger.exception above, but only
+ # expose the exception class name (and not the message) in the
+ # structured result so downstream callers can't echo it into
+ # logs or UI surfaces verbatim.
logger.exception(
f"Error sending notification for {event_type.value} to user "
f"{self._user_id}"
)
- return False
+ return NotificationResult(
+ sent=False,
+ reason=NotificationReason.EXCEPTION,
+ detail=f"dispatch raised {type(exc).__name__}",
+ )
def test_service(self, url: str) -> Dict[str, Any]:
"""
diff --git a/src/local_deep_research/notifications/queue_helpers.py b/src/local_deep_research/notifications/queue_helpers.py
index a0241162ae..82b2b09a7c 100644
--- a/src/local_deep_research/notifications/queue_helpers.py
+++ b/src/local_deep_research/notifications/queue_helpers.py
@@ -5,15 +5,27 @@ Provides helper functions for sending queue-related notifications
to keep the queue manager focused on queue logic.
"""
-from typing import Dict, Any, Optional
+from typing import Any, Dict, Optional
from loguru import logger
from sqlalchemy.orm import Session
from .exceptions import RateLimitError
-from .manager import NotificationManager
+from .manager import NotificationManager, NotificationResult
from .templates import EventType
+def _format_reason(result: Any) -> str:
+ """Render a ``send_notification`` outcome as ``"(reason: detail)"``,
+ falling back to ``bool(result)`` so legacy mocks / older callers that
+ still return a bare ``True``/``False`` keep working.
+ """
+ if isinstance(result, NotificationResult):
+ if result.detail:
+ return f"({result.reason.value}: {result.detail})"
+ return f"({result.reason.value})"
+ return f"({'sent' if bool(result) else 'dropped'})"
+
+
def send_queue_notification(
username: str,
research_id: str,
@@ -32,7 +44,9 @@ def send_queue_notification(
position: Queue position (optional)
Returns:
- True if notification was sent successfully, False otherwise
+ True if notification was sent successfully, False otherwise.
+ Returned as ``bool`` for backward compatibility; the precise
+ reason for a falsy return is logged via ``NotificationResult``.
"""
try:
notification_manager = NotificationManager(
@@ -51,10 +65,16 @@ def send_queue_notification(
"Unknown" # Could estimate based on active researches
)
- return notification_manager.send_notification(
+ result = notification_manager.send_notification(
event_type=EventType.RESEARCH_QUEUED,
context=context,
)
+ if not result:
+ logger.debug(
+ f"Queue notification not sent for {research_id} "
+ f"{_format_reason(result)}"
+ )
+ return bool(getattr(result, "sent", result))
except RateLimitError:
logger.warning(
@@ -84,7 +104,9 @@ def send_queue_failed_notification(
settings_snapshot: Settings snapshot for thread-safe access
Returns:
- True if notification was sent successfully, False otherwise
+ True if notification was sent successfully, False otherwise.
+ Returned as ``bool`` for backward compatibility; the precise
+ reason for a falsy return is logged via ``NotificationResult``.
"""
if not settings_snapshot:
logger.debug("No settings snapshot provided for failed notification")
@@ -104,10 +126,16 @@ def send_queue_failed_notification(
if error_message:
context["error"] = error_message
- return notification_manager.send_notification(
+ result = notification_manager.send_notification(
event_type=EventType.RESEARCH_FAILED,
context=context,
)
+ if not result:
+ logger.debug(
+ f"Failed-notification not sent for {research_id} "
+ f"{_format_reason(result)}"
+ )
+ return bool(getattr(result, "sent", result))
except RateLimitError:
logger.warning(
@@ -267,7 +295,8 @@ def send_research_completed_notification_from_session(
)
else:
logger.warning(
- f"Completion notification not sent for {research_id} (disabled)"
+ f"Completion notification not sent for {research_id} "
+ f"{_format_reason(result)}"
)
else:
@@ -289,13 +318,20 @@ def send_research_completed_notification_from_session(
"url": f"/research/{research_id}",
}
- notification_manager.send_notification(
+ minimal_result = notification_manager.send_notification(
event_type=EventType.RESEARCH_COMPLETED,
context=context,
)
- logger.info(
- f"Sent completion notification for research {research_id} (minimal details)"
- )
+ if minimal_result:
+ logger.info(
+ f"Sent completion notification for research {research_id} "
+ f"(minimal details)"
+ )
+ else:
+ logger.warning(
+ f"Completion notification not sent for {research_id} "
+ f"(minimal details) {_format_reason(minimal_result)}"
+ )
except RateLimitError:
logger.warning(
@@ -388,7 +424,8 @@ def send_research_failed_notification_from_session(
)
else:
logger.warning(
- f"Failure notification not sent for {research_id} (disabled)"
+ f"Failure notification not sent for {research_id} "
+ f"{_format_reason(result)}"
)
else:
@@ -409,13 +446,20 @@ def send_research_failed_notification_from_session(
"error": safe_error,
}
- notification_manager.send_notification(
+ minimal_result = notification_manager.send_notification(
event_type=EventType.RESEARCH_FAILED,
context=context,
)
- logger.info(
- f"Sent failure notification for research {research_id} (minimal details)"
- )
+ if minimal_result:
+ logger.info(
+ f"Sent failure notification for research {research_id} "
+ f"(minimal details)"
+ )
+ else:
+ logger.warning(
+ f"Failure notification not sent for {research_id} "
+ f"(minimal details) {_format_reason(minimal_result)}"
+ )
except RateLimitError:
logger.warning(
diff --git a/tests/error_handling/test_error_reporter.py b/tests/error_handling/test_error_reporter.py
index 89e6db3fb4..28cc394dda 100644
--- a/tests/error_handling/test_error_reporter.py
+++ b/tests/error_handling/test_error_reporter.py
@@ -349,3 +349,102 @@ class TestSendErrorNotifications:
)
mock_nm_instance.send_notification.assert_called_once()
+
+ def _run_notification_dropped(
+ self, error_reporter, mock_context_with_username, result
+ ):
+ """Run _send_error_notifications with ``result`` returned from
+ ``NotificationManager.send_notification`` and yield the captured
+ debug log records.
+ """
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session:
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = MagicMock(return_value=MagicMock())
+ mock_cm.__exit__ = MagicMock(return_value=None)
+ mock_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.settings.SettingsManager"
+ ) as mock_settings:
+ mock_settings.return_value.get_settings_snapshot.return_value = {}
+
+ with patch(
+ "local_deep_research.notifications.manager.NotificationManager"
+ ) as mock_nm:
+ mock_nm_instance = MagicMock()
+ mock_nm_instance.send_notification.return_value = result
+ mock_nm.return_value = mock_nm_instance
+
+ error_reporter._send_error_notifications(
+ ErrorCategory.MODEL_ERROR,
+ "401 API key error",
+ mock_context_with_username,
+ )
+
+ def test_logs_reason_value_with_detail_when_dropped(
+ self, error_reporter, mock_context_with_username, loguru_caplog
+ ):
+ """When the notification is dropped, the debug log must show the
+ ``reason.value`` string (``unconfigured``) — not the enum repr
+ (``NotificationReason.UNCONFIGURED``) — and must include the
+ operator-facing ``detail`` so the cause is visible. See PR #5082.
+ """
+
+ class FakeReason:
+ value = "unconfigured"
+
+ class FakeResult:
+ sent = False
+ detail = "notifications.service_url is not configured"
+ reason = FakeReason()
+
+ def __bool__(self) -> bool:
+ return self.sent
+
+ with loguru_caplog.at_level("DEBUG"):
+ self._run_notification_dropped(
+ error_reporter, mock_context_with_username, FakeResult()
+ )
+
+ messages = [rec.message for rec in loguru_caplog.records]
+ debug_lines = [
+ m for m in messages if "Error notification not sent" in m
+ ]
+ assert len(debug_lines) == 1, debug_lines
+ assert "unconfigured" in debug_lines[0]
+ assert "NotificationReason." not in debug_lines[0]
+ assert "notifications.service_url" in debug_lines[0]
+
+ def test_logs_reason_value_without_detail_when_dropped(
+ self, error_reporter, mock_context_with_username, loguru_caplog
+ ):
+ """When detail is empty, the debug log must still show the reason
+ value without trailing colon whitespace.
+ """
+
+ class FakeReason:
+ value = "event_disabled"
+
+ class FakeResult:
+ sent = False
+ detail = ""
+ reason = FakeReason()
+
+ def __bool__(self) -> bool:
+ return self.sent
+
+ with loguru_caplog.at_level("DEBUG"):
+ self._run_notification_dropped(
+ error_reporter, mock_context_with_username, FakeResult()
+ )
+
+ debug_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Error notification not sent" in rec.message
+ ]
+ assert len(debug_lines) == 1, debug_lines
+ assert debug_lines[0].endswith("event_disabled")
+ assert "NotificationReason." not in debug_lines[0]
diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.py
index 3b4249a3bf..398fe15072 100644
--- a/tests/notifications/test_manager.py
+++ b/tests/notifications/test_manager.py
@@ -9,6 +9,8 @@ from datetime import datetime, timezone
from local_deep_research.notifications.manager import (
NotificationManager,
RateLimiter,
+ NotificationReason,
+ NotificationResult,
)
from local_deep_research.notifications.templates import EventType
from local_deep_research.notifications.exceptions import RateLimitError
@@ -118,7 +120,7 @@ class TestSendNotification:
context=context,
)
- assert result is True
+ assert result.sent is True
manager._rate_limiter.is_allowed.assert_called_once_with("test_user")
manager.service.send_event.assert_called_once()
@@ -141,7 +143,7 @@ class TestSendNotification:
context=context,
)
- assert result is False
+ assert result.sent is False
manager.service.send_event.assert_not_called()
def test_send_notification_no_service_url(self, mocker):
@@ -163,7 +165,7 @@ class TestSendNotification:
context=context,
)
- assert result is False
+ assert result.sent is False
manager.service.send_event.assert_not_called()
def test_send_notification_respects_rate_limit(self, mocker):
@@ -214,7 +216,7 @@ class TestSendNotification:
force=True, # Bypass rate limit
)
- assert result is True
+ assert result.sent is True
# Rate limiter should still be checked but result ignored
manager._rate_limiter.is_allowed.assert_called_once()
manager.service.send_event.assert_called_once()
@@ -240,7 +242,7 @@ class TestSendNotification:
force=True,
)
- assert result is True
+ assert result.sent is True
manager.service.send_event.assert_called_once()
def test_send_notification_handles_service_failure(self, mocker):
@@ -265,7 +267,7 @@ class TestSendNotification:
context=context,
)
- assert result is False
+ assert result.sent is False
def test_send_notification_handles_exception(self, mocker):
"""Test graceful handling of exceptions."""
@@ -292,7 +294,7 @@ class TestSendNotification:
context=context,
)
- assert result is False
+ assert result.sent is False
class TestShouldNotify:
@@ -406,7 +408,7 @@ class TestMasterSwitchEnvGate:
context={"query": "Test"},
)
- assert result is False
+ assert result.sent is False
manager.service.send_event.assert_not_called()
def test_send_notification_with_force_does_not_bypass_env_gate(
@@ -427,7 +429,7 @@ class TestMasterSwitchEnvGate:
force=True,
)
- assert result is False
+ assert result.sent is False
manager.service.send_event.assert_not_called()
def test_test_service_returns_disabled_error_when_env_unset(
@@ -444,6 +446,191 @@ class TestMasterSwitchEnvGate:
assert "LDR_NOTIFICATIONS_ALLOW_OUTBOUND" in result["error"]
+class TestNotificationResultSemantics:
+ """Verify that every falsy code path in ``send_notification`` tags the
+ result with a distinct :class:`NotificationReason` (issue #4877).
+ """
+
+ def test_result_is_truthy_when_sent(self):
+ r = NotificationResult(
+ sent=True, reason=NotificationReason.SENT, detail=""
+ )
+ assert bool(r) is True
+ assert r.sent is True
+
+ def test_result_is_falsy_when_dropped(self):
+ r = NotificationResult(
+ sent=False,
+ reason=NotificationReason.UNCONFIGURED,
+ detail="x",
+ )
+ assert bool(r) is False
+ assert r.sent is False
+
+ def test_reason_serialization_is_snake_case(self):
+ # The ``detail: reason`` log format relies on the value matching
+ # the proposed enum names exactly.
+ assert NotificationReason.SERVER_DISABLED.value == "server_disabled"
+ assert NotificationReason.EVENT_DISABLED.value == "event_disabled"
+ assert NotificationReason.UNCONFIGURED.value == "unconfigured"
+ assert NotificationReason.EGRESS_DENIED.value == "egress_denied"
+ assert NotificationReason.WEBHOOK_FAILED.value == "webhook_failed"
+ assert NotificationReason.EXCEPTION.value == "exception"
+
+ def test_server_disabled(self, monkeypatch, mocker):
+ """Operator switch off → ``server_disabled``."""
+ monkeypatch.delenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", raising=False)
+ snapshot = {"notifications.service_url": "discord://x"}
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.SERVER_DISABLED
+ assert "LDR_NOTIFICATIONS_ALLOW_OUTBOUND" in result.detail
+
+ def test_event_disabled(self, mocker):
+ """Per-user toggle off → ``event_disabled``."""
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": False,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.EVENT_DISABLED
+ assert "notifications.on_research_completed" in result.detail
+
+ def test_event_disabled_force_bypasses(self, mocker):
+ """``force=True`` is allowed to skip the per-user toggle (not the
+ operator switch). Ensure we don't tag this case ``event_disabled``
+ just because ``_should_notify`` is False."""
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": False,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager.service.send_event = mocker.MagicMock(return_value=True)
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ force=True,
+ )
+ assert result.reason is NotificationReason.SENT
+
+ def test_unconfigured(self, mocker):
+ snapshot = {
+ "notifications.service_url": "",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.UNCONFIGURED
+ assert "service_url" in result.detail
+
+ def test_egress_denied(self, mocker):
+ """All URLs filtered by egress policy → ``egress_denied``."""
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": True,
+ "policy.egress_scope": "private_only",
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ with patch.object(
+ manager,
+ "_filter_urls_by_egress_policy",
+ return_value="",
+ ):
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ force=True,
+ )
+ assert result.reason is NotificationReason.EGRESS_DENIED
+ assert "egress" in result.detail
+
+ def test_webhook_failed(self, mocker):
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager.service.send_event = mocker.MagicMock(return_value=False)
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.WEBHOOK_FAILED
+
+ def test_exception(self, mocker):
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager.service.send_event = mocker.MagicMock(
+ side_effect=RuntimeError("boom")
+ )
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.EXCEPTION
+ assert "RuntimeError" in result.detail
+
+ def test_exception_detail_does_not_leak_message(self, mocker):
+ """The raw exception message must not appear in ``detail`` — it
+ can contain webhook URLs with embedded tokens, SMTP credentials,
+ or payload content that should never be echoed into structured
+ results (which downstream callers may log verbatim). Only the
+ exception class name is allowed.
+ """
+ sensitive_message = (
+ "POST to discord://id123/secret-token failed: "
+ "payload={'password': 'hunter2'}"
+ )
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager.service.send_event = mocker.MagicMock(
+ side_effect=RuntimeError(sensitive_message)
+ )
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)
+ result = manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+ assert result.reason is NotificationReason.EXCEPTION
+ assert "secret-token" not in result.detail
+ assert "hunter2" not in result.detail
+ assert "discord://" not in result.detail
+ assert "RuntimeError" in result.detail
+
+ def test_rate_limit_still_raises(self, mocker):
+ """Backward compat: rate-limit refusal still raises, not returned."""
+ snapshot = {
+ "notifications.service_url": "discord://x",
+ "notifications.on_research_completed": True,
+ }
+ manager = NotificationManager(settings_snapshot=snapshot, user_id="u")
+ manager._rate_limiter.is_allowed = mocker.MagicMock(return_value=False)
+ with pytest.raises(RateLimitError):
+ manager.send_notification(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "q"},
+ )
+
+
class TestRateLimiter:
"""Tests for RateLimiter class."""
@@ -616,7 +803,7 @@ class TestIntegration:
context=context,
)
- assert result is True
+ assert result.sent is True
# Verify service was called with correct params
call_args = manager.service.send_event.call_args
@@ -644,7 +831,7 @@ class TestIntegration:
context={"query": "Test"},
force=True,
)
- assert result1 is True
+ assert result1.sent is True
# Research failed - should send
result2 = manager.send_notification(
@@ -652,14 +839,14 @@ class TestIntegration:
context={"query": "Test", "error": "Failed"},
force=True,
)
- assert result2 is True
+ assert result2.sent is True
# Subscription update - should not send (disabled)
result3 = manager.send_notification(
event_type=EventType.SUBSCRIPTION_UPDATE,
context={"subscription_name": "Test"},
)
- assert result3 is False
+ assert result3.sent is False
class TestPerUserRateLimiting:
@@ -754,12 +941,12 @@ class TestPerUserRateLimiting:
result1 = manager_a.send_notification(
EventType.RESEARCH_COMPLETED, context
)
- assert result1 is True
+ assert result1.sent is True
result2 = manager_a.send_notification(
EventType.RESEARCH_COMPLETED, context
)
- assert result2 is True
+ assert result2.sent is True
# User A exceeds limit
with pytest.raises(RateLimitError):
@@ -770,7 +957,7 @@ class TestPerUserRateLimiting:
result = manager_b.send_notification(
EventType.RESEARCH_COMPLETED, context
)
- assert result is True
+ assert result.sent is True
# User B exceeds their own limit
with pytest.raises(RateLimitError):
diff --git a/tests/notifications/test_queue_helpers_extended.py b/tests/notifications/test_queue_helpers_extended.py
index a9cfb4b014..93cd9159f3 100644
--- a/tests/notifications/test_queue_helpers_extended.py
+++ b/tests/notifications/test_queue_helpers_extended.py
@@ -535,3 +535,222 @@ class TestSendResearchFailedNotificationFromSession:
ctx = mock_nm.send_notification.call_args.kwargs["context"]
assert ctx["query"] == "What is quantum computing?"
+
+
+# ---------------------------------------------------------------------------
+# Regression: minimal-details logging path must not double-log
+# (see PR #5082 review feedback — bug introduced in ee606c791).
+# ---------------------------------------------------------------------------
+
+
+def _result(sent: bool, reason_value: str = "sent", detail: str = ""):
+ """Build a real ``NotificationResult`` with the given outcome so the
+ queue-helper code under test sees the same dataclass type that
+ ``NotificationManager.send_notification`` actually returns. We need a
+ genuine ``NotificationResult`` (not a duck-typed stub) because
+ ``_format_reason`` uses ``isinstance(result, NotificationResult)`` to
+ pick the rendering branch.
+ """
+ from local_deep_research.notifications.manager import (
+ NotificationReason,
+ NotificationResult,
+ )
+
+ return NotificationResult(
+ sent=sent,
+ reason=NotificationReason(reason_value),
+ detail=detail,
+ )
+
+
+class TestMinimalDetailsLoggingRegression:
+ """Regression coverage for the duplicate / contradictory log lines that
+ the minimal-details (research-not-found) paths used to emit when the
+ new conditional logger.info/warning block was added on top of a
+ pre-existing unconditional logger.info line.
+ """
+
+ @patch(NOTIF_MGR)
+ def test_completed_minimal_success_logs_once(
+ self, mock_nm_class, loguru_caplog
+ ):
+ """Minimal-details success: a single 'Sent ...' INFO, no warning."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_completed_notification_from_session,
+ )
+
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+
+ mock_nm = Mock()
+ mock_nm.send_notification.return_value = _result(
+ sent=True, reason_value="sent"
+ )
+ mock_nm_class.return_value = mock_nm
+
+ mock_settings = Mock()
+ mock_settings.get_settings_snapshot.return_value = {}
+
+ with patch(SETTINGS_MGR, return_value=mock_settings):
+ with loguru_caplog.at_level("INFO"):
+ send_research_completed_notification_from_session(
+ username="alice",
+ research_id="r-min",
+ db_session=mock_db,
+ )
+
+ sent_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Sent completion notification" in rec.message
+ ]
+ warning_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Completion notification not sent" in rec.message
+ ]
+ assert len(sent_lines) == 1, sent_lines
+ assert warning_lines == []
+
+ @patch(NOTIF_MGR)
+ def test_completed_minimal_failure_logs_warning_only(
+ self, mock_nm_class, loguru_caplog
+ ):
+ """Minimal-details failure: a single WARNING, no contradictory INFO."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_completed_notification_from_session,
+ )
+
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+
+ mock_nm = Mock()
+ mock_nm.send_notification.return_value = _result(
+ sent=False,
+ reason_value="unconfigured",
+ detail="notifications.service_url is not configured",
+ )
+ mock_nm_class.return_value = mock_nm
+
+ mock_settings = Mock()
+ mock_settings.get_settings_snapshot.return_value = {}
+
+ with patch(SETTINGS_MGR, return_value=mock_settings):
+ with loguru_caplog.at_level("INFO"):
+ send_research_completed_notification_from_session(
+ username="alice",
+ research_id="r-min",
+ db_session=mock_db,
+ )
+
+ sent_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Sent completion notification" in rec.message
+ ]
+ warning_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Completion notification not sent" in rec.message
+ ]
+ assert sent_lines == [], sent_lines
+ assert len(warning_lines) == 1, warning_lines
+ assert "unconfigured" in warning_lines[0]
+ assert "notifications.service_url" in warning_lines[0]
+
+ @patch(NOTIF_MGR)
+ def test_failed_minimal_success_logs_once(
+ self, mock_nm_class, loguru_caplog
+ ):
+ """Failed-research minimal-details success: single INFO, no warning."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_failed_notification_from_session,
+ )
+
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+
+ mock_nm = Mock()
+ mock_nm.send_notification.return_value = _result(
+ sent=True, reason_value="sent"
+ )
+ mock_nm_class.return_value = mock_nm
+
+ mock_settings = Mock()
+ mock_settings.get_settings_snapshot.return_value = {}
+
+ with patch(SETTINGS_MGR, return_value=mock_settings):
+ with loguru_caplog.at_level("INFO"):
+ send_research_failed_notification_from_session(
+ username="alice",
+ research_id="r-min",
+ error_message="boom",
+ db_session=mock_db,
+ )
+
+ sent_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Sent failure notification" in rec.message
+ ]
+ warning_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Failure notification not sent" in rec.message
+ ]
+ assert len(sent_lines) == 1, sent_lines
+ assert warning_lines == []
+
+ @patch(NOTIF_MGR)
+ def test_failed_minimal_failure_logs_warning_only(
+ self, mock_nm_class, loguru_caplog
+ ):
+ """Failed-research minimal-details failure: single WARNING."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_failed_notification_from_session,
+ )
+
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+
+ mock_nm = Mock()
+ mock_nm.send_notification.return_value = _result(
+ sent=False,
+ reason_value="egress_denied",
+ detail="all configured URLs refused by egress policy",
+ )
+ mock_nm_class.return_value = mock_nm
+
+ mock_settings = Mock()
+ mock_settings.get_settings_snapshot.return_value = {}
+
+ with patch(SETTINGS_MGR, return_value=mock_settings):
+ with loguru_caplog.at_level("INFO"):
+ send_research_failed_notification_from_session(
+ username="alice",
+ research_id="r-min",
+ error_message="boom",
+ db_session=mock_db,
+ )
+
+ sent_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Sent failure notification" in rec.message
+ ]
+ warning_lines = [
+ rec.message
+ for rec in loguru_caplog.records
+ if "Failure notification not sent" in rec.message
+ ]
+ assert sent_lines == [], sent_lines
+ assert len(warning_lines) == 1, warning_lines
+ assert "egress_denied" in warning_lines[0]
diff --git a/tests/security/test_egress_notifications_callsite.py b/tests/security/test_egress_notifications_callsite.py
index 3270324d6f..a5c7f18383 100644
--- a/tests/security/test_egress_notifications_callsite.py
+++ b/tests/security/test_egress_notifications_callsite.py
@@ -185,14 +185,14 @@ def test_send_notification_blocks_dispatch_when_policy_filters_all():
snap_deny = _snapshot("private_only", service_url="discord://id/token")
deny_mgr = _build_manager(snap_deny, outbound=True)
# force=True bypasses per-user toggles + rate limit, NOT the egress filter.
- sent = deny_mgr.send_notification(EventType.TEST, {}, force=True)
- assert sent is False
+ result = deny_mgr.send_notification(EventType.TEST, {}, force=True)
+ assert result.sent is False
deny_mgr.service.send_event.assert_not_called()
snap_allow = _snapshot("both", service_url="discord://id/token")
allow_mgr = _build_manager(snap_allow, outbound=True)
- sent = allow_mgr.send_notification(EventType.TEST, {}, force=True)
- assert sent is True
+ result = allow_mgr.send_notification(EventType.TEST, {}, force=True)
+ assert result.sent is True
allow_mgr.service.send_event.assert_called_once()
# The allowed subset (the discord url) is what gets handed to dispatch.
_, kwargs = allow_mgr.service.send_event.call_args
@@ -209,12 +209,14 @@ def test_outbound_master_switch_blocks_even_policy_allowed_url():
# Outbound OFF: a BOTH-scope, policy-allowed url is still not dispatched.
off_mgr = _build_manager(snap, outbound=False)
- assert off_mgr.send_notification(EventType.TEST, {}, force=True) is False
+ assert (
+ off_mgr.send_notification(EventType.TEST, {}, force=True).sent is False
+ )
off_mgr.service.send_event.assert_not_called()
# Flipping ONLY the master switch on lets the same url through.
on_mgr = _build_manager(snap, outbound=True)
- assert on_mgr.send_notification(EventType.TEST, {}, force=True) is True
+ assert on_mgr.send_notification(EventType.TEST, {}, force=True).sent is True
on_mgr.service.send_event.assert_called_once()
diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.py
index a6b5d84ac0..2c81cf8f8c 100644
--- a/tests/web/services/test_notification_coverage.py
+++ b/tests/web/services/test_notification_coverage.py
@@ -1329,7 +1329,7 @@ class TestNotificationManager:
EventType.RESEARCH_COMPLETED,
{"query": "test", "research_id": "123"},
)
- assert result is True
+ assert result.sent is True
mock_send_event.assert_called_once()
def test_send_notification_disabled_returns_false(self, disabled_settings):
@@ -1338,7 +1338,7 @@ class TestNotificationManager:
EventType.RESEARCH_COMPLETED,
{"query": "test"},
)
- assert result is False
+ assert result.sent is False
def test_send_notification_no_service_url_returns_false(self):
settings = {
@@ -1352,7 +1352,7 @@ class TestNotificationManager:
EventType.RESEARCH_COMPLETED,
{"query": "test"},
)
- assert result is False
+ assert result.sent is False
def test_send_notification_rate_limited(self):
settings = {
@@ -1390,7 +1390,7 @@ class TestNotificationManager:
result = mgr.send_notification(
EventType.RESEARCH_COMPLETED, {"query": "second"}, force=True
)
- assert result is True
+ assert result.sent is True
@patch.object(NotificationService, "send_event", return_value=True)
def test_send_notification_force_bypasses_disabled(self, mock_send):
@@ -1404,7 +1404,7 @@ class TestNotificationManager:
result = mgr.send_notification(
EventType.RESEARCH_COMPLETED, {"query": "forced"}, force=True
)
- assert result is True
+ assert result.sent is True
@patch.object(
NotificationService, "send_event", side_effect=Exception("boom")
@@ -1417,7 +1417,7 @@ class TestNotificationManager:
EventType.RESEARCH_COMPLETED,
{"query": "test"},
)
- assert result is False
+ assert result.sent is False
# -- test_service via manager ------------------------------------------