~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Refactor notification system: simplify caching and improve documentation
tombii1c55d274d97a
diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex c6dfa55eb9..2f056a1345 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -31,10 +31,13 @@ Notifications are configured per-user via the settings system:- **Security**: Service URLs containing credentials are encrypted at rest using SQLCipher (AES-256) in your per-user encrypted database. The encryption key is derived from your login password, ensuring zero-knowledge security.### Event-Specific Settings-- `notifications.on_research_completed` - Enable notifications for completed research-- `notifications.on_research_failed` - Enable notifications for failed research-- `notifications.on_subscription_update` - Enable notifications for subscription updates-- `notifications.on_subscription_error` - Enable notifications for subscription errors+- `notifications.on_research_completed` - Enable notifications for completed research (default: true)+- `notifications.on_research_failed` - Enable notifications for failed research (default: true)+- `notifications.on_research_queued` - Enable notifications when research is queued (default: false)+- `notifications.on_subscription_update` - Enable notifications for subscription updates (default: true)+- `notifications.on_subscription_error` - Enable notifications for subscription errors (default: false)+- `notifications.on_api_quota_warning` - Enable notifications for API quota/rate limit warnings (default: false)+- `notifications.on_auth_issue` - Enable notifications for authentication failures (default: false)### Rate Limiting Settings- `notifications.rate_limit_per_hour` - Max notifications per hour per user@@ -57,11 +60,19 @@ Each URL follows the Apprise format for the specific service.## Available Event Types+### Research Events- `research_completed` - When research completes successfully-- `research_failed` - When research fails+- `research_failed` - When research fails (error details are sanitized in notifications for security)+- `research_queued` - When research is added to the queue++### Subscription Events- `subscription_update` - When a subscription completes- `subscription_error` - When a subscription fails+### System Events+- `api_quota_warning` - When API quota or rate limits are exceeded+- `auth_issue` - When authentication fails for API services+## Testing NotificationsUse the test function to verify notification configuration:@@ -79,6 +90,8 @@ print(result) # {'success': True, 'message': 'Test notification sent successful## Programmatic Usage+For detailed code examples, see the source files in `src/local_deep_research/notifications/`.+### Basic Notification```python@@ -92,51 +105,18 @@ with get_user_db_session(username, password) as session:settings_manager = SettingsManager(session)settings_snapshot = settings_manager.get_settings_snapshot()-# Create notification manager with snapshot (thread-safe)+# Create notification manager and sendnotification_manager = NotificationManager(settings_snapshot=settings_snapshot)--# Send a notification-context = {- "query": "What is quantum computing?",- "research_id": "12345-abcde",- "summary": "Brief summary of the research results...",- "url": "/research/12345-abcde" # Relative URL-}--success = notification_manager.send_notification(+notification_manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,- context=context,+ context={"query": "...", "summary": "...", "url": "/research/123"},user_id="username")```-### Building Full URLs for Notifications--To include clickable links with full URLs in notifications:--```python-from local_deep_research.notifications import build_notification_url-from local_deep_research.settings import SettingsManager--# Get settings manager-settings_manager = SettingsManager(db_session)+### Building Full URLs-# Build full URL from relative path-full_url = build_notification_url(- "/research/12345-abcde",- settings_manager=settings_manager-)-# Result: "https://ldr.example.com/research/12345-abcde"-# (or "http://localhost:5000/research/12345-abcde" if external_url not configured)--# Use in notification context-context = {- "query": "What is quantum computing?",- "research_id": "12345-abcde",- "summary": "Brief summary...",- "url": full_url # Full clickable URL-}-```+Use `build_notification_url()` to convert relative paths to full URLs for clickable links in notifications.## Architecture@@ -157,7 +137,7 @@ The system fetches service URLs from user settings when needed, rather than main### Performance Optimizations-- **Apprise Instance Caching**: The system caches Apprise instances per service URL hash to reuse connections and improve performance, especially for services like SMTP where connection setup is expensive.+- **Temporary Apprise Instances**: Temporary Apprise instances are created for each send operation and automatically garbage collected by Python. This simple approach avoids memory management complexity.- **Shared Rate Limiter**: A single rate limiter instance is shared across all NotificationManager instances to correctly enforce per-user rate limits.- **Thread-Safe**: The rate limiter uses threading locks for safe concurrent access within a single process.- **Exponential Backoff Retry**: Failed notifications are retried up to 3 times with exponential backoff (0.5s → 1.0s → 2.0s) to handle transient network issues.@@ -168,209 +148,39 @@ The notification system is designed to work safely from background threads (e.g.### Settings Snapshot Pattern-**✅ CORRECT** - Using settings snapshot for background threads:+**Key Principle**: Capture settings once with a database session, then pass the snapshot (not the session) to `NotificationManager`.-```python-from local_deep_research.notifications.manager import NotificationManager-from local_deep_research.settings import SettingsManager-from local_deep_research.database.session_context import get_user_db_session+- ✅ **Correct**: `NotificationManager(settings_snapshot=settings_snapshot)`+- ❌ **Wrong**: `NotificationManager(session=session)` - Not thread-safe!-# In background thread or queue processor-with get_user_db_session(username, password) as session:- # Capture settings snapshot in main thread (with DB session)- settings_manager = SettingsManager(session)- settings_snapshot = settings_manager.get_settings_snapshot()-- # Create NotificationManager with snapshot (no session - thread-safe!)- notification_manager = NotificationManager(- settings_snapshot=settings_snapshot- )-- # Safe to use from any thread- notification_manager.send_notification(- event_type=EventType.RESEARCH_COMPLETED,- context=context,- user_id=username- )-```--**❌ WRONG** - Passing database session to background thread:+See the source code in `web/queue/processor_v2.py` and `error_handling/error_reporter.py` for implementation examples.-```python-# DON'T DO THIS - Session is not thread-safe!-with get_user_db_session(username, password) as session:- notification_manager = NotificationManager(session=session)-- # This will cause issues if used from background thread- # SQLite connections are not thread-safe- notification_manager.send_notification(...)-```--### Flask Route Usage (Main Thread)--For Flask routes running in the main thread, use settings snapshot:--```python-from flask import g, request, jsonify-from local_deep_research.notifications.manager import NotificationManager-from local_deep_research.settings import SettingsManager-[email protected]('/api/test-notification', methods=['POST'])-@login_required-def test_notification():- # Get settings snapshot from database session- settings_manager = SettingsManager(g.db_session)- settings_snapshot = settings_manager.get_settings_snapshot()-- # Create notification manager with snapshot- notification_manager = NotificationManager(settings_snapshot=settings_snapshot)-- result = notification_manager.test_service(- request.json.get('service_url')- )-- return jsonify(result)-```--## Advanced Usage Examples--### Custom Retry Behavior--The notification system has built-in retry logic that can be bypassed:--```python-notification_manager = NotificationManager(settings_snapshot=snapshot)--# Force send without rate limiting or retries-try:- result = notification_manager.send_notification(- event_type=EventType.RESEARCH_COMPLETED,- context=context,- force=True # Bypasses rate limits and disabled settings- )-except Exception as e:- # After 3 retry attempts, exception is raised- logger.error(f"All retry attempts exhausted: {e}")-```+## Advanced Usage### Multiple Service URLs-Send to multiple services simultaneously:--```python-# Configure multiple services in settings-settings_snapshot = {- "notifications.service_url": (- "discord://webhook_id/webhook_token,"- "slack://token_a/token_b/token_c,"- "mailto://user:[email protected]"- ),- "notifications.on_research_completed": True,-}+Configure multiple comma-separated service URLs to send notifications to multiple services simultaneously (Discord, Slack, email, etc.).-notification_manager = NotificationManager(settings_snapshot=settings_snapshot)+### Custom Retry Behavior-# Notification sent to all configured services-notification_manager.send_notification(- event_type=EventType.RESEARCH_COMPLETED,- context=context,-)-```+Use `force=True` parameter to bypass rate limits and disabled settings for critical notifications.### Event-Specific Configuration-Enable/disable notifications per event type:--```python-settings_snapshot = {- "notifications.service_url": "discord://webhook/token",- "notifications.on_research_completed": True, # Enabled- "notifications.on_research_failed": True, # Enabled- "notifications.on_subscription_update": False, # Disabled- "notifications.on_subscription_error": True, # Enabled-}--notification_manager = NotificationManager(settings_snapshot=settings_snapshot)--# This will send (research_completed is enabled)-notification_manager.send_notification(- event_type=EventType.RESEARCH_COMPLETED,- context={"query": "Test"}-)--# This will NOT send (subscription_update is disabled)-notification_manager.send_notification(- event_type=EventType.SUBSCRIPTION_UPDATE,- context={"subscription_name": "Daily News"}-)-```+Each event type can be individually enabled/disabled via settings (see Event-Specific Settings above).### Rate Limit Handling-Handle rate limit errors gracefully:--```python-from local_deep_research.notifications.exceptions import RateLimitError--notification_manager = NotificationManager(settings_snapshot=snapshot)--try:- notification_manager.send_notification(- event_type=EventType.RESEARCH_COMPLETED,- context=context,- user_id="test_user"- )-except RateLimitError as e:- logger.warning(f"Rate limit exceeded: {e}")- # Optionally notify user via UI or schedule for later-```+Rate limit exceptions (`RateLimitError`) can be caught and handled gracefully. See `notifications/exceptions.py` for available exception types.## Troubleshooting### Notifications Not Sending-1. **Check service URL configuration**:- ```python- from local_deep_research.settings import SettingsManager- from local_deep_research.database.session_context import get_user_db_session-- with get_user_db_session(username, password) as session:- settings_manager = SettingsManager(session)- service_url = settings_manager.get_setting("notifications.service_url")- print(f"Configured service URL: {service_url}")- ```--2. **Test service connection**:- ```python- from local_deep_research.notifications.manager import NotificationManager-- with get_user_db_session(username, password) as session:- settings_manager = SettingsManager(session)- settings_snapshot = settings_manager.get_settings_snapshot()- notification_manager = NotificationManager(settings_snapshot=settings_snapshot)- result = notification_manager.test_service(service_url)- if not result["success"]:- print(f"Service test failed: {result.get('error')}")- ```--3. **Check event-specific settings**:- ```python- # Verify notifications are enabled for the event type- with get_user_db_session(username, password) as session:- settings_manager = SettingsManager(session)- enabled = settings_manager.get_setting(- "notifications.on_research_completed",- default=True- )- print(f"Notifications enabled: {enabled}")- ```--4. **Check rate limits**:- ```python- # Rate limits are enforced per-user- # Check logs for rate limit messages- # Logs will show: "Rate limit exceeded for user {user_id}"- ```+1. **Check service URL configuration**: Use `SettingsManager.get_setting("notifications.service_url")` to verify the service URL is configured+2. **Test service connection**: Use `notification_manager.test_service(service_url)` to verify connectivity+3. **Check event-specific settings**: Verify the specific event type is enabled (e.g., `notifications.on_research_completed`)+4. **Check rate limits**: Look for "Rate limit exceeded for user {user_id}" messages in logs### Common Issuesdiff --git a/docs/NOTIFICATION_FLOW.md b/docs/NOTIFICATION_FLOW.mdindex 00b9a85824..77cdbf4d73 100644--- a/docs/NOTIFICATION_FLOW.md+++ b/docs/NOTIFICATION_FLOW.md@@ -7,8 +7,11 @@ This document traces the complete flow of notifications from research completionNotifications are sent when:1. **Research completes successfully** → `RESEARCH_COMPLETED` event2. **Research fails** → `RESEARCH_FAILED` event-3. **Subscription updates** → `SUBSCRIPTION_UPDATE` event (future)-4. **Subscription errors** → `SUBSCRIPTION_ERROR` event (future)+3. **Research is queued** → `RESEARCH_QUEUED` event+4. **Subscription updates** → `SUBSCRIPTION_UPDATE` event+5. **Subscription errors** → `SUBSCRIPTION_ERROR` event+6. **API quota/rate limits exceeded** → `API_QUOTA_WARNING` event+7. **Authentication fails** → `AUTH_ISSUE` event## Complete Flow: Research Completed@@ -153,7 +156,7 @@ def send_notification(```**Settings Checked (from `settings_snapshot`):**-1. **`notifications.on_research_completed`** - Is this event type enabled? (default: True)+1. **`notifications.on_research_completed`** - Is this event type enabled? (default: False for most events)2. **Rate limits** - Check shared rate limiter (per-user):- `notifications.rate_limit_per_hour` (default: 10)- `notifications.rate_limit_per_day` (default: 50)@@ -224,18 +227,13 @@ def send(for attempt in range(1, MAX_RETRY_ATTEMPTS + 1): # 3 attemptstry:- # Get or create cached Apprise instance for these URLs- url_hash = hashlib.sha256(service_urls.encode()).hexdigest()[:16]-- if url_hash not in self._apprise_cache:- cached_apprise = apprise.Apprise()- result = cached_apprise.add(service_urls, tag=tag)- self._apprise_cache[url_hash] = cached_apprise- else:- cached_apprise = self._apprise_cache[url_hash]-- # Send notification with the cached instance- notify_result = cached_apprise.notify(+ # Create temporary Apprise instance+ # Automatically garbage collected by Python when out of scope+ apprise_instance = apprise.Apprise()+ apprise_instance.add(service_urls, tag=tag)++ # Send notification+ notify_result = apprise_instance.notify(title=title,body=body,tag=tag,@@ -264,9 +262,9 @@ def send(- **Attempt 3**: Wait 1.0s, retry- **After 3 attempts**: Raise `SendError`-**Apprise Caching:**-- Caches Apprise instances by URL hash-- Reuses connections for better performance (especially SMTP)+**Apprise Instances:**+- Temporary instances created for each send operation+- Automatically garbage collected by Python- Multiple service URLs supported (comma-separated)### 8. Apprise Delivers Notification@@ -303,12 +301,14 @@ Similar to completed flow, but:```pythonEventType.RESEARCH_FAILED: {"title": "Research Failed: {query}",- "body": "Your research '{query}' has failed.\n\n"+ "body": "Research on '{query}' failed.\n\n""Error: {error}\n\n"- "Research ID: {research_id}",+ "Please check the logs for more details.",}```+**Note**: Error messages are sanitized for security to avoid exposing sensitive information in notifications.+## Settings Snapshot Pattern**Why Settings Snapshot?**@@ -398,11 +398,14 @@ class NotificationManager:# Service URL (required) - comma-separated listnotifications.service_url = "discord://webhook_id/token,mailto://user:[email protected]"-# Event-specific toggles (default: True)-notifications.on_research_completed = True-notifications.on_research_failed = True-notifications.on_subscription_update = True-notifications.on_subscription_error = True+# Event-specific toggles (default: False for most events)+notifications.on_research_completed = True # Default: True+notifications.on_research_failed = True # Default: True+notifications.on_research_queued = False # Default: False+notifications.on_subscription_update = True # Default: True+notifications.on_subscription_error = False # Default: False+notifications.on_api_quota_warning = False # Default: False+notifications.on_auth_issue = False # Default: False# Rate limits (per-user)notifications.rate_limit_per_hour = 10 # Max notifications per hour@@ -531,25 +534,48 @@ Apprise.notify(title=title, body=body)1. **Settings Snapshot Pattern**: Avoids thread-safety issues with database sessions2. **Shared Rate Limiter**: Single instance ensures correct per-user enforcement-3. **Apprise Caching**: Reuses connections for performance (especially SMTP)+3. **Temporary Apprise Instances**: Created per-send and automatically garbage collected4. **Exponential Backoff**: 3 retry attempts with increasing delays (0.5s → 1.0s → 2.0s)5. **Encrypted Storage**: Service URLs stored encrypted in per-user SQLCipher database6. **URL Masking**: Credentials hidden in logs (e.g., `discord://webhook_id/***`)7. **No Session in Manager**: NotificationManager never receives database session (thread-safe)+8. **Error Sanitization**: Error messages sanitized in notifications to prevent information exposure++## Additional Notification Events++### Research Queued Notifications++Sent when research is added to the queue:++- **Event**: `EventType.RESEARCH_QUEUED`+- **Triggered from**: `web/queue/manager.py` when adding research to queue+- **Context**: `query`, `position`, `wait_time`+- **Default**: Disabled (opt-in)++### API Quota Warnings++Sent when API rate limits are exceeded:++- **Event**: `EventType.API_QUOTA_WARNING`+- **Triggered from**: `error_handling/error_reporter.py` when detecting rate limit errors+- **Context**: `service`, `current`, `limit`, `reset_time`+- **Default**: Disabled (opt-in)++### Authentication Issues++Sent when API authentication fails:-## Future: Subscription Notifications+- **Event**: `EventType.AUTH_ISSUE`+- **Triggered from**: `error_handling/error_reporter.py` when detecting auth errors+- **Context**: `service`+- **Default**: Disabled (opt-in)-Similar flow will be implemented for:+### Subscription Notifications-- **`EventType.SUBSCRIPTION_UPDATE`**: When subscription refresh finds new items-- **`EventType.SUBSCRIPTION_ERROR`**: When subscription refresh fails+Sent when subscriptions update or fail:-Template context will include:-- `subscription_name`: Name of the subscription-- `subscription_id`: Subscription ID-- `item_count`: Number of new items (for updates)-- `error`: Error message (for errors)-- `url`: Full URL to view subscription+- **Events**: `EventType.SUBSCRIPTION_UPDATE`, `EventType.SUBSCRIPTION_ERROR`+- **Context**: `subscription_name`, `subscription_id`, `item_count`/`error`, `url`## Testingdiff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex f090307581..15a281cffe 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -5471,5 +5471,47 @@"ui_element": "checkbox","value": false,"visible": true+ },+ "notifications.on_research_queued": {+ "category": "notifications",+ "description": "Send notification when research is added to queue",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Research Queued",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "notifications.on_api_quota_warning": {+ "category": "notifications",+ "description": "Send notification when API quota/rate limits are exceeded",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "API Quota Warnings",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "notifications.on_auth_issue": {+ "category": "notifications",+ "description": "Send notification when authentication fails for API services",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Authentication Issues",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true}}diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pyindex a13d12cb15..3107a5dc17 100644--- a/src/local_deep_research/error_handling/error_reporter.py+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -232,8 +232,132 @@ class ErrorReporter:or context.get("search_results"))+ # Send notifications for specific error types+ self._send_error_notifications(category, error_message, context)+return analysis+ def _send_error_notifications(+ self,+ category: ErrorCategory,+ error_message: str,+ context: Optional[Dict[str, Any]] = None,+ ) -> None:+ """+ Send notifications for specific error categories.++ Args:+ category: Error category+ error_message: Error message+ context: Optional context information+ """+ try:+ # Only send notifications for AUTH and QUOTA errors+ if category not in [+ ErrorCategory.MODEL_ERROR,+ ErrorCategory.RATE_LIMIT_ERROR,+ ]:+ return++ # Try to get username from context+ username = None+ if context:+ username = context.get("username")++ # Don't send notifications if we can't determine user+ if not username:+ logger.debug(+ "No username in context, skipping error notification"+ )+ return++ from ..notifications.manager import NotificationManager+ from ..notifications import EventType+ from ..database.session_context import get_user_db_session++ # Get settings snapshot for notification+ with get_user_db_session(username) as session:+ from ..settings import SettingsManager++ settings_manager = SettingsManager(session)+ settings_snapshot = settings_manager.get_settings_snapshot()++ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Determine event type and build context+ if category == ErrorCategory.MODEL_ERROR:+ # Check if it's an auth error specifically+ error_str = error_message.lower()+ if any(+ pattern in error_str+ for pattern in [+ "api key",+ "authentication",+ "401",+ "unauthorized",+ ]+ ):+ event_type = EventType.AUTH_ISSUE+ notification_context = {+ "service": self._extract_service_name(error_message),+ }+ else:+ # Not an auth error, don't notify+ return++ elif category == ErrorCategory.RATE_LIMIT_ERROR:+ event_type = EventType.API_QUOTA_WARNING+ notification_context = {+ "service": self._extract_service_name(error_message),+ "current": "Unknown",+ "limit": "Unknown",+ "reset_time": "Unknown",+ }++ else:+ return++ # Send notification+ notification_manager.send_notification(+ event_type=event_type,+ context=notification_context,+ user_id=username,+ )++ except Exception as e:+ logger.debug(f"Failed to send error notification: {e}")++ def _extract_service_name(self, error_message: str) -> str:+ """+ Extract service name from error message.++ Args:+ error_message: Error message++ Returns:+ Service name or "API Service"+ """+ error_lower = error_message.lower()++ # Check for common service names+ services = [+ "openai",+ "anthropic",+ "google",+ "ollama",+ "searxng",+ "tavily",+ "brave",+ ]++ for service in services:+ if service in error_lower:+ return service.title()++ return "API Service"+def _determine_severity(self, category: ErrorCategory) -> str:"""Determine error severity level"""severity_map = {diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex a80797f4d5..df73d0691f 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -208,7 +208,7 @@ class NotificationManager:try:# Check event-specific setting (from snapshot or database)setting_key = f"notifications.on_{event_type.value}"- enabled = self._get_setting(setting_key, default=True)+ enabled = self._get_setting(setting_key, default=False)return enableddiff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.pyindex 05e06c434c..076731cd0e 100644--- a/src/local_deep_research/notifications/service.py+++ b/src/local_deep_research/notifications/service.py@@ -2,10 +2,8 @@Core notification service using Apprise."""-import hashlibimport reimport time-from collections import OrderedDictfrom typing import Dict, List, Optional, Anyfrom urllib.parse import urlparse@@ -20,9 +18,6 @@ MAX_RETRY_ATTEMPTS = 3INITIAL_RETRY_DELAY = 0.5 # secondsRETRY_BACKOFF_MULTIPLIER = 2-# Cache configuration - prevents unbounded memory growth-MAX_APPRISE_CACHE_SIZE = 1000 # Reasonable limit for notification URL caching-class NotificationService:"""@@ -41,16 +36,12 @@ class NotificationService:def __init__(self):"""Initialize the notification service."""self.apprise = apprise.Apprise()- # Cache for Apprise instances by service URL hash- # Improves performance by reusing connections- # Uses OrderedDict to maintain insertion order for FIFO eviction- self._apprise_cache: OrderedDict[str, apprise.Apprise] = OrderedDict()def send(self,title: str,body: str,- service_urls: Optional[str] = None, # Changed parameter name+ service_urls: Optional[str] = None,tag: Optional[str] = None,attach: Optional[List[str]] = None,) -> bool:@@ -69,54 +60,32 @@ class NotificationService:Raises:SendError: If sending fails after all retry attempts++ Note:+ Temporary Apprise instances are created for each send operation+ and are automatically garbage collected by Python when they go+ out of scope. This simple approach is ideal for small deployments+ (~5 users) and avoids memory management complexity."""last_error = Noneretry_delay = INITIAL_RETRY_DELAYfor attempt in range(1, MAX_RETRY_ATTEMPTS + 1):try:- # If service_urls are provided, use cached Apprise instance+ # If service_urls are provided, create a new Apprise instanceif service_urls:- # Get or create cached Apprise instance for these URLs- url_hash = hashlib.sha256(- service_urls.encode()- ).hexdigest()[:16]-- if url_hash not in self._apprise_cache:- # Check cache size and evict oldest entry if at limit- if len(self._apprise_cache) >= MAX_APPRISE_CACHE_SIZE:- # Remove oldest entry (FIFO eviction)- evicted_hash, _ = self._apprise_cache.popitem(- last=False- )- logger.debug(- f"Evicted oldest Apprise cache entry "- f"{evicted_hash} "- f"(cache at max size: {MAX_APPRISE_CACHE_SIZE})"- )-- logger.debug(- f"Creating new cached Apprise instance "- f"for URL hash {url_hash} "- f"(cache size: {len(self._apprise_cache) + 1})"- )- cached_apprise = apprise.Apprise()- result = cached_apprise.add(service_urls, tag=tag)-- if not result:- logger.error(- f"Failed to add service URLs to Apprise: "- f"{self._mask_url(service_urls)}"- )- return False+ logger.debug(+ "Creating Apprise instance for provided service URLs"+ )+ temp_apprise = apprise.Apprise()+ result = temp_apprise.add(service_urls, tag=tag)- self._apprise_cache[url_hash] = cached_apprise- else:- logger.debug(- f"Using cached Apprise instance "- f"for URL hash {url_hash}"+ if not result:+ logger.error(+ f"Failed to add service URLs to Apprise: "+ f"{self._mask_url(service_urls)}")- cached_apprise = self._apprise_cache[url_hash]+ return Falselogger.debug(f"Sending notification (attempt {attempt}/"@@ -125,8 +94,8 @@ class NotificationService:)logger.debug(f"Body preview: {body[:200]}...")- # Send notification with the cached instance- notify_result = cached_apprise.notify(+ # Send notification with the temp instance+ notify_result = temp_apprise.notify(title=title,body=body,tag=tag,diff --git a/src/local_deep_research/notifications/templates.py b/src/local_deep_research/notifications/templates.pyindex 04129b71d5..2660f4382a 100644--- a/src/local_deep_research/notifications/templates.py+++ b/src/local_deep_research/notifications/templates.py@@ -74,14 +74,6 @@ class NotificationTemplate:"The subscription will retry automatically."),},- EventType.RATE_LIMIT_WARNING: {- "title": "Rate Limit Warning",- "body": (- "You are approaching rate limits for {service}.\n\n"- "Current usage: {current}/{limit}\n"- "Reset time: {reset_time}"- ),- },EventType.API_QUOTA_WARNING: {"title": "API Quota Warning","body": (diff --git a/src/local_deep_research/notifications/utils.py b/src/local_deep_research/notifications/utils.pydeleted file mode 100644index 99cdc1b6d5..0000000000--- a/src/local_deep_research/notifications/utils.py+++ /dev/null@@ -1,8 +0,0 @@-"""-Utility functions for notifications.--Note: build_notification_url has been moved to url_builder.py-Import it from there or from the notifications package directly:-- from local_deep_research.notifications import build_notification_url-"""diff --git a/src/local_deep_research/web/queue/manager.py b/src/local_deep_research/web/queue/manager.pyindex 3724cd147b..0c9ca40e0c 100644--- a/src/local_deep_research/web/queue/manager.py+++ b/src/local_deep_research/web/queue/manager.py@@ -58,6 +58,34 @@ class QueueManager:f"Added research {research_id} to queue at position {max_position + 1}")+ # Send RESEARCH_QUEUED notification if enabled+ try:+ from ...settings import SettingsManager+ from ...notifications.manager import NotificationManager+ from ...notifications import EventType++ settings_manager = SettingsManager(session)+ settings_snapshot = settings_manager.get_settings_snapshot()++ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Build notification context+ context = {+ "query": query,+ "position": max_position + 1,+ "wait_time": "Unknown", # Could estimate based on active researches+ }++ notification_manager.send_notification(+ event_type=EventType.RESEARCH_QUEUED,+ context=context,+ user_id=username,+ )+ except Exception as e:+ logger.debug(f"Failed to send queued notification: {e}")+# Notify queue processor about the new queued research# Note: When using QueueManager, we don't have all parameters for direct execution# So it will fall back to queue modediff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 54d10ae781..15be5a7f54 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -441,10 +441,13 @@ class QueueProcessorV2:else report_content)else: # RESEARCH_FAILED+ # Sanitize error message for notification to avoid exposing+ # sensitive information (as noted by github-advanced-security)+ safe_error = "Research failed. Check logs for details."context = {"query": research.query or "Unknown query","research_id": research_id,- "error": error_message or "Unknown error",+ "error": safe_error,}logger.info(@@ -485,10 +488,12 @@ class QueueProcessorV2:"url": f"/research/{research_id}",}else: # RESEARCH_FAILED+ # Sanitize error for notification+ safe_error = "Research failed. Check logs for details."context = {"query": f"Research {research_id}","research_id": research_id,- "error": error_message or "Unknown error",+ "error": safe_error,}notification_manager.send_notification(diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 4fb9df331f..bcac268bbd 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1584,44 +1584,6 @@ def run_research_process(now = datetime.now(UTC)completed_at = now.isoformat()- # NOTE: Database updates from threads are handled by queue processor- # The queue_processor.queue_error_update() method is already being used below- # to safely update the database from the main thread- """- # DEPRECATED: Direct database updates from background threads- # Get the start time from the database- duration_seconds = None- with get_user_db_session(username) as db_session:- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )- assert research is not None, "Research not in database"-- duration_seconds = calculate_duration(research.created_at)-- with get_user_db_session(username) as db_session:- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )- assert research is not None, "Research not in database"-- # Update the ResearchHistory object with the new status and completion time- research.status = status- research.completed_at = completed_at- research.duration_seconds = duration_seconds- research.research_meta = metadata-- # Add error report path if available- if "report_path_to_save" in locals() and report_path_to_save:- research.report_path = report_path_to_save-- db_session.commit()- """-# Queue the error update to be processed in main thread# Using the existing queue processor system (there are multiple implementations:# processor.py, processor_v2.py, and several queue models as noted in issue #596)@@ -1698,50 +1660,6 @@ def cleanup_research_resources(# Get the current status from the database to determine the final status messagecurrent_status = "completed" # Default- # NOTE: Queue processor already handles database updates from the main thread- # The notify_research_completed() method is called at the end of this function- # which safely updates the database status- """- # DEPRECATED: Direct database access from background threads- try:- with get_user_db_session(username) as db_session:- research = (- db_session.query(ResearchHistory)- .filter(ResearchHistory.id == research_id)- .first()- )- if research:- current_status = research.status- else:- logger.error("Research with ID %s not found", research_id)-- # Clean up UserActiveResearch record- if username:- from ...database.models import UserActiveResearch-- active_record = (- db_session.query(UserActiveResearch)- .filter_by(username=username, research_id=research_id)- .first()- )- if active_record:- logger.info(- f"Cleaning up active research {research_id} for user {username} (was started at {active_record.started_at})"- )- db_session.delete(active_record)- db_session.commit()- logger.info(- f"Cleaned up active research record for user {username}"- )- else:- logger.warning(- f"No active research record found to clean up for {research_id} / {username}"- )-- except Exception:- logger.exception("Error retrieving research status during cleanup")- """-# Notify queue processor that research completed# This uses processor_v2 which handles database updates in the main thread# avoiding the Flask request context issues that occur in background threads