Skip to content

Agent Zero AI framework

feat: notifications backend system and frontend display

Rafael Uzarowskie476b4bfceca
diff --git a/agent.py b/agent.py
index abe5276ca..b42cb4aeb 100644
--- a/agent.py
+++ b/agent.py
@@ -36,6 +36,7 @@ class AgentContext:
_contexts: dict[str, "AgentContext"] = {}
_counter: int = 0
+ _notification_manager = None
def __init__(
self,
@@ -85,6 +86,13 @@ class AgentContext:
def all():
return list(AgentContext._contexts.values())
+ @classmethod
+ def get_notification_manager(cls):
+ if cls._notification_manager is None:
+ from python.helpers.notification import NotificationManager
+ cls._notification_manager = NotificationManager()
+ return cls._notification_manager
+
@staticmethod
def remove(id: str):
context = AgentContext._contexts.pop(id, None)
diff --git a/prompts/default/agent.system.tool.notify_user.md b/prompts/default/agent.system.tool.notify_user.md
new file mode 100644
index 000000000..17f276e18
--- /dev/null
+++ b/prompts/default/agent.system.tool.notify_user.md
@@ -0,0 +1,43 @@
+### notify_user:
+This tool can be used to notify the user of a message independent of the current task.
+
+!!! This is a universal notification tool
+!!! Supported notification types: info, success, warning, error, progress
+
+#### Arguments:
+ * "message" (string) : The message to be displayed to the user.
+ * "title" (Optional, string) : The title of the notification.
+ * "detail" (Optional, string) : The detail of the notification. May contain html tags.
+ * "type" (Optional, string) : The type of the notification. Can be "info", "success", "warning", "error", "progress".
+
+#### Usage examples:
+##### 1: Success notification
+```json
+{
+ "thoughts": [
+ "...",
+ ],
+ "tool_name": "notify_user",
+ "tool_args": {
+ "message": "Important notification: task xyz is completed succesfully",
+ "title": "Task Completed",
+ "detail": "This is a test notification detail with <a href='https://www.google.com'>link</a>",
+ "type": "success"
+ }
+}
+```
+##### 2: Error notification
+```json
+{
+ "thoughts": [
+ "...",
+ ],
+ "tool_name": "notify_user",
+ "tool_args": {
+ "message": "Important notification: task xyz is failed",
+ "title": "Task Failed",
+ "detail": "This is a test notification detail with <a href='https://www.google.com'>link</a> and <img src='https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'>",
+ "type": "error"
+ }
+}
+```
diff --git a/prompts/default/agent.system.tools.md b/prompts/default/agent.system.tools.md
index e5b9d4090..8fb8be436 100644
--- a/prompts/default/agent.system.tools.md
+++ b/prompts/default/agent.system.tools.md
@@ -19,3 +19,5 @@
{{ include './agent.system.tool.scheduler.md' }}
{{ include './agent.system.tool.document_query.md' }}
+
+{{ include './agent.system.tool.notify_user.md' }}
diff --git a/prompts/default/fw.notify_user.notification_sent.md b/prompts/default/fw.notify_user.notification_sent.md
new file mode 100644
index 000000000..1452e202d
--- /dev/null
+++ b/prompts/default/fw.notify_user.notification_sent.md
@@ -0,0 +1 @@
+The notification has been sent to the user.
diff --git a/python/api/notification_create.py b/python/api/notification_create.py
new file mode 100644
index 000000000..676e64192
--- /dev/null
+++ b/python/api/notification_create.py
@@ -0,0 +1,63 @@
+from python.helpers.api import ApiHandler
+from flask import Request, Response
+from python.helpers.notification import AgentNotification, NotificationType
+
+
+class NotificationCreate(ApiHandler):
+ @classmethod
+ def requires_auth(cls) -> bool:
+ return True
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ # Extract notification data
+ notification_type = input.get("type", "info")
+ message = input.get("message", "")
+ title = input.get("title", "")
+ detail = input.get("detail", "")
+ display_time = input.get("display_time", 3) # Default to 3 seconds
+
+ # Validate required fields
+ if not message:
+ return {"success": False, "error": "Message is required"}
+
+ # Validate display_time
+ try:
+ display_time = int(display_time)
+ if display_time <= 0:
+ display_time = 3 # Reset to default if invalid
+ except (ValueError, TypeError):
+ display_time = 3 # Reset to default if not convertible to int
+
+ # Validate notification type
+ try:
+ if isinstance(notification_type, str):
+ notification_type = NotificationType(notification_type.lower())
+ except ValueError:
+ return {"success": False, "error": f"Invalid notification type: {notification_type}"}
+
+ # Create notification using the appropriate helper method
+ try:
+ if notification_type == NotificationType.INFO:
+ notification = AgentNotification.info(message, title, detail, display_time)
+ elif notification_type == NotificationType.SUCCESS:
+ notification = AgentNotification.success(message, title, detail, display_time)
+ elif notification_type == NotificationType.WARNING:
+ notification = AgentNotification.warning(message, title, detail, display_time)
+ elif notification_type == NotificationType.ERROR:
+ notification = AgentNotification.error(message, title, detail, display_time)
+ elif notification_type == NotificationType.PROGRESS:
+ notification = AgentNotification.progress(message, title, detail, display_time)
+ else:
+ notification = AgentNotification.info(message, title, detail, display_time)
+
+ return {
+ "success": True,
+ "notification_id": notification.id,
+ "message": "Notification created successfully"
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": f"Failed to create notification: {str(e)}"
+ }
diff --git a/python/api/notifications_history.py b/python/api/notifications_history.py
new file mode 100644
index 000000000..1b9e9f3d2
--- /dev/null
+++ b/python/api/notifications_history.py
@@ -0,0 +1,20 @@
+from python.helpers.api import ApiHandler
+from flask import Request, Response
+from agent import AgentContext
+
+
+class NotificationsHistory(ApiHandler):
+ @classmethod
+ def requires_auth(cls) -> bool:
+ return True
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ # Get the global notification manager
+ notification_manager = AgentContext.get_notification_manager()
+
+ # Return all notifications for history modal
+ return {
+ "notifications": [n.output() for n in notification_manager.notifications],
+ "guid": notification_manager.guid,
+ "count": len(notification_manager.notifications),
+ }
diff --git a/python/api/notifications_mark_read.py b/python/api/notifications_mark_read.py
new file mode 100644
index 000000000..6f3d182d8
--- /dev/null
+++ b/python/api/notifications_mark_read.py
@@ -0,0 +1,38 @@
+from python.helpers.api import ApiHandler
+from flask import Request, Response
+from agent import AgentContext
+
+
+class NotificationsMarkRead(ApiHandler):
+ @classmethod
+ def requires_auth(cls) -> bool:
+ return True
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ notification_ids = input.get("notification_ids", [])
+ mark_all = input.get("mark_all", False)
+
+ notification_manager = AgentContext.get_notification_manager()
+
+ if mark_all:
+ notification_manager.mark_all_read()
+ return {"success": True, "message": "All notifications marked as read"}
+
+ if not notification_ids:
+ return {"success": False, "error": "No notification IDs provided"}
+
+ # Mark specific notifications as read
+ marked_count = 0
+ for notification_id in notification_ids:
+ # Find notification by ID and mark as read
+ for notification in notification_manager.notifications:
+ if notification.id == notification_id and not notification.read:
+ notification.mark_read()
+ marked_count += 1
+ break
+
+ return {
+ "success": True,
+ "marked_count": marked_count,
+ "message": f"Marked {marked_count} notifications as read"
+ }
diff --git a/python/api/poll.py b/python/api/poll.py
index df3e22c80..7c0eca049 100644
--- a/python/api/poll.py
+++ b/python/api/poll.py
@@ -1,11 +1,8 @@
-import time
-from datetime import datetime
from python.helpers.api import ApiHandler
from flask import Request, Response
from agent import AgentContext
-from python.helpers import persist_chat
from python.helpers.task_scheduler import TaskScheduler
from python.helpers.localization import Localization
from python.helpers.dotenv import get_dotenv_value
@@ -16,6 +13,7 @@ class Poll(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
ctxid = input.get("context", None)
from_no = input.get("log_from", 0)
+ notifications_from = input.get("notifications_from", 0)
# Get timezone from input (default to dotenv default or UTC if not provided)
timezone = input.get("timezone", get_dotenv_value("DEFAULT_USER_TIMEZONE", "UTC"))
@@ -26,6 +24,10 @@ class Poll(ApiHandler):
logs = context.log.output(start=from_no)
+ # Get notifications from global notification manager
+ notification_manager = AgentContext.get_notification_manager()
+ notifications = notification_manager.output(start=notifications_from)
+
# loop AgentContext._contexts
# Get a task scheduler instance
@@ -65,7 +67,7 @@ class Poll(ApiHandler):
# Add task details to context_data with the same field names
# as used in scheduler endpoints to maintain UI compatibility
context_data.update({
- "task_name": task_details.get("name"), # name is for context, task_name for the task name
+ "task_name": task_details.get("name"), # name is for context, task_name for the task name
"uuid": task_details.get("uuid"),
"state": task_details.get("state"),
"type": task_details.get("type"),
@@ -105,4 +107,7 @@ class Poll(ApiHandler):
"log_progress": context.log.progress,
"log_progress_active": context.log.progress_active,
"paused": context.paused,
+ "notifications": notifications,
+ "notifications_guid": notification_manager.guid,
+ "notifications_version": len(notification_manager.updates),
}
diff --git a/python/helpers/notification.py b/python/helpers/notification.py
new file mode 100644
index 000000000..1661eb644
--- /dev/null
+++ b/python/helpers/notification.py
@@ -0,0 +1,174 @@
+from dataclasses import dataclass
+import uuid
+from datetime import datetime, timezone, timedelta
+from enum import Enum
+
+
+class NotificationType(Enum):
+ INFO = "info"
+ SUCCESS = "success"
+ WARNING = "warning"
+ ERROR = "error"
+ PROGRESS = "progress"
+
+
+@dataclass
+class NotificationItem:
+ manager: "NotificationManager"
+ no: int
+ type: NotificationType
+ title: str
+ message: str
+ detail: str # HTML content for expandable details
+ timestamp: datetime
+ display_time: int = 3 # Display duration in seconds, default 3 seconds
+ read: bool = False
+ id: str = ""
+
+ def __post_init__(self):
+ if not self.id:
+ self.id = str(uuid.uuid4())
+ # Ensure type is always NotificationType
+ if isinstance(self.type, str):
+ self.type = NotificationType(self.type)
+
+ def mark_read(self):
+ self.read = True
+ self.manager._update_item(self.no, read=True)
+
+ def output(self):
+ return {
+ "no": self.no,
+ "id": self.id,
+ "type": self.type.value,
+ "title": self.title,
+ "message": self.message,
+ "detail": self.detail,
+ "timestamp": self.timestamp.isoformat(),
+ "display_time": self.display_time,
+ "read": self.read,
+ }
+
+
+class NotificationManager:
+ def __init__(self, max_notifications: int = 100):
+ self.guid: str = str(uuid.uuid4())
+ self.updates: list[int] = []
+ self.notifications: list[NotificationItem] = []
+ self.max_notifications = max_notifications
+
+ def add_notification(
+ self,
+ type: NotificationType,
+ message: str,
+ title: str = "",
+ detail: str = "",
+ display_time: int = 3,
+ ) -> NotificationItem:
+ # Create notification item
+ item = NotificationItem(
+ manager=self,
+ no=len(self.notifications),
+ type=type,
+ title=title,
+ message=message,
+ detail=detail,
+ timestamp=datetime.now(timezone.utc),
+ display_time=display_time,
+ )
+
+ # Add to notifications
+ self.notifications.append(item)
+ self.updates.append(item.no)
+
+ # Enforce limit
+ self._enforce_limit()
+
+ return item
+
+ def _enforce_limit(self):
+ if len(self.notifications) > self.max_notifications:
+ # Remove oldest notifications
+ to_remove = len(self.notifications) - self.max_notifications
+ self.notifications = self.notifications[to_remove:]
+ # Adjust notification numbers
+ for i, notification in enumerate(self.notifications):
+ notification.no = i
+ # Adjust updates list
+ self.updates = [no - to_remove for no in self.updates if no >= to_remove]
+
+ def get_recent_notifications(self, seconds: int = 30) -> list[NotificationItem]:
+ cutoff = datetime.now(timezone.utc) - timedelta(seconds=seconds)
+ return [n for n in self.notifications if n.timestamp >= cutoff]
+
+ def output(self, start: int | None = None, end: int | None = None) -> list[dict]:
+ if start is None:
+ start = 0
+ if end is None:
+ end = len(self.updates)
+
+ out = []
+ seen = set()
+ for update in self.updates[start:end]:
+ if update not in seen and update < len(self.notifications):
+ out.append(self.notifications[update].output())
+ seen.add(update)
+
+ return out
+
+ def _update_item(self, no: int, **kwargs):
+ if no < len(self.notifications):
+ item = self.notifications[no]
+ for key, value in kwargs.items():
+ if hasattr(item, key):
+ setattr(item, key, value)
+ self.updates.append(no)
+
+ def mark_all_read(self):
+ for notification in self.notifications:
+ notification.read = True
+
+ def clear_all(self):
+ self.notifications = []
+ self.updates = []
+ self.guid = str(uuid.uuid4())
+
+ def get_notifications_by_type(self, type: NotificationType) -> list[NotificationItem]:
+ return [n for n in self.notifications if n.type == type]
+
+
+class AgentNotification:
+ @staticmethod
+ def info(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ from agent import AgentContext
+ return AgentContext.get_notification_manager().add_notification(
+ NotificationType.INFO, message, title, detail, display_time
+ )
+
+ @staticmethod
+ def success(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ from agent import AgentContext
+ return AgentContext.get_notification_manager().add_notification(
+ NotificationType.SUCCESS, message, title, detail, display_time
+ )
+
+ @staticmethod
+ def warning(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ from agent import AgentContext
+ return AgentContext.get_notification_manager().add_notification(
+ NotificationType.WARNING, message, title, detail, display_time
+ )
+
+ @staticmethod
+ def error(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ from agent import AgentContext
+ return AgentContext.get_notification_manager().add_notification(
+ NotificationType.ERROR, message, title, detail, display_time
+ )
+
+ @staticmethod
+ def progress(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ from agent import AgentContext
+ return AgentContext.get_notification_manager().add_notification(
+ NotificationType.PROGRESS, message, title, detail, display_time
+ )
diff --git a/python/tools/notify_user.py b/python/tools/notify_user.py
new file mode 100644
index 000000000..487c501ca
--- /dev/null
+++ b/python/tools/notify_user.py
@@ -0,0 +1,26 @@
+from python.helpers.tool import Tool, Response
+from agent import AgentContext
+
+
+class NotifyUserTool(Tool):
+
+ async def execute(self, **kwargs):
+
+ message = self.args.get("message", "")
+ title = self.args.get("title", "")
+ detail = self.args.get("detail", "")
+ notification_type = self.args.get("type", "info")
+
+ if notification_type not in ["info", "success", "warning", "error", "progress"]:
+ return Response(message=f"Invalid notification type: {notification_type}", break_loop=False)
+
+ if not message:
+ return Response(message="Message is required", break_loop=False)
+
+ AgentContext.get_notification_manager().add_notification(
+ message=message,
+ title=title,
+ detail=detail,
+ type=notification_type,
+ )
+ return Response(message=self.agent.read_prompt("fw.notify_user.notification_sent.md"), break_loop=False)
diff --git a/webui/components/notifications/notification-icons.html b/webui/components/notifications/notification-icons.html
new file mode 100644
index 000000000..e16b79947
--- /dev/null
+++ b/webui/components/notifications/notification-icons.html
@@ -0,0 +1,34 @@
+<html>
+<head>
+ <script type="module">
+ import { store } from "/js/notificationStore.js";
+ console.log('Notification component script loaded');
+ </script>
+</head>
+<body>
+ <div x-data>
+ <!-- Notification Toggle Button (always visible and clickable) -->
+ <div class="notification-toggle"
+ :class="{
+ 'has-unread': $store.notificationStore.unreadCount > 0,
+ 'has-notifications': $store.notificationStore.notifications.length > 0
+ }"
+ @click="$store.notificationStore.openModal()"
+ title="View Notifications">
+ <div class="notification-icon">
+ 🔔
+ </div>
+ <span x-show="$store.notificationStore.unreadCount > 0"
+ class="notification-badge"
+ x-text="$store.notificationStore.unreadCount"></span>
+ </div>
+
+ <!-- Test Notification Button (for development) -->
+ <button class="notification-test-button"
+ @click="$store.notificationStore.info('Test notification message', 'Test Title', '<p>This is test detail content with <strong>HTML</strong> formatting.</p>')"
+ title="Create Test Notification">
+ <div class="notification-icon">🧪</div>
+ </button>
+ </div>
+</body>
+</html>
diff --git a/webui/components/notifications/notification-modal.html b/webui/components/notifications/notification-modal.html
new file mode 100644
index 000000000..f00c62bba
--- /dev/null
+++ b/webui/components/notifications/notification-modal.html
@@ -0,0 +1,359 @@
+<html>
+<head>
+ <title>Notifications</title>
+ <script type="module">
+ import { store } from "/js/notificationStore.js";
+
+ // Ensure notification store is available globally for the modal
+ if (!window.notificationStore) {
+ window.notificationStore = store;
+ }
+ </script>
+</head>
+<body>
+ <div x-data="notificationModalComponent()">
+ <!-- Modal Header Actions -->
+ <div class="modal-subheader">
+ <div class="notification-header-actions">
+ <button class="notification-action"
+ @click="$store.notificationStore.clearAll()"
+ :disabled="$store.notificationStore.getDisplayNotifications().length === 0"
+ title="Clear All">
+ 🗑️ Clear All
+ </button>
+ </div>
+ </div>
+
+ <!-- Notifications List -->
+ <div class="notification-list" x-show="$store.notificationStore.getDisplayNotifications().length > 0">
+ <template x-for="notification in $store.notificationStore.getDisplayNotifications()" :key="notification.id">
+ <div class="notification-item"
+ x-data="{ expanded: false }"
+ :class="$store.notificationStore.getNotificationItemClass(notification)"
+ @click="$store.notificationStore.markAsRead(notification.id)">
+
+ <div class="notification-icon"
+ x-html="$store.notificationStore.getNotificationIcon(notification.type)">
+ </div>
+
+ <div class="notification-content">
+ <div class="notification-title"
+ x-show="notification.title"
+ x-text="notification.title">
+ </div>
+ <div class="notification-message"
+ x-text="notification.message">
+ </div>
+ <div class="notification-timestamp"
+ x-text="$store.notificationStore.formatTimestamp(notification.timestamp)">
+ </div>
+
+ <!-- Expand Toggle Button (as last row element) -->
+ <button class="notification-expand-toggle"
+ x-show="notification.detail"
+ @click.stop="expanded = !expanded"
+ :title="expanded ? 'Collapse Details' : 'Expand Details'">
+ <span x-show="!expanded">▶ Show Details</span>
+ <span x-show="expanded">▼ Hide Details</span>
+ </button>
+
+ <!-- Expandable Detail Content -->
+ <div class="notification-detail"
+ x-show="expanded && notification.detail"
+ x-transition:enter="transition ease-out duration-200"
+ x-transition:enter-start="opacity-0 max-h-0"
+ x-transition:enter-end="opacity-100 max-h-96"
+ x-transition:leave="transition ease-in duration-200"
+ x-transition:leave-start="opacity-100 max-h-96"
+ x-transition:leave-end="opacity-0 max-h-0">
+ <div class="notification-detail-content" x-html="notification.detail"></div>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Empty State -->
+ <div class="notification-empty" x-show="$store.notificationStore.getDisplayNotifications().length === 0">
+ <div class="notification-empty-icon">🔔</div>
+ <p>No notifications to display</p>
+ <p style="font-size: 0.8rem; opacity: 0.7; margin-top: 0.5rem;"
+ x-show="$store.notificationStore.notifications.length > 0">
+ All notifications have been read and are older than 5 minutes
+ </p>
+ </div>
+ </div>
+
+ <style>
+ /* Modal-specific styles that override the standard modal */
+ .modal-container.notification-modal {
+ width: 90%;
+ max-width: 600px;
+ max-height: 80vh;
+ }
+
+ .notification-header-actions {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ justify-content: flex-end;
+ width: 100%;
+ }
+
+ .notification-action {
+ padding: 0.5rem 0.75rem;
+ background: rgba(255, 255, 255, 0.1);
+ border: 1px solid rgba(255, 255, 255, 0.2);
+ border-radius: 4px;
+ color: var(--color-text);
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 0.85rem;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ }
+
+ .notification-action:hover {
+ background: rgba(255, 255, 255, 0.15);
+ border-color: rgba(255, 255, 255, 0.3);
+ }
+
+ .notification-action:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+
+ .notification-action:disabled:hover {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
+ }
+
+ /* Notification List */
+ .notification-list {
+ max-height: 60vh;
+ overflow-y: auto;
+ padding: 0.5rem 0;
+ }
+
+ .notification-list::-webkit-scrollbar {
+ width: 6px;
+ }
+
+ .notification-list::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ .notification-list::-webkit-scrollbar-thumb {
+ background-color: rgba(155, 155, 155, 0.3);
+ border-radius: 6px;
+ }
+
+ .notification-list::-webkit-scrollbar-thumb:hover {
+ background-color: rgba(155, 155, 155, 0.5);
+ }
+
+ /* Include all the notification item styles from the CSS file */
+ .notification-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.75rem;
+ padding: 1rem;
+ margin-bottom: 0.5rem;
+ background: rgba(0, 0, 0, 0.1);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ position: relative;
+ }
+
+ .notification-item:hover {
+ background: rgba(0, 0, 0, 0.15);
+ border-color: rgba(255, 255, 255, 0.2);
+ }
+
+ .notification-item:last-child {
+ margin-bottom: 0;
+ }
+
+ .notification-item.unread {
+ border-left: 4px solid #2196F3;
+ background: rgba(33, 150, 243, 0.05);
+ }
+
+ .notification-item.read {
+ opacity: 0.7;
+ }
+
+ .notification-item.read .notification-title {
+ color: var(--color-text-muted);
+ }
+
+ .notification-item.read .notification-message {
+ color: var(--color-text-muted);
+ }
+
+ /* Notification Icon */
+ .notification-icon {
+ font-size: 1.1rem;
+ line-height: 1;
+ opacity: 0.8;
+ min-width: 20px;
+ text-align: center;
+ margin-top: 0.1rem;
+ }
+
+ .notification-info .notification-icon {
+ color: #2196F3;
+ }
+
+ .notification-success .notification-icon {
+ color: #4CAF50;
+ }
+
+ .notification-warning .notification-icon {
+ color: #FF9800;
+ }
+
+ .notification-error .notification-icon {
+ color: #F44336;
+ }
+
+ .notification-progress .notification-icon {
+ color: #9C27B0;
+ animation: spin 2s linear infinite;
+ }
+
+ /* Notification Content */
+ .notification-content {
+ flex: 1;
+ min-width: 0;
+ }
+
+ .notification-title {
+ font-weight: 600;
+ font-size: 0.9rem;
+ color: var(--color-primary);
+ margin-bottom: 0.25rem;
+ line-height: 1.3;
+ }
+
+ .notification-message {
+ font-size: 0.85rem;
+ color: var(--color-text);
+ line-height: 1.4;
+ margin-bottom: 0.5rem;
+ }
+
+ .notification-expand-toggle {
+ background: transparent;
+ border: none;
+ color: var(--color-text);
+ cursor: pointer;
+ padding: 0.25rem;
+ border-radius: 4px;
+ transition: all 0.2s ease;
+ font-size: 0.8rem;
+ opacity: 0.7;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ }
+
+ .notification-expand-toggle:hover {
+ opacity: 1;
+ background: rgba(255, 255, 255, 0.1);
+ }
+
+ .notification-timestamp {
+ font-size: 0.75rem;
+ color: var(--color-text);
+ opacity: 0.6;
+ margin-top: 0.5rem;
+ }
+
+ /* Notification Detail */
+ .notification-detail {
+ margin-top: 0.75rem;
+ padding: 0.75rem;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 6px;
+ border-left: 3px solid rgba(255, 255, 255, 0.2);
+ overflow: hidden;
+ transition: all 0.2s ease;
+ }
+
+ .notification-detail-content {
+ font-size: 0.85rem;
+ line-height: 1.4;
+ color: var(--color-text);
+ }
+
+ /* Empty State */
+ .notification-empty {
+ text-align: center;
+ padding: 3rem 1rem;
+ color: var(--color-text);
+ opacity: 0.6;
+ }
+
+ .notification-empty-icon {
+ font-size: 3rem;
+ margin-bottom: 1rem;
+ opacity: 0.5;
+ }
+
+ /* Animations */
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+
+ /* Light Mode Styles */
+ .light-mode .notification-item {
+ background: rgba(0, 0, 0, 0.03);
+ border-color: rgba(0, 0, 0, 0.1);
+ }
+
+ .light-mode .notification-item:hover {
+ background: rgba(0, 0, 0, 0.06);
+ border-color: rgba(0, 0, 0, 0.15);
+ }
+
+ .light-mode .notification-action {
+ border-color: rgba(0, 0, 0, 0.2);
+ color: var(--color-text);
+ }
+
+ .light-mode .notification-action:hover {
+ background: rgba(0, 0, 0, 0.05);
+ border-color: rgba(0, 0, 0, 0.3);
+ }
+
+ .light-mode .notification-detail {
+ background: rgba(0, 0, 0, 0.05);
+ border-left-color: rgba(0, 0, 0, 0.15);
+ }
+ </style>
+
+ <script>
+ function notificationModalComponent() {
+ return {
+ init() {
+ // Initialize component when modal loads
+ console.log('Notification modal component initialized');
+
+ // Mark all notifications as read when modal opens
+ // This can be configured later if needed
+ setTimeout(() => {
+ if (this.$store.notificationStore) {
+ this.$store.notificationStore.markAllAsRead();
+ }
+ }, 1000);
+ }
+ };
+ }
+ </script>
+</body>
+</html>
diff --git a/webui/components/notifications/notification-toast-stack.html b/webui/components/notifications/notification-toast-stack.html
new file mode 100644
index 000000000..8bbd77fc2
--- /dev/null
+++ b/webui/components/notifications/notification-toast-stack.html
@@ -0,0 +1,245 @@
+<html>
+<head>
+ <title>Notification Toast Stack</title>
+ <script type="module">
+ import { store } from "/js/notificationStore.js";
+ </script>
+</head>
+<body>
+ <div x-data>
+ <!-- Toast Stack Container -->
+ <div class="toast-stack-container"
+ x-show="$store.notificationStore.toastStack.length > 0">
+
+ <template x-for="(toast, index) in $store.notificationStore.toastStack" :key="toast.toastId">
+ <div class="toast-item"
+ :class="$store.notificationStore.getNotificationClass(toast.type)"
+ @click="$store.notificationStore.handleToastClick(toast.toastId)"
+ x-transition:enter="toast-enter"
+ x-transition:leave="toast-leave">
+
+ <!-- Toast Icon -->
+ <div class="toast-icon"
+ x-html="$store.notificationStore.getNotificationIcon(toast.type)">
+ </div>
+
+ <!-- Toast Content -->
+ <div class="toast-content">
+ <div class="toast-title"
+ x-show="toast.title"
+ x-text="toast.title">
+ </div>
+ <div class="toast-message"
+ x-text="toast.message">
+ </div>
+ <div class="toast-timestamp"
+ x-text="$store.notificationStore.formatTimestamp(toast.timestamp)">
+ </div>
+ </div>
+
+ <!-- Toast Dismiss -->
+ <button class="toast-dismiss"
+ @click.stop="$store.notificationStore.removeFromToastStack(toast.toastId)"
+ title="Dismiss">
+ ✕
+ </button>
+ </div>
+ </template>
+ </div>
+ </div>
+
+ <style>
+ /* Toast Stack Container */
+ .toast-stack-container {
+ position: fixed;
+ bottom: 20px;
+ right: 20px;
+ z-index: 1500;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ pointer-events: none;
+ max-width: 400px;
+ width: 100%;
+ }
+
+ /* Individual Toast Items */
+ .toast-item {
+ pointer-events: auto;
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 16px;
+ background: rgba(0, 0, 0, 0.9);
+ border: 1px solid rgba(255, 255, 255, 0.2);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ backdrop-filter: blur(10px);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
+ position: relative;
+ min-height: 60px;
+ }
+
+ .toast-item:hover {
+ background: rgba(0, 0, 0, 0.95);
+ border-color: rgba(255, 255, 255, 0.3);
+ transform: translateY(-2px);
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
+ }
+
+ /* Toast Type Styling */
+ .toast-item.notification-info {
+ border-left: 4px solid #2196F3;
+ background: rgba(33, 150, 243, 0.1);
+ }
+
+ .toast-item.notification-success {
+ border-left: 4px solid #4CAF50;
+ background: rgba(76, 175, 80, 0.1);
+ }
+
+ .toast-item.notification-warning {
+ border-left: 4px solid #FF9800;
+ background: rgba(255, 152, 0, 0.1);
+ }
+
+ .toast-item.notification-error {
+ border-left: 4px solid #F44336;
+ background: rgba(244, 67, 54, 0.1);
+ }
+
+ .toast-item.notification-progress {
+ border-left: 4px solid #9C27B0;
+ background: rgba(156, 39, 176, 0.1);
+ }
+
+ /* Toast Icon */
+ .toast-icon {
+ font-size: 1.2rem;
+ line-height: 1;
+ opacity: 0.9;
+ min-width: 24px;
+ text-align: center;
+ margin-top: 2px;
+ }
+
+ /* Toast Content */
+ .toast-content {
+ flex: 1;
+ min-width: 0;
+ }
+
+ .toast-title {
+ font-weight: 600;
+ font-size: 0.9rem;
+ color: var(--color-primary);
+ margin-bottom: 4px;
+ line-height: 1.3;
+ }
+
+ .toast-message {
+ font-size: 0.85rem;
+ color: var(--color-text);
+ line-height: 1.4;
+ margin-bottom: 4px;
+ }
+
+ .toast-timestamp {
+ font-size: 0.75rem;
+ color: var(--color-text);
+ opacity: 0.6;
+ }
+
+ /* Toast Dismiss */
+ .toast-dismiss {
+ background: rgba(255, 255, 255, 0.1);
+ border: none;
+ border-radius: 4px;
+ color: var(--color-text);
+ cursor: pointer;
+ padding: 4px 6px;
+ font-size: 0.8rem;
+ transition: all 0.2s ease;
+ opacity: 0;
+ }
+
+ .toast-item:hover .toast-dismiss {
+ opacity: 1;
+ }
+
+ .toast-dismiss:hover {
+ background: rgba(255, 255, 255, 0.2);
+ color: #fff;
+ }
+
+ /* Toast Animations */
+ .toast-enter {
+ transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
+ opacity: 0;
+ transform: translateX(100%) scale(0.8);
+ }
+
+ .toast-leave {
+ transition: all 0.2s ease;
+ opacity: 0;
+ transform: translateX(100%) scale(0.8);
+ }
+
+ /* Light Mode Styles */
+ .light-mode .toast-item {
+ background: rgba(255, 255, 255, 0.95);
+ border-color: rgba(0, 0, 0, 0.1);
+ color: var(--color-text);
+ }
+
+ .light-mode .toast-item:hover {
+ background: rgba(255, 255, 255, 0.98);
+ border-color: rgba(0, 0, 0, 0.2);
+ }
+
+ .light-mode .toast-dismiss {
+ background: rgba(0, 0, 0, 0.1);
+ }
+
+ .light-mode .toast-dismiss:hover {
+ background: rgba(0, 0, 0, 0.2);
+ }
+
+ /* Mobile Responsive */
+ @media (max-width: 768px) {
+ .toast-stack-container {
+ bottom: 10px;
+ right: 10px;
+ left: 10px;
+ max-width: none;
+ }
+
+ .toast-item {
+ padding: 12px;
+ font-size: 0.9rem;
+ }
+
+ .toast-title {
+ font-size: 0.85rem;
+ }
+
+ .toast-message {
+ font-size: 0.8rem;
+ }
+ }
+
+ /* Accessibility */
+ @media (prefers-reduced-motion: reduce) {
+ .toast-enter,
+ .toast-leave {
+ transition: none;
+ }
+
+ .toast-item:hover {
+ transform: none;
+ }
+ }
+ </style>
+</body>
+</html>
diff --git a/webui/css/notification.css b/webui/css/notification.css
new file mode 100644
index 000000000..cd38311f5
--- /dev/null
+++ b/webui/css/notification.css
@@ -0,0 +1,156 @@
+/* ===== NOTIFICATION SYSTEM STYLES ===== */
+
+/* Notification Toggle Button */
+.notification-toggle {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ padding: 0;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 6px;
+ color: var(--color-text);
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 1rem;
+ width: 36px;
+ height: 36px;
+ flex-shrink: 0;
+ margin: 0;
+ box-sizing: border-box;
+ text-align: center;
+}
+
+.notification-toggle:hover {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
+ transform: scale(1.05);
+}
+
+.notification-toggle .notification-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 1rem;
+ width: 100%;
+ height: 100%;
+ text-align: center;
+ line-height: 1;
+ vertical-align: middle;
+ margin: 0;
+ padding: 0;
+}
+
+.notification-toggle.has-unread {
+ border-color: #2196F3;
+ background: rgba(33, 150, 243, 0.1);
+ animation: pulse 2s infinite;
+}
+
+.notification-badge {
+ position: absolute;
+ top: -8px;
+ right: -8px;
+ background: #F44336;
+ color: white;
+ font-size: 0.7rem;
+ font-weight: bold;
+ padding: 0.2rem 0.4rem;
+ border-radius: 10px;
+ min-width: 1.2rem;
+ text-align: center;
+ line-height: 1;
+ border: 2px solid var(--bg-color);
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.notification-toggle.disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.notification-toggle.has-notifications {
+ opacity: 1;
+}
+
+.notification-toggle.disabled:hover {
+ background: rgba(255, 255, 255, 0.05);
+ border-color: rgba(255, 255, 255, 0.1);
+ transform: none;
+}
+
+/* Test Button (for development) - positioned next to bell icon */
+.notification-test-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 36px;
+ height: 36px;
+ background: rgba(33, 150, 243, 0.1);
+ border: 1px solid rgba(33, 150, 243, 0.3);
+ border-radius: 6px;
+ color: var(--color-text);
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 0.85rem;
+ margin-left: 0.5rem;
+}
+
+.notification-test-button:hover {
+ background: rgba(33, 150, 243, 0.2);
+ border-color: rgba(33, 150, 243, 0.5);
+}
+
+.notification-test-button .notification-icon {
+ font-size: 1.2rem;
+}
+
+/* Light Mode Styles */
+.light-mode .notification-toggle {
+ background: rgba(0, 0, 0, 0.05);
+ border-color: rgba(0, 0, 0, 0.1);
+}
+
+.light-mode .notification-toggle:hover {
+ background: rgba(0, 0, 0, 0.1);
+ border-color: rgba(0, 0, 0, 0.2);
+}
+
+.light-mode .notification-toggle.has-unread {
+ border-color: #2196F3;
+ background: rgba(33, 150, 243, 0.1);
+}
+
+.light-mode .notification-toggle.disabled:hover {
+ background: rgba(0, 0, 0, 0.05);
+ border-color: rgba(0, 0, 0, 0.1);
+}
+
+.light-mode .notification-test-button {
+ background: rgba(33, 150, 243, 0.1);
+ border-color: rgba(33, 150, 243, 0.3);
+}
+
+.light-mode .notification-test-button:hover {
+ background: rgba(33, 150, 243, 0.2);
+ border-color: rgba(33, 150, 243, 0.5);
+}
+
+/* Animations */
+@keyframes pulse {
+ 0%, 100% { transform: scale(1); }
+ 50% { transform: scale(1.05); }
+}
+
+/* Mobile Responsive */
+@media (max-width: 768px) {
+ .notification-toggle {
+ min-width: 40px;
+ min-height: 40px;
+ padding: 0.4rem;
+ }
+}
diff --git a/webui/index.css b/webui/index.css
index 9583c8b99..e4a0694c1 100644
--- a/webui/index.css
+++ b/webui/index.css
@@ -198,7 +198,7 @@ img {
padding: 0.47rem 0.56rem;
position: absolute;
top: var(--spacing-md);
- z-index: 1004;
+ z-index: 999;
-webkit-transition: all var(--transition-speed) ease-in-out;
transition: all var(--transition-speed) ease-in-out;
}
@@ -403,11 +403,10 @@ img {
#time-date-container {
position: fixed;
- right: 0;
+ right: var(--spacing-md);
display: flex;
align-items: center;
gap: var(--spacing-sm);
- margin-right: var(--spacing-md);
margin-top: var(--spacing-md);
}
@@ -466,7 +465,7 @@ pre {
position: fixed;
margin-left: 4.6rem;
margin-top: var(--spacing-md);
- z-index: 1004;
+ z-index: 999;
-webkit-transition: margin-left var(--transition-speed) ease-in-out;
transition: margin-left var(--transition-speed) ease-in-out;
}
diff --git a/webui/index.html b/webui/index.html
index 97461b18a..9de6562f0 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -17,6 +17,7 @@
<link rel="stylesheet" href="css/history.css">
<link rel="stylesheet" href="css/scheduler-datepicker.css">
<link rel="stylesheet" href="css/tunnel.css">
+ <link rel="stylesheet" href="css/notification.css">
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
@@ -102,6 +103,7 @@
<script type="module" src="js/scheduler.js"></script>
<script type="module" src="js/speech.js"></script>
<script type="module" src="js/history.js"></script>
+ <script type="module" src="js/notificationStore.js"></script>
<script type="module" src="index.js"></script>
<!-- Then load Alpine.js -->
@@ -121,7 +123,7 @@
<!-- Google Icons -->
<link rel="stylesheet" href="vendor/google/google-icons.css" />
-
+
<!-- Non-module scripts after Alpine.js -->
<script type="text/javascript" src="js/settings.js"></script>
@@ -349,9 +351,15 @@
stroke-width="3" x-bind:opacity="connected ? 0 : 1" />
</svg>
</div>
+ <!-- Notification Toggle positioned next to time-date -->
+ <x-component path="notifications/notification-icons.html"></x-component>
</div>
<div id="chat-history">
</div>
+
+ <!-- NEW: Toast Stack Component -->
+ <x-component path="notifications/notification-toast-stack.html"></x-component>
+
<div id="toast" class="toast">
<div class="toast__content">
<div class="toast__title"></div>
diff --git a/webui/index.js b/webui/index.js
index c4b48feae..06e56f39f 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -331,6 +331,7 @@ async function poll() {
const response = await sendJsonData("/poll", {
log_from: lastLogVersion,
+ notifications_from: globalThis.Alpine?.store('notificationStore')?.lastNotificationVersion || 0,
context: context || null,
timezone: timezone,
});
@@ -370,6 +371,11 @@ async function poll() {
updateProgress(response.log_progress, response.log_progress_active);
+ // Update notifications from response
+ if (globalThis.Alpine?.store('notificationStore')) {
+ globalThis.Alpine.store('notificationStore').updateFromPoll(response);
+ }
+
//set ui model vars from backend
if (window.Alpine && inputSection) {
const inputAD = Alpine.$data(inputSection);
diff --git a/webui/js/initFw.js b/webui/js/initFw.js
index 5560d0eb6..fe62ac6ca 100644
--- a/webui/js/initFw.js
+++ b/webui/js/initFw.js
@@ -1,5 +1,6 @@
import * as _modals from "./modals.js";
import * as _components from "./components.js";
+import "./notificationStore.js";
await import("../vendor/alpine/alpine.min.js");
@@ -11,3 +12,13 @@ Alpine.directive(
cleanup(() => onDestroy());
}
);
+
+// Initialize notification store when Alpine is ready
+document.addEventListener('alpine:init', () => {
+ // Initialize the notification store
+ setTimeout(() => {
+ if (Alpine.store('notificationStore')) {
+ Alpine.store('notificationStore').initialize();
+ }
+ }, 100);
+});
diff --git a/webui/js/notificationStore.js b/webui/js/notificationStore.js
new file mode 100644
index 000000000..fff7aa40d
--- /dev/null
+++ b/webui/js/notificationStore.js
@@ -0,0 +1,374 @@
+import { createStore } from "/js/AlpineStore.js";
+import * as API from "/js/api.js";
+
+const model = {
+ notifications: [],
+ loading: false,
+ lastNotificationVersion: 0,
+ lastNotificationGuid: "",
+ unreadCount: 0,
+
+ // NEW: Toast stack management
+ toastStack: [],
+ maxToastStack: 5,
+
+ // Initialize the notification store
+ initialize() {
+ console.log("NotificationStore: Initializing with toast stack");
+ this.loading = true;
+ this.updateUnreadCount();
+ this.removeOldNotifications();
+ this.toastStack = [];
+
+ // Auto-cleanup old notifications and toasts
+ setInterval(() => {
+ this.removeOldNotifications();
+ this.cleanupExpiredToasts();
+ }, 5 * 60 * 1000); // Every 5 minutes
+ },
+
+ // Update notifications from polling data
+ updateFromPoll(pollData) {
+ if (!pollData) return;
+
+ // Check if GUID changed (system restart)
+ if (pollData.notifications_guid !== this.lastNotificationGuid) {
+ this.lastNotificationVersion = 0;
+ this.notifications = [];
+ this.toastStack = []; // Clear toast stack on restart
+ this.lastNotificationGuid = pollData.notifications_guid || '';
+ }
+
+ // Process new notifications and add to toast stack
+ if (pollData.notifications && pollData.notifications.length > 0) {
+ pollData.notifications.forEach(notification => {
+ const isNew = !this.notifications.find(n => n.id === notification.id);
+ this.addOrUpdateNotification(notification);
+
+ // Add new notifications to toast stack
+ if (isNew && !notification.read) {
+ this.addToToastStack(notification);
+ }
+ });
+ }
+
+ // Update version tracking
+ this.lastNotificationVersion = pollData.notifications_version || 0;
+ this.lastNotificationGuid = pollData.notifications_guid || '';
+
+ // Update UI state
+ this.updateUnreadCount();
+ this.removeOldNotifications();
+
+ // Limit notifications to prevent memory issues (keep most recent)
+ if (this.notifications.length > 50) {
+ // Sort by timestamp and keep newest 50
+ this.notifications.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
+ this.notifications = this.notifications.slice(0, 50);
+ }
+ },
+
+ // NEW: Add notification to toast stack
+ addToToastStack(notification) {
+ // Create toast object with auto-dismiss timer
+ const toast = {
+ ...notification,
+ toastId: `toast-${notification.id}`,
+ addedAt: Date.now(),
+ autoRemoveTimer: null
+ };
+
+ // Add to bottom of stack (newest at bottom)
+ this.toastStack.push(toast);
+
+ // Enforce max stack limit (remove oldest from top)
+ if (this.toastStack.length > this.maxToastStack) {
+ const removed = this.toastStack.shift(); // Remove from top
+ if (removed.autoRemoveTimer) {
+ clearTimeout(removed.autoRemoveTimer);
+ }
+ }
+
+ // Set auto-dismiss timer
+ toast.autoRemoveTimer = setTimeout(() => {
+ this.removeFromToastStack(toast.toastId);
+ }, notification.display_time * 1000);
+
+ console.log(`Toast added: ${notification.type} - ${notification.message}`);
+ },
+
+ // NEW: Remove toast from stack
+ removeFromToastStack(toastId) {
+ const index = this.toastStack.findIndex(t => t.toastId === toastId);
+ if (index >= 0) {
+ const toast = this.toastStack[index];
+ if (toast.autoRemoveTimer) {
+ clearTimeout(toast.autoRemoveTimer);
+ }
+ this.toastStack.splice(index, 1);
+ console.log(`Toast removed: ${toastId}`);
+ }
+ },
+
+ // NEW: Clear entire toast stack
+ clearToastStack() {
+ this.toastStack.forEach(toast => {
+ if (toast.autoRemoveTimer) {
+ clearTimeout(toast.autoRemoveTimer);
+ }
+ });
+ this.toastStack = [];
+ console.log('Toast stack cleared');
+ },
+
+ // NEW: Clean up expired toasts (backup cleanup)
+ cleanupExpiredToasts() {
+ const now = Date.now();
+ this.toastStack = this.toastStack.filter(toast => {
+ const age = now - toast.addedAt;
+ const maxAge = toast.display_time * 1000;
+
+ if (age > maxAge) {
+ if (toast.autoRemoveTimer) {
+ clearTimeout(toast.autoRemoveTimer);
+ }
+ return false;
+ }
+ return true;
+ });
+ },
+
+ // NEW: Handle toast click (opens modal)
+ async handleToastClick(toastId) {
+ console.log(`Toast clicked: ${toastId}`);
+ await this.openModal();
+ // Modal opening will clear toast stack via markAllAsRead
+ },
+
+ // Add or update a notification
+ addOrUpdateNotification(notification) {
+ const existingIndex = this.notifications.findIndex(n => n.id === notification.id);
+
+ if (existingIndex >= 0) {
+ // Update existing notification
+ this.notifications[existingIndex] = notification;
+ } else {
+ // Add new notification at the beginning (most recent first)
+ this.notifications.unshift(notification);
+ }
+ },
+
+ // Update unread count
+ updateUnreadCount() {
+ this.unreadCount = this.notifications.filter(n => !n.read).length;
+ },
+
+ // Mark notification as read
+ async markAsRead(notificationId) {
+ const notification = this.notifications.find(n => n.id === notificationId);
+ if (notification && !notification.read) {
+ notification.read = true;
+ this.updateUnreadCount();
+
+ // Sync with backend (non-blocking)
+ try {
+ await API.callJsonApi('notifications_mark_read', {
+ notification_ids: [notificationId]
+ });
+ } catch (error) {
+ console.error('Failed to sync notification read status:', error);
+ // Don't revert the UI change - user experience should not be affected
+ }
+ }
+ },
+
+ // Enhanced: Mark all as read and clear toast stack
+ async markAllAsRead() {
+ const unreadNotifications = this.notifications.filter(n => !n.read);
+ if (unreadNotifications.length === 0) return;
+
+ // Update UI immediately
+ this.notifications.forEach(notification => {
+ notification.read = true;
+ });
+ this.updateUnreadCount();
+
+ // Clear toast stack when marking all as read
+ this.clearToastStack();
+
+ // Sync with backend (non-blocking)
+ try {
+ await API.callJsonApi('notifications_mark_read', {
+ mark_all: true
+ });
+ } catch (error) {
+ console.error('Failed to sync mark all as read:', error);
+ }
+ },
+
+ // Clear all notifications
+ async clearAll() {
+ this.notifications = [];
+ this.unreadCount = 0;
+ this.clearToastStack(); // Also clear toast stack
+
+ // Note: We don't sync clear with backend as notifications are stored in memory only
+ console.log('All notifications cleared');
+ },
+
+ // Get notifications by type
+ getNotificationsByType(type) {
+ return this.notifications.filter(n => n.type === type);
+ },
+
+ // Get notifications for display: ALL unread + read from last 5 minutes
+ getDisplayNotifications() {
+ const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
+
+ return this.notifications.filter(notification => {
+ // Always show unread notifications
+ if (!notification.read) {
+ return true;
+ }
+
+ // Show read notifications only if they're from the last 5 minutes
+ const notificationDate = new Date(notification.timestamp);
+ return notificationDate > fiveMinutesAgo;
+ });
+ },
+
+ // Get recent notifications (last 5) - kept for backwards compatibility
+ getRecentNotifications() {
+ return this.notifications.slice(0, 5);
+ },
+
+ // Get notification by ID
+ getNotificationById(id) {
+ return this.notifications.find(n => n.id === id);
+ },
+
+ // Remove old notifications (older than 1 hour)
+ removeOldNotifications() {
+ const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
+ const initialCount = this.notifications.length;
+ this.notifications = this.notifications.filter(n =>
+ new Date(n.timestamp) > oneHourAgo
+ );
+
+ if (this.notifications.length !== initialCount) {
+ this.updateUnreadCount();
+ }
+ },
+
+ // Format timestamp for display
+ formatTimestamp(timestamp) {
+ const date = new Date(timestamp);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'Just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays < 7) return `${diffDays}d ago`;
+
+ return date.toLocaleDateString();
+ },
+
+ // Get CSS class for notification type
+ getNotificationClass(type) {
+ const classes = {
+ info: "notification-info",
+ success: "notification-success",
+ warning: "notification-warning",
+ error: "notification-error",
+ progress: "notification-progress"
+ };
+ return classes[type] || "notification-info";
+ },
+
+ // Get CSS class for notification item including read state
+ getNotificationItemClass(notification) {
+ const typeClass = this.getNotificationClass(notification.type);
+ const readClass = notification.read ? "read" : "unread";
+ return `notification-item ${typeClass} ${readClass}`;
+ },
+
+ // Get icon for notification type
+ getNotificationIcon(type) {
+ const icons = {
+ info: "ℹ️",
+ success: "✅",
+ warning: "⚠️",
+ error: "❌",
+ progress: "⏳"
+ };
+ return icons[type] || "ℹ️";
+ },
+
+ // Create notification via backend (will appear via polling)
+ async createNotification(type, message, title = "", detail = "", display_time = 3) {
+ try {
+ const response = await window.sendJsonData('/notification_create', {
+ type: type,
+ message: message,
+ title: title,
+ detail: detail,
+ display_time: display_time
+ });
+
+ if (response.success) {
+ console.log('Notification created:', response.notification_id);
+ return response.notification_id;
+ } else {
+ console.error('Failed to create notification:', response.error);
+ return null;
+ }
+ } catch (error) {
+ console.error('Error creating notification:', error);
+ return null;
+ }
+ },
+
+ // Convenience methods for different notification types
+ async info(message, title = "", detail = "", display_time = 3) {
+ return await this.createNotification('info', message, title, detail, display_time);
+ },
+
+ async success(message, title = "", detail = "", display_time = 3) {
+ return await this.createNotification('success', message, title, detail, display_time);
+ },
+
+ async warning(message, title = "", detail = "", display_time = 3) {
+ return await this.createNotification('warning', message, title, detail, display_time);
+ },
+
+ async error(message, title = "", detail = "", display_time = 3) {
+ return await this.createNotification('error', message, title, detail, display_time);
+ },
+
+ async progress(message, title = "", detail = "", display_time = 3) {
+ return await this.createNotification('progress', message, title, detail, display_time);
+ },
+
+ // Enhanced: Open modal and clear toast stack
+ async openModal() {
+ // Import the standard modal system
+ const { openModal } = await import("/js/modals.js");
+ await openModal("notifications/notification-modal.html");
+
+ // Clear toast stack when modal opens
+ this.clearToastStack();
+ },
+
+ // Legacy method for backward compatibility
+ toggleNotifications() {
+ this.openModal();
+ }
+};
+
+// Create and export the store
+const store = createStore("notificationStore", model);
+export { store };