~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 whitespace and end-of-file issues in JS and HTML files
hashedviking25b70bf65d72
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.jsindex 68ca3e1427..0d96651079 100644--- a/src/local_deep_research/web/static/js/components/progress.js+++ b/src/local_deep_research/web/static/js/components/progress.js@@ -8,7 +8,7 @@let pollInterval = null;let isCompleted = false;let socketErrorShown = false;-+// DOM Elementslet progressBar = null;let progressPercentage = null;@@ -16,24 +16,24 @@let currentTaskText = null;let cancelButton = null;let viewResultsButton = null;-+// Socket instancelet socket = null;let reconnectAttempts = 0;const MAX_RECONNECT_ATTEMPTS = 5;const RECONNECT_DELAY = 3000;-+// Current research infolet researchCompleted = false;let notificationsEnabled = false;-+/*** Initialize the progress component*/function initializeProgress() {// Get research ID from URL or localStoragecurrentResearchId = getResearchIdFromUrl() || localStorage.getItem('currentResearchId');-+if (!currentResearchId) {console.error('No research ID found');if (window.ui) window.ui.showError('No active research found. Please start a new research.');@@ -42,7 +42,7 @@}, 3000);return;}-+// Get DOM elementsprogressBar = document.getElementById('progress-bar');progressPercentage = document.getElementById('progress-percentage');@@ -50,9 +50,9 @@currentTaskText = document.getElementById('current-task');cancelButton = document.getElementById('cancel-research-btn');viewResultsButton = document.getElementById('view-results-btn');-+// Log available elements for debugging- console.log('Progress DOM elements:', {+ console.log('Progress DOM elements:', {progressBar: !!progressBar,progressPercentage: !!progressPercentage,statusText: !!statusText,@@ -60,30 +60,30 @@cancelButton: !!cancelButton,viewResultsButton: !!viewResultsButton});-+// Check for required elementsconst missingElements = [];if (!progressBar) missingElements.push('progress-bar');if (!statusText) missingElements.push('status-text');if (!currentTaskText) missingElements.push('current-task');-+if (missingElements.length > 0) {console.error('Required DOM elements not found for progress component:', missingElements.join(', '));// Try to create fallback elements if not foundcreateFallbackElements(missingElements);}-+// Set up event listenersif (cancelButton) {cancelButton.addEventListener('click', handleCancelResearch);}-+// Note: Log panel is now automatically initialized by logpanel.js// No need to manually initialize it here-+// Make sure navigation stays working even if Socket.IO failssetupSafeNavigationHandling();-+// Initialize socket connection if availableif (window.socket) {initializeSocket();@@ -92,30 +92,30 @@// Set up polling as fallbackpollInterval = setInterval(checkProgress, 3000);}-+// Initial progress checkcheckProgress();-+console.log('Progress component initialized for research ID:', currentResearchId);-+// Get notification preferencenotificationsEnabled = localStorage.getItem('notificationsEnabled') === 'true';-+// Get initial research statusgetInitialStatus();}-+/*** Set up safe navigation handling to prevent WebSocket errors from blocking navigation*/function setupSafeNavigationHandling() {// Find all navigation linksconst navLinks = document.querySelectorAll('a, .sidebar-nav li, .mobile-tab-bar li');-+navLinks.forEach(link => {// Don't override existing click handlers, add our handlerconst originalClickHandler = link.onclick;-+link.onclick = function(event) {// If socket has errors, disconnect it before navigationif (window.socket && typeof window.socket.isUsingPolling === 'function' && window.socket.isUsingPolling()) {@@ -131,18 +131,18 @@console.error('Error cleaning up before navigation:', e);}}-+// Call the original click handler if it existsif (typeof originalClickHandler === 'function') {return originalClickHandler.call(this, event);}-+// Default behaviorreturn true;};});}-+/*** Create fallback elements if they're missing* @param {Array} missingElements - Array of missing element IDs@@ -151,7 +151,7 @@const progressContainer = document.querySelector('.progress-container');const statusContainer = document.querySelector('.status-container');const taskContainer = document.querySelector('.task-container');-+if (missingElements.includes('progress-bar') && progressContainer) {console.log('Creating fallback progress bar');const progressBarContainer = document.createElement('div');@@ -159,7 +159,7 @@progressBarContainer.innerHTML = '<div id="progress-bar" class="progress-fill" style="width: 0%"></div>';progressContainer.prepend(progressBarContainer);progressBar = document.getElementById('progress-bar');-+if (!progressPercentage) {const percentEl = document.createElement('div');percentEl.id = 'progress-percentage';@@ -169,7 +169,7 @@progressPercentage = percentEl;}}-+if (missingElements.includes('status-text') && statusContainer) {console.log('Creating fallback status text');const statusEl = document.createElement('div');@@ -179,7 +179,7 @@statusContainer.appendChild(statusEl);statusText = statusEl;}-+if (missingElements.includes('current-task') && taskContainer) {console.log('Creating fallback task text');const taskEl = document.createElement('div');@@ -190,7 +190,7 @@currentTaskText = taskEl;}}-+/*** Extract research ID from URL* @returns {string|null} The research ID or null if not found@@ -198,21 +198,21 @@function getResearchIdFromUrl() {const pathParts = window.location.pathname.split('/');const idIndex = pathParts.indexOf('progress') + 1;-+if (idIndex > 0 && idIndex < pathParts.length) {return pathParts[idIndex];}-+return null;}-+/*** Initialize Socket.IO connection and listeners*/function initializeSocket() {try {console.log('Initializing socket connection for research ID:', currentResearchId);-+// Check if socket service is availableif (!window.socket) {console.warn('Socket service not available, falling back to polling');@@ -220,16 +220,16 @@fallbackToPolling();return;}-+// Subscribe to research eventswindow.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);-+// Handle socket reconnectionwindow.socket.onReconnect(() => {console.log('Socket reconnected, resubscribing to research events');window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);});-+// Check socket status after a short delay to see if we're connectedsetTimeout(() => {if (window.socket.isUsingPolling && window.socket.isUsingPolling()) {@@ -241,7 +241,7 @@window.addConsoleLog('Using polling for updates due to WebSocket connection issues', 'info');}}-+// Ensure we check for updates right awaycheckProgress();} else {@@ -254,32 +254,32 @@fallbackToPolling();}}-+/*** Fall back to polling for updates*/function fallbackToPolling() {console.log('Setting up polling fallback for research updates');-+if (!pollInterval) {pollInterval = setInterval(checkProgress, 3000);-+// Add a log entry about pollingif (window.addConsoleLog) {window.addConsoleLog('Using polling for research updates instead of WebSockets', 'info');}}}-+/*** Handle progress update from socket* @param {Object} data - The progress data*/function handleProgressUpdate(data) {console.log('Received progress update:', data);-+if (!data) return;-+// Process progress_log if available and add to logs// NOTE: This is now handled by the logpanel component directly// We'll just ensure the panel is visible and let it manage logs@@ -289,13 +289,13 @@const progressLogsCheck = JSON.parse(data.progress_log);if (Array.isArray(progressLogsCheck) && progressLogsCheck.length > 0) {console.log(`Found ${progressLogsCheck.length} logs in progress update - forwarding to log panel`);-+// Make the log panel visible if it existsconst logPanel = document.querySelector('.collapsible-log-panel');if (logPanel && window.getComputedStyle(logPanel).display === 'none') {logPanel.style.display = 'flex';}-+// The actual log processing is now handled by socket.js and logpanel.js// We don't need to process logs here anymore}@@ -303,24 +303,24 @@console.error('Error checking progress_log format:', e);}}-+// Update progress UIupdateProgressUI(data);-+// Check if research is completedif (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {handleResearchCompletion(data);}-+// Update the current query text if availableconst currentQueryEl = document.getElementById('current-query');if (currentQueryEl && localStorage.getItem('currentQuery')) {currentQueryEl.textContent = localStorage.getItem('currentQuery');}-+// Check for task message updates with better fallbackslet taskUpdated = false;-+if (data.task_message && data.task_message.trim() !== '') {// Direct task message is highest prioritysetCurrentTask(data.task_message);@@ -338,11 +338,11 @@taskUpdated = true;}}-+// If no task info was provided, leave the current task as is// This prevents tasks from being overwritten by empty updates}-+/*** Determine log level based on status* @param {string} status - The research status@@ -350,18 +350,18 @@*/function determineLogLevel(status) {if (!status) return 'info';-+if (status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'error') {return 'milestone';}-+if (status === 'error' || status.includes('error')) {return 'error';}-+return 'info';}-+/*** Check research progress via API*/@@ -371,16 +371,16 @@console.error('API service not available');return;}-+console.log('Checking research progress for ID:', currentResearchId);const data = await window.api.getResearchStatus(currentResearchId);-+if (data) {console.log('Got research status update:', data);-+// Update progress UIupdateProgressUI(data);-+// Check if research is completedif (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {handleResearchCompletion(data);@@ -390,7 +390,7 @@console.log('Setting up polling interval for progress updates');pollInterval = setInterval(checkProgress, 5000);}-+// Log a message every 5th poll to show activityif (reconnectAttempts % 5 === 0) {console.log('Still monitoring research progress...');@@ -407,7 +407,7 @@}}}-+/*** Update progress bar* @param {HTMLElement} progressBar - The progress bar element@@ -415,32 +415,32 @@*/function updateProgressBar(progressBar, progress) {if (!progressBar) return;-+// Ensure progress is between 0-100const percentage = Math.max(0, Math.min(100, Math.floor(progress)));-+// Update progress bar width with transition for smooth animationprogressBar.style.transition = 'width 0.3s ease-in-out';progressBar.style.width = `${percentage}%`;-+// Update percentage text if availableif (progressPercentage) {progressPercentage.textContent = `${percentage}%`;}}-+/*** Update the progress UI with data* @param {Object} data - The progress data*/function updateProgressUI(data) {console.log('Updating progress UI with data:', data);-+// Update progress barif (data.progress !== undefined && progressBar) {updateProgressBar(progressBar, data.progress);}-+// Update status text with better formattingif (data.status && statusText) {let formattedStatus;@@ -462,15 +462,15 @@formattedStatus = 'Cancelled';break;default:- formattedStatus = data.status.charAt(0).toUpperCase() ++ formattedStatus = data.status.charAt(0).toUpperCase() +data.status.slice(1).replace(/_/g, ' ');}}-+// Only update status text if we have a non-empty formatted statusif (formattedStatus && formattedStatus.trim() !== '') {statusText.textContent = formattedStatus;-+// Add status class for stylingdocument.querySelectorAll('.status-indicator').forEach(el => {el.className = 'status-indicator';@@ -478,11 +478,11 @@});}}-+// Extract current task from progress_logif (currentTaskText) {let taskMessage = null;-+// Try to parse progress_log to get the latest taskif (data.progress_log && typeof data.progress_log === 'string') {try {@@ -500,7 +500,7 @@console.error('Error parsing progress_log for task message:', e);}}-+// Check various fields that might contain the current task messageif (!taskMessage) {if (data.current_task) {@@ -517,7 +517,7 @@taskMessage = data.log_entry.message;}}-+// Update the task text if we found a message AND it's not just "In Progress"if (taskMessage && taskMessage.trim() !== 'In Progress' && taskMessage.trim() !== 'in progress') {console.log('Updating current task text to:', taskMessage);@@ -525,7 +525,7 @@// Remember this message to avoid overwriting with generic messagescurrentTaskText.dataset.lastMessage = taskMessage;}-+// If no message but we have a status, generate a more descriptive message// BUT ONLY if we don't already have a meaningful message displayedif (!taskMessage && data.status && (!currentTaskText.dataset.lastMessage || currentTaskText.textContent === 'In Progress')) {@@ -560,7 +560,7 @@default:statusMsg = `${data.status.charAt(0).toUpperCase() + data.status.slice(1).replace('_', ' ')}...`;}-+// Only update if we have a new messageif (statusMsg) {console.log('Using enhanced status-based message:', statusMsg);@@ -570,29 +570,29 @@}}}-+// Update page title with progressif (data.progress !== undefined) {document.title = `Research (${Math.floor(data.progress)}%) - Local Deep Research`;}-+// Update favicon based on statusif (window.ui && typeof window.ui.updateFavicon === 'function') {window.ui.updateFavicon(data.status || 'in_progress');}-+// Show notification if enabledif (data.status === 'completed' && localStorage.getItem('notificationsEnabled') === 'true') {showNotification('Research Completed', 'Your research has been completed successfully.');}-+// Ensure log entry is added if message exists but no specific log_entryif (data.message && window.addConsoleLog && !data.log_entry) {console.log('Adding message to console log:', data.message);window.addConsoleLog(data.message, determineLogLevel(data.status));}}-+/*** Handle research completion* @param {Object} data - The completion data@@ -600,13 +600,13 @@function handleResearchCompletion(data) {if (isCompleted) return;isCompleted = true;-+// Clear polling intervalif (pollInterval) {clearInterval(pollInterval);pollInterval = null;}-+// Update UI for completionif (data.status === 'completed') {// Show view results button@@ -614,7 +614,7 @@viewResultsButton.style.display = 'inline-block';viewResultsButton.href = `/research/results/${currentResearchId}`;}-+// Hide cancel buttonif (cancelButton) {cancelButton.style.display = 'none';@@ -626,21 +626,21 @@} else {console.error('Research failed:', data.error || 'Unknown error');}-+// Update button to go back to homeif (viewResultsButton) {viewResultsButton.textContent = 'Start New Research';viewResultsButton.href = '/';viewResultsButton.style.display = 'inline-block';}-+// Hide cancel buttonif (cancelButton) {cancelButton.style.display = 'none';}}}-+/*** Handle research cancellation*/@@ -648,20 +648,20 @@if (!confirm('Are you sure you want to cancel this research?')) {return;}-+// Disable cancel buttonif (cancelButton) {cancelButton.disabled = true;cancelButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cancelling...';}-+try {if (!window.api || !window.api.terminateResearch) {throw new Error('API service not available');}-+await window.api.terminateResearch(currentResearchId);-+// Update status manually (in case socket fails)if (statusText) {statusText.textContent = 'Cancelled';@@ -669,82 +669,169 @@el.className = 'status-indicator status-cancelled';});}-+// Show messageif (window.ui) {window.ui.showMessage('Research has been cancelled.');}-+// Update cancel buttonif (cancelButton) {cancelButton.style.display = 'none';}-+// Show go home buttonif (viewResultsButton) {viewResultsButton.textContent = 'Start New Research';viewResultsButton.href = '/';viewResultsButton.style.display = 'inline-block';}-+} catch (error) {console.error('Error cancelling research:', error);-+// Re-enable cancel buttonif (cancelButton) {cancelButton.disabled = false;cancelButton.innerHTML = '<i class="fas fa-stop-circle"></i> Cancel Research';}-+// Show error messageif (window.ui) {window.ui.showError('Failed to cancel research. Please try again.');}}}-+/**- * Show browser notification+ * Show a notification to the user* @param {string} title - Notification title* @param {string} message - Notification message+ * @param {string} type - Notification type ('info', 'warning', 'error')+ * @param {number} duration - Duration in ms to show in-app notification (0 to not auto-hide)*/- function showNotification(title, message) {- if (!('Notification' in window)) return;-- // Check if permission is already granted- if (Notification.permission === 'granted') {- new Notification(title, { body: message });- }- // Otherwise, request permission- else if (Notification.permission !== 'denied') {- Notification.requestPermission().then(permission => {- if (permission === 'granted') {- new Notification(title, { body: message });+ function showNotification(title, message, type = 'info', duration = 5000) {+ // First attempt browser notification if enabled+ if ('Notification' in window) {+ // Check if permission is already granted+ if (Notification.permission === 'granted') {+ try {+ const notification = new Notification(title, {+ body: message,+ icon: type === 'error' ? '/research/static/img/error-icon.png' : '/research/static/img/favicon.png'+ });++ // Auto-close after 10 seconds+ setTimeout(() => notification.close(), 10000);+ } catch (e) {+ console.warn('Browser notification failed, falling back to in-app notification', e);}+ }+ // Otherwise, request permission (only if it's not been denied)+ else if (Notification.permission !== 'denied') {+ Notification.requestPermission().then(permission => {+ if (permission === 'granted') {+ new Notification(title, {+ body: message,+ icon: type === 'error' ? '/research/static/img/error-icon.png' : '/research/static/img/favicon.png'+ });+ }+ });+ }+ }++ // Also show in-app notification+ try {+ // Create or get notification container+ let notificationContainer = document.getElementById('notification-container');+ if (!notificationContainer) {+ notificationContainer = document.createElement('div');+ notificationContainer.id = 'notification-container';+ notificationContainer.style.position = 'fixed';+ notificationContainer.style.top = '20px';+ notificationContainer.style.right = '20px';+ notificationContainer.style.zIndex = '9999';+ notificationContainer.style.width = '350px';+ document.body.appendChild(notificationContainer);+ }++ // Create notification element+ const notificationEl = document.createElement('div');+ notificationEl.className = 'alert alert-dismissible fade show';++ // Set type-specific styling+ switch(type) {+ case 'error':+ notificationEl.classList.add('alert-danger');+ break;+ case 'warning':+ notificationEl.classList.add('alert-warning');+ break;+ default:+ notificationEl.classList.add('alert-info');+ }++ // Add title and message+ notificationEl.innerHTML = `+ <strong>${title}</strong>+ <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>+ <hr>+ <p>${message}</p>+ `;++ // Add to container+ notificationContainer.appendChild(notificationEl);++ // Set up auto-dismiss if duration is provided+ if (duration > 0) {+ setTimeout(() => {+ notificationEl.classList.remove('show');+ setTimeout(() => {+ notificationContainer.removeChild(notificationEl);+ }, 300); // Wait for fade animation+ }, duration);+ }++ // Set up click to dismiss+ notificationEl.querySelector('.btn-close').addEventListener('click', () => {+ notificationEl.classList.remove('show');+ setTimeout(() => {+ if (notificationContainer.contains(notificationEl)) {+ notificationContainer.removeChild(notificationEl);+ }+ }, 300);});++ } catch (e) {+ console.error('Failed to show in-app notification', e);}++ // Also log to console+ const logMethod = type === 'error' ? console.error :+ type === 'warning' ? console.warn : console.log;+ logMethod(`${title}: ${message}`);}-+/*** Get initial research status from API*/async function getInitialStatus() {try {const status = await window.api.getResearchStatus(currentResearchId);-+// Process statusif (status) {// If complete, show complete UIif (status.status === 'completed') {handleResearchComplete({ research_id: currentResearchId });- }+ }// If error, show error UIelse if (status.status === 'error') {- handleResearchError({- research_id: currentResearchId,- error: status.message || 'Unknown error'+ handleResearchError({+ research_id: currentResearchId,+ error: status.message || 'Unknown error'});- }+ }// Otherwise update progresselse {updateProgressUI(status);@@ -755,94 +842,94 @@setErrorState('Error loading research status. Please refresh the page to try again.');}}-+/*** Handle research complete event* @param {Object} data - Complete event data*/function handleResearchComplete(data) {console.log('Research complete received:', data);-+if (data.research_id != currentResearchId) {console.warn('Received complete event for different research ID');return;}-+// Update UIsetProgressValue(100);setStatus('completed');setCurrentTask('Research completed successfully');-+// Hide cancel buttonif (cancelButton) {cancelButton.style.display = 'none';}-+// Show results buttonshowResultsButton();-+// Show notification if enabledshowNotification('Research Complete', 'Your research has been completed successfully.');-+// Update faviconupdateFavicon(100);-+// Set flagresearchCompleted = true;}-+/*** Handle research error event* @param {Object} data - Error event data*/function handleResearchError(data) {console.error('Research error received:', data);-+if (data.research_id != currentResearchId) {console.warn('Received error event for different research ID');return;}-+// Update UI to error statesetProgressValue(100);setStatus('error');setCurrentTask(`Error: ${data.error || 'Unknown error'}`);-+// Add error class to progress barif (progressBar) {progressBar.classList.remove('bg-primary', 'bg-success');progressBar.classList.add('bg-danger');}-+// Hide cancel buttonif (cancelButton) {cancelButton.style.display = 'none';}-+// Show results button (might have partial results)showResultsButton();-+// Show notification if enabledshowNotification('Research Error', `There was an error with your research: ${data.error}`);-+// Update faviconupdateFavicon(100, true);}-+/*** Set progress bar value* @param {number} value - Progress value (0-100)*/function setProgressValue(value) {if (!progressBar) return;-+// Ensure value is in rangevalue = Math.min(Math.max(value, 0), 100);-+// Update progress barprogressBar.style.width = `${value}%`;progressBar.setAttribute('aria-valuenow', value);-+// Update classes based on progressif (value >= 100) {progressBar.classList.remove('bg-primary');@@ -852,16 +939,16 @@progressBar.classList.add('bg-primary');}}-+/*** Set status text* @param {string} status - Status string*/function setStatus(status) {if (!statusText) return;-+let statusDisplay = 'Unknown';-+// Map status to display textswitch (status) {case 'not_started':@@ -882,10 +969,10 @@default:statusDisplay = status ? status.charAt(0).toUpperCase() + status.slice(1) : 'Unknown';}-+statusText.textContent = statusDisplay;}-+/*** Set current task text* @param {string} task - Current task description@@ -894,7 +981,7 @@if (!currentTaskText) return;currentTaskText.textContent = task || 'No active task';}-+/*** Set error state for the UI* @param {string} message - Error message@@ -904,29 +991,29 @@setProgressValue(100);setStatus('error');setCurrentTask(`Error: ${message}`);-+// Add error class to progress barif (progressBar) {progressBar.classList.remove('bg-primary', 'bg-success');progressBar.classList.add('bg-danger');}-+// Hide cancel buttonif (cancelButton) {cancelButton.style.display = 'none';}}-+/*** Show results button*/function showResultsButton() {if (!viewResultsButton) return;-+viewResultsButton.style.display = 'inline-block';viewResultsButton.disabled = false;}-+/*** Update favicon with progress* @param {number} progress - Progress value (0-100)@@ -935,35 +1022,35 @@function updateFavicon(progress, isError = false) {try {// Find favicon link or create it if it doesn't exist- let link = document.querySelector("link[rel='icon']") ||+ let link = document.querySelector("link[rel='icon']") ||document.querySelector("link[rel='shortcut icon']");-+if (!link) {// If no favicon link exists, don't try to create it// This avoids error spam in the consoleconsole.debug('Favicon link not found, skipping dynamic favicon update');return;}-+// Create canvas for drawing the faviconconst canvas = document.createElement('canvas');canvas.width = 32;canvas.height = 32;-+const ctx = canvas.getContext('2d');-+// Draw backgroundctx.fillStyle = '#343a40'; // Dark backgroundctx.beginPath();ctx.arc(16, 16, 16, 0, 2 * Math.PI);ctx.fill();-+// Draw progress arcctx.beginPath();ctx.moveTo(16, 16);ctx.arc(16, 16, 14, -0.5 * Math.PI, (-0.5 + 2 * progress / 100) * Math.PI);ctx.lineTo(16, 16);-+// Color based on statusif (isError) {ctx.fillStyle = '#dc3545'; // Danger red@@ -972,40 +1059,40 @@} else {ctx.fillStyle = '#007bff'; // Primary blue}-+ctx.fill();-+// Draw center circlectx.fillStyle = '#343a40';ctx.beginPath();ctx.arc(16, 16, 8, 0, 2 * Math.PI);ctx.fill();-+// Draw letter Rctx.fillStyle = '#ffffff';ctx.font = 'bold 14px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';ctx.fillText('R', 16, 16);-+// Update faviconlink.href = canvas.toDataURL('image/png');-+} catch (error) {console.error('Error updating favicon:', error);// Failure to update favicon is not critical, so we just log the error}}-+// Initialize on page loaddocument.addEventListener('DOMContentLoaded', initializeProgress);-+// Expose components publicly for testing and debuggingwindow.progressComponent = {checkProgress,handleCancelResearch};-+// Add global error handler for WebSocket errorswindow.addEventListener('error', function(event) {if (event.message && event.message.includes('WebSocket') && event.message.includes('frame header')) {@@ -1014,4 +1101,7 @@return true; // Prevent the error from showing in console}});-})();\ No newline at end of file++ // Expose notification function globally+ window.showNotification = showNotification;+})();diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.jsindex 6db40ef7d2..19f4888b8e 100644--- a/src/local_deep_research/web/static/js/services/api.js+++ b/src/local_deep_research/web/static/js/services/api.js@@ -8,6 +8,15 @@ if (typeof API_BASE_URL === 'undefined') {const API_BASE_URL = '/research/api';}+/**+ * Get CSRF token from meta tag+ * @returns {string} The CSRF token+ */+function getCsrfToken() {+ const metaTag = document.querySelector('meta[name="csrf-token"]');+ return metaTag ? metaTag.getAttribute('content') : '';+}+/*** Get the full URL for an API endpoint* @param {string} path - The API path (without leading slash)@@ -25,20 +34,22 @@ function getApiUrl(path) {*/async function fetchWithErrorHandling(url, options = {}) {try {+ const csrfToken = getCsrfToken();const response = await fetch(url, {...options,headers: {'Content-Type': 'application/json',+ ...(csrfToken ? { 'X-CSRFToken': csrfToken } : {}),...(options.headers || {})}});-+// Handle non-200 responsesif (!response.ok) {const errorData = await response.json().catch(() => ({}));throw new Error(errorData.message || `API Error: ${response.status} ${response.statusText}`);}-+// Parse the responsereturn await response.json();} catch (error) {@@ -129,8 +140,12 @@ async function terminateResearch(researchId) {* @returns {Promise<Object>} The deletion response*/async function deleteResearch(researchId) {+ const csrfToken = getCsrfToken();return fetchWithErrorHandling(`/research/api/delete/${researchId}`, {- method: 'DELETE'+ method: 'DELETE',+ headers: {+ 'X-CSRFToken': csrfToken+ }});}@@ -235,4 +250,4 @@ window.api = {saveLlmConfig,postJSON,getApiUrl-};\ No newline at end of file+};diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex ad2f23d81d..597245cfce 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -9,13 +9,13 @@ window.socket = (function() {let reconnectCallback = null;let connectionAttempts = 0;const MAX_CONNECTION_ATTEMPTS = 3;-+// Keep track of the research we're currently subscribed tolet currentResearchId = null;-+// Track if we're using polling fallbacklet usingPolling = false;-+/*** Initialize the Socket.IO connection*/@@ -24,10 +24,10 @@ window.socket = (function() {// Already initializedreturn socket;}-+// Get the base URL from the current pageconst baseUrl = window.location.protocol + '//' + window.location.host;-+// Create a new socket instancetry {// Use polling only to avoid WebSocket issues@@ -38,7 +38,7 @@ window.socket = (function() {reconnectionAttempts: 5,transports: ['polling'] // Use only polling to avoid WebSocket issues});-+setupSocketEvents();console.log('Socket.IO initialized with polling only strategy');} catch (error) {@@ -46,10 +46,10 @@ window.socket = (function() {// Set a flag that we're not connected - will use polling for updatesusingPolling = true;}-+return socket;}-+/*** Set up the socket event handlers*/@@ -58,61 +58,61 @@ window.socket = (function() {console.log('Socket connected');connectionAttempts = 0;usingPolling = false;-+// Re-subscribe to current research if anyif (currentResearchId) {subscribeToResearch(currentResearchId);}-+// Call reconnect callback if existsif (reconnectCallback) {reconnectCallback();}});-+socket.on('connect_error', (error) => {console.warn('Socket connection error:', error);connectionAttempts++;-+if (connectionAttempts >= MAX_CONNECTION_ATTEMPTS) {console.warn(`Failed to connect after ${MAX_CONNECTION_ATTEMPTS} attempts, falling back to polling`);usingPolling = true;-+// If we can't establish a socket connection, use polling for any active researchif (currentResearchId && typeof window.pollResearchStatus === 'function') {window.pollResearchStatus(currentResearchId);}}});-+socket.on('disconnect', (reason) => {console.log('Socket disconnected:', reason);-+// Fall back to polling on disconnectif (currentResearchId) {fallbackToPolling(currentResearchId);}});-+socket.on('reconnect', (attemptNumber) => {console.log('Socket reconnected after', attemptNumber, 'attempts');connectionAttempts = 0;});-+socket.on('reconnect_attempt', (attemptNumber) => {console.log('Socket reconnection attempt:', attemptNumber);});-+socket.on('error', (error) => {console.error('Socket error:', error);-+// Fall back to polling on any errorif (currentResearchId) {fallbackToPolling(currentResearchId);}});}-+/*** Subscribe to research events* @param {string} researchId - The research ID to subscribe to@@ -123,27 +123,27 @@ window.socket = (function() {console.warn('Socket not initialized, initializing now');initializeSocket();}-+if (!researchId) {console.error('No research ID provided');return;}-+console.log('Subscribing to research:', researchId);-+// Remember the current research IDcurrentResearchId = researchId;-+// Add the callback if providedif (callback && typeof callback === 'function') {addResearchEventHandler(researchId, callback);}-+// If we have a socket connection, join the research roomif (socket && socket.connected) {try {socket.emit('join', { research_id: researchId });-+// Setup direct event handler for progress updatessocket.on(`progress_${researchId}`, (data) => {handleProgressUpdate(researchId, data);@@ -157,7 +157,7 @@ window.socket = (function() {fallbackToPolling(researchId);}}-+/*** Handle progress updates from research* @param {string} researchId - The research ID this update is for@@ -165,7 +165,67 @@ window.socket = (function() {*/function handleProgressUpdate(researchId, data) {console.log('Progress update for research', researchId, ':', data);-++ // Special handling for synthesis errors to make them more visible to users+ if (data.metadata && (data.metadata.phase === 'synthesis_error' || data.metadata.error_type)) {+ const errorType = data.metadata.error_type || 'unknown';+ let errorMessage = 'Error during research synthesis';+ let detailedMessage = '';++ // Format user-friendly error messages based on error type+ switch(errorType) {+ case 'timeout':+ errorMessage = 'LLM Timeout Error';+ detailedMessage = 'The AI model took too long to respond. This may be due to server load or the complexity of your query.';+ break;+ case 'token_limit':+ errorMessage = 'Token Limit Exceeded';+ detailedMessage = 'Your research query generated too much data for the AI model to process. Try a more specific query.';+ break;+ case 'connection':+ errorMessage = 'LLM Connection Error';+ detailedMessage = 'Could not connect to the AI service. Please check that your LLM service is running.';+ break;+ case 'rate_limit':+ errorMessage = 'API Rate Limit Reached';+ detailedMessage = 'The AI service API rate limit was reached. Please wait a few minutes and try again.';+ break;+ case 'llm_error':+ default:+ errorMessage = 'LLM Synthesis Error';+ detailedMessage = 'The AI model encountered an error during final answer synthesis. A fallback response will be provided.';+ }++ // Add prominent error notification+ try {+ // If we have a UI notification function available+ if (typeof window.showNotification === 'function') {+ window.showNotification(errorMessage, detailedMessage, 'error', 10000); // Show for 10 seconds+ }++ // Log to console+ console.error(`Research error (${errorType}): ${errorMessage} - ${detailedMessage}`);++ // Add to log panel with the error status+ if (typeof window.addConsoleLog === 'function') {+ window.addConsoleLog(`${errorMessage}: ${detailedMessage}`, 'error', {+ phase: 'synthesis_error',+ error_type: errorType+ });++ // Add explanation about fallback mode as a separate log entry+ window.addConsoleLog(+ 'Switching to fallback mode. Research will continue with available data.',+ 'milestone',+ {phase: 'synthesis_fallback'}+ );+ }+ } catch (notificationError) {+ console.error('Error showing notification:', notificationError);+ }+ }++ // Continue with normal progress update handling// Call all registered event handlers for this researchif (researchEventHandlers[researchId]) {researchEventHandlers[researchId].forEach(handler => {@@ -176,55 +236,55 @@ window.socket = (function() {}});}-+// Initialize message tracking if not existswindow._processedSocketMessages = window._processedSocketMessages || new Map();-+// Process logs from progress_log if availableif (data.progress_log && typeof data.progress_log === 'string') {try {const progressLogs = JSON.parse(data.progress_log);if (Array.isArray(progressLogs) && progressLogs.length > 0) {console.log(`Socket received ${progressLogs.length} logs in progress_log`);-+// Process each log entryprogressLogs.forEach(logItem => {// Skip if no message or timeif (!logItem.message || !logItem.time) return;-+// Generate a unique key for this messageconst messageKey = `${logItem.time}-${logItem.message}`;-+// Skip if we've seen this exact message beforeif (window._processedSocketMessages.has(messageKey)) {console.log('Skipping duplicate socket message:', logItem.message);return;}-+// Record that we've processed this messagewindow._processedSocketMessages.set(messageKey, Date.now());-+// Determine log type based on metadatalet logType = 'info';if (logItem.metadata) {- if (logItem.metadata.phase === 'iteration_complete' ||+ if (logItem.metadata.phase === 'iteration_complete' ||logItem.metadata.phase === 'report_complete' ||logItem.metadata.phase === 'complete' ||logItem.metadata.phase === 'search_complete' ||logItem.metadata.is_milestone === true ||logItem.metadata.type === 'milestone') {logType = 'milestone';- } else if (logItem.metadata.phase === 'error' ||+ } else if (logItem.metadata.phase === 'error' ||logItem.metadata.type === 'error') {logType = 'error';}}-+// Also check for keywords in the message for better milestone detectionif (logType !== 'milestone' && logItem.message) {const msg = logItem.message.toLowerCase();- if (msg.includes('complete') ||- msg.includes('finished') ||+ if (msg.includes('complete') ||+ msg.includes('finished') ||msg.includes('starting phase') ||msg.includes('generated report')) {logType = 'milestone';@@ -232,7 +292,7 @@ window.socket = (function() {logType = 'error';}}-+// Send to log panelif (typeof window.addConsoleLog === 'function') {// Use the main console log function if available@@ -250,7 +310,7 @@ window.socket = (function() {console.warn('No log handler function available for log:', logItem);}});-+// Clean up old entries from message tracking (keep only last 5 minutes)const now = Date.now();for (const [key, timestamp] of window._processedSocketMessages.entries()) {@@ -263,32 +323,32 @@ window.socket = (function() {console.error('Error processing progress_log:', error);}}-+// If the event contains log data, add it to the consoleif (data.log_entry) {console.log('Adding log entry from socket event:', data.log_entry);-+// Make sure global tracking is initializedwindow._processedSocketMessages = window._processedSocketMessages || new Map();-+// Generate a message keyconst messageKey = `${data.log_entry.time || new Date().toISOString()}-${data.log_entry.message}`;-+// Skip if we've seen this message beforeif (window._processedSocketMessages.has(messageKey)) {console.log('Skipping duplicate individual log entry:', data.log_entry.message);return;}-+// Record that we've processed this messagewindow._processedSocketMessages.set(messageKey, Date.now());-+if (typeof window.addConsoleLog === 'function') {window.addConsoleLog(- data.log_entry.message,- data.log_entry.type ||- (data.log_entry.metadata && data.log_entry.metadata.type) ||- 'info',+ data.log_entry.message,+ data.log_entry.type ||+ (data.log_entry.metadata && data.log_entry.metadata.type) ||+ 'info',data.log_entry.metadata);} else if (typeof window._socketAddLogEntry === 'function') {@@ -299,21 +359,21 @@ window.socket = (function() {} else if (data.message && typeof window.addConsoleLog === 'function') {// Use the message field if no specific log entryconsole.log('Adding message from socket event:', data.message);-+// Skip duplicate general messages tooconst messageKey = `${new Date().toISOString()}-${data.message}`;if (window._processedSocketMessages.has(messageKey)) {console.log('Skipping duplicate message:', data.message);return;}-+// Record this messagewindow._processedSocketMessages.set(messageKey, Date.now());-+window.addConsoleLog(data.message, determineLogLevel(data.status));}}-+/*** Determine log level based on status* @param {string} status - The research status@@ -321,18 +381,18 @@ window.socket = (function() {*/function determineLogLevel(status) {if (!status) return 'info';-+if (status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'error') {return 'milestone';}-+if (status === 'error' || status.includes('error')) {return 'error';}-+return 'info';}-+/*** Add a log entry to the console log container* @param {Object} logEntry - The log entry data@@ -344,7 +404,7 @@ window.socket = (function() {window._socketAddLogEntry(logEntry);return;}-+// If window.addConsoleLog is available, use itif (typeof window.addConsoleLog === 'function') {console.log('Using window.addConsoleLog for log:', logEntry.message);@@ -357,53 +417,53 @@ window.socket = (function() {window.addConsoleLog(logEntry.message, logLevel, logEntry.metadata);return;}-+// Fallback implementation if none of the above is availableconsole.log('Using socket.js fallback log implementation for:', logEntry.message);const consoleLogContainer = document.getElementById('console-log-container');if (!consoleLogContainer) return;-+// Clear empty message if presentconst emptyMessage = consoleLogContainer.querySelector('.empty-log-message');if (emptyMessage) {emptyMessage.remove();}-+// Get the log templateconst template = document.getElementById('console-log-entry-template');if (!template) {console.error('Console log entry template not found');return;}-+// Create a new log entry from the templateconst entry = document.importNode(template.content, true);-+// Determine the log levellet logLevel = 'info';if (logEntry.metadata && logEntry.metadata.type) {logLevel = logEntry.metadata.type;} else if (logEntry.metadata && logEntry.metadata.phase) {- if (logEntry.metadata.phase === 'complete' ||+ if (logEntry.metadata.phase === 'complete' ||logEntry.metadata.phase === 'iteration_complete' ||logEntry.metadata.phase === 'report_complete') {logLevel = 'milestone';}}-+// Format the timestampconst timestamp = new Date(logEntry.time);const timeStr = timestamp.toLocaleTimeString();-+// Set contententry.querySelector('.log-timestamp').textContent = timeStr;entry.querySelector('.log-badge').textContent = logLevel.charAt(0).toUpperCase() + logLevel.slice(1);entry.querySelector('.log-badge').className = `log-badge ${logLevel}`;entry.querySelector('.log-message').textContent = logEntry.message;-+// Add to container (at the beginning for newest first)consoleLogContainer.insertBefore(entry, consoleLogContainer.firstChild);-+// Update log countconst logIndicator = document.getElementById('log-indicator');if (logIndicator) {@@ -411,7 +471,7 @@ window.socket = (function() {logIndicator.textContent = currentCount + 1;}}-+/*** Fall back to polling for research updates* @param {string} researchId - The research ID@@ -419,7 +479,7 @@ window.socket = (function() {function fallbackToPolling(researchId) {console.log('Falling back to polling for research', researchId);usingPolling = true;-+// Start polling if the global polling function existsif (typeof window.pollResearchStatus === 'function') {window.pollResearchStatus(researchId);@@ -430,13 +490,13 @@ window.socket = (function() {console.error('API service not available for polling');return;}-+const pollInterval = setInterval(async () => {try {const data = await window.api.getResearchStatus(id);if (data) {handleProgressUpdate(id, data);-+// Stop polling if the research is completeif (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {clearInterval(pollInterval);@@ -446,56 +506,56 @@ window.socket = (function() {console.error('Error polling research status:', error);}}, 3000);-+// Store the interval ID for later cleanupwindow.pollIntervals = window.pollIntervals || {};window.pollIntervals[id] = pollInterval;};-+// Start polling for this researchwindow.pollResearchStatus(researchId);}}-+/*** Unsubscribe from research events* @param {string} researchId - The research ID to unsubscribe from*/function unsubscribeFromResearch(researchId) {if (!researchId) return;-+console.log('Unsubscribing from research:', researchId);-+// Clear any polling intervalsif (window.pollIntervals && window.pollIntervals[researchId]) {clearInterval(window.pollIntervals[researchId]);delete window.pollIntervals[researchId];}-+// If we have a socket connection, leave the research roomif (socket && socket.connected) {try {// Leave the research roomsocket.emit('leave', { research_id: researchId });-+// Remove the event handlersocket.off(`progress_${researchId}`);} catch (error) {console.error('Error unsubscribing from research:', error);}}-+// Clear handlersif (researchId === currentResearchId) {currentResearchId = null;}-+// Clear event handlersif (researchEventHandlers[researchId]) {delete researchEventHandlers[researchId];}}-+/*** Add a research event handler* @param {string} researchId - The research ID to handle events for@@ -506,18 +566,18 @@ window.socket = (function() {console.error('Invalid research event handler');return;}-+// Initialize the handlers array if neededif (!researchEventHandlers[researchId]) {researchEventHandlers[researchId] = [];}-+// Add the handler if it's not already in the arrayif (!researchEventHandlers[researchId].includes(callback)) {researchEventHandlers[researchId].push(callback);}}-+/*** Remove a research event handler* @param {string} researchId - The research ID to remove handler for@@ -525,11 +585,11 @@ window.socket = (function() {*/function removeResearchEventHandler(researchId, callback) {if (!researchId || !researchEventHandlers[researchId]) return;-+if (callback) {// Find the handler indexconst index = researchEventHandlers[researchId].indexOf(callback);-+// Remove if foundif (index !== -1) {researchEventHandlers[researchId].splice(index, 1);@@ -539,7 +599,7 @@ window.socket = (function() {delete researchEventHandlers[researchId];}}-+/*** Set a callback for socket reconnection* @param {function} callback - The function to call on reconnection@@ -547,7 +607,7 @@ window.socket = (function() {function setReconnectCallback(callback) {reconnectCallback = callback;}-+/*** Disconnect the socket*/@@ -559,7 +619,7 @@ window.socket = (function() {});window.pollIntervals = {};}-+if (socket) {try {socket.disconnect();@@ -568,14 +628,14 @@ window.socket = (function() {}socket = null;}-+researchEventHandlers = {};reconnectCallback = null;currentResearchId = null;connectionAttempts = 0;usingPolling = false;}-+/*** Filter logs by type* @param {string} type - The log type to filter by ('all', 'info', 'error', 'milestone')@@ -587,22 +647,22 @@ window.socket = (function() {window.filterLogsByType(type);return;}-+console.log('Using socket.js filtering implementation for:', type);-+// Update button UIconst buttons = document.querySelectorAll('.filter-buttons .small-btn');buttons.forEach(button => {button.classList.remove('selected');- if (button.textContent.toLowerCase() === type ||+ if (button.textContent.toLowerCase() === type ||(type === 'all' && button.textContent.toLowerCase() === 'all')) {button.classList.add('selected');}});-+// Get all log entriesconst logEntries = document.querySelectorAll('.console-log-entry');-+logEntries.forEach(entry => {// Use dataset for type if available (new way)if (entry.dataset && entry.dataset.logType) {@@ -613,24 +673,24 @@ window.socket = (function() {}return;}-+// Fallback to badge content (old way)const badge = entry.querySelector('.log-badge');const logType = badge ? badge.textContent.toLowerCase() : 'info';-+if (type === 'all' || logType === type) {entry.style.display = '';} else {entry.style.display = 'none';}});-+// Update empty state message if neededconst logContainer = document.getElementById('console-log-container');if (logContainer) {const visibleEntries = logContainer.querySelectorAll('.console-log-entry[style="display: ;"], .console-log-entry:not([style])');const emptyMessage = logContainer.querySelector('.empty-log-message');-+if (visibleEntries.length === 0 && !emptyMessage) {logContainer.innerHTML = `<div class="empty-log-message">No ${type === 'all' ? '' : type + ' '}logs available.</div>` + logContainer.innerHTML;} else if (visibleEntries.length > 0 && emptyMessage) {@@ -638,7 +698,7 @@ window.socket = (function() {}}}-+/*** Check if socket is connected* @returns {boolean} True if connected@@ -646,7 +706,7 @@ window.socket = (function() {function isConnected() {return socket && socket.connected;}-+/*** Check if we're using polling fallback* @returns {boolean} True if using polling@@ -654,14 +714,14 @@ window.socket = (function() {function isUsingPolling() {return usingPolling;}-+// Initialize socket on load with a small delay to ensure document is readysetTimeout(initializeSocket, 100);-+// Expose functions globallywindow.filterLogsByType = filterLogsByType;window._socketAddLogEntry = addLogEntry; // Expose the addLogEntry function-+// Public APIreturn {init: initializeSocket,@@ -699,11 +759,11 @@ if (!window.filterLogsByType) {}return;}-+// Fallback to badge (old way)const badge = entry.querySelector('.log-badge');const logType = badge ? badge.textContent.toLowerCase() : 'info';-+if (type === 'all' || logType === type.toLowerCase()) {entry.style.display = '';} else {@@ -722,7 +782,7 @@ if (!window.filterLogsByType) {if (!window.addConsoleLog) {window.addConsoleLog = function(message, level = 'info', metadata = null) {console.log(`Adding console log (socket.js fallback): ${message} (${level})`);-+// Create a log entry objectconst logEntry = {time: new Date().toISOString(),@@ -730,49 +790,49 @@ if (!window.addConsoleLog) {type: level,metadata: metadata || { type: level }};-- // Try to use the log panel's direct function first++ // Try to use the log panel's direct function firstif (window.logPanel && typeof window.logPanel.addLog === 'function') {console.log('Using logPanel.addLog to add log entry');window.logPanel.addLog(message, level, metadata);return;}-+// Then try the socket's connector functionif (window._socketAddLogEntry) {console.log('Using _socketAddLogEntry to add log entry');window._socketAddLogEntry(logEntry);return;}-+console.warn('LogPanel functions not available, using fallback implementation');-+// FALLBACK IMPLEMENTATIONconst consoleLogContainer = document.getElementById('console-log-container');if (!consoleLogContainer) {console.warn('Console log container not found, log will be lost');return;}-+// Clear empty message if presentconst emptyMessage = consoleLogContainer.querySelector('.empty-log-message');if (emptyMessage) {emptyMessage.remove();}-+// Get or create a new log entryconst template = document.getElementById('console-log-entry-template');let entry;-+if (template) {entry = document.importNode(template.content, true);-+// Set contententry.querySelector('.log-timestamp').textContent = new Date().toLocaleTimeString();entry.querySelector('.log-badge').textContent = level.charAt(0).toUpperCase() + level.slice(1);entry.querySelector('.log-badge').className = `log-badge ${level}`;entry.querySelector('.log-message').textContent = message;-+// Add data attribute for filteringconst logEntry = entry.querySelector('.console-log-entry');if (logEntry) {@@ -785,7 +845,7 @@ if (!window.addConsoleLog) {entry.className = 'console-log-entry';entry.dataset.logType = level.toLowerCase();entry.classList.add(`log-${level.toLowerCase()}`);-+// Create log contententry.innerHTML = `<span class="log-timestamp">${new Date().toLocaleTimeString()}</span>@@ -793,21 +853,21 @@ if (!window.addConsoleLog) {<span class="log-message">${message}</span>`;}-+// Add to container (at the beginning for newest first)consoleLogContainer.insertBefore(entry, consoleLogContainer.firstChild);-+// Update log countconst logIndicator = document.getElementById('log-indicator');if (logIndicator) {const currentCount = parseInt(logIndicator.textContent) || 0;logIndicator.textContent = currentCount + 1;}-+// Show log panel if hiddenconst logPanelToggle = document.getElementById('log-panel-toggle');const logPanelContent = document.getElementById('log-panel-content');-+if (logPanelContent && logPanelContent.classList.contains('collapsed') && logPanelToggle) {// Auto-expand after a few logsif (!window._logAutoExpandTimer) {@@ -819,4 +879,4 @@ if (!window.addConsoleLog) {}}};-}\ No newline at end of file+}diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 8ba933dd20..d25812efee 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -11,17 +11,17 @@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-100const safePercentage = Math.min(100, Math.max(0, percentage || 0));-+// Update the width of the fill elementprogressFill.style.width = `${safePercentage}%`;-+// Update the percentage textprogressPercentage.textContent = `${Math.round(safePercentage)}%`;-+// Add classes for visual feedbackif (safePercentage >= 100) {progressFill.classList.add('complete');@@ -38,17 +38,17 @@ function updateProgressBar(fillElementId, percentageElementId, percentage) {*/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;}}@@ -59,7 +59,7 @@ function showSpinner(container, message = 'Loading...') {*/function hideSpinner(container) {const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-+if (containerEl) {const spinner = containerEl.querySelector('.loading-spinner');if (spinner) {@@ -75,7 +75,7 @@ function hideSpinner(container) {*/function showError(container, message) {const containerEl = typeof container === 'string' ? document.getElementById(container) : container;-+if (containerEl) {const errorHTML = `<div class="error-message">@@ -83,7 +83,7 @@ function showError(container, message) {<span>${message}</span></div>`;-+containerEl.innerHTML = errorHTML;}}@@ -97,18 +97,18 @@ function showError(container, message) {function showMessage(message, type = 'success', duration = 3000) {// Check if the toast container existslet toastContainer = document.getElementById('toast-container');-+// Create it if it doesn't existif (!toastContainer) {toastContainer = document.createElement('div');toastContainer.id = 'toast-container';document.body.appendChild(toastContainer);}-+// Create a new toastconst toast = document.createElement('div');toast.className = `toast toast-${type}`;-+// Add icon based on typelet icon = '';switch (type) {@@ -125,25 +125,25 @@ function showMessage(message, type = 'success', duration = 3000) {icon = '<i class="fas fa-exclamation-triangle"></i>';break;}-+// Set the contenttoast.innerHTML = `${icon}<div class="toast-message">${message}</div>`;-+// Add to containertoastContainer.appendChild(toast);-+// Show with animationsetTimeout(() => {toast.classList.add('visible');}, 10);-+// Remove after durationsetTimeout(() => {toast.classList.remove('visible');-+// Remove from DOM after animationsetTimeout(() => {toast.remove();@@ -160,7 +160,7 @@ function renderMarkdown(markdown) {if (!markdown) {return '<div class="alert alert-warning">No content available</div>';}-+try {// Use marked library if availableif (typeof marked !== 'undefined') {@@ -179,13 +179,13 @@ function renderMarkdown(markdown) {return code;}});-+// Parse markdown and return HTMLconst html = marked.parse(markdown);-+// Process any special elements like image referencesconst processedHtml = processSpecialMarkdown(html);-+return `<div class="markdown-content">${processedHtml}</div>`;} else {// Basic fallback if marked is not available@@ -195,7 +195,7 @@ function renderMarkdown(markdown) {.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/\*(.*?)\*/g, '<em>$1</em>').replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');-+return `<div class="markdown-content">${basic}</div>`;}} catch (error) {@@ -215,9 +215,9 @@ function processSpecialMarkdown(html) {// Check if this is a reference to a generated imageif (ref.startsWith('image-')) {return `<div class="generated-image" data-image-id="${ref}">- <img src="/research/static/img/generated/${ref}.png"- alt="Generated image ${ref}"- class="img-fluid"+ <img src="/research/static/img/generated/${ref}.png"+ alt="Generated image ${ref}"+ class="img-fluid"loading="lazy" /><div class="image-caption">Generated image (${ref})</div></div>`;@@ -235,24 +235,24 @@ function createDynamicFavicon(emoji = '⚡') {const canvas = document.createElement('canvas');canvas.width = 64;canvas.height = 64;-+// Get the 2D drawing contextconst ctx = canvas.getContext('2d');-+// Clear the canvasctx.clearRect(0, 0, canvas.width, canvas.height);-+// Set fontctx.font = '48px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';-+// Draw the emojictx.fillText(emoji, 32, 32);-+// Convert to data URLconst dataUrl = canvas.toDataURL('image/png');-+// Create or update the favicon linklet link = document.querySelector('link[rel="icon"]');if (!link) {@@ -260,7 +260,7 @@ function createDynamicFavicon(emoji = '⚡') {link.rel = 'icon';document.head.appendChild(link);}-+// Set the new faviconlink.href = dataUrl;}@@ -272,9 +272,9 @@ function createDynamicFavicon(emoji = '⚡') {function updateFavicon(status) {try {// Find favicon link or create it if it doesn't exist- let link = document.querySelector("link[rel='icon']") ||+ let link = document.querySelector("link[rel='icon']") ||document.querySelector("link[rel='shortcut icon']");-+if (!link) {console.log('Favicon link not found, creating a new one');link = document.createElement('link');@@ -282,16 +282,16 @@ function updateFavicon(status) {link.type = 'image/x-icon';document.head.appendChild(link);}-+// Create dynamic favicon using canvasconst canvas = document.createElement('canvas');canvas.width = 32;canvas.height = 32;const ctx = canvas.getContext('2d');-+// Background color based on statuslet bgColor = '#007bff'; // Default blue-+if (status === 'completed') {bgColor = '#28a745'; // Success green} else if (status === 'failed' || status === 'error') {@@ -299,39 +299,97 @@ function updateFavicon(status) {} else if (status === 'cancelled') {bgColor = '#6c757d'; // Gray}-+// Draw circle backgroundctx.fillStyle = bgColor;ctx.beginPath();ctx.arc(16, 16, 16, 0, 2 * Math.PI);ctx.fill();-+// Draw inner circlectx.fillStyle = '#ffffff';ctx.beginPath();ctx.arc(16, 16, 10, 0, 2 * Math.PI);ctx.fill();-+// Draw letter Rctx.fillStyle = bgColor;ctx.font = 'bold 16px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';ctx.fillText('R', 16, 16);-+// Set the favicon to the canvas data URLlink.href = canvas.toDataURL('image/png');-+console.log('Updated favicon to:', status);} catch (error) {console.error('Error updating favicon:', error);}}+/**+ * Show an alert message in a container on the page+ * @param {string} message - The message to display+ * @param {string} type - The alert type: success, error, warning, info+ * @param {boolean} skipIfToastShown - Whether to skip showing this alert if a toast was already shown+ */+function showAlert(message, type = 'info', skipIfToastShown = true) {+ // If we're showing a toast and we want to skip the regular alert, just return+ if (skipIfToastShown && window.ui && window.ui.showMessage) {+ return;+ }++ // Find the alert container - look for different possible alert containers+ let alertContainer = document.getElementById('filtered-settings-alert');++ // If not found, try other common alert containers+ if (!alertContainer) {+ alertContainer = document.getElementById('settings-alert');+ }++ if (!alertContainer) {+ alertContainer = document.getElementById('research-alert');+ }++ if (!alertContainer) return;++ // Clear any existing alerts+ alertContainer.innerHTML = '';++ // Create alert element+ const alert = document.createElement('div');+ alert.className = `alert alert-${type}`;+ alert.innerHTML = `<i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${message}`;++ // Add a close button+ const closeBtn = document.createElement('span');+ closeBtn.className = 'alert-close';+ closeBtn.innerHTML = '×';+ closeBtn.addEventListener('click', () => {+ alert.remove();+ alertContainer.style.display = 'none';+ });++ alert.appendChild(closeBtn);++ // Add to container+ alertContainer.appendChild(alert);+ alertContainer.style.display = 'block';++ // Auto-hide after 5 seconds+ setTimeout(() => {+ alert.remove();+ if (alertContainer.children.length === 0) {+ alertContainer.style.display = 'none';+ }+ }, 5000);+}+// Add CSS for toast messagesfunction addToastStyles() {if (document.getElementById('toast-styles')) return;-+const styleEl = document.createElement('style');styleEl.id = 'toast-styles';styleEl.textContent = `@@ -344,7 +402,7 @@ function addToastStyles() {flex-direction: column;gap: 10px;}-+.toast {display: flex;align-items: center;@@ -360,54 +418,119 @@ function addToastStyles() {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 CSS for alert styles+function addAlertStyles() {+ if (document.getElementById('alert-styles')) return;++ const styleEl = document.createElement('style');+ styleEl.id = 'alert-styles';+ styleEl.textContent = `+ .alert {+ padding: 12px 16px;+ margin-bottom: 1rem;+ border-radius: 8px;+ display: flex;+ align-items: center;+ position: relative;+ }++ .alert i {+ margin-right: 12px;+ font-size: 1.2rem;+ }++ .alert-success {+ background-color: rgba(40, 167, 69, 0.15);+ color: var(--success-color, #28a745);+ border-left: 4px solid var(--success-color, #28a745);+ }++ .alert-error, .alert-danger {+ background-color: rgba(220, 53, 69, 0.15);+ color: var(--danger-color, #dc3545);+ border-left: 4px solid var(--danger-color, #dc3545);+ }++ .alert-info {+ background-color: rgba(23, 162, 184, 0.15);+ color: var(--info-color, #17a2b8);+ border-left: 4px solid var(--info-color, #17a2b8);+ }++ .alert-warning {+ background-color: rgba(255, 193, 7, 0.15);+ color: var(--warning-color, #ffc107);+ border-left: 4px solid var(--warning-color, #ffc107);+ }++ .alert-close {+ position: absolute;+ right: 10px;+ top: 8px;+ font-size: 1.2rem;+ font-weight: bold;+ cursor: pointer;+ opacity: 0.7;+ }++ .alert-close:hover {+ opacity: 1;+ }+ `;+document.head.appendChild(styleEl);}// Add toast styles when the script loadsaddToastStyles();+// Add alert styles when the script loads+addAlertStyles();// Export the UI functionswindow.ui = {@@ -418,5 +541,6 @@ window.ui = {showMessage,renderMarkdown,createDynamicFavicon,- updateFavicon-};\ No newline at end of file+ updateFavicon,+ showAlert+};diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 8307aa0395..64e9bd6c16 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -3,6 +3,7 @@<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">+ <meta name="csrf-token" content="{{ csrf_token() }}"><title>{% block title %}Deep Research System{% endblock %}</title><link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">@@ -17,7 +18,7 @@<!-- Main Content --><main class="main-content">{% block content %}{% endblock %}-+<!-- Collapsible Log Panel is included in specific pages --></main></div>@@ -34,22 +35,22 @@<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script><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/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>-+<!-- Shared Components --><script src="{{ url_for('research.serve_static', path='js/components/logpanel.js') }}"></script>-+<!-- Page-specific Components -->{% block component_scripts %}{% endblock %}-+<!-- Page-specific JS -->{% block page_scripts %}{% endblock %}-+<script>// Configure marked to not use evalif (typeof marked !== 'undefined') {@@ -66,4 +67,4 @@}</script></body>-</html>\ No newline at end of file+</html>