~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
Add comprehensive notification system with Apprise integration
tombii17762f9e1b48
diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdnew file mode 100644index 0000000000..c6dfa55eb9--- /dev/null+++ b/docs/NOTIFICATIONS.md@@ -0,0 +1,391 @@+# Notifications System++The Local Deep Research (LDR) notifications system provides a flexible way to send notifications to various services when important events occur, such as research completion, failures, or subscription updates.++## Overview++The notification system uses [Apprise](https://github.com/caronc/apprise) to support multiple notification services with a unified API. It allows users to configure comma-separated service URLs to receive notifications for different events.++## Supported Services++The system supports all services that Apprise supports, including but not limited to:++- Discord (via webhooks)+- Slack (via webhooks)+- Telegram+- Email (SMTP)+- Pushover+- Gotify+- Many more...++For a complete list, refer to the [Apprise documentation](https://github.com/caronc/apprise/wiki).++## Configuration++Notifications are configured per-user via the settings system:++### Service URL Setting+- **Key**: `notifications.service_url`+- **Type**: String (comma-separated list of service URLs)+- **Example**: `discord://webhook_id/webhook_token,mailto://user:[email protected]`+- **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++### Rate Limiting Settings+- `notifications.rate_limit_per_hour` - Max notifications per hour per user+- `notifications.rate_limit_per_day` - Max notifications per day per user++**Note on Multi-Worker Deployments**: The current rate limiting implementation uses in-memory storage and is process-local. In multi-worker deployments (e.g., gunicorn with multiple workers), each worker process maintains its own rate limit counters. This means a user could potentially send up to `N × max_per_hour` notifications (where N = number of workers) by distributing requests across different workers. For single-worker deployments (the default for LDR), this is not a concern. If you're running a multi-worker production deployment, consider monitoring notification volumes or implementing Redis-based rate limiting.++### URL Configuration+- `app.external_url` - Public URL where your LDR instance is accessible (e.g., `https://ldr.example.com`). Used to generate clickable links in notifications. If not set, defaults to `http://localhost:5000` or auto-constructs from `app.host` and `app.port`.++## Service URL Format++Multiple service URLs can be configured by separating them with commas:++```+discord://webhook1_id/webhook1_token,slack://token1/token2/token3,mailto://user:[email protected]+```++Each URL follows the Apprise format for the specific service.++## Available Event Types++- `research_completed` - When research completes successfully+- `research_failed` - When research fails+- `subscription_update` - When a subscription completes+- `subscription_error` - When a subscription fails++## Testing Notifications++Use the test function to verify notification configuration:++```python+from local_deep_research.notifications.manager import NotificationManager++# Create manager with empty settings (testing doesn't need settings)+notification_manager = NotificationManager(settings_snapshot={})++# Test a service URL+result = notification_manager.test_service("discord://webhook_id/webhook_token")+print(result) # {'success': True, 'message': 'Test notification sent successfully'}+```++## Programmatic Usage++### Basic Notification++```python+from local_deep_research.notifications.manager import NotificationManager+from local_deep_research.notifications.templates import EventType+from local_deep_research.settings import SettingsManager+from local_deep_research.database.session_context import get_user_db_session++# Get settings snapshot+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)+notification_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(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ 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)++# 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+}+```++## Architecture++The notification system consists of three main components:++1. **NotificationManager** - High-level manager that handles rate limiting, settings, and user preferences+2. **NotificationService** - Low-level service that uses Apprise to send notifications+3. **Settings Integration** - User-specific configuration for services and event preferences++The system fetches service URLs from user settings when needed, rather than maintaining persistent channels, making it more efficient and secure.++### Security & Privacy++- **Encrypted Storage**: All notification service URLs (including credentials like SMTP passwords or webhook tokens) are stored encrypted at rest in your per-user SQLCipher database using AES-256 encryption.+- **Zero-Knowledge Architecture**: The encryption key is derived from your login password using PBKDF2-SHA512. Your password is never stored, and notification settings cannot be recovered without it.+- **URL Masking**: Service URLs are automatically masked in logs to prevent credential exposure (e.g., `discord://webhook_id/***`).+- **Per-User Isolation**: Each user's notification settings are completely isolated in their own encrypted database.++### 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.+- **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.++## Thread Safety & Background Tasks++The notification system is designed to work safely from background threads (e.g., research queue processors). Use the **settings snapshot pattern** to avoid thread-safety issues with database sessions.++### Settings Snapshot Pattern++**✅ CORRECT** - Using settings snapshot for background threads:++```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++# 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:++```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}")+```++### 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,+}++notification_manager = NotificationManager(settings_snapshot=settings_snapshot)++# Notification sent to all configured services+notification_manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+)+```++### 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"}+)+```++### 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+```++## 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}"+ ```++### Common Issues++**Issue**: "No notification service URLs configured"+- **Cause**: `notifications.service_url` setting is empty or not set+- **Fix**: Configure service URL in settings dashboard or via API++**Issue**: "Rate limit exceeded"+- **Cause**: User has sent too many notifications within the time window+- **Fix**: Wait for rate limit window to expire, or use `force=True` for critical notifications++**Issue**: "Failed to send notification after 3 attempts"+- **Cause**: Service is unreachable or credentials are invalid+- **Fix**: Verify service URL is correct, test with `test_service()`, check network connectivity++**Issue**: Notifications work in main thread but fail in background thread+- **Cause**: Using database session in background thread (not thread-safe)+- **Fix**: Use settings snapshot pattern as shown in migration guide abovediff --git a/docs/NOTIFICATION_FLOW.md b/docs/NOTIFICATION_FLOW.mdnew file mode 100644index 0000000000..00b9a85824--- /dev/null+++ b/docs/NOTIFICATION_FLOW.md@@ -0,0 +1,561 @@+# Notification Flow - Complete Trace++This document traces the complete flow of notifications from research completion/failure through to delivery via Apprise.++## Overview++Notifications are sent when:+1. **Research completes successfully** → `RESEARCH_COMPLETED` event+2. **Research fails** → `RESEARCH_FAILED` event+3. **Subscription updates** → `SUBSCRIPTION_UPDATE` event (future)+4. **Subscription errors** → `SUBSCRIPTION_ERROR` event (future)++## Complete Flow: Research Completed++### 1. Research Thread Completes (`research_service.py:1166-1168`)++When research finishes successfully in the background thread:++```python+# src/local_deep_research/web/services/research_service.py:1166+cleanup_research_resources(+ research_id, active_research, termination_flags, username+)+```++### 2. Cleanup Calls Queue Processor (`research_service.py:1727`)++The cleanup function notifies the queue processor:++```python+# src/local_deep_research/web/services/research_service.py:1727+queue_processor.notify_research_completed(username, research_id, user_password=user_password)+```++**Key Points:**+- Called from background research thread+- Passes `user_password` for secure database access+- Uses `processor_v2` which handles encrypted per-user databases++### 3. Queue Processor Updates Status (`processor_v2.py:278-306`)++```python+# src/local_deep_research/web/queue/processor_v2.py:278-306+def notify_research_completed(self, username: str, research_id: str, user_password: str = None):+ with get_user_db_session(username, user_password) as session:+ # Update queue status+ queue_service = UserQueueService(session)+ queue_service.update_task_status(research_id, "completed")++ # Send notification if enabled+ self._send_research_notification(+ session=session,+ username=username,+ research_id=research_id,+ event_type="RESEARCH_COMPLETED",+ )+```++**Key Points:**+- Opens encrypted user database with password+- Updates queue status first+- Delegates to `_send_research_notification` helper++### 4. Build Notification Context (`processor_v2.py:357-243`)++The helper method prepares the notification:++```python+# src/local_deep_research/web/queue/processor_v2.py:357-243+def _send_research_notification(+ self,+ session,+ username: str,+ research_id: str,+ event_type: str,+ error_message: str = None,+):+ # Get settings snapshot for thread-safe notification sending+ settings_manager = SettingsManager(session)+ settings_snapshot = settings_manager.get_settings_snapshot()++ # Lookup research details (with retry logic for timing issues)+ research = session.query(ResearchHistory).filter_by(id=research_id).first()++ if research:+ # Create notification manager with settings snapshot+ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Build full URL for notification+ full_url = build_notification_url(+ f"/research/{research_id}",+ settings_manager=settings_manager,+ )++ # Build notification context+ context = {+ "query": research.query or "Unknown query",+ "research_id": research_id,+ "summary": report_content[:200] + "...", # Truncated+ "url": full_url, # Full clickable URL+ }++ # Send notification+ result = notification_manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ user_id=username,+ )+```++**Key Points:**+- **Settings Snapshot**: Captures settings at notification time (thread-safe)+- **Research Lookup**: Queries database for research details with 3 retry attempts+- **URL Building**: Constructs full URL using `app.external_url` or `app.host`/`app.port`+- **Context Building**: Includes query, research_id, summary (truncated to 200 chars), full URL+- **No Session Passed**: NotificationManager gets `settings_snapshot`, NOT session (thread-safe)++### 5. NotificationManager Checks Settings (`manager.py:91-126`)++```python+# src/local_deep_research/notifications/manager.py:91-126+def send_notification(+ self,+ event_type: EventType,+ context: Dict[str, Any],+ user_id: Optional[str] = None,+ force: bool = False,+) -> bool:+ # Check if notifications are enabled for this event type+ should_notify = self._should_notify(event_type, user_id)+ if not force and not should_notify:+ logger.debug(f"Notifications disabled for event type: {event_type.value}")+ return False++ # Check rate limit+ rate_limit_ok = self._rate_limiter.allow(user_id or "default")+ if not force and not rate_limit_ok:+ raise RateLimitError("Notification rate limit exceeded")++ # Get service URLs from settings snapshot+ service_urls = self._get_setting("notifications.service_url", default="")++ if not service_urls or not service_urls.strip():+ logger.debug("No notification service URLs configured")+ return False++ # Send notification with service URLs+ result = self.service.send_event(event_type, context, service_urls=service_urls)++ return result+```++**Settings Checked (from `settings_snapshot`):**+1. **`notifications.on_research_completed`** - Is this event type enabled? (default: True)+2. **Rate limits** - Check shared rate limiter (per-user):+ - `notifications.rate_limit_per_hour` (default: 10)+ - `notifications.rate_limit_per_day` (default: 50)+3. **`notifications.service_url`** - Comma-separated list of Apprise URLs (required)++**Key Points:**+- All settings come from `settings_snapshot` (captured earlier)+- Rate limiter is **shared singleton** across all NotificationManager instances+- `force=False` by default (respects settings and rate limits)++### 6. NotificationService Formats Message (`service.py:198-235`)++```python+# src/local_deep_research/notifications/service.py:198-235+def send_event(+ self,+ event_type: EventType,+ context: Dict[str, Any],+ service_urls: Optional[str] = None,+ tag: Optional[str] = None,+ custom_template: Optional[Dict[str, str]] = None,+) -> bool:+ # Format notification using template+ message = NotificationTemplate.format(+ event_type, context, custom_template+ )++ # Send notification+ result = self.send(+ title=message["title"],+ body=message["body"],+ service_urls=service_urls,+ tag=tag,+ )+ return result+```++**Template Used (`templates.py`):**+```python+EventType.RESEARCH_COMPLETED: {+ "title": "Research Completed: {query}",+ "body": "Your research '{query}' has completed successfully.\n\n"+ "Summary: {summary}\n\n"+ "View results: {url}",+}+```++**Context Variables:**+- `{query}` - Research query text+- `{summary}` - Truncated report content (max 200 chars)+- `{url}` - Full clickable URL to view research+- `{research_id}` - Research ID (available but not used in default template)++### 7. NotificationService Sends via Apprise (`service.py:47-196`)++```python+# src/local_deep_research/notifications/service.py:47-196+def send(+ self,+ title: str,+ body: str,+ service_urls: Optional[str] = None,+ tag: Optional[str] = None,+ attach: Optional[List[str]] = None,+) -> bool:+ # Retry logic with exponential backoff+ retry_delay = INITIAL_RETRY_DELAY # 0.5s++ for attempt in range(1, MAX_RETRY_ATTEMPTS + 1): # 3 attempts+ try:+ # 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(+ title=title,+ body=body,+ tag=tag,+ attach=attach,+ )++ if notify_result:+ return True++ # Retry with exponential backoff+ time.sleep(retry_delay)+ retry_delay *= RETRY_BACKOFF_MULTIPLIER # 2x++ except Exception as e:+ logger.error(f"Error sending notification: {e}")+ time.sleep(retry_delay)+ retry_delay *= RETRY_BACKOFF_MULTIPLIER++ # All attempts failed+ raise SendError("Failed to send notification after 3 attempts")+```++**Retry Strategy:**+- **Attempt 1**: Immediate send+- **Attempt 2**: Wait 0.5s, retry+- **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)+- Multiple service URLs supported (comma-separated)++### 8. Apprise Delivers Notification++Apprise handles the actual delivery to configured services:++```python+# User's settings: notifications.service_url+"discord://webhook_id/webhook_token,mailto://user:[email protected]"+```++**Supported Services** (via Apprise):+- Discord, Slack, Telegram+- Email (SMTP, Gmail, etc.)+- Pushover, Gotify+- Many more: https://github.com/caronc/apprise/wiki++**Security:**+- Service URLs encrypted at rest (AES-256 via SQLCipher)+- Encryption key derived from user's login password (PBKDF2-SHA512)+- URLs masked in logs (e.g., `discord://webhook_id/***`)++## Complete Flow: Research Failed++Similar to completed flow, but:++1. **Entry Point**: `research_service.py:1642` (exception handler)+2. **Queue Method**: `queue_processor.queue_error_update()` (processor.py)+3. **Notification**: Sent from `processor.py:577-606` (error update handler)+4. **Event Type**: `EventType.RESEARCH_FAILED`+5. **Context**: Includes `error` field instead of `summary`++**Template for RESEARCH_FAILED:**+```python+EventType.RESEARCH_FAILED: {+ "title": "Research Failed: {query}",+ "body": "Your research '{query}' has failed.\n\n"+ "Error: {error}\n\n"+ "Research ID: {research_id}",+}+```++## Settings Snapshot Pattern++**Why Settings Snapshot?**++Notifications are sent from background threads that shouldn't access Flask `g` or SQLite sessions (not thread-safe). The solution is to **capture settings once** in the main thread and pass them as a dict.++**How It Works:**++```python+# 1. In main thread (with database session)+settings_manager = SettingsManager(session)+settings_snapshot = settings_manager.get_settings_snapshot()+# Returns dict like: {"notifications.service_url": "...", "notifications.on_research_completed": True, ...}++# 2. Pass to NotificationManager (thread-safe - no session!)+notification_manager = NotificationManager(settings_snapshot=settings_snapshot)++# 3. NotificationManager reads from snapshot+def _get_setting(self, key: str, default: Any = None) -> Any:+ return self._settings_snapshot.get(key, default)+```++**Benefits:**+- ✅ Thread-safe (no database access in background threads)+- ✅ Consistent settings (captured at notification time, not changed mid-notification)+- ✅ No Flask `g` context needed+- ✅ Works from queue processors, schedulers, etc.++## Rate Limiting++**Implementation:** In-memory, per-user, shared singleton++```python+class RateLimiter:+ _lock = threading.Lock()+ _hourly_counts: Dict[str, deque] = {} # user_id -> timestamps+ _daily_counts: Dict[str, deque] = {} # user_id -> timestamps++ def allow(self, user_id: str) -> bool:+ with self._lock: # Thread-safe+ now = datetime.now(timezone.utc)++ # Clean old entries (> 1 hour, > 1 day)+ self._clean_old_entries(user_id, now)++ # Check limits+ if len(self._hourly_counts[user_id]) >= self.max_per_hour:+ return False+ if len(self._daily_counts[user_id]) >= self.max_per_day:+ return False++ # Record this notification+ self._hourly_counts[user_id].append(now)+ self._daily_counts[user_id].append(now)++ return True+```++**Shared Singleton Pattern:**+```python+class NotificationManager:+ _shared_rate_limiter: Optional["RateLimiter"] = None+ _rate_limiter_lock = threading.Lock()++ def __init__(self, settings_snapshot: Dict[str, Any]):+ with NotificationManager._rate_limiter_lock:+ if NotificationManager._shared_rate_limiter is None:+ NotificationManager._shared_rate_limiter = RateLimiter(+ max_per_hour=settings_snapshot.get("notifications.rate_limit_per_hour", 10),+ max_per_day=settings_snapshot.get("notifications.rate_limit_per_day", 50),+ )+ self._rate_limiter = NotificationManager._shared_rate_limiter+```++**Key Points:**+- One rate limiter instance across all NotificationManager instances+- Ensures per-user limits are enforced correctly+- Thread-safe with `threading.Lock()`+- Automatic cleanup of old entries+- Periodic cleanup of inactive users (every 24 hours)++## Configuration++### Required Settings++```python+# Service URL (required) - comma-separated list+notifications.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++# Rate limits (per-user)+notifications.rate_limit_per_hour = 10 # Max notifications per hour+notifications.rate_limit_per_day = 50 # Max notifications per day++# URL configuration (for clickable links)+app.external_url = "https://ldr.example.com" # Preferred+# OR+app.host = "localhost"+app.port = 5000+```++### Testing Notifications++```python+from local_deep_research.notifications.manager import NotificationManager++# Create manager with empty settings (testing doesn't need settings)+notification_manager = NotificationManager(settings_snapshot={})++# Test a service URL+result = notification_manager.test_service("discord://webhook_id/webhook_token")+print(result) # {'success': True, 'message': 'Test notification sent successfully'}+```++## Error Handling++### Rate Limit Exceeded++```python+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}")+ # Notification not sent, user needs to wait+```++### Send Failure (After 3 Retries)++```python+try:+ result = service.send(title="...", body="...", service_urls="...")+except SendError as e:+ logger.error(f"Failed to send notification after 3 attempts: {e}")+ # All retry attempts exhausted+```++### No Service URLs Configured++```python+result = notification_manager.send_notification(...)+# Returns: False (no error raised)+# Log: "No notification service URLs configured for user {user_id}"+```++### Notifications Disabled for Event Type++```python+# settings_snapshot = {"notifications.on_research_completed": False}+result = notification_manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context+)+# Returns: False (respects user preference)+# Log: "Notifications disabled for event type: research_completed"+```++## Architecture Diagram++```+[Research Thread]+ ↓+cleanup_research_resources()+ ↓+queue_processor.notify_research_completed(username, research_id, password)+ ↓+[Queue Processor - Main Thread]+ ↓+get_user_db_session(username, password) → [Encrypted DB]+ ↓+SettingsManager(session).get_settings_snapshot() → settings_snapshot+ ↓+ResearchHistory.query.filter_by(id=research_id).first() → research details+ ↓+build_notification_url() → full_url+ ↓+NotificationManager(settings_snapshot=settings_snapshot)+ ↓+notification_manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context={query, research_id, summary, url},+ user_id=username+)+ ↓+[NotificationManager]+ ├─ Check: notifications.on_research_completed+ ├─ Check: Rate limiter (hourly/daily)+ └─ Get: notifications.service_url+ ↓+NotificationService.send_event(event_type, context, service_urls)+ ↓+NotificationTemplate.format(event_type, context) → {title, body}+ ↓+NotificationService.send(title, body, service_urls)+ ↓+[Retry Loop: 3 attempts with exponential backoff]+ ├─ Attempt 1: Immediate+ ├─ Attempt 2: Wait 0.5s+ └─ Attempt 3: Wait 1.0s+ ↓+Apprise.add(service_urls)+ ↓+Apprise.notify(title=title, body=body)+ ↓+[Apprise - Delivery]+ ├─ Discord webhook+ ├─ SMTP email+ └─ Other services...+```++## Key Design Decisions++1. **Settings Snapshot Pattern**: Avoids thread-safety issues with database sessions+2. **Shared Rate Limiter**: Single instance ensures correct per-user enforcement+3. **Apprise Caching**: Reuses connections for performance (especially SMTP)+4. **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 database+6. **URL Masking**: Credentials hidden in logs (e.g., `discord://webhook_id/***`)+7. **No Session in Manager**: NotificationManager never receives database session (thread-safe)++## Future: Subscription Notifications++Similar flow will be implemented for:++- **`EventType.SUBSCRIPTION_UPDATE`**: When subscription refresh finds new items+- **`EventType.SUBSCRIPTION_ERROR`**: When subscription refresh fails++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++## Testing++Run notification tests:+```bash+pdm run python -m pytest tests/notifications/ -v+```++All 91 tests passing ✓diff --git a/pdm.lock b/pdm.lockindex ee8375585c..85b476f934 100644--- a/pdm.lock+++ b/pdm.lock@@ -5,7 +5,7 @@groups = ["default", "dev"]strategy = ["inherit_metadata"]lock_version = "4.5.0"-content_hash = "sha256:b9aa1d52fc1c168dcfae477a1609552a263bfecdb127ef88a87ced2f6d38d90f"+content_hash = "sha256:53708d525d7873dee05dac1580ff35fd842a15182d1a361c6af97ceb1b657e4f"[[metadata.targets]]requires_python = ">=3.11"@@ -199,6 +199,26 @@ files = [{file = "appnope-0.1.4.tar.gz", hash = "sha256:1de3860566df9caf38f01f86f65e0e13e379af54f9e4bee1e66b48f2efffd1ee"},]+[[package]]+name = "apprise"+version = "1.9.5"+requires_python = ">=3.9"+summary = "Push Notifications that work with just about every platform!"+groups = ["default"]+dependencies = [+ "PyYAML",+ "certifi",+ "click>=5.0",+ "markdown",+ "requests",+ "requests-oauthlib",+ "tzdata; platform_system == \"Windows\"",+]+files = [+ {file = "apprise-1.9.5-py3-none-any.whl", hash = "sha256:1873a8a1b8cf9e44fcbefe0486ed260b590652aea12427f545b37c8566142961"},+ {file = "apprise-1.9.5.tar.gz", hash = "sha256:8f3be318bb429c2017470e33928a2e313cbf7600fc74b8184782a37060db366a"},+]+[[package]]name = "apscheduler"version = "3.11.0"@@ -1138,6 +1158,33 @@ files = [{file = "dataclasses_json-0.6.7.tar.gz", hash = "sha256:b6b3e528266ea45b9535223bc53ca645f5208833c29229e847b3f26a1cc55fc0"},]+[[package]]+name = "datasets"+version = "4.2.0"+requires_python = ">=3.9.0"+summary = "HuggingFace community-driven open-source library of datasets"+groups = ["default"]+dependencies = [+ "dill<0.4.1,>=0.3.0",+ "filelock",+ "fsspec[http]<=2025.9.0,>=2023.1.0",+ "httpx<1.0.0",+ "huggingface-hub<2.0,>=0.25.0",+ "multiprocess<0.70.17",+ "numpy>=1.17",+ "packaging",+ "pandas",+ "pyarrow>=21.0.0",+ "pyyaml>=5.1",+ "requests>=2.32.2",+ "tqdm>=4.66.3",+ "xxhash",+]+files = [+ {file = "datasets-4.2.0-py3-none-any.whl", hash = "sha256:fdc43aaf4a73b31f64f80f72f195ab413a1141ed15555d675b2fd17926f8b026"},+ {file = "datasets-4.2.0.tar.gz", hash = "sha256:8333a7db9f3bb8044c1b819a35d4e3e2809596c837793b0921382efffdc36e78"},+]+[[package]]name = "debugpy"version = "1.8.17"@@ -1187,6 +1234,17 @@ files = [{file = "defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69"},]+[[package]]+name = "dill"+version = "0.4.0"+requires_python = ">=3.8"+summary = "serialize all of Python"+groups = ["default"]+files = [+ {file = "dill-0.4.0-py3-none-any.whl", hash = "sha256:44f54bf6412c2c8464c14e8243eb163690a9800dbe2c367330883b19c7561049"},+ {file = "dill-0.4.0.tar.gz", hash = "sha256:0633f1d2df477324f53a895b02c901fb961bdbf65a17122586ea7019292cbcf0"},+]+[[package]]name = "distlib"version = "0.4.0"@@ -1703,6 +1761,22 @@ files = [{file = "fsspec-2025.9.0.tar.gz", hash = "sha256:19fd429483d25d28b65ec68f9f4adc16c17ea2c7c7bf54ec61360d478fb19c19"},]+[[package]]+name = "fsspec"+version = "2025.9.0"+extras = ["http"]+requires_python = ">=3.9"+summary = "File-system specification"+groups = ["default"]+dependencies = [+ "aiohttp!=4.0.0a0,!=4.0.0a1",+ "fsspec==2025.9.0",+]+files = [+ {file = "fsspec-2025.9.0-py3-none-any.whl", hash = "sha256:530dc2a2af60a414a832059574df4a6e10cce927f6f4a78209390fe38955cfb7"},+ {file = "fsspec-2025.9.0.tar.gz", hash = "sha256:19fd429483d25d28b65ec68f9f4adc16c17ea2c7c7bf54ec61360d478fb19c19"},+]+[[package]]name = "google-search-results"version = "2.4.2"@@ -3364,6 +3438,21 @@ files = [{file = "multidict-6.6.4.tar.gz", hash = "sha256:d2d4e4787672911b48350df02ed3fa3fffdc2f2e8ca06dd6afdf34189b76a9dd"},]+[[package]]+name = "multiprocess"+version = "0.70.16"+requires_python = ">=3.8"+summary = "better multiprocessing and multithreading in Python"+groups = ["default"]+dependencies = [+ "dill>=0.3.8",+]+files = [+ {file = "multiprocess-0.70.16-py311-none-any.whl", hash = "sha256:af4cabb0dac72abfb1e794fa7855c325fd2b55a10a44628a3c1ad3311c04127a"},+ {file = "multiprocess-0.70.16-py312-none-any.whl", hash = "sha256:fc0544c531920dde3b00c29863377f87e1632601092ea2daca74e4beb40faa2e"},+ {file = "multiprocess-0.70.16.tar.gz", hash = "sha256:161af703d4652a0e1410be6abccecde4a7ddffd19341be0a7011b94aeb171ac1"},+]+[[package]]name = "mypy-extensions"version = "1.1.0"@@ -3613,6 +3702,17 @@ files = [{file = "numpy-2.3.3.tar.gz", hash = "sha256:ddc7c39727ba62b80dfdbedf400d1c10ddfa8eefbd7ec8dcb118be8b56d31029"},]+[[package]]+name = "oauthlib"+version = "3.3.1"+requires_python = ">=3.8"+summary = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic"+groups = ["default"]+files = [+ {file = "oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1"},+ {file = "oauthlib-3.3.1.tar.gz", hash = "sha256:0f0f8aa759826a193cf66c12ea1af1637f87b9b4622d46e866952bb022e538c9"},+]+[[package]]name = "olefile"version = "0.47"@@ -4217,6 +4317,44 @@ files = [{file = "pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42"},]+[[package]]+name = "pyarrow"+version = "21.0.0"+requires_python = ">=3.9"+summary = "Python library for Apache Arrow"+groups = ["default"]+files = [+ {file = "pyarrow-21.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:c077f48aab61738c237802836fc3844f85409a46015635198761b0d6a688f87b"},+ {file = "pyarrow-21.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:689f448066781856237eca8d1975b98cace19b8dd2ab6145bf49475478bcaa10"},+ {file = "pyarrow-21.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:479ee41399fcddc46159a551705b89c05f11e8b8cb8e968f7fec64f62d91985e"},+ {file = "pyarrow-21.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:40ebfcb54a4f11bcde86bc586cbd0272bac0d516cfa539c799c2453768477569"},+ {file = "pyarrow-21.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8d58d8497814274d3d20214fbb24abcad2f7e351474357d552a8d53bce70c70e"},+ {file = "pyarrow-21.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:585e7224f21124dd57836b1530ac8f2df2afc43c861d7bf3d58a4870c42ae36c"},+ {file = "pyarrow-21.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:555ca6935b2cbca2c0e932bedd853e9bc523098c39636de9ad4693b5b1df86d6"},+ {file = "pyarrow-21.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:3a302f0e0963db37e0a24a70c56cf91a4faa0bca51c23812279ca2e23481fccd"},+ {file = "pyarrow-21.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:b6b27cf01e243871390474a211a7922bfbe3bda21e39bc9160daf0da3fe48876"},+ {file = "pyarrow-21.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e72a8ec6b868e258a2cd2672d91f2860ad532d590ce94cdf7d5e7ec674ccf03d"},+ {file = "pyarrow-21.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b7ae0bbdc8c6674259b25bef5d2a1d6af5d39d7200c819cf99e07f7dfef1c51e"},+ {file = "pyarrow-21.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:58c30a1729f82d201627c173d91bd431db88ea74dcaa3885855bc6203e433b82"},+ {file = "pyarrow-21.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:072116f65604b822a7f22945a7a6e581cfa28e3454fdcc6939d4ff6090126623"},+ {file = "pyarrow-21.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:cf56ec8b0a5c8c9d7021d6fd754e688104f9ebebf1bf4449613c9531f5346a18"},+ {file = "pyarrow-21.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e99310a4ebd4479bcd1964dff9e14af33746300cb014aa4a3781738ac63baf4a"},+ {file = "pyarrow-21.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:d2fe8e7f3ce329a71b7ddd7498b3cfac0eeb200c2789bd840234f0dc271a8efe"},+ {file = "pyarrow-21.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:f522e5709379d72fb3da7785aa489ff0bb87448a9dc5a75f45763a795a089ebd"},+ {file = "pyarrow-21.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:69cbbdf0631396e9925e048cfa5bce4e8c3d3b41562bbd70c685a8eb53a91e61"},+ {file = "pyarrow-21.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:731c7022587006b755d0bdb27626a1a3bb004bb56b11fb30d98b6c1b4718579d"},+ {file = "pyarrow-21.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc56bc708f2d8ac71bd1dcb927e458c93cec10b98eb4120206a4091db7b67b99"},+ {file = "pyarrow-21.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:186aa00bca62139f75b7de8420f745f2af12941595bbbfa7ed3870ff63e25636"},+ {file = "pyarrow-21.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:a7a102574faa3f421141a64c10216e078df467ab9576684d5cd696952546e2da"},+ {file = "pyarrow-21.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:1e005378c4a2c6db3ada3ad4c217b381f6c886f0a80d6a316fe586b90f77efd7"},+ {file = "pyarrow-21.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:65f8e85f79031449ec8706b74504a316805217b35b6099155dd7e227eef0d4b6"},+ {file = "pyarrow-21.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:3a81486adc665c7eb1a2bde0224cfca6ceaba344a82a971ef059678417880eb8"},+ {file = "pyarrow-21.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:fc0d2f88b81dcf3ccf9a6ae17f89183762c8a94a5bdcfa09e05cfe413acf0503"},+ {file = "pyarrow-21.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6299449adf89df38537837487a4f8d3bd91ec94354fdd2a7d30bc11c48ef6e79"},+ {file = "pyarrow-21.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:222c39e2c70113543982c6b34f3077962b44fca38c0bd9e68bb6781534425c10"},+ {file = "pyarrow-21.0.0.tar.gz", hash = "sha256:5051f2dccf0e283ff56335760cbc8622cf52264d67e359d5569541ac11b6d5bc"},+]+[[package]]name = "pycparser"version = "2.23"@@ -5010,6 +5148,21 @@ files = [{file = "requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf"},]+[[package]]+name = "requests-oauthlib"+version = "2.0.0"+requires_python = ">=3.4"+summary = "OAuthlib authentication support for Requests."+groups = ["default"]+dependencies = [+ "oauthlib>=3.0.0",+ "requests>=2.0.0",+]+files = [+ {file = "requests-oauthlib-2.0.0.tar.gz", hash = "sha256:b3dffaebd884d8cd778494369603a9e7b58d29111bf6b41bdc2dcd87203af4e9"},+ {file = "requests_oauthlib-2.0.0-py2.py3-none-any.whl", hash = "sha256:7dd8a5c40426b779b0868c404bdef9768deccf22749cde15852df527e6269b36"},+]+[[package]]name = "requests-toolbelt"version = "1.0.0"@@ -6223,6 +6376,111 @@ files = [{file = "xmltodict-1.0.2.tar.gz", hash = "sha256:54306780b7c2175a3967cad1db92f218207e5bc1aba697d887807c0fb68b7649"},]+[[package]]+name = "xxhash"+version = "3.6.0"+requires_python = ">=3.7"+summary = "Python binding for xxHash"+groups = ["default"]+files = [+ {file = "xxhash-3.6.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b47bbd8cf2d72797f3c2772eaaac0ded3d3af26481a26d7d7d41dc2d3c46b04a"},+ {file = "xxhash-3.6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2b6821e94346f96db75abaa6e255706fb06ebd530899ed76d32cd99f20dc52fa"},+ {file = "xxhash-3.6.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:d0a9751f71a1a65ce3584e9cae4467651c7e70c9d31017fa57574583a4540248"},+ {file = "xxhash-3.6.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b29ee68625ab37b04c0b40c3fafdf24d2f75ccd778333cfb698f65f6c463f62"},+ {file = "xxhash-3.6.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6812c25fe0d6c36a46ccb002f40f27ac903bf18af9f6dd8f9669cb4d176ab18f"},+ {file = "xxhash-3.6.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4ccbff013972390b51a18ef1255ef5ac125c92dc9143b2d1909f59abc765540e"},+ {file = "xxhash-3.6.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:297b7fbf86c82c550e12e8fb71968b3f033d27b874276ba3624ea868c11165a8"},+ {file = "xxhash-3.6.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dea26ae1eb293db089798d3973a5fc928a18fdd97cc8801226fae705b02b14b0"},+ {file = "xxhash-3.6.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7a0b169aafb98f4284f73635a8e93f0735f9cbde17bd5ec332480484241aaa77"},+ {file = "xxhash-3.6.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:08d45aef063a4531b785cd72de4887766d01dc8f362a515693df349fdb825e0c"},+ {file = "xxhash-3.6.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:929142361a48ee07f09121fe9e96a84950e8d4df3bb298ca5d88061969f34d7b"},+ {file = "xxhash-3.6.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:51312c768403d8540487dbbfb557454cfc55589bbde6424456951f7fcd4facb3"},+ {file = "xxhash-3.6.0-cp311-cp311-win32.whl", hash = "sha256:d1927a69feddc24c987b337ce81ac15c4720955b667fe9b588e02254b80446fd"},+ {file = "xxhash-3.6.0-cp311-cp311-win_amd64.whl", hash = "sha256:26734cdc2d4ffe449b41d186bbeac416f704a482ed835d375a5c0cb02bc63fef"},+ {file = "xxhash-3.6.0-cp311-cp311-win_arm64.whl", hash = "sha256:d72f67ef8bf36e05f5b6c65e8524f265bd61071471cd4cf1d36743ebeeeb06b7"},+ {file = "xxhash-3.6.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:01362c4331775398e7bb34e3ab403bc9ee9f7c497bc7dee6272114055277dd3c"},+ {file = "xxhash-3.6.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b7b2df81a23f8cb99656378e72501b2cb41b1827c0f5a86f87d6b06b69f9f204"},+ {file = "xxhash-3.6.0-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:dc94790144e66b14f67b10ac8ed75b39ca47536bf8800eb7c24b50271ea0c490"},+ {file = "xxhash-3.6.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93f107c673bccf0d592cdba077dedaf52fe7f42dcd7676eba1f6d6f0c3efffd2"},+ {file = "xxhash-3.6.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2aa5ee3444c25b69813663c9f8067dcfaa2e126dc55e8dddf40f4d1c25d7effa"},+ {file = "xxhash-3.6.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7f99123f0e1194fa59cc69ad46dbae2e07becec5df50a0509a808f90a0f03f0"},+ {file = "xxhash-3.6.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:49e03e6fe2cac4a1bc64952dd250cf0dbc5ef4ebb7b8d96bce82e2de163c82a2"},+ {file = "xxhash-3.6.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bd17fede52a17a4f9a7bc4472a5867cb0b160deeb431795c0e4abe158bc784e9"},+ {file = "xxhash-3.6.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:6fb5f5476bef678f69db04f2bd1efbed3030d2aba305b0fc1773645f187d6a4e"},+ {file = "xxhash-3.6.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:843b52f6d88071f87eba1631b684fcb4b2068cd2180a0224122fe4ef011a9374"},+ {file = "xxhash-3.6.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:7d14a6cfaf03b1b6f5f9790f76880601ccc7896aff7ab9cd8978a939c1eb7e0d"},+ {file = "xxhash-3.6.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:418daf3db71e1413cfe211c2f9a528456936645c17f46b5204705581a45390ae"},+ {file = "xxhash-3.6.0-cp312-cp312-win32.whl", hash = "sha256:50fc255f39428a27299c20e280d6193d8b63b8ef8028995323bf834a026b4fbb"},+ {file = "xxhash-3.6.0-cp312-cp312-win_amd64.whl", hash = "sha256:c0f2ab8c715630565ab8991b536ecded9416d615538be8ecddce43ccf26cbc7c"},+ {file = "xxhash-3.6.0-cp312-cp312-win_arm64.whl", hash = "sha256:eae5c13f3bc455a3bbb68bdc513912dc7356de7e2280363ea235f71f54064829"},+ {file = "xxhash-3.6.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:599e64ba7f67472481ceb6ee80fa3bd828fd61ba59fb11475572cc5ee52b89ec"},+ {file = "xxhash-3.6.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7d8b8aaa30fca4f16f0c84a5c8d7ddee0e25250ec2796c973775373257dde8f1"},+ {file = "xxhash-3.6.0-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:d597acf8506d6e7101a4a44a5e428977a51c0fadbbfd3c39650cca9253f6e5a6"},+ {file = "xxhash-3.6.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:858dc935963a33bc33490128edc1c12b0c14d9c7ebaa4e387a7869ecc4f3e263"},+ {file = "xxhash-3.6.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba284920194615cb8edf73bf52236ce2e1664ccd4a38fdb543506413529cc546"},+ {file = "xxhash-3.6.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4b54219177f6c6674d5378bd862c6aedf64725f70dd29c472eaae154df1a2e89"},+ {file = "xxhash-3.6.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42c36dd7dbad2f5238950c377fcbf6811b1cdb1c444fab447960030cea60504d"},+ {file = "xxhash-3.6.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f22927652cba98c44639ffdc7aaf35828dccf679b10b31c4ad72a5b530a18eb7"},+ {file = "xxhash-3.6.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b45fad44d9c5c119e9c6fbf2e1c656a46dc68e280275007bbfd3d572b21426db"},+ {file = "xxhash-3.6.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:6f2580ffab1a8b68ef2b901cde7e55fa8da5e4be0977c68f78fc80f3c143de42"},+ {file = "xxhash-3.6.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:40c391dd3cd041ebc3ffe6f2c862f402e306eb571422e0aa918d8070ba31da11"},+ {file = "xxhash-3.6.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f205badabde7aafd1a31e8ca2a3e5a763107a71c397c4481d6a804eb5063d8bd"},+ {file = "xxhash-3.6.0-cp313-cp313-win32.whl", hash = "sha256:2577b276e060b73b73a53042ea5bd5203d3e6347ce0d09f98500f418a9fcf799"},+ {file = "xxhash-3.6.0-cp313-cp313-win_amd64.whl", hash = "sha256:757320d45d2fbcce8f30c42a6b2f47862967aea7bf458b9625b4bbe7ee390392"},+ {file = "xxhash-3.6.0-cp313-cp313-win_arm64.whl", hash = "sha256:457b8f85dec5825eed7b69c11ae86834a018b8e3df5e77783c999663da2f96d6"},+ {file = "xxhash-3.6.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:a42e633d75cdad6d625434e3468126c73f13f7584545a9cf34e883aa1710e702"},+ {file = "xxhash-3.6.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:568a6d743219e717b07b4e03b0a828ce593833e498c3b64752e0f5df6bfe84db"},+ {file = "xxhash-3.6.0-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bec91b562d8012dae276af8025a55811b875baace6af510412a5e58e3121bc54"},+ {file = "xxhash-3.6.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:78e7f2f4c521c30ad5e786fdd6bae89d47a32672a80195467b5de0480aa97b1f"},+ {file = "xxhash-3.6.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3ed0df1b11a79856df5ffcab572cbd6b9627034c1c748c5566fa79df9048a7c5"},+ {file = "xxhash-3.6.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0e4edbfc7d420925b0dd5e792478ed393d6e75ff8fc219a6546fb446b6a417b1"},+ {file = "xxhash-3.6.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fba27a198363a7ef87f8c0f6b171ec36b674fe9053742c58dd7e3201c1ab30ee"},+ {file = "xxhash-3.6.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:794fe9145fe60191c6532fa95063765529770edcdd67b3d537793e8004cabbfd"},+ {file = "xxhash-3.6.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:6105ef7e62b5ac73a837778efc331a591d8442f8ef5c7e102376506cb4ae2729"},+ {file = "xxhash-3.6.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:f01375c0e55395b814a679b3eea205db7919ac2af213f4a6682e01220e5fe292"},+ {file = "xxhash-3.6.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:d706dca2d24d834a4661619dcacf51a75c16d65985718d6a7d73c1eeeb903ddf"},+ {file = "xxhash-3.6.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5f059d9faeacd49c0215d66f4056e1326c80503f51a1532ca336a385edadd033"},+ {file = "xxhash-3.6.0-cp313-cp313t-win32.whl", hash = "sha256:1244460adc3a9be84731d72b8e80625788e5815b68da3da8b83f78115a40a7ec"},+ {file = "xxhash-3.6.0-cp313-cp313t-win_amd64.whl", hash = "sha256:b1e420ef35c503869c4064f4a2f2b08ad6431ab7b229a05cce39d74268bca6b8"},+ {file = "xxhash-3.6.0-cp313-cp313t-win_arm64.whl", hash = "sha256:ec44b73a4220623235f67a996c862049f375df3b1052d9899f40a6382c32d746"},+ {file = "xxhash-3.6.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:a40a3d35b204b7cc7643cbcf8c9976d818cb47befcfac8bbefec8038ac363f3e"},+ {file = "xxhash-3.6.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a54844be970d3fc22630b32d515e79a90d0a3ddb2644d8d7402e3c4c8da61405"},+ {file = "xxhash-3.6.0-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:016e9190af8f0a4e3741343777710e3d5717427f175adfdc3e72508f59e2a7f3"},+ {file = "xxhash-3.6.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f6f72232f849eb9d0141e2ebe2677ece15adfd0fa599bc058aad83c714bb2c6"},+ {file = "xxhash-3.6.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:63275a8aba7865e44b1813d2177e0f5ea7eadad3dd063a21f7cf9afdc7054063"},+ {file = "xxhash-3.6.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3cd01fa2aa00d8b017c97eb46b9a794fbdca53fc14f845f5a328c71254b0abb7"},+ {file = "xxhash-3.6.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0226aa89035b62b6a86d3c68df4d7c1f47a342b8683da2b60cedcddb46c4d95b"},+ {file = "xxhash-3.6.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c6e193e9f56e4ca4923c61238cdaced324f0feac782544eb4c6d55ad5cc99ddd"},+ {file = "xxhash-3.6.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9176dcaddf4ca963d4deb93866d739a343c01c969231dbe21680e13a5d1a5bf0"},+ {file = "xxhash-3.6.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:c1ce4009c97a752e682b897aa99aef84191077a9433eb237774689f14f8ec152"},+ {file = "xxhash-3.6.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:8cb2f4f679b01513b7adbb9b1b2f0f9cdc31b70007eaf9d59d0878809f385b11"},+ {file = "xxhash-3.6.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:653a91d7c2ab54a92c19ccf43508b6a555440b9be1bc8be553376778be7f20b5"},+ {file = "xxhash-3.6.0-cp314-cp314-win32.whl", hash = "sha256:a756fe893389483ee8c394d06b5ab765d96e68fbbfe6fde7aa17e11f5720559f"},+ {file = "xxhash-3.6.0-cp314-cp314-win_amd64.whl", hash = "sha256:39be8e4e142550ef69629c9cd71b88c90e9a5db703fecbcf265546d9536ca4ad"},+ {file = "xxhash-3.6.0-cp314-cp314-win_arm64.whl", hash = "sha256:25915e6000338999236f1eb68a02a32c3275ac338628a7eaa5a269c401995679"},+ {file = "xxhash-3.6.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:c5294f596a9017ca5a3e3f8884c00b91ab2ad2933cf288f4923c3fd4346cf3d4"},+ {file = "xxhash-3.6.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1cf9dcc4ab9cff01dfbba78544297a3a01dafd60f3bde4e2bfd016cf7e4ddc67"},+ {file = "xxhash-3.6.0-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:01262da8798422d0685f7cef03b2bd3f4f46511b02830861df548d7def4402ad"},+ {file = "xxhash-3.6.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51a73fb7cb3a3ead9f7a8b583ffd9b8038e277cdb8cb87cf890e88b3456afa0b"},+ {file = "xxhash-3.6.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b9c6df83594f7df8f7f708ce5ebeacfc69f72c9fbaaababf6cf4758eaada0c9b"},+ {file = "xxhash-3.6.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:627f0af069b0ea56f312fd5189001c24578868643203bca1abbc2c52d3a6f3ca"},+ {file = "xxhash-3.6.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aa912c62f842dfd013c5f21a642c9c10cd9f4c4e943e0af83618b4a404d9091a"},+ {file = "xxhash-3.6.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:b465afd7909db30168ab62afe40b2fcf79eedc0b89a6c0ab3123515dc0df8b99"},+ {file = "xxhash-3.6.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:a881851cf38b0a70e7c4d3ce81fc7afd86fbc2a024f4cfb2a97cf49ce04b75d3"},+ {file = "xxhash-3.6.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:9b3222c686a919a0f3253cfc12bb118b8b103506612253b5baeaac10d8027cf6"},+ {file = "xxhash-3.6.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:c5aa639bc113e9286137cec8fadc20e9cd732b2cc385c0b7fa673b84fc1f2a93"},+ {file = "xxhash-3.6.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5c1343d49ac102799905e115aee590183c3921d475356cb24b4de29a4bc56518"},+ {file = "xxhash-3.6.0-cp314-cp314t-win32.whl", hash = "sha256:5851f033c3030dd95c086b4a36a2683c2ff4a799b23af60977188b057e467119"},+ {file = "xxhash-3.6.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0444e7967dac37569052d2409b00a8860c2135cff05502df4da80267d384849f"},+ {file = "xxhash-3.6.0-cp314-cp314t-win_arm64.whl", hash = "sha256:bb79b1e63f6fd84ec778a4b1916dfe0a7c3fdb986c06addd5db3a0d413819d95"},+ {file = "xxhash-3.6.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0f7b7e2ec26c1666ad5fc9dbfa426a6a3367ceaf79db5dd76264659d509d73b0"},+ {file = "xxhash-3.6.0-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5dc1e14d14fa0f5789ec29a7062004b5933964bb9b02aae6622b8f530dc40296"},+ {file = "xxhash-3.6.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:881b47fc47e051b37d94d13e7455131054b56749b91b508b0907eb07900d1c13"},+ {file = "xxhash-3.6.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6dc31591899f5e5666f04cc2e529e69b4072827085c1ef15294d91a004bc1bd"},+ {file = "xxhash-3.6.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:15e0dac10eb9309508bfc41f7f9deaa7755c69e35af835db9cb10751adebc35d"},+ {file = "xxhash-3.6.0.tar.gz", hash = "sha256:f0162a78b13a0d7617b2845b90c763339d1f1d82bb04a4b07f4ab535cc5e05d6"},+]+[[package]]name = "yarl"version = "1.20.1"diff --git a/pyproject.toml b/pyproject.tomlindex bfa8990c0d..12146abb15 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -82,6 +82,7 @@ dependencies = ["markdown>=3.9","datasets>=2.14.0","pyarrow>=12.0.0",+ "apprise>=1.9.0",][project.optional-dependencies]diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 5ef3b2732a..f090307581 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -136,6 +136,20 @@"value": 5000,"visible": true},+ "app.external_url": {+ "category": "app_interface",+ "description": "Public URL where this application is accessible (e.g., http://localhost:5000, https://myapp.example.com). Used for generating links in notifications. Leave empty to auto-detect from request context.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "External URL",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "text",+ "value": "",+ "visible": true+ },"app.theme": {"category": "app_interface","description": "User interface theme",@@ -5306,7 +5320,7 @@},"research_library.shared_library": {"category": "research_library",- "description": "⚠️ WARNING: When enabled, all users share the same library directory. Documents from all users will be visible to each other. Only enable in trusted environments.",+ "description": "\u26a0\ufe0f WARNING: When enabled, all users share the same library directory. Documents from all users will be visible to each other. Only enable in trusted environments.","editable": true,"max_value": null,"min_value": null,@@ -5320,7 +5334,7 @@},"research_library.enable_pdf_storage": {"category": "research_library",- "description": "⚠️ PRIVACY WARNING: PDFs will be stored unencrypted on disk, exposing your research interests to anyone with filesystem access. Only enable if you need PDF files for external tools.",+ "description": "\u26a0\ufe0f PRIVACY WARNING: PDFs will be stored unencrypted on disk, exposing your research interests to anyone with filesystem access. Only enable if you need PDF files for external tools.","editable": true,"max_value": null,"min_value": null,@@ -5334,7 +5348,7 @@},"research_library.enable_txt_storage": {"category": "research_library",- "description": "⚠️ PRIVACY WARNING: Text files will be stored unencrypted on disk for RAG/ChromaDB integration. This exposes document contents to anyone with filesystem access.",+ "description": "\u26a0\ufe0f PRIVACY WARNING: Text files will be stored unencrypted on disk for RAG/ChromaDB integration. This exposes document contents to anyone with filesystem access.","editable": true,"max_value": null,"min_value": null,@@ -5345,5 +5359,117 @@"ui_element": "checkbox","value": false,"visible": true+ },+ "notifications.enabled": {+ "category": "notifications",+ "description": "Enable external notifications (email, messaging, etc.)",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Enable Notifications",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "notifications.service_url": {+ "category": "notifications",+ "description": "Notification service URL(s). Supports multiple comma-separated URLs to send notifications to multiple destinations (e.g., discord://webhook_id/token, mailto://user:[email protected][email protected]). See <a href=\"https://github.com/LearningCircuit/local-deep-research/blob/main/docs/NOTIFICATIONS.md\" target=\"_blank\">documentation</a> for supported services.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Service URL(s)",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "textarea",+ "value": "",+ "visible": true+ },+ "notifications.rate_limit_per_hour": {+ "category": "notifications",+ "description": "Maximum number of notifications per hour (prevents spam)",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Rate Limit (Hourly)",+ "options": null,+ "step": 1,+ "type": "APP",+ "ui_element": "number",+ "value": 10,+ "visible": true+ },+ "notifications.rate_limit_per_day": {+ "category": "notifications",+ "description": "Maximum number of notifications per day (prevents spam)",+ "editable": true,+ "max_value": 500,+ "min_value": 1,+ "name": "Rate Limit (Daily)",+ "options": null,+ "step": 1,+ "type": "APP",+ "ui_element": "number",+ "value": 50,+ "visible": true+ },+ "notifications.on_research_completed": {+ "category": "notifications",+ "description": "Send notification when research completes",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Research Completed",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "notifications.on_research_failed": {+ "category": "notifications",+ "description": "Send notification when research fails",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Research Failed",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "notifications.on_subscription_update": {+ "category": "notifications",+ "description": "Send notification when subscriptions have new content",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Subscription Updates",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "notifications.on_subscription_error": {+ "category": "notifications",+ "description": "Send notification when subscription encounters an error",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Subscription Errors",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true}}diff --git a/src/local_deep_research/notifications/__init__.py b/src/local_deep_research/notifications/__init__.pynew file mode 100644index 0000000000..d9a8c34cf1--- /dev/null+++ b/src/local_deep_research/notifications/__init__.py@@ -0,0 +1,38 @@+"""+Notification system for Local Deep Research.++Supports multiple notification services via Apprise including:+- Email (SMTP, Gmail, etc.)+- Messaging (Discord, Slack, Telegram, etc.)+- SMS (Twilio, AWS SNS, etc.)+- Push notifications (Pushover, Gotify, etc.)+"""++from .exceptions import (+ NotificationError,+ ServiceError,+ SendError,+ RateLimitError,+)+from .service import NotificationService+from .manager import NotificationManager+from .templates import NotificationTemplate, EventType+from .url_builder import (+ build_notification_url,+ validate_url,+ URLValidationError,+)++__all__ = [+ "NotificationError",+ "ServiceError",+ "SendError",+ "RateLimitError",+ "NotificationService",+ "NotificationManager",+ "NotificationTemplate",+ "EventType",+ "build_notification_url",+ "validate_url",+ "URLValidationError",+]diff --git a/src/local_deep_research/notifications/exceptions.py b/src/local_deep_research/notifications/exceptions.pynew file mode 100644index 0000000000..1edc27b9d8--- /dev/null+++ b/src/local_deep_research/notifications/exceptions.py@@ -0,0 +1,27 @@+"""+Exceptions for the notification system.+"""+++class NotificationError(Exception):+ """Base exception for notification-related errors."""++ pass+++class ServiceError(NotificationError):+ """Error related to notification service configuration or validation."""++ pass+++class SendError(NotificationError):+ """Error occurred while sending a notification."""++ pass+++class RateLimitError(NotificationError):+ """Rate limit exceeded for notifications."""++ passdiff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pynew file mode 100644index 0000000000..a80797f4d5--- /dev/null+++ b/src/local_deep_research/notifications/manager.py@@ -0,0 +1,429 @@+"""+High-level notification manager with database integration.+"""++from datetime import datetime, timezone, timedelta+from typing import Dict, Optional, Any+from collections import deque+import threading++from loguru import logger++from .service import NotificationService+from .templates import EventType+from .exceptions import RateLimitError+++class NotificationManager:+ """+ High-level notification manager that uses settings snapshots for+ thread-safe access to user settings.++ This manager is designed to be used from background threads (e.g., queue+ processors) by passing a settings_snapshot dictionary captured from the+ main thread.+ """++ # Shared rate limiter instance across all NotificationManager instances+ # This ensures rate limits are enforced correctly even when multiple+ # NotificationManager instances are created+ _shared_rate_limiter: Optional["RateLimiter"] = None+ _rate_limiter_lock = threading.Lock()++ def __init__(self, settings_snapshot: Dict[str, Any]):+ """+ Initialize the notification manager.++ Args:+ settings_snapshot: Dictionary of settings key-value pairs captured+ from SettingsManager.get_settings_snapshot().+ This allows thread-safe access to user settings+ from background threads.++ Example:+ >>> # In main thread with database session+ >>> settings_manager = SettingsManager(session)+ >>> snapshot = settings_manager.get_settings_snapshot()+ >>>+ >>> # In background thread (thread-safe)+ >>> notification_manager = NotificationManager(snapshot)+ >>> notification_manager.send_notification(...)+ """+ # Store settings snapshot for thread-safe access+ self._settings_snapshot = settings_snapshot++ self.service = NotificationService()++ # Initialize shared rate limiter on first use+ with NotificationManager._rate_limiter_lock:+ if NotificationManager._shared_rate_limiter is None:+ # Get rate limit settings from snapshot+ max_per_hour = self._get_setting(+ "notifications.rate_limit_per_hour", default=10+ )+ max_per_day = self._get_setting(+ "notifications.rate_limit_per_day", default=50+ )++ NotificationManager._shared_rate_limiter = RateLimiter(+ max_per_hour=max_per_hour,+ max_per_day=max_per_day,+ )++ # Use the shared instance+ self._rate_limiter = NotificationManager._shared_rate_limiter++ def _get_setting(self, key: str, default: Any = None) -> Any:+ """+ Get a setting value from snapshot.++ Args:+ key: Setting key+ default: Default value if not found++ Returns:+ Setting value or default+ """+ return self._settings_snapshot.get(key, default)++ def send_notification(+ self,+ event_type: EventType,+ context: Dict[str, Any],+ user_id: Optional[str] = None,+ force: bool = False,+ ) -> bool:+ """+ Send a notification for an event.++ Args:+ event_type: Type of event+ context: Context data for the notification+ user_id: User ID (for rate limiting and preferences)+ force: If True, bypass rate limiting++ Returns:+ True if notification was sent successfully++ Raises:+ RateLimitError: If rate limit is exceeded and force=False+ """+ try:+ logger.debug(+ f"Sending notification: event_type={event_type.value}, user_id={user_id}, force={force}"+ )+ logger.debug(f"Context keys: {list(context.keys())}")++ # Check if notifications are enabled for this event type+ should_notify = self._should_notify(event_type, user_id)+ logger.debug(+ f"Notification enabled check for {event_type.value}: {should_notify}"+ )++ if not force and not should_notify:+ logger.debug(+ f"Notifications disabled for event type: {event_type.value} (user: {user_id})"+ )+ return False++ # Check rate limit+ rate_limit_ok = self._rate_limiter.allow(user_id or "default")+ logger.debug(+ f"Rate limit check for {user_id or 'default'}: {rate_limit_ok}"+ )++ if not force and not rate_limit_ok:+ logger.warning(f"Rate limit exceeded for user {user_id}")+ raise RateLimitError(+ "Notification rate limit exceeded. "+ "Please wait before sending more notifications."+ )++ # Get service URLs from settings (snapshot or database)+ service_urls = self._get_setting(+ "notifications.service_url", default=""+ )++ if not service_urls or not service_urls.strip():+ logger.debug(+ f"No notification service URLs configured for user {user_id}"+ )+ return False++ # Send notification with service URLs+ logger.debug(f"Calling service.send_event for {event_type.value}")+ result = self.service.send_event(+ event_type, context, service_urls=service_urls+ )++ # Log to database if enabled+ if result:+ self._log_notification(event_type, context, user_id)+ logger.info(+ f"Notification sent: {event_type.value} to user {user_id}"+ )+ else:+ logger.warning(+ f"Notification failed: {event_type.value} to user {user_id}"+ )++ return result++ except RateLimitError:+ logger.warning(f"Rate limit error for user {user_id}")+ raise+ except Exception as e:+ logger.exception(+ f"Error sending notification for {event_type.value} to user {user_id}: {e}"+ )+ return False++ def test_service(self, url: str) -> Dict[str, Any]:+ """+ Test a notification service.++ Args:+ url: Service URL to test++ Returns:+ Dict with test results+ """+ return self.service.test_service(url)++ def _should_notify(+ self,+ event_type: EventType,+ user_id: Optional[str] = None,+ ) -> bool:+ """+ Check if notifications should be sent for this event type.++ Args:+ event_type: Event type to check+ user_id: User ID++ Returns:+ True if notifications should be sent+ """+ 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)++ return enabled++ except Exception as e:+ logger.debug(f"Error checking notification preferences: {e}")+ # Default to disabled on error to avoid infinite loops during login+ return False++ def _log_notification(+ self,+ event_type: EventType,+ context: Dict[str, Any],+ user_id: Optional[str] = None,+ ) -> None:+ """+ Log a sent notification (simplified logging to application logs only).++ Args:+ event_type: Event type+ context: Notification context+ user_id: User ID+ """+ try:+ title = (+ context.get("query")+ or context.get("subscription_name")+ or "Unknown"+ )+ logger.info(+ f"Notification sent: {event_type.value} - {title} (user: {user_id or 'unknown'})"+ )+ except Exception as e:+ logger.debug(f"Failed to log notification: {e}")+++class RateLimiter:+ """+ Simple in-memory rate limiter for notifications.++ Note: This implementation stores rate limits in memory only, which means+ limits are reset when the server restarts. This is acceptable for normal+ users since they cannot restart the server. If an admin restarts the server,+ rate limits reset which is reasonable behavior.++ Thread Safety: This implementation is thread-safe using threading.Lock()+ for concurrent requests from the same user. However, in a production+ environment with multiple worker processes (e.g., gunicorn with multiple+ workers), rate limits are not shared across processes.++ **Multi-Worker Limitation**: In multi-worker deployments, each worker+ process maintains its own rate limit counters. Users could potentially+ bypass rate limits by distributing requests across different workers,+ getting up to N × max_per_hour notifications (where N = number of workers).+ For single-worker deployments (the default for LDR), this is not a concern.+ For production multi-worker deployments, consider implementing Redis-based+ rate limiting.+ """++ def __init__(+ self,+ max_per_hour: int = 10,+ max_per_day: int = 50,+ cleanup_interval_hours: int = 24,+ ):+ """+ Initialize rate limiter.++ Args:+ max_per_hour: Maximum notifications per hour per user+ max_per_day: Maximum notifications per day per user+ cleanup_interval_hours: How often to run cleanup of inactive users (hours)+ """+ self.max_per_hour = max_per_hour+ self.max_per_day = max_per_day+ self.cleanup_interval_hours = cleanup_interval_hours+ self._hourly_counts: Dict[str, deque] = {}+ self._daily_counts: Dict[str, deque] = {}+ self._last_cleanup = datetime.now(timezone.utc)+ self._lock = threading.Lock() # Add thread safety++ def allow(self, user_id: str) -> bool:+ """+ Check if a notification is allowed for a user.++ Args:+ user_id: User identifier++ Returns:+ True if notification is allowed+ """+ with self._lock:+ now = datetime.now(timezone.utc)++ # Periodic cleanup of inactive users+ self._cleanup_inactive_users_if_needed(now)++ # Initialize queues for user if needed+ if user_id not in self._hourly_counts:+ self._hourly_counts[user_id] = deque()+ self._daily_counts[user_id] = deque()++ # Clean old entries+ self._clean_old_entries(user_id, now)++ # Check limits+ hourly_count = len(self._hourly_counts[user_id])+ daily_count = len(self._daily_counts[user_id])++ if hourly_count >= self.max_per_hour:+ logger.warning(+ f"Hourly rate limit exceeded for user {user_id}: "+ f"{hourly_count}/{self.max_per_hour}"+ )+ return False++ if daily_count >= self.max_per_day:+ logger.warning(+ f"Daily rate limit exceeded for user {user_id}: "+ f"{daily_count}/{self.max_per_day}"+ )+ return False++ # Record this notification+ self._hourly_counts[user_id].append(now)+ self._daily_counts[user_id].append(now)++ return True++ def _clean_old_entries(self, user_id: str, now: datetime) -> None:+ """+ Remove old entries from rate limit counters.++ Args:+ user_id: User identifier+ now: Current time+ """+ hour_ago = now - timedelta(hours=1)+ day_ago = now - timedelta(days=1)++ # Clean hourly queue+ while (+ self._hourly_counts[user_id]+ and self._hourly_counts[user_id][0] < hour_ago+ ):+ self._hourly_counts[user_id].popleft()++ # Clean daily queue+ while (+ self._daily_counts[user_id]+ and self._daily_counts[user_id][0] < day_ago+ ):+ self._daily_counts[user_id].popleft()++ def reset(self, user_id: Optional[str] = None) -> None:+ """+ Reset rate limits for a user or all users.++ Args:+ user_id: User to reset, or None for all users+ """+ if user_id:+ self._hourly_counts.pop(user_id, None)+ self._daily_counts.pop(user_id, None)+ else:+ self._hourly_counts.clear()+ self._daily_counts.clear()++ def _cleanup_inactive_users_if_needed(self, now: datetime) -> None:+ """+ Periodically clean up data for inactive users to prevent memory leaks.++ Args:+ now: Current timestamp+ """+ # Check if cleanup is needed+ if now - self._last_cleanup < timedelta(+ hours=self.cleanup_interval_hours+ ):+ return++ logger.debug("Running periodic cleanup of inactive notification users")++ # Define inactive threshold (users with no activity for 7 days)+ inactive_threshold = now - timedelta(days=7)++ inactive_users = []++ # Find users with no recent activity+ # Convert to list to avoid "dictionary changed size during iteration" error+ for user_id in list(self._hourly_counts.keys()):+ # Check if user has any recent entries+ hourly_entries = self._hourly_counts.get(user_id, [])+ daily_entries = self._daily_counts.get(user_id, [])++ # If no entries or all entries are old, mark as inactive+ has_recent_activity = False+ for entry in hourly_entries + daily_entries:+ if entry > inactive_threshold:+ has_recent_activity = True+ break++ if not has_recent_activity:+ inactive_users.append(user_id)++ # Remove inactive users+ for user_id in inactive_users:+ self._hourly_counts.pop(user_id, None)+ self._daily_counts.pop(user_id, None)+ logger.debug(+ f"Cleaned up inactive user {user_id} from rate limiter"+ )++ if inactive_users:+ logger.info(+ f"Cleaned up {len(inactive_users)} inactive users from rate limiter"+ )++ self._last_cleanup = nowdiff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.pynew file mode 100644index 0000000000..7a94749429--- /dev/null+++ b/src/local_deep_research/notifications/service.py@@ -0,0 +1,380 @@+"""+Core notification service using Apprise.+"""++import hashlib+import re+import time+from collections import OrderedDict+from typing import Dict, List, Optional, Any+from urllib.parse import urlparse++import apprise+from loguru import logger++from .exceptions import ServiceError, SendError+from .templates import EventType, NotificationTemplate++# Retry configuration constants+MAX_RETRY_ATTEMPTS = 3+INITIAL_RETRY_DELAY = 0.5 # seconds+RETRY_BACKOFF_MULTIPLIER = 2++# Cache configuration - prevents unbounded memory growth+MAX_APPRISE_CACHE_SIZE = 1000 # Reasonable limit for notification URL caching+++class NotificationService:+ """+ Low-level notification service that wraps Apprise.+ """++ # Regex patterns for common service types (for validation)+ SERVICE_PATTERNS = {+ "email": r"^mailto://",+ "discord": r"^discord://",+ "slack": r"^slack://",+ "telegram": r"^tgram://",+ "smtp": r"^(smtp|smtps)://",+ }++ 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+ tag: Optional[str] = None,+ attach: Optional[List[str]] = None,+ ) -> bool:+ """+ Send a notification to service URLs with exponential backoff retry.++ Args:+ title: Notification title+ body: Notification body text+ service_urls: Comma-separated list of service URLs to override configured ones+ tag: Optional tag to target specific services+ attach: Optional list of file paths to attach++ Returns:+ True if notification was sent successfully to at least one service++ Raises:+ SendError: If sending fails after all retry attempts+ """+ last_error = None+ retry_delay = INITIAL_RETRY_DELAY++ for attempt in range(1, MAX_RETRY_ATTEMPTS + 1):+ try:+ # If service_urls are provided, use cached Apprise instance+ if 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++ self._apprise_cache[url_hash] = cached_apprise+ else:+ logger.debug(+ f"Using cached Apprise instance "+ f"for URL hash {url_hash}"+ )+ cached_apprise = self._apprise_cache[url_hash]++ logger.debug(+ f"Sending notification (attempt {attempt}/"+ f"{MAX_RETRY_ATTEMPTS}): "+ f"title='{title[:50]}...', tag={tag}"+ )+ logger.debug(f"Body preview: {body[:200]}...")++ # Send notification with the cached instance+ notify_result = cached_apprise.notify(+ title=title,+ body=body,+ tag=tag,+ attach=attach,+ )+ else:+ # Use the configured apprise instance+ if len(self.apprise) == 0:+ logger.debug(+ "No notification services configured in Apprise"+ )+ return False++ logger.debug(+ f"Sending notification (attempt {attempt}/"+ f"{MAX_RETRY_ATTEMPTS}): "+ f"title='{title[:50]}...', tag={tag}"+ )+ logger.debug(f"Body preview: {body[:200]}...")++ # Send notification+ notify_result = self.apprise.notify(+ title=title,+ body=body,+ tag=tag,+ attach=attach,+ )++ if notify_result:+ if attempt > 1:+ logger.info(+ f"Notification sent successfully on attempt "+ f"{attempt}/{MAX_RETRY_ATTEMPTS}: "+ f"'{title[:50]}...'"+ )+ else:+ logger.debug(+ f"Notification sent successfully: '{title[:50]}...'"+ )+ return True+ else:+ error_msg = "Failed to send notification to any service"+ logger.warning(+ f"{error_msg} (attempt {attempt}/{MAX_RETRY_ATTEMPTS})"+ )+ last_error = SendError(error_msg)++ # Retry with exponential backoff if not last attempt+ if attempt < MAX_RETRY_ATTEMPTS:+ logger.debug(+ f"Retrying in {retry_delay}s "+ f"(attempt {attempt + 1}/{MAX_RETRY_ATTEMPTS})"+ )+ time.sleep(retry_delay)+ retry_delay *= RETRY_BACKOFF_MULTIPLIER++ except Exception as e:+ error_msg = f"Error sending notification '{title[:50]}...': {e}"+ logger.exception(+ f"{error_msg} (attempt {attempt}/{MAX_RETRY_ATTEMPTS})"+ )+ last_error = SendError(f"Failed to send notification: {str(e)}")++ # Retry with exponential backoff if not last attempt+ if attempt < MAX_RETRY_ATTEMPTS:+ logger.debug(+ f"Retrying in {retry_delay}s "+ f"(attempt {attempt + 1}/{MAX_RETRY_ATTEMPTS})"+ )+ time.sleep(retry_delay)+ retry_delay *= RETRY_BACKOFF_MULTIPLIER++ # All attempts failed+ logger.error(+ f"Failed to send notification after {MAX_RETRY_ATTEMPTS} "+ f"attempts: '{title[:50]}...'"+ )+ raise last_error++ def send_event(+ self,+ event_type: EventType,+ context: Dict[str, Any],+ service_urls: Optional[str] = None,+ tag: Optional[str] = None,+ custom_template: Optional[Dict[str, str]] = None,+ ) -> bool:+ """+ Send a notification for a specific event type.++ Args:+ event_type: Type of event+ context: Context data for template formatting+ service_urls: Comma-separated list of service URLs+ tag: Optional tag to target specific services+ custom_template: Optional custom template override++ Returns:+ True if notification was sent successfully+ """+ logger.debug(f"send_event: event_type={event_type.value}, tag={tag}")+ logger.debug(f"Context: {context}")++ # Format notification using template+ message = NotificationTemplate.format(+ event_type, context, custom_template+ )+ logger.debug(+ f"Template formatted - title: '{message['title'][:50]}...'"+ )++ # Send notification+ result = self.send(+ title=message["title"],+ body=message["body"],+ service_urls=service_urls,+ tag=tag,+ )+ return result++ def test_service(self, url: str) -> Dict[str, Any]:+ """+ Test a notification service.++ Args:+ url: Apprise-compatible service URL++ Returns:+ Dict with 'success' boolean and optional 'error' message+ """+ try:+ # Create temporary Apprise instance+ temp_apprise = apprise.Apprise()+ add_result = temp_apprise.add(url)++ if not add_result:+ return {+ "success": False,+ "error": "Failed to add service URL",+ }++ # Send test notification+ result = temp_apprise.notify(+ title="Test Notification",+ body=(+ "This is a test notification from Local Deep Research. "+ "If you see this, your service is configured correctly!"+ ),+ )++ if result:+ return {+ "success": True,+ "message": "Test notification sent successfully",+ }+ else:+ return {+ "success": False,+ "error": "Failed to send test notification",+ }++ except Exception as e:+ logger.exception("Error testing notification service")+ return {+ "success": False,+ "error": str(e),+ }++ @staticmethod+ def _validate_url(url: str) -> None:+ """+ Validate a notification service URL.++ Args:+ url: URL to validate++ Raises:+ ServiceError: If URL is invalid++ Note:+ URL scheme validation is handled by Apprise itself, which maintains+ a comprehensive whitelist of supported notification services.+ Apprise will reject unsupported schemes like 'file://' or 'javascript://'.+ See: https://github.com/caronc/apprise/wiki+ """+ if not url or not isinstance(url, str):+ raise ServiceError("URL must be a non-empty string")++ # Check if it looks like a URL+ parsed = urlparse(url)+ if not parsed.scheme:+ raise ServiceError(+ "Invalid URL format. Must be an Apprise-compatible "+ "service URL (e.g., discord://webhook_id/token)"+ )++ @staticmethod+ def _mask_url(url: str) -> str:+ """+ Mask sensitive parts of a URL for logging.++ Args:+ url: URL to mask++ Returns:+ Masked URL with credentials hidden+ """+ try:+ parsed = urlparse(url)++ # Mask password if present+ if parsed.password:+ netloc = parsed.netloc.replace(parsed.password, "***")+ else:+ netloc = parsed.netloc++ # Mask path tokens (common in webhooks)+ path = parsed.path+ if path:+ # Replace long alphanumeric tokens with ***+ path = re.sub(+ r"/[a-zA-Z0-9_-]{20,}",+ "/***",+ path,+ )++ # Reconstruct URL+ masked = f"{parsed.scheme}://{netloc}{path}"+ if parsed.query:+ masked += "?***"++ return masked++ except Exception:+ # If parsing fails, just return generic mask+ return f"{url.split(':')[0]}://***"++ def get_service_type(self, url: str) -> Optional[str]:+ """+ Detect service type from URL.++ Args:+ url: Service URL++ Returns:+ Service type name or None if unknown+ """+ for service_name, pattern in self.SERVICE_PATTERNS.items():+ if re.match(pattern, url, re.IGNORECASE):+ return service_name+ return "unknown"diff --git a/src/local_deep_research/notifications/templates.py b/src/local_deep_research/notifications/templates.pynew file mode 100644index 0000000000..04129b71d5--- /dev/null+++ b/src/local_deep_research/notifications/templates.py@@ -0,0 +1,169 @@+"""+Notification templates for different event types.+"""++from enum import Enum+from typing import Dict, Any, Optional+++class EventType(Enum):+ """Types of events that can trigger notifications."""++ # Research events+ RESEARCH_COMPLETED = "research_completed"+ RESEARCH_FAILED = "research_failed"+ RESEARCH_QUEUED = "research_queued"++ # Subscription events+ SUBSCRIPTION_UPDATE = "subscription_update"+ SUBSCRIPTION_ERROR = "subscription_error"++ # System events+ RATE_LIMIT_WARNING = "rate_limit_warning"+ API_QUOTA_WARNING = "api_quota_warning"+ AUTH_ISSUE = "auth_issue"++ # Test event+ TEST = "test"+++class NotificationTemplate:+ """+ Manages notification message templates.+ """++ # Default templates for each event type+ TEMPLATES: Dict[EventType, Dict[str, str]] = {+ EventType.RESEARCH_COMPLETED: {+ "title": "Research Completed: {query}",+ "body": (+ "Your research on '{query}' has completed successfully.\n\n"+ "Summary: {summary}\n\n"+ "View full results: {url}"+ ),+ },+ EventType.RESEARCH_FAILED: {+ "title": "Research Failed: {query}",+ "body": (+ "Research on '{query}' failed.\n\n"+ "Error: {error}\n\n"+ "Please check the logs for more details."+ ),+ },+ EventType.RESEARCH_QUEUED: {+ "title": "Research Queued: {query}",+ "body": (+ "Your research on '{query}' has been queued.\n\n"+ "Position in queue: {position}\n"+ "Estimated wait time: {wait_time}"+ ),+ },+ EventType.SUBSCRIPTION_UPDATE: {+ "title": "New Updates: {subscription_name}",+ "body": (+ "New content available for '{subscription_name}'.\n\n"+ "{item_count} new items found.\n\n"+ "View updates: {url}"+ ),+ },+ EventType.SUBSCRIPTION_ERROR: {+ "title": "Subscription Error: {subscription_name}",+ "body": (+ "Error updating subscription '{subscription_name}'.\n\n"+ "Error: {error}\n\n"+ "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": (+ "You are approaching API quota limits for {service}.\n\n"+ "Current usage: {current}/{limit}\n"+ "Reset time: {reset_time}"+ ),+ },+ EventType.AUTH_ISSUE: {+ "title": "Authentication Issue",+ "body": (+ "Authentication failed for {service}.\n\n"+ "Please check your credentials and try again."+ ),+ },+ EventType.TEST: {+ "title": "Test Notification",+ "body": (+ "This is a test notification from Local Deep Research.\n\n"+ "If you received this, your notification service "+ "is configured correctly!"+ ),+ },+ }++ @classmethod+ def format(+ cls,+ event_type: EventType,+ context: Dict[str, Any],+ custom_template: Optional[Dict[str, str]] = None,+ ) -> Dict[str, str]:+ """+ Format a notification template with context data.++ Args:+ event_type: Type of event+ context: Context data for template formatting+ custom_template: Optional custom template override++ Returns:+ Dict with 'title' and 'body' keys+ """+ template = custom_template or cls.TEMPLATES.get(event_type)++ if not template:+ return {+ "title": f"Notification: {event_type.value}",+ "body": str(context),+ }++ try:+ title = template["title"].format(**context)+ body = template["body"].format(**context)+ return {"title": title, "body": body}+ except KeyError as e:+ # Missing template variable - return a safe fallback+ return {+ "title": f"Notification: {event_type.value}",+ "body": f"Template error: Missing variable {e}. Context: {context}",+ }++ @classmethod+ def get_required_context(cls, event_type: EventType) -> list[str]:+ """+ Get required context variables for an event type.++ Args:+ event_type: Type of event++ Returns:+ List of required variable names+ """+ template = cls.TEMPLATES.get(event_type)+ if not template:+ return []++ # Extract variables from template strings+ import re++ variables = set()+ for text in [template.get("title", ""), template.get("body", "")]:+ variables.update(re.findall(r"\{(\w+)\}", text))++ return sorted(variables)diff --git a/src/local_deep_research/notifications/url_builder.py b/src/local_deep_research/notifications/url_builder.pynew file mode 100644index 0000000000..9531688d11--- /dev/null+++ b/src/local_deep_research/notifications/url_builder.py@@ -0,0 +1,166 @@+"""+URL builder utility for notification links.+"""++from typing import Optional+from urllib.parse import urlparse+from loguru import logger+++class URLValidationError(ValueError):+ """Raised when URL construction fails validation."""++ pass+++def validate_url(url: str) -> bool:+ """+ Validate that a URL is well-formed and safe.++ Args:+ url: URL to validate++ Returns:+ True if valid++ Raises:+ URLValidationError: If URL is invalid+ """+ if not url or not isinstance(url, str):+ raise URLValidationError("URL must be a non-empty string")++ try:+ parsed = urlparse(url)+ except Exception as e:+ raise URLValidationError(f"Failed to parse URL: {e}")++ # Must have a scheme+ if not parsed.scheme:+ raise URLValidationError("URL must have a scheme (http or https)")++ # Must be http or https+ if parsed.scheme not in ("http", "https"):+ raise URLValidationError(+ f"URL scheme must be http or https, got: {parsed.scheme}"+ )++ # Must have a netloc (hostname)+ if not parsed.netloc:+ raise URLValidationError("URL must have a hostname")++ # Check for obvious issues+ if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):+ raise URLValidationError(f"Invalid hostname: {parsed.netloc}")++ # Path should be valid+ if parsed.path and not parsed.path.startswith("/"):+ raise URLValidationError(f"URL path must start with /: {parsed.path}")++ return True+++def build_notification_url(+ path: str,+ settings_manager=None,+ settings_snapshot: Optional[dict] = None,+ fallback_base: str = "http://localhost:5000",+ validate: bool = True,+) -> str:+ """+ Build a full URL for use in notifications.++ Args:+ path: Relative path (e.g., "/research/123")+ settings_manager: Optional SettingsManager instance to get external_url+ settings_snapshot: Optional settings snapshot dict (alternative to settings_manager)+ fallback_base: Fallback base URL if no setting configured+ validate: Whether to validate the constructed URL (default: True)++ Returns:+ Full URL (e.g., "https://myapp.com/research/123")++ Raises:+ URLValidationError: If validate=True and URL is invalid++ Note:+ You can provide either settings_manager OR settings_snapshot, not both.+ settings_snapshot is preferred for thread-safe background tasks.+ """+ # Ensure path starts with /+ if not path.startswith("/"):+ path = f"/{path}"++ # Try to get external URL from settings+ base_url = None++ # Try settings_snapshot first (preferred for thread-safety)+ if settings_snapshot:+ try:+ base_url = settings_snapshot.get("app.external_url", "")+ # Clean up base_url+ if base_url:+ base_url = base_url.rstrip("/")+ logger.debug(+ f"Using configured external URL from snapshot: {base_url}"+ )+ except Exception as e:+ logger.debug(f"Could not get external_url from snapshot: {e}")++ # Fallback to settings_manager if provided+ elif settings_manager:+ try:+ base_url = settings_manager.get_setting(+ "app.external_url", default=""+ )+ # Clean up base_url+ if base_url:+ base_url = base_url.rstrip("/")+ logger.debug(f"Using configured external URL: {base_url}")+ except Exception as e:+ logger.debug(f"Could not get external_url setting: {e}")++ # Fallback to constructing from app.host and app.port (if settings available)+ if not base_url and (settings_snapshot or settings_manager):+ try:+ if settings_snapshot:+ host = settings_snapshot.get("app.host", "localhost")+ port = settings_snapshot.get("app.port", 5000)+ elif settings_manager:+ host = settings_manager.get_setting(+ "app.host", default="localhost"+ )+ port = settings_manager.get_setting("app.port", default=5000)+ else:+ host = None+ port = None++ if host and port:+ # Convert 0.0.0.0 to localhost for URLs+ if host in ("0.0.0.0", "::"):+ host = "localhost"++ base_url = f"http://{host}:{port}"+ logger.debug(f"Constructed URL from host/port: {base_url}")+ except Exception as e:+ logger.debug(f"Could not construct URL from settings: {e}")++ # Final fallback+ if not base_url:+ base_url = fallback_base+ logger.debug(f"Using fallback URL: {base_url}")++ # Construct full URL+ full_url = f"{base_url}{path}"++ # Validate if requested+ if validate:+ try:+ validate_url(full_url)+ except URLValidationError as e:+ logger.exception(+ f"Constructed invalid URL '{full_url}' from base '{base_url}' "+ f"and path '{path}': {e}"+ )+ raise++ return full_urldiff --git a/src/local_deep_research/notifications/utils.py b/src/local_deep_research/notifications/utils.pynew file mode 100644index 0000000000..99cdc1b6d5--- /dev/null+++ b/src/local_deep_research/notifications/utils.py@@ -0,0 +1,8 @@+"""+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/settings/manager.py b/src/local_deep_research/settings/manager.pyindex 967dfe6d6a..a360614e4b 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -25,13 +25,34 @@ from .env_registry import registry as env_registrydef parse_boolean(value: Any) -> bool:"""- Convert various representations to boolean.+ Convert various representations to boolean using HTML checkbox semantics.This function handles form values, JSON booleans, and environment variables,ensuring consistent behavior across client and server.- HTML checkbox semantics: Any value present (except explicit false) = checked = True.- This matches standard HTML form behavior where checkbox presence indicates checked state.+ **HTML Checkbox Semantics** (INTENTIONAL DESIGN):+ - **Any value present (except explicit false) = checked = True**+ - This matches standard HTML form behavior where checkbox presence indicates checked state+ - In HTML forms, checkboxes send a value when checked, nothing when unchecked++ **Examples**:+ parse_boolean("on") # True - standard HTML checkbox value+ parse_boolean("true") # True - explicit true+ parse_boolean("1") # True - numeric true+ parse_boolean("enabled") # True - any non-empty string+ parse_boolean("disabled") # True - INTENTIONAL: any string = checkbox was checked!+ parse_boolean("custom") # True - custom checkbox value++ parse_boolean("false") # False - explicit false+ parse_boolean("off") # False - explicit false+ parse_boolean("0") # False - explicit false+ parse_boolean("") # False - empty string = unchecked+ parse_boolean(None) # False - missing = unchecked++ **Why "disabled" returns True**:+ This is NOT a bug! If a checkbox sends the value "disabled", it means the checkbox+ was checked (present in form data). The actual string content doesn't matter for+ HTML checkboxes - only presence vs absence matters.Args:value: Value to convert to boolean. Accepts strings, booleans, or None.@@ -39,6 +60,10 @@ def parse_boolean(value: Any) -> bool:Returns:bool: True for truthy values (any non-empty string except explicit false);False for falsy values ('off', 'false', '0', '', 'no', False, None)++ Note:+ This function implements HTML form semantics, NOT generic boolean parsing.+ See tests/settings/test_boolean_parsing.py for comprehensive test coverage."""# Constants for boolean value parsingFALSY_VALUES = ("off", "false", "0", "", "no")@@ -429,7 +454,10 @@ class SettingsManager(ISettingsManager):def get_all_settings(self, bypass_cache: bool = False) -> Dict[str, Any]:"""- Get all settings+ Get all settings, merging defaults with database values.++ This ensures that new settings added to defaults.json automatically+ appear in the UI without requiring a database reset.Args:bypass_cache: If True, bypass the cache and read directly from database@@ -439,7 +467,11 @@ class SettingsManager(ISettingsManager):"""result = {}- # Add database settings if available+ # Start with defaults so new settings are always included+ for key, default_setting in self.default_settings.items():+ result[key] = dict(default_setting)++ # Override with database settings if availabletry:for setting in self.__query_settings():# Handle type field - it might be a string or an enum@@ -447,6 +479,15 @@ class SettingsManager(ISettingsManager):if hasattr(setting_type, "name"):setting_type = setting_type.name+ # Log if this is a custom setting not in defaults+ if setting.key not in self.default_settings:+ logger.debug(+ f"Database contains custom setting not in "+ f"defaults: {setting.key} (type={setting_type}, "+ f"category={setting.category})"+ )++ # Override default with database valueresult[setting.key] = dict(value=setting.value,type=setting_type,diff --git a/src/local_deep_research/web/queue/processor.py b/src/local_deep_research/web/queue/processor.pyindex 2f703f8500..e189db61d0 100644--- a/src/local_deep_research/web/queue/processor.py+++ b/src/local_deep_research/web/queue/processor.py@@ -574,6 +574,43 @@ class QueueProcessor:op_data["status"],)+ # Send failure notification if status is 'failed'+ if op_data["status"] == "failed":+ try:+ from ...notifications import EventType+ from ...notifications.manager import NotificationManager+ from ...settings import SettingsManager++ # Get settings snapshot from database session+ settings_manager = SettingsManager(db_session)+ settings_snapshot = settings_manager.get_settings_snapshot()++ # Create notification manager with settings snapshot+ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Build notification context+ context = {+ "query": research.query or "Unknown query",+ "research_id": research_id,+ "error": op_data.get("error_message", "Unknown error"),+ }++ # Send notification using the manager+ notification_manager.send_notification(+ event_type=EventType.RESEARCH_FAILED,+ context=context,+ user_id=op_data["username"],+ )+ logger.info(+ f"Sent failure notification for research {research_id}"+ )+ except Exception:+ logger.exception(+ f"Failed to send failure notification for {research_id}"+ )+except Exception:logger.exception(f"Error processing error update for research {research_id}"diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex b4cd691fd6..54d10ae781 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -24,6 +24,11 @@ from ..services.research_service import (start_research_process,)+# Retry configuration constants for notification database queries+MAX_RESEARCH_LOOKUP_RETRIES = 3+INITIAL_RESEARCH_LOOKUP_DELAY = 0.5 # seconds+RETRY_BACKOFF_MULTIPLIER = 2+class QueueProcessorV2:"""@@ -270,23 +275,238 @@ class QueueProcessorV2:except Exception:pass- def notify_research_completed(self, username: str, research_id: str):+ def notify_research_completed(+ self, username: str, research_id: str, user_password: str = None+ ):"""Notify that a research completed.Updates the user's queue status in their database.++ Args:+ username: The username+ research_id: The research ID+ user_password: User password for database access. Required for queue+ updates and database lookups during notification sending.+ Optional only because some callers may not have it+ available, in which case only basic updates occur."""try:- with get_user_db_session(username) as session:+ # get_user_db_session is already imported at module level (line 19)+ # It accepts optional password parameter and returns a context manager+ with get_user_db_session(username, user_password) as session:queue_service = UserQueueService(session)queue_service.update_task_status(research_id, "completed")logger.info(f"Research {research_id} completed for user {username}")++ # Send notification if enabled+ self._send_research_notification(+ session=session,+ username=username,+ research_id=research_id,+ event_type="RESEARCH_COMPLETED",+ )+except Exception:logger.exception(f"Failed to update completion status for {username}")+ def notify_research_failed(+ self,+ username: str,+ research_id: str,+ error_message: str = None,+ user_password: str = None,+ ):+ """+ Notify that a research failed.+ Updates the user's queue status in their database and sends notification.++ Args:+ username: The username+ research_id: The research ID+ error_message: Optional error message+ user_password: User password for database access. Required for queue+ updates and database lookups during notification sending.+ Optional only because some callers may not have it+ available, in which case only basic updates occur.+ """+ try:+ # get_user_db_session is already imported at module level (line 19)+ # It accepts optional password parameter and returns a context manager+ with get_user_db_session(username, user_password) as session:+ queue_service = UserQueueService(session)+ queue_service.update_task_status(+ research_id, "failed", error_message=error_message+ )+ logger.info(+ f"Research {research_id} failed for user {username}: "+ f"{error_message}"+ )++ # Send notification if enabled+ self._send_research_notification(+ session=session,+ username=username,+ research_id=research_id,+ event_type="RESEARCH_FAILED",+ error_message=error_message,+ )++ except Exception:+ logger.exception(f"Failed to update failure status for {username}")++ def _send_research_notification(+ self,+ session,+ username: str,+ research_id: str,+ event_type: str,+ error_message: str = None,+ ):+ """+ Helper method to send research notification with settings snapshot.++ Args:+ session: Database session+ username: Username+ research_id: Research ID+ event_type: Event type ("RESEARCH_COMPLETED" or "RESEARCH_FAILED")+ error_message: Optional error message for failed research+ """+ try:+ logger.info(+ f"Starting notification process for research {research_id}, "+ f"user {username}"+ )+ from ...notifications import EventType++ # Get research details for notification+ # No retry logic needed - research should already exist since we're+ # notifying about its completion/failure. If it's not found, something+ # is seriously wrong and retrying won't help.+ research = (+ session.query(ResearchHistory).filter_by(id=research_id).first()+ )++ # Get settings snapshot for thread-safe notification sending+ from ...settings import SettingsManager++ settings_manager = SettingsManager(session)+ settings_snapshot = settings_manager.get_settings_snapshot()++ if research:+ logger.info(+ f"Found research record, creating NotificationManager "+ f"for user {username}"+ )+ # Create notification manager with settings snapshot+ # (no session to avoid thread-safety issues)+ from ...notifications.manager import NotificationManager+ from ...notifications.url_builder import build_notification_url++ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Build context based on event type+ if event_type == "RESEARCH_COMPLETED":+ # Build full URL for notification+ full_url = build_notification_url(+ f"/research/{research_id}",+ settings_manager=settings_manager,+ )++ # Build notification context with required fields+ context = {+ "query": research.query or "Unknown query",+ "research_id": research_id,+ "summary": "No summary available",+ "url": full_url,+ }++ # Get report content for notification+ from ...storage import get_report_storage++ storage = get_report_storage(session=session)+ report_content = storage.get_report(research_id)++ if report_content:+ # Truncate summary if too long+ context["summary"] = (+ report_content[:200] + "..."+ if len(report_content) > 200+ else report_content+ )+ else: # RESEARCH_FAILED+ context = {+ "query": research.query or "Unknown query",+ "research_id": research_id,+ "error": error_message or "Unknown error",+ }++ logger.info(+ f"Sending {event_type} notification for research "+ f"{research_id} to user {username}"+ )+ logger.debug(f"Notification context: {context}")++ # Send notification using the manager+ result = notification_manager.send_notification(+ event_type=EventType[event_type],+ context=context,+ user_id=username,+ )+ logger.info(f"Notification sent, result: {result}")+ logger.info(+ f"Successfully sent {event_type.lower()} notification "+ f"for research {research_id}"+ )+ else:+ logger.warning(+ f"Could not find research {research_id} in database, "+ f"sending notification with minimal details"+ )+ # Create notification manager with settings snapshot+ from ...notifications.manager import NotificationManager++ notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot+ )++ # Build minimal context+ if event_type == "RESEARCH_COMPLETED":+ context = {+ "query": f"Research {research_id}",+ "research_id": research_id,+ "summary": "Research completed but details unavailable",+ "url": f"/research/{research_id}",+ }+ else: # RESEARCH_FAILED+ context = {+ "query": f"Research {research_id}",+ "research_id": research_id,+ "error": error_message or "Unknown error",+ }++ notification_manager.send_notification(+ event_type=EventType[event_type],+ context=context,+ user_id=username,+ )+ logger.info(+ f"Sent {event_type.lower()} notification for research "+ f"{research_id} (minimal details)"+ )++ except Exception:+ logger.exception(+ f"Failed to send {event_type.lower()} notification for "+ f"{research_id}"+ )+def _process_queue_loop(self):"""Main loop that processes the queue."""while self.running:diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 2427cbe265..136e56d4bf 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -657,7 +657,7 @@ def start_research():termination_flags,run_research_process,username=username, # Pass username to the thread- user_password=user_password, # Pass password for metrics database access+ user_password=user_password, # Pass password for database accessmodel_provider=model_provider,model=model,custom_endpoint=custom_endpoint,diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex d066100885..5229250ac6 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -276,16 +276,20 @@ def save_all_settings():# Store original values for better messagingoriginal_values = {}+ # Fetch all settings once to avoid N+1 query problem+ all_db_settings = {+ setting.key: setting+ for setting in db_session.query(Setting).all()+ }+# Update each settingfor key, value in form_data.items():# Skip corrupted keys or empty strings as keysif not key or not isinstance(key, str) or key.strip() == "":continue- # Get the setting metadata- current_setting = (- db_session.query(Setting).filter(Setting.key == key).first()- )+ # Get the setting metadata from pre-fetched dict+ current_setting = all_db_settings.get(key)# EARLY VALIDATION: Convert checkbox values BEFORE any other processing# This prevents incorrect triggering of corrupted value detection@@ -494,9 +498,8 @@ def save_all_settings():if len(updated_settings) == 1:# For a single update, provide more specific info about what changedkey = updated_settings[0]- updated_setting = (- db_session.query(Setting).filter(Setting.key == key).first()- )+ # Reuse the already-fetched setting from our pre-fetched dict+ updated_setting = all_db_settings.get(key)name = (updated_setting.nameif updated_setting@@ -2262,3 +2265,48 @@ def api_get_data_location():except Exception:logger.exception("Error getting data location information")return jsonify({"error": "Failed to retrieve settings"}), 500+++@settings_bp.route("/api/notifications/test-url", methods=["POST"])+@login_required+def api_test_notification_url():+ """+ Test a notification service URL.++ This endpoint creates a temporary NotificationService instance to test+ the provided URL. No database session or password is required because:+ - The service URL is provided directly in the request body+ - Test notifications use a temporary Apprise instance+ - No user settings or database queries are performed++ Security note: Rate limiting is not applied here because users need to+ test URLs when configuring notifications. Abuse is mitigated by the+ @login_required decorator and the fact that users can only spam their+ own notification services.+ """+ try:+ from ...notifications.service import NotificationService++ data = request.get_json()+ if not data or "service_url" not in data:+ return jsonify(+ {"success": False, "error": "service_url is required"}+ ), 400++ service_url = data["service_url"]++ # Create notification service instance and test the URL+ # No password/session needed - URL provided directly, no DB access+ notification_service = NotificationService()+ result = notification_service.test_service(service_url)++ return jsonify(result)++ except Exception as e:+ logger.exception("Error testing notification URL")+ return jsonify(+ {+ "success": False,+ "error": f"Failed to test notification: {str(e)}",+ }+ ), 500diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 6c7245adb8..4fb9df331f 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -337,6 +337,10 @@ def run_research_process(if not username:logger.error("No username provided to research thread")raise ValueError("Username is required for research process")++ # Get user password if provided (needed for notifications)+ user_password = kwargs.get("user_password")+try:# Check if this research has been terminated before we even startif termination_flags.get(research_id):@@ -344,7 +348,11 @@ def run_research_process(f"Research {research_id} was terminated before starting")cleanup_research_resources(- research_id, active_research, termination_flags, username+ research_id,+ active_research,+ termination_flags,+ username,+ user_password,)return@@ -429,9 +437,6 @@ def run_research_process(set_settings_context(settings_context)- # Get user password if provided- user_password = kwargs.get("user_password")-# Create shared research context that can be updated during researchshared_research_context = {"research_id": research_id,@@ -442,7 +447,7 @@ def run_research_process("search_engines_planned": None,"search_engine_selected": search_engine,"username": username, # Add username for queue operations- "user_password": user_password, # Add password for metrics access+ "user_password": user_password, # Add password for database access}# If this is a follow-up research, include the parent context@@ -463,7 +468,11 @@ def run_research_process(# Frequent termination checkif termination_flags.get(research_id):handle_termination(- research_id, active_research, termination_flags, username+ research_id,+ active_research,+ termination_flags,+ username,+ user_password,)raise Exception("Research was terminated by user")@@ -563,7 +572,11 @@ def run_research_process(def check_termination():if termination_flags.get(research_id):handle_termination(- research_id, active_research, termination_flags, username+ research_id,+ active_research,+ termination_flags,+ username,+ user_password,)raise Exception("Research was terminated by user during long-running operation"@@ -1164,7 +1177,10 @@ def run_research_process("Cleaning up resources for research_id: %s", research_id)cleanup_research_resources(- research_id, active_research, termination_flags+ research_id,+ active_research,+ termination_flags,+ username,)logger.info("Resources cleaned up for research_id: %s", research_id@@ -1403,7 +1419,11 @@ def run_research_process(# Clean up resourcescleanup_research_resources(- research_id, active_research, termination_flags, username+ research_id,+ active_research,+ termination_flags,+ username,+ user_password,)except Exception as e:@@ -1645,7 +1665,11 @@ def run_research_process(def cleanup_research_resources(- research_id, active_research, termination_flags, username=None+ research_id,+ active_research,+ termination_flags,+ username=None,+ user_password=None,):"""Clean up resources for a completed research.@@ -1655,6 +1679,7 @@ def cleanup_research_resources(active_research: Dictionary of active research processestermination_flags: Dictionary of termination flagsusername: The username for database access (required for thread context)+ user_password: The user's password for secure database access (for notifications)"""logger.info("Cleaning up resources for research %s", research_id)@@ -1681,37 +1706,37 @@ def cleanup_research_resources(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)+ db_session.query(ResearchHistory)+ .filter(ResearchHistory.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}"- )+ if research:+ current_status = research.statuselse:- logger.warning(- f"No active research record found to clean up for {research_id} / {username}"+ 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")@@ -1723,7 +1748,9 @@ def cleanup_research_resources(from ..queue.processor_v2 import queue_processorif username:- queue_processor.notify_research_completed(username, research_id)+ queue_processor.notify_research_completed(+ username, research_id, user_password=user_password+ )logger.info(f"Notified queue processor of completion for research {research_id} (user: {username})")@@ -1779,7 +1806,11 @@ def cleanup_research_resources(def handle_termination(- research_id, active_research, termination_flags, username=None+ research_id,+ active_research,+ termination_flags,+ username=None,+ user_password=None,):"""Handle the termination of a research process.@@ -1789,6 +1820,7 @@ def handle_termination(active_research: Dictionary of active research processestermination_flags: Dictionary of termination flagsusername: The username for database access (required for thread context)+ user_password: The user's password for secure database access (for notifications)"""logger.info(f"Handling termination for research {research_id}")@@ -1819,7 +1851,7 @@ def handle_termination(# Clean up resources (this already handles things properly)cleanup_research_resources(- research_id, active_research, termination_flags, username+ research_id, active_research, termination_flags, username, user_password)diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex aa5c54d754..444ffcf280 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -91,6 +91,65 @@function setupRefreshButtons() {console.log('Setting up refresh buttons...');+ // Handle test notification button+ let testNotificationBtn = document.getElementById('test-notification-button');++ // If the button doesn't exist, create it dynamically for the notifications service URL field+ if (!testNotificationBtn) {+ const serviceUrlInput = document.getElementById('notifications-service-url') ||+ document.querySelector('input[name="notifications.service_url"], textarea[name="notifications.service_url"]');+ if (serviceUrlInput) {+ // Find the parent container for the setting+ const settingContainer = serviceUrlInput.closest('.ldr-settings-item, .settings-item');+ if (settingContainer) {+ // Check if button container already exists to avoid duplicates+ let buttonContainer = settingContainer.querySelector('.ldr-settings-test-button-container');+ if (!buttonContainer) {+ // Create button container+ buttonContainer = document.createElement('div');+ buttonContainer.className = 'ldr-settings-test-button-container';+ buttonContainer.innerHTML = `+ <input type="button"+ id="test-notification-button"+ class="btn btn-secondary btn-sm"+ value="Test Notification">+ <div id="test-notification-result" class="ldr-test-result" style="display: none;"></div>+ `;++ // Add the button container right after the input field+ serviceUrlInput.parentNode.insertBefore(buttonContainer, serviceUrlInput.nextSibling);++ console.log('Dynamically created test notification button');+ }++ // Now get the button (either newly created or existing)+ testNotificationBtn = document.getElementById('test-notification-button');+ }+ }+ }++ if (testNotificationBtn) {+ console.log('Found and set up test notification button');+ testNotificationBtn.addEventListener('click', function() {+ testNotification();+ });++ // Also enable/disable button based on input value+ const serviceUrlInput = document.getElementById('notifications-service-url') ||+ document.querySelector('input[name="notifications.service_url"], textarea[name="notifications.service_url"]');+ if (serviceUrlInput) {+ const updateButtonState = () => {+ const hasValue = serviceUrlInput.value.trim() !== '';+ testNotificationBtn.disabled = !hasValue;+ };++ serviceUrlInput.addEventListener('input', updateButtonState);+ serviceUrlInput.addEventListener('change', updateButtonState);+ // Initial check+ updateButtonState();+ }+ }+// Handle model refresh buttonconst modelRefreshBtn = document.getElementById('llm.model-refresh');if (modelRefreshBtn) {@@ -1069,6 +1128,7 @@if (category === 'llm_parameters') return 'LLM Parameters';if (category === 'report_parameters') return 'Report Parameters';if (category === 'search_general') return 'Search General';+ if (category === 'notifications') return 'Notifications';if (category === 'search_parameters') return 'Search Parameters';if (category === 'warnings') return 'Warnings';@@ -1747,7 +1807,7 @@}// Define the order for the types in "all" tab- const typeOrder = ['llm', 'search', 'report', 'app'];+ const typeOrder = ['llm', 'search', 'report', 'app', 'notifications'];const prefixTypes = Object.keys(groupedSettings);// Sort prefixes by the defined order for the "all" tab@@ -1834,6 +1894,7 @@setupCustomDropdowns();// Setup provider change listener after renderingsetupProviderChangeListener();+}/**@@ -4408,6 +4469,118 @@});}+ /**+ * Test notification functionality+ */+ function testNotification() {+ const testBtn = document.getElementById('test-notification-button');+ const resultDiv = document.getElementById('test-notification-result');++ if (!testBtn || !resultDiv) {+ console.error('Test notification elements not found');+ return;+ }++ // Get the service URL from the input field - try multiple possible selectors+ let serviceUrl = '';++ // Try the standard ID formats+ const serviceUrlInput = document.getElementById('notifications-service-url');+ if (serviceUrlInput) {+ serviceUrl = serviceUrlInput.value.trim();+ }++ // Try the alt format if still empty+ if (!serviceUrl) {+ const altInput = document.getElementById('notifications.service_url');+ if (altInput) {+ serviceUrl = altInput.value.trim();+ }+ }++ // Try the dynamically generated format (e.g., setting-notifications-service_url) if still empty+ if (!serviceUrl) {+ const dynamicInput = document.getElementById('setting-notifications-service_url');+ if (dynamicInput) {+ serviceUrl = dynamicInput.value.trim();+ }+ }++ // Also try to find by name attribute if still empty+ if (!serviceUrl) {+ const nameInput = document.querySelector('input[name="notifications.service_url"], textarea[name="notifications.service_url"]');+ if (nameInput) {+ serviceUrl = nameInput.value.trim();+ }+ }++ if (!serviceUrl) {+ showTestResult('No notification service URL configured', 'error');+ return;+ }++ // Disable button and show loading state+ testBtn.disabled = true;+ const originalText = testBtn.innerHTML;+ testBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';++ // Make API call to test notification+ fetch('/settings/api/notifications/test-url', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCsrfToken()+ },+ body: JSON.stringify({+ service_url: serviceUrl+ })+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ showTestResult('Test notification sent successfully!', 'success');+ } else {+ showTestResult(`Test failed: ${data.error || 'Unknown error'}`, 'error');+ }+ })+ .catch(error => {+ console.error('Error testing notification:', error);+ showTestResult('Network error while testing notification', 'error');+ })+ .finally(() => {+ // Re-enable button and restore original text+ testBtn.disabled = false;+ testBtn.innerHTML = originalText;+ });+ }++ /**+ * Show test result message+ * @param {string} message - The message to display+ * @param {string} type - The type of message ('success' or 'error')+ */+ function showTestResult(message, type) {+ const resultDiv = document.getElementById('test-notification-result');+ if (!resultDiv) return;++ resultDiv.textContent = message;+ resultDiv.className = `ldr-test-result ldr-test-${type}`;+ resultDiv.style.display = 'block';++ // Auto-hide after 5 seconds+ setTimeout(() => {+ resultDiv.style.display = 'none';+ }, 5000);+ }++ /**+ * Get CSRF token from meta tag+ */+ function getCsrfToken() {+ const token = document.querySelector('meta[name="csrf-token"]');+ return token ? token.getAttribute('content') : '';+ }+/*** Create a refresh button for a dropdown input* @param {string} inputId - The ID of the input to create a refresh button fordiff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.htmlindex 989f577763..56b9b179d2 100644--- a/src/local_deep_research/web/templates/components/settings_form.html+++ b/src/local_deep_research/web/templates/components/settings_form.html@@ -289,6 +289,18 @@{% if setting.description and setting.key != "llm.model" and setting.key != "search.tool" and setting.key != "llm.provider" %}<div class="ldr-input-help">{{ setting.description }}</div>{% endif %}++ {% if setting.key == "notifications.service_url" %}+ <div class="ldr-settings-test-button-container">+ <button type="button"+ id="test-notification-button"+ class="btn btn-secondary btn-sm"+ {% if not setting.value or setting.value.strip() == "" %}disabled{% endif %}>+ <i class="fas fa-paper-plane"></i> Test Notification+ </button>+ <div id="test-notification-result" class="ldr-test-result" style="display: none;"></div>+ </div>+ {% endif %}</div>{% endmacro %}diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.htmlindex cf9ff534e1..cd21510ed1 100644--- a/src/local_deep_research/web/templates/settings_dashboard.html+++ b/src/local_deep_research/web/templates/settings_dashboard.html@@ -55,6 +55,7 @@<div class="ldr-settings-tab" data-tab="search">Search Engines</div><div class="ldr-settings-tab" data-tab="report">Reports</div><div class="ldr-settings-tab" data-tab="app">Application</div>+ <div class="ldr-settings-tab" data-tab="notifications">Notifications</div><div class="ldr-settings-tab" data-tab="domains">Domain Classification</div></div>diff --git a/tests/notifications/__init__.py b/tests/notifications/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.pynew file mode 100644index 0000000000..2eaa48fb33--- /dev/null+++ b/tests/notifications/test_manager.py@@ -0,0 +1,557 @@+"""+Tests for NotificationManager.+"""++import pytest+from unittest.mock import patch+from datetime import datetime, timezone++from local_deep_research.notifications.manager import (+ NotificationManager,+ RateLimiter,+)+from local_deep_research.notifications.templates import EventType+from local_deep_research.notifications.exceptions import RateLimitError+++class TestNotificationManagerInit:+ """Tests for NotificationManager initialization."""++ def test_init_with_settings_snapshot(self, mocker):+ """Test initialization with settings snapshot."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ "notifications.rate_limit_per_hour": 10,+ "notifications.rate_limit_per_day": 50,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ assert manager._settings_snapshot == snapshot++ def test_shared_rate_limiter_singleton(self, mocker):+ """Test that rate limiter is shared across instances."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ snapshot = {+ "notifications.rate_limit_per_hour": 10,+ "notifications.rate_limit_per_day": 50,+ }++ manager1 = NotificationManager(settings_snapshot=snapshot)+ manager2 = NotificationManager(settings_snapshot=snapshot)++ # Both managers should have the same rate limiter instance+ assert manager1._rate_limiter is manager2._rate_limiter+ assert (+ manager1._rate_limiter is NotificationManager._shared_rate_limiter+ )+++class TestGetSetting:+ """Tests for _get_setting method."""++ def test_get_setting_from_snapshot(self, mocker):+ """Test getting setting from snapshot."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ result = manager._get_setting("notifications.service_url")++ assert result == "discord://webhook/token"++ def test_get_setting_returns_default(self, mocker):+ """Test getting setting returns default when not found."""+ snapshot = {}+ manager = NotificationManager(settings_snapshot=snapshot)++ result = manager._get_setting(+ "notifications.nonexistent", default="default_value"+ )++ assert result == "default_value"+++class TestSendNotification:+ """Tests for send_notification method."""++ def test_send_notification_success(self, mocker):+ """Test successful notification sending."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ # Mock service.send_event+ manager.service.send_event = mocker.MagicMock(return_value=True)++ # Mock rate limiter+ manager._rate_limiter.allow = mocker.MagicMock(return_value=True)++ context = {+ "query": "Test query",+ "research_id": "123",+ }++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ user_id="test_user",+ )++ assert result is True+ manager._rate_limiter.allow.assert_called_once_with("test_user")+ manager.service.send_event.assert_called_once()++ def test_send_notification_disabled_by_setting(self, mocker):+ """Test notification not sent when disabled by setting."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": False, # Disabled+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock()++ context = {"query": "Test"}++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ )++ assert result is False+ manager.service.send_event.assert_not_called()++ def test_send_notification_no_service_url(self, mocker):+ """Test notification not sent when service URL missing."""+ snapshot = {+ "notifications.service_url": "", # Empty+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock()++ context = {"query": "Test"}++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ )++ assert result is False+ manager.service.send_event.assert_not_called()++ def test_send_notification_respects_rate_limit(self, mocker):+ """Test notification respects rate limiting."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock()++ # Mock rate limiter to deny+ manager._rate_limiter.allow = mocker.MagicMock(return_value=False)++ context = {"query": "Test"}++ with pytest.raises(RateLimitError, match="rate limit exceeded"):+ manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ user_id="test_user",+ )++ manager.service.send_event.assert_not_called()++ def test_send_notification_force_bypasses_rate_limit(self, mocker):+ """Test force=True bypasses rate limiting."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock(return_value=True)++ # Mock rate limiter to deny, but force should bypass+ manager._rate_limiter.allow = mocker.MagicMock(return_value=False)++ context = {"query": "Test"}++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ user_id="test_user",+ force=True, # Bypass rate limit+ )++ assert result is True+ # Rate limiter should still be checked but result ignored+ manager._rate_limiter.allow.assert_called_once()+ manager.service.send_event.assert_called_once()++ def test_send_notification_force_bypasses_disabled_setting(self, mocker):+ """Test force=True bypasses disabled setting."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": False, # Disabled+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock(return_value=True)+ manager._rate_limiter.allow = mocker.MagicMock(return_value=True)++ context = {"query": "Test"}++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ force=True,+ )++ assert result is True+ manager.service.send_event.assert_called_once()++ def test_send_notification_handles_service_failure(self, mocker):+ """Test graceful handling of service failures."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ # Mock service to fail+ manager.service.send_event = mocker.MagicMock(return_value=False)+ manager._rate_limiter.allow = mocker.MagicMock(return_value=True)++ context = {"query": "Test"}++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ )++ assert result is False++ def test_send_notification_handles_exception(self, mocker):+ """Test graceful handling of exceptions."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ # Mock service to raise exception+ manager.service.send_event = mocker.MagicMock(+ side_effect=Exception("Service error")+ )+ manager._rate_limiter.allow = mocker.MagicMock(return_value=True)++ context = {"query": "Test"}++ # Should not raise, returns False+ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ )++ assert result is False+++class TestShouldNotify:+ """Tests for _should_notify method."""++ def test_should_notify_enabled(self, mocker):+ """Test notification enabled by default."""+ snapshot = {+ "notifications.on_research_completed": True,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ result = manager._should_notify(+ EventType.RESEARCH_COMPLETED, user_id="test_user"+ )++ assert result is True++ def test_should_notify_disabled(self, mocker):+ """Test notification disabled by setting."""+ snapshot = {+ "notifications.on_research_completed": False,+ }++ manager = NotificationManager(settings_snapshot=snapshot)++ result = manager._should_notify(+ EventType.RESEARCH_COMPLETED, user_id="test_user"+ )++ assert result is False++ def test_should_notify_default_true(self, mocker):+ """Test notification defaults to True when setting missing."""+ snapshot = {}+ manager = NotificationManager(settings_snapshot=snapshot)++ result = manager._should_notify(+ EventType.RESEARCH_COMPLETED, user_id="test_user"+ )++ # Default is True for missing settings+ assert result is True+++class TestTestService:+ """Tests for test_service method."""++ def test_test_service_success(self, mocker):+ """Test successful service test."""+ snapshot = {}+ manager = NotificationManager(settings_snapshot=snapshot)++ manager.service.test_service = mocker.MagicMock(+ return_value={"success": True}+ )++ result = manager.test_service("discord://webhook/token")++ assert result == {"success": True}+ manager.service.test_service.assert_called_once_with(+ "discord://webhook/token"+ )++ def test_test_service_failure(self, mocker):+ """Test failed service test."""+ snapshot = {}+ manager = NotificationManager(settings_snapshot=snapshot)++ manager.service.test_service = mocker.MagicMock(+ return_value={"success": False, "error": "Connection failed"}+ )++ result = manager.test_service("invalid://url")++ assert result["success"] is False+ assert "error" in result+++class TestRateLimiter:+ """Tests for RateLimiter class."""++ def test_allow_first_notification(self):+ """Test first notification is always allowed."""+ limiter = RateLimiter(max_per_hour=10, max_per_day=50)++ result = limiter.allow("user1")++ assert result is True++ def test_allow_within_hourly_limit(self):+ """Test notifications allowed within hourly limit."""+ limiter = RateLimiter(max_per_hour=3, max_per_day=10)++ # Send 3 notifications (at limit)+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True++ # 4th should be denied+ assert limiter.allow("user1") is False++ def test_allow_within_daily_limit(self):+ """Test notifications allowed within daily limit."""+ limiter = RateLimiter(max_per_hour=100, max_per_day=3)++ # Send 3 notifications (at limit)+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True++ # 4th should be denied+ assert limiter.allow("user1") is False++ def test_allow_separate_users(self):+ """Test rate limits are per-user."""+ limiter = RateLimiter(max_per_hour=2, max_per_day=10)++ # User 1 hits limit+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is False++ # User 2 should still be allowed+ assert limiter.allow("user2") is True+ assert limiter.allow("user2") is True++ def test_reset_single_user(self):+ """Test resetting rate limit for single user."""+ limiter = RateLimiter(max_per_hour=2, max_per_day=10)++ # Hit limit+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is True+ assert limiter.allow("user1") is False++ # Reset user1+ limiter.reset("user1")++ # Should be allowed again+ assert limiter.allow("user1") is True++ def test_reset_all_users(self):+ """Test resetting rate limit for all users."""+ limiter = RateLimiter(max_per_hour=2, max_per_day=10)++ # Multiple users hit limits+ limiter.allow("user1")+ limiter.allow("user1")+ limiter.allow("user2")+ limiter.allow("user2")++ # Reset all+ limiter.reset()++ # Both should be allowed again+ assert limiter.allow("user1") is True+ assert limiter.allow("user2") is True++ def test_cleanup_inactive_users(self, mocker):+ """Test periodic cleanup of inactive users."""+ limiter = RateLimiter(+ max_per_hour=10, max_per_day=50, cleanup_interval_hours=1+ )++ # Add some activity+ limiter.allow("user1")++ # Mock datetime to simulate time passing (8 days)+ from datetime import timedelta++ fake_now = datetime.now(timezone.utc) + timedelta(days=8)++ with patch(+ "local_deep_research.notifications.manager.datetime"+ ) as mock_dt:+ mock_dt.now.return_value = fake_now++ # Trigger cleanup by calling allow+ limiter._cleanup_inactive_users_if_needed(fake_now)++ # User1 should be cleaned up+ assert "user1" not in limiter._hourly_counts+ assert "user1" not in limiter._daily_counts++ def test_thread_safety(self, mocker):+ """Test rate limiter is thread-safe."""+ import threading++ limiter = RateLimiter(max_per_hour=100, max_per_day=1000)+ results = []++ def send_notifications():+ for _ in range(10):+ results.append(limiter.allow("user1"))++ # Create 5 threads sending notifications concurrently+ threads = [+ threading.Thread(target=send_notifications) for _ in range(5)+ ]++ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ # All should be allowed (50 total, well under limit)+ assert all(results)+ assert len(results) == 50+++class TestIntegration:+ """Integration tests for NotificationManager."""++ def test_full_notification_workflow(self, mocker):+ """Test complete notification workflow with settings snapshot."""+ # Simulate background thread scenario+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ "notifications.rate_limit_per_hour": 10,+ "notifications.rate_limit_per_day": 50,+ }++ # Create manager with snapshot (no session - thread-safe)+ manager = NotificationManager(settings_snapshot=snapshot)++ # Mock service+ manager.service.send_event = mocker.MagicMock(return_value=True)++ # Send notification+ context = {+ "query": "What is quantum computing?",+ "research_id": "123-abc",+ "summary": "Quantum computing uses quantum mechanics...",+ }++ result = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ user_id="test_user",+ )++ assert result is True++ # Verify service was called with correct params+ call_args = manager.service.send_event.call_args+ assert call_args[0][0] == EventType.RESEARCH_COMPLETED+ assert call_args[0][1] == context+ assert call_args[1]["service_urls"] == "discord://webhook/token"++ def test_multiple_event_types(self, mocker):+ """Test sending different event types."""+ snapshot = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ "notifications.on_research_failed": True,+ "notifications.on_subscription_update": False, # Disabled+ }++ manager = NotificationManager(settings_snapshot=snapshot)+ manager.service.send_event = mocker.MagicMock(return_value=True)++ # Research completed - should send+ result1 = manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context={"query": "Test"},+ force=True,+ )+ assert result1 is True++ # Research failed - should send+ result2 = manager.send_notification(+ event_type=EventType.RESEARCH_FAILED,+ context={"query": "Test", "error": "Failed"},+ force=True,+ )+ assert result2 is True++ # Subscription update - should not send (disabled)+ result3 = manager.send_notification(+ event_type=EventType.SUBSCRIPTION_UPDATE,+ context={"subscription_name": "Test"},+ )+ assert result3 is Falsediff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.pynew file mode 100644index 0000000000..bc2e1f6d4f--- /dev/null+++ b/tests/notifications/test_service.py@@ -0,0 +1,640 @@+"""+Tests for NotificationService.+"""++import pytest+from unittest.mock import patch, MagicMock, call++from local_deep_research.notifications.service import (+ NotificationService,+ MAX_RETRY_ATTEMPTS,+ INITIAL_RETRY_DELAY,+ RETRY_BACKOFF_MULTIPLIER,+)+from local_deep_research.notifications.templates import EventType+from local_deep_research.notifications.exceptions import SendError, ServiceError+++class TestNotificationServiceInit:+ """Tests for NotificationService initialization."""++ def test_init_creates_apprise_instance(self):+ """Test initialization creates Apprise instance."""+ service = NotificationService()++ assert service.apprise is not None+ assert service._apprise_cache == {}+++class TestSend:+ """Tests for send method."""++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_success_first_attempt(self, mock_apprise_class, mocker):+ """Test successful notification on first attempt."""+ # Setup mock+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.send(+ title="Test Title",+ body="Test Body",+ service_urls="discord://webhook/token",+ )++ assert result is True+ # Verify notify was called once+ assert mock_apprise_instance.notify.call_count == 1++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_caches_apprise_instances(self, mock_apprise_class, mocker):+ """Test Apprise instances are cached by URL hash."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_instance.add.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ # Send first notification+ service.send(+ title="Test 1",+ body="Body 1",+ service_urls="discord://webhook/token",+ )++ # Send second notification with same URL+ service.send(+ title="Test 2",+ body="Body 2",+ service_urls="discord://webhook/token",+ )++ # Should only create one cached instance+ assert len(service._apprise_cache) == 1++ # Send notification with different URL+ service.send(+ title="Test 3",+ body="Body 3",+ service_urls="slack://token/channel",+ )++ # Should now have two cached instances+ assert len(service._apprise_cache) == 2++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ @patch("local_deep_research.notifications.service.time.sleep")+ def test_send_retries_on_failure(+ self, mock_sleep, mock_apprise_class, mocker+ ):+ """Test exponential backoff retry on failure."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ # Fail twice, succeed on third attempt+ mock_apprise_instance.notify.side_effect = [False, False, True]+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ )++ assert result is True+ # Should have tried 3 times+ assert mock_apprise_instance.notify.call_count == 3++ # Verify exponential backoff sleep calls+ expected_sleeps = [+ call(INITIAL_RETRY_DELAY), # 0.5s after 1st failure+ call(+ INITIAL_RETRY_DELAY * RETRY_BACKOFF_MULTIPLIER+ ), # 1.0s after 2nd+ ]+ mock_sleep.assert_has_calls(expected_sleeps)++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ @patch("local_deep_research.notifications.service.time.sleep")+ def test_send_raises_after_max_retries(+ self, mock_sleep, mock_apprise_class, mocker+ ):+ """Test exception raised after max retry attempts."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ # Always fail+ mock_apprise_instance.notify.return_value = False+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ with pytest.raises(SendError, match="Failed to send notification"):+ service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ )++ # Should have tried MAX_RETRY_ATTEMPTS times+ assert mock_apprise_instance.notify.call_count == MAX_RETRY_ATTEMPTS++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ @patch("local_deep_research.notifications.service.time.sleep")+ def test_send_handles_exception_with_retry(+ self, mock_sleep, mock_apprise_class, mocker+ ):+ """Test exception handling with retry logic."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ # Raise exception twice, succeed on third attempt+ mock_apprise_instance.notify.side_effect = [+ Exception("Network error"),+ Exception("Network error"),+ True,+ ]+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ )++ assert result is True+ assert mock_apprise_instance.notify.call_count == 3++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_with_no_service_urls(self, mock_apprise_class, mocker):+ """Test send returns False when configured instance empty."""+ service = NotificationService()+ # Don't provide service_urls, use configured instance++ result = service.send(+ title="Test",+ body="Body",+ # No service_urls parameter+ )++ assert result is False++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_with_tag(self, mock_apprise_class, mocker):+ """Test send with tag parameter."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_instance.add.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ tag="urgent",+ )++ # Verify tag was passed to notify+ call_kwargs = mock_apprise_instance.notify.call_args[1]+ assert call_kwargs["tag"] == "urgent"++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_with_attachments(self, mock_apprise_class, mocker):+ """Test send with file attachments."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_instance.add.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ attachments = ["/path/to/file.pdf"]+ service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ attach=attachments,+ )++ # Verify attachments were passed+ call_kwargs = mock_apprise_instance.notify.call_args[1]+ assert call_kwargs["attach"] == attachments++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_fails_when_add_fails(self, mock_apprise_class, mocker):+ """Test send returns False when adding service URL fails."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = False # Add fails+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.send(+ title="Test",+ body="Body",+ service_urls="invalid://url",+ )++ assert result is False+ # Should not attempt to notify+ mock_apprise_instance.notify.assert_not_called()+++class TestSendEvent:+ """Tests for send_event method."""++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_event_formats_template(self, mock_apprise_class, mocker):+ """Test send_event formats message using template."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_instance.add.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ # Include all required template variables+ context = {+ "query": "What is quantum computing?",+ "research_id": "123",+ "summary": "Brief summary",+ "url": "http://localhost:5000/research/123",+ }++ result = service.send_event(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ service_urls="discord://webhook/token",+ )++ assert result is True++ # Verify notify was called with formatted message+ call_kwargs = mock_apprise_instance.notify.call_args[1]+ assert "title" in call_kwargs+ assert "body" in call_kwargs+ # Title should contain the query (from template: "Research Completed: {query}")+ assert "quantum computing" in call_kwargs["title"].lower()+ assert "research completed" in call_kwargs["title"].lower()++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_send_event_custom_template(self, mock_apprise_class, mocker):+ """Test send_event with custom template override."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.notify.return_value = True+ mock_apprise_instance.add.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ context = {"query": "Test"}+ custom_template = {"title": "Custom: {query}", "body": "Custom body"}++ service.send_event(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ service_urls="discord://webhook/token",+ custom_template=custom_template,+ )++ # Verify custom template was used+ call_kwargs = mock_apprise_instance.notify.call_args[1]+ assert call_kwargs["title"] == "Custom: Test"+ assert call_kwargs["body"] == "Custom body"+++class TestTestService:+ """Tests for test_service method."""++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_test_service_success(self, mock_apprise_class):+ """Test successful service test."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ mock_apprise_instance.notify.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.test_service("discord://webhook/token")++ assert result["success"] is True+ assert "message" in result+ # Verify test notification was sent+ mock_apprise_instance.notify.assert_called_once()++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_test_service_add_fails(self, mock_apprise_class):+ """Test service test when add fails."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = False # Add fails+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.test_service("invalid://url")++ assert result["success"] is False+ assert "error" in result+ assert "Failed to add service URL" in result["error"]++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_test_service_notify_fails(self, mock_apprise_class):+ """Test service test when notify fails."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ mock_apprise_instance.notify.return_value = False # Notify fails+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ result = service.test_service("discord://webhook/token")++ assert result["success"] is False+ assert "error" in result+ assert "Failed to send test notification" in result["error"]++ def test_test_service_exception(self):+ """Test service test handles exceptions."""+ service = NotificationService()++ # Mock the internal apprise.Apprise to raise exception+ with patch(+ "local_deep_research.notifications.service.apprise.Apprise"+ ) as mock_apprise:+ mock_instance = MagicMock()+ mock_instance.add.side_effect = Exception("Network error")+ mock_apprise.return_value = mock_instance++ result = service.test_service("discord://webhook/token")++ assert result["success"] is False+ assert "error" in result+ # Exception should be caught and returned in error field+ assert len(result["error"]) > 0+++class TestValidateURL:+ """Tests for _validate_url method."""++ def test_validate_url_valid(self):+ """Test validation passes for valid URLs."""+ service = NotificationService()++ # Should not raise+ service._validate_url("discord://webhook/token")+ service._validate_url("slack://token/channel")+ service._validate_url("mailto://[email protected]")++ def test_validate_url_empty(self):+ """Test validation fails for empty URL."""+ service = NotificationService()++ with pytest.raises(ServiceError, match="non-empty string"):+ service._validate_url("")++ def test_validate_url_none(self):+ """Test validation fails for None."""+ service = NotificationService()++ with pytest.raises(ServiceError, match="non-empty string"):+ service._validate_url(None)++ def test_validate_url_no_scheme(self):+ """Test validation fails for URL without scheme."""+ service = NotificationService()++ with pytest.raises(ServiceError, match="Invalid URL format"):+ service._validate_url("webhook/token")+++class TestMaskURL:+ """Tests for _mask_url method."""++ def test_mask_url_with_password(self):+ """Test URL masking hides passwords."""+ service = NotificationService()++ masked = service._mask_url("smtp://user:[email protected]")++ assert "secret123" not in masked+ assert "***" in masked+ assert "smtp://" in masked++ def test_mask_url_with_webhook_token(self):+ """Test URL masking hides long webhook tokens."""+ service = NotificationService()++ masked = service._mask_url(+ "discord://webhook_id/very_long_webhook_token_12345678901234567890"+ )++ assert "very_long_webhook_token" not in masked+ assert "***" in masked+ assert "discord://" in masked++ def test_mask_url_with_query_params(self):+ """Test URL masking hides query parameters."""+ service = NotificationService()++ masked = service._mask_url(+ "https://api.example.com/notify?token=secret&key=value"+ )++ assert "secret" not in masked+ assert "value" not in masked+ assert "?***" in masked++ def test_mask_url_simple(self):+ """Test URL masking for simple URLs."""+ service = NotificationService()++ # Use a long token (20+ chars) to trigger masking+ masked = service._mask_url(+ "discord://webhook_id/very_long_token_12345678901234567890"+ )++ # Should still be readable but long tokens masked+ assert "discord://" in masked+ assert "***" in masked+ assert "very_long_token" not in masked++ def test_mask_url_handles_invalid(self):+ """Test URL masking handles invalid URLs gracefully."""+ service = NotificationService()++ # Test with URL that has no ':' - will cause exception in urlparse+ # The fallback is: url.split(':')[0] + '://***'+ # For a string with no ':', split(':')[0] returns the whole string+ masked = service._mask_url("invalid_url_no_colon")++ # Should contain the fallback pattern+ assert "://" in masked+++class TestGetServiceType:+ """Tests for get_service_type method."""++ def test_get_service_type_discord(self):+ """Test detecting Discord service."""+ service = NotificationService()++ service_type = service.get_service_type("discord://webhook/token")++ assert service_type == "discord"++ def test_get_service_type_slack(self):+ """Test detecting Slack service."""+ service = NotificationService()++ service_type = service.get_service_type("slack://token/channel")++ assert service_type == "slack"++ def test_get_service_type_email(self):+ """Test detecting email service."""+ service = NotificationService()++ service_type = service.get_service_type("mailto://[email protected]")++ assert service_type == "email"++ def test_get_service_type_smtp(self):+ """Test detecting SMTP service."""+ service = NotificationService()++ service_type = service.get_service_type(+ "smtp://user:[email protected]"+ )++ assert service_type == "smtp"++ def test_get_service_type_telegram(self):+ """Test detecting Telegram service."""+ service = NotificationService()++ service_type = service.get_service_type("tgram://bot_token/chat_id")++ assert service_type == "telegram"++ def test_get_service_type_unknown(self):+ """Test unknown service type."""+ service = NotificationService()++ service_type = service.get_service_type("unknown://service")++ assert service_type == "unknown"+++class TestRetryConfiguration:+ """Tests for retry configuration constants."""++ def test_retry_constants_are_defined(self):+ """Test retry constants have expected values."""+ assert MAX_RETRY_ATTEMPTS == 3+ assert INITIAL_RETRY_DELAY == 0.5+ assert RETRY_BACKOFF_MULTIPLIER == 2++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ @patch("local_deep_research.notifications.service.time.sleep")+ def test_exponential_backoff_timing(self, mock_sleep, mock_apprise_class):+ """Test exponential backoff uses correct timing."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ mock_apprise_instance.notify.return_value = False # Always fail+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ try:+ service.send(+ title="Test",+ body="Body",+ service_urls="discord://webhook/token",+ )+ except SendError:+ pass # Expected++ # Verify sleep was called with exponentially increasing delays+ sleep_calls = [+ call_args[0][0] for call_args in mock_sleep.call_args_list+ ]++ expected_delays = [+ INITIAL_RETRY_DELAY, # 0.5s+ INITIAL_RETRY_DELAY * RETRY_BACKOFF_MULTIPLIER, # 1.0s+ ]++ assert sleep_calls == expected_delays+++class TestIntegration:+ """Integration tests for NotificationService."""++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_complete_notification_flow(self, mock_apprise_class):+ """Test complete notification flow from event to send."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ mock_apprise_instance.notify.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ # Test multiple notification types+ events = [+ (+ EventType.RESEARCH_COMPLETED,+ {+ "query": "Test query",+ "research_id": "123",+ "summary": "Test summary",+ },+ ),+ (+ EventType.RESEARCH_FAILED,+ {"query": "Failed query", "error": "Test error"},+ ),+ ]++ for event_type, context in events:+ result = service.send_event(+ event_type=event_type,+ context=context,+ service_urls="discord://webhook/token",+ )+ assert result is True++ @patch("local_deep_research.notifications.service.apprise.Apprise")+ def test_multiple_service_urls(self, mock_apprise_class):+ """Test sending to multiple service URLs."""+ mock_apprise_instance = MagicMock()+ mock_apprise_instance.add.return_value = True+ mock_apprise_instance.notify.return_value = True+ mock_apprise_class.return_value = mock_apprise_instance++ service = NotificationService()++ # Comma-separated URLs+ multiple_urls = (+ "discord://webhook1/token1,"+ "slack://token2/channel2,"+ "mailto://[email protected]"+ )++ result = service.send(+ title="Test",+ body="Body",+ service_urls=multiple_urls,+ )++ assert result is True+ # Verify add was called with all URLs+ mock_apprise_instance.add.assert_called()diff --git a/tests/notifications/test_url_builder.py b/tests/notifications/test_url_builder.pynew file mode 100644index 0000000000..1d7d56cfcf--- /dev/null+++ b/tests/notifications/test_url_builder.py@@ -0,0 +1,280 @@+"""+Tests for notification URL builder.+"""++import pytest+from unittest.mock import Mock++from local_deep_research.notifications.url_builder import (+ build_notification_url,+ validate_url,+ URLValidationError,+)+++class TestValidateURL:+ """Tests for URL validation function."""++ def test_valid_http_url(self):+ """Test validation accepts valid HTTP URLs."""+ assert validate_url("http://localhost:5000/path")+ assert validate_url("http://example.com/research/123")+ assert validate_url("http://192.168.1.100:8080/test")++ def test_valid_https_url(self):+ """Test validation accepts valid HTTPS URLs."""+ assert validate_url("https://example.com/path")+ assert validate_url("https://ldr.example.com:8443/research")+ assert validate_url("https://sub.domain.example.com/test")++ def test_empty_url(self):+ """Test validation rejects empty URLs."""+ with pytest.raises(URLValidationError, match="non-empty string"):+ validate_url("")++ def test_none_url(self):+ """Test validation rejects None."""+ with pytest.raises(URLValidationError, match="non-empty string"):+ validate_url(None)++ def test_invalid_type(self):+ """Test validation rejects non-string types."""+ with pytest.raises(URLValidationError, match="non-empty string"):+ validate_url(123)++ def test_missing_scheme(self):+ """Test validation rejects URLs without scheme."""+ with pytest.raises(URLValidationError, match="must have a scheme"):+ validate_url("example.com/path")++ def test_invalid_scheme(self):+ """Test validation rejects non-http(s) schemes."""+ with pytest.raises(URLValidationError, match="must be http or https"):+ validate_url("ftp://example.com/path")++ with pytest.raises(URLValidationError, match="must be http or https"):+ validate_url("javascript://alert(1)")++ with pytest.raises(URLValidationError, match="must be http or https"):+ validate_url("file:///etc/passwd")++ def test_missing_hostname(self):+ """Test validation rejects URLs without hostname."""+ with pytest.raises(URLValidationError, match="must have a hostname"):+ validate_url("http:///path")++ def test_invalid_hostname(self):+ """Test validation rejects malformed hostnames."""+ with pytest.raises(URLValidationError, match="Invalid hostname"):+ validate_url("http://.example.com/path")++ with pytest.raises(URLValidationError, match="Invalid hostname"):+ validate_url("http://example.com./path")++ def test_url_with_port(self):+ """Test validation accepts URLs with ports."""+ assert validate_url("http://localhost:5000/path")+ assert validate_url("https://example.com:8443/path")++ def test_url_with_query_params(self):+ """Test validation accepts URLs with query parameters."""+ assert validate_url("http://example.com/path?param=value")+ assert validate_url("https://example.com/research?id=123&user=test")++ def test_url_with_fragment(self):+ """Test validation accepts URLs with fragments."""+ assert validate_url("http://example.com/path#section")+ assert validate_url("https://example.com/research/123#results")+++class TestBuildNotificationURL:+ """Tests for build_notification_url function."""++ def test_build_with_fallback_only(self):+ """Test URL construction with fallback only."""+ url = build_notification_url("/research/123")+ assert url == "http://localhost:5000/research/123"++ def test_build_with_custom_fallback(self):+ """Test URL construction with custom fallback."""+ url = build_notification_url(+ "/research/123", fallback_base="https://example.com"+ )+ assert url == "https://example.com/research/123"++ def test_build_with_external_url_setting(self):+ """Test URL construction with external_url setting."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "https://ldr.example.com"++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "https://ldr.example.com/research/123"+ mock_settings.get_setting.assert_called_with(+ "app.external_url", default=""+ )++ def test_build_with_external_url_trailing_slash(self):+ """Test URL construction strips trailing slash from base."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "https://ldr.example.com/"++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "https://ldr.example.com/research/123"++ def test_build_with_host_port_fallback(self):+ """Test URL construction from app.host and app.port."""+ mock_settings = Mock()+ # external_url is empty, should fall back to host/port+ mock_settings.get_setting.side_effect = lambda key, default=None: {+ "app.external_url": "",+ "app.host": "192.168.1.100",+ "app.port": 8080,+ }.get(key, default)++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "http://192.168.1.100:8080/research/123"++ def test_build_converts_bind_all_to_localhost(self):+ """Test 0.0.0.0 is converted to localhost in URLs."""+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default=None: {+ "app.external_url": "",+ "app.host": "0.0.0.0",+ "app.port": 5000,+ }.get(key, default)++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "http://localhost:5000/research/123"++ def test_build_converts_ipv6_bind_all_to_localhost(self):+ """Test :: is converted to localhost in URLs."""+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default=None: {+ "app.external_url": "",+ "app.host": "::",+ "app.port": 5000,+ }.get(key, default)++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "http://localhost:5000/research/123"++ def test_build_adds_leading_slash_to_path(self):+ """Test path without leading slash gets one added."""+ url = build_notification_url("research/123")+ assert url == "http://localhost:5000/research/123"++ def test_build_with_complex_path(self):+ """Test URL construction with complex paths."""+ url = build_notification_url(+ "/research/123/results?format=json#section"+ )+ assert (+ url+ == "http://localhost:5000/research/123/results?format=json#section"+ )++ def test_build_validation_enabled_by_default(self):+ """Test validation is enabled by default."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "not-a-valid-url"++ with pytest.raises(URLValidationError):+ build_notification_url("/path", settings_manager=mock_settings)++ def test_build_validation_can_be_disabled(self):+ """Test validation can be disabled."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "not-a-valid-url"++ # Should not raise when validation disabled+ url = build_notification_url(+ "/path", settings_manager=mock_settings, validate=False+ )+ assert url == "not-a-valid-url/path"++ def test_build_handles_settings_exception(self):+ """Test graceful handling of settings errors."""+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = Exception("Database error")++ # Should fall back to default+ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )+ assert url == "http://localhost:5000/research/123"++ def test_build_with_port_in_external_url(self):+ """Test external_url with port number."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "https://ldr.example.com:8443"++ url = build_notification_url(+ "/research/123", settings_manager=mock_settings+ )++ assert url == "https://ldr.example.com:8443/research/123"++ def test_build_invalid_url_raises_error(self):+ """Test that invalid URL construction raises URLValidationError."""+ mock_settings = Mock()+ # This will create an invalid URL (no scheme)+ mock_settings.get_setting.return_value = "example.com"++ with pytest.raises(+ URLValidationError,+ match="Constructed invalid URL|must have a scheme",+ ):+ build_notification_url("/path", settings_manager=mock_settings)+++class TestIntegration:+ """Integration tests for URL builder."""++ def test_realistic_local_development_scenario(self):+ """Test typical local development setup."""+ url = build_notification_url("/research/abc123")+ assert url == "http://localhost:5000/research/abc123"+ assert validate_url(url)++ def test_realistic_production_scenario(self):+ """Test typical production setup with external URL."""+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "https://ldr.company.com"++ url = build_notification_url(+ "/research/abc123", settings_manager=mock_settings+ )++ assert url == "https://ldr.company.com/research/abc123"+ assert validate_url(url)++ def test_realistic_custom_port_scenario(self):+ """Test setup with custom port."""+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default=None: {+ "app.external_url": "",+ "app.host": "server.local",+ "app.port": 8080,+ }.get(key, default)++ url = build_notification_url(+ "/research/abc123", settings_manager=mock_settings+ )++ assert url == "http://server.local:8080/research/abc123"+ assert validate_url(url)diff --git a/tests/settings/test_boolean_parsing.py b/tests/settings/test_boolean_parsing.pynew file mode 100644index 0000000000..10df4a1aac--- /dev/null+++ b/tests/settings/test_boolean_parsing.py@@ -0,0 +1,304 @@+"""+Tests for boolean parsing in settings manager.++This module tests the parse_boolean() function which handles HTML checkbox+semantics and various boolean representations from forms, JSON, and environment+variables.+"""++import pytest++from src.local_deep_research.settings.manager import parse_boolean+++class TestParseBooleanBasicTypes:+ """Test parse_boolean with basic Python types."""++ def test_boolean_true(self):+ """Test that True remains True."""+ assert parse_boolean(True) is True++ def test_boolean_false(self):+ """Test that False remains False."""+ assert parse_boolean(False) is False++ def test_none_is_false(self):+ """Test that None converts to False."""+ assert parse_boolean(None) is False+++class TestParseBooleanStringValues:+ """Test parse_boolean with string representations."""++ @pytest.mark.parametrize(+ "value",+ [+ "true",+ "True",+ "TRUE",+ "yes",+ "Yes",+ "YES",+ "on",+ "On",+ "ON",+ "1",+ "enabled",+ "ENABLED",+ "checked",+ "CHECKED",+ "any_random_string",+ " true ", # With whitespace+ " yes ",+ " on ",+ ],+ )+ def test_truthy_strings(self, value):+ """Test that various truthy string values convert to True."""+ assert parse_boolean(value) is True++ @pytest.mark.parametrize(+ "value",+ [+ "false",+ "False",+ "FALSE",+ "no",+ "No",+ "NO",+ "off",+ "Off",+ "OFF",+ "0",+ "",+ " ", # Whitespace only+ " false ", # With whitespace+ " no ",+ " off ",+ " 0 ",+ ],+ )+ def test_falsy_strings(self, value):+ """Test that various falsy string values convert to False."""+ assert parse_boolean(value) is False+++class TestParseBooleanHTMLFormValues:+ """Test parse_boolean with HTML form submission values."""++ def test_checkbox_checked_standard(self):+ """Test standard HTML checkbox checked value."""+ # Most browsers send "on" for checked checkboxes+ # "on" is NOT in FALSY_VALUES, so it's treated as True+ assert parse_boolean("on") is True++ def test_checkbox_unchecked(self):+ """Test HTML checkbox unchecked (empty string from hidden input)."""+ assert parse_boolean("") is False++ def test_checkbox_with_custom_value(self):+ """Test HTML checkbox with custom value attribute."""+ # <input type="checkbox" value="custom">+ assert parse_boolean("custom") is True++ def test_hidden_fallback_false(self):+ """Test hidden input fallback value for unchecked checkbox."""+ # Common pattern: <input type="hidden" value="false">+ assert parse_boolean("false") is False+++class TestParseBooleanJSONValues:+ """Test parse_boolean with values from JSON parsing."""++ def test_json_true(self):+ """Test JSON boolean true."""+ assert parse_boolean(True) is True++ def test_json_false(self):+ """Test JSON boolean false."""+ assert parse_boolean(False) is False++ def test_json_string_true(self):+ """Test JSON string "true"."""+ assert parse_boolean("true") is True++ def test_json_string_false(self):+ """Test JSON string "false"."""+ assert parse_boolean("false") is False+++class TestParseBooleanEnvironmentVariables:+ """Test parse_boolean with environment variable values."""++ @pytest.mark.parametrize(+ "env_value",+ ["1", "true", "True", "TRUE", "yes", "YES", "on", "ON", "enabled"],+ )+ def test_common_env_true_values(self, env_value):+ """Test common environment variable values for true."""+ assert parse_boolean(env_value) is True++ @pytest.mark.parametrize(+ "env_value",+ ["0", "false", "False", "FALSE", "no", "NO", "off", "OFF", ""],+ )+ def test_common_env_false_values(self, env_value):+ """Test common environment variable values for false."""+ assert parse_boolean(env_value) is False+++class TestParseBooleanEdgeCases:+ """Test parse_boolean with edge cases and unusual inputs."""++ def test_whitespace_only_is_false(self):+ """Test that whitespace-only strings are false."""+ assert parse_boolean(" ") is False+ assert parse_boolean("\t") is False+ assert parse_boolean("\n") is False++ def test_numeric_zero_is_false(self):+ """Test that numeric 0 converts to False."""+ assert parse_boolean(0) is False++ def test_numeric_nonzero_is_true(self):+ """Test that non-zero numbers convert to True."""+ assert parse_boolean(1) is True+ assert parse_boolean(42) is True+ assert parse_boolean(-1) is True+ assert parse_boolean(3.14) is True++ def test_empty_list_is_false(self):+ """Test that empty list converts to False."""+ assert parse_boolean([]) is False++ def test_nonempty_list_is_true(self):+ """Test that non-empty list converts to True."""+ assert parse_boolean([1, 2, 3]) is True+ assert parse_boolean(["false"]) is True # Non-empty list++ def test_empty_dict_is_false(self):+ """Test that empty dict converts to False."""+ assert parse_boolean({}) is False++ def test_nonempty_dict_is_true(self):+ """Test that non-empty dict converts to True."""+ assert parse_boolean({"key": "value"}) is True++ def test_case_insensitive_handling(self):+ """Test that string comparison is case-insensitive."""+ assert parse_boolean("TrUe") is True+ assert parse_boolean("FaLsE") is False+ assert parse_boolean("YeS") is True+ assert parse_boolean("nO") is False++ def test_string_with_leading_trailing_spaces(self):+ """Test strings with leading/trailing whitespace are trimmed."""+ assert parse_boolean(" true ") is True+ assert parse_boolean(" false ") is False+ assert parse_boolean(" 0 ") is False+ assert parse_boolean(" 1 ") is True+++class TestParseBooleanConsistency:+ """Test parse_boolean for consistency across different input sources."""++ def test_form_json_env_consistency_true(self):+ """Test that true values are consistent across input sources."""+ # Form data+ assert parse_boolean("true") is True+ # JSON+ assert parse_boolean(True) is True+ # Environment+ assert parse_boolean("1") is True++ def test_form_json_env_consistency_false(self):+ """Test that false values are consistent across input sources."""+ # Form data+ assert parse_boolean("false") is False+ assert parse_boolean("") is False+ # JSON+ assert parse_boolean(False) is False+ # Environment+ assert parse_boolean("0") is False++ def test_roundtrip_bool_to_string_to_bool(self):+ """Test roundtrip conversion: bool -> str -> bool."""+ # True roundtrip+ assert parse_boolean(str(True).lower()) is True+ # False roundtrip+ assert parse_boolean(str(False).lower()) is False+++class TestParseBooleanHTMLSemantics:+ """+ Test parse_boolean for HTML checkbox semantics.++ HTML checkbox semantics: Any value present (except explicit false) = checked = True.+ This is documented behavior in the parse_boolean docstring.+ """++ def test_unchecked_checkbox_not_submitted(self):+ """Test unchecked checkbox (not in form data) = None = False."""+ assert parse_boolean(None) is False++ def test_unchecked_checkbox_hidden_fallback(self):+ """Test unchecked checkbox with hidden fallback value."""+ # Pattern: <input type="hidden" name="setting" value="false">+ # <input type="checkbox" name="setting">+ # When unchecked, form submits hidden input value+ assert parse_boolean("false") is False++ def test_checked_checkbox_standard(self):+ """Test checked checkbox with standard value."""+ # Most browsers send "on" for checked checkboxes+ # "on" is NOT in FALSY_VALUES, so it's treated as True+ assert parse_boolean("on") is True++ def test_checked_checkbox_explicit_true(self):+ """Test checked checkbox with explicit "true" value."""+ # Pattern: <input type="checkbox" name="setting" value="true">+ assert parse_boolean("true") is True++ def test_checked_checkbox_value_one(self):+ """Test checked checkbox with value="1"."""+ # Pattern: <input type="checkbox" name="setting" value="1">+ assert parse_boolean("1") is True+++class TestParseBooleanRegressions:+ """Test parse_boolean for known issues and regressions."""++ def test_issue_corrupted_value_detection(self):+ """+ Test that checkbox values are parsed before corrupted value detection.++ This prevents incorrect triggering of corrupted value detection when+ checkbox values come in as strings (e.g., "true") instead of booleans.++ Related to settings_routes.py:292-299+ """+ # String "true" from form should not be considered corrupted+ assert parse_boolean("true") is True+ assert isinstance(parse_boolean("true"), bool)++ # String "false" from form should not be considered corrupted+ assert parse_boolean("false") is False+ assert isinstance(parse_boolean("false"), bool)++ def test_ajax_vs_post_consistency(self):+ """+ Test consistency between AJAX (JSON) and traditional POST submissions.++ Related to settings_routes.py:1-38 dual-mode submission pattern.+ """+ # AJAX mode: JavaScript sends boolean+ ajax_checked = True+ ajax_unchecked = False++ # Traditional POST: Browser sends string+ post_checked = "true"+ post_unchecked = "false"++ # Both modes should produce same results+ assert parse_boolean(ajax_checked) == parse_boolean(post_checked)+ assert parse_boolean(ajax_unchecked) == parse_boolean(post_unchecked)