Agent Zero AI framework
improvements to drag drop, image modal
decic6ba915b16e7
diff --git a/webui/components/chat/attachments/attachmentsStore.js b/webui/components/chat/attachments/attachmentsStore.jsindex 7aa60b1a0..569b6e295 100644--- a/webui/components/chat/attachments/attachmentsStore.js+++ b/webui/components/chat/attachments/attachmentsStore.js@@ -1,17 +1,28 @@+console.log('attachmentsStore.js module loading...');import { createStore } from "/js/AlpineStore.js";+console.log('attachmentsStore.js module loaded, creating model...');const model = {// State propertiesattachments: [],hasAttachments: false,dragDropOverlayVisible: false,+ // Image modal properties+ currentImageUrl: null,+ currentImageName: null,+ imageLoaded: false,+ imageError: false,+ zoomLevel: 1,+// Initialize the storeasync initialize() {+ console.log('Initializing attachments store...');// Setup event listeners for drag and dropthis.setupDragDropHandlers();// Setup paste event listener for clipboard imagesthis.setupPasteHandler();+ console.log('Attachments store initialized successfully');},// Basic attachment management methods@@ -60,6 +71,7 @@ const model = {// Setup drag and drop event handlerssetupDragDropHandlers() {+ console.log('Setting up drag and drop handlers...');let dragCounter = 0;// Prevent default drag behaviors@@ -72,8 +84,10 @@ const model = {// Handle drag enterdocument.addEventListener('dragenter', (e) => {+ console.log('Drag enter detected');dragCounter++;if (dragCounter === 1) {+ console.log('Showing drag drop overlay');this.showDragDropOverlay();}}, false);@@ -88,6 +102,7 @@ const model = {// Handle dropdocument.addEventListener('drop', (e) => {+ console.log('Drop detected with files:', e.dataTransfer.files.length);dragCounter = 0;this.hideDragDropOverlay();@@ -98,47 +113,76 @@ const model = {// Setup paste event handler for clipboard imagessetupPasteHandler() {+ console.log('Setting up paste handler...');document.addEventListener('paste', (e) => {+ console.log('Paste event detected, target:', e.target.tagName);+ // Only handle paste when not in an input field (to avoid interfering with text pasting)+ if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {+ console.log('Ignoring paste in input field');+ return;+ }+const items = e.clipboardData.items;+ let imageFound = false;+ console.log('Checking clipboard items:', items.length);+for (let i = 0; i < items.length; i++) {const item = items[i];if (item.type.indexOf('image') !== -1) {+ imageFound = true;const blob = item.getAsFile();- this.handleClipboardImage(blob);+ if (blob) {+ e.preventDefault(); // Prevent default paste behavior for images+ this.handleClipboardImage(blob);+ }}}++ if (imageFound) {+ console.log('Image detected in clipboard, processing...');+ }});},// Handle clipboard image pastingasync handleClipboardImage(blob) {- // Generate unique filename- const guid = this.generateGUID();- const filename = `clipboard-${guid}.png`;-- // Create file object from blob- const file = new File([blob], filename, { type: 'image/png' });-- // Create attachment object- const attachment = {- file: file,- type: 'image',- name: filename,- extension: 'png'- };-- // Read as data URL for preview- const reader = new FileReader();- reader.onload = (e) => {- attachment.url = e.target.result;- this.addAttachment(attachment);- };- reader.readAsDataURL(file);+ try {+ // Generate unique filename+ const guid = this.generateGUID();+ const filename = `clipboard-${guid}.png`;++ // Create file object from blob+ const file = new File([blob], filename, { type: 'image/png' });++ // Create attachment object+ const attachment = {+ file: file,+ type: 'image',+ name: filename,+ extension: 'png'+ };++ // Read as data URL for preview+ const reader = new FileReader();+ reader.onload = (e) => {+ attachment.url = e.target.result;+ this.addAttachment(attachment);+ };+ reader.readAsDataURL(file);++ // Show success feedback+ console.log('Clipboard image pasted successfully:', filename);++ } catch (error) {+ console.error('Failed to handle clipboard image:', error);+ }},// File handling logic (moved from index.js)handleFiles(files) {+ console.log('handleFiles called with', files.length, 'files');Array.from(files).forEach(file => {+ console.log('Processing file:', file.name, file.type);const ext = file.name.split('.').pop().toLowerCase();const isImage = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'webp'].includes(ext);@@ -187,9 +231,56 @@ const model = {const v = c == 'x' ? r : (r & 0x3 | 0x8);return v.toString(16);});+ },++ // Image modal methods+ openImageModal(imageUrl, imageName) {+ this.currentImageUrl = imageUrl;+ this.currentImageName = imageName;+ this.imageLoaded = false;+ this.imageError = false;+ this.zoomLevel = 1;++ // Open the modal using the modals system+ if (window.openModal) {+ window.openModal('chat/attachments/imageModal.html');+ }+ },++ closeImageModal() {+ this.currentImageUrl = null;+ this.currentImageName = null;+ this.imageLoaded = false;+ this.imageError = false;+ this.zoomLevel = 1;+ },++ // Zoom controls+ zoomIn() {+ this.zoomLevel = Math.min(this.zoomLevel * 1.2, 5); // Max 5x zoom+ this.updateImageZoom();+ },++ zoomOut() {+ this.zoomLevel = Math.max(this.zoomLevel / 1.2, 0.1); // Min 0.1x zoom+ this.updateImageZoom();+ },++ resetZoom() {+ this.zoomLevel = 1;+ this.updateImageZoom();+ },++ updateImageZoom() {+ const img = document.querySelector('.modal-image');+ if (img) {+ img.style.transform = `scale(${this.zoomLevel})`;+ }}};+console.log('Creating chatAttachments store...');const store = createStore("chatAttachments", model);+console.log('chatAttachments store created:', store);export { store };\ No newline at end of filediff --git a/webui/components/chat/attachments/imageModal.html b/webui/components/chat/attachments/imageModal.htmlnew file mode 100644index 000000000..a14800456--- /dev/null+++ b/webui/components/chat/attachments/imageModal.html@@ -0,0 +1,148 @@+<html>++<head>+ <title>Image Viewer</title>++ <script type="module">+ import { store } from "/components/chat/attachments/attachmentsStore.js";+ </script>+</head>++<body>+ <div x-data>+ <template x-if="$store.chatAttachments">+ <div id="image-modal-content" class="image-modal-container">+ <!-- Image display area -->+ <div class="image-display-wrapper">+ <img+ x-show="$store.chatAttachments.currentImageUrl"+ :src="$store.chatAttachments.currentImageUrl"+ :alt="$store.chatAttachments.currentImageName || 'Image'"+ class="modal-image"+ @load="$store.chatAttachments.imageLoaded = true"+ @error="$store.chatAttachments.imageError = true"+ />++ <!-- Loading indicator -->+ <div x-show="!$store.chatAttachments.imageLoaded && !$store.chatAttachments.imageError" class="loading-indicator">+ <div class="loading-spinner"></div>+ <p>Loading image...</p>+ </div>++ <!-- Error indicator -->+ <div x-show="$store.chatAttachments.imageError" class="error-indicator">+ <p>Failed to load image</p>+ </div>+ </div>++ <!-- Simple zoom controls -->+ <div class="zoom-controls">+ <button @click="$store.chatAttachments.zoomOut()" class="zoom-btn" title="Zoom Out">−</button>+ <button @click="$store.chatAttachments.resetZoom()" class="zoom-btn" title="Reset">⌂</button>+ <button @click="$store.chatAttachments.zoomIn()" class="zoom-btn" title="Zoom In">+</button>+ </div>+ </div>+ </template>+ </div>++ <style>+ .image-modal-container {+ width: 100%;+ height: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ position: relative;+ background: var(--color-bg-secondary);+ }++ .image-display-wrapper {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: auto;+ width: 100%;+ height: 100%;+ position: relative;+ }++ .modal-image {+ max-width: 100%;+ max-height: 100%;+ object-fit: contain;+ transition: transform 0.2s ease;+ cursor: grab;+ }++ .modal-image:active {+ cursor: grabbing;+ }++ .loading-indicator, .error-indicator {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ color: var(--color-text-secondary);+ }++ .loading-spinner {+ width: 40px;+ height: 40px;+ border: 3px solid var(--color-border);+ border-top: 3px solid var(--color-primary);+ border-radius: 50%;+ animation: spin 1s linear infinite;+ margin-bottom: 10px;+ }++ @keyframes spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+ }++ .zoom-controls {+ position: absolute;+ bottom: 20px;+ right: 20px;+ display: flex;+ align-items: center;+ gap: 4px;+ background: rgba(0, 0, 0, 0.6);+ padding: 6px;+ border-radius: 12px;+ backdrop-filter: blur(5px);+ }++ .zoom-btn {+ background: transparent;+ border: none;+ color: white;+ cursor: pointer;+ padding: 6px 10px;+ border-radius: 6px;+ font-size: 16px;+ font-weight: 500;+ min-width: 32px;+ height: 32px;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: background-color 0.2s ease;+ }++ .zoom-btn:hover {+ background: rgba(255, 255, 255, 0.15);+ }++ /* Dark mode adjustments */+ .dark-mode .image-modal-container {+ background: var(--color-bg-secondary);+ }+ </style>++</body>++</html>\ No newline at end of filediff --git a/webui/index.html b/webui/index.htmlindex 8d3ec86b5..117ae0226 100644--- a/webui/index.html+++ b/webui/index.html@@ -379,7 +379,9 @@<template x-for="(attachment, index) in $store.chatAttachments.attachments" :key="index"><div class="preview-item" :class="{'image-preview': attachment.type === 'image'}"><template x-if="attachment.type === 'image'">- <img :src="attachment.url" :alt="attachment.name">+ <img :src="attachment.url" :alt="attachment.name"+ style="cursor: pointer;"+ @click="$store.chatAttachments.openImageModal(attachment.url, attachment.name)"></template><template x-if="attachment.type === 'file'"><div class="file-preview">@@ -681,20 +683,20 @@<div id="section-tunnel" class="section" x-show="activeTab === 'external'"><div class="section-title">Flare Tunnel</div><div class="section-description">Create a secure public URL to access your Agent Zero instance anytime, anywhere.</div>- <div class="field">- <div class="field-label">- <div class="field-title">Tunnel provider</div>- <div class="field-description">Select provider for public tunnel</div>- </div>- <div class="field-control">- <select id="tunnel-provider" x-model="provider" :disabled="isLoading">- <option value="serveo">Serveo</option>- <option value="cloudflared">Cloudflare</option>- </select>- </div>- </div><!-- Tunnel content UI --><div class="tunnel-container" x-data="tunnelSettings">+ <div class="field">+ <div class="field-label">+ <div class="field-title">Tunnel provider</div>+ <div class="field-description">Select provider for public tunnel</div>+ </div>+ <div class="field-control">+ <select id="tunnel-provider" x-model="provider" :disabled="isLoading">+ <option value="serveo">Serveo</option>+ <option value="cloudflared">Cloudflare</option>+ </select>+ </div>+ </div><!-- Loading spinner for tunnel operations --><div class="loading-spinner" x-show="isLoading"><i class="fas fa-spinner fa-spin"></i>diff --git a/webui/index.js b/webui/index.jsindex 17bc212c7..35c13f3ab 100644--- a/webui/index.js+++ b/webui/index.js@@ -84,7 +84,7 @@ document.addEventListener('DOMContentLoaded', setupSidebarToggle);export async function sendMessage() {try {const message = chatInput.value.trim();- const attachmentsStore = Alpine.store('chatAttachments');+ const attachmentsStore = window.Alpine ? Alpine.store('chatAttachments') : null;const attachments = attachmentsStore ? attachmentsStore.attachments : [];const hasAttachments = attachmentsStore ? attachmentsStore.hasAttachments : false;@@ -321,8 +321,15 @@ function getConnectionStatus() {function setConnectionStatus(connected) {connectionStatus = connected- const statusIcon = Alpine.$data(timeDate.querySelector('.status-icon'));- statusIcon.connected = connected+ if (window.Alpine && timeDate) {+ const statusIconEl = timeDate.querySelector('.status-icon');+ if (statusIconEl) {+ const statusIcon = Alpine.$data(statusIconEl);+ if (statusIcon) {+ statusIcon.connected = connected;+ }+ }+ }}let lastLogVersion = 0;@@ -373,37 +380,48 @@ async function poll() {updateProgress(response.log_progress, response.log_progress_active)//set ui model vars from backend- const inputAD = Alpine.$data(inputSection);- inputAD.paused = response.paused;+ if (window.Alpine && inputSection) {+ const inputAD = Alpine.$data(inputSection);+ if (inputAD) {+ inputAD.paused = response.paused;+ }+ }// Update status icon statesetConnectionStatus(true)// Update chats list and sort by created_at time (newer first)- const chatsAD = Alpine.$data(chatsSection);- const contexts = response.contexts || [];- chatsAD.contexts = contexts.sort((a, b) =>- (b.created_at || 0) - (a.created_at || 0)- );+ let chatsAD = null;+ let contexts = response.contexts || [];+ if (window.Alpine && chatsSection) {+ chatsAD = Alpine.$data(chatsSection);+ if (chatsAD) {+ chatsAD.contexts = contexts.sort((a, b) =>+ (b.created_at || 0) - (a.created_at || 0)+ );+ }+ }// Update tasks list and sort by creation time (newer first)const tasksSection = document.getElementById('tasks-section');- if (tasksSection) {+ if (window.Alpine && tasksSection) {const tasksAD = Alpine.$data(tasksSection);- let tasks = response.tasks || [];-- // Always update tasks to ensure state changes are reflected- if (tasks.length > 0) {- // Sort the tasks by creation time- const sortedTasks = [...tasks].sort((a, b) =>- (b.created_at || 0) - (a.created_at || 0)- );-- // Assign the sorted tasks to the Alpine data- tasksAD.tasks = sortedTasks;- } else {- // Make sure to use a new empty array instance- tasksAD.tasks = [];+ if (tasksAD) {+ let tasks = response.tasks || [];++ // Always update tasks to ensure state changes are reflected+ if (tasks.length > 0) {+ // Sort the tasks by creation time+ const sortedTasks = [...tasks].sort((a, b) =>+ (b.created_at || 0) - (a.created_at || 0)+ );++ // Assign the sorted tasks to the Alpine data+ tasksAD.tasks = sortedTasks;+ } else {+ // Make sure to use a new empty array instance+ tasksAD.tasks = [];+ }}}@@ -412,7 +430,7 @@ async function poll() {// Update selection in the active tabconst activeTab = localStorage.getItem('activeTab') || 'chats';- if (activeTab === 'chats') {+ if (activeTab === 'chats' && chatsAD) {chatsAD.selected = context;localStorage.setItem('lastSelectedChat', context);@@ -457,7 +475,7 @@ async function poll() {tasksAD.selected = firstTaskId;localStorage.setItem('lastSelectedTask', firstTaskId);}- } else if (contexts.length > 0 && localStorage.getItem('activeTab') === 'chats') {+ } else if (contexts.length > 0 && localStorage.getItem('activeTab') === 'chats' && chatsAD) {// If we're in chats tab with no selection but have chats, select the first oneconst firstChatId = contexts[0].id;@@ -681,11 +699,16 @@ export const setContext = function (id) {chatHistory.innerHTML = "";// Update both selected states- const chatsAD = Alpine.$data(chatsSection);- const tasksAD = Alpine.$data(tasksSection);-- chatsAD.selected = id;- tasksAD.selected = id;+ if (window.Alpine) {+ if (chatsSection) {+ const chatsAD = Alpine.$data(chatsSection);+ if (chatsAD) chatsAD.selected = id;+ }+ if (tasksSection) {+ const tasksAD = Alpine.$data(tasksSection);+ if (tasksAD) tasksAD.selected = id;+ }+ }}export const getContext = function () {@@ -1021,8 +1044,12 @@ function hideToast() {}function scrollChanged(isAtBottom) {- const inputAS = Alpine.$data(autoScrollSwitch);- inputAS.autoScroll = isAtBottom+ if (window.Alpine && autoScrollSwitch) {+ const inputAS = Alpine.$data(autoScrollSwitch);+ if (inputAS) {+ inputAS.autoScroll = isAtBottom;+ }+ }// autoScrollSwitch.checked = isAtBottom}@@ -1073,9 +1100,13 @@ document.addEventListener("DOMContentLoaded", startPolling);// Update handleFileUpload to use the attachments storewindow.handleFileUpload = function(event) {+ console.log('handleFileUpload called with files:', event.target.files.length);const files = event.target.files;- if (Alpine.store('chatAttachments')) {+ if (window.Alpine && Alpine.store('chatAttachments')) {+ console.log('Calling store handleFiles...');Alpine.store('chatAttachments').handleFiles(files);+ } else {+ console.error('Alpine or chatAttachments store not found!');}}@@ -1137,8 +1168,8 @@ function activateTab(tabName) {chatsSection.style.display = '';// Get the available contexts from Alpine.js data- const chatsAD = Alpine.$data(chatsSection);- const availableContexts = chatsAD.contexts || [];+ const chatsAD = window.Alpine ? Alpine.$data(chatsSection) : null;+ const availableContexts = chatsAD?.contexts || [];// Restore previous chat selectionconst lastSelectedChat = localStorage.getItem('lastSelectedChat');@@ -1158,8 +1189,8 @@ function activateTab(tabName) {tasksSection.style.flexDirection = 'column';// Get the available tasks from Alpine.js data- const tasksAD = Alpine.$data(tasksSection);- const availableTasks = tasksAD.tasks || [];+ const tasksAD = window.Alpine ? Alpine.$data(tasksSection) : null;+ const availableTasks = tasksAD?.tasks || [];// Restore previous task selectionconst lastSelectedTask = localStorage.getItem('lastSelectedTask');@@ -1223,7 +1254,7 @@ function openTaskDetail(taskId) {}// Get the Alpine.js data for the modal- const modalData = Alpine.$data(modalEl);+ const modalData = window.Alpine ? Alpine.$data(modalEl) : null;// Use a timeout to ensure the modal is fully renderedsetTimeout(() => {@@ -1240,7 +1271,7 @@ function openTaskDetail(taskId) {}// Get the Alpine.js data for the scheduler component- const schedulerData = Alpine.$data(schedulerComponent);+ const schedulerData = window.Alpine ? Alpine.$data(schedulerComponent) : null;// Show the task detail view for the specific taskschedulerData.showTaskDetail(taskId);diff --git a/webui/js/AlpineStore.js b/webui/js/AlpineStore.jsindex bf386c279..a7634757a 100644--- a/webui/js/AlpineStore.js+++ b/webui/js/AlpineStore.js@@ -10,6 +10,7 @@ const stores = new Map();* @returns {T}*/export function createStore(name, initialState) {+ console.log('createStore called for:', name);const proxy = new Proxy(initialState, {set(target, prop, value) {const store = globalThis.Alpine?.store(name);@@ -23,13 +24,19 @@ export function createStore(name, initialState) {});if (globalThis.Alpine) {+ console.log('Alpine available, registering store immediately:', name);globalThis.Alpine.store(name, initialState);} else {- document.addEventListener("alpine:init", () => Alpine.store(name, initialState));+ console.log('Alpine not available, waiting for alpine:init for store:', name);+ document.addEventListener("alpine:init", () => {+ console.log('alpine:init fired, registering store:', name);+ Alpine.store(name, initialState);+ });}// Store the proxystores.set(name, proxy);+ console.log('Store proxy created and stored for:', name);return /** @type {T} */ (proxy); // explicitly cast for linter support}diff --git a/webui/js/initFw.js b/webui/js/initFw.jsindex a441d04bb..c6977721a 100644--- a/webui/js/initFw.js+++ b/webui/js/initFw.js@@ -4,7 +4,9 @@ import * as _components from "./components.js";await import("./alpine.min.js");// Import attachments store+console.log('initFw.js: About to import attachments store...');import { store as attachmentsStore } from "../components/chat/attachments/attachmentsStore.js";+console.log('initFw.js: Attachments store imported:', attachmentsStore);// add x-destroy directiveAlpine.directive(@@ -16,10 +18,34 @@ Alpine.directive();// Initialize attachments store when Alpine.js is ready-document.addEventListener('alpine:init', () => {- // Store is already created via createStore in attachmentsStore.js- // Just call initialize to set up event handlers- if (Alpine.store('chatAttachments')) {+function initializeAttachmentsStore() {+ console.log('Attempting to initialize attachments store...');+ if (window.Alpine && Alpine.store('chatAttachments')) {+ console.log('chatAttachments store found, initializing...');Alpine.store('chatAttachments').initialize();+ return true;+ } else {+ console.log('Alpine or store not ready yet, will retry...');+ return false;}+}++// Try multiple initialization approaches+document.addEventListener('alpine:init', () => {+ console.log('Alpine.js alpine:init event fired');+ setTimeout(() => initializeAttachmentsStore(), 100);});++// Also try when Alpine is fully initialized+document.addEventListener('alpine:initialized', () => {+ console.log('Alpine.js alpine:initialized event fired');+ initializeAttachmentsStore();+});++// Fallback: try after a delay+setTimeout(() => {+ if (!initializeAttachmentsStore()) {+ console.log('Retrying attachments store initialization after delay...');+ setTimeout(initializeAttachmentsStore, 1000);+ }+}, 500);diff --git a/webui/js/messages.js b/webui/js/messages.jsindex ac089710d..8b13af69f 100644--- a/webui/js/messages.js+++ b/webui/js/messages.js@@ -344,6 +344,12 @@ export function drawMessageUser(img.src = getServerImageUrl(filename);img.alt = filename;img.classList.add("attachment-preview");+ img.style.cursor = "pointer";+ img.addEventListener('click', () => {+ if (window.Alpine && window.Alpine.store('chatAttachments')) {+ window.Alpine.store('chatAttachments').openImageModal(getServerImageUrl(filename), filename);+ }+ });const fileInfo = document.createElement("div");fileInfo.classList.add("file-info");@@ -372,13 +378,21 @@ export function drawMessageUser(const img = document.createElement("img");// Use server URL if we have filename, otherwise fall back to blob URL for current session+ let imageUrl;if (attachment.name && !attachment.url.startsWith('blob:')) {- img.src = getServerImageUrl(attachment.name);+ imageUrl = getServerImageUrl(attachment.name);} else {- img.src = attachment.url;+ imageUrl = attachment.url;}+ img.src = imageUrl;img.alt = attachment.name;img.classList.add("attachment-preview");+ img.style.cursor = "pointer";+ img.addEventListener('click', () => {+ if (window.Alpine && window.Alpine.store('chatAttachments')) {+ window.Alpine.store('chatAttachments').openImageModal(imageUrl, attachment.name);+ }+ });const fileInfo = document.createElement("div");fileInfo.classList.add("file-info");diff --git a/webui/js/tunnel.js b/webui/js/tunnel.jsindex 40833c01e..1e2b5d0e7 100644--- a/webui/js/tunnel.js+++ b/webui/js/tunnel.js@@ -5,6 +5,7 @@ document.addEventListener('alpine:init', () => {tunnelLink: '',linkGenerated: false,loadingText: '',+ provider: 'serveo', // Default tunnel providerinit() {this.checkTunnelStatus();@@ -160,10 +161,8 @@ document.addEventListener('alpine:init', () => {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);- const provider = modalAD.provider || 'serveo'; // Default to serveo if not set+ // Use the local provider setting+ const provider = this.provider || 'serveo'; // Default to serveo if not set// Change create button appearanceconst createButton = document.querySelector('.tunnel-actions .btn-ok');