Skip to content

Agent Zero AI framework

attachments merge

frdela2c01c63cf59
diff --cc python/api/image_get.py
index 7a04bdf5e,ec7c857d3..d3583645c
--- a/python/api/image_get.py
+++ b/python/api/image_get.py
@@@ -7,34 -6,190 +7,195 @@@ from flask import Request, Response, se
class ImageGet(ApiHandler):
+
+ @classmethod
+ def get_methods(cls) -> list[str]:
+ return ["GET"]
+
async def process(self, input: dict, request: Request) -> dict | Response:
- # input data
- path = input.get("path", request.args.get("path", ""))
- if not path:
- raise ValueError("No path provided")
+ # input data
+ path = input.get("path", request.args.get("path", ""))
+ metadata = input.get("metadata", request.args.get("metadata", "false")).lower() == "true"
+
+ print(f"ImageGet: Processing path={path}, metadata={metadata}") # Debug
+
+ if not path:
+ raise ValueError("No path provided")
+
+ # check if path is within base directory
+ if not files.is_in_base_dir(path):
+ raise ValueError("Path is outside of allowed directory")
+
+ # get file extension and info
+ file_ext = os.path.splitext(path)[1].lower()
+ filename = os.path.basename(path)
+
+ print(f"ImageGet: file_ext={file_ext}, filename={filename}") # Debug
+
+ # list of allowed image extensions
+ image_extensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"]
+
+ # If metadata is requested, return file information
+ if metadata:
+ return self._get_file_metadata(path, filename, file_ext, image_extensions)
+
+ if file_ext in image_extensions:
+ # Handle image files
+ print(f"ImageGet: Handling as image file") # Debug
+ if not os.path.exists(path):
+ # If image doesn't exist, return default image icon
+ return self._get_fallback_icon("image")
+
+ # send actual image file with proper headers for device sync
+ response = send_file(path)
+ # Add cache headers for better device sync performance
+ response.headers['Cache-Control'] = 'public, max-age=3600'
+ response.headers['X-File-Type'] = 'image'
+ response.headers['X-File-Name'] = filename
+ return response
+ else:
+ # Handle non-image files with fallback icons
+ print(f"ImageGet: Handling as non-image file, getting icon") # Debug
+ return self._get_file_type_icon(file_ext, filename)
+
+ def _get_file_type_icon(self, file_ext, filename=None):
+ """Return appropriate icon for file type"""
+ print(f"_get_file_type_icon: file_ext={file_ext}, filename={filename}") # Debug
+
+ # Map file extensions to icon names
+ icon_mapping = {
+ # Archive files
+ '.zip': 'archive',
+ '.rar': 'archive',
+ '.7z': 'archive',
+ '.tar': 'archive',
+ '.gz': 'archive',
+
+ # Document files
+ '.pdf': 'document',
+ '.doc': 'document',
+ '.docx': 'document',
+ '.txt': 'document',
+ '.rtf': 'document',
+ '.odt': 'document',
+
+ # Code files
+ '.py': 'code',
+ '.js': 'code',
+ '.html': 'code',
+ '.css': 'code',
+ '.json': 'code',
+ '.xml': 'code',
+ '.md': 'code',
+ '.yml': 'code',
+ '.yaml': 'code',
+ '.sql': 'code',
+ '.sh': 'code',
+ '.bat': 'code',
+
+ # Spreadsheet files
+ '.xls': 'document',
+ '.xlsx': 'document',
+ '.csv': 'document',
+
+ # Presentation files
+ '.ppt': 'document',
+ '.pptx': 'document',
+ '.odp': 'document',
+ }
+
+ # Get icon name, default to 'file' if not found
+ icon_name = icon_mapping.get(file_ext, 'file')
+ print(f"_get_file_type_icon: icon_name={icon_name}") # Debug
+
+ response = self._get_fallback_icon(icon_name)
+
+ # Add headers for device sync
+ if hasattr(response, 'headers'):
+ response.headers['Cache-Control'] = 'public, max-age=86400' # Cache icons for 24 hours
+ response.headers['X-File-Type'] = 'icon'
+ response.headers['X-Icon-Type'] = icon_name
+ if filename:
+ response.headers['X-File-Name'] = filename
+
+ return response
+
+ def _get_file_metadata(self, path, filename, file_ext, image_extensions):
+ """Return file metadata for device sync and UI enhancement"""
+ metadata = {
+ 'filename': filename,
+ 'extension': file_ext,
+ 'exists': os.path.exists(path),
+ 'is_image': file_ext in image_extensions,
+ 'file_type': 'image' if file_ext in image_extensions else self._get_file_category(file_ext),
+ 'api_url': f'/image_get?path={path}',
+ 'icon_type': self._get_icon_type(file_ext) if file_ext not in image_extensions else 'image'
+ }
+
+ # Add file size if file exists
+ if metadata['exists']:
+ try:
+ metadata['size'] = os.path.getsize(path)
+ metadata['size_human'] = self._format_file_size(metadata['size'])
+ except OSError:
+ metadata['size'] = 0
+ metadata['size_human'] = 'Unknown'
+
+ return metadata
+
+ def _get_file_category(self, file_ext):
+ """Get file category for metadata"""
+ categories = {
+ '.zip': 'archive', '.rar': 'archive', '.7z': 'archive', '.tar': 'archive', '.gz': 'archive',
+ '.pdf': 'document', '.doc': 'document', '.docx': 'document', '.txt': 'document',
+ '.py': 'code', '.js': 'code', '.html': 'code', '.css': 'code', '.json': 'code',
+ '.xls': 'spreadsheet', '.xlsx': 'spreadsheet', '.csv': 'spreadsheet',
+ '.ppt': 'presentation', '.pptx': 'presentation'
+ }
+ return categories.get(file_ext, 'file')
+
+ def _get_icon_type(self, file_ext):
+ """Get icon type for metadata (matches the icon mapping)"""
+ icon_mapping = {
+ '.zip': 'archive', '.rar': 'archive', '.7z': 'archive', '.tar': 'archive', '.gz': 'archive',
+ '.pdf': 'document', '.doc': 'document', '.docx': 'document', '.txt': 'document', '.rtf': 'document', '.odt': 'document',
+ '.py': 'code', '.js': 'code', '.html': 'code', '.css': 'code', '.json': 'code', '.xml': 'code', '.md': 'code',
+ '.yml': 'code', '.yaml': 'code', '.sql': 'code', '.sh': 'code', '.bat': 'code',
+ '.xls': 'document', '.xlsx': 'document', '.csv': 'document',
+ '.ppt': 'document', '.pptx': 'document', '.odp': 'document'
+ }
+ return icon_mapping.get(file_ext, 'file')
+
+ def _format_file_size(self, size_bytes):
+ """Format file size in human readable format"""
+ if size_bytes == 0:
+ return "0 B"
+ size_names = ["B", "KB", "MB", "GB", "TB"]
+ import math
+ i = int(math.floor(math.log(size_bytes, 1024)))
+ p = math.pow(1024, i)
+ s = round(size_bytes / p, 2)
+ return f"{s} {size_names[i]}"
+
+ def _get_fallback_icon(self, icon_name):
+ """Return fallback icon from public directory"""
+ print(f"_get_fallback_icon: icon_name={icon_name}") # Debug
+
+ # Path to public icons
+ icon_path = files.get_abs_path(f"webui/public/{icon_name}.svg")
+ print(f"_get_fallback_icon: icon_path={icon_path}") # Debug
+
+ # Check if specific icon exists, fallback to generic file icon
+ if not os.path.exists(icon_path):
+ print(f"_get_fallback_icon: Icon not found, falling back to file.svg") # Debug
+ icon_path = files.get_abs_path("webui/public/file.svg")
+
+ # Final fallback if file.svg doesn't exist
+ if not os.path.exists(icon_path):
+ print(f"_get_fallback_icon: ERROR - file.svg not found at {icon_path}") # Debug
+ raise ValueError(f"Fallback icon not found: {icon_path}")
+
+ print(f"_get_fallback_icon: Sending file {icon_path}") # Debug
+ return send_file(icon_path, mimetype='image/svg+xml')
- # check if path is within base directory
- if not files.is_in_base_dir(path):
- raise ValueError("Path is outside of allowed directory")
-
- # check if file has an image extension
- # list of allowed image extensions
- allowed_extensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"]
- # get file extension
- file_ext = os.path.splitext(path)[1].lower()
- if file_ext not in allowed_extensions:
- raise ValueError(
- f"File type not allowed. Allowed types: {', '.join(allowed_extensions)}"
- )
-
- # check if file exists
- if not os.path.exists(path):
- raise ValueError("File not found")
-
- # send file
- return send_file(path)
+
diff --cc webui/components/chat/attachments/attachmentsStore.js
index 000000000,94bf83127..840d2ca68
mode 000000,100644..100644
--- a/webui/components/chat/attachments/attachmentsStore.js
+++ b/webui/components/chat/attachments/attachmentsStore.js
@@@ -1,0 -1,370 +1,370 @@@
-console.log('attachmentsStore.js module loading...');
+ import { createStore } from "/js/AlpineStore.js";
+
-console.log('attachmentsStore.js module loaded, creating model...');
+ const model = {
+ // State properties
+ attachments: [],
+ hasAttachments: false,
+ dragDropOverlayVisible: false,
+
+ // Image modal properties
+ currentImageUrl: null,
+ currentImageName: null,
+ imageLoaded: false,
+ imageError: false,
+ zoomLevel: 1,
+
++ async init() {
++ await this.initialize();
++ },
++
+ // Initialize the store
+ async initialize() {
- console.log('Initializing attachments store...');
+ // Setup event listeners for drag and drop
+ this.setupDragDropHandlers();
+ // Setup paste event listener for clipboard images
+ this.setupPasteHandler();
- console.log('Attachments store initialized successfully');
+ },
+
+ // Basic attachment management methods
+ addAttachment(attachment) {
+ // Validate for duplicates
+ if (this.validateDuplicates(attachment)) {
+ this.attachments.push(attachment);
+ this.updateAttachmentState();
+ }
+ },
+
+ removeAttachment(index) {
+ if (index >= 0 && index < this.attachments.length) {
+ this.attachments.splice(index, 1);
+ this.updateAttachmentState();
+ }
+ },
+
+ clearAttachments() {
+ this.attachments = [];
+ this.updateAttachmentState();
+ },
+
+ validateDuplicates(newAttachment) {
+ // Check if attachment already exists based on name and size
+ const isDuplicate = this.attachments.some(existing =>
+ existing.name === newAttachment.name &&
+ existing.file && newAttachment.file &&
+ existing.file.size === newAttachment.file.size
+ );
+ return !isDuplicate;
+ },
+
+ updateAttachmentState() {
+ this.hasAttachments = this.attachments.length > 0;
+ },
+
+ // Drag drop overlay control methods
+ showDragDropOverlay() {
+ this.dragDropOverlayVisible = true;
+ },
+
+ hideDragDropOverlay() {
+ this.dragDropOverlayVisible = false;
+ },
+
+ // Setup drag and drop event handlers
+ setupDragDropHandlers() {
+ console.log('Setting up drag and drop handlers...');
+ let dragCounter = 0;
+
+ // Prevent default drag behaviors
+ ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
+ document.addEventListener(eventName, (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ });
+
+ // Handle drag enter
+ document.addEventListener('dragenter', (e) => {
+ console.log('Drag enter detected');
+ dragCounter++;
+ if (dragCounter === 1) {
+ console.log('Showing drag drop overlay');
+ this.showDragDropOverlay();
+ }
+ }, false);
+
+ // Handle drag leave
+ document.addEventListener('dragleave', (e) => {
+ dragCounter--;
+ if (dragCounter === 0) {
+ this.hideDragDropOverlay();
+ }
+ }, false);
+
+ // Handle drop
+ document.addEventListener('drop', (e) => {
+ console.log('Drop detected with files:', e.dataTransfer.files.length);
+ dragCounter = 0;
+ this.hideDragDropOverlay();
+
+ const files = e.dataTransfer.files;
+ this.handleFiles(files);
+ }, false);
+ },
+
+ // Setup paste event handler for clipboard images
+ setupPasteHandler() {
+ console.log('Setting up paste handler...');
+ document.addEventListener('paste', (e) => {
+ console.log('Paste event detected, target:', e.target.tagName);
+
+ const items = e.clipboardData.items;
+ let imageFound = false;
+ console.log('Checking clipboard items:', items.length);
+
+ // First, check if there are any images in the clipboard
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ if (item.type.indexOf('image') !== -1) {
+ imageFound = true;
+ const blob = item.getAsFile();
+ if (blob) {
+ e.preventDefault(); // Prevent default paste behavior for images
+ this.handleClipboardImage(blob);
+ console.log('Image detected in clipboard, processing...');
+ }
+ break; // Only handle the first image found
+ }
+ }
+
+ // If no images found and we're in an input field, let normal text paste happen
+ if (!imageFound && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) {
+ console.log('No images in clipboard, allowing normal text paste in input field');
+ return;
+ }
+
+ // If no images found and not in input field, do nothing
+ if (!imageFound) {
+ console.log('No images in clipboard');
+ }
+ });
+ },
+
+ // Handle clipboard image pasting
+ async handleClipboardImage(blob) {
+ 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);
+
+ const attachment = {
+ file: file,
+ type: isImage ? 'image' : 'file',
+ name: file.name,
+ extension: ext
+ };
+
+ if (isImage) {
+ // Read image as data URL for preview
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ attachment.url = e.target.result;
+ this.addAttachment(attachment);
+ };
+ reader.readAsDataURL(file);
+ } else {
+ // For non-image files, add directly
+ this.addAttachment(attachment);
+ }
+ });
+ },
+
+ // Get attachments for sending message
+ getAttachmentsForSending() {
+ return this.attachments.map(attachment => {
+ if (attachment.type === 'image') {
+ return {
+ ...attachment,
+ url: URL.createObjectURL(attachment.file)
+ };
+ } else {
+ return {
+ ...attachment
+ };
+ }
+ });
+ },
+
+ // Generate server-side API URL for file (for device sync)
+ getServerFileUrl(filename) {
+ return `/image_get?path=/a0/tmp/uploads/${encodeURIComponent(filename)}`;
+ },
+
+ // Get file metadata from server (for device sync and enhanced UI)
+ async getFileMetadata(filename) {
+ try {
+ const response = await fetch(`/image_get?path=/a0/tmp/uploads/${encodeURIComponent(filename)}&metadata=true`);
+ if (response.ok) {
+ return await response.json();
+ }
+ return null;
+ } catch (error) {
+ console.error('Failed to get file metadata:', error);
+ return null;
+ }
+ },
+
+ // Check if file is an image based on extension
+ isImageFile(filename) {
+ const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
+ const extension = filename.split('.').pop().toLowerCase();
+ return imageExtensions.includes(extension);
+ },
+
+ // Get attachment preview URL (server URL for persistence, blob URL for current session)
+ getAttachmentPreviewUrl(attachment) {
+ // If attachment has a name and we're dealing with a server-stored file
+ if (typeof attachment === 'string') {
+ // attachment is just a filename (from loaded chat)
+ return this.getServerFileUrl(attachment);
+ } else if (attachment.name && attachment.file) {
+ // attachment is an object from current session
+ if (attachment.type === 'image') {
+ // For images, use blob URL for current session preview
+ return attachment.url || URL.createObjectURL(attachment.file);
+ } else {
+ // For non-image files, use server URL to get appropriate icon
+ return this.getServerFileUrl(attachment.name);
+ }
+ }
+ return null;
+ },
+
+ // Enhanced method to get attachment display info for UI
+ getAttachmentDisplayInfo(attachment) {
+ if (typeof attachment === 'string') {
+ // attachment is filename only (from persistent storage)
+ const filename = attachment;
+ const extension = filename.split('.').pop();
+ return {
+ filename: filename,
+ extension: extension.toUpperCase(),
+ isImage: this.isImageFile(filename),
+ previewUrl: this.getServerFileUrl(filename),
+ clickHandler: () => {
+ if (this.isImageFile(filename)) {
+ this.openImageModal(this.getServerFileUrl(filename), filename);
+ }
+ }
+ };
+ } else {
+ // attachment is object (from current session)
+ return {
+ filename: attachment.name,
+ extension: attachment.extension.toUpperCase(),
+ isImage: attachment.type === 'image',
+ previewUrl: this.getAttachmentPreviewUrl(attachment),
+ clickHandler: () => {
+ if (attachment.type === 'image') {
+ const imageUrl = this.getAttachmentPreviewUrl(attachment);
+ this.openImageModal(imageUrl, attachment.name);
+ }
+ }
+ };
+ }
+ },
+
+ // Generate GUID for unique filenames
+ generateGUID() {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+ const r = Math.random() * 16 | 0;
+ 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 };
diff --cc webui/index.css
index d76dbc7ac,9d36a547d..0af90fe00
--- a/webui/index.css
+++ b/webui/index.css
@@@ -1341,6 -1844,109 +1493,70 @@@ input:checked + .slider:before
display: none;
}
- /* New styles for mobile messages */
-
- .message-followup {
- margin-left: var(--spacing-md);
- margin-bottom: var(--spacing-md);
- }
-
- .msg-kvps {
- display: flex;
- flex-direction: column;
- border-collapse: separate;
- border-spacing: 0 0.5rem;
- }
-
- .msg-kvps tr {
- display: flex;
- flex-direction: column;
- margin-top: 0.3rem;
- padding-bottom: 0;
- }
-
- .msg-kvps th,
- .msg-kvps td {
- display: block;
- width: 100%;
- text-align: left;
- border-bottom: none;
- padding: 0.25rem 0;
- padding-left: 0 !important;
- }
-
- .msg-kvps th {
- color: var(--color-primary);
- margin-bottom: 0.25rem;
- }
-
- .kvps-val {
- margin: 0 0 0.4rem 0;
- }
-
++
+ /* Responsive tiles for mobile */
+ .preview-section {
+ grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
+ gap: 8px;
+ padding: var(--spacing-xs);
+ }
+
+ .attachments-container {
+ grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
+ gap: 8px;
+ padding: var(--spacing-xs);
+ max-width: 300px; /* Limits to ~3 columns at 90px each */
+ }
+
+ .preview-item,
+ .attachment-item {
+ width: 90px;
+ height: 90px;
+ border-radius: 8px;
+ }
+
+ .preview-item.file-preview,
+ .attachment-item.file-type {
+ padding: 8px;
+ }
+
+ .preview-item.file-preview .file-icon,
+ .attachment-item.file-type .file-icon {
+ width: 32px;
+ height: 32px;
+ margin-bottom: 4px;
+ }
+
+ .preview-item.file-preview .filename,
+ .attachment-item.file-type .file-title,
+ .attachment-name,
+ .filename {
+ font-size: 0.65rem;
+ -webkit-line-clamp: 1;
+ }
+
+ .preview-item.file-preview .extension,
+ .attachment-item.file-type .file-extension,
+ .attachment-item.image-type .image-badge,
+ .attachment-ext,
+ .extension {
+ font-size: 0.6rem;
+ padding: 1px 4px;
+ }
+
+ .remove-attachment,
+ .remove-image {
+ width: 20px;
+ height: 20px;
+ top: 2px;
+ right: 2px;
+ }
+
+ .attachment-item.image-type .image-badge {
+ bottom: 4px;
+ font-size: 0.55rem;
+ padding: 1px 6px;
+ }
}
@media (max-width: 640px) {
diff --cc webui/index.js
index 4088cb815,35c13f3ab..8dcdf408e
--- a/webui/index.js
+++ b/webui/index.js
@@@ -78,103 -69,93 +78,93 @@@ document.addEventListener("DOMContentLo
});
function setupSidebarToggle() {
- const leftPanel = document.getElementById('left-panel');
- const rightPanel = document.getElementById('right-panel');
- const toggleSidebarButton = document.getElementById('toggle-sidebar');
- if (toggleSidebarButton) {
- toggleSidebarButton.addEventListener('click', toggleSidebar);
- } else {
- console.error('Toggle sidebar button not found');
- setTimeout(setupSidebarToggle, 100);
- }
+ const leftPanel = document.getElementById("left-panel");
+ const rightPanel = document.getElementById("right-panel");
+ const toggleSidebarButton = document.getElementById("toggle-sidebar");
+ if (toggleSidebarButton) {
+ toggleSidebarButton.addEventListener("click", toggleSidebar);
+ } else {
+ console.error("Toggle sidebar button not found");
+ setTimeout(setupSidebarToggle, 100);
+ }
}
-document.addEventListener('DOMContentLoaded', setupSidebarToggle);
+document.addEventListener("DOMContentLoaded", setupSidebarToggle);
export async function sendMessage() {
- try {
- const message = chatInput.value.trim();
- const inputAD = Alpine.$data(inputSection);
- const attachments = inputAD.attachments;
- const hasAttachments = attachments && attachments.length > 0;
+ try {
+ const message = chatInput.value.trim();
+ const attachmentsStore = window.Alpine ? Alpine.store('chatAttachments') : null;
+ const attachments = attachmentsStore ? attachmentsStore.attachments : [];
+ const hasAttachments = attachmentsStore ? attachmentsStore.hasAttachments : false;
- if (message || hasAttachments) {
- let response;
- const messageId = generateGUID();
+ if (message || hasAttachments) {
+ let response;
+ const messageId = generateGUID();
- // Include attachments in the user message
- if (hasAttachments) {
- const attachmentsWithUrls = attachments.map((attachment) => {
- if (attachment.type === "image") {
- return {
- ...attachment,
- url: URL.createObjectURL(attachment.file),
- };
- } else {
- return {
- ...attachment,
- };
- }
- });
+ // Include attachments in the user message
+ if (hasAttachments) {
+ const attachmentsWithUrls = attachmentsStore.getAttachmentsForSending();
- // Render user message with attachments
- setMessage(messageId, 'user', '', message, false, {
- attachments: attachmentsWithUrls
- });
-
- const formData = new FormData();
- formData.append('text', message);
- formData.append('context', context);
- formData.append('message_id', messageId);
+ // Render user message with attachments
+ setMessage(messageId, "user", "", message, false, {
+ attachments: attachmentsWithUrls,
+ });
- for (let i = 0; i < attachments.length; i++) {
- formData.append('attachments', attachments[i].file);
- }
+ const formData = new FormData();
+ formData.append("text", message);
+ formData.append("context", context);
+ formData.append("message_id", messageId);
- response = await fetch('/message_async', {
- method: 'POST',
- body: formData
- });
- } else {
- // For text-only messages
- const data = {
- text: message,
- context,
- message_id: messageId
- };
- response = await fetch('/message_async', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(data)
- });
- }
+ for (let i = 0; i < attachments.length; i++) {
+ formData.append("attachments", attachments[i].file);
+ }
- // Handle response
- const jsonResponse = await response.json();
- if (!jsonResponse) {
- toast("No response returned.", "error");
- }
- // else if (!jsonResponse.ok) {
- // if (jsonResponse.message) {
- // toast(jsonResponse.message, "error");
- // } else {
- // toast("Undefined error.", "error");
- // }
- // }
- else {
- setContext(jsonResponse.context);
- }
+ response = await api.fetchApi("/message_async", {
+ method: "POST",
+ body: formData,
+ });
+ } else {
+ // For text-only messages
+ const data = {
+ text: message,
+ context,
+ message_id: messageId,
+ };
+ response = await api.fetchApi("/message_async", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+ }
+
+ // Handle response
+ const jsonResponse = await response.json();
+ if (!jsonResponse) {
+ toast("No response returned.", "error");
+ }
+ // else if (!jsonResponse.ok) {
+ // if (jsonResponse.message) {
+ // toast(jsonResponse.message, "error");
+ // } else {
+ // toast("Undefined error.", "error");
+ // }
+ // }
+ else {
+ setContext(jsonResponse.context);
+ }
- // Clear input and attachments
- chatInput.value = "";
- inputAD.attachments = [];
- inputAD.hasAttachments = false;
- adjustTextareaHeight();
+ // Clear input and attachments
+ chatInput.value = '';
+ if (attachmentsStore) {
+ attachmentsStore.clearAttachments();
+ }
+ adjustTextareaHeight();
+ }
+ } catch (e) {
+ toastFetchError("Error sending message", e)
}
- } catch (e) {
- toastFetchError("Error sending message", e);
- }
}
function toastFetchError(text, error) {
@@@ -325,168 -333,169 +322,172 @@@ function setConnectionStatus(connected
}
let lastLogVersion = 0;
-let lastLogGuid = ""
-let lastSpokenNo = 0
+let lastLogGuid = "";
+let lastSpokenNo = 0;
async function poll() {
- let updated = false
- try {
- // Get timezone from navigator
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
- const response = await sendJsonData(
- "/poll",
- {
- log_from: lastLogVersion,
- context: context || null,
- timezone: timezone
- }
- );
+ let updated = false;
+ try {
+ // Get timezone from navigator
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ const response = await sendJsonData("/poll", {
+ log_from: lastLogVersion,
+ context: context || null,
+ timezone: timezone,
+ });
- // Check if the response is valid
- if (!response) {
- console.error("Invalid response from poll endpoint");
- return false;
- }
+ // Check if the response is valid
+ if (!response) {
+ console.error("Invalid response from poll endpoint");
+ return false;
+ }
- if (!context) setContext(response.context)
- if (response.context != context) return //skip late polls after context change
+ if (!context) setContext(response.context);
+ if (response.context != context) return; //skip late polls after context change
- if (lastLogGuid != response.log_guid) {
- chatHistory.innerHTML = ""
- lastLogVersion = 0
- }
+ if (lastLogGuid != response.log_guid) {
+ chatHistory.innerHTML = "";
+ lastLogVersion = 0;
+ }
- if (lastLogVersion != response.log_version) {
- updated = true
- for (const log of response.logs) {
- const messageId = log.id || log.no; // Use log.id if available
- setMessage(messageId, log.type, log.heading, log.content, log.temp, log.kvps);
- }
- afterMessagesUpdate(response.logs)
- }
+ if (lastLogVersion != response.log_version) {
+ updated = true;
+ for (const log of response.logs) {
+ const messageId = log.id || log.no; // Use log.id if available
+ setMessage(
+ messageId,
+ log.type,
+ log.heading,
+ log.content,
+ log.temp,
+ log.kvps
+ );
+ }
+ afterMessagesUpdate(response.logs);
+ }
- lastLogVersion = response.log_version;
- lastLogGuid = response.log_guid;
+ lastLogVersion = response.log_version;
+ lastLogGuid = response.log_guid;
- updateProgress(response.log_progress, response.log_progress_active)
+ updateProgress(response.log_progress, response.log_progress_active);
- //set ui model vars from backend
- const inputAD = Alpine.$data(inputSection);
- inputAD.paused = response.paused;
+ //set ui model vars from backend
+ if (window.Alpine && inputSection) {
+ const inputAD = Alpine.$data(inputSection);
+ if (inputAD) {
+ inputAD.paused = response.paused;
+ }
+ }
- // Update status icon state
- setConnectionStatus(true)
+ // Update status icon state
+ setConnectionStatus(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)
- );
-
- // Update tasks list and sort by creation time (newer first)
- const tasksSection = document.getElementById("tasks-section");
- if (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)
- );
+ // Update chats list and sort by created_at time (newer first)
+ 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)
+ );
+ }
+ }
- // Assign the sorted tasks to the Alpine data
- tasksAD.tasks = sortedTasks;
- } else {
- // Make sure to use a new empty array instance
- tasksAD.tasks = [];
- }
- }
+ // Update tasks list and sort by creation time (newer first)
+ const tasksSection = document.getElementById('tasks-section');
+ if (window.Alpine && tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ 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 = [];
+ }
+ }
+ }
- // Make sure the active context is properly selected in both lists
- if (context) {
- // Update selection in the active tab
- const activeTab = localStorage.getItem('activeTab') || 'chats';
+ // Make sure the active context is properly selected in both lists
+ if (context) {
+ // Update selection in the active tab
+ const activeTab = localStorage.getItem("activeTab") || "chats";
- if (activeTab === "chats") {
- chatsAD.selected = context;
- localStorage.setItem("lastSelectedChat", context);
+ if (activeTab === 'chats' && chatsAD) {
+ chatsAD.selected = context;
+ localStorage.setItem('lastSelectedChat', context);
- // Check if this context exists in the chats list
- const contextExists = contexts.some(ctx => ctx.id === context);
-
- // If it doesn't exist in the chats list but we're in chats tab, try to select the first chat
- if (!contextExists && contexts.length > 0) {
- // Check if the current context is empty before creating a new one
- // If there's already a current context and we're just updating UI, don't automatically
- // create a new context by calling setContext
- const firstChatId = contexts[0].id;
-
- // Only create a new context if we're not currently in an existing context
- // This helps prevent duplicate contexts when switching tabs
- setContext(firstChatId);
- chatsAD.selected = firstChatId;
- localStorage.setItem('lastSelectedChat', firstChatId);
- }
- } else if (activeTab === 'tasks' && tasksSection) {
- const tasksAD = Alpine.$data(tasksSection);
- tasksAD.selected = context;
- localStorage.setItem('lastSelectedTask', context);
+ // Check if this context exists in the chats list
+ const contextExists = contexts.some((ctx) => ctx.id === context);
+
+ // If it doesn't exist in the chats list but we're in chats tab, try to select the first chat
+ if (!contextExists && contexts.length > 0) {
+ // Check if the current context is empty before creating a new one
+ // If there's already a current context and we're just updating UI, don't automatically
+ // create a new context by calling setContext
+ const firstChatId = contexts[0].id;
+
+ // Only create a new context if we're not currently in an existing context
+ // This helps prevent duplicate contexts when switching tabs
+ setContext(firstChatId);
+ chatsAD.selected = firstChatId;
+ localStorage.setItem("lastSelectedChat", firstChatId);
+ }
+ } else if (activeTab === "tasks" && tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = context;
+ localStorage.setItem("lastSelectedTask", context);
- // Check if this context exists in the tasks list
- const taskExists = response.tasks?.some(task => task.id === context);
+ // Check if this context exists in the tasks list
+ const taskExists = response.tasks?.some((task) => task.id === context);
- // If it doesn't exist in the tasks list but we're in tasks tab, try to select the first task
- if (!taskExists && response.tasks?.length > 0) {
- const firstTaskId = response.tasks[0].id;
- setContext(firstTaskId);
- tasksAD.selected = firstTaskId;
- localStorage.setItem("lastSelectedTask", firstTaskId);
- }
- }
- } else if (
- response.tasks &&
- response.tasks.length > 0 &&
- localStorage.getItem("activeTab") === "tasks"
- ) {
- // If we're in tasks tab with no selection but have tasks, select the first one
- const firstTaskId = response.tasks[0].id;
- setContext(firstTaskId);
- if (tasksSection) {
- const tasksAD = Alpine.$data(tasksSection);
- tasksAD.selected = firstTaskId;
- localStorage.setItem("lastSelectedTask", firstTaskId);
- }
- } else if (
- contexts.length > 0 &&
- localStorage.getItem("activeTab") === "chats"
- ) {
- // If we're in chats tab with no selection but have chats, select the first one
- const firstChatId = contexts[0].id;
+ // If it doesn't exist in the tasks list but we're in tasks tab, try to select the first task
+ if (!taskExists && response.tasks?.length > 0) {
+ const firstTaskId = response.tasks[0].id;
+ setContext(firstTaskId);
+ tasksAD.selected = firstTaskId;
+ localStorage.setItem('lastSelectedTask', firstTaskId);
+ }
+ }
+ } else if (response.tasks && response.tasks.length > 0 && localStorage.getItem('activeTab') === 'tasks') {
+ // If we're in tasks tab with no selection but have tasks, select the first one
+ const firstTaskId = response.tasks[0].id;
+ setContext(firstTaskId);
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = firstTaskId;
+ localStorage.setItem('lastSelectedTask', firstTaskId);
+ }
+ } 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 one
+ const firstChatId = contexts[0].id;
- // Only set context if we don't already have one to avoid duplicates
- if (!context) {
- setContext(firstChatId);
- chatsAD.selected = firstChatId;
- localStorage.setItem('lastSelectedChat', firstChatId);
- }
- }
-
- lastLogVersion = response.log_version;
- lastLogGuid = response.log_guid;
-
- } catch (error) {
- console.error('Error:', error);
- setConnectionStatus(false)
+ // Only set context if we don't already have one to avoid duplicates
+ if (!context) {
+ setContext(firstChatId);
+ chatsAD.selected = firstChatId;
+ localStorage.setItem("lastSelectedChat", firstChatId);
+ }
}
- return updated
+ lastLogVersion = response.log_version;
+ lastLogGuid = response.log_guid;
+ } catch (error) {
+ console.error("Error:", error);
+ setConnectionStatus(false);
+ }
+
+ return updated;
}
function afterMessagesUpdate(logs) {
@@@ -653,98 -652,100 +654,103 @@@ function ensureProperTabSelection(conte
}
window.selectChat = async function (id) {
- if (id === context) return //already selected
+ if (id === context) return; //already selected
- // Check if we need to switch tabs based on the context type
- const tabSwitched = ensureProperTabSelection(id);
+ // Check if we need to switch tabs based on the context type
+ const tabSwitched = ensureProperTabSelection(id);
- // If we didn't switch tabs, proceed with normal selection
- if (!tabSwitched) {
- // Switch to the new context - this will clear chat history and reset tracking variables
- setContext(id);
+ // If we didn't switch tabs, proceed with normal selection
+ if (!tabSwitched) {
+ // Switch to the new context - this will clear chat history and reset tracking variables
+ setContext(id);
- // Update both contexts and tasks lists to reflect the selected item
- const chatsAD = Alpine.$data(chatsSection);
- const tasksSection = document.getElementById('tasks-section');
- if (tasksSection) {
- const tasksAD = Alpine.$data(tasksSection);
- tasksAD.selected = id;
- }
- chatsAD.selected = id;
-
- // Store this selection in the appropriate localStorage key
- const activeTab = localStorage.getItem('activeTab') || 'chats';
- if (activeTab === 'chats') {
- localStorage.setItem('lastSelectedChat', id);
- } else if (activeTab === 'tasks') {
- localStorage.setItem('lastSelectedTask', id);
- }
-
- // Trigger an immediate poll to fetch content
- poll();
+ // Update both contexts and tasks lists to reflect the selected item
+ const chatsAD = Alpine.$data(chatsSection);
+ const tasksSection = document.getElementById("tasks-section");
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = id;
+ }
+ chatsAD.selected = id;
+
+ // Store this selection in the appropriate localStorage key
+ const activeTab = localStorage.getItem("activeTab") || "chats";
+ if (activeTab === "chats") {
+ localStorage.setItem("lastSelectedChat", id);
+ } else if (activeTab === "tasks") {
+ localStorage.setItem("lastSelectedTask", id);
}
- updateAfterScroll();
-}
+ // Trigger an immediate poll to fetch content
+ poll();
+ }
+
+ updateAfterScroll();
+};
export const setContext = function (id) {
- if (id == context) return;
- context = id;
- // Always reset the log tracking variables when switching contexts
- // This ensures we get fresh data from the backend
- lastLogGuid = "";
- lastLogVersion = 0;
- lastSpokenNo = 0;
+ if (id == context) return;
+ context = id;
+ // Always reset the log tracking variables when switching contexts
+ // This ensures we get fresh data from the backend
+ lastLogGuid = "";
+ lastLogVersion = 0;
+ lastSpokenNo = 0;
- // Clear the chat history immediately to avoid showing stale content
- chatHistory.innerHTML = "";
+ // Clear the chat history immediately to avoid showing stale content
+ chatHistory.innerHTML = "";
- // Update both selected states
- const chatsAD = Alpine.$data(chatsSection);
- const tasksAD = Alpine.$data(tasksSection);
-
- chatsAD.selected = id;
- tasksAD.selected = id;
- };
+ // Update both selected states
+ 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 () {
- return context
-}
+ return context;
+};
window.toggleAutoScroll = async function (_autoScroll) {
- autoScroll = _autoScroll;
-}
+ autoScroll = _autoScroll;
+};
window.toggleJson = async function (showJson) {
- // add display:none to .msg-json class definition
- toggleCssProperty('.msg-json', 'display', showJson ? 'block' : 'none');
-}
+ css.toggleCssProperty(".msg-json", "display", showJson ? "block" : "none");
+};
window.toggleThoughts = async function (showThoughts) {
- // add display:none to .msg-json class definition
- toggleCssProperty('.msg-thoughts', 'display', showThoughts ? undefined : 'none');
-}
+ css.toggleCssProperty(
+ ".msg-thoughts",
+ "display",
+ showThoughts ? undefined : "none"
+ );
+};
window.toggleUtils = async function (showUtils) {
- // add display:none to .msg-json class definition
- toggleCssProperty('.message-util', 'display', showUtils ? undefined : 'none');
- // toggleCssProperty('.message-util .msg-kvps', 'display', showUtils ? undefined : 'none');
- // toggleCssProperty('.message-util .msg-content', 'display', showUtils ? undefined : 'none');
-}
+ css.toggleCssProperty(
+ ".message-util",
+ "display",
+ showUtils ? undefined : "none"
+ );
+};
window.toggleDarkMode = function (isDark) {
- if (isDark) {
- document.body.classList.remove('light-mode');
- document.body.classList.add('dark-mode');
- } else {
- document.body.classList.remove('dark-mode');
- document.body.classList.add('light-mode');
- }
- console.log("Dark mode:", isDark);
- localStorage.setItem('darkMode', isDark);
+ if (isDark) {
+ document.body.classList.remove("light-mode");
+ document.body.classList.add("dark-mode");
+ } else {
+ document.body.classList.remove("dark-mode");
+ document.body.classList.add("light-mode");
+ }
+ console.log("Dark mode:", isDark);
+ localStorage.setItem("darkMode", isDark);
};
window.toggleSpeech = function (isOn) {
@@@ -1064,106 -1096,25 +1074,25 @@@ async function startPolling()
document.addEventListener("DOMContentLoaded", startPolling);
- document.addEventListener("DOMContentLoaded", () => {
- const dragDropOverlay = document.getElementById("dragdrop-overlay");
- const inputSection = document.getElementById("input-section");
- let dragCounter = 0;
-
- // Prevent default drag behaviors
- ["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
- document.addEventListener(
- eventName,
- (e) => {
- e.preventDefault();
- e.stopPropagation();
- },
- false
- );
- });
-
- // Handle drag enter
- document.addEventListener(
- "dragenter",
- (e) => {
- dragCounter++;
- if (dragCounter === 1) {
- Alpine.$data(dragDropOverlay).isVisible = true;
- }
- },
- false
- );
-
- // Handle drag leave
- document.addEventListener(
- "dragleave",
- (e) => {
- dragCounter--;
- if (dragCounter === 0) {
- Alpine.$data(dragDropOverlay).isVisible = false;
- }
- },
- false
- );
-
- // Handle drop
- dragDropOverlay.addEventListener(
- "drop",
- (e) => {
- dragCounter = 0;
- Alpine.$data(dragDropOverlay).isVisible = false;
-
- const inputAD = Alpine.$data(inputSection);
- const files = e.dataTransfer.files;
- handleFiles(files, inputAD);
- },
- false
- );
- });
+ // Drag and drop functionality has been moved to attachmentsStore.js
- // Separate file handling logic to be used by both drag-drop and file input
- function handleFiles(files, inputAD) {
- Array.from(files).forEach((file) => {
- const ext = file.name.split(".").pop().toLowerCase();
-
- const isImage = ["jpg", "jpeg", "png", "bmp"].includes(ext);
-
- if (isImage) {
- const reader = new FileReader();
- reader.onload = (e) => {
- inputAD.attachments.push({
- file: file,
- url: e.target.result,
- type: "image",
- name: file.name,
- extension: ext,
- });
- inputAD.hasAttachments = true;
- };
- reader.readAsDataURL(file);
+ // Update handleFileUpload to use the attachments store
+ window.handleFileUpload = function(event) {
+ console.log('handleFileUpload called with files:', event.target.files.length);
+ const files = event.target.files;
+ if (window.Alpine && Alpine.store('chatAttachments')) {
+ console.log('Calling store handleFiles...');
+ Alpine.store('chatAttachments').handleFiles(files);
} else {
- inputAD.attachments.push({
- file: file,
- type: "file",
- name: file.name,
- extension: ext,
- });
- inputAD.hasAttachments = true;
+ console.error('Alpine or chatAttachments store not found!');
}
- });
}
- // Modify the existing handleFileUpload to use the new handleFiles function
- window.handleFileUpload = function (event) {
- const files = event.target.files;
- const inputAD = Alpine.$data(inputSection);
- handleFiles(files, inputAD);
- };
-
// Setup event handlers once the DOM is fully loaded
-document.addEventListener('DOMContentLoaded', function() {
- setupSidebarToggle();
- setupTabs();
- initializeActiveTab();
+document.addEventListener("DOMContentLoaded", function () {
+ setupSidebarToggle();
+ setupTabs();
+ initializeActiveTab();
});
// Setup tabs functionality
@@@ -1186,82 -1137,77 +1115,82 @@@ function setupTabs()
}
function activateTab(tabName) {
- const chatsTab = document.getElementById('chats-tab');
- const tasksTab = document.getElementById('tasks-tab');
- const chatsSection = document.getElementById('chats-section');
- const tasksSection = document.getElementById('tasks-section');
-
- // Get current context to preserve before switching
- const currentContext = context;
-
- // Store the current selection for the active tab before switching
- const previousTab = localStorage.getItem('activeTab');
- if (previousTab === 'chats') {
- localStorage.setItem('lastSelectedChat', currentContext);
- } else if (previousTab === 'tasks') {
- localStorage.setItem('lastSelectedTask', currentContext);
- }
-
- // Reset all tabs and sections
- chatsTab.classList.remove('active');
- tasksTab.classList.remove('active');
- chatsSection.style.display = 'none';
- tasksSection.style.display = 'none';
-
- // Remember the last active tab in localStorage
- localStorage.setItem('activeTab', tabName);
-
- // Activate selected tab and section
- if (tabName === 'chats') {
- chatsTab.classList.add('active');
- chatsSection.style.display = '';
+ const chatsTab = document.getElementById("chats-tab");
+ const tasksTab = document.getElementById("tasks-tab");
+ const chatsSection = document.getElementById("chats-section");
+ const tasksSection = document.getElementById("tasks-section");
+
+ // Get current context to preserve before switching
+ const currentContext = context;
+
+ // Store the current selection for the active tab before switching
+ const previousTab = localStorage.getItem("activeTab");
+ if (previousTab === "chats") {
+ localStorage.setItem("lastSelectedChat", currentContext);
+ } else if (previousTab === "tasks") {
+ localStorage.setItem("lastSelectedTask", currentContext);
+ }
+
+ // Reset all tabs and sections
+ chatsTab.classList.remove("active");
+ tasksTab.classList.remove("active");
+ chatsSection.style.display = "none";
+ tasksSection.style.display = "none";
+
+ // Remember the last active tab in localStorage
+ localStorage.setItem("activeTab", tabName);
+
+ // Activate selected tab and section
+ if (tabName === "chats") {
+ chatsTab.classList.add("active");
+ chatsSection.style.display = "";
- // Get the available contexts from Alpine.js data
- const chatsAD = Alpine.$data(chatsSection);
- const availableContexts = chatsAD.contexts || [];
+ // Get the available contexts from Alpine.js data
+ const chatsAD = window.Alpine ? Alpine.$data(chatsSection) : null;
+ const availableContexts = chatsAD?.contexts || [];
- // Restore previous chat selection
- const lastSelectedChat = localStorage.getItem('lastSelectedChat');
-
- // Only switch if:
- // 1. lastSelectedChat exists AND
- // 2. It's different from current context AND
- // 3. The context actually exists in our contexts list OR there are no contexts yet
- if (lastSelectedChat &&
- lastSelectedChat !== currentContext &&
- (availableContexts.some(ctx => ctx.id === lastSelectedChat) || availableContexts.length === 0)) {
- setContext(lastSelectedChat);
- }
- } else if (tabName === 'tasks') {
- tasksTab.classList.add('active');
- tasksSection.style.display = 'flex';
- tasksSection.style.flexDirection = 'column';
+ // Restore previous chat selection
+ const lastSelectedChat = localStorage.getItem("lastSelectedChat");
+
+ // Only switch if:
+ // 1. lastSelectedChat exists AND
+ // 2. It's different from current context AND
+ // 3. The context actually exists in our contexts list OR there are no contexts yet
+ if (
+ lastSelectedChat &&
+ lastSelectedChat !== currentContext &&
+ (availableContexts.some((ctx) => ctx.id === lastSelectedChat) ||
+ availableContexts.length === 0)
+ ) {
+ setContext(lastSelectedChat);
+ }
+ } else if (tabName === "tasks") {
+ tasksTab.classList.add("active");
+ tasksSection.style.display = "flex";
+ tasksSection.style.flexDirection = "column";
- // Get the available tasks from Alpine.js data
- const tasksAD = Alpine.$data(tasksSection);
- const availableTasks = tasksAD.tasks || [];
+ // Get the available tasks from Alpine.js data
+ const tasksAD = window.Alpine ? Alpine.$data(tasksSection) : null;
+ const availableTasks = tasksAD?.tasks || [];
- // Restore previous task selection
- const lastSelectedTask = localStorage.getItem('lastSelectedTask');
-
- // Only switch if:
- // 1. lastSelectedTask exists AND
- // 2. It's different from current context AND
- // 3. The task actually exists in our tasks list
- if (lastSelectedTask &&
- lastSelectedTask !== currentContext &&
- availableTasks.some(task => task.id === lastSelectedTask)) {
- setContext(lastSelectedTask);
- }
+ // Restore previous task selection
+ const lastSelectedTask = localStorage.getItem("lastSelectedTask");
+
+ // Only switch if:
+ // 1. lastSelectedTask exists AND
+ // 2. It's different from current context AND
+ // 3. The task actually exists in our tasks list
+ if (
+ lastSelectedTask &&
+ lastSelectedTask !== currentContext &&
+ availableTasks.some((task) => task.id === lastSelectedTask)
+ ) {
+ setContext(lastSelectedTask);
}
+ }
- // Request a poll update
- poll();
+ // Request a poll update
+ poll();
}
// Add function to initialize active tab and selections from localStorage
@@@ -1292,55 -1238,53 +1221,55 @@@ function initializeActiveTab()
// Open the scheduler detail view for a specific task
function openTaskDetail(taskId) {
- // Wait for Alpine.js to be fully loaded
- if (window.Alpine) {
- // Get the settings modal button and click it to ensure all init logic happens
- const settingsButton = document.getElementById('settings');
- if (settingsButton) {
- // Programmatically click the settings button
- settingsButton.click();
-
- // Now get a reference to the modal element
- const modalEl = document.getElementById('settingsModal');
- if (!modalEl) {
- console.error('Settings modal element not found after clicking button');
- return;
- }
+ // Wait for Alpine.js to be fully loaded
+ if (window.Alpine) {
+ // Get the settings modal button and click it to ensure all init logic happens
+ const settingsButton = document.getElementById("settings");
+ if (settingsButton) {
+ // Programmatically click the settings button
+ settingsButton.click();
+
+ // Now get a reference to the modal element
+ const modalEl = document.getElementById("settingsModal");
+ if (!modalEl) {
+ console.error("Settings modal element not found after clicking button");
+ return;
+ }
- // Get the Alpine.js data for the modal
- const modalData = Alpine.$data(modalEl);
+ // Get the Alpine.js data for the modal
+ const modalData = window.Alpine ? Alpine.$data(modalEl) : null;
- // Use a timeout to ensure the modal is fully rendered
- setTimeout(() => {
- // Switch to the scheduler tab first
- modalData.switchTab('scheduler');
+ // Use a timeout to ensure the modal is fully rendered
+ setTimeout(() => {
+ // Switch to the scheduler tab first
+ modalData.switchTab("scheduler");
- // Use another timeout to ensure the scheduler component is initialized
- setTimeout(() => {
- // Get the scheduler component
- const schedulerComponent = document.querySelector('[x-data="schedulerSettings"]');
- if (!schedulerComponent) {
- console.error('Scheduler component not found');
- return;
- }
+ // Use another timeout to ensure the scheduler component is initialized
+ setTimeout(() => {
+ // Get the scheduler component
+ const schedulerComponent = document.querySelector(
+ '[x-data="schedulerSettings"]'
+ );
+ if (!schedulerComponent) {
+ console.error("Scheduler component not found");
+ return;
+ }
- // Get the Alpine.js data for the scheduler component
- const schedulerData = Alpine.$data(schedulerComponent);
+ // Get the Alpine.js data for the scheduler component
+ const schedulerData = window.Alpine ? Alpine.$data(schedulerComponent) : null;
- // Show the task detail view for the specific task
- schedulerData.showTaskDetail(taskId);
+ // Show the task detail view for the specific task
+ schedulerData.showTaskDetail(taskId);
- console.log('Task detail view opened for task:', taskId);
- }, 50); // Give time for the scheduler tab to initialize
- }, 25); // Give time for the modal to render
- } else {
- console.error('Settings button not found');
- }
+ console.log("Task detail view opened for task:", taskId);
+ }, 50); // Give time for the scheduler tab to initialize
+ }, 25); // Give time for the modal to render
} else {
- console.error('Alpine.js not loaded');
+ console.error("Settings button not found");
}
+ } else {
+ console.error("Alpine.js not loaded");
+ }
}
// Make the function available globally