Skip to content

Agent Zero AI framework

history/context/image modals components

Alessandro5bb89301f663
diff --git a/webui/components/chat/attachments/attachmentsStore.js b/webui/components/chat/attachments/attachmentsStore.js
index bb159d2d1..5688b9e99 100644
--- a/webui/components/chat/attachments/attachmentsStore.js
+++ b/webui/components/chat/attachments/attachmentsStore.js
@@ -1,5 +1,6 @@
import { createStore } from "/js/AlpineStore.js";
import { fetchApi } from "/js/api.js";
+import { store as imageViewerStore } from "/components/modals/image-viewer-store.js";
const model = {
// State properties
@@ -7,13 +8,6 @@ const model = {
hasAttachments: false,
dragDropOverlayVisible: false,
- // Image modal properties
- currentImageUrl: null,
- currentImageName: null,
- imageLoaded: false,
- imageError: false,
- zoomLevel: 1,
-
async init() {
await this.initialize();
},
@@ -358,7 +352,7 @@ const model = {
previewUrl: previewUrl,
clickHandler: () => {
if (this.isImageFile(filename)) {
- this.openImageModal(this.getServerImgUrl(filename), filename);
+ imageViewerStore.open(this.getServerImgUrl(filename), { name: filename });
} else {
this.downloadAttachment(filename);
}
@@ -380,7 +374,7 @@ const model = {
clickHandler: () => {
if (attachment.type === "image") {
const imageUrl = this.getServerImgUrl(attachment.name);
- this.openImageModal(imageUrl, attachment.name);
+ imageViewerStore.open(imageUrl, { name: attachment.name });
} else {
this.downloadAttachment(attachment.name);
}
@@ -425,50 +419,6 @@ const model = {
);
},
- // 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})`;
- }
- },
};
const store = createStore("chatAttachments", model);
diff --git a/webui/components/chat/attachments/inputPreview.html b/webui/components/chat/attachments/inputPreview.html
index 0ed55365a..f7e979153 100644
--- a/webui/components/chat/attachments/inputPreview.html
+++ b/webui/components/chat/attachments/inputPreview.html
@@ -1,5 +1,6 @@
<script type="module">
import { store } from "/components/chat/attachments/attachmentsStore.js";
+ import { store as imageViewerStore } from "/components/modals/image-viewer-store.js";
</script>
<div x-data>
@@ -11,7 +12,7 @@
:class="{'image-type': attachment.type === 'image', 'file-type': attachment.type === 'file'}">
<template x-if="attachment.type === 'image'">
<img :src="attachment.url" class="attachment-preview" :alt="attachment.name" style="cursor: pointer;"
- @click="$store.chatAttachments.openImageModal(attachment.url, attachment.name)">
+ @click="$store.imageViewer.open(attachment.url, { name: attachment.name })">
</template>
<template x-if="attachment.type === 'file'">
<div>
diff --git a/webui/components/chat/input/bottom-actions.html b/webui/components/chat/input/bottom-actions.html
index 8c2d5260b..ea5b72063 100644
--- a/webui/components/chat/input/bottom-actions.html
+++ b/webui/components/chat/input/bottom-actions.html
@@ -40,14 +40,14 @@
<p>Files</p>
</button>
- <button class="text-button" id="history_inspect" @click="globalThis.openHistoryModal()">
+ <button class="text-button" id="history_inspect" @click="$store.history.open()">
<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.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-.942-2.478-.946-3.42,0Z"></path>
</svg>
<p>History</p>
</button>
- <button class="text-button" id="ctx_window" @click="globalThis.openCtxWindowModal()">
+ <button class="text-button" id="ctx_window" @click="$store.context.open()">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="17 15 70 70" fill="currentColor">
<path d="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"></path>
<path d="m63 79c1.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"></path>
diff --git a/webui/components/modals/context-store.js b/webui/components/modals/context-store.js
new file mode 100644
index 000000000..9687ce620
--- /dev/null
+++ b/webui/components/modals/context-store.js
@@ -0,0 +1,132 @@
+import { createStore } from "/js/AlpineStore.js";
+
+const model = {
+ // State
+ isLoading: false,
+ contextData: null,
+ tokenCount: 0,
+ error: null,
+ editor: null,
+ closePromise: null,
+
+ // Open Context Window modal
+ async open() {
+ if (this.isLoading) return; // Prevent double-open
+
+ this.isLoading = true;
+ this.error = null;
+ this.contextData = null;
+ this.tokenCount = 0;
+
+ try {
+ // Open modal FIRST (immediate UI feedback, but DON'T await)
+ this.closePromise = window.openModal('modals/context.html');
+
+ // Setup cleanup on modal close
+ if (this.closePromise && typeof this.closePromise.then === 'function') {
+ this.closePromise.then(() => {
+ this.destroy();
+ });
+ }
+
+ this.updateModalTitle(); // Set initial "loading" title
+
+ // Fetch data from backend
+ const contextId = window.getContext();
+ const response = await window.sendJsonData('/ctx_window_get', {
+ context: contextId,
+ });
+
+ // Update state with data
+ this.contextData = response.content;
+ this.tokenCount = response.tokens || 0;
+ this.isLoading = false;
+ this.updateModalTitle(); // Update with token count
+
+ // Initialize ACE editor
+ this.scheduleEditorInit();
+
+ } catch (error) {
+ console.error("Context fetch error:", error);
+ this.error = error?.message || "Failed to load context window";
+ this.isLoading = false;
+ this.updateModalTitle(); // Show error in title
+ }
+ },
+
+ scheduleEditorInit() {
+ // Use double requestAnimationFrame to ensure DOM is ready
+ window.requestAnimationFrame(() => {
+ if (this.isLoading || this.error) return;
+ window.requestAnimationFrame(() => this.initEditor());
+ });
+ },
+
+ initEditor() {
+ const container = document.getElementById("context-viewer-container");
+ if (!container) {
+ console.warn("Context container not found, deferring editor init");
+ return;
+ }
+
+ // Destroy old instance if exists
+ if (this.editor?.destroy) {
+ this.editor.destroy();
+ }
+
+ // Check if ACE is available
+ if (!window.ace?.edit) {
+ console.error("ACE editor not available");
+ this.error = "Editor library not loaded";
+ return;
+ }
+
+ const editorInstance = window.ace.edit("context-viewer-container");
+ if (!editorInstance) {
+ console.error("Failed to create ACE editor instance");
+ return;
+ }
+
+ this.editor = editorInstance;
+
+ // Configure theme based on dark mode (legacy parity: != "false")
+ const darkMode = window.localStorage?.getItem("darkMode");
+ const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/tomorrow";
+
+ this.editor.setTheme(theme);
+ this.editor.session.setMode("ace/mode/markdown");
+ this.editor.setValue(this.contextData, -1); // -1 moves cursor to start
+ this.editor.setReadOnly(true);
+ this.editor.clearSelection();
+ },
+
+ updateModalTitle() {
+ window.requestAnimationFrame(() => {
+ const modalTitles = document.querySelectorAll(".modal.show .modal-title");
+ if (!modalTitles.length) return;
+
+ // Get the last (topmost) modal title
+ const title = modalTitles[modalTitles.length - 1];
+ if (!title) return;
+
+ if (this.error) {
+ title.textContent = "Context Window – Error";
+ } else if (this.isLoading) {
+ title.textContent = "Context Window (loading…)";
+ } else {
+ title.textContent = `Context Window ~${this.tokenCount} tokens`;
+ }
+ });
+ },
+
+ // Optional: cleanup method for lifecycle management
+ destroy() {
+ if (this.editor?.destroy) {
+ this.editor.destroy();
+ }
+ this.editor = null;
+ },
+};
+
+export const store = createStore("context", model);
+
diff --git a/webui/components/modals/context.html b/webui/components/modals/context.html
new file mode 100644
index 000000000..7ff537aa0
--- /dev/null
+++ b/webui/components/modals/context.html
@@ -0,0 +1,107 @@
+<html>
+<head>
+ <title>Context Window</title>
+ <script type="module">
+ import { store } from "/components/modals/context-store.js";
+ </script>
+</head>
+<body>
+ <div x-data>
+ <template x-if="$store.context">
+ <div class="context-modal-root">
+
+ <!-- Loading State -->
+ <template x-if="$store.context.isLoading">
+ <div class="loading-state">
+ <div class="loading-spinner"></div>
+ <p>Loading context window…</p>
+ </div>
+ </template>
+
+ <!-- Error State -->
+ <template x-if="$store.context.error">
+ <div class="error-state">
+ <p class="error-message" x-text="$store.context.error"></p>
+ </div>
+ </template>
+
+ <!-- Content (ACE Editor) -->
+ <template x-if="!$store.context.isLoading && !$store.context.error">
+ <div id="context-viewer-container"></div>
+ </template>
+
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .context-modal-root {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ min-height: 400px;
+ }
+
+ .loading-state,
+ .error-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: var(--spacing-lg);
+ min-height: 200px;
+ }
+
+ .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: var(--spacing-md);
+ }
+
+ @keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+
+ .loading-state p,
+ .error-state p {
+ color: var(--color-text-secondary);
+ margin: 0;
+ }
+
+ .error-message {
+ color: var(--color-error);
+ font-weight: 500;
+ }
+
+ /* ACE Editor Container */
+ #context-viewer-container {
+ width: 100%;
+ height: 71vh;
+ border-radius: 0.4rem;
+ overflow: auto;
+ }
+
+ #context-viewer-container::-webkit-scrollbar {
+ width: 0;
+ }
+
+ /* ACE Editor Scrollbar */
+ .ace_scrollbar-v {
+ overflow-y: auto;
+ }
+
+ /* Viewer Styles */
+ .context-modal-root {
+ overflow: hidden;
+ }
+ </style>
+
+</body>
+</html>
+
diff --git a/webui/components/modals/history-store.js b/webui/components/modals/history-store.js
new file mode 100644
index 000000000..4e934d759
--- /dev/null
+++ b/webui/components/modals/history-store.js
@@ -0,0 +1,132 @@
+import { createStore } from "/js/AlpineStore.js";
+
+const model = {
+ // State
+ isLoading: false,
+ historyData: null,
+ tokenCount: 0,
+ error: null,
+ editor: null,
+ closePromise: null,
+
+ // Open History modal
+ async open() {
+ if (this.isLoading) return; // Prevent double-open
+
+ this.isLoading = true;
+ this.error = null;
+ this.historyData = null;
+ this.tokenCount = 0;
+
+ try {
+ // Open modal FIRST (immediate UI feedback, but DON'T await)
+ this.closePromise = window.openModal('modals/history.html');
+
+ // Setup cleanup on modal close
+ if (this.closePromise && typeof this.closePromise.then === 'function') {
+ this.closePromise.then(() => {
+ this.destroy();
+ });
+ }
+
+ this.updateModalTitle(); // Set initial "loading" title
+
+ // Fetch data from backend
+ const contextId = window.getContext();
+ const response = await window.sendJsonData('/history_get', {
+ context: contextId,
+ });
+
+ // Update state with data
+ this.historyData = response.history;
+ this.tokenCount = response.tokens || 0;
+ this.isLoading = false;
+ this.updateModalTitle(); // Update with token count
+
+ // Initialize ACE editor
+ this.scheduleEditorInit();
+
+ } catch (error) {
+ console.error("History fetch error:", error);
+ this.error = error?.message || "Failed to load history";
+ this.isLoading = false;
+ this.updateModalTitle(); // Show error in title
+ }
+ },
+
+ scheduleEditorInit() {
+ // Use double requestAnimationFrame to ensure DOM is ready
+ window.requestAnimationFrame(() => {
+ if (this.isLoading || this.error) return;
+ window.requestAnimationFrame(() => this.initEditor());
+ });
+ },
+
+ initEditor() {
+ const container = document.getElementById("history-viewer-container");
+ if (!container) {
+ console.warn("History container not found, deferring editor init");
+ return;
+ }
+
+ // Destroy old instance if exists
+ if (this.editor?.destroy) {
+ this.editor.destroy();
+ }
+
+ // Check if ACE is available
+ if (!window.ace?.edit) {
+ console.error("ACE editor not available");
+ this.error = "Editor library not loaded";
+ return;
+ }
+
+ const editorInstance = window.ace.edit("history-viewer-container");
+ if (!editorInstance) {
+ console.error("Failed to create ACE editor instance");
+ return;
+ }
+
+ this.editor = editorInstance;
+
+ // Configure theme based on dark mode (legacy parity: != "false")
+ const darkMode = window.localStorage?.getItem("darkMode");
+ const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/tomorrow";
+
+ this.editor.setTheme(theme);
+ this.editor.session.setMode("ace/mode/markdown");
+ this.editor.setValue(this.historyData, -1); // -1 moves cursor to start
+ this.editor.setReadOnly(true);
+ this.editor.clearSelection();
+ },
+
+ updateModalTitle() {
+ window.requestAnimationFrame(() => {
+ const modalTitles = document.querySelectorAll(".modal.show .modal-title");
+ if (!modalTitles.length) return;
+
+ // Get the last (topmost) modal title
+ const title = modalTitles[modalTitles.length - 1];
+ if (!title) return;
+
+ if (this.error) {
+ title.textContent = "History – Error";
+ } else if (this.isLoading) {
+ title.textContent = "History (loading…)";
+ } else {
+ title.textContent = `History ~${this.tokenCount} tokens`;
+ }
+ });
+ },
+
+ // Optional: cleanup method for lifecycle management
+ destroy() {
+ if (this.editor?.destroy) {
+ this.editor.destroy();
+ }
+ this.editor = null;
+ },
+};
+
+export const store = createStore("history", model);
+
diff --git a/webui/components/modals/history.html b/webui/components/modals/history.html
new file mode 100644
index 000000000..551a25b2e
--- /dev/null
+++ b/webui/components/modals/history.html
@@ -0,0 +1,107 @@
+<html>
+<head>
+ <title>History</title>
+ <script type="module">
+ import { store } from "/components/modals/history-store.js";
+ </script>
+</head>
+<body>
+ <div x-data>
+ <template x-if="$store.history">
+ <div class="history-modal-root">
+
+ <!-- Loading State -->
+ <template x-if="$store.history.isLoading">
+ <div class="loading-state">
+ <div class="loading-spinner"></div>
+ <p>Loading history…</p>
+ </div>
+ </template>
+
+ <!-- Error State -->
+ <template x-if="$store.history.error">
+ <div class="error-state">
+ <p class="error-message" x-text="$store.history.error"></p>
+ </div>
+ </template>
+
+ <!-- Content (ACE Editor) -->
+ <template x-if="!$store.history.isLoading && !$store.history.error">
+ <div id="history-viewer-container"></div>
+ </template>
+
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .history-modal-root {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ min-height: 400px;
+ }
+
+ .loading-state,
+ .error-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: var(--spacing-lg);
+ min-height: 200px;
+ }
+
+ .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: var(--spacing-md);
+ }
+
+ @keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+
+ .loading-state p,
+ .error-state p {
+ color: var(--color-text-secondary);
+ margin: 0;
+ }
+
+ .error-message {
+ color: var(--color-error);
+ font-weight: 500;
+ }
+
+ /* ACE Editor Container */
+ #history-viewer-container {
+ width: 100%;
+ height: 71vh;
+ border-radius: 0.4rem;
+ overflow: auto;
+ }
+
+ #history-viewer-container::-webkit-scrollbar {
+ width: 0;
+ }
+
+ /* ACE Editor Scrollbar */
+ .ace_scrollbar-v {
+ overflow-y: auto;
+ }
+
+ /* Viewer Styles (legacy parity) */
+ .history-modal-root {
+ overflow: hidden;
+ }
+ </style>
+
+</body>
+</html>
+
diff --git a/webui/components/modals/image-viewer-store.js b/webui/components/modals/image-viewer-store.js
new file mode 100644
index 000000000..473445b1f
--- /dev/null
+++ b/webui/components/modals/image-viewer-store.js
@@ -0,0 +1,188 @@
+import { createStore } from "/js/AlpineStore.js";
+
+const model = {
+ // State
+ currentImageUrl: null,
+ currentImageName: null,
+ baseImageUrl: null,
+ imageLoaded: false,
+ imageError: false,
+ zoomLevel: 1,
+ refreshInterval: 0,
+ activeIntervalId: null,
+ closePromise: null,
+
+ /**
+ * Open image viewer modal
+ * @param {string} imageUrl - URL of the image to display
+ * @param {number|object} refreshOrOptions - Either:
+ * - number: refresh interval in ms (legacy compat)
+ * - object: { refreshInterval?: number, name?: string }
+ */
+ async open(imageUrl, refreshOrOptions) {
+ // Parse options (backward compatibility)
+ const options = typeof refreshOrOptions === 'number'
+ ? { refreshInterval: refreshOrOptions, name: null }
+ : refreshOrOptions || {};
+
+ // Reset state
+ this.baseImageUrl = imageUrl;
+ this.refreshInterval = options.refreshInterval || 0;
+ this.currentImageName = options.name || this.extractImageName(imageUrl);
+ this.imageLoaded = false;
+ this.imageError = false;
+ this.zoomLevel = 1;
+
+ // Add timestamp for cache-busting if refreshing
+ this.currentImageUrl = this.refreshInterval > 0
+ ? this.addTimestamp(imageUrl)
+ : imageUrl;
+
+ try {
+ // Open modal and track close promise for cleanup
+ this.closePromise = window.openModal('modals/image-viewer.html');
+
+ // Setup cleanup on modal close
+ if (this.closePromise && typeof this.closePromise.finally === 'function') {
+ this.closePromise.finally(() => {
+ this.stopRefresh();
+ this.resetState();
+ });
+ }
+
+ // Start refresh loop if needed
+ if (this.refreshInterval > 0) {
+ this.setupAutoRefresh();
+ }
+ } catch (error) {
+ console.error("Image viewer error:", error);
+ this.imageError = true;
+ }
+ },
+
+ setupAutoRefresh() {
+ // Clear any existing interval
+ this.stopRefresh();
+
+ this.activeIntervalId = setInterval(() => {
+ if (!this.isModalVisible()) {
+ this.stopRefresh();
+ return;
+ }
+ this.preloadNextImage();
+ }, this.refreshInterval);
+ },
+
+ async preloadNextImage() {
+ const nextSrc = this.addTimestamp(this.baseImageUrl);
+
+ // Create a promise that resolves when the image is loaded
+ const preloadPromise = new Promise((resolve, reject) => {
+ const tempImg = new Image();
+ tempImg.onload = () => resolve(nextSrc);
+ tempImg.onerror = reject;
+ tempImg.src = nextSrc;
+ });
+
+ try {
+ // Wait for preload to complete
+ const loadedSrc = await preloadPromise;
+
+ // Check if modal is still visible before updating
+ if (this.isModalVisible()) {
+ this.currentImageUrl = loadedSrc;
+ this.imageLoaded = false; // Trigger reload animation
+ }
+ } catch (err) {
+ console.error('Failed to preload image:', err);
+ }
+ },
+
+ isModalVisible() {
+ const container = document.querySelector('#image-viewer-wrapper');
+ if (!container) return false;
+
+ // Check if element or any parent is hidden
+ let element = container;
+ while (element) {
+ const styles = window.getComputedStyle(element);
+ if (styles.display === 'none' || styles.visibility === 'hidden') {
+ return false;
+ }
+ element = element.parentElement;
+ }
+ return true;
+ },
+
+ stopRefresh() {
+ if (this.activeIntervalId !== null) {
+ clearInterval(this.activeIntervalId);
+ this.activeIntervalId = null;
+ }
+ },
+
+ resetState() {
+ this.currentImageUrl = null;
+ this.currentImageName = null;
+ this.baseImageUrl = null;
+ this.imageLoaded = false;
+ this.imageError = false;
+ this.zoomLevel = 1;
+ this.refreshInterval = 0;
+ },
+
+ // 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})`;
+ }
+ },
+
+ // Utility methods
+ addTimestamp(url) {
+ try {
+ const urlObj = new URL(url, window.location.origin);
+ urlObj.searchParams.set("t", Date.now().toString());
+ return urlObj.toString();
+ } catch (e) {
+ // Fallback for invalid URLs
+ const separator = url.includes('?') ? '&' : '?';
+ return `${url}${separator}t=${Date.now()}`;
+ }
+ },
+
+ extractImageName(url) {
+ try {
+ const urlObj = new URL(url, window.location.origin);
+ const pathname = urlObj.pathname;
+ return pathname.split("/").pop() || "Image";
+ } catch (e) {
+ return url.split("/").pop() || "Image";
+ }
+ },
+
+ // Optional: cleanup on store destruction
+ destroy() {
+ this.stopRefresh();
+ this.resetState();
+ },
+};
+
+export const store = createStore("imageViewer", model);
+
diff --git a/webui/components/chat/attachments/imageModal.html b/webui/components/modals/image-viewer.html
similarity index 74%
rename from webui/components/chat/attachments/imageModal.html
rename to webui/components/modals/image-viewer.html
index a14800456..ab9d81717 100644
--- a/webui/components/chat/attachments/imageModal.html
+++ b/webui/components/modals/image-viewer.html
@@ -4,42 +4,42 @@
<title>Image Viewer</title>
<script type="module">
- import { store } from "/components/chat/attachments/attachmentsStore.js";
+ import { store } from "/components/modals/image-viewer-store.js";
</script>
</head>
<body>
<div x-data>
- <template x-if="$store.chatAttachments">
- <div id="image-modal-content" class="image-modal-container">
+ <template x-if="$store.imageViewer">
+ <div id="image-viewer-wrapper" 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'"
+ x-show="$store.imageViewer.currentImageUrl"
+ :src="$store.imageViewer.currentImageUrl"
+ :alt="$store.imageViewer.currentImageName || 'Image'"
class="modal-image"
- @load="$store.chatAttachments.imageLoaded = true"
- @error="$store.chatAttachments.imageError = true"
+ @load="$store.imageViewer.imageLoaded = true"
+ @error="$store.imageViewer.imageError = true"
/>
<!-- Loading indicator -->
- <div x-show="!$store.chatAttachments.imageLoaded && !$store.chatAttachments.imageError" class="loading-indicator">
+ <div x-show="!$store.imageViewer.imageLoaded && !$store.imageViewer.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">
+ <div x-show="$store.imageViewer.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>
+ <button @click="$store.imageViewer.zoomOut()" class="zoom-btn" title="Zoom Out">−</button>
+ <button @click="$store.imageViewer.resetZoom()" class="zoom-btn" title="Reset">⌂</button>
+ <button @click="$store.imageViewer.zoomIn()" class="zoom-btn" title="Zoom In">+</button>
</div>
</div>
</template>
@@ -145,4 +145,5 @@
</body>
-</html>
\ No newline at end of file
+</html>
+
diff --git a/webui/css/history.css b/webui/css/history.css
deleted file mode 100644
index 6608c97ae..000000000
--- a/webui/css/history.css
+++ /dev/null
@@ -1,25 +0,0 @@
-/* History Styles */
-
-/* ACE Editor Scrollbar */
-.ace_scrollbar-v {
- overflow-y: auto;
- }
-
- /* JSON Viewer Container */
- #json-viewer-container {
- width: 100%;
- height: 71vh;
- border-radius: 0.4rem;
- overflow: auto;
- }
-
- #json-viewer-container::-webkit-scrollbar {
- width: 0;
- }
-
- /* Viewer Styles */
- .history-viewer {
- overflow: hidden;
- margin-bottom: 0.5rem;
- }
-
\ No newline at end of file
diff --git a/webui/index.html b/webui/index.html
index a76a637b4..113dcf592 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -14,7 +14,6 @@
<link rel="stylesheet" href="css/modals.css">
<link rel="stylesheet" href="css/modals2.css">
<link rel="stylesheet" href="css/speech.css">
- <link rel="stylesheet" href="css/history.css">
<link rel="stylesheet" href="css/scheduler-datepicker.css">
<link rel="stylesheet" href="css/notification.css">
@@ -97,7 +96,6 @@
<!-- Load module scripts first -->
<script type="module" src="js/scheduler.js"></script>
- <script type="module" src="js/history.js"></script>
<script type="module" src="index.js"></script>
@@ -127,7 +125,6 @@
<!-- Non-module scripts after Alpine.js -->
<script type="text/javascript" src="js/settings.js"></script>
<script type="text/javascript" src="js/file_browser.js"></script>
- <script type="text/javascript" src="js/modal.js"></script>
<script type="module" src="js/tunnel.js"></script>
<script>
// Expose git info for sidebar component
diff --git a/webui/js/history.js b/webui/js/history.js
deleted file mode 100644
index c071c53bf..000000000
--- a/webui/js/history.js
+++ /dev/null
@@ -1,55 +0,0 @@
-import { getContext } from "../index.js";
-
-export async function openHistoryModal() {
- try {
- const hist = await window.sendJsonData("/history_get", { context: getContext() });
- // const data = JSON.stringify(hist.history, null, 4);
- const data = hist.history
- const size = hist.tokens
- await showEditorModal(data, "markdown", `History ~${size} tokens`, "Conversation history visible to the LLM. History is compressed to fit into the context window over time.");
- } catch (e) {
- window.toastFrontendError("Error fetching history: " + e.message, "Chat History Error");
- return
- }
-}
-
-export async function openCtxWindowModal() {
- try {
- const win = await window.sendJsonData("/ctx_window_get", { context: getContext() });
- const data = win.content
- const size = win.tokens
- await showEditorModal(data, "markdown", `Context window ~${size} tokens`, "Data passed to the LLM during last interaction. Contains system message, conversation history and RAG.");
- } catch (e) {
- window.toastFrontendError("Error fetching context: " + e.message, "Context Error");
- return
- }
-}
-
-async function showEditorModal(data, type = "json", title, description = "") {
- // Generate the HTML with JSON Viewer container
- const html = `<div id="json-viewer-container"></div>`;
-
- // Open the modal with the generated HTML
- await window.genericModalProxy.openModal(title, description, html, ["history-viewer"]);
-
- // Initialize the JSON Viewer after the modal is rendered
- const container = document.getElementById("json-viewer-container");
- if (container) {
- const editor = ace.edit("json-viewer-container");
-
- const dark = localStorage.getItem('darkMode')
- if (dark != "false") {
- editor.setTheme("ace/theme/github_dark");
- } else {
- editor.setTheme("ace/theme/tomorrow");
- }
-
- editor.session.setMode("ace/mode/" + type);
- editor.setValue(data);
- editor.clearSelection();
- // editor.session.$toggleFoldWidget(5, {})
- }
-}
-
-window.openHistoryModal = openHistoryModal;
-window.openCtxWindowModal = openCtxWindowModal;
diff --git a/webui/js/image_modal.js b/webui/js/image_modal.js
deleted file mode 100644
index 6c6bc1e49..000000000
--- a/webui/js/image_modal.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Singleton interval ID for image refresh
-let activeIntervalId = null;
-
-export async function openImageModal(src, refreshInterval = 0) {
- try {
- let imgSrc = src;
-
- // Clear any existing refresh interval
- if (activeIntervalId !== null) {
- clearInterval(activeIntervalId);
- activeIntervalId = null;
- }
-
- if (refreshInterval > 0) {
- // Add or update timestamp to bypass cache
- const addTimestamp = (url) => {
- const urlObj = new URL(url, window.location.origin);
- urlObj.searchParams.set('t', Date.now());
- return urlObj.toString();
- };
-
- // Check if image viewer is still active
- const isImageViewerActive = () => {
- const container = document.querySelector('#image-viewer-container');
- if (!container) return false;
-
- // Check if element or any parent is hidden
- let element = container;
- while (element) {
- const style = window.getComputedStyle(element);
- if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
- return false;
- }
- element = element.parentElement;
- }
- return true;
- };
-
- // Preload next image before displaying
- const preloadAndUpdate = async (currentImg) => {
- const nextSrc = addTimestamp(src);
- // Create a promise that resolves when the image is loaded
- const preloadPromise = new Promise((resolve, reject) => {
- const tempImg = new Image();
- tempImg.onload = () => resolve(nextSrc);
- tempImg.onerror = reject;
- tempImg.src = nextSrc;
- });
-
- try {
- // Wait for preload to complete
- const loadedSrc = await preloadPromise;
- // Check if this interval is still the active one
- if (currentImg && isImageViewerActive()) {
- currentImg.src = loadedSrc;
- }
- } catch (err) {
- console.error('Failed to preload image:', err);
- }
- };
-
- imgSrc = addTimestamp(src);
-
- // Set up periodic refresh with preloading
- activeIntervalId = setInterval(() => {
- if (!isImageViewerActive()) {
- clearInterval(activeIntervalId);
- activeIntervalId = null;
- return;
- }
- const img = document.querySelector('.image-viewer-img');
- if (img) {
- preloadAndUpdate(img);
- }
- }, refreshInterval);
- }
-
- const html = `<div id="image-viewer-container"><img class="image-viewer-img" src="${imgSrc}" /></div>`;
- const fileName = src.split("/").pop();
-
- // Open the modal with the generated HTML
- await window.genericModalProxy.openModal(fileName, "", html);
- } catch (e) {
- window.toastFrontendError("Error fetching history: " + e.message, "Image History Error");
- return;
- }
-}
diff --git a/webui/js/messages.js b/webui/js/messages.js
index 89c056eea..c05494ce6 100644
--- a/webui/js/messages.js
+++ b/webui/js/messages.js
@@ -1,5 +1,5 @@
// message actions and components
-import { openImageModal } from "./image_modal.js";
+import { store as imageViewerStore } from "/components/modals/image-viewer-store.js";
import { marked } from "../vendor/marked/marked.esm.js";
import { store as _messageResizeStore } from "/components/messages/resize/message-resize-store.js"; // keep here, required in html
import { store as attachmentsStore } from "/components/chat/attachments/attachmentsStore.js";
@@ -852,7 +852,7 @@ function drawKvpsIncremental(container, kvps, latex) {
// Add click handler and cursor change
imgElement.style.cursor = "pointer";
imgElement.addEventListener("click", () => {
- openImageModal(imgElement.src, 1000);
+ imageViewerStore.open(imgElement.src, { refreshInterval: 1000 });
});
} else {
const pre = document.createElement("pre");
diff --git a/webui/js/modal.js b/webui/js/modal.js
deleted file mode 100644
index b4c12b24d..000000000
--- a/webui/js/modal.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// Full-Screen Input Modal logic moved to /components/modals/full-screen-store.js
-// Keep only other modals here.
-
-const genericModalProxy = {
- isOpen: false,
- isLoading: false,
- title: '',
- description: '',
- html: '',
-
- async openModal(title, description, html, contentClasses = []) {
- const modalEl = document.getElementById('genericModal');
- const modalContent = document.getElementById('viewer');
- const modalAD = Alpine.$data(modalEl);
-
- modalAD.isOpen = true;
- modalAD.title = title
- modalAD.description = description
- modalAD.html = html
-
- modalContent.className = 'modal-content';
- modalContent.classList.add(...contentClasses);
- },
-
- handleClose() {
- this.isOpen = false;
- }
-}
-
-// Wait for Alpine to be ready
-document.addEventListener('alpine:init', () => {
- Alpine.data('genericModalProxy', () => ({
- init() {
- Object.assign(this, genericModalProxy);
- // Ensure immediate file fetch when modal opens
- this.$watch('isOpen', async (value) => {
- // what now?
- });
- }
- }));
-});
-
-// Keep the global assignment for backward compatibility
-window.genericModalProxy = genericModalProxy;
\ No newline at end of file