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.

Fix history page UI and functionality

hashedvikinge2af6c2a273a
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index f0291ee827..6c22ad42c5 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -38,7 +38,8 @@ def init_db():
report_path TEXT,
metadata TEXT,
progress_log TEXT,
- progress INTEGER
+ progress INTEGER,
+ title TEXT
)
"""
)
@@ -73,6 +74,11 @@ def init_db():
if "progress" not in columns:
print("Adding missing 'progress' column to research_history table")
cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")
+
+ # Check if the title column exists, add it if missing
+ if "title" not in columns:
+ print("Adding missing 'title' column to research_history table")
+ cursor.execute("ALTER TABLE research_history ADD COLUMN title TEXT")
# Enable foreign key support
cursor.execute("PRAGMA foreign_keys = ON")
@@ -80,17 +86,53 @@ def init_db():
conn.commit()
conn.close()
-def calculate_duration(created_at_str):
+def calculate_duration(created_at_str, completed_at_str=None):
"""
- Calculate duration in seconds between created_at timestamp and now.
+ Calculate duration in seconds between created_at timestamp and completed_at or now.
Handles various timestamp formats and returns None if calculation fails.
+
+ Args:
+ created_at_str: The start timestamp
+ completed_at_str: Optional end timestamp, defaults to current time if None
+
+ Returns:
+ Duration in seconds or None if calculation fails
"""
if not created_at_str:
return None
- now = datetime.utcnow()
- duration_seconds = None
-
+ end_time = None
+ if completed_at_str:
+ # Use completed_at time if provided
+ try:
+ if "T" in completed_at_str: # ISO format with T separator
+ end_time = datetime.fromisoformat(completed_at_str)
+ else: # Older format without T
+ # Try different formats
+ try:
+ end_time = datetime.strptime(completed_at_str, "%Y-%m-%d %H:%M:%S.%f")
+ except ValueError:
+ try:
+ end_time = datetime.strptime(completed_at_str, "%Y-%m-%d %H:%M:%S")
+ except ValueError:
+ # Last resort fallback
+ end_time = datetime.fromisoformat(
+ completed_at_str.replace(" ", "T")
+ )
+ except Exception as e:
+ print(f"Error parsing completed_at timestamp: {str(e)}")
+ try:
+ from dateutil import parser
+ end_time = parser.parse(completed_at_str)
+ except Exception:
+ print(f"Fallback parsing also failed for completed_at: {completed_at_str}")
+ # Fall back to current time
+ end_time = datetime.utcnow()
+ else:
+ # Use current time if no completed_at provided
+ end_time = datetime.utcnow()
+
+ start_time = None
try:
# Proper parsing of ISO format
if "T" in created_at_str: # ISO format with T separator
@@ -107,22 +149,24 @@ def calculate_duration(created_at_str):
start_time = datetime.fromisoformat(
created_at_str.replace(" ", "T")
)
-
- # Ensure we're comparing UTC times
- duration_seconds = int((now - start_time).total_seconds())
except Exception as e:
- print(f"Error calculating duration: {str(e)}")
+ print(f"Error parsing created_at timestamp: {str(e)}")
# Fallback method if parsing fails
try:
from dateutil import parser
- start_time_fallback = parser.parse(created_at_str)
- duration_seconds = int((now - start_time_fallback).total_seconds())
+ start_time = parser.parse(created_at_str)
except Exception:
- print(
- f"Fallback duration calculation also failed for timestamp: {created_at_str}"
- )
+ print(f"Fallback parsing also failed for created_at: {created_at_str}")
+ return None
- return duration_seconds
+ # Calculate duration if both timestamps are valid
+ if start_time and end_time:
+ try:
+ return int((end_time - start_time).total_seconds())
+ except Exception as e:
+ print(f"Error calculating duration: {str(e)}")
+
+ return None
def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):
"""
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index ce416eb019..a22ae16260 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -3,6 +3,8 @@ import traceback
from datetime import datetime
import json
import os
+import platform
+import subprocess
from importlib import resources as importlib_resources
from flask import Blueprint, render_template, request, jsonify, make_response, redirect, url_for, send_from_directory
@@ -78,27 +80,32 @@ def history_page():
@research_bp.route("/settings", methods=["GET"])
def settings_page():
"""Render the settings page"""
- return render_template("pages/settings.html")
+ return render_template("settings_dashboard.html")
@research_bp.route("/settings/main", methods=["GET"])
def main_config_page():
"""Render the main settings config page"""
- return render_template("pages/settings_main.html")
+ return render_template("main_config.html")
@research_bp.route("/settings/collections", methods=["GET"])
def collections_config_page():
"""Render the collections config page"""
- return render_template("pages/settings_collections.html")
+ return render_template("collections_config.html")
@research_bp.route("/settings/api_keys", methods=["GET"])
def api_keys_config_page():
"""Render the API keys config page"""
- return render_template("pages/settings_api_keys.html")
+ return render_template("api_keys_config.html")
@research_bp.route("/settings/search_engines", methods=["GET"])
def search_engines_config_page():
"""Render the search engines config page"""
- return render_template("pages/settings_search_engines.html")
+ return render_template("search_engines_config.html")
+
+@research_bp.route("/settings/llm", methods=["GET"])
+def llm_config_page():
+ """Render the LLM config page"""
+ return render_template("llm_config.html")
@research_bp.route("/api/start_research", methods=["POST"])
def start_research():
@@ -328,4 +335,183 @@ def delete_research(research_id):
conn.commit()
conn.close()
- return jsonify({"status": "success"})
\ No newline at end of file
+ return jsonify({"status": "success"})
+
+@research_bp.route("/api/clear_history", methods=["POST"])
+def clear_history():
+ """Clear all research history"""
+ try:
+ from ..models.database import get_db_connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Get all research IDs first to clean up files
+ cursor.execute("SELECT id, report_path FROM research_history")
+ research_records = cursor.fetchall()
+
+ # Clean up report files
+ for research_id, report_path in research_records:
+ # Skip active research
+ if research_id in active_research:
+ continue
+
+ # Delete report file if it exists
+ if report_path and os.path.exists(report_path):
+ try:
+ os.remove(report_path)
+ except Exception as e:
+ print(f"Error removing report file: {str(e)}")
+
+ # Delete records from the database, except active research
+ placeholders = ', '.join(['?'] * len(active_research))
+ if active_research:
+ cursor.execute(
+ f"DELETE FROM research_history WHERE id NOT IN ({placeholders})",
+ list(active_research.keys())
+ )
+ else:
+ cursor.execute("DELETE FROM research_history")
+
+ conn.commit()
+ conn.close()
+
+ return jsonify({"status": "success"})
+ except Exception as e:
+ return jsonify({"status": "error", "message": str(e)}), 500
+
+@research_bp.route("/open_file_location", methods=["POST"])
+def open_file_location():
+ """Open a file location in the system file explorer"""
+ data = request.json
+ file_path = data.get("path")
+
+ if not file_path:
+ return jsonify({"status": "error", "message": "Path is required"}), 400
+
+ # Convert to absolute path if needed
+ if not os.path.isabs(file_path):
+ file_path = os.path.abspath(file_path)
+
+ # Check if path exists
+ if not os.path.exists(file_path):
+ return jsonify({"status": "error", "message": "Path does not exist"}), 404
+
+ try:
+ if platform.system() == "Windows":
+ # On Windows, open the folder and select the file
+ if os.path.isfile(file_path):
+ subprocess.run(["explorer", "/select,", file_path], check=True)
+ else:
+ # If it's a directory, just open it
+ subprocess.run(["explorer", file_path], check=True)
+ elif platform.system() == "Darwin": # macOS
+ subprocess.run(["open", file_path], check=True)
+ else: # Linux and others
+ subprocess.run(["xdg-open", os.path.dirname(file_path)], check=True)
+
+ return jsonify({"status": "success"})
+ except Exception as e:
+ return jsonify({"status": "error", "message": str(e)}), 500
+
+@research_bp.route("/api/save_raw_config", methods=["POST"])
+def save_raw_config():
+ """Save raw configuration"""
+ data = request.json
+ raw_config = data.get("raw_config")
+
+ if not raw_config:
+ return jsonify({"success": False, "error": "Raw configuration is required"}), 400
+
+ try:
+ # Get the config file path
+ config_dir = os.path.join(os.path.expanduser("~"), ".local_deep_research")
+ os.makedirs(config_dir, exist_ok=True)
+ config_path = os.path.join(config_dir, "config.toml")
+
+ # Write the configuration to file
+ with open(config_path, "w", encoding="utf-8") as f:
+ f.write(raw_config)
+
+ return jsonify({"success": True})
+ except Exception as e:
+ return jsonify({"success": False, "error": str(e)}), 500
+
+@research_bp.route("/api/history", methods=["GET"])
+def get_history():
+ """Get research history"""
+ try:
+ from ..models.database import get_db_connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Check if title column exists in the database
+ cursor.execute("PRAGMA table_info(research_history)")
+ columns = [column[1] for column in cursor.fetchall()]
+
+ # Build query based on existing columns
+ select_columns = [
+ "id",
+ "query",
+ "mode",
+ "status",
+ "created_at",
+ "completed_at",
+ "report_path"
+ ]
+
+ # Optionally include title if it exists
+ if "title" in columns:
+ select_columns.append("title")
+
+ # Construct query
+ select_query = f"SELECT {', '.join(select_columns)} FROM research_history ORDER BY created_at DESC"
+
+ # Execute query
+ cursor.execute(select_query)
+
+ history_items = []
+ for row in cursor.fetchall():
+ # Extract values
+ row_data = dict(zip(select_columns, row))
+ research_id = row_data["id"]
+ query = row_data["query"]
+ mode = row_data["mode"]
+ status = row_data["status"]
+ created_at = row_data["created_at"]
+ completed_at = row_data["completed_at"]
+ report_path = row_data["report_path"]
+ title = row_data.get("title", None) # Use get to handle title not being present
+
+ # Calculate duration if completed
+ duration_seconds = None
+ if completed_at and created_at:
+ try:
+ duration_seconds = calculate_duration(created_at, completed_at)
+ except Exception as e:
+ print(f"Error calculating duration: {e}")
+
+ # Create a history item
+ item = {
+ "id": research_id,
+ "query": query,
+ "mode": mode,
+ "status": status,
+ "created_at": created_at,
+ "completed_at": completed_at,
+ "duration_seconds": duration_seconds,
+ "report_path": report_path
+ }
+
+ # Add title if not None
+ if title is not None:
+ item["title"] = title
+
+ history_items.append(item)
+
+ conn.close()
+ return jsonify({"status": "success", "items": history_items})
+ except Exception as e:
+ import traceback
+ print(f"Error getting history: {e}")
+ print(traceback.format_exc())
+ return jsonify({"status": "error", "message": str(e)}), 500
\ No newline at end of file
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 76aa71768f..5399a44a48 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -13,6 +13,123 @@
let historyItems = [];
let filteredItems = [];
+ // Fallback UI utilities in case main UI utils aren't loaded
+ const uiUtils = {
+ showSpinner: function(container, message) {
+ if (window.ui && window.ui.showSpinner) {
+ return window.ui.showSpinner(container, message);
+ }
+
+ // Fallback implementation
+ if (!container) container = document.body;
+ const spinnerHtml = `
+ <div class="loading-spinner centered">
+ <div class="spinner"></div>
+ ${message ? `<div class="spinner-message">${message}</div>` : ''}
+ </div>
+ `;
+ container.innerHTML = spinnerHtml;
+ },
+
+ hideSpinner: function(container) {
+ if (window.ui && window.ui.hideSpinner) {
+ return window.ui.hideSpinner(container);
+ }
+
+ // Fallback implementation
+ if (!container) container = document.body;
+ const spinner = container.querySelector('.loading-spinner');
+ if (spinner) {
+ spinner.remove();
+ }
+ },
+
+ showError: function(message) {
+ if (window.ui && window.ui.showError) {
+ return window.ui.showError(message);
+ }
+
+ // Fallback implementation
+ console.error(message);
+ alert(message);
+ },
+
+ showMessage: function(message) {
+ if (window.ui && window.ui.showMessage) {
+ return window.ui.showMessage(message);
+ }
+
+ // Fallback implementation
+ console.log(message);
+ alert(message);
+ }
+ };
+
+ // Fallback API utilities
+ const apiUtils = {
+ getResearchHistory: async function() {
+ if (window.api && window.api.getResearchHistory) {
+ return window.api.getResearchHistory();
+ }
+
+ // Fallback implementation
+ try {
+ const response = await fetch('/research/api/history');
+ if (!response.ok) {
+ throw new Error(`API Error: ${response.status} ${response.statusText}`);
+ }
+ return await response.json();
+ } catch (error) {
+ console.error('API Error:', error);
+ throw error;
+ }
+ },
+
+ deleteResearch: async function(researchId) {
+ if (window.api && window.api.deleteResearch) {
+ return window.api.deleteResearch(researchId);
+ }
+
+ // Fallback implementation
+ try {
+ const response = await fetch(`/research/api/research/${researchId}/delete`, {
+ method: 'DELETE'
+ });
+ if (!response.ok) {
+ throw new Error(`API Error: ${response.status} ${response.statusText}`);
+ }
+ return await response.json();
+ } catch (error) {
+ console.error('API Error:', error);
+ throw error;
+ }
+ },
+
+ clearResearchHistory: async function() {
+ if (window.api && window.api.clearResearchHistory) {
+ return window.api.clearResearchHistory();
+ }
+
+ // Fallback implementation
+ try {
+ const response = await fetch('/research/api/clear_history', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({})
+ });
+ if (!response.ok) {
+ throw new Error(`API Error: ${response.status} ${response.statusText}`);
+ }
+ return await response.json();
+ } catch (error) {
+ console.error('API Error:', error);
+ throw error;
+ }
+ }
+ };
+
/**
* Initialize the history component
*/
@@ -68,11 +185,11 @@
*/
async function loadHistoryData() {
// Show loading state
- window.ui.showSpinner(historyContainer, 'Loading research history...');
+ uiUtils.showSpinner(historyContainer, 'Loading research history...');
try {
// Get history items
- const response = await window.api.getResearchHistory();
+ const response = await apiUtils.getResearchHistory();
if (response && Array.isArray(response.items)) {
historyItems = response.items;
@@ -85,8 +202,8 @@
}
} catch (error) {
console.error('Error loading history:', error);
- window.ui.hideSpinner(historyContainer);
- window.ui.showError('Error loading history: ' + error.message);
+ uiUtils.hideSpinner(historyContainer);
+ uiUtils.showError('Error loading history: ' + error.message);
}
}
@@ -95,7 +212,7 @@
*/
function renderHistoryItems() {
// Hide spinner
- window.ui.hideSpinner(historyContainer);
+ uiUtils.hideSpinner(historyContainer);
// Clear container
historyContainer.innerHTML = '';
@@ -137,6 +254,59 @@
});
}
+ /**
+ * Format date safely using the formatter if available
+ */
+ function formatDate(dateStr) {
+ if (window.formatting && window.formatting.formatDate) {
+ return window.formatting.formatDate(dateStr);
+ }
+
+ // Simple fallback date formatting
+ try {
+ const date = new Date(dateStr);
+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
+ } catch (e) {
+ return dateStr;
+ }
+ }
+
+ /**
+ * Format status safely using the formatter if available
+ */
+ function formatStatus(status) {
+ if (window.formatting && window.formatting.formatStatus) {
+ return window.formatting.formatStatus(status);
+ }
+
+ // Simple fallback formatting
+ const statusMap = {
+ 'in_progress': 'In Progress',
+ 'completed': 'Completed',
+ 'failed': 'Failed',
+ 'suspended': 'Suspended'
+ };
+
+ return statusMap[status] || status;
+ }
+
+ /**
+ * Format mode safely using the formatter if available
+ */
+ function formatMode(mode) {
+ if (window.formatting && window.formatting.formatMode) {
+ return window.formatting.formatMode(mode);
+ }
+
+ // Simple fallback formatting
+ const modeMap = {
+ 'quick': 'Quick Summary',
+ 'detailed': 'Detailed Report'
+ };
+
+ return modeMap[mode] || mode;
+ }
+
/**
* Create a history item element
* @param {Object} item - The history item data
@@ -147,49 +317,69 @@
itemEl.className = 'history-item';
itemEl.dataset.id = item.id;
- // Status class
- if (item.status) {
- itemEl.classList.add(`status-${item.status}`);
- }
+ // Status class - use the CSS classes from styles.css
+ const statusClass = item.status ? item.status.replace('_', '-') : '';
+ itemEl.classList.add(`status-${statusClass}`);
// Format date
- const formattedDate = window.formatting.formatDate(item.created_at);
-
- // Create result link if completed
- const resultLink = item.status === 'completed'
- ? `<a href="/research/results/${item.id}" class="view-results-btn">
- <i class="fas fa-eye"></i> View Results
- </a>`
- : '';
-
- // Create status badge
- const statusBadge = `<span class="status-badge status-${item.status}">
- ${window.formatting.formatStatus(item.status)}
- </span>`;
+ const formattedDate = formatDate(item.created_at);
+
+ // Get a display title (use query if title is not available)
+ const displayTitle = item.title || formatTitleFromQuery(item.query);
- // Set item content
+ // Create the HTML content
itemEl.innerHTML = `
- <div class="item-header">
- <h3 class="item-title">${item.title || 'Untitled Research'}</h3>
- ${statusBadge}
+ <div class="history-item-header">
+ <div class="history-item-title">${displayTitle}</div>
+ <div class="history-item-status status-${statusClass}">${formatStatus(item.status)}</div>
</div>
- <div class="item-query">${item.query || ''}</div>
- <div class="item-metadata">
- <span><i class="far fa-clock"></i> ${formattedDate}</span>
- <span><i class="fas fa-tag"></i> ${window.formatting.formatMode(item.mode)}</span>
- ${item.duration_seconds ? `<span><i class="fas fa-hourglass-end"></i> ${Math.floor(item.duration_seconds / 60)}m ${item.duration_seconds % 60}s</span>` : ''}
+ <div class="history-item-meta">
+ <div class="history-item-date"><i class="far fa-clock"></i> ${formattedDate}</div>
+ <div class="history-item-mode"><i class="fas fa-tag"></i> ${formatMode(item.mode)}</div>
+ ${item.duration_seconds ? `<div><i class="fas fa-hourglass-end"></i> ${Math.floor(item.duration_seconds / 60)}m ${item.duration_seconds % 60}s</div>` : ''}
</div>
- <div class="item-actions">
- ${resultLink}
- <button class="delete-item-btn" aria-label="Delete research">
+ <div class="history-item-actions">
+ ${item.status === 'completed' ?
+ `<button class="btn btn-sm btn-outline view-btn">
+ <i class="fas fa-eye"></i> View
+ </button>
+ <button class="btn btn-sm btn-outline pdf-btn" style="display: none;">
+ <i class="fas fa-file-pdf"></i> PDF
+ </button>` : ''}
+ <button class="btn btn-sm delete-btn delete-item-btn">
<i class="fas fa-trash-alt"></i>
</button>
</div>
`;
+ // Add event listener for the view button
+ const viewBtn = itemEl.querySelector('.view-btn');
+ if (viewBtn) {
+ viewBtn.addEventListener('click', () => {
+ window.location.href = `/research/results/${item.id}`;
+ });
+ }
+
return itemEl;
}
+ /**
+ * Format a title from a query string
+ * Truncates long queries and adds ellipsis
+ * @param {string} query - The query string
+ * @returns {string} Formatted title
+ */
+ function formatTitleFromQuery(query) {
+ if (!query) return 'Untitled Research';
+
+ // Truncate long queries
+ if (query.length > 60) {
+ return query.substring(0, 57) + '...';
+ }
+
+ return query;
+ }
+
/**
* Handle search input
*/
@@ -202,10 +392,17 @@
} else {
// Filter items based on search term
filteredItems = historyItems.filter(item => {
- return (
- (item.title && item.title.toLowerCase().includes(searchTerm)) ||
- (item.query && item.query.toLowerCase().includes(searchTerm))
- );
+ // Search in title if available, otherwise in query
+ const titleMatch = item.title ?
+ item.title.toLowerCase().includes(searchTerm) :
+ false;
+
+ // Always search in query
+ const queryMatch = item.query ?
+ item.query.toLowerCase().includes(searchTerm) :
+ false;
+
+ return titleMatch || queryMatch;
});
}
@@ -224,20 +421,20 @@
try {
// Delete item via API
- await window.api.deleteResearch(itemId);
+ await apiUtils.deleteResearch(itemId);
// Remove from arrays
historyItems = historyItems.filter(item => item.id != itemId);
filteredItems = filteredItems.filter(item => item.id != itemId);
// Show success message
- window.ui.showMessage('Research deleted successfully');
+ uiUtils.showMessage('Research deleted successfully');
// Re-render history items
renderHistoryItems();
} catch (error) {
console.error('Error deleting research:', error);
- window.ui.showError('Error deleting research: ' + error.message);
+ uiUtils.showError('Error deleting research: ' + error.message);
}
}
@@ -251,20 +448,20 @@
try {
// Clear history via API
- await window.api.clearResearchHistory();
+ await apiUtils.clearResearchHistory();
// Clear arrays
historyItems = [];
filteredItems = [];
// Show success message
- window.ui.showMessage('Research history cleared successfully');
+ uiUtils.showMessage('Research history cleared successfully');
// Re-render history items
renderHistoryItems();
} catch (error) {
console.error('Error clearing history:', error);
- window.ui.showError('Error clearing history: ' + error.message);
+ uiUtils.showError('Error clearing history: ' + error.message);
}
}
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
new file mode 100644
index 0000000000..757deeb99b
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -0,0 +1,170 @@
+/**
+ * Settings component for managing application settings
+ */
+(function() {
+ 'use strict';
+
+ // DOM elements
+ const settingsForm = document.querySelector('form');
+ const rawConfigToggle = document.getElementById('toggle-raw-config');
+ const rawConfigSection = document.getElementById('raw-config');
+ const rawConfigEditor = document.getElementById('raw-config-editor-container');
+ const rawConfigTextarea = document.getElementById('raw_config_editor');
+
+ // Range input elements that need live value display
+ const rangeInputs = document.querySelectorAll('input[type="range"]');
+
+ /**
+ * Initialize the settings component
+ */
+ function initializeSettings() {
+ // Set up event listeners
+ if (settingsForm) {
+ settingsForm.addEventListener('submit', handleSettingsSubmit);
+ }
+
+ // Initialize range inputs to display their values
+ rangeInputs.forEach(input => {
+ const valueDisplay = document.getElementById(`${input.id}-value`);
+ if (valueDisplay) {
+ // Update on input change
+ input.addEventListener('input', () => {
+ valueDisplay.textContent = input.value;
+ });
+ }
+ });
+
+ // Add click handler for the logo to navigate home
+ const logoLink = document.getElementById('logo-link');
+ if (logoLink) {
+ logoLink.addEventListener('click', () => {
+ window.location.href = '/research/';
+ });
+ }
+ }
+
+ /**
+ * Handle settings form submission
+ * @param {Event} e - The submit event
+ */
+ function handleSettingsSubmit(e) {
+ e.preventDefault();
+
+ // Show loading state
+ window.ui.showSpinner();
+
+ // Get form data
+ const formData = new FormData(settingsForm);
+ const data = {};
+
+ // Convert form data to JSON object
+ for (const [key, value] of formData.entries()) {
+ // Handle checkboxes separately (they're only included when checked)
+ if (settingsForm.elements[key].type === 'checkbox') {
+ data[key] = settingsForm.elements[key].checked;
+ } else {
+ data[key] = value;
+ }
+ }
+
+ // Determine which settings form is being submitted based on form ID
+ let endpoint = '/research/api/save_main_config';
+
+ if (settingsForm.id === 'search-engines-form') {
+ endpoint = '/research/api/save_search_engines_config';
+ } else if (settingsForm.id === 'collections-form') {
+ endpoint = '/research/api/save_collections_config';
+ } else if (settingsForm.id === 'api-keys-form') {
+ endpoint = '/research/api/save_api_keys_config';
+ } else if (settingsForm.id === 'llm-config-form') {
+ endpoint = '/research/api/save_llm_config';
+ }
+
+ // Save the settings
+ window.api.postJSON(endpoint, data)
+ .then(response => {
+ if (response.success) {
+ window.ui.showNotification('Settings saved successfully');
+ } else {
+ window.ui.showErrorMessage('Failed to save settings: ' + (response.error || 'Unknown error'));
+ }
+ })
+ .catch(error => {
+ window.ui.showErrorMessage('Error saving settings: ' + error.message);
+ })
+ .finally(() => {
+ window.ui.hideSpinner();
+ });
+ }
+
+ /**
+ * Toggle the display of raw configuration
+ */
+ function toggleRawConfig() {
+ if (rawConfigSection && rawConfigEditor) {
+ const isVisible = rawConfigSection.style.display !== 'none';
+
+ rawConfigSection.style.display = isVisible ? 'none' : 'block';
+ rawConfigEditor.style.display = isVisible ? 'none' : 'block';
+
+ if (rawConfigToggle) {
+ const toggleText = document.getElementById('toggle-text');
+ if (toggleText) {
+ toggleText.textContent = isVisible ? 'Show Raw Configuration' : 'Hide Raw Configuration';
+ }
+ }
+ }
+ }
+
+ /**
+ * Save raw configuration
+ */
+ function saveRawConfig() {
+ if (rawConfigTextarea) {
+ const rawConfig = rawConfigTextarea.value;
+
+ window.ui.showSpinner();
+
+ window.api.saveRawConfig(rawConfig)
+ .then(data => {
+ if (data.success) {
+ window.ui.showNotification('Configuration saved successfully');
+ // Reload the page to show updated values
+ window.location.reload();
+ } else {
+ window.ui.showErrorMessage('Error saving configuration: ' + (data.error || 'Unknown error'));
+ }
+ })
+ .catch(error => {
+ window.ui.showErrorMessage('Error saving configuration: ' + error.message);
+ })
+ .finally(() => {
+ window.ui.hideSpinner();
+ });
+ }
+ }
+
+ /**
+ * Cancel raw configuration editing
+ */
+ function cancelRawEdit() {
+ if (rawConfigSection && rawConfigEditor && rawConfigToggle) {
+ rawConfigSection.style.display = 'none';
+ rawConfigEditor.style.display = 'none';
+
+ const toggleText = document.getElementById('toggle-text');
+ if (toggleText) {
+ toggleText.textContent = 'Show Raw Configuration';
+ }
+ }
+ }
+
+ // Initialize when the DOM is ready
+ document.addEventListener('DOMContentLoaded', initializeSettings);
+
+ // Expose functions to the global scope if they need to be called from HTML
+ window.toggleRawConfig = toggleRawConfig;
+ window.saveRawConfig = saveRawConfig;
+ window.cancelRawEdit = cancelRawEdit;
+
+})();
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/main.js b/src/local_deep_research/web/static/js/main.js
index 5ca0de6ec2..b339236c6c 100644
--- a/src/local_deep_research/web/static/js/main.js
+++ b/src/local_deep_research/web/static/js/main.js
@@ -9,7 +9,8 @@
'page-progress': ['progress.js'],
'page-results': ['results.js'],
'page-detail': ['detail.js'],
- 'page-history': ['history.js']
+ 'page-history': ['history.js'],
+ 'page-settings': ['settings.js']
};
// Core services to always load
@@ -41,7 +42,8 @@
console.log('Current page detected:', currentPage);
// Load core services
- loadScripts('services', coreServices);
+ loadScripts('utils', coreServices.filter(s => s.includes('formatting') || s.includes('ui')));
+ loadScripts('services', coreServices.filter(s => s.includes('api') || s.includes('socket')));
// Load optional services for this page
if (optionalServices[currentPage]) {
@@ -73,7 +75,7 @@
// Check URL patterns as fallback
const path = window.location.pathname;
- if (path === '/' || path === '/index' || path === '/home') {
+ if (path === '/' || path === '/index' || path === '/home' || path === '/research/') {
return 'page-home';
} else if (path.includes('/research/progress')) {
return 'page-progress';
@@ -83,6 +85,8 @@
return 'page-detail';
} else if (path.includes('/research/history')) {
return 'page-history';
+ } else if (path.includes('/research/settings')) {
+ return 'page-settings';
}
return null;
@@ -98,7 +102,7 @@
scripts.forEach(script => {
const scriptElement = document.createElement('script');
- scriptElement.src = `/static/js/${folder}/${script}`;
+ scriptElement.src = `/research/static/js/${folder}/${script}`;
scriptElement.async = false; // Load in sequence
document.body.appendChild(scriptElement);
});
diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.js
index acd32121eb..0f81aef882 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -3,8 +3,10 @@
* Handles all communication with the server API endpoints
*/
-// Base URL for API
-const API_BASE_URL = '/api';
+// Base URL for API - use existing one if already declared
+if (typeof API_BASE_URL === 'undefined') {
+ const API_BASE_URL = '/research/api';
+}
/**
* Get the full URL for an API endpoint
@@ -45,6 +47,19 @@ async function fetchWithErrorHandling(url, options = {}) {
}
}
+/**
+ * Helper method to perform POST requests with JSON data
+ * @param {string} path - API path
+ * @param {Object} data - JSON data to send
+ * @returns {Promise<any>} Response data
+ */
+async function postJSON(path, data) {
+ return fetchWithErrorHandling(path, {
+ method: 'POST',
+ body: JSON.stringify(data)
+ });
+}
+
/**
* Start a new research
* @param {string} query - The research query
@@ -52,10 +67,7 @@ async function fetchWithErrorHandling(url, options = {}) {
* @returns {Promise<Object>} The research response with ID
*/
async function startResearch(query, mode) {
- return fetchWithErrorHandling(getApiUrl('research/api/start_research'), {
- method: 'POST',
- body: JSON.stringify({ query, mode })
- });
+ return postJSON('/research/api/start_research', { query, mode });
}
/**
@@ -64,7 +76,7 @@ async function startResearch(query, mode) {
* @returns {Promise<Object>} The research status
*/
async function getResearchStatus(researchId) {
- return fetchWithErrorHandling(getApiUrl(`research/${researchId}`));
+ return fetchWithErrorHandling(`/research/api/research/${researchId}`);
}
/**
@@ -73,7 +85,7 @@ async function getResearchStatus(researchId) {
* @returns {Promise<Object>} The research details
*/
async function getResearchDetails(researchId) {
- return fetchWithErrorHandling(getApiUrl(`research/${researchId}/details`));
+ return fetchWithErrorHandling(`/research/api/research/${researchId}/details`);
}
/**
@@ -82,7 +94,7 @@ async function getResearchDetails(researchId) {
* @returns {Promise<Object>} The research logs
*/
async function getResearchLogs(researchId) {
- return fetchWithErrorHandling(getApiUrl(`research/${researchId}/logs`));
+ return fetchWithErrorHandling(`/research/api/research/${researchId}/logs`);
}
/**
@@ -90,7 +102,7 @@ async function getResearchLogs(researchId) {
* @returns {Promise<Array>} The research history
*/
async function getResearchHistory() {
- return fetchWithErrorHandling(getApiUrl('history'));
+ return fetchWithErrorHandling('/research/api/history');
}
/**
@@ -99,7 +111,7 @@ async function getResearchHistory() {
* @returns {Promise<Object>} The research report
*/
async function getReport(researchId) {
- return fetchWithErrorHandling(getApiUrl(`report/${researchId}`));
+ return fetchWithErrorHandling(`/research/api/report/${researchId}`);
}
/**
@@ -108,9 +120,7 @@ async function getReport(researchId) {
* @returns {Promise<Object>} The termination response
*/
async function terminateResearch(researchId) {
- return fetchWithErrorHandling(getApiUrl(`research/${researchId}/terminate`), {
- method: 'POST'
- });
+ return postJSON(`/research/api/research/${researchId}/terminate`, {});
}
/**
@@ -119,11 +129,82 @@ async function terminateResearch(researchId) {
* @returns {Promise<Object>} The deletion response
*/
async function deleteResearch(researchId) {
- return fetchWithErrorHandling(getApiUrl(`research/${researchId}/delete`), {
+ return fetchWithErrorHandling(`/research/api/research/${researchId}/delete`, {
method: 'DELETE'
});
}
+/**
+ * Clear all research history
+ * @returns {Promise<Object>} The response
+ */
+async function clearResearchHistory() {
+ return postJSON('/research/api/clear_history', {});
+}
+
+/**
+ * Open a file location in the system file explorer
+ * @param {string} path - Path to open
+ * @returns {Promise<Object>} The response
+ */
+async function openFileLocation(path) {
+ return postJSON('/research/open_file_location', { path });
+}
+
+/**
+ * Save raw configuration
+ * @param {string} rawConfig - Raw configuration text
+ * @returns {Promise<Object>} The response
+ */
+async function saveRawConfig(rawConfig) {
+ return postJSON('/research/api/save_raw_config', { raw_config: rawConfig });
+}
+
+/**
+ * Save main configuration
+ * @param {Object} config - Configuration object
+ * @returns {Promise<Object>} The response
+ */
+async function saveMainConfig(config) {
+ return postJSON('/research/api/save_main_config', config);
+}
+
+/**
+ * Save search engines configuration
+ * @param {Object} config - Configuration object
+ * @returns {Promise<Object>} The response
+ */
+async function saveSearchEnginesConfig(config) {
+ return postJSON('/research/api/save_search_engines_config', config);
+}
+
+/**
+ * Save collections configuration
+ * @param {Object} config - Configuration object
+ * @returns {Promise<Object>} The response
+ */
+async function saveCollectionsConfig(config) {
+ return postJSON('/research/api/save_collections_config', config);
+}
+
+/**
+ * Save API keys configuration
+ * @param {Object} config - Configuration object
+ * @returns {Promise<Object>} The response
+ */
+async function saveApiKeysConfig(config) {
+ return postJSON('/research/api/save_api_keys_config', config);
+}
+
+/**
+ * Save LLM configuration
+ * @param {Object} config - Configuration object
+ * @returns {Promise<Object>} The response
+ */
+async function saveLlmConfig(config) {
+ return postJSON('/research/api/save_llm_config', config);
+}
+
// Export the API functions
window.api = {
startResearch,
@@ -134,5 +215,14 @@ window.api = {
getReport,
terminateResearch,
deleteResearch,
+ clearResearchHistory,
+ openFileLocation,
+ saveRawConfig,
+ saveMainConfig,
+ saveSearchEnginesConfig,
+ saveCollectionsConfig,
+ saveApiKeysConfig,
+ saveLlmConfig,
+ postJSON,
getApiUrl
};
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/utils/formatting.js b/src/local_deep_research/web/static/js/utils/formatting.js
index 7f27fea49f..25a720409d 100644
--- a/src/local_deep_research/web/static/js/utils/formatting.js
+++ b/src/local_deep_research/web/static/js/utils/formatting.js
@@ -70,6 +70,24 @@ function formatDate(date, duration = null) {
}
}
+/**
+ * Format a duration in seconds to a readable string
+ * @param {number} seconds - Duration in seconds
+ * @returns {string} Formatted duration string
+ */
+function formatDuration(seconds) {
+ if (!seconds || isNaN(seconds)) return 'Unknown';
+
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = Math.floor(seconds % 60);
+
+ if (minutes === 0) {
+ return `${remainingSeconds}s`;
+ } else {
+ return `${minutes}m ${remainingSeconds}s`;
+ }
+}
+
/**
* Capitalize the first letter of a string
* @param {string} string - The string to capitalize
@@ -80,8 +98,22 @@ function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
+/**
+ * Format a number with thousands separators
+ * @param {number} num - The number to format
+ * @returns {string} Formatted number
+ */
+function formatNumber(num) {
+ if (num === null || num === undefined) return '0';
+ return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
+}
+
// Export the functions to make them available to other modules
-window.formatStatus = formatStatus;
-window.formatMode = formatMode;
-window.formatDate = formatDate;
-window.capitalizeFirstLetter = capitalizeFirstLetter;
\ No newline at end of file
+window.formatting = {
+ formatStatus,
+ formatMode,
+ formatDate,
+ formatDuration,
+ formatNumber,
+ capitalizeFirstLetter
+};
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/utils/ui.js b/src/local_deep_research/web/static/js/utils/ui.js
index 74007e5098..0e831e015d 100644
--- a/src/local_deep_research/web/static/js/utils/ui.js
+++ b/src/local_deep_research/web/static/js/utils/ui.js
@@ -4,13 +4,13 @@
/**
* Update a progress bar UI element
- * @param {string} fillElementId - The ID of the element to fill
- * @param {string} percentageElementId - The ID of the element to show percentage
+ * @param {string|Element} fillElementId - The ID or element to fill
+ * @param {string|Element} percentageElementId - The ID or element to show percentage
* @param {number} percentage - The percentage to set
*/
function updateProgressBar(fillElementId, percentageElementId, percentage) {
- const progressFill = document.getElementById(fillElementId);
- const progressPercentage = document.getElementById(percentageElementId);
+ const progressFill = typeof fillElementId === 'string' ? document.getElementById(fillElementId) : fillElementId;
+ const progressPercentage = typeof percentageElementId === 'string' ? document.getElementById(percentageElementId) : percentageElementId;
if (progressFill && progressPercentage) {
// Convert any value to a percentage between 0-100
@@ -33,13 +33,14 @@ function updateProgressBar(fillElementId, percentageElementId, percentage) {
/**
* Show a loading spinner
- * @param {string} containerId - The ID of the container to add the spinner to
+ * @param {string|Element} container - The container ID or element to add the spinner to
* @param {string} message - Optional message to show with the spinner
*/
-function showSpinner(containerId, message = 'Loading...') {
- const container = document.getElementById(containerId);
- if (container) {
- container.innerHTML = '';
+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">
@@ -48,18 +49,19 @@ function showSpinner(containerId, message = 'Loading...') {
</div>
`;
- container.innerHTML = spinnerHTML;
+ containerEl.innerHTML = spinnerHTML;
}
}
/**
* Hide a loading spinner
- * @param {string} containerId - The ID of the container with the spinner
+ * @param {string|Element} container - The container ID or element with the spinner
*/
-function hideSpinner(containerId) {
- const container = document.getElementById(containerId);
- if (container) {
- const spinner = container.querySelector('.loading-spinner');
+function hideSpinner(container) {
+ const containerEl = typeof container === 'string' ? document.getElementById(container) : container;
+
+ if (containerEl) {
+ const spinner = containerEl.querySelector('.loading-spinner');
if (spinner) {
spinner.remove();
}
@@ -68,12 +70,13 @@ function hideSpinner(containerId) {
/**
* Show an error message
- * @param {string} containerId - The ID of the container to add the error to
+ * @param {string|Element} container - The container ID or element to add the error to
* @param {string} message - The error message
*/
-function showError(containerId, message) {
- const container = document.getElementById(containerId);
- if (container) {
+function showError(container, message) {
+ const containerEl = typeof container === 'string' ? document.getElementById(container) : container;
+
+ if (containerEl) {
const errorHTML = `
<div class="error-message">
<i class="fas fa-exclamation-circle"></i>
@@ -81,24 +84,88 @@ function showError(containerId, message) {
</div>
`;
- container.innerHTML = errorHTML;
+ containerEl.innerHTML = errorHTML;
}
}
+/**
+ * Show a notification message
+ * @param {string} message - The message to display
+ * @param {string} type - Message type: 'success', 'error', 'info', 'warning'
+ * @param {number} duration - How long to show the message in ms
+ */
+function showMessage(message, type = 'success', duration = 3000) {
+ // Check if the toast container exists
+ let toastContainer = document.getElementById('toast-container');
+
+ // Create it if it doesn't exist
+ if (!toastContainer) {
+ toastContainer = document.createElement('div');
+ toastContainer.id = 'toast-container';
+ document.body.appendChild(toastContainer);
+ }
+
+ // Create a new toast
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ // Add icon based on type
+ let icon = '';
+ switch (type) {
+ case 'success':
+ icon = '<i class="fas fa-check-circle"></i>';
+ break;
+ case 'error':
+ icon = '<i class="fas fa-exclamation-circle"></i>';
+ break;
+ case 'info':
+ icon = '<i class="fas fa-info-circle"></i>';
+ break;
+ case 'warning':
+ icon = '<i class="fas fa-exclamation-triangle"></i>';
+ break;
+ }
+
+ // Set the content
+ toast.innerHTML = `
+ ${icon}
+ <div class="toast-message">${message}</div>
+ `;
+
+ // Add to container
+ toastContainer.appendChild(toast);
+
+ // Show with animation
+ setTimeout(() => {
+ toast.classList.add('visible');
+ }, 10);
+
+ // Remove after duration
+ setTimeout(() => {
+ toast.classList.remove('visible');
+
+ // Remove from DOM after animation
+ setTimeout(() => {
+ toast.remove();
+ }, 300);
+ }, duration);
+}
+
/**
* Format and render Markdown content
- * @param {string} containerId - The ID of the container to render markdown into
+ * @param {string|Element} container - The container ID or element to render markdown into
* @param {string} markdown - The markdown content
*/
-function renderMarkdown(containerId, markdown) {
- const container = document.getElementById(containerId);
- if (container && window.marked) {
+function renderMarkdown(container, markdown) {
+ const containerEl = typeof container === 'string' ? document.getElementById(container) : container;
+
+ if (containerEl && window.marked) {
// Add a wrapper for proper styling
- container.innerHTML = `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;
+ containerEl.innerHTML = `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;
// Highlight code blocks if highlight.js is available
if (window.hljs) {
- container.querySelectorAll('pre code').forEach((block) => {
+ containerEl.querySelectorAll('pre code').forEach((block) => {
window.hljs.highlightBlock(block);
});
}
@@ -144,10 +211,94 @@ function createDynamicFavicon(emoji = '⚡') {
link.href = dataUrl;
}
-// Export the functions to make them available to other modules
-window.updateProgressBar = updateProgressBar;
-window.showSpinner = showSpinner;
-window.hideSpinner = hideSpinner;
-window.showError = showError;
-window.renderMarkdown = renderMarkdown;
-window.createDynamicFavicon = createDynamicFavicon;
\ No newline at end of file
+// Add CSS for toast messages
+function addToastStyles() {
+ if (document.getElementById('toast-styles')) return;
+
+ const styleEl = document.createElement('style');
+ styleEl.id = 'toast-styles';
+ styleEl.textContent = `
+ #toast-container {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ z-index: 9999;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+
+ .toast {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ background-color: var(--card-bg, #2a2a2a);
+ color: var(--text-color, #fff);
+ padding: 12px 16px;
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+ max-width: 350px;
+ transform: translateX(120%);
+ opacity: 0;
+ transition: transform 0.3s ease, opacity 0.3s ease;
+ border-left: 4px solid transparent;
+ }
+
+ .toast.visible {
+ transform: translateX(0);
+ opacity: 1;
+ }
+
+ .toast i {
+ font-size: 1.2rem;
+ }
+
+ .toast-success {
+ border-left-color: var(--success-color, #28a745);
+ }
+
+ .toast-success i {
+ color: var(--success-color, #28a745);
+ }
+
+ .toast-error {
+ border-left-color: var(--danger-color, #dc3545);
+ }
+
+ .toast-error i {
+ color: var(--danger-color, #dc3545);
+ }
+
+ .toast-info {
+ border-left-color: var(--info-color, #17a2b8);
+ }
+
+ .toast-info i {
+ color: var(--info-color, #17a2b8);
+ }
+
+ .toast-warning {
+ border-left-color: var(--warning-color, #ffc107);
+ }
+
+ .toast-warning i {
+ color: var(--warning-color, #ffc107);
+ }
+ `;
+
+ document.head.appendChild(styleEl);
+}
+
+// Add toast styles when the script loads
+addToastStyles();
+
+// Export the UI functions
+window.ui = {
+ updateProgressBar,
+ showSpinner,
+ hideSpinner,
+ showError,
+ showMessage,
+ renderMarkdown,
+ createDynamicFavicon
+};
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/components/mobile_nav.html b/src/local_deep_research/web/templates/components/mobile_nav.html
index 1f219f3abd..3a6f236fde 100644
--- a/src/local_deep_research/web/templates/components/mobile_nav.html
+++ b/src/local_deep_research/web/templates/components/mobile_nav.html
@@ -1,12 +1,16 @@
<nav class="mobile-tab-bar">
<ul>
<li {% if active_page == 'new-research' %}class="active"{% endif %} data-page="new-research">
- <i class="fas fa-search"></i>
- <span>Research</span>
+ <a href="{{ url_for('research.index') }}">
+ <i class="fas fa-search"></i>
+ <span>Research</span>
+ </a>
</li>
<li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">
- <i class="fas fa-history"></i>
- <span>History</span>
+ <a href="{{ url_for('research.history_page') }}">
+ <i class="fas fa-history"></i>
+ <span>History</span>
+ </a>
</li>
<li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">
<a href="{{ url_for('research.settings_page') }}">
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index 690fb06517..f294d7ecda 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -5,13 +5,13 @@
<nav class="sidebar-nav">
<ul>
<li {% if active_page == 'new-research' %}class="active"{% endif %} data-page="new-research">
- <i class="fas fa-search"></i> New Research
+ <a href="{{ url_for('research.index') }}"><i class="fas fa-search"></i> New Research</a>
</li>
<li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">
- <i class="fas fa-history"></i> History
+ <a href="{{ url_for('research.history_page') }}"><i class="fas fa-history"></i> History</a>
</li>
<li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">
- <i class="fas fa-cog"></i> <a href="{{ url_for('research.settings_page') }}">Settings</a>
+ <a href="{{ url_for('research.settings_page') }}"><i class="fas fa-cog"></i> Settings</a>
</li>
</ul>
</nav>
diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.html
index bdd23a2524..b223fbb104 100644
--- a/src/local_deep_research/web/templates/pages/history.html
+++ b/src/local_deep_research/web/templates/pages/history.html
@@ -4,44 +4,48 @@
{% block title %}Research History - Deep Research System{% endblock %}
+{% block styles %}
+{{ super() }}
+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/components/history.css') }}">
+{% endblock %}
+
{% block content %}
<div class="page active" id="history">
<div class="page-header">
<h1>Research History</h1>
+ <div class="search-controls">
+ <input type="text" id="history-search" placeholder="Search history..." class="search-input">
+ <button id="clear-history-btn" class="btn btn-danger" style="display: none;">
+ <i class="fas fa-trash-alt"></i> Clear All
+ </button>
+ </div>
</div>
<div class="card">
<div class="card-content">
- <div class="history-list" id="history-list">
+ <div id="history-items" class="history-list">
<!-- Will be populated dynamically -->
<div class="loading-spinner centered">
<div class="spinner"></div>
</div>
</div>
+ <div id="history-empty-message" class="empty-state" style="display: none;">
+ <i class="fas fa-history empty-icon"></i>
+ <p>No research history found.</p>
+ </div>
</div>
</div>
</div>
{% endblock %}
{% block templates %}
-<template id="history-item-template">
- <div class="history-item">
- <div class="history-item-header">
- <div class="history-item-title"></div>
- <div class="history-item-status"></div>
- </div>
- <div class="history-item-meta">
- <div class="history-item-date"></div>
- <div class="history-item-mode"></div>
- </div>
- <div class="history-item-actions">
- <button class="btn btn-sm btn-outline view-btn"><i class="fas fa-eye"></i> View</button>
- <button class="btn btn-sm btn-outline pdf-btn" style="display: none;"><i class="fas fa-file-pdf"></i> PDF</button>
- <!-- Delete button will be added dynamically -->
- </div>
- </div>
-</template>
+<!-- Template is no longer needed since we build items dynamically in JavaScript -->
{% endblock %}
{% block page_scripts %}
+<!-- Load utilities first -->
+<script src="{{ url_for('research.serve_static', path='js/utils/ui.js') }}"></script>
+<script src="{{ url_for('research.serve_static', path='js/utils/formatting.js') }}"></script>
+<script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script>
+<!-- Then load the component -->
<script src="{{ url_for('research.serve_static', path='js/components/history.js') }}"></script>
{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/pages/settings.html b/src/local_deep_research/web/templates/pages/settings.html
deleted file mode 100644
index 17348d91f5..0000000000
--- a/src/local_deep_research/web/templates/pages/settings.html
+++ /dev/null
@@ -1,26 +0,0 @@
-{% extends 'base.html' %}
-{% set active_page = 'settings' %}
-
-{% block title %}Settings - Deep Research System{% endblock %}
-
-{% block content %}
-<div class="page-header">
- <h1>Settings</h1>
-</div>
-
-<div class="card">
- <div class="card-content">
- <div class="settings-menu">
- <ul>
- <li><a href="{{ url_for('research.main_config_page') }}"><i class="fas fa-cog"></i> Main Configuration</a></li>
- <li><a href="{{ url_for('research.collections_config_page') }}"><i class="fas fa-folder"></i> Collections</a></li>
- <li><a href="{{ url_for('research.api_keys_config_page') }}"><i class="fas fa-key"></i> API Keys</a></li>
- <li><a href="{{ url_for('research.search_engines_config_page') }}"><i class="fas fa-search"></i> Search Engines</a></li>
- </ul>
- </div>
- <div class="settings-info">
- <p>Select a settings category from the menu to configure your research system.</p>
- </div>
- </div>
-</div>
-{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/pages/settings_api_keys.html b/src/local_deep_research/web/templates/pages/settings_api_keys.html
deleted file mode 100644
index 6d0fdc94b8..0000000000
--- a/src/local_deep_research/web/templates/pages/settings_api_keys.html
+++ /dev/null
@@ -1,39 +0,0 @@
-{% extends 'base.html' %}
-{% set active_page = 'settings' %}
-
-{% block title %}API Keys Settings - Deep Research System{% endblock %}
-
-{% block content %}
-<div class="page-header">
- <h1>API Keys Settings</h1>
- <div class="page-actions">
- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back to Settings</a>
- </div>
-</div>
-
-<div class="card">
- <div class="card-content">
- <form id="api-keys-form">
- <div class="form-group">
- <label for="openai_api_key">OpenAI API Key</label>
- <input type="password" id="openai_api_key" name="openai_api_key" placeholder="sk-...">
- <div class="input-help">Required for AI-powered research features</div>
- </div>
-
- <div class="form-group">
- <label for="serper_api_key">Serper API Key (Optional)</label>
- <input type="password" id="serper_api_key" name="serper_api_key" placeholder="Your Serper API key">
- <div class="input-help">Used for enhanced web search results</div>
- </div>
-
- <div class="form-actions">
- <button type="submit" class="btn btn-primary">Save Keys</button>
- </div>
- </form>
- </div>
-</div>
-{% endblock %}
-
-{% block page_scripts %}
-<script src="{{ url_for('research.serve_static', path='js/components/settings.js') }}"></script>
-{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/pages/settings_collections.html b/src/local_deep_research/web/templates/pages/settings_collections.html
deleted file mode 100644
index 274fa37d8e..0000000000
--- a/src/local_deep_research/web/templates/pages/settings_collections.html
+++ /dev/null
@@ -1,29 +0,0 @@
-{% extends 'base.html' %}
-{% set active_page = 'settings' %}
-
-{% block title %}Collections Settings - Deep Research System{% endblock %}
-
-{% block content %}
-<div class="page-header">
- <h1>Collections Settings</h1>
- <div class="page-actions">
- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back to Settings</a>
- </div>
-</div>
-
-<div class="card">
- <div class="card-content">
- <div class="collections-container">
- <div class="collections-list" id="collections-list">
- <!-- Collections will be displayed here -->
- <div class="empty-message">No collections configured yet.</div>
- </div>
- <button id="add-collection-btn" class="btn btn-primary"><i class="fas fa-plus"></i> Add Collection</button>
- </div>
- </div>
-</div>
-{% endblock %}
-
-{% block page_scripts %}
-<script src="{{ url_for('research.serve_static', path='js/components/settings.js') }}"></script>
-{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/pages/settings_main.html b/src/local_deep_research/web/templates/pages/settings_main.html
deleted file mode 100644
index 1b1d2cb667..0000000000
--- a/src/local_deep_research/web/templates/pages/settings_main.html
+++ /dev/null
@@ -1,40 +0,0 @@
-{% extends 'base.html' %}
-{% set active_page = 'settings' %}
-
-{% block title %}Main Settings - Deep Research System{% endblock %}
-
-{% block content %}
-<div class="page-header">
- <h1>Main Settings</h1>
- <div class="page-actions">
- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back to Settings</a>
- </div>
-</div>
-
-<div class="card">
- <div class="card-content">
- <form id="main-settings-form">
- <div class="form-group">
- <label for="output_dir">Research Output Directory</label>
- <input type="text" id="output_dir" name="output_dir" placeholder="Path to research outputs">
- </div>
-
- <div class="form-group">
- <label for="debug_mode">Debug Mode</label>
- <div class="checkbox-wrapper">
- <input type="checkbox" id="debug_mode" name="debug_mode">
- <span class="checkbox-label">Enable debug mode</span>
- </div>
- </div>
-
- <div class="form-actions">
- <button type="submit" class="btn btn-primary">Save Changes</button>
- </div>
- </form>
- </div>
-</div>
-{% endblock %}
-
-{% block page_scripts %}
-<script src="{{ url_for('research.serve_static', path='js/components/settings.js') }}"></script>
-{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/pages/settings_search_engines.html b/src/local_deep_research/web/templates/pages/settings_search_engines.html
deleted file mode 100644
index c82f46fd93..0000000000
--- a/src/local_deep_research/web/templates/pages/settings_search_engines.html
+++ /dev/null
@@ -1,50 +0,0 @@
-{% extends 'base.html' %}
-{% set active_page = 'settings' %}
-
-{% block title %}Search Engines Settings - Deep Research System{% endblock %}
-
-{% block content %}
-<div class="page-header">
- <h1>Search Engines Settings</h1>
- <div class="page-actions">
- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back to Settings</a>
- </div>
-</div>
-
-<div class="card">
- <div class="card-content">
- <form id="search-engines-form">
- <div class="form-group">
- <label>Enabled Search Engines</label>
- <div class="checkbox-group">
- <div class="checkbox-wrapper">
- <input type="checkbox" id="engine_google" name="engines" value="google" checked>
- <span class="checkbox-label">Google</span>
- </div>
- <div class="checkbox-wrapper">
- <input type="checkbox" id="engine_bing" name="engines" value="bing">
- <span class="checkbox-label">Bing</span>
- </div>
- <div class="checkbox-wrapper">
- <input type="checkbox" id="engine_serper" name="engines" value="serper">
- <span class="checkbox-label">Serper (Requires API key)</span>
- </div>
- </div>
- </div>
-
- <div class="form-group">
- <label for="max_results">Maximum Results Per Engine</label>
- <input type="number" id="max_results" name="max_results" value="5" min="1" max="20">
- </div>
-
- <div class="form-actions">
- <button type="submit" class="btn btn-primary">Save Settings</button>
- </div>
- </form>
- </div>
-</div>
-{% endblock %}
-
-{% block page_scripts %}
-<script src="{{ url_for('research.serve_static', path='js/components/settings.js') }}"></script>
-{% endblock %}
\ No newline at end of file