Skip to content

Agent Zero AI framework

finalize the notification system

Rafael Uzarowskie32a04fb77d3
diff --git a/docs/notifications.md b/docs/notifications.md
new file mode 100644
index 000000000..e78e55452
--- /dev/null
+++ b/docs/notifications.md
@@ -0,0 +1,130 @@
+# Agent Zero Notifications
+
+Quick guide for using the notification system in Agent Zero.
+
+## Backend Usage
+
+Use `AgentNotification` helper methods anywhere in your Python code:
+
+```python
+from python.helpers.notification import AgentNotification
+
+# Basic notifications
+AgentNotification.info("Operation completed")
+AgentNotification.success("File saved successfully", "File Manager")
+AgentNotification.warning("High CPU usage detected", "System Monitor")
+AgentNotification.error("Connection failed", "Network Error")
+AgentNotification.progress("Processing files...", "Task Progress")
+
+# With details and custom display time
+AgentNotification.info(
+ message="System backup completed",
+ title="Backup Manager",
+ detail="<p>Backup size: <strong>2.4 GB</strong></p>",
+ display_time=8 # seconds
+)
+
+# Grouped notifications (replaces previous in same group)
+AgentNotification.progress("Download: 25%", "File Download", group="download-status")
+AgentNotification.progress("Download: 75%", "File Download", group="download-status") # Replaces previous
+AgentNotification.progress("Download: Complete!", "File Download", group="download-status") # Replaces previous
+```
+
+## Frontend Usage
+
+Use the notification store in Alpine.js components:
+
+```javascript
+// Basic notifications
+$store.notificationStore.info("User logged in")
+$store.notificationStore.success("Settings saved", "Configuration")
+$store.notificationStore.warning("Session expiring soon")
+$store.notificationStore.error("Failed to load data")
+
+// With grouping
+$store.notificationStore.info("Connecting...", "Status", "", 3, "connection")
+$store.notificationStore.success("Connected!", "Status", "", 3, "connection") // Replaces previous
+
+// Frontend notifications with backend persistence (new feature!)
+$store.notificationStore.frontendError("Database timeout", "Connection Error")
+$store.notificationStore.frontendWarning("High memory usage", "Performance")
+$store.notificationStore.frontendInfo("Cache cleared", "System")
+```
+
+## Frontend Notifications with Backend Sync
+
+**New Feature**: Frontend notifications now automatically sync to the backend when connected, providing persistent history and cross-session availability.
+
+### How it Works:
+- **Backend Connected**: Notifications are sent to backend and appear via polling (persistent)
+- **Backend Disconnected**: Notifications show as frontend-only toasts (temporary)
+- **Automatic Fallback**: Seamless degradation when backend is unavailable
+
+### Global Functions:
+```javascript
+// These functions automatically try backend first, then fallback to frontend-only
+toastFrontendError("Server unreachable", "Connection Error")
+toastFrontendWarning("Slow connection detected")
+toastFrontendInfo("Reconnected successfully")
+```
+
+## HTML Usage
+
+```html
+<button @click="$store.notificationStore.success('Task completed!')">
+ Complete Task
+</button>
+
+<button @click="$store.notificationStore.warning('Progress: 50%', 'Upload', '', 5, 'upload-progress')">
+ Update Progress
+</button>
+
+<!-- Frontend notifications with backend sync -->
+<button @click="$store.notificationStore.frontendError('Connection failed', 'Network')">
+ Report Connection Error
+</button>
+```
+
+## Notification Groups
+
+Groups ensure only the latest notification from each group is shown in the toast stack:
+
+```python
+# Progress updates - each new notification replaces the previous one
+AgentNotification.info("Starting backup...", group="backup-status")
+AgentNotification.progress("Backup: 30%", group="backup-status") # Replaces previous
+AgentNotification.progress("Backup: 80%", group="backup-status") # Replaces previous
+AgentNotification.success("Backup complete!", group="backup-status") # Replaces previous
+
+# Connection status - only show current state
+AgentNotification.warning("Disconnected", group="network")
+AgentNotification.info("Reconnecting...", group="network") # Replaces previous
+AgentNotification.success("Connected", group="network") # Replaces previous
+```
+
+## Parameters
+
+All notification methods support these parameters:
+
+- `message` (required): Main notification text
+- `title` (optional): Notification title
+- `detail` (optional): HTML content for expandable details
+- `display_time` (optional): Toast display duration in seconds (default: 3)
+- `group` (optional): Group identifier for replacement behavior
+
+## Types
+
+- **info** (ℹ️): General information
+- **success** (✅): Successful operations
+- **warning** (⚠️): Important alerts
+- **error** (❌): Error conditions
+- **progress** (⏳): Ongoing operations
+
+## Behavior
+
+- **Toast Display**: Notifications appear as toasts in the bottom-right corner
+- **Persistent History**: All notifications (including synced frontend ones) are stored in notification history
+- **Modal Access**: Full history accessible via the bell icon
+- **Auto-dismiss**: Toasts automatically disappear after `display_time`
+- **Group Replacement**: Notifications with the same group replace previous ones immediately
+- **Backend Sync**: Frontend notifications automatically sync to backend when connected
diff --git a/python/api/notification_create.py b/python/api/notification_create.py
index 676e64192..d76352fea 100644
--- a/python/api/notification_create.py
+++ b/python/api/notification_create.py
@@ -15,6 +15,7 @@ class NotificationCreate(ApiHandler):
title = input.get("title", "")
detail = input.get("detail", "")
display_time = input.get("display_time", 3) # Default to 3 seconds
+ group = input.get("group", "") # Group parameter for notification grouping
# Validate required fields
if not message:
@@ -38,17 +39,17 @@ class NotificationCreate(ApiHandler):
# Create notification using the appropriate helper method
try:
if notification_type == NotificationType.INFO:
- notification = AgentNotification.info(message, title, detail, display_time)
+ notification = AgentNotification.info(message, title, detail, display_time, group)
elif notification_type == NotificationType.SUCCESS:
- notification = AgentNotification.success(message, title, detail, display_time)
+ notification = AgentNotification.success(message, title, detail, display_time, group)
elif notification_type == NotificationType.WARNING:
- notification = AgentNotification.warning(message, title, detail, display_time)
+ notification = AgentNotification.warning(message, title, detail, display_time, group)
elif notification_type == NotificationType.ERROR:
- notification = AgentNotification.error(message, title, detail, display_time)
+ notification = AgentNotification.error(message, title, detail, display_time, group)
elif notification_type == NotificationType.PROGRESS:
- notification = AgentNotification.progress(message, title, detail, display_time)
+ notification = AgentNotification.progress(message, title, detail, display_time, group)
else:
- notification = AgentNotification.info(message, title, detail, display_time)
+ notification = AgentNotification.info(message, title, detail, display_time, group)
return {
"success": True,
diff --git a/python/helpers/notification.py b/python/helpers/notification.py
index 1661eb644..528d55f3a 100644
--- a/python/helpers/notification.py
+++ b/python/helpers/notification.py
@@ -24,6 +24,7 @@ class NotificationItem:
display_time: int = 3 # Display duration in seconds, default 3 seconds
read: bool = False
id: str = ""
+ group: str = "" # Group identifier for grouping related notifications
def __post_init__(self):
if not self.id:
@@ -47,6 +48,7 @@ class NotificationItem:
"timestamp": self.timestamp.isoformat(),
"display_time": self.display_time,
"read": self.read,
+ "group": self.group,
}
@@ -64,6 +66,7 @@ class NotificationManager:
title: str = "",
detail: str = "",
display_time: int = 3,
+ group: str = "",
) -> NotificationItem:
# Create notification item
item = NotificationItem(
@@ -75,6 +78,7 @@ class NotificationManager:
detail=detail,
timestamp=datetime.now(timezone.utc),
display_time=display_time,
+ group=group,
)
# Add to notifications
@@ -139,36 +143,36 @@ class NotificationManager:
class AgentNotification:
@staticmethod
- def info(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ 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
+ NotificationType.INFO, message, title, detail, display_time, group
)
@staticmethod
- def success(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ 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
+ NotificationType.SUCCESS, message, title, detail, display_time, group
)
@staticmethod
- def warning(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ 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
+ NotificationType.WARNING, message, title, detail, display_time, group
)
@staticmethod
- def error(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ 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
+ NotificationType.ERROR, message, title, detail, display_time, group
)
@staticmethod
- def progress(message: str, title: str = "", detail: str = "", display_time: int = 3) -> NotificationItem:
+ 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
+ NotificationType.PROGRESS, message, title, detail, display_time, group
)
diff --git a/webui/components/notifications/notification-icons.html b/webui/components/notifications/notification-icons.html
index b1fed75a8..9df55fbee 100644
--- a/webui/components/notifications/notification-icons.html
+++ b/webui/components/notifications/notification-icons.html
@@ -2,12 +2,11 @@
<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) -->
+ <!-- Notification Toggle Button -->
<div class="notification-toggle"
:class="{
'has-unread': $store.notificationStore.unreadCount > 0,
@@ -22,20 +21,6 @@
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>
-
- <!-- Test Frontend Error Button (for development) -->
- <button class="notification-test-button frontend-error"
- @click="toastFrontendError('Backend connection failed', 'Connection Error')"
- title="Test Frontend Error Toast">
- <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
index f00c62bba..21e63b2bc 100644
--- a/webui/components/notifications/notification-modal.html
+++ b/webui/components/notifications/notification-modal.html
@@ -341,9 +341,6 @@
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(() => {
diff --git a/webui/components/settings/backup/backup-store.js b/webui/components/settings/backup/backup-store.js
index 0dee50f74..328fd3bb1 100644
--- a/webui/components/settings/backup/backup-store.js
+++ b/webui/components/settings/backup/backup-store.js
@@ -3,6 +3,7 @@ import { createStore } from "/js/AlpineStore.js";
// Global function references
const sendJsonData = window.sendJsonData;
const toast = window.toast;
+const fetchApi = window.fetchApi;
// ⚠️ CRITICAL: The .env file contains API keys and essential configuration.
// This file is REQUIRED for Agent Zero to function and must be backed up.
@@ -375,9 +376,9 @@ const model = {
const fileList = this.previewFiles.map(f => f.path).join('\n');
try {
await navigator.clipboard.writeText(fileList);
- toast('File list copied to clipboard', 'success');
+ window.toastFrontendInfo('File list copied to clipboard', 'Clipboard');
} catch (error) {
- toast('Failed to copy to clipboard', 'error');
+ window.toastFrontendError('Failed to copy to clipboard', 'Clipboard Error');
}
},
@@ -419,7 +420,7 @@ const model = {
window.URL.revokeObjectURL(url);
this.addFileOperation('Backup created and downloaded successfully!');
- toast('Backup created and downloaded successfully', 'success');
+ window.toastFrontendInfo('Backup created and downloaded successfully', 'Backup Status');
} else {
// Try to parse error response
const errorText = await response.text();
@@ -677,7 +678,7 @@ const model = {
}
if (warnings.length > 0) {
- toast(`Compatibility warnings: ${warnings.join(', ')}`, 'warning');
+ window.toastFrontendWarning(`Compatibility warnings: ${warnings.join(', ')}`, 'Backup Compatibility');
}
},
@@ -746,7 +747,7 @@ const model = {
this.addFileOperation(`\nRestore completed: ${deletedCount} deleted, ${restoredCount} restored, ${skippedCount} skipped, ${errorCount} errors`);
this.restoreResult = result;
- toast('Restore completed successfully', 'success');
+ window.toastFrontendInfo('Restore completed successfully', 'Restore Status');
} else {
this.error = result.error;
this.addFileOperation(`Error: ${result.error}`);
diff --git a/webui/components/settings/mcp/client/mcp-servers-store.js b/webui/components/settings/mcp/client/mcp-servers-store.js
index e7c507570..1012ad21a 100644
--- a/webui/components/settings/mcp/client/mcp-servers-store.js
+++ b/webui/components/settings/mcp/client/mcp-servers-store.js
@@ -113,7 +113,6 @@ const model = {
scrollModal("mcp-servers-status");
} catch (error) {
console.error("Failed to apply MCP servers:", error);
- alert("Failed to apply MCP servers: " + error.message);
}
this.loading = false;
},
diff --git a/webui/css/notification.css b/webui/css/notification.css
index 1f41574a5..3a02a7d01 100644
--- a/webui/css/notification.css
+++ b/webui/css/notification.css
@@ -83,42 +83,7 @@
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;
-}
-
-/* Frontend Error Test Button - distinct orange/red styling */
-.notification-test-button.frontend-error {
- background: rgba(255, 152, 0, 0.15);
- border-color: rgba(255, 152, 0, 0.4);
-}
-
-.notification-test-button.frontend-error:hover {
- background: rgba(255, 152, 0, 0.25);
- border-color: rgba(255, 152, 0, 0.6);
-}
/* Light Mode Styles */
.light-mode .notification-toggle {
@@ -141,25 +106,7 @@
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);
-}
-
-.light-mode .notification-test-button.frontend-error {
- background: rgba(255, 152, 0, 0.15);
- border-color: rgba(255, 152, 0, 0.4);
-}
-.light-mode .notification-test-button.frontend-error:hover {
- background: rgba(255, 152, 0, 0.25);
- border-color: rgba(255, 152, 0, 0.6);
-}
/* Animations */
@keyframes pulse {
diff --git a/webui/index.js b/webui/index.js
index 06e56f39f..64cd5b639 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -23,7 +23,7 @@ const timeDate = document.getElementById("time-date-container");
let autoScroll = true;
let context = "";
-let connectionStatus = false;
+let connectionStatus = undefined; // undefined = not checked yet, true = connected, false = disconnected
// Initialize the toggle button
setupSidebarToggle();
@@ -161,20 +161,26 @@ export async function sendMessage() {
}
}
} catch (e) {
- toastFetchError("Error sending message", e);
+ toastFetchError("Error sending message", e); // Will use new notification system
}
}
function toastFetchError(text, error) {
+ console.error(text, error);
+ // Use new frontend error notification system (async, but we don't need to wait)
+ const errorMessage = error?.message || error?.toString() || "Unknown error";
+
if (getConnectionStatus()) {
- toast(`${text}: ${error.message}`, "error");
+ // Backend is connected, just show the error
+ toastFrontendError(`${text}: ${errorMessage}`).catch(e =>
+ console.error('Failed to show error toast:', e)
+ );
} else {
- toast(
- `${text} (it seems the backend is not running): ${error.message}`,
- "error"
+ // Backend is disconnected, show connection error
+ toastFrontendError(`${text} (backend appears to be disconnected): ${errorMessage}`, "Connection Error").catch(e =>
+ console.error('Failed to show connection error toast:', e)
);
}
- console.error(text, error);
}
window.toastFetchError = toastFetchError;
@@ -373,7 +379,17 @@ async function poll() {
// Update notifications from response
if (globalThis.Alpine?.store('notificationStore')) {
- globalThis.Alpine.store('notificationStore').updateFromPoll(response);
+ const notificationStore = globalThis.Alpine.store('notificationStore');
+
+ // Ensure store is initialized
+ if (!notificationStore.lastNotificationGuid && response.notifications_guid) {
+ console.log('Initializing notification store on fresh load');
+ notificationStore.initialize();
+ }
+
+ notificationStore.updateFromPoll(response);
+ } else {
+ console.warn('Notification store not available during poll');
}
//set ui model vars from backend
@@ -813,8 +829,6 @@ window.restart = async function () {
const resp = await sendJsonData("/health", {});
// Server is back up, show success message
await new Promise((resolve) => setTimeout(resolve, 250));
- hideToast();
- await new Promise((resolve) => setTimeout(resolve, 400));
toast("Restarted", "success", 5000);
return;
} catch (e) {
@@ -825,8 +839,6 @@ window.restart = async function () {
}
// If we get here, restart failed or took too long
- hideToast();
- await new Promise((resolve) => setTimeout(resolve, 400));
toast("Restart timed out or failed", "error", 5000);
}
};
@@ -955,95 +967,32 @@ function removeClassFromElement(element, className) {
}
function toast(text, type = "info", timeout = 5000) {
- const toast = document.getElementById("toast");
- const isVisible = toast.classList.contains("show");
-
- // Clear any existing timeout immediately
- if (toast.timeoutId) {
- clearTimeout(toast.timeoutId);
- toast.timeoutId = null;
- }
-
- // Function to update toast content and show it
- const updateAndShowToast = () => {
- // Update the toast content and type
- const title = type.charAt(0).toUpperCase() + type.slice(1);
- toast.querySelector(".toast__title").textContent = title;
- toast.querySelector(".toast__message").textContent = text;
-
- // Remove old classes and add new ones
- toast.classList.remove("toast--success", "toast--error", "toast--info");
- toast.classList.add(`toast--${type}`);
-
- // Show/hide copy button based on toast type
- const copyButton = toast.querySelector(".toast__copy");
- copyButton.style.display = type === "error" ? "inline-block" : "none";
-
- // Add the close button event listener
- const closeButton = document.querySelector(".toast__close");
- closeButton.onclick = () => {
- hideToast();
- };
-
- // Add the copy button event listener
- copyButton.onclick = () => {
- navigator.clipboard.writeText(text);
- copyButton.textContent = "Copied!";
- setTimeout(() => {
- copyButton.textContent = "Copy";
- }, 2000);
- };
-
- // Show the toast
- toast.style.display = "flex";
- // Force a reflow to ensure the animation triggers
- void toast.offsetWidth;
- toast.classList.add("show");
-
- // Set timeout if specified
- if (timeout) {
- const minTimeout = Math.max(timeout, 5000);
- toast.timeoutId = setTimeout(() => {
- hideToast();
- }, minTimeout);
+ // Convert timeout from milliseconds to seconds for new notification system
+ const display_time = Math.max(timeout / 1000, 3); // Minimum 3 seconds
+
+ // Use new frontend notification system based on type
+ if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
+ const store = window.Alpine.store('notificationStore');
+ switch (type.toLowerCase()) {
+ case 'error':
+ return store.frontendError(text, "Error", display_time);
+ case 'success':
+ return store.frontendInfo(text, "Success", display_time);
+ case 'warning':
+ return store.frontendWarning(text, "Warning", display_time);
+ case 'info':
+ default:
+ return store.frontendInfo(text, "Info", display_time);
}
- };
-
- if (isVisible) {
- // If a toast is visible, hide it first then show the new one
- toast.classList.remove("show");
- toast.classList.add("hide");
-
- // Wait for hide animation to complete before showing new toast
- setTimeout(() => {
- toast.classList.remove("hide");
- updateAndShowToast();
- }, 400); // Match this with CSS transition duration
} else {
- // If no toast is visible, show the new one immediately
- updateAndShowToast();
+ // Fallback if Alpine/store not ready
+ console.log(`${type.toUpperCase()}: ${text}`);
+ return null;
}
}
window.toast = toast;
-function hideToast() {
- const toast = document.getElementById("toast");
-
- // Clear any existing timeout
- if (toast.timeoutId) {
- clearTimeout(toast.timeoutId);
- toast.timeoutId = null;
- }
-
- toast.classList.remove("show");
- toast.classList.add("hide");
-
- // Wait for the hide animation to complete before removing from display
- setTimeout(() => {
- toast.style.display = "none";
- toast.classList.remove("hide");
- }, 400); // Match this with CSS transition duration
-}
+// OLD: hideToast function removed - now using new notification system
function scrollChanged(isAtBottom) {
if (window.Alpine && autoScrollSwitch) {
@@ -1106,6 +1055,14 @@ document.addEventListener("DOMContentLoaded", function () {
setupSidebarToggle();
setupTabs();
initializeActiveTab();
+
+ // Initialize notification store early to ensure it's ready for polling
+ setTimeout(() => {
+ if (globalThis.Alpine?.store('notificationStore')) {
+ globalThis.Alpine.store('notificationStore').initialize();
+ console.log('Notification store initialized on DOM ready');
+ }
+ }, 100); // Small delay to ensure Alpine is ready
});
// Setup tabs functionality
diff --git a/webui/js/file_browser.js b/webui/js/file_browser.js
index d86a2f6d4..33d987154 100644
--- a/webui/js/file_browser.js
+++ b/webui/js/file_browser.js
@@ -53,7 +53,7 @@ const fileBrowserModalProxy = {
this.browser.entries = [];
}
} catch (error) {
- window.toastFetchError("Error fetching files", error);
+ window.toastFrontendError("Error fetching files: " + error.message, "File Browser Error");
this.browser.entries = [];
} finally {
this.isLoading = false;
@@ -134,7 +134,7 @@ const fileBrowserModalProxy = {
alert(`Error deleting file: ${await response.text()}`);
}
} catch (error) {
- window.toastFetchError("Error deleting file", error);
+ window.toastFrontendError("Error deleting file: " + error.message, "File Delete Error");
alert("Error deleting file");
}
},
@@ -188,7 +188,7 @@ const fileBrowserModalProxy = {
alert(data.message);
}
} catch (error) {
- window.toastFetchError("Error uploading files", error);
+ window.toastFrontendError("Error uploading files: " + error.message, "File Upload Error");
alert("Error uploading files");
}
},
@@ -215,7 +215,7 @@ const fileBrowserModalProxy = {
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
} catch (error) {
- window.toastFetchError("Error downloading file", error);
+ window.toastFrontendError("Error downloading file: " + error.message, "File Download Error");
alert("Error downloading file");
}
},
@@ -267,7 +267,7 @@ openFileLink = async function (path) {
try {
const resp = await window.sendJsonData("/file_info", { path });
if (!resp.exists) {
- window.toast("File does not exist.", "error");
+ window.toastFrontendError("File does not exist.", "File Error");
return;
}
@@ -280,7 +280,7 @@ openFileLink = async function (path) {
});
}
} catch (e) {
- window.toastFetchError("Error opening file", e);
+ window.toastFrontendError("Error opening file: " + e.message, "File Open Error");
}
};
window.openFileLink = openFileLink;
diff --git a/webui/js/history.js b/webui/js/history.js
index 040de72fe..c071c53bf 100644
--- a/webui/js/history.js
+++ b/webui/js/history.js
@@ -8,7 +8,7 @@ export async function openHistoryModal() {
const size = hist.tokens
await showEditorModal(data, "markdown", `History ~${size} tokens`, "Conversation history visible to the LLM. History is compressed to fit into the context window over time.");
} catch (e) {
- window.toastFetchError("Error fetching history", e)
+ window.toastFrontendError("Error fetching history: " + e.message, "Chat History Error");
return
}
}
@@ -20,7 +20,7 @@ export async function openCtxWindowModal() {
const size = win.tokens
await showEditorModal(data, "markdown", `Context window ~${size} tokens`, "Data passed to the LLM during last interaction. Contains system message, conversation history and RAG.");
} catch (e) {
- window.toastFetchError("Error fetching context", e)
+ window.toastFrontendError("Error fetching context: " + e.message, "Context Error");
return
}
}
diff --git a/webui/js/image_modal.js b/webui/js/image_modal.js
index c2f4edb23..6c6bc1e49 100644
--- a/webui/js/image_modal.js
+++ b/webui/js/image_modal.js
@@ -4,13 +4,13 @@ let activeIntervalId = null;
export async function openImageModal(src, refreshInterval = 0) {
try {
let imgSrc = src;
-
+
// Clear any existing refresh interval
if (activeIntervalId !== null) {
clearInterval(activeIntervalId);
activeIntervalId = null;
}
-
+
if (refreshInterval > 0) {
// Add or update timestamp to bypass cache
const addTimestamp = (url) => {
@@ -23,7 +23,7 @@ export async function openImageModal(src, refreshInterval = 0) {
const isImageViewerActive = () => {
const container = document.querySelector('#image-viewer-container');
if (!container) return false;
-
+
// Check if element or any parent is hidden
let element = container;
while (element) {
@@ -46,7 +46,7 @@ export async function openImageModal(src, refreshInterval = 0) {
tempImg.onerror = reject;
tempImg.src = nextSrc;
});
-
+
try {
// Wait for preload to complete
const loadedSrc = await preloadPromise;
@@ -58,9 +58,9 @@ export async function openImageModal(src, refreshInterval = 0) {
console.error('Failed to preload image:', err);
}
};
-
+
imgSrc = addTimestamp(src);
-
+
// Set up periodic refresh with preloading
activeIntervalId = setInterval(() => {
if (!isImageViewerActive()) {
@@ -77,11 +77,11 @@ export async function openImageModal(src, refreshInterval = 0) {
const html = `<div id="image-viewer-container"><img class="image-viewer-img" src="${imgSrc}" /></div>`;
const fileName = src.split("/").pop();
-
+
// Open the modal with the generated HTML
await window.genericModalProxy.openModal(fileName, "", html);
} catch (e) {
- window.toastFetchError("Error fetching history", e);
+ window.toastFrontendError("Error fetching history: " + e.message, "Image History Error");
return;
}
}
diff --git a/webui/js/notificationStore.js b/webui/js/notificationStore.js
index 05600b89d..257b8b14f 100644
--- a/webui/js/notificationStore.js
+++ b/webui/js/notificationStore.js
@@ -14,7 +14,6 @@ const model = {
// Initialize the notification store
initialize() {
- console.log("NotificationStore: Initializing with toast stack");
this.loading = true;
this.updateUnreadCount();
this.removeOldNotifications();
@@ -31,6 +30,8 @@ const model = {
updateFromPoll(pollData) {
if (!pollData) return;
+ const isFirstLoad = !this.lastNotificationGuid && pollData.notifications_guid;
+
// Check if GUID changed (system restart)
if (pollData.notifications_guid !== this.lastNotificationGuid) {
this.lastNotificationVersion = 0;
@@ -45,7 +46,7 @@ const model = {
const isNew = !this.notifications.find(n => n.id === notification.id);
this.addOrUpdateNotification(notification);
- // Add new notifications to toast stack
+ // Add new unread notifications to toast stack
if (isNew && !notification.read) {
this.addToToastStack(notification);
}
@@ -70,6 +71,21 @@ const model = {
// NEW: Add notification to toast stack
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(t =>
+ t.group === notification.group
+ );
+
+ if (existingToastIndex >= 0) {
+ const existingToast = this.toastStack[existingToastIndex];
+ if (existingToast.autoRemoveTimer) {
+ clearTimeout(existingToast.autoRemoveTimer);
+ }
+ this.toastStack.splice(existingToastIndex, 1);
+ }
+ }
+
// Create toast object with auto-dismiss timer
const toast = {
...notification,
@@ -93,8 +109,6 @@ const model = {
toast.autoRemoveTimer = setTimeout(() => {
this.removeFromToastStack(toast.toastId);
}, notification.display_time * 1000);
-
- console.log(`Toast added: ${notification.type} - ${notification.message}`);
},
// NEW: Remove toast from stack
@@ -106,7 +120,6 @@ const model = {
clearTimeout(toast.autoRemoveTimer);
}
this.toastStack.splice(index, 1);
- console.log(`Toast removed: ${toastId}`);
}
},
@@ -118,7 +131,6 @@ const model = {
}
});
this.toastStack = [];
- console.log('Toast stack cleared');
},
// NEW: Clean up expired toasts (backup cleanup)
@@ -140,7 +152,6 @@ const model = {
// 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
},
@@ -213,7 +224,6 @@ const model = {
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
@@ -309,18 +319,18 @@ const model = {
},
// Create notification via backend (will appear via polling)
- async createNotification(type, message, title = "", detail = "", display_time = 3) {
+ async createNotification(type, message, title = "", detail = "", display_time = 3, group = "") {
try {
const response = await window.sendJsonData('/notification_create', {
type: type,
message: message,
title: title,
detail: detail,
- display_time: display_time
+ display_time: display_time,
+ group: group
});
if (response.success) {
- console.log('Notification created:', response.notification_id);
return response.notification_id;
} else {
console.error('Failed to create notification:', response.error);
@@ -333,24 +343,24 @@ const model = {
},
// 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 info(message, title = "", detail = "", display_time = 3, group = "") {
+ return await this.createNotification('info', message, title, detail, display_time, group);
},
- async success(message, title = "", detail = "", display_time = 3) {
- return await this.createNotification('success', message, title, detail, display_time);
+ async success(message, title = "", detail = "", display_time = 3, group = "") {
+ return await this.createNotification('success', message, title, detail, display_time, group);
},
- async warning(message, title = "", detail = "", display_time = 3) {
- return await this.createNotification('warning', message, title, detail, display_time);
+ async warning(message, title = "", detail = "", display_time = 3, group = "") {
+ return await this.createNotification('warning', message, title, detail, display_time, group);
},
- async error(message, title = "", detail = "", display_time = 3) {
- return await this.createNotification('error', message, title, detail, display_time);
+ async error(message, title = "", detail = "", display_time = 3, group = "") {
+ return await this.createNotification('error', message, title, detail, display_time, group);
},
- async progress(message, title = "", detail = "", display_time = 3) {
- return await this.createNotification('progress', message, title, detail, display_time);
+ async progress(message, title = "", detail = "", display_time = 3, group = "") {
+ return await this.createNotification('progress', message, title, detail, display_time, group);
},
// Enhanced: Open modal and clear toast stack
@@ -368,8 +378,24 @@ const model = {
this.openModal();
},
- // NEW: Add frontend-only toast directly to stack (for connection errors, etc.)
- addFrontendToast(type, message, title = "", display_time = 5) {
+ // NEW: Check if backend connection is available
+ isConnected() {
+ // Use the global connection status from index.js, but default to true if undefined
+ // This handles the case where polling hasn't run yet but backend is actually available
+ const pollingStatus = typeof window.getConnectionStatus === 'function' ? window.getConnectionStatus() : undefined;
+
+ // If polling status is explicitly false, respect that
+ if (pollingStatus === false) {
+ return false;
+ }
+
+ // If polling status is undefined/true, assume backend is available
+ // (since the page loaded successfully, backend must be working)
+ return true;
+ },
+
+ // NEW: Add frontend-only toast directly to stack (renamed from original addFrontendToast)
+ addFrontendToastOnly(type, message, title = "", display_time = 5, group = "") {
const timestamp = new Date().toISOString();
const notification = {
id: `frontend-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
@@ -380,9 +406,25 @@ const model = {
timestamp: timestamp,
display_time: display_time,
read: false,
- frontend: true // Mark as frontend-only
+ frontend: true, // Mark as frontend-only
+ group: group
};
+ // If notification has a group, remove any existing toasts with the same group
+ if (group && group.trim() !== "") {
+ const existingToastIndex = this.toastStack.findIndex(t =>
+ t.group === group
+ );
+
+ if (existingToastIndex >= 0) {
+ const existingToast = this.toastStack[existingToastIndex];
+ if (existingToast.autoRemoveTimer) {
+ clearTimeout(existingToast.autoRemoveTimer);
+ }
+ this.toastStack.splice(existingToastIndex, 1);
+ }
+ }
+
// Create toast object with auto-dismiss timer
const toast = {
...notification,
@@ -407,21 +449,41 @@ const model = {
this.removeFromToastStack(toast.toastId);
}, notification.display_time * 1000);
- console.log(`Frontend toast added: ${notification.type} - ${notification.message}`);
return notification.id;
},
- // NEW: Convenience methods for frontend-only notifications
- frontendError(message, title = "Connection Error", display_time = 8) {
- return this.addFrontendToast('error', message, title, display_time);
+ // NEW: Enhanced frontend toast that tries backend first, falls back to frontend-only
+ async addFrontendToast(type, message, title = "", display_time = 5, group = "") {
+ // Try to send to backend first if connected
+ if (this.isConnected()) {
+ try {
+ const notificationId = await this.createNotification(type, message, title, "", display_time, group);
+ if (notificationId) {
+ // Backend handled it, notification will arrive via polling
+ return notificationId;
+ }
+ } catch (error) {
+ console.log(`Backend unavailable for notification, showing as frontend-only: ${error.message || error}`);
+ }
+ } else {
+ console.log('Backend disconnected, showing as frontend-only toast');
+ }
+
+ // Fallback to frontend-only toast
+ return this.addFrontendToastOnly(type, message, title, display_time, group);
},
- frontendWarning(message, title = "Warning", display_time = 5) {
- return this.addFrontendToast('warning', message, title, display_time);
+ // NEW: Convenience methods for frontend notifications (updated to use new backend-first logic)
+ async frontendError(message, title = "Connection Error", display_time = 8, group = "") {
+ return await this.addFrontendToast('error', message, title, display_time, group);
},
- frontendInfo(message, title = "Info", display_time = 3) {
- return this.addFrontendToast('info', message, title, display_time);
+ async frontendWarning(message, title = "Warning", display_time = 5, group = "") {
+ return await this.addFrontendToast('warning', message, title, display_time, group);
+ },
+
+ async frontendInfo(message, title = "Info", display_time = 3, group = "") {
+ return await this.addFrontendToast('info', message, title, display_time, group);
}
};
@@ -429,9 +491,16 @@ const model = {
const store = createStore("notificationStore", model);
// NEW: Global function for frontend error toasts (replaces toastFetchError)
-window.toastFrontendError = function(message, title = "Connection Error") {
+window.toastFrontendError = async function(message, title = "Connection Error") {
if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
- return window.Alpine.store('notificationStore').frontendError(message, title);
+ try {
+ return await window.Alpine.store('notificationStore').frontendError(message, title);
+ } catch (error) {
+ console.error('Failed to create frontend error notification:', error);
+ // Fallback to console if something goes wrong
+ console.error('Frontend Error:', title, '-', message);
+ return null;
+ }
} else {
// Fallback if Alpine/store not ready
console.error('Frontend Error:', title, '-', message);
@@ -440,18 +509,30 @@ window.toastFrontendError = function(message, title = "Connection Error") {
};
// NEW: Additional global convenience functions
-window.toastFrontendWarning = function(message, title = "Warning") {
+window.toastFrontendWarning = async function(message, title = "Warning") {
if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
- return window.Alpine.store('notificationStore').frontendWarning(message, title);
+ try {
+ return await window.Alpine.store('notificationStore').frontendWarning(message, title);
+ } catch (error) {
+ console.error('Failed to create frontend warning notification:', error);
+ console.warn('Frontend Warning:', title, '-', message);
+ return null;
+ }
} else {
console.warn('Frontend Warning:', title, '-', message);
return null;
}
};
-window.toastFrontendInfo = function(message, title = "Info") {
+window.toastFrontendInfo = async function(message, title = "Info") {
if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
- return window.Alpine.store('notificationStore').frontendInfo(message, title);
+ try {
+ return await window.Alpine.store('notificationStore').frontendInfo(message, title);
+ } catch (error) {
+ console.error('Failed to create frontend info notification:', error);
+ console.log('Frontend Info:', title, '-', message);
+ return null;
+ }
} else {
console.log('Frontend Info:', title, '-', message);
return null;
diff --git a/webui/js/scheduler.js b/webui/js/scheduler.js
index b0cba1f72..fbe2ad39c 100644
--- a/webui/js/scheduler.js
+++ b/webui/js/scheduler.js
@@ -59,11 +59,27 @@ import { switchFromContext } from '../index.js';
// Add this near the top of the scheduler.js file, outside of any function
const showToast = function(message, type = 'info') {
- // Use the global toast function if available, otherwise fallback to console
- if (typeof window.toast === 'function') {
- window.toast(message, type);
+ // Use new frontend notification system
+ if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
+ const store = window.Alpine.store('notificationStore');
+ switch (type.toLowerCase()) {
+ case 'error':
+ return store.frontendError(message, "Scheduler", 5);
+ case 'success':
+ return store.frontendInfo(message, "Scheduler", 3);
+ case 'warning':
+ return store.frontendWarning(message, "Scheduler", 4);
+ case 'info':
+ default:
+ return store.frontendInfo(message, "Scheduler", 3);
+ }
} else {
- console.log(`Toast (${type}): ${message}`);
+ // Fallback to global toast function or console
+ if (typeof window.toast === 'function') {
+ window.toast(message, type);
+ } else {
+ console.log(`SCHEDULER ${type.toUpperCase()}: ${message}`);
+ }
}
};
@@ -976,7 +992,7 @@ const fullComponentImplementation = function() {
}
showToast('Task deleted successfully', 'success');
-
+
// If we were viewing the detail of the deleted task, close the detail view
if (this.selectedTaskForDetail && this.selectedTaskForDetail.uuid === taskId) {
this.closeTaskDetail();
diff --git a/webui/js/settings.js b/webui/js/settings.js
index fc6f759df..5ee7c1039 100644
--- a/webui/js/settings.js
+++ b/webui/js/settings.js
@@ -575,24 +575,25 @@ document.addEventListener('alpine:init', function () {
});
});
-// Show toast notification
+// Show toast notification - now uses new notification system
function showToast(message, type = 'info') {
- const toast = document.createElement('div');
- toast.className = `toast toast-${type}`;
- toast.textContent = message;
-
- document.body.appendChild(toast);
-
- // Trigger animation
- setTimeout(() => {
- toast.classList.add('show');
- }, 10);
-
- // Remove after delay
- setTimeout(() => {
- toast.classList.remove('show');
- setTimeout(() => {
- document.body.removeChild(toast);
- }, 300);
- }, 3000);
+ // Use new frontend notification system based on type
+ if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {
+ const store = window.Alpine.store('notificationStore');
+ switch (type.toLowerCase()) {
+ case 'error':
+ return store.frontendError(message, "Settings", 5);
+ case 'success':
+ return store.frontendInfo(message, "Settings", 3);
+ case 'warning':
+ return store.frontendWarning(message, "Settings", 4);
+ case 'info':
+ default:
+ return store.frontendInfo(message, "Settings", 3);
+ }
+ } else {
+ // Fallback if Alpine/store not ready
+ console.log(`SETTINGS ${type.toUpperCase()}: ${message}`);
+ return null;
+ }
}
diff --git a/webui/js/speech.js b/webui/js/speech.js
index 040d0b783..59671bc74 100644
--- a/webui/js/speech.js
+++ b/webui/js/speech.js
@@ -47,7 +47,7 @@ async function loadMicSettings() {
});
}
} catch (error) {
- window.toastFetchError("Failed to load speech settings", error);
+ window.toastFrontendError("Failed to load speech settings: " + error.message, "Speech Settings Error");
console.error("Failed to load speech settings:", error);
}
}
@@ -205,7 +205,7 @@ class MicrophoneInput {
return true;
} catch (error) {
console.error("Microphone initialization error:", error);
- toast("Failed to access microphone. Please check permissions.", "error");
+ window.toastFrontendError("Failed to access microphone. Please check permissions.", "Microphone Error");
return false;
}
}
@@ -295,7 +295,7 @@ class MicrophoneInput {
await this.updateCallback(result.text, true);
}
} catch (error) {
- window.toastFetchError("Transcription error", error);
+ window.toastFrontendError("Transcription error: " + error.message, "Speech Recognition Error");
console.error("Transcription error:", error);
} finally {
this.audioChunks = [];
@@ -386,10 +386,7 @@ async function requestMicrophonePermission() {
return true;
} catch (err) {
console.error("Error accessing microphone:", err);
- toast(
- "Microphone access denied. Please enable microphone access in your browser settings.",
- "error"
- );
+ window.toastFrontendError("Microphone access denied. Please enable microphone access in your browser settings.", "Microphone Error");
return false;
}
}
diff --git a/webui/js/speech_browser.js b/webui/js/speech_browser.js
index 9f214a7b7..e6d7ff2b0 100644
--- a/webui/js/speech_browser.js
+++ b/webui/js/speech_browser.js
@@ -178,7 +178,7 @@ class MicrophoneInput {
} catch (error) {
console.error('Microphone initialization error:', error);
- toast('Failed to access microphone. Please check permissions.', 'error');
+ window.toastFrontendError('Failed to access microphone. Please check permissions.', 'Microphone Error');
return false;
}
}
@@ -193,7 +193,7 @@ class MicrophoneInput {
this.analyserNode.smoothingTimeConstant = 0.85;
this.mediaStreamSource.connect(this.analyserNode);
}
-
+
startAudioAnalysis() {
const analyzeFrame = () => {
@@ -251,7 +251,7 @@ class MicrophoneInput {
return;
}
- const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
+ const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
@@ -268,7 +268,7 @@ class MicrophoneInput {
}
} catch (error) {
console.error('Transcription error:', error);
- toast('Transcription failed.', 'error');
+ window.toastFrontendError('Transcription failed.', 'Speech Recognition Error');
} finally {
URL.revokeObjectURL(audioUrl);
this.audioChunks = [];
@@ -347,7 +347,7 @@ async function requestMicrophonePermission() {
return true;
} catch (err) {
console.error('Error accessing microphone:', err);
- toast('Microphone access denied. Please enable microphone access in your browser settings.', 'error');
+ window.toastFrontendError('Microphone access denied. Please enable microphone access in your browser settings.', 'Microphone Error');
return false;
}
}
@@ -391,4 +391,4 @@ class Speech {
}
export const speech = new Speech();
-window.speech = speech
\ No newline at end of file
+window.speech = speech
diff --git a/webui/js/tunnel.js b/webui/js/tunnel.js
index 8e257e47b..cd06374ec 100644
--- a/webui/js/tunnel.js
+++ b/webui/js/tunnel.js
@@ -24,9 +24,9 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({ action: 'get' }),
});
-
+
const data = await response.json();
-
+
if (data.success && data.tunnel_url) {
// Update the stored URL if it's different from what we have
if (this.tunnelLink !== data.tunnel_url) {
@@ -37,7 +37,7 @@ document.addEventListener('alpine:init', () => {
} else {
// Check if we have a stored tunnel URL
const storedTunnelUrl = localStorage.getItem('agent_zero_tunnel_url');
-
+
if (storedTunnelUrl) {
// Use the stored URL but verify it's still valid
const verifyResponse = await fetchApi('/tunnel_proxy', {
@@ -47,9 +47,9 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({ action: 'verify', url: storedTunnelUrl }),
});
-
+
const verifyData = await verifyResponse.json();
-
+
if (verifyData.success && verifyData.is_valid) {
this.tunnelLink = storedTunnelUrl;
this.linkGenerated = true;
@@ -77,14 +77,14 @@ document.addEventListener('alpine:init', () => {
if (confirm("Are you sure you want to generate a new tunnel URL? The old URL will no longer work.")) {
this.isLoading = true;
this.loadingText = 'Refreshing tunnel...';
-
+
// Change refresh button appearance
const refreshButton = document.querySelector('.refresh-link-button');
const originalContent = refreshButton.innerHTML;
refreshButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Refreshing...';
refreshButton.disabled = true;
refreshButton.classList.add('refreshing');
-
+
try {
// First stop any existing tunnel
const stopResponse = await fetchApi('/tunnel_proxy', {
@@ -94,19 +94,19 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({ action: 'stop' }),
});
-
+
// Check if stopping was successful
const stopData = await stopResponse.json();
if (!stopData.success) {
console.warn("Warning: Couldn't stop existing tunnel cleanly");
// Continue anyway since we want to create a new one
}
-
+
// Then generate a new one
await this.generateLink();
} catch (error) {
console.error("Error refreshing tunnel:", error);
- window.toast("Error refreshing tunnel", "error", 3000);
+ window.toastFrontendError("Error refreshing tunnel", "Tunnel Error");
this.isLoading = false;
this.loadingText = '';
} finally {
@@ -123,17 +123,17 @@ document.addEventListener('alpine:init', () => {
try {
const authCheckResponse = await fetchApi('/settings_get');
const authData = await authCheckResponse.json();
-
+
// Find the auth_login and auth_password in the settings
let hasAuth = false;
-
+
if (authData && authData.settings && authData.settings.sections) {
for (const section of authData.settings.sections) {
if (section.fields) {
const authLoginField = section.fields.find(field => field.id === 'auth_login');
const authPasswordField = section.fields.find(field => field.id === 'auth_password');
-
- if (authLoginField && authPasswordField &&
+
+ if (authLoginField && authPasswordField &&
authLoginField.value && authPasswordField.value) {
hasAuth = true;
break;
@@ -141,7 +141,7 @@ document.addEventListener('alpine:init', () => {
}
}
}
-
+
// If no authentication is set, warn the user
if (!hasAuth) {
const proceed = confirm(
@@ -152,7 +152,7 @@ document.addEventListener('alpine:init', () => {
"before creating a public tunnel.\n\n" +
"Do you want to proceed anyway?"
);
-
+
if (!proceed) {
return; // User cancelled
}
@@ -161,13 +161,16 @@ document.addEventListener('alpine:init', () => {
console.error("Error checking authentication status:", error);
// Continue anyway if we can't check auth status
}
-
+
this.isLoading = true;
this.loadingText = 'Creating tunnel...';
+ // Get provider from the parent settings modal scope
+ const modalEl = document.getElementById('settingsModal');
+ const modalAD = Alpine.$data(modalEl);
// Use the local provider setting
const provider = this.provider || 'serveo'; // Default to serveo if not set
-
+
// Change create button appearance
const createButton = document.querySelector('.tunnel-actions .btn-ok');
if (createButton) {
@@ -175,7 +178,7 @@ document.addEventListener('alpine:init', () => {
createButton.disabled = true;
createButton.classList.add('creating');
}
-
+
try {
// Call the backend API to create a tunnel
const response = await fetchApi('/tunnel_proxy', {
@@ -183,31 +186,31 @@ document.addEventListener('alpine:init', () => {
headers: {
'Content-Type': 'application/json',
},
- body: JSON.stringify({
+ body: JSON.stringify({
action: 'create',
provider: provider
// port: window.location.port || (window.location.protocol === 'https:' ? 443 : 80)
}),
});
-
+
const data = await response.json();
-
+
if (data.success && data.tunnel_url) {
// Store the tunnel URL in localStorage for persistence
localStorage.setItem('agent_zero_tunnel_url', data.tunnel_url);
-
+
this.tunnelLink = data.tunnel_url;
this.linkGenerated = true;
-
+
// Show success message to confirm creation
- window.toast("Tunnel created successfully", "success", 3000);
+ window.toastFrontendInfo("Tunnel created successfully", "Tunnel Status");
} else {
// The tunnel might still be starting up, check again after a delay
this.loadingText = 'Tunnel creation taking longer than expected...';
-
+
// Wait for 5 seconds and check if the tunnel is running
await new Promise(resolve => setTimeout(resolve, 5000));
-
+
// Check if tunnel is running now
try {
const statusResponse = await fetchApi('/tunnel_proxy', {
@@ -217,33 +220,33 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({ action: 'get' }),
});
-
+
const statusData = await statusResponse.json();
-
+
if (statusData.success && statusData.tunnel_url) {
// Tunnel is now running, we can update the UI
localStorage.setItem('agent_zero_tunnel_url', statusData.tunnel_url);
this.tunnelLink = statusData.tunnel_url;
this.linkGenerated = true;
- window.toast("Tunnel created successfully", "success", 3000);
+ window.toastFrontendInfo("Tunnel created successfully", "Tunnel Status");
return;
}
} catch (statusError) {
console.error("Error checking tunnel status:", statusError);
}
-
+
// If we get here, the tunnel really failed to start
const errorMessage = data.message || "Failed to create tunnel. Please try again.";
- window.toast(errorMessage, "error", 5000);
+ window.toastFrontendError(errorMessage, "Tunnel Error");
console.error("Tunnel creation failed:", data);
}
} catch (error) {
- window.toast("Error creating tunnel", "error", 5000);
+ window.toastFrontendError("Error creating tunnel", "Tunnel Error");
console.error("Error creating tunnel:", error);
} finally {
this.isLoading = false;
this.loadingText = '';
-
+
// Reset create button if it's still in the DOM
const createButton = document.querySelector('.tunnel-actions .btn-ok');
if (createButton) {
@@ -258,8 +261,8 @@ document.addEventListener('alpine:init', () => {
if (confirm("Are you sure you want to stop the tunnel? The URL will no longer be accessible.")) {
this.isLoading = true;
this.loadingText = 'Stopping tunnel...';
-
-
+
+
try {
// Call the backend to stop the tunnel
const response = await fetchApi('/tunnel_proxy', {
@@ -269,30 +272,30 @@ document.addEventListener('alpine:init', () => {
},
body: JSON.stringify({ action: 'stop' }),
});
-
+
const data = await response.json();
-
+
if (data.success) {
// Clear the stored URL
localStorage.removeItem('agent_zero_tunnel_url');
-
+
// Update UI state
this.tunnelLink = '';
this.linkGenerated = false;
-
- window.toast("Tunnel stopped successfully", "success", 3000);
+
+ window.toastFrontendInfo("Tunnel stopped successfully", "Tunnel Status");
} else {
- window.toast("Failed to stop tunnel", "error", 3000);
-
+ window.toastFrontendError("Failed to stop tunnel", "Tunnel Error");
+
// Reset stop button
stopButton.innerHTML = originalStopContent;
stopButton.disabled = false;
stopButton.classList.remove('stopping');
}
} catch (error) {
- window.toast("Error stopping tunnel", "error", 3000);
+ window.toastFrontendError("Error stopping tunnel", "Tunnel Error");
console.error("Error stopping tunnel:", error);
-
+
// Reset stop button
stopButton.innerHTML = originalStopContent;
stopButton.disabled = false;
@@ -306,19 +309,19 @@ document.addEventListener('alpine:init', () => {
copyToClipboard() {
if (!this.tunnelLink) return;
-
+
const copyButton = document.querySelector('.copy-link-button');
const originalContent = copyButton.innerHTML;
-
+
navigator.clipboard.writeText(this.tunnelLink)
.then(() => {
// Update button to show success state
copyButton.innerHTML = '<i class="fas fa-check"></i> Copied!';
copyButton.classList.add('copy-success');
-
+
// Show toast notification
- window.toast("Tunnel URL copied to clipboard!", "success", 3000);
-
+ window.toastFrontendInfo("Tunnel URL copied to clipboard!", "Clipboard");
+
// Reset button after 2 seconds
setTimeout(() => {
copyButton.innerHTML = originalContent;
@@ -327,12 +330,12 @@ document.addEventListener('alpine:init', () => {
})
.catch(err => {
console.error('Failed to copy URL: ', err);
- window.toast("Failed to copy tunnel URL", "error", 3000);
-
+ window.toastFrontendError("Failed to copy tunnel URL", "Clipboard Error");
+
// Show error state
copyButton.innerHTML = '<i class="fas fa-times"></i> Failed';
copyButton.classList.add('copy-error');
-
+
// Reset button after 2 seconds
setTimeout(() => {
copyButton.innerHTML = originalContent;
@@ -341,4 +344,4 @@ document.addEventListener('alpine:init', () => {
});
}
}));
-});
\ No newline at end of file
+});