~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Fix UI components and API endpoints for history and results pages
hashedvikingd8015162e457
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 9263b8f35f..bb00b4fded 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -127,7 +127,7 @@ def register_blueprints(app):# Register blueprintsapp.register_blueprint(research_bp)- app.register_blueprint(history_bp)+ app.register_blueprint(history_bp, url_prefix='/research/api')# Add root route redirect@app.route("/")diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex 3f0dcd4dd5..066ab164c9 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -9,7 +9,7 @@ from ..models.database import get_db_connection, get_logs_for_researchlogger = logging.getLogger(__name__)# Create a Blueprint for the history routes-history_bp = Blueprint("history", __name__, url_prefix="/api")+history_bp = Blueprint("history", __name__)@history_bp.route("/history", methods=["GET"])def get_history():@@ -90,8 +90,14 @@ def get_history():history.append(item)+ # Format response to match what client expects+ response_data = {+ "status": "success",+ "items": history # Use 'items' key as expected by client+ }+# Add CORS headers- response = make_response(jsonify(history))+ response = make_response(jsonify(response_data))response.headers.add("Access-Control-Allow-Origin", "*")response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization"@@ -104,7 +110,7 @@ def get_history():print(f"Error getting history: {str(e)}")print(traceback.format_exc())# Return empty array with CORS headers- response = make_response(jsonify([]))+ response = make_response(jsonify({"status": "error", "items": [], "message": str(e)}))response.headers.add("Access-Control-Allow-Origin", "*")response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization"diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex a22ae16260..b49408090e 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -45,16 +45,14 @@ def index():# Add the missing static file serving route@research_bp.route("/static/<path:path>")def serve_static(path):- """Serve static files for the research blueprint"""- try:- PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"- with importlib_resources.as_file(PACKAGE_DIR) as package_dir:- static_dir = package_dir / "static"- return send_from_directory(static_dir, path)- except Exception as e:- print(f"Error serving static file: {e}")- # Fallback to regular static path- return send_from_directory("static", path)+ """Serve static files"""+ return send_from_directory(os.path.join(os.path.dirname(os.path.dirname(__file__)), "static"), path)++# Add static route at the root level+@research_bp.route("/redirect-static/<path:path>")+def redirect_static(path):+ """Redirect old static URLs to new static URLs"""+ return redirect(url_for('static', filename=path))@research_bp.route("/progress/<int:research_id>")def progress_page(research_id):diff --git a/src/local_deep_research/web/static/js/components/fallback/formatting.js b/src/local_deep_research/web/static/js/components/fallback/formatting.jsnew file mode 100644index 0000000000..240d202ddf--- /dev/null+++ b/src/local_deep_research/web/static/js/components/fallback/formatting.js@@ -0,0 +1,122 @@+/**+ * Formatting Fallback Utilities+ * Basic implementations of formatting utilities that can be used if the main formatting module is not available+ */+(function() {+ // Only initialize if window.formatting is not already defined+ if (window.formatting) {+ console.log('Main formatting utilities already available, skipping fallback');+ return;+ }++ console.log('Initializing fallback formatting utilities');++ /**+ * Format a date+ * @param {string} dateStr - ISO date string+ * @returns {string} Formatted date+ */+ function formatDate(dateStr) {+ if (!dateStr) return 'N/A';++ try {+ const date = new Date(dateStr);+ return date.toLocaleString(undefined, {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit'+ });+ } catch (e) {+ console.error('Error formatting date:', e);+ return dateStr;+ }+ }++ /**+ * Format a status string+ * @param {string} status - Status code+ * @returns {string} Formatted status+ */+ function formatStatus(status) {+ if (!status) return 'Unknown';++ const statusMap = {+ 'in_progress': 'In Progress',+ 'completed': 'Completed',+ 'failed': 'Failed',+ 'suspended': 'Suspended',+ 'pending': 'Pending',+ 'error': 'Error'+ };++ return statusMap[status] || status;+ }++ /**+ * Format a mode string+ * @param {string} mode - Mode code+ * @returns {string} Formatted mode+ */+ function formatMode(mode) {+ if (!mode) return 'Unknown';++ const modeMap = {+ 'quick': 'Quick Summary',+ 'detailed': 'Detailed Report',+ 'standard': 'Standard Research',+ 'advanced': 'Advanced Research'+ };++ return modeMap[mode] || mode;+ }++ /**+ * Format duration in seconds to readable text+ * @param {number} seconds - Duration in seconds+ * @returns {string} Formatted duration+ */+ function formatDuration(seconds) {+ if (!seconds && seconds !== 0) return 'N/A';++ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = seconds % 60;++ if (minutes === 0) {+ return `${remainingSeconds}s`;+ } else {+ return `${minutes}m ${remainingSeconds}s`;+ }+ }++ /**+ * Format file size in bytes to human readable format+ * @param {number} bytes - Size in bytes+ * @returns {string} Formatted size+ */+ function formatFileSize(bytes) {+ if (!bytes && bytes !== 0) return 'N/A';++ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ let size = bytes;+ let unitIndex = 0;++ while (size >= 1024 && unitIndex < units.length - 1) {+ size /= 1024;+ unitIndex++;+ }++ return `${size.toFixed(1)} ${units[unitIndex]}`;+ }++ // Export utilities to window.formatting+ window.formatting = {+ formatDate,+ formatStatus,+ formatMode,+ formatDuration,+ formatFileSize+ };+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/fallback/ui.js b/src/local_deep_research/web/static/js/components/fallback/ui.jsnew file mode 100644index 0000000000..b650cfc8aa--- /dev/null+++ b/src/local_deep_research/web/static/js/components/fallback/ui.js@@ -0,0 +1,177 @@+/**+ * UI Fallback Utilities+ * Basic implementations of UI utilities that can be used if the main UI module is not available+ */+(function() {+ // Only initialize if window.ui is not already defined+ if (window.ui) {+ console.log('Main UI utilities already available, skipping fallback');+ return;+ }++ console.log('Initializing fallback UI utilities');++ /**+ * Show a loading spinner+ * @param {HTMLElement} container - Container element for spinner+ * @param {string} message - Optional loading message+ */+ function showSpinner(container, message) {+ if (!container) container = document.body;+ const spinnerHtml = `+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ ${message ? `<div class="spinner-message">${message}</div>` : ''}+ </div>+ `;+ container.innerHTML = spinnerHtml;+ }++ /**+ * Hide loading spinner+ * @param {HTMLElement} container - Container with spinner+ */+ function hideSpinner(container) {+ if (!container) container = document.body;+ const spinner = container.querySelector('.loading-spinner');+ if (spinner) {+ spinner.remove();+ }+ }++ /**+ * Show an error message+ * @param {string} message - Error message to display+ */+ function showError(message) {+ console.error(message);++ // Create a notification element+ const notification = document.createElement('div');+ notification.className = 'notification error';+ notification.innerHTML = `+ <i class="fas fa-exclamation-circle"></i>+ <span>${message}</span>+ <button class="close-notification"><i class="fas fa-times"></i></button>+ `;++ // Add to the page if a notification container exists, otherwise use alert+ const container = document.querySelector('.notifications-container');+ if (container) {+ container.appendChild(notification);++ // Remove after a delay+ setTimeout(() => {+ notification.classList.add('removing');+ setTimeout(() => notification.remove(), 500);+ }, 5000);++ // Set up close button+ const closeBtn = notification.querySelector('.close-notification');+ if (closeBtn) {+ closeBtn.addEventListener('click', () => {+ notification.classList.add('removing');+ setTimeout(() => notification.remove(), 500);+ });+ }+ } else {+ // Fallback to alert+ alert(message);+ }+ }++ /**+ * Show a success/info message+ * @param {string} message - Message to display+ */+ function showMessage(message) {+ console.log(message);++ // Create a notification element+ const notification = document.createElement('div');+ notification.className = 'notification success';+ notification.innerHTML = `+ <i class="fas fa-check-circle"></i>+ <span>${message}</span>+ <button class="close-notification"><i class="fas fa-times"></i></button>+ `;++ // Add to the page if a notification container exists, otherwise use alert+ const container = document.querySelector('.notifications-container');+ if (container) {+ container.appendChild(notification);++ // Remove after a delay+ setTimeout(() => {+ notification.classList.add('removing');+ setTimeout(() => notification.remove(), 500);+ }, 5000);++ // Set up close button+ const closeBtn = notification.querySelector('.close-notification');+ if (closeBtn) {+ closeBtn.addEventListener('click', () => {+ notification.classList.add('removing');+ setTimeout(() => notification.remove(), 500);+ });+ }+ } else {+ // Fallback to alert+ alert(message);+ }+ }++ /**+ * Simple markdown renderer+ * @param {string} markdown - Markdown content+ * @returns {string} HTML content+ */+ function renderMarkdown(markdown) {+ if (!markdown) return '';++ // This is a very basic markdown renderer for fallback purposes+ let html = markdown;++ // Convert headers+ html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');+ html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');+ html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');+ html = html.replace(/^#### (.*$)/gm, '<h4>$1</h4>');+ html = html.replace(/^##### (.*$)/gm, '<h5>$1</h5>');++ // Convert code blocks+ html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');++ // Convert inline code+ html = html.replace(/`([^`]+)`/g, '<code>$1</code>');++ // Convert bold+ html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');++ // Convert italic+ html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');++ // Convert links+ html = html.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');++ // Convert paragraphs - this is simplistic+ html = html.replace(/\n\s*\n/g, '</p><p>');+ html = '<p>' + html + '</p>';++ // Fix potentially broken paragraph tags+ html = html.replace(/<\/p><p><\/p><p>/g, '</p><p>');+ html = html.replace(/<\/p><p><(h[1-5])/g, '</p><$1');+ html = html.replace(/<\/(h[1-5])><p>/g, '</$1>');++ return html;+ }++ // Export utilities to window.ui+ window.ui = {+ showSpinner,+ hideSpinner,+ showError,+ showMessage,+ renderMarkdown+ };+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.jsindex 45946ecdcf..86160ad94d 100644--- a/src/local_deep_research/web/static/js/components/results.js+++ b/src/local_deep_research/web/static/js/components/results.js@@ -103,15 +103,20 @@*/async function fetchLogsForResearch(researchId) {try {+ console.log('Fetching logs for research ID:', researchId);+if (!window.api || !window.api.getResearchLogs) {console.warn('API service not available for logs');return;}- const logsData = await window.api.getResearchLogs(researchId);+ const response = await window.api.getResearchLogs(researchId);+ console.log('Log response:', response);- if (logsData && logsData.logs && Array.isArray(logsData.logs)) {- displayLogs(logsData.logs);+ if (response && response.status === 'success' && response.logs && Array.isArray(response.logs)) {+ displayLogs(response.logs);+ } else {+ console.warn('Invalid log data format:', response);}} catch (error) {console.error('Error fetching logs:', error);@@ -251,12 +256,31 @@researchData = await window.api.getReport(currentResearchId);- if (!researchData || !researchData.content) {+ if (!researchData) {throw new Error('No research results found');}+ // Handle different response structures+ if (researchData.status === 'success' && researchData.content) {+ // API returned {status: 'success', content: '...', metadata: {...}}+ if (researchData.metadata) {+ // Add metadata to the top level of researchData for easier access+ Object.assign(researchData, researchData.metadata);+ }+ } else if (typeof researchData.content === 'undefined') {+ // If content is missing, check if the data itself is the content+ if (researchData.query || researchData.title) {+ // This might be the complete research data, keep as is+ } else {+ throw new Error('Invalid research results format');+ }+ }+// Render resultsrenderResults(researchData);++ // Debug log for result data+ console.log('Research data:', researchData);} catch (error) {console.error('Error loading research results:', error);if (window.ui && window.ui.hideSpinner) {@@ -288,15 +312,34 @@renderMetadata(data);}+ // Determine content to render+ let contentToRender = '';+ if (data.status === 'success' && data.content) {+ // API returned {status: 'success', content: '...'}+ contentToRender = data.content;+ } else if (data.report_content) {+ // Some APIs might use report_content+ contentToRender = data.report_content;+ } else if (data.content) {+ // Direct content field+ contentToRender = data.content;+ } else {+ // No valid content found+ resultsContainer.innerHTML = '<p class="text-error">No research content available.</p>';+ return;+ }+// Render content- if (data.content) {+ if (contentToRender) {// Render markdownif (window.ui && window.ui.renderMarkdown) {- const renderedHtml = window.ui.renderMarkdown(data.content);- resultsContainer.innerHTML = renderedHtml;+ resultsContainer.innerHTML = window.ui.renderMarkdown(contentToRender);+ } else if (window.marked) {+ // Fallback to direct marked usage+ resultsContainer.innerHTML = `<div class="markdown-content">${window.marked.parse(contentToRender)}</div>`;} else {// Simple fallback - treat as pre-formatted text- resultsContainer.innerHTML = `<pre>${data.content}</pre>`;+ resultsContainer.innerHTML = `<pre>${contentToRender}</pre>`;}// Generate table of contents@@ -520,6 +563,31 @@}}+ // Set up global log filtering function+ window.filterLogsByType = function(type) {+ const logEntries = document.querySelectorAll('.console-log-entry');++ // Update filter button states+ const filterButtons = document.querySelectorAll('.log-filter .small-btn');+ filterButtons.forEach(btn => {+ btn.classList.remove('selected');+ });+ document.querySelector(`.log-filter .small-btn[onclick*="${type}"]`).classList.add('selected');++ // Show/hide log entries based on filter+ for (const entry of logEntries) {+ const badge = entry.querySelector('.log-badge');+ if (!badge) continue;++ const logType = badge.textContent.trim().toLowerCase();+ if (type === 'all' || logType === type) {+ entry.style.display = '';+ } else {+ entry.style.display = 'none';+ }+ }+ };+// Initialize on DOM content loadedif (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', initializeResults);diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 0e831e015d..1818df99b6 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -153,22 +153,24 @@ function showMessage(message, type = 'success', duration = 3000) {/*** Format and render Markdown content- * @param {string|Element} container - The container ID or element to render markdown into* @param {string} markdown - The markdown content+ * @returns {string} The rendered HTML*/-function renderMarkdown(container, markdown) {- const containerEl = typeof container === 'string' ? document.getElementById(container) : container;+function renderMarkdown(markdown) {+ if (!markdown) return '';- if (containerEl && window.marked) {- // Add a wrapper for proper styling- containerEl.innerHTML = `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;-- // Highlight code blocks if highlight.js is available- if (window.hljs) {- containerEl.querySelectorAll('pre code').forEach((block) => {- window.hljs.highlightBlock(block);- });+ try {+ if (window.marked) {+ // Add a wrapper for proper styling+ return `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;+ } else {+ // Fallback if marked is not available+ console.warn('Marked library not available for rendering markdown');+ return `<pre>${markdown}</pre>`;}+ } catch (error) {+ console.error('Error rendering markdown:', error);+ return `<pre>${markdown}</pre>`;}}diff --git a/src/local_deep_research/web/static/js/utils/formatting.js b/src/local_deep_research/web/static/js/utils/formatting.jsdeleted file mode 100644index 25a720409d..0000000000--- a/src/local_deep_research/web/static/js/utils/formatting.js+++ /dev/null@@ -1,119 +0,0 @@-/**- * Utility functions for formatting data- */--/**- * Format a status string to be more user-friendly- * @param {string} status - The status string- * @returns {string} The formatted status string- */-function formatStatus(status) {- switch(status) {- case 'in_progress': return 'In Progress';- case 'completed': return 'Completed';- case 'failed': return 'Failed';- case 'suspended': return 'Suspended';- default: return status.charAt(0).toUpperCase() + status.slice(1);- }-}--/**- * Format a research mode string to be more user-friendly- * @param {string} mode - The mode string- * @returns {string} The formatted mode string- */-function formatMode(mode) {- switch(mode) {- case 'quick': return 'Quick Summary';- case 'detailed': return 'Detailed Report';- default: return mode.charAt(0).toUpperCase() + mode.slice(1);- }-}--/**- * Format a date string with optional duration- * @param {string} date - The date string in ISO format- * @param {number|null} duration - Optional duration in seconds- * @returns {string} The formatted date string- */-function formatDate(date, duration = null) {- if (!date) return 'Unknown';-- try {- const dateObj = new Date(date);- const options = {- year: 'numeric',- month: 'short',- day: 'numeric',- hour: '2-digit',- minute: '2-digit'- };-- let formattedDate = dateObj.toLocaleDateString('en-US', options);-- if (duration) {- // Format the duration- const minutes = Math.floor(duration / 60);- const seconds = duration % 60;-- if (minutes > 0) {- formattedDate += ` (${minutes}m ${seconds}s)`;- } else {- formattedDate += ` (${seconds}s)`;- }- }-- return formattedDate;- } catch (e) {- console.error('Error formatting date:', e);- return date; // Return the original date if there's an error- }-}--/**- * Format a duration in seconds to a readable string- * @param {number} seconds - Duration in seconds- * @returns {string} Formatted duration string- */-function formatDuration(seconds) {- if (!seconds || isNaN(seconds)) return 'Unknown';-- const minutes = Math.floor(seconds / 60);- const remainingSeconds = Math.floor(seconds % 60);-- if (minutes === 0) {- return `${remainingSeconds}s`;- } else {- return `${minutes}m ${remainingSeconds}s`;- }-}--/**- * Capitalize the first letter of a string- * @param {string} string - The string to capitalize- * @returns {string} The capitalized string- */-function capitalizeFirstLetter(string) {- if (!string) return '';- return string.charAt(0).toUpperCase() + string.slice(1);-}--/**- * Format a number with thousands separators- * @param {number} num - The number to format- * @returns {string} Formatted number- */-function formatNumber(num) {- if (num === null || num === undefined) return '0';- return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");-}--// Export the functions to make them available to other modules-window.formatting = {- formatStatus,- formatMode,- formatDate,- formatDuration,- formatNumber,- capitalizeFirstLetter-};\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/utils/ui.js b/src/local_deep_research/web/static/js/utils/ui.jsdeleted file mode 100644index 0e831e015d..0000000000--- a/src/local_deep_research/web/static/js/utils/ui.js+++ /dev/null@@ -1,304 +0,0 @@-/**- * UI utility functions- */--/**- * Update a progress bar UI element- * @param {string|Element} fillElementId - The ID or element to fill- * @param {string|Element} percentageElementId - The ID or element to show percentage- * @param {number} percentage - The percentage to set- */-function updateProgressBar(fillElementId, percentageElementId, percentage) {- const progressFill = typeof fillElementId === 'string' ? document.getElementById(fillElementId) : fillElementId;- const progressPercentage = typeof percentageElementId === 'string' ? document.getElementById(percentageElementId) : percentageElementId;-- if (progressFill && progressPercentage) {- // Convert any value to a percentage between 0-100- const safePercentage = Math.min(100, Math.max(0, percentage || 0));-- // Update the width of the fill element- progressFill.style.width = `${safePercentage}%`;-- // Update the percentage text- progressPercentage.textContent = `${Math.round(safePercentage)}%`;-- // Add classes for visual feedback- if (safePercentage >= 100) {- progressFill.classList.add('complete');- } else {- progressFill.classList.remove('complete');- }- }-}--/**- * Show a loading spinner- * @param {string|Element} container - The container ID or element to add the spinner to- * @param {string} message - Optional message to show with the spinner- */-function showSpinner(container, message = 'Loading...') {- const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-- if (containerEl) {- containerEl.innerHTML = '';-- const spinnerHTML = `- <div class="loading-spinner centered">- <div class="spinner"></div>- ${message ? `<div class="spinner-message">${message}</div>` : ''}- </div>- `;-- containerEl.innerHTML = spinnerHTML;- }-}--/**- * Hide a loading spinner- * @param {string|Element} container - The container ID or element with the spinner- */-function hideSpinner(container) {- const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-- if (containerEl) {- const spinner = containerEl.querySelector('.loading-spinner');- if (spinner) {- spinner.remove();- }- }-}--/**- * Show an error message- * @param {string|Element} container - The container ID or element to add the error to- * @param {string} message - The error message- */-function showError(container, message) {- const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-- if (containerEl) {- const errorHTML = `- <div class="error-message">- <i class="fas fa-exclamation-circle"></i>- <span>${message}</span>- </div>- `;-- containerEl.innerHTML = errorHTML;- }-}--/**- * Show a notification message- * @param {string} message - The message to display- * @param {string} type - Message type: 'success', 'error', 'info', 'warning'- * @param {number} duration - How long to show the message in ms- */-function showMessage(message, type = 'success', duration = 3000) {- // Check if the toast container exists- let toastContainer = document.getElementById('toast-container');-- // Create it if it doesn't exist- if (!toastContainer) {- toastContainer = document.createElement('div');- toastContainer.id = 'toast-container';- document.body.appendChild(toastContainer);- }-- // Create a new toast- const toast = document.createElement('div');- toast.className = `toast toast-${type}`;-- // Add icon based on type- let icon = '';- switch (type) {- case 'success':- icon = '<i class="fas fa-check-circle"></i>';- break;- case 'error':- icon = '<i class="fas fa-exclamation-circle"></i>';- break;- case 'info':- icon = '<i class="fas fa-info-circle"></i>';- break;- case 'warning':- icon = '<i class="fas fa-exclamation-triangle"></i>';- break;- }-- // Set the content- toast.innerHTML = `- ${icon}- <div class="toast-message">${message}</div>- `;-- // Add to container- toastContainer.appendChild(toast);-- // Show with animation- setTimeout(() => {- toast.classList.add('visible');- }, 10);-- // Remove after duration- setTimeout(() => {- toast.classList.remove('visible');-- // Remove from DOM after animation- setTimeout(() => {- toast.remove();- }, 300);- }, duration);-}--/**- * Format and render Markdown content- * @param {string|Element} container - The container ID or element to render markdown into- * @param {string} markdown - The markdown content- */-function renderMarkdown(container, markdown) {- const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-- if (containerEl && window.marked) {- // Add a wrapper for proper styling- containerEl.innerHTML = `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;-- // Highlight code blocks if highlight.js is available- if (window.hljs) {- containerEl.querySelectorAll('pre code').forEach((block) => {- window.hljs.highlightBlock(block);- });- }- }-}--/**- * Create a dynamic favicon- * @param {string} emoji - The emoji to use for the favicon- */-function createDynamicFavicon(emoji = '⚡') {- // Create a canvas element- const canvas = document.createElement('canvas');- canvas.width = 64;- canvas.height = 64;-- // Get the 2D drawing context- const ctx = canvas.getContext('2d');-- // Clear the canvas- ctx.clearRect(0, 0, canvas.width, canvas.height);-- // Set font- ctx.font = '48px Arial';- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';-- // Draw the emoji- ctx.fillText(emoji, 32, 32);-- // Convert to data URL- const dataUrl = canvas.toDataURL('image/png');-- // Create or update the favicon link- let link = document.querySelector('link[rel="icon"]');- if (!link) {- link = document.createElement('link');- link.rel = 'icon';- document.head.appendChild(link);- }-- // Set the new favicon- link.href = dataUrl;-}--// Add CSS for toast messages-function addToastStyles() {- if (document.getElementById('toast-styles')) return;-- const styleEl = document.createElement('style');- styleEl.id = 'toast-styles';- styleEl.textContent = `- #toast-container {- position: fixed;- top: 20px;- right: 20px;- z-index: 9999;- display: flex;- flex-direction: column;- gap: 10px;- }-- .toast {- display: flex;- align-items: center;- gap: 10px;- background-color: var(--card-bg, #2a2a2a);- color: var(--text-color, #fff);- padding: 12px 16px;- border-radius: 8px;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);- max-width: 350px;- transform: translateX(120%);- opacity: 0;- transition: transform 0.3s ease, opacity 0.3s ease;- border-left: 4px solid transparent;- }-- .toast.visible {- transform: translateX(0);- opacity: 1;- }-- .toast i {- font-size: 1.2rem;- }-- .toast-success {- border-left-color: var(--success-color, #28a745);- }-- .toast-success i {- color: var(--success-color, #28a745);- }-- .toast-error {- border-left-color: var(--danger-color, #dc3545);- }-- .toast-error i {- color: var(--danger-color, #dc3545);- }-- .toast-info {- border-left-color: var(--info-color, #17a2b8);- }-- .toast-info i {- color: var(--info-color, #17a2b8);- }-- .toast-warning {- border-left-color: var(--warning-color, #ffc107);- }-- .toast-warning i {- color: var(--warning-color, #ffc107);- }- `;-- document.head.appendChild(styleEl);-}--// Add toast styles when the script loads-addToastStyles();--// Export the UI functions-window.ui = {- updateProgressBar,- showSpinner,- hideSpinner,- showError,- showMessage,- renderMarkdown,- createDynamicFavicon-};\ No newline at end of filediff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 9c12f2b859..e0368adea3 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -37,8 +37,8 @@<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script><!-- Core JS -->- <script src="{{ url_for('research.serve_static', path='js/utils/formatting.js') }}"></script>- <script src="{{ url_for('research.serve_static', path='js/utils/ui.js') }}"></script>+ <script src="{{ url_for('research.serve_static', path='js/services/formatting.js') }}"></script>+ <script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/socket.js') }}"></script>diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.htmlindex edac26afc4..8491c7ba90 100644--- a/src/local_deep_research/web/templates/pages/history.html+++ b/src/local_deep_research/web/templates/pages/history.html@@ -43,8 +43,8 @@{% block page_scripts %}<!-- Load utilities first -->-<script src="{{ url_for('research.serve_static', path='js/utils/ui.js') }}"></script>-<script src="{{ url_for('research.serve_static', path='js/utils/formatting.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/formatting.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script><!-- Then load the component --><script src="{{ url_for('research.serve_static', path='js/components/history.js') }}"></script>diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.htmlindex d560f37ab7..92d404df50 100644--- a/src/local_deep_research/web/templates/pages/results.html+++ b/src/local_deep_research/web/templates/pages/results.html@@ -39,29 +39,21 @@</div></div>- <div class="card mt-4">- <div class="card-header">- <h3><i class="fas fa-history"></i> Research Logs</h3>- <div class="tabs log-tabs">- <button class="tab log-tab active" data-type="all">All</button>- <button class="tab log-tab" data-type="info">Info</button>- <button class="tab log-tab" data-type="milestone">Milestones</button>- <button class="tab log-tab" data-type="error">Errors</button>- </div>- </div>- <div class="card-content">- <div id="logs-container" class="logs-container">- <div class="empty-logs">No logs yet. Research logs will appear here as they occur.</div>- </div>- </div>- </div>+ {% include "components/log_panel.html" %}</div>{% endblock %}{% block page_scripts %}+<!-- Fallback utilities in case main services are not available -->+<script src="{{ url_for('research.serve_static', path='js/components/fallback/ui.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/components/fallback/formatting.js') }}"></script>++<!-- Main services --><script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/formatting.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/services/pdf.js') }}"></script>++<!-- Results component --><script src="{{ url_for('research.serve_static', path='js/components/results.js') }}"></script>{% endblock %}\ No newline at end of file