Skip to content

Agent Zero AI framework

non image generic icons working

decib4881359c8c1
diff --git a/python/api/image_get.py b/python/api/image_get.py
index ff33dd5a7..ec7c857d3 100644
--- a/python/api/image_get.py
+++ b/python/api/image_get.py
@@ -9,6 +9,10 @@ class ImageGet(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
# 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")
@@ -16,26 +20,42 @@ class ImageGet(ApiHandler):
if not files.is_in_base_dir(path):
raise ValueError("Path is outside of allowed directory")
- # get file extension
+ # 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
- return send_file(path)
+ # 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
- return self._get_file_type_icon(file_ext)
+ 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):
+ 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
@@ -80,21 +100,96 @@ class ImageGet(ApiHandler):
# Get icon name, default to 'file' if not found
icon_name = icon_mapping.get(file_ext, 'file')
- return self._get_fallback_icon(icon_name)
+ 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')
\ No newline at end of file
diff --git a/webui/components/chat/attachments/attachmentsStore.js b/webui/components/chat/attachments/attachmentsStore.js
index 4a9cb98be..94bf83127 100644
--- a/webui/components/chat/attachments/attachmentsStore.js
+++ b/webui/components/chat/attachments/attachmentsStore.js
@@ -229,6 +229,85 @@ const model = {
});
},
+ // 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) {
diff --git a/webui/js/messages.js b/webui/js/messages.js
index 8b13af69f..6862d1960 100644
--- a/webui/js/messages.js
+++ b/webui/js/messages.js
@@ -318,103 +318,116 @@ export function drawMessageUser(
const attachmentDiv = document.createElement("div");
attachmentDiv.classList.add("attachment-item");
- // Helper function to generate server-side image URL
+ // Get attachment store for enhanced device sync support
+ const attachmentStore = window.Alpine && window.Alpine.store('chatAttachments');
+
+ // Helper function to generate server-side image URL (fallback if store not available)
const getServerImageUrl = (filename) => {
+ if (attachmentStore) {
+ return attachmentStore.getServerFileUrl(filename);
+ }
return `/image_get?path=/a0/tmp/uploads/${encodeURIComponent(filename)}`;
};
- // Helper function to check if file is an image
+ // Helper function to check if file is an image (fallback if store not available)
const isImageFile = (filename) => {
+ if (attachmentStore) {
+ return attachmentStore.isImageFile(filename);
+ }
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
const extension = filename.split('.').pop().toLowerCase();
return imageExtensions.includes(extension);
};
- if (typeof attachment === "string") {
- // attachment is filename only (from persistent storage)
- const filename = attachment;
- const extension = filename.split(".").pop().toUpperCase();
-
- if (isImageFile(filename)) {
- // Render as image with server URL
- const imgWrapper = document.createElement("div");
- imgWrapper.classList.add("image-wrapper");
-
- const img = document.createElement("img");
- 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);
+ // Use enhanced attachment store methods for better device sync
+ let displayInfo;
+ if (attachmentStore) {
+ displayInfo = attachmentStore.getAttachmentDisplayInfo(attachment);
+ } else {
+ // Fallback for when store is not available
+ if (typeof attachment === "string") {
+ const filename = attachment;
+ const extension = filename.split(".").pop();
+ displayInfo = {
+ filename: filename,
+ extension: extension.toUpperCase(),
+ isImage: isImageFile(filename),
+ previewUrl: getServerImageUrl(filename),
+ clickHandler: () => {
+ if (isImageFile(filename) && window.Alpine && window.Alpine.store('chatAttachments')) {
+ window.Alpine.store('chatAttachments').openImageModal(getServerImageUrl(filename), filename);
+ }
}
- });
-
- const fileInfo = document.createElement("div");
- fileInfo.classList.add("file-info");
- fileInfo.innerHTML = `
- <span class="filename">${filename}</span>
- <span class="extension">${extension}</span>
- `;
-
- imgWrapper.appendChild(img);
- attachmentDiv.appendChild(imgWrapper);
- attachmentDiv.appendChild(fileInfo);
+ };
} else {
- // Render as file icon
- attachmentDiv.classList.add("file-type");
- attachmentDiv.innerHTML = `
- <div class="file-preview">
- <span class="filename">${filename}</span>
- <span class="extension">${extension}</span>
- </div>
- `;
+ displayInfo = {
+ filename: attachment.name,
+ extension: attachment.extension.toUpperCase(),
+ isImage: attachment.type === 'image',
+ previewUrl: attachment.url,
+ clickHandler: () => {
+ if (attachment.type === 'image' && window.Alpine && window.Alpine.store('chatAttachments')) {
+ window.Alpine.store('chatAttachments').openImageModal(attachment.url, attachment.name);
+ }
+ }
+ };
}
- } else if (attachment.type === "image") {
- // attachment is object (from current session)
+ }
+
+ if (displayInfo.isImage) {
+ // Render as image with enhanced device sync support
const imgWrapper = document.createElement("div");
imgWrapper.classList.add("image-wrapper");
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:')) {
- imageUrl = getServerImageUrl(attachment.name);
- } else {
- imageUrl = attachment.url;
- }
- img.src = imageUrl;
- img.alt = attachment.name;
+ img.src = displayInfo.previewUrl;
+ img.alt = displayInfo.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(imageUrl, attachment.name);
- }
- });
+ img.addEventListener('click', displayInfo.clickHandler);
const fileInfo = document.createElement("div");
fileInfo.classList.add("file-info");
fileInfo.innerHTML = `
- <span class="filename">${attachment.name}</span>
- <span class="extension">${attachment.extension.toUpperCase()}</span>
+ <span class="filename">${displayInfo.filename}</span>
+ <span class="extension">${displayInfo.extension}</span>
`;
imgWrapper.appendChild(img);
attachmentDiv.appendChild(imgWrapper);
attachmentDiv.appendChild(fileInfo);
} else {
- // attachment is object but not image (from current session)
+ // Render as file with icon support for device sync
attachmentDiv.classList.add("file-type");
- attachmentDiv.innerHTML = `
- <div class="file-preview">
- <span class="filename">${attachment.name}</span>
- <span class="extension">${attachment.extension.toUpperCase()}</span>
- </div>
- `;
+
+ // Create file preview with potential server-side icon
+ const filePreview = document.createElement("div");
+ filePreview.classList.add("file-preview");
+
+ // If we have a preview URL (server icon), show it
+ if (displayInfo.previewUrl && displayInfo.previewUrl !== displayInfo.filename) {
+ const iconImg = document.createElement("img");
+ iconImg.src = displayInfo.previewUrl;
+ iconImg.alt = `${displayInfo.extension} file`;
+ iconImg.classList.add("file-icon");
+ iconImg.style.width = "24px";
+ iconImg.style.height = "24px";
+ iconImg.style.marginRight = "8px";
+ filePreview.appendChild(iconImg);
+ }
+
+ const textInfo = document.createElement("div");
+ textInfo.innerHTML = `
+ <span class="filename">${displayInfo.filename}</span>
+ <span class="extension">${displayInfo.extension}</span>
+ `;
+ filePreview.appendChild(textInfo);
+
+ attachmentDiv.appendChild(filePreview);
}
+
+
attachmentsContainer.appendChild(attachmentDiv);
});