diff --git a/python/api/notification_create.py b/python/api/notification_create.py index d76352fea..6699fd258 100644 --- a/python/api/notification_create.py +++ b/python/api/notification_create.py @@ -1,6 +1,6 @@ from python.helpers.api import ApiHandler from flask import Request, Response -from python.helpers.notification import AgentNotification, NotificationType +from python.helpers.notification import NotificationManager, NotificationPriority, NotificationType class NotificationCreate(ApiHandler): @@ -10,7 +10,8 @@ class NotificationCreate(ApiHandler): async def process(self, input: dict, request: Request) -> dict | Response: # Extract notification data - notification_type = input.get("type", "info") + notification_type = input.get("type", NotificationType.INFO.value) + priority = input.get("priority", NotificationPriority.NORMAL.value) message = input.get("message", "") title = input.get("title", "") detail = input.get("detail", "") @@ -34,31 +35,31 @@ class NotificationCreate(ApiHandler): if isinstance(notification_type, str): notification_type = NotificationType(notification_type.lower()) except ValueError: - return {"success": False, "error": f"Invalid notification type: {notification_type}"} + 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, group) - elif notification_type == NotificationType.SUCCESS: - notification = AgentNotification.success(message, title, detail, display_time, group) - elif notification_type == NotificationType.WARNING: - notification = AgentNotification.warning(message, title, detail, display_time, group) - elif notification_type == NotificationType.ERROR: - notification = AgentNotification.error(message, title, detail, display_time, group) - elif notification_type == NotificationType.PROGRESS: - notification = AgentNotification.progress(message, title, detail, display_time, group) - else: - notification = AgentNotification.info(message, title, detail, display_time, group) + notification = NotificationManager.send_notification( + notification_type, + priority, + message, + title, + detail, + display_time, + group, + ) return { "success": True, "notification_id": notification.id, - "message": "Notification created successfully" + "message": "Notification created successfully", } except Exception as e: return { "success": False, - "error": f"Failed to create notification: {str(e)}" + "error": f"Failed to create notification: {str(e)}", } diff --git a/python/api/notifications_clear.py b/python/api/notifications_clear.py new file mode 100644 index 000000000..f8e6a0520 --- /dev/null +++ b/python/api/notifications_clear.py @@ -0,0 +1,18 @@ +from python.helpers.api import ApiHandler +from flask import Request, Response +from agent import AgentContext + + +class NotificationsClear(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() + + # Clear all notifications + notification_manager.clear_all() + + return {"success": True, "message": "All notifications cleared"} diff --git a/python/helpers/notification.py b/python/helpers/notification.py index 528d55f3a..1aefff7b4 100644 --- a/python/helpers/notification.py +++ b/python/helpers/notification.py @@ -11,12 +11,17 @@ class NotificationType(Enum): ERROR = "error" PROGRESS = "progress" +class NotificationPriority(Enum): + NORMAL = 10 + HIGH = 20 + @dataclass class NotificationItem: manager: "NotificationManager" no: int type: NotificationType + priority: NotificationPriority title: str message: str detail: str # HTML content for expandable details @@ -41,7 +46,8 @@ class NotificationItem: return { "no": self.no, "id": self.id, - "type": self.type.value, + "type": self.type.value if isinstance(self.type, NotificationType) else self.type, + "priority": self.priority.value if isinstance(self.priority, NotificationPriority) else self.priority, "title": self.title, "message": self.message, "detail": self.detail, @@ -59,9 +65,25 @@ class NotificationManager: self.notifications: list[NotificationItem] = [] self.max_notifications = max_notifications + @staticmethod + def send_notification( + type: NotificationType, + priority: NotificationPriority, + message: str, + title: str = "", + detail: str = "", + display_time: int = 3, + group: str = "", + ) -> NotificationItem: + from agent import AgentContext + return AgentContext.get_notification_manager().add_notification( + type, priority, message, title, detail, display_time, group + ) + def add_notification( self, type: NotificationType, + priority: NotificationPriority, message: str, title: str = "", detail: str = "", @@ -72,7 +94,8 @@ class NotificationManager: item = NotificationItem( manager=self, no=len(self.notifications), - type=type, + type=NotificationType(type), + priority=NotificationPriority(priority), title=title, message=message, detail=detail, @@ -138,41 +161,4 @@ class NotificationManager: 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, group: str = "") -> NotificationItem: - from agent import AgentContext - return AgentContext.get_notification_manager().add_notification( - NotificationType.INFO, message, title, detail, display_time, group - ) - - @staticmethod - def success(message: str, title: str = "", detail: str = "", display_time: int = 3, group: str = "") -> NotificationItem: - from agent import AgentContext - return AgentContext.get_notification_manager().add_notification( - NotificationType.SUCCESS, message, title, detail, display_time, group - ) - - @staticmethod - def warning(message: str, title: str = "", detail: str = "", display_time: int = 3, group: str = "") -> NotificationItem: - from agent import AgentContext - return AgentContext.get_notification_manager().add_notification( - NotificationType.WARNING, message, title, detail, display_time, group - ) - - @staticmethod - def error(message: str, title: str = "", detail: str = "", display_time: int = 3, group: str = "") -> NotificationItem: - from agent import AgentContext - return AgentContext.get_notification_manager().add_notification( - NotificationType.ERROR, message, title, detail, display_time, group - ) - - @staticmethod - def progress(message: str, title: str = "", detail: str = "", display_time: int = 3, group: str = "") -> NotificationItem: - from agent import AgentContext - return AgentContext.get_notification_manager().add_notification( - NotificationType.PROGRESS, message, title, detail, display_time, group - ) + return [n for n in self.notifications if n.type == type] \ No newline at end of file diff --git a/python/tools/notify_user.py b/python/tools/notify_user.py index 487c501ca..b436cffde 100644 --- a/python/tools/notify_user.py +++ b/python/tools/notify_user.py @@ -1,6 +1,6 @@ from python.helpers.tool import Tool, Response from agent import AgentContext - +from python.helpers.notification import NotificationPriority, NotificationType class NotifyUserTool(Tool): @@ -9,11 +9,20 @@ class NotifyUserTool(Tool): message = self.args.get("message", "") title = self.args.get("title", "") detail = self.args.get("detail", "") - notification_type = self.args.get("type", "info") + notification_type = self.args.get("type", NotificationType.INFO) + priority = self.args.get("priority", NotificationPriority.HIGH) # by default, agents should notify with high priority + timeout = int(self.args.get("timeout", 30)) # agent's notifications should have longer timeouts - if notification_type not in ["info", "success", "warning", "error", "progress"]: + try: + notification_type = NotificationType(notification_type) + except ValueError: return Response(message=f"Invalid notification type: {notification_type}", break_loop=False) + try: + priority = NotificationPriority(priority) + except ValueError: + return Response(message=f"Invalid notification priority: {priority}", break_loop=False) + if not message: return Response(message="Message is required", break_loop=False) @@ -22,5 +31,7 @@ class NotifyUserTool(Tool): title=title, detail=detail, type=notification_type, + priority=priority, + display_time=timeout, ) 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 index 918cd885f..2beb22e5f 100644 --- a/webui/components/notifications/notification-icons.html +++ b/webui/components/notifications/notification-icons.html @@ -10,7 +10,7 @@
notifications
- + x-text="$store.notificationStore.unreadPrioCount"> diff --git a/webui/components/notifications/notification-modal.html b/webui/components/notifications/notification-modal.html index 1cd1c538c..a8a9d1c14 100644 --- a/webui/components/notifications/notification-modal.html +++ b/webui/components/notifications/notification-modal.html @@ -1,84 +1,82 @@ + Notifications + -
- - - - -
-
- - + + \ No newline at end of file diff --git a/webui/components/notifications/notification-store.js b/webui/components/notifications/notification-store.js index 8d4f6823c..6335e23c1 100644 --- a/webui/components/notifications/notification-store.js +++ b/webui/components/notifications/notification-store.js @@ -1,5 +1,24 @@ import { createStore } from "/js/AlpineStore.js"; import * as API from "/js/api.js"; +import { openModal } from "/js/modals.js"; + +export const NotificationType = { + INFO: "info", + SUCCESS: "success", + WARNING: "warning", + ERROR: "error", + PROGRESS: "progress", +}; + +export const NotificationPriority = { + NORMAL: 10, + HIGH: 20, +}; + +export const defaultPriority = NotificationPriority.NORMAL; + +const maxNotifications = 100 +const maxToasts = 5 const model = { notifications: [], @@ -7,33 +26,27 @@ const model = { lastNotificationVersion: 0, lastNotificationGuid: "", unreadCount: 0, + unreadPrioCount: 0, // NEW: Toast stack management toastStack: [], - maxToastStack: 5, - + init() { this.initialize(); - - setTimeout(function () { - this.frontendInfo("Notification store initialized 1"); - // this.frontendInfo("Notification store initialized 2"); - // this.frontendInfo("Notification store initialized 3"); - }.bind(this), 100); }, // Initialize the notification store initialize() { this.loading = true; this.updateUnreadCount(); - this.removeOldNotifications(); + // this.removeOldNotifications(); this.toastStack = []; - // Auto-cleanup old notifications and toasts - setInterval(() => { - this.removeOldNotifications(); - this.cleanupExpiredToasts(); - }, 5 * 60 * 1000); // Every 5 minutes + // // Auto-cleanup old notifications and toasts + // setInterval(() => { + // this.removeOldNotifications(); + // this.cleanupExpiredToasts(); + // }, 5 * 60 * 1000); // Every 5 minutes }, // Update notifications from polling data @@ -51,11 +64,17 @@ const model = { // Process new notifications and add to toast stack if (pollData.notifications && pollData.notifications.length > 0) { pollData.notifications.forEach((notification) => { + // should we toast the notification? + const shouldToast = !notification.read; + + // adjust notification data before adding + this.adjustNotificationData(notification); + const isNew = !this.notifications.find((n) => n.id === notification.id); this.addOrUpdateNotification(notification); // Add new unread notifications to toast stack - if (isNew && !notification.read) { + if (isNew && shouldToast) { this.addToToastStack(notification); } }); @@ -68,14 +87,12 @@ const model = { // 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); + adjustNotificationData(notification) { + // set default priority if not set + if (!notification.priority) { + notification.priority = defaultPriority; } }, @@ -83,17 +100,11 @@ const model = { addToToastStack(notification) { // If notification has a group, remove any existing toasts with the same group if (notification.group && notification.group.trim() !== "") { - const existingToastIndex = this.toastStack.findIndex( + const existingToast = this.toastStack.find( (t) => t.group === notification.group ); - - if (existingToastIndex >= 0) { - const existingToast = this.toastStack[existingToastIndex]; - if (existingToast.autoRemoveTimer) { - clearTimeout(existingToast.autoRemoveTimer); - } - this.toastStack.splice(existingToastIndex, 1); - } + if (existingToast && existingToast.toastId) + this.removeFromToastStack(existingToast.toastId); } // Create toast object with auto-dismiss timer @@ -107,12 +118,10 @@ const model = { // 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); - } + // Enforce max stack limit (remove oldest) + while (this.toastStack.length > maxToasts) { + const oldest = this.toastStack[0]; + if (oldest && oldest.toastId) this.removeFromToastStack(oldest.toastId); } // Set auto-dismiss timer @@ -122,7 +131,7 @@ const model = { }, // NEW: Remove toast from stack - removeFromToastStack(toastId) { + removeFromToastStack(toastId, removedByUser = false) { const index = this.toastStack.findIndex((t) => t.toastId === toastId); if (index >= 0) { const toast = this.toastStack[index]; @@ -130,14 +139,30 @@ const model = { clearTimeout(toast.autoRemoveTimer); } this.toastStack.splice(index, 1); + + // execute after toast removed callback + this.afterToastRemoved(toast, removedByUser); + } + }, + + // called by UI + dismissToast(toastId) { + this.removeFromToastStack(toastId, true); + }, + + async afterToastRemoved(toast, removedByUser = false) { + // if the toast is closed by the user OR timed out with normal priority, mark it as read + if (removedByUser || toast.priority <= NotificationPriority.NORMAL) { + this.markAsRead(toast.id); } }, // NEW: Clear entire toast stack - clearToastStack() { + clearToastStack(withCallback = true, removedByUser = false) { this.toastStack.forEach((toast) => { if (toast.autoRemoveTimer) { clearTimeout(toast.autoRemoveTimer); + if (withCallback) this.afterToastRemoved(toast, removedByUser); } }); this.toastStack = []; @@ -179,12 +204,21 @@ const model = { // Add new notification at the beginning (most recent first) this.notifications.unshift(notification); } + + // Limit notifications to prevent memory issues (keep most recent) + if (this.notifications.length > maxNotifications) { + this.notifications = this.notifications.slice(0, maxNotifications); + } }, // Update unread count updateUnreadCount() { const unread = this.notifications.filter((n) => !n.read).length; + const unreadPrio = this.notifications.filter( + (n) => !n.read && n.priority > NotificationPriority.NORMAL + ).length; if (this.unreadCount !== unread) this.unreadCount = unread; + if (this.unreadPrioCount !== unreadPrio) this.unreadPrioCount = unreadPrio; }, // Mark notification as read @@ -220,7 +254,7 @@ const model = { this.updateUnreadCount(); // Clear toast stack when marking all as read - this.clearToastStack(); + this.clearToastStack(false); // Sync with backend (non-blocking) try { @@ -233,12 +267,19 @@ const model = { }, // Clear all notifications - async clearAll() { + async clearAll(syncBackend = true) { this.notifications = []; this.unreadCount = 0; - this.clearToastStack(); // Also clear toast stack + this.clearToastStack(false); // Also clear toast stack + this.clearBackendNotifications(); + }, - // Note: We don't sync clear with backend as notifications are stored in memory only + async clearBackendNotifications() { + try { + await API.callJsonApi("notifications_clear", null); + } catch (error) { + console.error("Failed to clear notifications:", error); + } }, // Get notifications by type @@ -290,14 +331,15 @@ const model = { 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); + const diffMins = diffMs / 60000; + const diffHours = diffMs / 3600000; + const diffDays = 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`; + if (diffMins < 0.15) return "Just now"; + else if (diffMins < 1) return "Less than a minute ago"; + else if (diffMins < 60) return `${Math.round(diffMins)}m ago`; + else if (diffHours < 24) return `${Math.round(diffHours)}h ago`; + else if (diffDays < 7) return `${Math.round(diffDays)}d ago`; return date.toLocaleDateString(); }, @@ -341,7 +383,8 @@ const model = { title = "", detail = "", display_time = 3, - group = "" + group = "", + priority = defaultPriority ) { try { const response = await globalThis.sendJsonData("/notification_create", { @@ -351,6 +394,7 @@ const model = { detail: detail, display_time: display_time, group: group, + priority: priority, }); if (response.success) { @@ -366,14 +410,22 @@ const model = { }, // Convenience methods for different notification types - async info(message, title = "", detail = "", display_time = 3, group = "") { + async info( + message, + title = "", + detail = "", + display_time = 3, + group = "", + priority = defaultPriority + ) { return await this.createNotification( - "info", + NotificationType.INFO, message, title, detail, display_time, - group + group, + priority ); }, @@ -382,15 +434,17 @@ const model = { title = "", detail = "", display_time = 3, - group = "" + group = "", + priority = defaultPriority ) { return await this.createNotification( - "success", + NotificationType.SUCCESS, message, title, detail, display_time, - group + group, + priority ); }, @@ -399,26 +453,36 @@ const model = { title = "", detail = "", display_time = 3, - group = "" + group = "", + priority = defaultPriority ) { return await this.createNotification( - "warning", + NotificationType.WARNING, message, title, detail, display_time, - group + group, + priority ); }, - async error(message, title = "", detail = "", display_time = 3, group = "") { + async error( + message, + title = "", + detail = "", + display_time = 3, + group = "", + priority = defaultPriority + ) { return await this.createNotification( - "error", + NotificationType.ERROR, message, title, detail, display_time, - group + group, + priority ); }, @@ -427,26 +491,28 @@ const model = { title = "", detail = "", display_time = 3, - group = "" + group = "", + priority = defaultPriority ) { return await this.createNotification( - "progress", + NotificationType.PROGRESS, message, title, detail, display_time, - group + group, + priority ); }, // 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(); + this.clearToastStack(false); + // open modal + await openModal("notifications/notification-modal.html"); + // mark all as read when modal closes + this.markAllAsRead(); }, // Legacy method for backward compatibility @@ -479,7 +545,8 @@ const model = { message, title = "", display_time = 5, - group = "" + group = "", + priority = defaultPriority ) { const timestamp = new Date().toISOString(); const notification = { @@ -493,10 +560,14 @@ const model = { read: false, frontend: true, // Mark as frontend-only group: group, + priority: priority, }; + //adjust data before using + this.adjustNotificationData(notification); + // If notification has a group, remove any existing toasts with the same group - if (group && group.trim() !== "") { + if (group && String(group).trim() !== "") { const existingToastIndex = this.toastStack.findIndex( (t) => t.group === group ); @@ -543,7 +614,8 @@ const model = { message, title = "", display_time = 5, - group = "" + group = "", + priority = defaultPriority ) { // Try to send to backend first if connected if (this.isConnected()) { @@ -554,7 +626,8 @@ const model = { title, "", display_time, - group + group, + priority ); if (notificationId) { // Backend handled it, notification will arrive via polling @@ -572,7 +645,14 @@ const model = { } // Fallback to frontend-only toast - return this.addFrontendToastOnly(type, message, title, display_time, group); + return this.addFrontendToastOnly( + type, + message, + title, + display_time, + group, + priority + ); }, // NEW: Convenience methods for frontend notifications (updated to use new backend-first logic) @@ -580,14 +660,16 @@ const model = { message, title = "Connection Error", display_time = 8, - group = "" + group = "", + priority = defaultPriority ) { return await this.addFrontendToast( - "error", + NotificationType.ERROR, message, title, display_time, - group + group, + priority ); }, @@ -595,24 +677,33 @@ const model = { message, title = "Warning", display_time = 5, - group = "" + group = "", + priority = defaultPriority ) { return await this.addFrontendToast( - "warning", + NotificationType.WARNING, message, title, display_time, - group + group, + priority ); }, - async frontendInfo(message, title = "Info", display_time = 3, group = "") { + async frontendInfo( + message, + title = "Info", + display_time = 3, + group = "", + priority = defaultPriority + ) { return await this.addFrontendToast( - "info", + NotificationType.INFO, message, title, display_time, - group + group, + priority ); }, @@ -620,14 +711,16 @@ const model = { message, title = "Success", display_time = 3, - group = "" + group = "", + priority = defaultPriority ) { return await this.addFrontendToast( - "success", + NotificationType.SUCCESS, message, title, display_time, - group + group, + priority ); }, }; @@ -636,7 +729,6 @@ const model = { const store = createStore("notificationStore", model); export { store }; - // add toasts to global for backward compatibility with older scripts globalThis.toastFrontendInfo = store.frontendInfo.bind(store); globalThis.toastFrontendSuccess = store.frontendSuccess.bind(store); diff --git a/webui/components/notifications/notification-toast-stack.html b/webui/components/notifications/notification-toast-stack.html index 3d9a540e0..d726fa902 100644 --- a/webui/components/notifications/notification-toast-stack.html +++ b/webui/components/notifications/notification-toast-stack.html @@ -40,7 +40,7 @@ @@ -62,7 +62,7 @@ gap: 8px; pointer-events: none; max-width: 400px; - width: calc(100% - 10px); + right: 5px; /* Anchor to the right */ align-items: flex-end; } diff --git a/webui/index.js b/webui/index.js index 87a355eb0..8b9ec8f9b 100644 --- a/webui/index.js +++ b/webui/index.js @@ -636,7 +636,7 @@ globalThis.killChat = async function (id) { updateAfterScroll(); - toast("Chat deleted successfully", "success"); + justToast("Chat deleted successfully", "success", 1000, "chat-removal"); } catch (e) { console.error("Error deleting chat:", e); globalThis.toastFetchError("Error deleting chat", e); @@ -990,9 +990,20 @@ function removeClassFromElement(element, className) { element.classList.remove(className); } +function justToast(text, type = "info", timeout = 5000, group = "") { + notificationStore.addFrontendToastOnly( + type, + text, + "", + timeout / 1000, + group + ) +} + + function toast(text, type = "info", timeout = 5000) { // Convert timeout from milliseconds to seconds for new notification system - const display_time = Math.max(timeout / 1000, 3); // Minimum 3 seconds + const display_time = Math.max(timeout / 1000, 1); // Minimum 1 second // Use new frontend notification system based on type switch (type.toLowerCase()) {