Skip to content

~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.

feat: Update frontend components with improved functionality and error handling

hashedviking9eb204492627
diff --git a/src/local_deep_research/web/static/js/app.js b/src/local_deep_research/web/static/js/app.js
index 337cbce5a5..401119984c 100644
--- a/src/local_deep_research/web/static/js/app.js
+++ b/src/local_deep_research/web/static/js/app.js
@@ -3760,4 +3760,41 @@ document.addEventListener('DOMContentLoaded', () => {
return false;
});
}
+
+ // Ensure the console log function is available globally
+ if (!window.addConsoleLog) {
+ console.log('Creating fallback console log function');
+ window.addConsoleLog = function(message, level = 'info') {
+ console.log(`[${level.toUpperCase()}] ${message}`);
+
+ // Try to add to the console log UI if it exists
+ const consoleLogContainer = document.getElementById('console-log-container');
+ if (consoleLogContainer) {
+ // Check for empty message and remove it
+ const emptyMessage = consoleLogContainer.querySelector('.empty-log-message');
+ if (emptyMessage) {
+ emptyMessage.remove();
+ }
+
+ // Create a new log entry
+ const entry = document.createElement('div');
+ entry.className = 'console-log-entry';
+ entry.innerHTML = `
+ <span class="log-timestamp">${new Date().toLocaleTimeString()}</span>
+ <span class="log-badge ${level}">${level.charAt(0).toUpperCase() + level.slice(1)}</span>
+ <span class="log-message">${message}</span>
+ `;
+
+ // Add to container (at the beginning for newest first)
+ consoleLogContainer.insertBefore(entry, consoleLogContainer.firstChild);
+
+ // Update log count
+ const logIndicator = document.getElementById('log-indicator');
+ if (logIndicator) {
+ const currentCount = parseInt(logIndicator.textContent) || 0;
+ logIndicator.textContent = currentCount + 1;
+ }
+ }
+ };
+ }
});
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/components/detail.js b/src/local_deep_research/web/static/js/components/detail.js
index f2d5def7c8..5bf4000d4f 100644
--- a/src/local_deep_research/web/static/js/components/detail.js
+++ b/src/local_deep_research/web/static/js/components/detail.js
@@ -24,14 +24,14 @@
if (!currentResearchId || !currentTopicId) {
console.error('No research or topic ID found');
- window.ui.showError('Invalid research or topic. Please return to the results page.');
+ if (window.ui && window.ui.showError) {
+ window.ui.showError('Invalid research or topic. Please return to the results page.');
+ }
return;
}
// Get DOM elements
- detailContainer = document.getElementById('detail-content');
- sourcesList = document.getElementById('sources-list');
- tabsContainer = document.getElementById('detail-tabs');
+ detailContainer = document.getElementById('research-log');
if (!detailContainer) {
console.error('Required DOM elements not found for detail component');
@@ -69,6 +69,18 @@
* Set up event listeners
*/
function setupEventListeners() {
+ // Back button
+ const backButton = document.getElementById('back-to-history-from-details');
+ if (backButton) {
+ backButton.addEventListener('click', function() {
+ window.location.href = '/research/history';
+ });
+ }
+
+ // Progress elements
+ const progressBar = document.getElementById('detail-progress-fill');
+ const progressPercentage = document.getElementById('detail-progress-percentage');
+
// Tab click events
if (tabsContainer) {
tabsContainer.addEventListener('click', function(e) {
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 726c724885..0600f53676 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -92,7 +92,7 @@
// Fallback implementation
try {
- const response = await fetch(`/research/api/research/${researchId}/delete`, {
+ const response = await fetch(`/research/api/delete/${researchId}`, {
method: 'DELETE'
});
if (!response.ok) {
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.js
index adff1ef4e3..68ca3e1427 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -7,6 +7,7 @@
let currentResearchId = null;
let pollInterval = null;
let isCompleted = false;
+ let socketErrorShown = false;
// DOM Elements
let progressBar = null;
@@ -16,6 +17,16 @@
let cancelButton = null;
let viewResultsButton = null;
+ // Socket instance
+ let socket = null;
+ let reconnectAttempts = 0;
+ const MAX_RECONNECT_ATTEMPTS = 5;
+ const RECONNECT_DELAY = 3000;
+
+ // Current research info
+ let researchCompleted = false;
+ let notificationsEnabled = false;
+
/**
* Initialize the progress component
*/
@@ -67,6 +78,12 @@
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 fails
+ setupSafeNavigationHandling();
+
// Initialize socket connection if available
if (window.socket) {
initializeSocket();
@@ -80,6 +97,50 @@
checkProgress();
console.log('Progress component initialized for research ID:', currentResearchId);
+
+ // Get notification preference
+ notificationsEnabled = localStorage.getItem('notificationsEnabled') === 'true';
+
+ // Get initial research status
+ getInitialStatus();
+ }
+
+ /**
+ * Set up safe navigation handling to prevent WebSocket errors from blocking navigation
+ */
+ function setupSafeNavigationHandling() {
+ // Find all navigation links
+ const navLinks = document.querySelectorAll('a, .sidebar-nav li, .mobile-tab-bar li');
+
+ navLinks.forEach(link => {
+ // Don't override existing click handlers, add our handler
+ const originalClickHandler = link.onclick;
+
+ link.onclick = function(event) {
+ // If socket has errors, disconnect it before navigation
+ if (window.socket && typeof window.socket.isUsingPolling === 'function' && window.socket.isUsingPolling()) {
+ console.log('Navigation with polling fallback active, ensuring clean state');
+ try {
+ // Clean up any polling intervals
+ if (window.pollIntervals) {
+ Object.keys(window.pollIntervals).forEach(id => {
+ clearInterval(window.pollIntervals[id]);
+ });
+ }
+ } catch (e) {
+ console.error('Error cleaning up before navigation:', e);
+ }
+ }
+
+ // Call the original click handler if it exists
+ if (typeof originalClickHandler === 'function') {
+ return originalClickHandler.call(this, event);
+ }
+
+ // Default behavior
+ return true;
+ };
+ });
}
/**
@@ -150,6 +211,16 @@
*/
function initializeSocket() {
try {
+ console.log('Initializing socket connection for research ID:', currentResearchId);
+
+ // Check if socket service is available
+ if (!window.socket) {
+ console.warn('Socket service not available, falling back to polling');
+ // Set up polling as fallback
+ fallbackToPolling();
+ return;
+ }
+
// Subscribe to research events
window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);
@@ -158,17 +229,50 @@
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 connected
+ setTimeout(() => {
+ if (window.socket.isUsingPolling && window.socket.isUsingPolling()) {
+ console.log('Socket using polling fallback');
+ if (!socketErrorShown) {
+ socketErrorShown = true;
+ // Add an info message to the console log if it exists
+ if (window.addConsoleLog) {
+ window.addConsoleLog('Using polling for updates due to WebSocket connection issues', 'info');
+ }
+ }
+
+ // Ensure we check for updates right away
+ checkProgress();
+ } else {
+ console.log('Socket using WebSockets successfully');
+ }
+ }, 2000);
} catch (error) {
console.error('Error initializing socket:', error);
// Fall back to polling
- if (!pollInterval) {
- pollInterval = setInterval(checkProgress, 3000);
+ 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 polling
+ if (window.addConsoleLog) {
+ window.addConsoleLog('Using polling for research updates instead of WebSockets', 'info');
}
}
}
/**
- * Handle progress updates from Socket.IO
+ * Handle progress update from socket
* @param {Object} data - The progress data
*/
function handleProgressUpdate(data) {
@@ -176,6 +280,30 @@
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
+ if (data.progress_log && typeof data.progress_log === 'string') {
+ try {
+ // Validate that the progress_log is valid JSON
+ 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 exists
+ const 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
+ }
+ } catch (e) {
+ console.error('Error checking progress_log format:', e);
+ }
+ }
+
// Update progress UI
updateProgressUI(data);
@@ -183,6 +311,55 @@
if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {
handleResearchCompletion(data);
}
+
+ // Update the current query text if available
+ const currentQueryEl = document.getElementById('current-query');
+ if (currentQueryEl && localStorage.getItem('currentQuery')) {
+ currentQueryEl.textContent = localStorage.getItem('currentQuery');
+ }
+
+ // Check for task message updates with better fallbacks
+ let taskUpdated = false;
+
+ if (data.task_message && data.task_message.trim() !== '') {
+ // Direct task message is highest priority
+ setCurrentTask(data.task_message);
+ taskUpdated = true;
+ } else if (data.current_task && data.current_task.trim() !== '') {
+ // Then try current_task field
+ setCurrentTask(data.current_task);
+ taskUpdated = true;
+ } else if (data.message && data.message.trim() !== '') {
+ // Finally fall back to general message
+ // But only if it's informative (not just a status update)
+ const msg = data.message.toLowerCase();
+ if (!msg.includes('in progress') && !msg.includes('status update')) {
+ setCurrentTask(data.message);
+ 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
+ * @returns {string} Log level (info, milestone, error, etc)
+ */
+ 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';
}
/**
@@ -195,9 +372,12 @@
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 UI
updateProgressUI(data);
@@ -206,10 +386,19 @@
handleResearchCompletion(data);
} else {
// Set up polling for status updates as backup for socket
- if (!pollInterval) {
+ if (!pollInterval && (!window.socket || (window.socket.isUsingPolling && window.socket.isUsingPolling()))) {
+ console.log('Setting up polling interval for progress updates');
pollInterval = setInterval(checkProgress, 5000);
}
+
+ // Log a message every 5th poll to show activity
+ if (reconnectAttempts % 5 === 0) {
+ console.log('Still monitoring research progress...');
+ }
+ reconnectAttempts++; // Just using this as a counter for logging
}
+ } else {
+ console.warn('No data received from API');
}
} catch (error) {
console.error('Error checking research progress:', error);
@@ -230,7 +419,8 @@
// Ensure progress is between 0-100
const percentage = Math.max(0, Math.min(100, Math.floor(progress)));
- // Update progress bar width
+ // Update progress bar width with transition for smooth animation
+ progressBar.style.transition = 'width 0.3s ease-in-out';
progressBar.style.width = `${percentage}%`;
// Update percentage text if available
@@ -244,32 +434,141 @@
* @param {Object} data - The progress data
*/
function updateProgressUI(data) {
+ console.log('Updating progress UI with data:', data);
+
// Update progress bar
if (data.progress !== undefined && progressBar) {
- // Try to use UI service if available, otherwise use local function
- if (window.ui && typeof window.ui.updateProgressBar === 'function') {
- window.ui.updateProgressBar(progressBar, data.progress);
- } else {
- updateProgressBar(progressBar, data.progress);
- }
+ updateProgressBar(progressBar, data.progress);
}
- // Update status text
+ // Update status text with better formatting
if (data.status && statusText) {
- statusText.textContent = window.formatting ?
- window.formatting.formatStatus(data.status) :
- data.status.charAt(0).toUpperCase() + data.status.slice(1);
-
- // Add status class for styling
- document.querySelectorAll('.status-indicator').forEach(el => {
- el.className = 'status-indicator';
- el.classList.add(`status-${data.status}`);
- });
+ let formattedStatus;
+ if (window.formatting && typeof window.formatting.formatStatus === 'function') {
+ formattedStatus = window.formatting.formatStatus(data.status);
+ } else {
+ // Manual status formatting for better display
+ switch (data.status) {
+ case 'in_progress':
+ // Don't show "In Progress" at all in status text
+ return; // Skip status update entirely for in_progress
+ case 'completed':
+ formattedStatus = 'Completed';
+ break;
+ case 'failed':
+ formattedStatus = 'Failed';
+ break;
+ case 'cancelled':
+ formattedStatus = 'Cancelled';
+ break;
+ default:
+ formattedStatus = data.status.charAt(0).toUpperCase() +
+ data.status.slice(1).replace(/_/g, ' ');
+ }
+ }
+
+ // Only update status text if we have a non-empty formatted status
+ if (formattedStatus && formattedStatus.trim() !== '') {
+ statusText.textContent = formattedStatus;
+
+ // Add status class for styling
+ document.querySelectorAll('.status-indicator').forEach(el => {
+ el.className = 'status-indicator';
+ el.classList.add(`status-${data.status}`);
+ });
+ }
}
- // Update current task
- if (data.current_task && currentTaskText) {
- currentTaskText.textContent = data.current_task;
+ // Extract current task from progress_log
+ if (currentTaskText) {
+ let taskMessage = null;
+
+ // Try to parse progress_log to get the latest task
+ if (data.progress_log && typeof data.progress_log === 'string') {
+ try {
+ const progressLogs = JSON.parse(data.progress_log);
+ if (Array.isArray(progressLogs) && progressLogs.length > 0) {
+ // Get the latest log entry with a non-null message
+ for (let i = progressLogs.length - 1; i >= 0; i--) {
+ if (progressLogs[i].message && progressLogs[i].message.trim() !== '') {
+ taskMessage = progressLogs[i].message;
+ break;
+ }
+ }
+ }
+ } catch (e) {
+ console.error('Error parsing progress_log for task message:', e);
+ }
+ }
+
+ // Check various fields that might contain the current task message
+ if (!taskMessage) {
+ if (data.current_task) {
+ taskMessage = data.current_task;
+ } else if (data.message) {
+ taskMessage = data.message;
+ } else if (data.task) {
+ taskMessage = data.task;
+ } else if (data.step) {
+ taskMessage = data.step;
+ } else if (data.phase) {
+ taskMessage = `Phase: ${data.phase}`;
+ } else if (data.log_entry && data.log_entry.message) {
+ 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);
+ currentTaskText.textContent = taskMessage;
+ // Remember this message to avoid overwriting with generic messages
+ currentTaskText.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 displayed
+ if (!taskMessage && data.status && (!currentTaskText.dataset.lastMessage || currentTaskText.textContent === 'In Progress')) {
+ let statusMsg;
+ switch (data.status) {
+ case 'starting':
+ statusMsg = 'Starting research process...';
+ break;
+ case 'searching':
+ statusMsg = 'Searching for information...';
+ break;
+ case 'processing':
+ statusMsg = 'Processing search results...';
+ break;
+ case 'analyzing':
+ statusMsg = 'Analyzing gathered information...';
+ break;
+ case 'writing':
+ statusMsg = 'Writing research report...';
+ break;
+ case 'reviewing':
+ statusMsg = 'Reviewing and finalizing report...';
+ break;
+ case 'in_progress':
+ // Don't overwrite existing content with generic "In Progress" message
+ if (!currentTaskText.dataset.lastMessage || currentTaskText.textContent === '') {
+ statusMsg = 'Performing research...';
+ } else {
+ statusMsg = null; // Skip update
+ }
+ break;
+ default:
+ statusMsg = `${data.status.charAt(0).toUpperCase() + data.status.slice(1).replace('_', ' ')}...`;
+ }
+
+ // Only update if we have a new message
+ if (statusMsg) {
+ console.log('Using enhanced status-based message:', statusMsg);
+ currentTaskText.textContent = statusMsg;
+ // Don't remember generic messages
+ delete currentTaskText.dataset.lastMessage;
+ }
+ }
}
// Update page title with progress
@@ -279,13 +578,19 @@
// Update favicon based on status
if (window.ui && typeof window.ui.updateFavicon === 'function') {
- window.ui.updateFavicon(data.status);
+ window.ui.updateFavicon(data.status || 'in_progress');
}
// Show notification if enabled
if (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_entry
+ if (data.message && window.addConsoleLog && !data.log_entry) {
+ console.log('Adding message to console log:', data.message);
+ window.addConsoleLog(data.message, determineLogLevel(data.status));
+ }
}
/**
@@ -351,11 +656,11 @@
}
try {
- if (!window.api || !window.api.cancelResearch) {
+ if (!window.api || !window.api.terminateResearch) {
throw new Error('API service not available');
}
- await window.api.cancelResearch(currentResearchId);
+ await window.api.terminateResearch(currentResearchId);
// Update status manually (in case socket fails)
if (statusText) {
@@ -420,12 +725,293 @@
}
}
+ /**
+ * Get initial research status from API
+ */
+ async function getInitialStatus() {
+ try {
+ const status = await window.api.getResearchStatus(currentResearchId);
+
+ // Process status
+ if (status) {
+ // If complete, show complete UI
+ if (status.status === 'completed') {
+ handleResearchComplete({ research_id: currentResearchId });
+ }
+ // If error, show error UI
+ else if (status.status === 'error') {
+ handleResearchError({
+ research_id: currentResearchId,
+ error: status.message || 'Unknown error'
+ });
+ }
+ // Otherwise update progress
+ else {
+ updateProgressUI(status);
+ }
+ }
+ } catch (error) {
+ console.error('Error getting initial status:', error);
+ 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 UI
+ setProgressValue(100);
+ setStatus('completed');
+ setCurrentTask('Research completed successfully');
+
+ // Hide cancel button
+ if (cancelButton) {
+ cancelButton.style.display = 'none';
+ }
+
+ // Show results button
+ showResultsButton();
+
+ // Show notification if enabled
+ showNotification('Research Complete', 'Your research has been completed successfully.');
+
+ // Update favicon
+ updateFavicon(100);
+
+ // Set flag
+ researchCompleted = 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 state
+ setProgressValue(100);
+ setStatus('error');
+ setCurrentTask(`Error: ${data.error || 'Unknown error'}`);
+
+ // Add error class to progress bar
+ if (progressBar) {
+ progressBar.classList.remove('bg-primary', 'bg-success');
+ progressBar.classList.add('bg-danger');
+ }
+
+ // Hide cancel button
+ if (cancelButton) {
+ cancelButton.style.display = 'none';
+ }
+
+ // Show results button (might have partial results)
+ showResultsButton();
+
+ // Show notification if enabled
+ showNotification('Research Error', `There was an error with your research: ${data.error}`);
+
+ // Update favicon
+ updateFavicon(100, true);
+ }
+
+ /**
+ * Set progress bar value
+ * @param {number} value - Progress value (0-100)
+ */
+ function setProgressValue(value) {
+ if (!progressBar) return;
+
+ // Ensure value is in range
+ value = Math.min(Math.max(value, 0), 100);
+
+ // Update progress bar
+ progressBar.style.width = `${value}%`;
+ progressBar.setAttribute('aria-valuenow', value);
+
+ // Update classes based on progress
+ if (value >= 100) {
+ progressBar.classList.remove('bg-primary');
+ progressBar.classList.add('bg-success');
+ } else {
+ progressBar.classList.remove('bg-success', 'bg-danger');
+ 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 text
+ switch (status) {
+ case 'not_started':
+ statusDisplay = 'Not Started';
+ break;
+ case 'in_progress':
+ statusDisplay = 'In Progress';
+ break;
+ case 'completed':
+ statusDisplay = 'Completed';
+ break;
+ case 'cancelled':
+ statusDisplay = 'Cancelled';
+ break;
+ case 'error':
+ statusDisplay = 'Error';
+ break;
+ default:
+ statusDisplay = status ? status.charAt(0).toUpperCase() + status.slice(1) : 'Unknown';
+ }
+
+ statusText.textContent = statusDisplay;
+ }
+
+ /**
+ * Set current task text
+ * @param {string} task - Current task description
+ */
+ function setCurrentTask(task) {
+ if (!currentTaskText) return;
+ currentTaskText.textContent = task || 'No active task';
+ }
+
+ /**
+ * Set error state for the UI
+ * @param {string} message - Error message
+ */
+ function setErrorState(message) {
+ // Update progress UI
+ setProgressValue(100);
+ setStatus('error');
+ setCurrentTask(`Error: ${message}`);
+
+ // Add error class to progress bar
+ if (progressBar) {
+ progressBar.classList.remove('bg-primary', 'bg-success');
+ progressBar.classList.add('bg-danger');
+ }
+
+ // Hide cancel button
+ if (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)
+ * @param {boolean} isError - Whether there is an error
+ */
+ function updateFavicon(progress, isError = false) {
+ try {
+ // Find favicon link or create it if it doesn't exist
+ 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 console
+ console.debug('Favicon link not found, skipping dynamic favicon update');
+ return;
+ }
+
+ // Create canvas for drawing the favicon
+ const canvas = document.createElement('canvas');
+ canvas.width = 32;
+ canvas.height = 32;
+
+ const ctx = canvas.getContext('2d');
+
+ // Draw background
+ ctx.fillStyle = '#343a40'; // Dark background
+ ctx.beginPath();
+ ctx.arc(16, 16, 16, 0, 2 * Math.PI);
+ ctx.fill();
+
+ // Draw progress arc
+ ctx.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 status
+ if (isError) {
+ ctx.fillStyle = '#dc3545'; // Danger red
+ } else if (progress >= 100) {
+ ctx.fillStyle = '#28a745'; // Success green
+ } else {
+ ctx.fillStyle = '#007bff'; // Primary blue
+ }
+
+ ctx.fill();
+
+ // Draw center circle
+ ctx.fillStyle = '#343a40';
+ ctx.beginPath();
+ ctx.arc(16, 16, 8, 0, 2 * Math.PI);
+ ctx.fill();
+
+ // Draw letter R
+ ctx.fillStyle = '#ffffff';
+ ctx.font = 'bold 14px Arial';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText('R', 16, 16);
+
+ // Update favicon
+ link.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 load
document.addEventListener('DOMContentLoaded', initializeProgress);
- // Public API
+ // Expose components publicly for testing and debugging
window.progressComponent = {
checkProgress,
handleCancelResearch
};
+
+ // Add global error handler for WebSocket errors
+ window.addEventListener('error', function(event) {
+ if (event.message && event.message.includes('WebSocket') && event.message.includes('frame header')) {
+ console.warn('Caught WebSocket frame header error, suppressing');
+ event.preventDefault();
+ return true; // Prevent the error from showing in console
+ }
+ });
})();
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index a7bf931f3c..34b698bb61 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -51,6 +51,70 @@
form.addEventListener('submit', handleResearchSubmit);
}
+ /**
+ * Check if Ollama is running and model is available
+ * @returns {Promise<Object>} Result with status and error message if any
+ */
+ async function checkOllamaModel() {
+ try {
+ console.log('Checking Ollama status...');
+ // First check if the Ollama service is running
+ try {
+ const statusResponse = await fetch('/research/api/check/ollama_status');
+
+ // If we get a 404, assume the API doesn't exist and skip the check
+ if (statusResponse.status === 404) {
+ console.log('Ollama status check endpoint not available, skipping check');
+ return { success: true };
+ }
+
+ const statusData = await statusResponse.json();
+
+ if (!statusData.running) {
+ return {
+ success: false,
+ error: "Ollama service is not running. Please start Ollama before continuing.",
+ solution: "Run 'ollama serve' in your terminal to start the service."
+ };
+ }
+
+ // Then check if the model is available
+ const modelResponse = await fetch('/research/api/check/ollama_model');
+
+ // If we get a 404, assume the API doesn't exist and skip the check
+ if (modelResponse.status === 404) {
+ console.log('Ollama model check endpoint not available, skipping check');
+ return { success: true };
+ }
+
+ const modelData = await modelResponse.json();
+
+ if (!modelData.available) {
+ const modelName = modelData.model || "gemma3:12b";
+ return {
+ success: false,
+ error: `Required model '${modelName}' is not available in Ollama.`,
+ solution: `Run 'ollama pull ${modelName}' to download the model.`
+ };
+ }
+ } catch (error) {
+ // If we catch an error trying to access the check endpoints,
+ // assume the API doesn't support these checks and continue
+ console.log('Error checking Ollama status, skipping check:', error);
+ return { success: true };
+ }
+
+ return { success: true };
+ } catch (error) {
+ console.error('Error checking Ollama:', error);
+ return {
+ success: false,
+ error: "Could not verify Ollama status. Please ensure Ollama is properly configured.",
+ solution: "Check that Ollama is running and accessible at the configured URL."
+ };
+ }
+ }
+
/**
* Handle research form submission
* @param {Event} e - The form submit event
@@ -74,6 +138,14 @@
setFormSubmitting(true);
try {
+ // First check if Ollama is running and model is available
+ const ollamaCheck = await checkOllamaModel();
+ if (!ollamaCheck.success) {
+ showFormError(`${ollamaCheck.error} ${ollamaCheck.solution}`);
+ setFormSubmitting(false);
+ return;
+ }
+
// Start research process
const response = await window.api.startResearch(query, mode);
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 86160ad94d..8e6e8d0bee 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -1,48 +1,36 @@
/**
* Results Component
- * Manages the display and interaction with research results
+ * Handles the display of research results
*/
(function() {
- // Component state
- let currentResearchId = null;
- let researchData = null;
-
// DOM Elements
let resultsContainer = null;
- let metadataContainer = null;
- let exportPdfBtn = null;
- let exportMarkdownBtn = null;
- let backToHistoryBtn = null;
+ let exportBtn = null;
+ let pdfBtn = null;
+ let researchId = null;
+ let researchData = null;
/**
* Initialize the results component
*/
function initializeResults() {
- // Get research ID from URL
- currentResearchId = getResearchIdFromUrl();
+ // Get DOM elements
+ resultsContainer = document.getElementById('results-content');
+ exportBtn = document.getElementById('export-markdown-btn');
+ pdfBtn = document.getElementById('download-pdf-btn');
- if (!currentResearchId) {
- console.error('No research ID found');
- if (window.ui && window.ui.showError) {
- window.ui.showError('No research results found. Please start a new research.');
- } else {
- alert('No research results found. Please start a new research.');
- }
- setTimeout(() => {
- window.location.href = '/research';
- }, 3000);
+ if (!resultsContainer) {
+ console.error('Results container not found');
return;
}
- // Get DOM elements
- resultsContainer = document.getElementById('results-content');
- metadataContainer = document.getElementById('research-metadata');
- exportPdfBtn = document.getElementById('download-pdf-btn');
- exportMarkdownBtn = document.getElementById('export-markdown-btn');
- backToHistoryBtn = document.getElementById('back-to-history');
+ console.log('Results component initialized');
- if (!resultsContainer) {
- console.error('Required DOM elements not found for results component');
+ // Get research ID from URL
+ researchId = getResearchIdFromUrl();
+
+ if (!researchId) {
+ showError('Research ID not found in URL');
return;
}
@@ -52,542 +40,723 @@
// Load research results
loadResearchResults();
- // Set up log panel for this research
- initializeLogPanel();
-
- console.log('Results component initialized for research ID:', currentResearchId);
+ // Note: Log panel is now automatically initialized by logpanel.js
+ // No need to manually initialize it here
}
/**
- * Initialize log panel functionality
+ * Set up event listeners
*/
- function initializeLogPanel() {
- if (window.loadLogsForResearch && currentResearchId) {
- try {
- console.log('Loading logs for research ID:', currentResearchId);
- window.loadLogsForResearch(currentResearchId);
- } catch (error) {
- console.error('Error loading research logs:', error);
- }
- } else if (currentResearchId) {
- // Fallback to manually load logs if the global function isn't available
- try {
- const logContainer = document.getElementById('console-log-container');
- const logToggle = document.getElementById('log-panel-toggle');
-
- if (logContainer && logToggle) {
- // Set up log panel toggle
- logToggle.addEventListener('click', function() {
- const panel = document.querySelector('.collapsible-log-panel');
- if (panel) {
- panel.classList.toggle('expanded');
- const icon = panel.querySelector('.toggle-icon');
- if (icon) {
- icon.classList.toggle('fa-chevron-down');
- icon.classList.toggle('fa-chevron-up');
- }
- }
- });
-
- // Load logs from API
- fetchLogsForResearch(currentResearchId);
- }
- } catch (error) {
- console.error('Error setting up fallback log handling:', error);
- }
+ function setupEventListeners() {
+ // Export button
+ if (exportBtn) {
+ exportBtn.addEventListener('click', handleExport);
+ }
+
+ // PDF button
+ if (pdfBtn) {
+ pdfBtn.addEventListener('click', handlePdfExport);
+ }
+
+ // Back to history button
+ const backBtn = document.getElementById('back-to-history');
+ if (backBtn) {
+ backBtn.addEventListener('click', () => {
+ window.location.href = '/research/history';
+ });
}
}
/**
- * Fetch logs from API and display them
+ * Get research ID from URL
+ * @returns {string|null} Research ID
+ */
+ function getResearchIdFromUrl() {
+ const path = window.location.pathname;
+ const match = path.match(/\/research\/results\/(\d+)/);
+ return match ? match[1] : null;
+ }
+
+ /**
+ * Load research results from API
*/
- async function fetchLogsForResearch(researchId) {
+ async function loadResearchResults() {
try {
- console.log('Fetching logs for research ID:', researchId);
+ // Show loading state
+ resultsContainer.innerHTML = '<div class="text-center my-5"><i class="fas fa-spinner fa-pulse"></i><p class="mt-3">Loading research results...</p></div>';
+
+ // Fetch result from API
+ const response = await fetch(`/research/api/report/${researchId}`);
- if (!window.api || !window.api.getResearchLogs) {
- console.warn('API service not available for logs');
- return;
+ if (!response.ok) {
+ throw new Error(`HTTP error ${response.status}`);
}
- const response = await window.api.getResearchLogs(researchId);
- console.log('Log response:', response);
+ const responseData = await response.json();
+ console.log('Original API response:', responseData);
+
+ // Store data for export
+ researchData = responseData;
+
+ // Check if we have data to display
+ if (!responseData) {
+ throw new Error('No data received from server');
+ }
+
+ // Use the API metadata directly
+ if (responseData.metadata && typeof responseData.metadata === 'object') {
+ console.log('Using metadata directly from API response:', responseData.metadata);
+ populateMetadataFromApiResponse(responseData);
+ } else {
+ // Fallback to content extraction if no metadata in response
+ populateMetadata(responseData);
+ }
- if (response && response.status === 'success' && response.logs && Array.isArray(response.logs)) {
- displayLogs(response.logs);
+ // Render the content
+ if (responseData.content && typeof responseData.content === 'string') {
+ console.log('Rendering content from API response');
+ renderResults(responseData.content);
} else {
- console.warn('Invalid log data format:', response);
+ // Try to find content in other response formats
+ console.log('No direct content found, trying to find content in response');
+ findAndRenderContent(responseData);
}
+
+ // Enable export buttons
+ if (exportBtn) exportBtn.disabled = false;
+ if (pdfBtn) pdfBtn.disabled = false;
+
} catch (error) {
- console.error('Error fetching logs:', error);
+ console.error('Error loading research results:', error);
+ showError(`Error loading research results: ${error.message}`);
+
+ // Disable export buttons
+ if (exportBtn) exportBtn.disabled = true;
+ if (pdfBtn) pdfBtn.disabled = true;
}
}
/**
- * Display logs in the log panel
+ * Populate metadata directly from API response metadata
+ * @param {Object} data - API response with metadata
*/
- function displayLogs(logs) {
- const logContainer = document.getElementById('console-log-container');
- const logIndicator = document.getElementById('log-indicator');
-
- if (!logContainer) return;
-
- // Clear existing logs
- logContainer.innerHTML = '';
-
- if (logs.length === 0) {
- logContainer.innerHTML = '<div class="empty-log-message">No logs available for this research.</div>';
- if (logIndicator) logIndicator.textContent = '0';
- return;
+ function populateMetadataFromApiResponse(data) {
+ const metadata = data.metadata || {};
+ console.log('Using API response metadata:', metadata);
+
+ // Query field
+ const queryElement = document.getElementById('result-query');
+ if (queryElement) {
+ // Use query from metadata or content title
+ const query = metadata.query || metadata.title || data.query || 'Untitled Research';
+ console.log('Setting query to:', query);
+ queryElement.textContent = query;
}
- // Get the template
- const template = document.getElementById('console-log-entry-template');
-
- // Format and display each log
- logs.forEach(log => {
- let entry;
+ // Generated date field
+ const dateElement = document.getElementById('result-date');
+ if (dateElement) {
+ let dateStr = 'Unknown date';
- if (template) {
- // Use template if available
- entry = document.importNode(template.content, true).querySelector('.console-log-entry');
-
- // Set log data
- entry.querySelector('.log-timestamp').textContent = formatLogTimestamp(log.time);
-
- const badge = entry.querySelector('.log-badge');
- badge.textContent = log.type || 'info';
- badge.className = `log-badge log-badge-${log.type || 'info'}`;
-
- entry.querySelector('.log-message').textContent = log.message;
+ // Try multiple sources for the timestamp - first from the API response directly, then from metadata
+ const timestamp = data.created_at || data.timestamp || data.date ||
+ metadata.created_at || metadata.timestamp || metadata.date;
+
+ console.log('Found timestamp:', timestamp);
+
+ if (timestamp) {
+ if (window.formatting && typeof window.formatting.formatDate === 'function') {
+ dateStr = window.formatting.formatDate(timestamp);
+ console.log('Formatting timestamp with formatter:', timestamp, '→', dateStr);
+ } else {
+ try {
+ const date = new Date(timestamp);
+ dateStr = date.toLocaleString();
+ console.log('Formatting timestamp with toLocaleString:', timestamp, '→', dateStr);
+ } catch (e) {
+ console.error('Error parsing date:', e);
+ }
+ }
- } else {
- // Fallback if template is not available
- entry = document.createElement('div');
- entry.className = 'console-log-entry';
- entry.innerHTML = `
- <span class="log-timestamp">${formatLogTimestamp(log.time)}</span>
- <span class="log-badge log-badge-${log.type || 'info'}">${log.type || 'info'}</span>
- <span class="log-message">${log.message}</span>
- `;
+ // Add duration if available - format as "Xm Ys" for values over 60 seconds
+ if (metadata.duration || metadata.duration_seconds || data.duration_seconds) {
+ const durationSeconds = parseInt(metadata.duration || metadata.duration_seconds || data.duration_seconds, 10);
+
+ if (!isNaN(durationSeconds)) {
+ let durationStr;
+ if (durationSeconds < 60) {
+ durationStr = `${durationSeconds}s`;
+ } else {
+ const minutes = Math.floor(durationSeconds / 60);
+ const seconds = durationSeconds % 60;
+ durationStr = `${minutes}m ${seconds}s`;
+ }
+ dateStr += ` (${durationStr})`;
+ }
+ }
}
- logContainer.appendChild(entry);
- });
-
- // Update log count
- if (logIndicator) logIndicator.textContent = logs.length;
- }
-
- /**
- * Format log timestamp
- */
- function formatLogTimestamp(timestamp) {
- try {
- const date = new Date(timestamp);
- return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});
- } catch (e) {
- return timestamp || '';
+ console.log('Setting date to:', dateStr);
+ dateElement.textContent = dateStr;
}
- }
-
- /**
- * Extract research ID from URL
- * @returns {string|null} The research ID or null if not found
- */
- function getResearchIdFromUrl() {
- const pathParts = window.location.pathname.split('/');
- const idIndex = pathParts.indexOf('results') + 1;
- if (idIndex > 0 && idIndex < pathParts.length) {
- return pathParts[idIndex];
+ // Mode field
+ const modeElement = document.getElementById('result-mode');
+ if (modeElement) {
+ // Get mode from metadata or main response
+ let mode = metadata.mode || metadata.research_mode || metadata.type ||
+ data.mode || data.research_mode || data.type;
+
+ // Detect if this is a detailed report based on content structure
+ if (!mode && data.content) {
+ if (data.content.toLowerCase().includes('table of contents') ||
+ data.content.match(/^#.*\n+##.*\n+###/m)) {
+ mode = 'detailed';
+ } else {
+ mode = 'quick';
+ }
+ }
+
+ // Format mode using available formatter
+ if (window.formatting && typeof window.formatting.formatMode === 'function') {
+ mode = window.formatting.formatMode(mode);
+ console.log('Formatted mode:', mode);
+ }
+
+ console.log('Setting mode to:', mode || 'Quick');
+ modeElement.textContent = mode || 'Quick';
}
-
- return null;
}
/**
- * Set up event listeners
+ * Find and render content from various response formats
+ * @param {Object} data - Research data to extract content from
*/
- function setupEventListeners() {
- if (exportPdfBtn) {
- exportPdfBtn.addEventListener('click', handleExportPdf);
- }
-
- if (exportMarkdownBtn) {
- exportMarkdownBtn.addEventListener('click', handleExportMarkdown);
- }
-
- if (backToHistoryBtn) {
- backToHistoryBtn.addEventListener('click', () => {
- window.location.href = '/research/history';
- });
- }
-
- // Set up table of contents click events
- document.addEventListener('click', function(e) {
- if (e.target && e.target.matches('.toc-link')) {
- e.preventDefault();
- const targetId = e.target.getAttribute('href').substring(1);
- const targetElement = document.getElementById(targetId);
-
- if (targetElement) {
- // Smooth scroll to section
- targetElement.scrollIntoView({ behavior: 'smooth' });
+ function findAndRenderContent(data) {
+ if (data.content && typeof data.content === 'string') {
+ // Direct content property (newer format)
+ console.log('Rendering from data.content');
+ renderResults(data.content);
+ } else if (data.research && data.research.content) {
+ // Nested content in research object (older format)
+ console.log('Rendering from data.research.content');
+ renderResults(data.research.content);
+ } else if (data.report && typeof data.report === 'string') {
+ // Report format
+ console.log('Rendering from data.report');
+ renderResults(data.report);
+ } else if (data.results && data.results.content) {
+ // Results with content field
+ console.log('Rendering from data.results.content');
+ renderResults(data.results.content);
+ } else if (data.results && typeof data.results === 'string') {
+ // Results as direct string
+ console.log('Rendering from data.results string');
+ renderResults(data.results);
+ } else if (typeof data === 'string') {
+ // Plain string format
+ console.log('Rendering from string data');
+ renderResults(data);
+ } else {
+ // Look for any property that might contain the content
+ const contentProps = ['markdown', 'text', 'summary', 'output', 'research_output'];
+ let foundContent = false;
+
+ for (const prop of contentProps) {
+ if (data[prop] && typeof data[prop] === 'string') {
+ console.log(`Rendering from data.${prop}`);
+ renderResults(data[prop]);
+ foundContent = true;
+ break;
}
}
- });
+
+ if (!foundContent) {
+ // Last resort: try to render the entire data object
+ console.log('No clear content found, rendering entire data object');
+ renderResults(data);
+ }
+ }
}
/**
- * Load research results from API
+ * Populate metadata fields with information from the research data
+ * @param {Object} data - Research data with metadata
*/
- async function loadResearchResults() {
- // Show loading state
- if (window.ui && window.ui.showSpinner) {
- window.ui.showSpinner(resultsContainer, 'Loading research results...');
- }
-
- try {
- // Get research results - using getReport instead of undefined getResearchResults
- if (!window.api || !window.api.getReport) {
- throw new Error('API service not available');
- }
-
- researchData = await window.api.getReport(currentResearchId);
+ function populateMetadata(data) {
+ // Debug the data structure
+ console.log('API response data:', data);
+ console.log('Data type:', typeof data);
+ console.log('Available top-level keys:', Object.keys(data));
+
+ // Direct extraction from content
+ if (data.content && typeof data.content === 'string') {
+ console.log('Attempting to extract metadata from content');
- if (!researchData) {
- throw new Error('No research results found');
+ // Extract the query from content first line or header
+ // Avoid matching "Table of Contents" as query
+ const queryMatch = data.content.match(/^#\s*([^\n]+)/m) || // First heading
+ data.content.match(/Query:\s*([^\n]+)/i) || // Explicit query label
+ data.content.match(/Question:\s*([^\n]+)/i) || // Question label
+ data.content.match(/^([^\n#]+)(?=\n)/); // First line if not starting with #
+
+ if (queryMatch && queryMatch[1] && !queryMatch[1].toLowerCase().includes('table of contents')) {
+ const queryElement = document.getElementById('result-query');
+ if (queryElement) {
+ const extractedQuery = queryMatch[1].trim();
+ console.log('Extracted query from content:', extractedQuery);
+ queryElement.textContent = extractedQuery;
+ }
+ } else {
+ // Try to find the second heading if first was "Table of Contents"
+ const secondHeadingMatch = data.content.match(/^#\s*([^\n]+)[\s\S]*?^##\s*([^\n]+)/m);
+ if (secondHeadingMatch && secondHeadingMatch[2]) {
+ const queryElement = document.getElementById('result-query');
+ if (queryElement) {
+ const extractedQuery = secondHeadingMatch[2].trim();
+ console.log('Extracted query from second heading:', extractedQuery);
+ queryElement.textContent = extractedQuery;
+ }
+ }
}
- // 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');
+ // Extract generated date/time - Try multiple formats
+ const dateMatch = data.content.match(/Generated at:\s*([^\n]+)/i) ||
+ data.content.match(/Date:\s*([^\n]+)/i) ||
+ data.content.match(/Generated:\s*([^\n]+)/i) ||
+ data.content.match(/Created:\s*([^\n]+)/i);
+
+ if (dateMatch && dateMatch[1]) {
+ const dateElement = document.getElementById('result-date');
+ if (dateElement) {
+ const extractedDate = dateMatch[1].trim();
+ console.log('Extracted date from content:', extractedDate);
+
+ // Format the date using the available formatter
+ let formattedDate = extractedDate;
+ if (window.formatting && typeof window.formatting.formatDate === 'function') {
+ formattedDate = window.formatting.formatDate(extractedDate);
+ console.log('Date formatted using formatter:', formattedDate);
+ }
+
+ dateElement.textContent = formattedDate || new Date().toLocaleString();
}
}
- // Render results
- renderResults(researchData);
+ // Extract mode
+ const modeMatch = data.content.match(/Mode:\s*([^\n]+)/i) ||
+ data.content.match(/Research type:\s*([^\n]+)/i);
- // 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) {
- window.ui.hideSpinner(resultsContainer);
- }
- if (window.ui && window.ui.showError) {
- window.ui.showError('Error loading research results: ' + error.message);
+ if (modeMatch && modeMatch[1]) {
+ const modeElement = document.getElementById('result-mode');
+ if (modeElement) {
+ const extractedMode = modeMatch[1].trim();
+ console.log('Extracted mode from content:', extractedMode);
+
+ // Format mode using available formatter
+ let formattedMode = extractedMode;
+ if (window.formatting && typeof window.formatting.formatMode === 'function') {
+ formattedMode = window.formatting.formatMode(extractedMode);
+ console.log('Mode formatted using formatter:', formattedMode);
+ }
+
+ modeElement.textContent = formattedMode || 'Standard';
+ }
} else {
- resultsContainer.innerHTML = `<div class="error-message">Error loading research results: ${error.message}</div>`;
+ // Detect mode based on content structure and keywords
+ const modeElement = document.getElementById('result-mode');
+ if (modeElement) {
+ if (data.content.toLowerCase().includes('table of contents') ||
+ data.content.toLowerCase().includes('detailed report') ||
+ data.content.match(/^#.*\n+##.*\n+###/m)) { // Has H1, H2, H3 structure
+ modeElement.textContent = 'Detailed';
+ } else if (data.content.toLowerCase().includes('quick research') ||
+ data.content.toLowerCase().includes('summary')) {
+ modeElement.textContent = 'Quick';
+ } else {
+ modeElement.textContent = 'Standard'; // Better default
+ }
+ }
}
+
+ return; // Exit early since we've handled extraction from content
}
- }
-
- /**
- * Render research results
- * @param {Object} data - The research data
- */
- function renderResults(data) {
- // Hide spinner
- if (window.ui && window.ui.hideSpinner) {
- window.ui.hideSpinner(resultsContainer);
+
+ // Also check the metadata field which likely contains the actual metadata
+ const metadata = data.metadata || {};
+ console.log('Metadata object:', metadata);
+ if (metadata) {
+ console.log('Metadata keys:', Object.keys(metadata));
}
- // Set page title
- document.title = `${data.title || 'Research Results'} - Local Deep Research`;
+ // Extract research object if nested
+ const researchData = data.research || data;
- // Render metadata
- if (metadataContainer) {
- renderMetadata(data);
+ // Debug nested structure if exists
+ if (data.research) {
+ console.log('Nested research data:', data.research);
+ console.log('Research keys:', Object.keys(data.research));
}
- // 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;
+ // Query field
+ const queryElement = document.getElementById('result-query');
+ if (queryElement) {
+ // Try different possible locations for query data
+ let query = 'Unknown query';
+
+ if (metadata.query) {
+ query = metadata.query;
+ } else if (metadata.title) {
+ query = metadata.title;
+ } else if (researchData.query) {
+ query = researchData.query;
+ } else if (researchData.prompt) {
+ query = researchData.prompt;
+ } else if (researchData.title) {
+ query = researchData.title;
+ } else if (researchData.question) {
+ query = researchData.question;
+ } else if (researchData.input) {
+ query = researchData.input;
+ }
+
+ console.log('Setting query to:', query);
+ queryElement.textContent = query;
}
- // Render content
- if (contentToRender) {
- // Render markdown
- if (window.ui && window.ui.renderMarkdown) {
- 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>${contentToRender}</pre>`;
+ // Generated date field
+ const dateElement = document.getElementById('result-date');
+ if (dateElement) {
+ let dateStr = 'Unknown date';
+ let timestampField = null;
+
+ // Try different possible date fields
+ if (metadata.created_at) {
+ timestampField = metadata.created_at;
+ } else if (metadata.timestamp) {
+ timestampField = metadata.timestamp;
+ } else if (metadata.date) {
+ timestampField = metadata.date;
+ } else if (researchData.timestamp) {
+ timestampField = researchData.timestamp;
+ } else if (researchData.created_at) {
+ timestampField = researchData.created_at;
+ } else if (researchData.date) {
+ timestampField = researchData.date;
+ } else if (researchData.time) {
+ timestampField = researchData.time;
}
- // Generate table of contents
- generateTableOfContents();
+ // Format the date using the available formatter
+ if (timestampField) {
+ if (window.formatting && typeof window.formatting.formatDate === 'function') {
+ dateStr = window.formatting.formatDate(timestampField);
+ console.log('Using formatter for timestamp:', timestampField, '→', dateStr);
+ } else {
+ try {
+ const date = new Date(timestampField);
+ dateStr = date.toLocaleString();
+ console.log('Using timestamp:', timestampField, '→', dateStr);
+ } catch (e) {
+ console.error('Error parsing date:', timestampField, e);
+ }
+ }
+ }
- // Add syntax highlighting
- highlightCodeBlocks();
- } else {
- resultsContainer.innerHTML = '<p class="text-error">No research content available.</p>';
- }
-
- // Enable export buttons
- if (exportPdfBtn) exportPdfBtn.disabled = false;
- if (exportMarkdownBtn) exportMarkdownBtn.disabled = false;
- }
-
- /**
- * Render research metadata
- * @param {Object} data - The research data
- */
- function renderMetadata(data) {
- const metadata = [];
-
- // Research title
- if (data.title) {
- const titleElement = document.querySelector('h1.page-title');
- if (titleElement) {
- titleElement.textContent = data.title;
+ // Add duration if available
+ if (metadata.duration) {
+ dateStr += ` (${metadata.duration} seconds)`;
+ } else if (metadata.duration_seconds) {
+ dateStr += ` (${metadata.duration_seconds} seconds)`;
+ } else if (researchData.duration) {
+ dateStr += ` (${researchData.duration} seconds)`;
}
+
+ console.log('Setting date to:', dateStr);
+ dateElement.textContent = dateStr;
}
- // Query
- if (data.query) {
- metadata.push(`<div class="metadata-item"><span>Query:</span> ${data.query}</div>`);
- }
-
- // Mode
- if (data.mode) {
- const formattedMode = window.formatting && window.formatting.formatMode ?
- window.formatting.formatMode(data.mode) : data.mode;
- metadata.push(`<div class="metadata-item"><span>Mode:</span> ${formattedMode}</div>`);
- }
-
- // Completed date
- if (data.completed_at) {
- const formattedDate = window.formatting && window.formatting.formatDate ?
- window.formatting.formatDate(data.completed_at) : data.completed_at;
- metadata.push(`<div class="metadata-item"><span>Completed:</span> ${formattedDate}</div>`);
- }
-
- // Duration
- if (data.duration_seconds) {
- const minutes = Math.floor(data.duration_seconds / 60);
- const seconds = data.duration_seconds % 60;
- metadata.push(`<div class="metadata-item"><span>Duration:</span> ${minutes}m ${seconds}s</div>`);
- }
-
- // Sources count
- if (data.sources_count) {
- metadata.push(`<div class="metadata-item"><span>Sources:</span> ${data.sources_count}</div>`);
+ // Mode field
+ const modeElement = document.getElementById('result-mode');
+ if (modeElement) {
+ let mode = 'Quick'; // Default to Quick
+
+ if (metadata.mode) {
+ mode = metadata.mode;
+ } else if (metadata.research_mode) {
+ mode = metadata.research_mode;
+ } else if (metadata.type) {
+ mode = metadata.type;
+ } else if (researchData.mode) {
+ mode = researchData.mode;
+ } else if (researchData.research_mode) {
+ mode = researchData.research_mode;
+ } else if (researchData.type) {
+ mode = researchData.type;
+ }
+
+ // Format mode using available formatter
+ if (window.formatting && typeof window.formatting.formatMode === 'function') {
+ mode = window.formatting.formatMode(mode);
+ }
+
+ console.log('Setting mode to:', mode);
+ modeElement.textContent = mode;
}
-
- // Render metadata
- metadataContainer.innerHTML = metadata.join('');
}
/**
- * Generate table of contents from headings
+ * Render research results in the container
+ * @param {Object|string} data - Research data to render
*/
- function generateTableOfContents() {
- const tocContainer = document.getElementById('table-of-contents');
- if (!tocContainer) return;
-
- const headings = resultsContainer.querySelectorAll('h2, h3, h4');
- if (headings.length === 0) {
- const tocParent = tocContainer.closest('.toc-container');
- if (tocParent) {
- tocParent.style.display = 'none';
+ function renderResults(data) {
+ try {
+ // Clear container
+ resultsContainer.innerHTML = '';
+
+ // Determine the content to render
+ let content = '';
+
+ if (typeof data === 'string') {
+ // Direct string content
+ content = data;
+ } else if (data.markdown) {
+ // Markdown content
+ content = data.markdown;
+ } else if (data.html) {
+ // HTML content
+ resultsContainer.innerHTML = data.html;
+ return; // Return early since we've set HTML directly
+ } else if (data.text) {
+ // Text content
+ content = data.text;
+ } else if (data.summary) {
+ // Summary content
+ content = data.summary;
+ } else if (data.results) {
+ // Results array (old format)
+ if (Array.isArray(data.results)) {
+ content = data.results.join('\n\n');
+ } else {
+ content = JSON.stringify(data.results, null, 2);
+ }
+ } else {
+ // Last resort: stringify the entire object
+ content = JSON.stringify(data, null, 2);
}
- return;
- }
-
- const tocItems = [];
-
- // Process each heading
- headings.forEach((heading, index) => {
- // Add ID if not present
- if (!heading.id) {
- heading.id = `heading-${index}`;
+
+ // Render the content as Markdown if possible
+ if (window.ui && window.ui.renderMarkdown) {
+ const renderedHtml = window.ui.renderMarkdown(content);
+ resultsContainer.innerHTML = renderedHtml;
+ } else {
+ // Fall back to basic formatting
+ content = content.replace(/\n/g, '<br>');
+ resultsContainer.innerHTML = `<div class="markdown-content">${content}</div>`;
}
- const level = parseInt(heading.tagName.substring(1)) - 2;
- const indentation = ' '.repeat(level);
+ // Add syntax highlighting if Prism is available
+ if (window.Prism) {
+ window.Prism.highlightAllUnder(resultsContainer);
+ }
- tocItems.push(`${indentation}<li><a href="#${heading.id}" class="toc-link">${heading.textContent}</a></li>`);
- });
-
- // Render table of contents
- tocContainer.innerHTML = `<ul>${tocItems.join('')}</ul>`;
+ } catch (error) {
+ console.error('Error rendering results:', error);
+ showError(`Error rendering results: ${error.message}`);
+ }
}
/**
- * Apply syntax highlighting to code blocks
+ * Show error message in the results container
+ * @param {string} message - Error message
*/
- function highlightCodeBlocks() {
- // Check if Prism is available
- if (typeof Prism !== 'undefined') {
- Prism.highlightAllUnder(resultsContainer);
- }
+ function showError(message) {
+ resultsContainer.innerHTML = `
+ <div class="alert alert-danger" role="alert">
+ <i class="fas fa-exclamation-triangle"></i> ${message}
+ </div>
+ <p class="text-center mt-3">
+ <a href="/research" class="btn btn-primary">
+ <i class="fas fa-arrow-left"></i> Back to Research
+ </a>
+ </p>
+ `;
}
/**
- * Handle PDF export
+ * Handle export button click
*/
- function handleExportPdf() {
- if (!researchData) return;
-
- // Disable button
- if (exportPdfBtn) {
- exportPdfBtn.disabled = true;
- exportPdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
- }
-
+ function handleExport() {
try {
- if (!window.pdf || !window.pdf.downloadPdf) {
- throw new Error('PDF service not available');
+ if (!researchData) {
+ throw new Error('No research data available');
}
- // Generate and download PDF
- window.pdf.downloadPdf(
- researchData.title || 'Research Results',
- researchData.content,
- {
- query: researchData.query,
- mode: window.formatting && window.formatting.formatMode ?
- window.formatting.formatMode(researchData.mode) : researchData.mode,
- completed: window.formatting && window.formatting.formatDate ?
- window.formatting.formatDate(researchData.completed_at) : researchData.completed_at,
- sources: researchData.sources_count
- }
- );
+ // Get metadata from DOM (which should be populated by now)
+ const query = document.getElementById('result-query')?.textContent || 'Unknown query';
+ const generated = document.getElementById('result-date')?.textContent || 'Unknown date';
+ const mode = document.getElementById('result-mode')?.textContent || 'Quick';
+
+ // Create markdown header with metadata
+ let markdownHeader = `# Research Results: ${query}\n\n`;
+ markdownHeader += `- **Generated:** ${generated}\n`;
+ markdownHeader += `- **Mode:** ${mode}\n\n`;
+ markdownHeader += `---\n\n`;
- // Reset button state after delay
- setTimeout(() => {
- if (exportPdfBtn) {
- exportPdfBtn.disabled = false;
- exportPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';
+ // Extract the content to export
+ let markdownContent = '';
+
+ // Try to extract the markdown content from various possible locations
+ if (typeof researchData === 'string') {
+ markdownContent = researchData;
+ } else {
+ // Check for content in standard locations
+ const contentProps = [
+ 'content',
+ 'report',
+ 'markdown',
+ 'text',
+ 'summary',
+ 'output',
+ 'research_output'
+ ];
+
+ let found = false;
+
+ // First check direct properties
+ for (const prop of contentProps) {
+ if (researchData[prop] && typeof researchData[prop] === 'string') {
+ markdownContent = researchData[prop];
+ console.log(`Using ${prop} for markdown content`);
+ found = true;
+ break;
+ }
+ }
+
+ // Then check nested properties
+ if (!found && researchData.research) {
+ for (const prop of contentProps) {
+ if (researchData.research[prop] && typeof researchData.research[prop] === 'string') {
+ markdownContent = researchData.research[prop];
+ console.log(`Using research.${prop} for markdown content`);
+ found = true;
+ break;
+ }
+ }
+ }
+
+ // Check results property
+ if (!found && researchData.results) {
+ if (typeof researchData.results === 'string') {
+ markdownContent = researchData.results;
+ console.log('Using results string for markdown content');
+ } else {
+ for (const prop of contentProps) {
+ if (researchData.results[prop] && typeof researchData.results[prop] === 'string') {
+ markdownContent = researchData.results[prop];
+ console.log(`Using results.${prop} for markdown content`);
+ found = true;
+ break;
+ }
+ }
+ }
+ }
+
+ // Last resort
+ if (!markdownContent) {
+ console.warn('Could not extract markdown content, using JSON');
+ markdownContent = "```json\n" + JSON.stringify(researchData, null, 2) + "\n```";
}
- }, 1000);
- } catch (error) {
- console.error('Error generating PDF:', error);
- if (window.ui && window.ui.showError) {
- window.ui.showError('Error generating PDF: ' + error.message);
}
- // Reset button state
- if (exportPdfBtn) {
- exportPdfBtn.disabled = false;
- exportPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';
- }
+ // Combine header and content
+ const fullMarkdown = markdownHeader + markdownContent;
+
+ // Create blob and trigger download
+ const blob = new Blob([fullMarkdown], { type: 'text/markdown' });
+ const link = document.createElement('a');
+ link.href = URL.createObjectURL(blob);
+ link.download = `research_${researchId}.md`;
+
+ // Trigger download
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+
+ } catch (error) {
+ console.error('Error exporting markdown:', error);
+ alert(`Error exporting markdown: ${error.message}`);
}
}
/**
- * Handle Markdown export
+ * Handle PDF export button click
*/
- async function handleExportMarkdown() {
- if (!researchData || !researchData.content) return;
-
- // Disable button
- if (exportMarkdownBtn) {
- exportMarkdownBtn.disabled = true;
- exportMarkdownBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating Markdown...';
- }
-
+ function handlePdfExport() {
try {
- if (!window.api || !window.api.getMarkdownExport) {
- throw new Error('API service not available');
+ if (!researchData) {
+ throw new Error('No research data available');
}
- // Get raw markdown content
- const response = await window.api.getMarkdownExport(currentResearchId);
+ console.log('PDF export initiated for research ID:', researchId);
- if (!response || !response.content) {
- throw new Error('Failed to get markdown content');
- }
+ // Show loading indicator
+ pdfBtn.disabled = true;
+ pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
- // Create blob and download link
- const blob = new Blob([response.content], { type: 'text/markdown' });
- const url = URL.createObjectURL(blob);
-
- const a = document.createElement('a');
- a.href = url;
- a.download = `${researchData.title || 'research-results'}.md`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- // Show success message
- if (window.ui && window.ui.showMessage) {
- window.ui.showMessage('Markdown file downloaded successfully');
- }
+ // Get metadata from DOM (which should be populated correctly by now)
+ const title = document.getElementById('result-query')?.textContent || `Research ${researchId}`;
+ console.log('Using title for PDF:', title);
- // Reset button state
- if (exportMarkdownBtn) {
- exportMarkdownBtn.disabled = false;
- exportMarkdownBtn.innerHTML = '<i class="fas fa-file-alt"></i> Export as Markdown';
+ // Check if PDF service is available
+ if (window.pdfService && window.pdfService.downloadPdf) {
+ console.log('PDF service available, calling downloadPdf');
+
+ // Add the metadata to the researchData for PDF generation
+ const pdfData = {
+ ...researchData,
+ title: title,
+ query: title,
+ metadata: {
+ title: title,
+ date: document.getElementById('result-date')?.textContent || 'Unknown date',
+ mode: document.getElementById('result-mode')?.textContent || 'Standard'
+ }
+ };
+
+ // Use the PDF service to generate and download the PDF
+ window.pdfService.downloadPdf(pdfData, researchId)
+ .then(() => {
+ console.log('PDF generated successfully');
+ // Reset button
+ pdfBtn.disabled = false;
+ pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';
+ })
+ .catch(error => {
+ console.error('Error generating PDF:', error);
+ alert(`Error generating PDF: ${error.message || 'Unknown error'}`);
+
+ // Reset button
+ pdfBtn.disabled = false;
+ pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';
+ });
+ } else {
+ console.error('PDF service not available');
+ throw new Error('PDF service not available');
}
+
} catch (error) {
- console.error('Error generating Markdown:', error);
- if (window.ui && window.ui.showError) {
- window.ui.showError('Error generating Markdown: ' + error.message);
- }
+ console.error('Error exporting PDF:', error);
+ alert(`Error exporting PDF: ${error.message || 'Unknown error'}`);
- // Reset button state
- if (exportMarkdownBtn) {
- exportMarkdownBtn.disabled = false;
- exportMarkdownBtn.innerHTML = '<i class="fas fa-file-alt"></i> Export as Markdown';
+ // Reset button
+ if (pdfBtn) {
+ pdfBtn.disabled = false;
+ pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';
}
}
}
- // 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 loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeResults);