Agent Zero AI framework
notifications redesign
frdele37e7139cf3d
diff --git a/docs/designs/backup-specification-frontend.md b/docs/designs/backup-specification-frontend.mdindex 8f1c99c18..26dd93c6d 100644--- a/docs/designs/backup-specification-frontend.md+++ b/docs/designs/backup-specification-frontend.md@@ -820,12 +820,12 @@ const model = {if (response.ok) {const blob = await response.blob();- const url = window.URL.createObjectURL(blob);+ const url = globalThis.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = `${backupName}.zip`;a.click();- window.URL.revokeObjectURL(url);+ globalThis.URL.revokeObjectURL(url);}} catch (error) {console.error('Download error:', error);@@ -1298,9 +1298,9 @@ Use existing `openModal()` and `closeModal()` functions from the global modal syUse existing Agent Zero toast system for consistent user feedback:```javascript// Use established toast patterns-window.toast("Backup created successfully", "success");-window.toast("Restore completed", "success");-window.toast("Error creating backup", "error");+globalThis.toast("Backup created successfully", "success");+globalThis.toast("Restore completed", "success");+globalThis.toast("Error creating backup", "error");```#### ACE Editor Integration@@ -1417,10 +1417,10 @@ formatTimestamp(timestamp) {// Use existing error handling patternstry {const result = await backupOperation();- window.toast("Operation completed successfully", "success");+ globalThis.toast("Operation completed successfully", "success");} catch (error) {console.error('Backup error:', error);- window.toast(`Error: ${error.message}`, "error");+ globalThis.toast(`Error: ${error.message}`, "error");}```diff --git a/webui/components/notifications/notification-store.js b/webui/components/notifications/notification-store.jsindex 869e54f41..8d4f6823c 100644--- a/webui/components/notifications/notification-store.js+++ b/webui/components/notifications/notification-store.js@@ -2,557 +2,643 @@ 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() {- 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;-- const isFirstLoad = !this.lastNotificationGuid && pollData.notifications_guid;-- // 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 unread 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();+ notifications: [],+ loading: false,+ lastNotificationVersion: 0,+ lastNotificationGuid: "",+ unreadCount: 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.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 || "";+ }- // 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) {- // 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);- }- }+ // 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);- // 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);- }+ // Add new unread notifications to toast stack+ if (isNew && !notification.read) {+ this.addToToastStack(notification);}+ });+ }- // Set auto-dismiss timer- toast.autoRemoveTimer = setTimeout(() => {- this.removeFromToastStack(toast.toastId);- }, notification.display_time * 1000);- },-- // 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);- }- },-- // NEW: Clear entire toast stack- clearToastStack() {- this.toastStack.forEach(toast => {- if (toast.autoRemoveTimer) {- clearTimeout(toast.autoRemoveTimer);- }- });- this.toastStack = [];- },-- // 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) {- 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- }+ // 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) {+ // 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);+ }+ }- // Enhanced: Mark all as read and clear toast stack- async markAllAsRead() {- const unreadNotifications = this.notifications.filter(n => !n.read);- if (unreadNotifications.length === 0) return;+ // 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);+ }+ }- // 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);+ // Set auto-dismiss timer+ toast.autoRemoveTimer = setTimeout(() => {+ this.removeFromToastStack(toast.toastId);+ }, notification.display_time * 1000);+ },++ // 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);+ }+ },++ // NEW: Clear entire toast stack+ clearToastStack() {+ this.toastStack.forEach((toast) => {+ if (toast.autoRemoveTimer) {+ clearTimeout(toast.autoRemoveTimer);+ }+ });+ this.toastStack = [];+ },++ // 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);}- },-- // 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- },-- // 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;+ return false;+ }+ return true;+ });+ },++ // NEW: Handle toast click (opens modal)+ async handleToastClick(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() {+ const unread = this.notifications.filter((n) => !n.read).length;+ if (this.unreadCount !== unread) this.unreadCount = unread;+ },++ // 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],});- },-- // 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 (Google Material Icons)- getNotificationIcon(type) {- const icons = {- info: "info",- success: "check_circle",- warning: "warning",- error: "error",- progress: "hourglass_empty"- };- const iconName = icons[type] || "info";- return `<span class="material-symbols-outlined">${iconName}</span>`;- },-- // Create notification via backend (will appear via polling)- 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,- group: group- });-- if (response.success) {- 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, group = "") {- return await this.createNotification('info', message, title, detail, display_time, group);- },-- 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, group = "") {- return await this.createNotification('warning', message, title, detail, display_time, group);- },-- 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, group = "") {- return await this.createNotification('progress', message, title, detail, display_time, group);- },-- // 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();- },-- // 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)}`,- type: type,- title: title,- message: message,- detail: "",- timestamp: timestamp,- display_time: display_time,- read: false,- 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,- 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);- }- }+ } 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);+ }+ },- // Set auto-dismiss timer- toast.autoRemoveTimer = setTimeout(() => {- this.removeFromToastStack(toast.toastId);- }, notification.display_time * 1000);-- return notification.id;- },-- // 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');- }+ // Clear all notifications+ async clearAll() {+ this.notifications = [];+ this.unreadCount = 0;+ this.clearToastStack(); // Also clear toast stack- // Fallback to frontend-only toast- return this.addFrontendToastOnly(type, message, title, display_time, group);- },+ // Note: We don't sync clear with backend as notifications are stored in memory only+ },- // 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);- },+ // Get notifications by type+ getNotificationsByType(type) {+ return this.notifications.filter((n) => n.type === type);+ },- async frontendWarning(message, title = "Warning", display_time = 5, group = "") {- return await this.addFrontendToast('warning', message, title, display_time, group);- },+ // Get notifications for display: ALL unread + read from last 5 minutes+ getDisplayNotifications() {+ const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);- async frontendInfo(message, title = "Info", display_time = 3, group = "") {- return await this.addFrontendToast('info', message, title, display_time, group);+ 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();}-};--// Create and export the store-const store = createStore("notificationStore", model);--// NEW: Global function for frontend error toasts (replaces toastFetchError)-window.toastFrontendError = async function(message, title = "Connection Error", display_time = 8, group = "") {- if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {- try {- return await window.Alpine.store('notificationStore').addFrontendToast('error', message, title, display_time, group);- } 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);+ },++ // 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 (Google Material Icons)+ getNotificationIcon(type) {+ const icons = {+ info: "info",+ success: "check_circle",+ warning: "warning",+ error: "error",+ progress: "hourglass_empty",+ };+ const iconName = icons[type] || "info";+ return `<span class="material-symbols-outlined">${iconName}</span>`;+ },++ // Create notification via backend (will appear via polling)+ async createNotification(+ type,+ message,+ title = "",+ detail = "",+ display_time = 3,+ group = ""+ ) {+ try {+ const response = await globalThis.sendJsonData("/notification_create", {+ type: type,+ message: message,+ title: title,+ detail: detail,+ display_time: display_time,+ group: group,+ });++ if (response.success) {+ 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, group = "") {+ return await this.createNotification(+ "info",+ message,+ title,+ detail,+ display_time,+ group+ );+ },++ 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,+ group = ""+ ) {+ return await this.createNotification(+ "warning",+ message,+ title,+ detail,+ display_time,+ group+ );+ },++ 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,+ group = ""+ ) {+ return await this.createNotification(+ "progress",+ message,+ title,+ detail,+ display_time,+ group+ );+ },++ // 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();+ },++ // 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 globalThis.getConnectionStatus === "function"+ ? globalThis.getConnectionStatus()+ : undefined;++ // If polling status is explicitly false, respect that+ if (pollingStatus === false) {+ return false;}-};-// NEW: Additional global convenience functions-window.toastFrontendWarning = async function(message, title = "Warning", display_time = 5, group = "") {- if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {- try {- return await window.Alpine.store('notificationStore').addFrontendToast('warning', message, title, display_time, group);- } catch (error) {- console.error('Failed to create frontend warning notification:', error);- console.warn('Frontend Warning:', title, '-', message);- return null;+ // 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)}`,+ type: type,+ title: title,+ message: message,+ detail: "",+ timestamp: timestamp,+ display_time: display_time,+ read: false,+ 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);}- } else {- console.warn('Frontend Warning:', title, '-', message);- return null;+ this.toastStack.splice(existingToastIndex, 1);+ }}-};-window.toastFrontendInfo = async function(message, title = "Info", display_time = 3, group = "") {- if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {- try {- return await window.Alpine.store('notificationStore').addFrontendToast('info', message, title, display_time, group);- } 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;+ // 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);+ }}-};-window.toastFrontendSuccess = async function(message, title = "Success", display_time = 3, group = "") {- if (window.Alpine && window.Alpine.store && window.Alpine.store('notificationStore')) {- try {- return await window.Alpine.store('notificationStore').addFrontendToast('success', message, title, display_time, group);- } catch (error) {- console.error('Failed to create frontend success notification:', error);- console.log('Frontend Success:', title, '-', message);- return null;+ // Set auto-dismiss timer+ toast.autoRemoveTimer = setTimeout(() => {+ this.removeFromToastStack(toast.toastId);+ }, notification.display_time * 1000);++ return notification.id;+ },++ // 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('Frontend Success:', title, '-', message);- return null;+ console.log("Backend disconnected, showing as frontend-only toast");}++ // Fallback to frontend-only toast+ return this.addFrontendToastOnly(type, message, title, display_time, group);+ },++ // 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+ );+ },++ 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+ );+ },++ async frontendSuccess(+ message,+ title = "Success",+ display_time = 3,+ group = ""+ ) {+ return await this.addFrontendToast(+ "success",+ message,+ title,+ display_time,+ group+ );+ },};+// Create and export the store+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);+globalThis.toastFrontendWarning = store.frontendWarning.bind(store);+globalThis.toastFrontendError = store.frontendError.bind(store);diff --git a/webui/components/notifications/notification-toast-stack.html b/webui/components/notifications/notification-toast-stack.htmlindex 4f37c6d5a..3d9a540e0 100644--- a/webui/components/notifications/notification-toast-stack.html+++ b/webui/components/notifications/notification-toast-stack.html@@ -33,9 +33,9 @@<div class="toast-message"x-text="toast.message"></div>- <div class="toast-timestamp"+ <!-- <div class="toast-timestamp"x-text="$store.notificationStore.formatTimestamp(toast.timestamp)">- </div>+ </div> --></div><!-- Toast Dismiss -->@@ -53,16 +53,17 @@<style>/* Toast Stack Container */.toast-stack-container {- position: fixed;- bottom: 20px;- right: 20px;+ position: absolute;+ bottom: 5px; /* Spacing from the bottom of the zero-height container */+ padding-right: 5px;z-index: 1500;display: flex;- flex-direction: column;+ flex-direction: column-reverse; /* Stack toasts upwards */gap: 8px;pointer-events: none;max-width: 400px;- width: 100%;+ width: calc(100% - 10px);+ align-items: flex-end;}/* Individual Toast Items */@@ -72,20 +73,18 @@align-items: flex-start;gap: 12px;padding: 16px;- background: rgba(0, 0, 0, 0.9);- border: 1px solid rgba(255, 255, 255, 0.2);+ background: var(--color-panel);+ border: 1px solid var(--color-border);border-radius: 8px;cursor: pointer;transition: all 0.2s ease;- backdrop-filter: blur(10px);+ /* 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);}@@ -93,34 +92,33 @@/* Toast Type Styling */.toast-item.notification-info {border-left: 4px solid #2196F3;- background: rgba(33, 150, 243, 0.1);+ /* background: rgba(33, 150, 243, 0.1); */}.toast-item.notification-success {border-left: 4px solid #4CAF50;- background: rgba(76, 175, 80, 0.1);+ /* background: rgba(76, 175, 80, 0.1); */}.toast-item.notification-warning {border-left: 4px solid #FF9800;- background: rgba(255, 152, 0, 0.1);+ /* background: rgba(255, 152, 0, 0.1); */}.toast-item.notification-error {border-left: 4px solid #F44336;- background: rgba(244, 67, 54, 0.1);+ /* background: rgba(244, 67, 54, 0.1); */}.toast-item.notification-progress {border-left: 4px solid #9C27B0;- background: rgba(156, 39, 176, 0.1);+ /* 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;@@ -155,7 +153,7 @@/* Toast Dismiss */.toast-dismiss {- background: rgba(255, 255, 255, 0.1);+ background: transparent; /* No background by default */border: none;border-radius: 4px;color: var(--color-text);@@ -163,16 +161,12 @@padding: 4px 6px;font-size: 0.8rem;transition: all 0.2s ease;- opacity: 0;- }-- .toast-item:hover .toast-dismiss {- opacity: 1;+ opacity: 1; /* Always visible */}.toast-dismiss:hover {- background: rgba(255, 255, 255, 0.2);- color: #fff;+ background: var(--color-panel);+ color: var(--color-primary);}/* Toast Animations */@@ -188,25 +182,6 @@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) {diff --git a/webui/components/settings/backup/backup-store.js b/webui/components/settings/backup/backup-store.jsindex 328fd3bb1..dcbff9a4e 100644--- a/webui/components/settings/backup/backup-store.js+++ b/webui/components/settings/backup/backup-store.js@@ -1,9 +1,9 @@import { createStore } from "/js/AlpineStore.js";// Global function references-const sendJsonData = window.sendJsonData;-const toast = window.toast;-const fetchApi = window.fetchApi;+const sendJsonData = globalThis.sendJsonData;+const toast = globalThis.toast;+const fetchApi = globalThis.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.diff --git a/webui/index.css b/webui/index.cssindex 8fbf97739..e337a4798 100644--- a/webui/index.css+++ b/webui/index.css@@ -68,6 +68,21 @@hue-rotate(177deg) brightness(87%) contrast(85%);}+/* Light mode class */+.light-mode {+ --color-background: var(--color-background-light);+ --color-text: var(--color-text-light);+ --color-primary: var(--color-primary-light);+ --color-secondary: var(--color-secondary-light);+ --color-accent: var(--color-accent-light);+ --color-message-bg: var(--color-message-bg-light);+ --color-message-text: var(--color-message-text-light);+ --color-panel: var(--color-panel-light);+ --color-border: var(--color-border-light);+ --color-input: var(--color-input-light);+ --color-input-focus: var(--color-input-focus-light);+}+/* Reset and Base Styles */body,html {@@ -402,6 +417,7 @@ img {}#time-date-container {+ z-index: 1000;position: fixed;right: var(--spacing-md);display: flex;@@ -1687,22 +1703,6 @@ a:active {color: inherit;}-/* Light mode class */-.light-mode {- --color-background: var(--color-background-light);- --color-text: var(--color-text-light);- --color-primary: var(--color-primary-light);- --color-secondary: var(--color-secondary-light);- --color-accent: var(--color-accent-light);- --color-message-bg: var(--color-message-bg-light);- --color-message-text: var(--color-message-text-light);- --color-panel: var(--color-panel-light);- --color-border: var(--color-border-light);- --color-input: var(--color-input-light);- --color-input-focus: var(--color-input-focus-light);-}--.light-mode .connected {color: #4caf50;diff --git a/webui/index.html b/webui/index.htmlindex 0dd1fd49b..ea16e736d 100644--- a/webui/index.html+++ b/webui/index.html@@ -27,7 +27,7 @@<script src="vendor/flatpickr/flatpickr.min.js"></script><script>- window.safeCall = function (name, ...args) {+ globalThis.safeCall = function (name, ...args) {if (window[name]) window[name](...args)}</script>@@ -35,7 +35,7 @@<!-- Pre-initialize schedulerSettings to ensure Alpine doesn't miss it --><script>// Pre-define schedulerSettings skeleton to ensure it's available to Alpine- window.schedulerSettings = function() {+ globalThis.schedulerSettings = function() {return {tasks: [],isLoading: true,@@ -214,7 +214,7 @@tasks: [],selected: '',openTaskDetail(taskId) {- window.openTaskDetail(taskId);+ globalThis.openTaskDetail(taskId);}}"style="display: none;">@@ -285,7 +285,7 @@<span>Autoscroll</span><label class="switch"><input id="auto-scroll-switch" type="checkbox" x-model="autoScroll"- x-effect="window.safeCall('toggleAutoScroll',autoScroll)">+ x-effect="globalThis.safeCall('toggleAutoScroll',autoScroll)"><span class="slider"></span></label></li>@@ -309,7 +309,7 @@<span>Show thoughts</span><label class="switch"><input type="checkbox" x-model="showThoughts"- x-effect="window.safeCall('toggleThoughts',showThoughts)">+ x-effect="globalThis.safeCall('toggleThoughts',showThoughts)"><span class="slider"></span></label></li>@@ -317,7 +317,7 @@<span>Show JSON</span><label class="switch"><input type="checkbox" x-model="showJson"- x-effect="window.safeCall('toggleJson',showJson)">+ x-effect="globalThis.safeCall('toggleJson',showJson)"><span class="slider"></span></label></li>@@ -325,7 +325,7 @@<span>Show utility messages</span><label class="switch"><input type="checkbox" x-model="showUtils"- x-effect="window.safeCall('toggleUtils',showUtils)">+ x-effect="globalThis.safeCall('toggleUtils',showUtils)"><span class="slider"></span></label></li>@@ -360,7 +360,9 @@</div><!-- NEW: Toast Stack Component -->- <x-component path="notifications/notification-toast-stack.html"></x-component>+ <div style="position: relative; height: 0;">+ <x-component path="notifications/notification-toast-stack.html"></x-component>+ </div><div id="toast" class="toast"><div class="toast__content">@@ -485,7 +487,7 @@<p>Files</p></button>- <button class="text-button" id="history_inspect" @click="window.openHistoryModal()">+ <button class="text-button" id="history_inspect" @click="globalThis.openHistoryModal()"><svg xmlns="http://www.w3.org/2000/svg" viewBox="5 10 85 85"><path fill="currentColor"d="m59.572,57.949c-.41,0-.826-.105-1.207-.325l-9.574-5.528c-.749-.432-1.21-1.231-1.21-2.095v-14.923c0-1.336,1.083-2.419,2.419-2.419s2.419,1.083,2.419,2.419v13.526l8.364,4.829c1.157.668,1.554,2.148.886,3.305-.448.776-1.261,1.21-2.097,1.21Zm30.427-7.947c0,10.684-4.161,20.728-11.716,28.283-6.593,6.59-15.325,10.69-24.59,11.544-1.223.113-2.448.169-3.669.169-7.492,0-14.878-2.102-21.22-6.068l-15.356,5.733c-.888.331-1.887.114-2.557-.556s-.887-1.669-.556-2.557l5.733-15.351c-4.613-7.377-6.704-16.165-5.899-24.891.854-9.266,4.954-17.998,11.544-24.588,7.555-7.555,17.6-11.716,28.285-11.716s20.73,4.161,28.285,11.716c7.555,7.555,11.716,17.599,11.716,28.283Zm-15.137-24.861c-13.71-13.71-36.018-13.71-49.728,0-11.846,11.846-13.682,30.526-4.365,44.417.434.647.53,1.464.257,2.194l-4.303,11.523,11.528-4.304c.274-.102.561-.153.846-.153.474,0,.944.139,1.348.41,13.888,9.315,32.568,7.479,44.417-4.365,13.707-13.708,13.706-36.014,0-49.723Zm-24.861-4.13c-15.989,0-28.996,13.006-28.996,28.992s13.008,28.992,28.996,28.992c1.336,0,2.419-1.083,2.419-2.419s-1.083-2.419-2.419-2.419c-13.32,0-24.157-10.835-24.157-24.153s10.837-24.153,24.157-24.153,24.153,10.835,24.153,24.153c0,1.336,1.083,2.419,2.419,2.419s2.419-1.083,2.419-2.419c0-15.986-13.006-28.992-28.992-28.992Zm25.041,33.531c-1.294.347-2.057,1.673-1.71,2.963.343,1.289,1.669,2.057,2.963,1.71,1.289-.343,2.053-1.669,1.71-2.963-.347-1.289-1.673-2.057-2.963-1.71Zm-2.03,6.328c-1.335,0-2.419,1.084-2.419,2.419s1.084,2.419,2.419,2.419,2.419-1.084,2.419-2.419-1.084-2.419-2.419-2.419Zm-3.598,5.587c-1.289-.347-2.615.416-2.963,1.71-.343,1.289.421,2.615,1.71,2.963,1.294.347,2.62-.421,2.963-1.71.347-1.294-.416-2.62-1.71-2.963Zm-4.919,4.462c-1.157-.667-2.638-.27-3.306.887-.667,1.157-.27,2.638.887,3.305,1.157.668,2.638.27,3.306-.887.667-1.157.27-2.638-.887-3.306Zm-9.327,3.04c-.946.946-.946,2.478,0,3.42.942.946,2.473.946,3.42,0,.946-.942.946-2.473,0-3.42-.946-.946-2.478-.946-3.42,0Z">@@ -494,7 +496,7 @@<p>History</p></button>- <button class="text-button" id="ctx_window" @click="window.openCtxWindowModal()">+ <button class="text-button" id="ctx_window" @click="globalThis.openCtxWindowModal()"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="17 15 70 70" fill="currentColor"><pathd="m63 25c1.1016 0 2-0.89844 2-2s-0.89844-2-2-2h-26c-1.1016 0-2 0.89844-2 2s0.89844 2 2 2z">diff --git a/webui/index.js b/webui/index.jsindex 95b4d0e53..87a355eb0 100644--- a/webui/index.js+++ b/webui/index.js@@ -4,8 +4,9 @@ import * as css from "/js/css.js";import { sleep } from "/js/sleep.js";import { store as attachmentsStore } from "/components/chat/attachments/attachmentsStore.js";import { store as speechStore } from "/components/chat/speech/speech-store.js";+import { store as notificationStore } from "/components/notifications/notification-store.js";-window.fetchApi = api.fetchApi; // TODO - backward compatibility for non-modular scripts, remove once refactored to alpine+globalThis.fetchApi = api.fetchApi; // TODO - backward compatibility for non-modular scripts, remove once refactored to alpineconst leftPanel = document.getElementById("left-panel");const rightPanel = document.getElementById("right-panel");@@ -69,8 +70,8 @@ function handleResize() {}}-window.addEventListener("load", handleResize);-window.addEventListener("resize", handleResize);+globalThis.addEventListener("load", handleResize);+globalThis.addEventListener("resize", handleResize);document.addEventListener("DOMContentLoaded", () => {const overlay = document.getElementById("sidebar-overlay");@@ -184,7 +185,7 @@ function toastFetchError(text, error) {).catch((e) => console.error("Failed to show connection error toast:", e));}}-window.toastFetchError = toastFetchError;+globalThis.toastFetchError = toastFetchError;chatInput.addEventListener("keydown", (e) => {if (e.key === "Enter" && !e.shiftKey) {@@ -241,7 +242,7 @@ function setMessage(id, type, heading, content, temp, kvps = null) {return result;}-window.loadKnowledge = async function () {+globalThis.loadKnowledge = async function () {const input = document.createElement("input");input.type = "file";input.accept = ".txt,.pdf,.csv,.html,.json,.md";@@ -300,7 +301,7 @@ export const sendJsonData = async function (url, data) {// const jsonResponse = await response.json();// return jsonResponse;};-window.sendJsonData = sendJsonData;+globalThis.sendJsonData = sendJsonData;function generateGUID() {return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {@@ -316,7 +317,7 @@ function getConnectionStatus() {function setConnectionStatus(connected) {connectionStatus = connected;- if (window.Alpine && timeDate) {+ if (globalThis.Alpine && timeDate) {const statusIconEl = timeDate.querySelector(".status-icon");if (statusIconEl) {const statusIcon = Alpine.$data(statusIconEl);@@ -388,7 +389,7 @@ async function poll() {notificationStore.updateFromPoll(response);//set ui model vars from backend- if (window.Alpine && inputSection) {+ if (globalThis.Alpine && inputSection) {const inputAD = Alpine.$data(inputSection);if (inputAD) {inputAD.paused = response.paused;@@ -401,7 +402,7 @@ async function poll() {// Update chats list and sort by created_at time (newer first)let chatsAD = null;let contexts = response.contexts || [];- if (window.Alpine && chatsSection) {+ if (globalThis.Alpine && chatsSection) {chatsAD = Alpine.$data(chatsSection);if (chatsAD) {chatsAD.contexts = contexts.sort(@@ -412,7 +413,7 @@ async function poll() {// Update tasks list and sort by creation time (newer first)const tasksSection = document.getElementById("tasks-section");- if (window.Alpine && tasksSection) {+ if (globalThis.Alpine && tasksSection) {const tasksAD = Alpine.$data(tasksSection);if (tasksAD) {let tasks = response.tasks || [];@@ -572,15 +573,15 @@ function updateProgress(progress, active) {}}-window.pauseAgent = async function (paused) {+globalThis.pauseAgent = async function (paused) {try {const resp = await sendJsonData("/pause", { paused: paused, context });} catch (e) {- window.toastFetchError("Error pausing agent", e);+ globalThis.toastFetchError("Error pausing agent", e);}};-window.resetChat = async function (ctxid = null) {+globalThis.resetChat = async function (ctxid = null) {try {const resp = await sendJsonData("/chat_reset", {context: ctxid === null ? context : ctxid,@@ -588,20 +589,20 @@ window.resetChat = async function (ctxid = null) {resetCounter++;if (ctxid === null) updateAfterScroll();} catch (e) {- window.toastFetchError("Error resetting chat", e);+ globalThis.toastFetchError("Error resetting chat", e);}};-window.newChat = async function () {+globalThis.newChat = async function () {try {setContext(generateGUID());updateAfterScroll();} catch (e) {- window.toastFetchError("Error creating new chat", e);+ globalThis.toastFetchError("Error creating new chat", e);}};-window.killChat = async function (id) {+globalThis.killChat = async function (id) {if (!id) {console.error("No chat ID provided for deletion");return;@@ -638,7 +639,7 @@ window.killChat = async function (id) {toast("Chat deleted successfully", "success");} catch (e) {console.error("Error deleting chat:", e);- window.toastFetchError("Error deleting chat", e);+ globalThis.toastFetchError("Error deleting chat", e);}};@@ -700,7 +701,7 @@ function ensureProperTabSelection(contextId) {return false;}-window.selectChat = async function (id) {+globalThis.selectChat = async function (id) {if (id === context) return; //already selected// Check if we need to switch tabs based on the context type@@ -751,7 +752,7 @@ export const setContext = function (id) {chatHistory.innerHTML = "";// Update both selected states- if (window.Alpine) {+ if (globalThis.Alpine) {if (chatsSection) {const chatsAD = Alpine.$data(chatsSection);if (chatsAD) chatsAD.selected = id;@@ -774,15 +775,15 @@ export const getChatBasedId = function (id) {return context + "-" + resetCounter + "-" + id;};-window.toggleAutoScroll = async function (_autoScroll) {+globalThis.toggleAutoScroll = async function (_autoScroll) {autoScroll = _autoScroll;};-window.toggleJson = async function (showJson) {+globalThis.toggleJson = async function (showJson) {css.toggleCssProperty(".msg-json", "display", showJson ? "block" : "none");};-window.toggleThoughts = async function (showThoughts) {+globalThis.toggleThoughts = async function (showThoughts) {css.toggleCssProperty(".msg-thoughts","display",@@ -790,7 +791,7 @@ window.toggleThoughts = async function (showThoughts) {);};-window.toggleUtils = async function (showUtils) {+globalThis.toggleUtils = async function (showUtils) {css.toggleCssProperty(".message-util","display",@@ -798,7 +799,7 @@ window.toggleUtils = async function (showUtils) {);};-window.toggleDarkMode = function (isDark) {+globalThis.toggleDarkMode = function (isDark) {if (isDark) {document.body.classList.remove("light-mode");document.body.classList.add("dark-mode");@@ -810,13 +811,13 @@ window.toggleDarkMode = function (isDark) {localStorage.setItem("darkMode", isDark);};-window.toggleSpeech = function (isOn) {+globalThis.toggleSpeech = function (isOn) {console.log("Speech:", isOn);localStorage.setItem("speech", isOn);if (!isOn) speechStore.stopAudio();};-window.nudge = async function () {+globalThis.nudge = async function () {try {const resp = await sendJsonData("/nudge", { ctxid: getContext() });} catch (e) {@@ -824,7 +825,7 @@ window.nudge = async function () {}};-window.restart = async function () {+globalThis.restart = async function () {try {if (!getConnectionStatus()) {await toastFrontendError(@@ -872,7 +873,7 @@ document.addEventListener("DOMContentLoaded", () => {toggleDarkMode(isDarkMode);});-window.loadChats = async function () {+globalThis.loadChats = async function () {try {const fileContents = await readJsonFiles();const response = await sendJsonData("/chat_load", { chats: fileContents });@@ -896,7 +897,7 @@ window.loadChats = async function () {}};-window.saveChat = async function () {+globalThis.saveChat = async function () {try {const response = await sendJsonData("/chat_export", { ctxid: context });@@ -1007,12 +1008,12 @@ function toast(text, type = "info", timeout = 5000) {}}-window.toast = toast;+globalThis.toast = toast;// OLD: hideToast function removed - now using new notification systemfunction scrollChanged(isAtBottom) {- if (window.Alpine && autoScrollSwitch) {+ if (globalThis.Alpine && autoScrollSwitch) {const inputAS = Alpine.$data(autoScrollSwitch);if (inputAS) {inputAS.autoScroll = isAtBottom;@@ -1124,7 +1125,7 @@ function activateTab(tabName) {chatsSection.style.display = "";// Get the available contexts from Alpine.js data- const chatsAD = window.Alpine ? Alpine.$data(chatsSection) : null;+ const chatsAD = globalThis.Alpine ? Alpine.$data(chatsSection) : null;const availableContexts = chatsAD?.contexts || [];// Restore previous chat selection@@ -1148,7 +1149,7 @@ function activateTab(tabName) {tasksSection.style.flexDirection = "column";// Get the available tasks from Alpine.js data- const tasksAD = window.Alpine ? Alpine.$data(tasksSection) : null;+ const tasksAD = globalThis.Alpine ? Alpine.$data(tasksSection) : null;const availableTasks = tasksAD?.tasks || [];// Restore previous task selection@@ -1200,7 +1201,7 @@ function initializeActiveTab() {// Open the scheduler detail view for a specific taskfunction openTaskDetail(taskId) {// Wait for Alpine.js to be fully loaded- if (window.Alpine) {+ if (globalThis.Alpine) {// Get the settings modal button and click it to ensure all init logic happensconst settingsButton = document.getElementById("settings");if (settingsButton) {@@ -1215,7 +1216,7 @@ function openTaskDetail(taskId) {}// Get the Alpine.js data for the modal- const modalData = window.Alpine ? Alpine.$data(modalEl) : null;+ const modalData = globalThis.Alpine ? Alpine.$data(modalEl) : null;// Use a timeout to ensure the modal is fully renderedsetTimeout(() => {@@ -1234,7 +1235,7 @@ function openTaskDetail(taskId) {}// Get the Alpine.js data for the scheduler component- const schedulerData = window.Alpine+ const schedulerData = globalThis.Alpine? Alpine.$data(schedulerComponent): null;@@ -1253,4 +1254,4 @@ function openTaskDetail(taskId) {}// Make the function available globally-window.openTaskDetail = openTaskDetail;+globalThis.openTaskDetail = openTaskDetail;