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.

Refactor settings management and improve research process integration with Ollama

hashedvikingd32da688f6e9
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 816f8044a7..528a6706a5 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -1,3 +1,4 @@
+import json
import logging
from typing import Dict
@@ -96,11 +97,15 @@ class StandardSearchStrategy(BaseSearchStrategy):
)
# Generate questions for this iteration using the question generator
+ # Prepare context for question generation
+ context = f"""Current Query: {query}
+Current Knowledge: {current_knowledge}
+Previous Questions: {json.dumps(self.questions_by_iteration, indent=2)}
+Iteration: {iteration + 1} of {total_iterations}"""
+
+ # Call question generator with updated interface
questions = self.question_generator.generate_questions(
- current_knowledge=current_knowledge,
- query=query,
- questions_per_iteration=self.questions_per_iteration,
- questions_by_iteration=self.questions_by_iteration,
+ query=query, context=context
)
self.questions_by_iteration[iteration] = questions
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 12a09a3a29..7f71e471c2 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -153,6 +153,7 @@ def register_blueprints(app):
"""Register blueprints with the Flask app."""
# Import blueprints
+ from .routes.api_routes import api_bp # Import the API blueprint
from .routes.history_routes import history_bp
from .routes.research_routes import research_bp
from .routes.settings_routes import settings_bp
@@ -161,6 +162,9 @@ def register_blueprints(app):
app.register_blueprint(research_bp)
app.register_blueprint(history_bp, url_prefix="/research/api")
app.register_blueprint(settings_bp)
+ app.register_blueprint(
+ api_bp, url_prefix="/research/api"
+ ) # Register API blueprint with prefix
# Configure settings paths
# Import config inside the function to avoid circular dependencies
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index dbe664214f..8da117c4dd 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -62,6 +62,23 @@ def init_db():
"""
)
+ # Create a dedicated table for research resources
+ cursor.execute(
+ """
+ CREATE TABLE IF NOT EXISTS research_resources (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ research_id INTEGER NOT NULL,
+ title TEXT,
+ url TEXT,
+ content_preview TEXT,
+ source_type TEXT,
+ metadata TEXT,
+ created_at TEXT NOT NULL,
+ FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE
+ )
+ """
+ )
+
# Check if the duration_seconds column exists, add it if missing
cursor.execute("PRAGMA table_info(research_history)")
columns = [column[1] for column in cursor.fetchall()]
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 33358e7c79..1de80e5846 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -7,15 +7,18 @@ from pathlib import Path
import requests
from flask import Blueprint, current_app, jsonify, request, send_from_directory
-from ..models.database import get_db
-from ..models.research import Research
-from ..models.task import Task
+from ..models.database import get_db_connection
+from ..routes.research_routes import active_research, get_globals, termination_flags
from ..services.research_service import (
cancel_research,
- get_research_status,
- start_research,
+ run_research_process,
+ start_research_process,
+)
+from ..services.resource_service import (
+ add_resource,
+ delete_resource,
+ get_resources_for_research,
)
-from ..services.resource_service import get_resources_for_research
# Create blueprint
api_bp = Blueprint("api", __name__)
@@ -36,8 +39,50 @@ def api_start_research():
return jsonify({"status": "error", "message": "Query is required"}), 400
try:
- # Start research process and get ID
- research_id = start_research(query, mode)
+ # Create a record in the database with explicit UTC timestamp
+ from datetime import datetime
+
+ created_at = datetime.utcnow().isoformat()
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Save basic research settings for API route
+ research_settings = {
+ "model_provider": "OLLAMA", # Default
+ "model": "llama2", # Default
+ "search_engine": "auto", # Default
+ }
+
+ cursor.execute(
+ "INSERT INTO research_history (query, mode, status, created_at, progress_log, metadata) VALUES (?, ?, ?, ?, ?, ?)",
+ (
+ query,
+ mode,
+ "in_progress",
+ created_at,
+ json.dumps(
+ [{"time": created_at, "message": "Research started", "progress": 0}]
+ ),
+ json.dumps(research_settings),
+ ),
+ )
+ research_id = cursor.lastrowid
+ conn.commit()
+ conn.close()
+
+ # Start the research process
+ research_thread = start_research_process(
+ research_id,
+ query,
+ mode,
+ active_research,
+ termination_flags,
+ run_research_process,
+ )
+
+ # Store the thread reference
+ active_research[research_id]["thread"] = research_thread
return jsonify(
{
@@ -47,6 +92,7 @@ def api_start_research():
}
)
except Exception as e:
+ logger.error(f"Error starting research: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
@@ -56,9 +102,39 @@ def api_research_status(research_id):
Get the status of a research process
"""
try:
- status = get_research_status(research_id)
- return jsonify(status)
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute(
+ "SELECT status, progress, completed_at, report_path, metadata FROM research_history WHERE id = ?",
+ (research_id,),
+ )
+ result = cursor.fetchone()
+ conn.close()
+
+ if result is None:
+ return jsonify({"error": "Research not found"}), 404
+
+ status, progress, completed_at, report_path, metadata_str = result
+
+ # Parse metadata if it exists
+ metadata = {}
+ if metadata_str:
+ try:
+ metadata = json.loads(metadata_str)
+ except json.JSONDecodeError:
+ logger.warning(f"Invalid JSON in metadata for research {research_id}")
+
+ return jsonify(
+ {
+ "status": status,
+ "progress": progress,
+ "completed_at": completed_at,
+ "report_path": report_path,
+ "metadata": metadata,
+ }
+ )
except Exception as e:
+ logger.error(f"Error getting research status: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
@@ -88,6 +164,84 @@ def api_get_resources(research_id):
return jsonify({"status": "error", "message": str(e)}), 500
+@api_bp.route("/resources/<int:research_id>", methods=["POST"])
+def api_add_resource(research_id):
+ """
+ Add a new resource to a research project
+ """
+ try:
+ data = request.json
+
+ # Required fields
+ title = data.get("title")
+ url = data.get("url")
+
+ # Optional fields
+ content_preview = data.get("content_preview")
+ source_type = data.get("source_type", "web")
+ metadata = data.get("metadata", {})
+
+ # Validate required fields
+ if not title or not url:
+ return (
+ jsonify({"status": "error", "message": "Title and URL are required"}),
+ 400,
+ )
+
+ # Check if the research exists
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))
+ result = cursor.fetchone()
+ conn.close()
+
+ if not result:
+ return jsonify({"status": "error", "message": "Research not found"}), 404
+
+ # Add the resource
+ resource_id = add_resource(
+ research_id=research_id,
+ title=title,
+ url=url,
+ content_preview=content_preview,
+ source_type=source_type,
+ metadata=metadata,
+ )
+
+ return jsonify(
+ {
+ "status": "success",
+ "message": "Resource added successfully",
+ "resource_id": resource_id,
+ }
+ )
+ except Exception as e:
+ logger.error(f"Error adding resource: {str(e)}")
+ return jsonify({"status": "error", "message": str(e)}), 500
+
+
+@api_bp.route(
+ "/resources/<int:research_id>/delete/<int:resource_id>", methods=["DELETE"]
+)
+def api_delete_resource(research_id, resource_id):
+ """
+ Delete a resource from a research project
+ """
+ try:
+ # Delete the resource
+ success = delete_resource(resource_id)
+
+ if success:
+ return jsonify(
+ {"status": "success", "message": "Resource deleted successfully"}
+ )
+ else:
+ return jsonify({"status": "error", "message": "Resource not found"}), 404
+ except Exception as e:
+ logger.error(f"Error deleting resource: {str(e)}")
+ return jsonify({"status": "error", "message": str(e)}), 500
+
+
@api_bp.route("/check/ollama_status", methods=["GET"])
def check_ollama_status():
"""
@@ -150,8 +304,14 @@ def check_ollama_model():
}
)
- # Get model name and Ollama API URL
- model_name = llm_config.get("model", "gemma3:12b")
+ # Get model name from request or use config default
+ model_name = request.args.get("model")
+ if not model_name:
+ model_name = llm_config.get("model", "gemma3:12b")
+
+ # Log which model we're checking for debugging
+ logger.info(f"Checking availability of Ollama model: {model_name}")
+
ollama_base_url = llm_config.get("ollama_base_url", "http://localhost:11434")
# Check if the model is available
@@ -166,8 +326,22 @@ def check_ollama_model():
}
)
- models = response.json().get("models", [])
- model_exists = any(m.get("name") == model_name for m in models)
+ # Handle both newer and older Ollama API formats
+ data = response.json()
+ if "models" in data:
+ # Newer Ollama API
+ models = data.get("models", [])
+ # Case-insensitive model name comparison
+ model_exists = any(
+ m.get("name", "").lower() == model_name.lower() for m in models
+ )
+ else:
+ # Older Ollama API format
+ models = data
+ # Case-insensitive model name comparison
+ model_exists = any(
+ m.get("name", "").lower() == model_name.lower() for m in models
+ )
if model_exists:
return jsonify(
@@ -178,19 +352,32 @@ def check_ollama_model():
}
)
else:
+ # Check if models were found at all
+ if not models:
+ message = "No models found in Ollama. Please pull models first."
+ else:
+ message = (
+ f"Model {model_name} is not available. Available models: "
+ + ", ".join([m.get("name", "") for m in models[:5]])
+ ) # Show first 5 models
+
return jsonify(
{
"available": False,
"model": model_name,
- "message": f"Model {model_name} is not available",
+ "message": message,
}
)
except Exception as e:
- logger.error(f"Error checking Ollama model: {str(e)}")
+ logger.error(f"Error checking Ollama model: {e}")
return jsonify(
{
"available": False,
- "model": llm_config.get("model", "gemma3:12b"),
+ "model": (
+ model_name
+ if "model_name" in locals()
+ else llm_config.get("model", "gemma3:12b")
+ ),
"message": f"Error checking model: {str(e)}",
}
)
diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.css
index 358ca2ff1b..bca3c17218 100644
--- a/src/local_deep_research/web/static/css/custom_dropdown.css
+++ b/src/local_deep_research/web/static/css/custom_dropdown.css
@@ -10,65 +10,134 @@
.custom-dropdown-input {
width: 100%;
- height: 38px;
- padding: 8px 12px;
- border: 1px solid var(--border-color);
- border-radius: 5px;
- background-color: var(--input-bg);
- color: var(--text-color);
- font-size: 14px;
- transition: border-color 0.2s;
+ padding: 10px;
+ border-radius: 6px;
+ border: 1px solid var(--border-color, #343452);
+ background-color: var(--bg-secondary, #1e1e2d);
+ color: var(--text-primary, #f5f5f5);
+ font-size: 0.9rem;
+ cursor: pointer;
}
.custom-dropdown-input:focus {
outline: none;
- border-color: var(--accent-color);
- box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.25);
+ border-color: var(--accent-primary, #6e4ff6);
+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.15);
}
.custom-dropdown-list {
position: absolute;
- top: 100%;
- left: 0;
width: 100%;
max-height: 250px;
overflow-y: auto;
- background-color: var(--dropdown-bg);
- border: 1px solid var(--border-color);
- border-radius: 0 0 5px 5px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
z-index: 100;
+ background-color: var(--bg-tertiary, #2a2a3a);
+ border: 1px solid var(--border-color, #343452);
+ border-radius: 6px;
+ margin-top: 5px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
display: none;
}
.custom-dropdown-item {
- padding: 8px 12px;
+ padding: 10px 15px;
cursor: pointer;
+ color: var(--text-primary, #f5f5f5);
transition: background-color 0.2s;
}
.custom-dropdown-item:hover,
.custom-dropdown-item.active {
- background-color: var(--hover-bg);
+ background-color: rgba(110, 79, 246, 0.1);
+}
+
+.custom-dropdown-item .highlight {
+ background-color: rgba(110, 79, 246, 0.3);
+ border-radius: 2px;
+ padding: 0 2px;
}
.custom-dropdown-no-results {
- padding: 12px;
- color: var(--text-muted);
- text-align: center;
+ padding: 10px 15px;
+ color: var(--text-secondary, #c0c0cc);
font-style: italic;
}
.custom-dropdown-footer {
- padding: 8px 12px;
- border-top: 1px solid var(--border-color);
- color: var(--text-muted);
- font-size: 13px;
- text-align: center;
+ padding: 10px 15px;
+ border-top: 1px solid var(--border-color, #343452);
+ color: var(--accent-tertiary, #40bfff);
+ font-size: 0.85rem;
+ background-color: rgba(64, 191, 255, 0.08);
}
-.custom-dropdown-item .highlight {
- background-color: rgba(59, 130, 246, 0.2);
- font-weight: bold;
- border-radius: 2px;
+/* Custom dropdown with refresh button */
+.custom-dropdown-with-refresh {
+ display: flex;
+ gap: 8px;
+ width: 100%;
+}
+
+.custom-dropdown-with-refresh .custom-dropdown {
+ flex: 1;
+}
+
+.custom-dropdown-refresh-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 38px;
+ height: 38px;
+ background-color: var(--bg-tertiary, #2a2a3a);
+ border: 1px solid var(--border-color, #343452);
+ border-radius: 6px;
+ color: var(--text-secondary, #c0c0cc);
+ cursor: pointer;
+ transition: all 0.2s;
+}
+
+.custom-dropdown-refresh-btn:hover {
+ background-color: var(--bg-secondary, #1e1e2d);
+ color: var(--accent-primary, #6e4ff6);
+ border-color: var(--accent-primary, #6e4ff6);
+}
+
+.custom-dropdown-refresh-btn.loading {
+ pointer-events: none;
+}
+
+.custom-dropdown-refresh-btn.loading i {
+ animation: spin 1s linear infinite;
+}
+
+@keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+}
+
+/* Advanced Options Panel Styles */
+.advanced-options-panel {
+ max-height: 0;
+ overflow: hidden;
+ transition: max-height 0.3s ease-out, opacity 0.3s ease;
+ opacity: 0;
+}
+
+.advanced-options-panel.expanded {
+ max-height: 500px; /* Set a large enough value to accommodate content */
+ opacity: 1;
+}
+
+/* Only add these styles if they don't conflict with styles.css */
+.advanced-options-toggle {
+ cursor: pointer;
+}
+
+.advanced-options-toggle i {
+ transition: transform 0.3s ease;
+}
+
+.advanced-options-toggle.expanded i,
+.advanced-options-toggle.open i {
+ transform: rotate(180deg);
}
diff --git a/src/local_deep_research/web/static/js/components/custom_dropdown.js b/src/local_deep_research/web/static/js/components/custom_dropdown.js
index 8516c32dc2..5330f9be0a 100644
--- a/src/local_deep_research/web/static/js/components/custom_dropdown.js
+++ b/src/local_deep_research/web/static/js/components/custom_dropdown.js
@@ -24,6 +24,18 @@
let isOpen = false;
let showAllOptions = false; // Flag to track if we should show all options
+ // Find the associated hidden input field
+ const hiddenInput = document.getElementById(`${input.id}_hidden`);
+
+ // Function to update hidden field
+ function updateHiddenField(value) {
+ if (hiddenInput) {
+ hiddenInput.value = value;
+ // Also dispatch a change event on the hidden input to trigger form handling
+ hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
+ }
+ }
+
// Function to filter options
function filterOptions(searchText, showAll = false) {
const options = getOptions();
@@ -84,6 +96,11 @@
div.innerHTML = highlightText(item.label, searchText);
div.setAttribute('data-value', item.value);
div.addEventListener('click', () => {
+ // Set display value
+ input.value = item.label;
+ // Update hidden input value
+ updateHiddenField(item.value);
+ // Call onSelect callback
onSelect(item.value, item);
hideDropdown();
});
@@ -123,36 +140,29 @@
}
});
- // Keyboard navigation
+ // Keyboard navigation for dropdown
input.addEventListener('keydown', (e) => {
const items = dropdownList.querySelectorAll('.custom-dropdown-item');
- // If dropdown is not open, only open on arrow down
- if (!isOpen && e.key === 'ArrowDown') {
- showAllOptions = true; // Show all options when opening with arrow down
- showDropdown();
- updateDropdown();
- return;
- }
-
- if (!isOpen) return;
-
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ if (e.key === 'ArrowDown') {
e.preventDefault();
-
- // Show all options when using arrow keys
- if (!showAllOptions) {
+ if (!isOpen) {
showAllOptions = true;
- updateDropdown(); // Update to show all options
+ showDropdown();
+ updateDropdown();
+ selectedIndex = 0;
+ } else {
+ selectedIndex = (selectedIndex + 1) % items.length;
}
-
- if (e.key === 'ArrowDown') {
- selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
- if (selectedIndex === -1 && items.length > 0) {
- selectedIndex = 0;
- }
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (!isOpen) {
+ showAllOptions = true;
+ showDropdown();
+ updateDropdown();
+ selectedIndex = items.length - 1;
} else {
- selectedIndex = Math.max(selectedIndex - 1, -1);
+ selectedIndex = (selectedIndex - 1 + items.length) % items.length;
}
} else if (e.key === 'Enter') {
e.preventDefault();
@@ -162,10 +172,18 @@
const selectedItem = items[selectedIndex];
const value = selectedItem.getAttribute('data-value');
const item = getOptions().find(o => o.value === value);
+ // Update display value
+ input.value = item.label;
+ // Update hidden input
+ updateHiddenField(value);
+ // Call callback
onSelect(value, item);
} else if (allowCustomValues && input.value.trim()) {
// Use the custom value
- onSelect(input.value.trim(), null);
+ const customValue = input.value.trim();
+ // Update hidden input with custom value
+ updateHiddenField(customValue);
+ onSelect(customValue, null);
}
hideDropdown();
} else if (e.key === 'Escape') {
@@ -218,11 +236,15 @@
const item = options.find(o => o.value === value);
if (item) {
input.value = item.label;
+ // Update hidden input
+ updateHiddenField(value);
if (fireEvent) {
onSelect(value, item);
}
} else if (allowCustomValues) {
input.value = value;
+ // Update hidden input with custom value
+ updateHiddenField(value);
if (fireEvent) {
onSelect(value, null);
}
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 54c961b09f..784b2a976d 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -15,14 +15,26 @@
let modelInput = null;
let modelDropdown = null;
let modelDropdownList = null;
+ let modelRefreshBtn = null;
let searchEngineInput = null;
let searchEngineDropdown = null;
let searchEngineDropdownList = null;
+ let searchEngineRefreshBtn = null;
let iterationsInput = null;
let questionsPerIterationInput = null;
let advancedToggle = null;
let advancedPanel = null;
+ // Cache keys
+ const CACHE_KEYS = {
+ MODELS: 'deepResearch.availableModels',
+ SEARCH_ENGINES: 'deepResearch.searchEngines',
+ CACHE_TIMESTAMP: 'deepResearch.cacheTimestamp'
+ };
+
+ // Cache expiration time (24 hours in milliseconds)
+ const CACHE_EXPIRATION = 24 * 60 * 60 * 1000;
+
// State variables for dropdowns
let modelOptions = [];
let selectedModelValue = '';
@@ -80,303 +92,238 @@
modelInput = document.getElementById('model');
modelDropdown = document.getElementById('model-dropdown');
modelDropdownList = document.getElementById('model-dropdown-list');
+ modelRefreshBtn = document.getElementById('model-refresh');
searchEngineInput = document.getElementById('search_engine');
searchEngineDropdown = document.getElementById('search-engine-dropdown');
searchEngineDropdownList = document.getElementById('search-engine-dropdown-list');
+ searchEngineRefreshBtn = document.getElementById('search_engine-refresh');
+ // Other form elements
iterationsInput = document.getElementById('iterations');
questionsPerIterationInput = document.getElementById('questions_per_iteration');
advancedToggle = document.querySelector('.advanced-options-toggle');
advancedPanel = document.querySelector('.advanced-options-panel');
- if (!form || !queryInput || !modeOptions.length || !startBtn) {
- console.error('Required DOM elements not found for research component');
- return;
- }
-
- // Set up event listeners
+ // Add event listeners
setupEventListeners();
- // Populate providers dropdown
+ // Populate model provider options
populateModelProviders();
- // Load data
- loadModelOptions();
- loadSearchEngineOptions();
- loadSettings();
+ // Initialize dropdowns
+ initializeDropdowns();
- console.log('Research component initialized');
+ // Load settings
+ loadSettings();
}
/**
- * Set up event listeners for the research form
+ * Initialize custom dropdowns for model and search engine
*/
- function setupEventListeners() {
- // Mode selection toggle
- modeOptions.forEach(option => {
- option.addEventListener('click', function() {
- // Remove active class from all options
- modeOptions.forEach(opt => opt.classList.remove('active'));
-
- // Add active class to clicked option
- this.classList.add('active');
- });
- });
-
- // Form submission
- form.addEventListener('submit', handleResearchSubmit);
-
- // Advanced options toggle
- if (advancedToggle && advancedPanel) {
- // Set initial state (closed by default)
- advancedPanel.style.display = 'none';
- advancedToggle.classList.remove('open');
-
- advancedToggle.addEventListener('click', function() {
- const isVisible = advancedPanel.style.display === 'block';
+ function initializeDropdowns() {
+ // Check if the custom dropdown script is loaded
+ if (typeof window.setupCustomDropdown !== 'function') {
+ console.error('Custom dropdown script is not loaded');
+ // Display an error message
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert('Failed to initialize dropdowns. Please reload the page.', 'error');
+ }
+ return;
+ }
- // Toggle panel visibility
- advancedPanel.style.display = isVisible ? 'none' : 'block';
+ console.log('Initializing dropdowns with setupCustomDropdown');
- // Toggle class for arrow rotation
- if (isVisible) {
- advancedToggle.classList.remove('open');
- } else {
- advancedToggle.classList.add('open');
- }
- });
- }
+ // Set up model dropdown
+ if (modelInput && modelDropdownList) {
+ // Clear any existing dropdown setup
+ modelDropdownList.innerHTML = '';
- // Handle model provider change
- if (modelProviderSelect) {
- modelProviderSelect.addEventListener('change', function() {
- const provider = this.value;
+ const modelDropdownInstance = window.setupCustomDropdown(
+ modelInput,
+ modelDropdownList,
+ () => {
+ console.log('Getting model options from dropdown:', modelOptions);
+ return modelOptions.length > 0 ? modelOptions : [{ value: '', label: 'No models available' }];
+ },
+ (value, item) => {
+ console.log('Model selected:', value, item);
+ selectedModelValue = value;
+
+ // Update the input field with the selected model's label or value
+ if (item) {
+ modelInput.value = item.label;
+ } else {
+ modelInput.value = value;
+ }
- // Show/hide custom endpoint input
- if (endpointContainer) {
- endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
- }
+ const isCustomValue = !item;
+ showCustomModelWarning(isCustomValue);
+ },
+ true, // Allow custom values
+ 'No models available. Type to enter a custom model name.'
+ );
- // Update model options based on provider and reset the selected model
- updateModelOptionsForProvider(provider, true);
- });
+ // Initialize model refresh button
+ if (modelRefreshBtn) {
+ modelRefreshBtn.addEventListener('click', function() {
+ const icon = modelRefreshBtn.querySelector('i');
+ if (icon) icon.className = 'fas fa-spinner fa-spin';
+
+ // Force refresh of model options
+ loadModelOptions(true).then(() => {
+ if (icon) icon.className = 'fas fa-sync-alt';
+
+ // Ensure the current provider's models are loaded
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ updateModelOptionsForProvider(currentProvider, false);
+
+ // Force dropdown update
+ const event = new Event('click', { bubbles: true });
+ modelInput.dispatchEvent(event);
+ }).catch(error => {
+ console.error('Error refreshing models:', error);
+ if (icon) icon.className = 'fas fa-sync-alt';
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert('Failed to refresh models: ' + error.message, 'error');
+ }
+ });
+ });
+ }
}
- // Setup custom dropdown for model
- setupCustomDropdown(
- modelInput,
- modelDropdownList,
- () => modelOptions,
- (value, item) => {
- selectedModelValue = item ? item.value : value;
- modelInput.value = item ? item.label : value;
- showCustomModelWarning(!item && value);
- },
- true, // allowCustomValues
- 'No models available. Type to enter a custom model name.'
- );
+ // Set up search engine dropdown
+ if (searchEngineInput && searchEngineDropdownList) {
+ // Clear any existing dropdown setup
+ searchEngineDropdownList.innerHTML = '';
- // Setup custom dropdown for search engine
- setupCustomDropdown(
+ const searchDropdownInstance = window.setupCustomDropdown(
searchEngineInput,
searchEngineDropdownList,
- () => searchEngineOptions,
+ () => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }],
(value, item) => {
- selectedSearchEngineValue = item ? item.value : null;
- searchEngineInput.value = item ? item.label : value;
- },
- false, // allowCustomValues
+ console.log('Search engine selected:', value, item);
+ selectedSearchEngineValue = value;
+
+ // Update the input field with the selected search engine's label or value
+ if (item) {
+ searchEngineInput.value = item.label;
+ } else {
+ searchEngineInput.value = value;
+ }
+ },
+ false, // Don't allow custom values
'No search engines available.'
);
+
+ // Initialize search engine refresh button
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.addEventListener('click', function() {
+ const icon = searchEngineRefreshBtn.querySelector('i');
+ if (icon) icon.className = 'fas fa-spinner fa-spin';
+
+ // Force refresh of search engine options
+ loadSearchEngineOptions(true).then(() => {
+ if (icon) icon.className = 'fas fa-sync-alt';
+
+ // Force dropdown update
+ const event = new Event('click', { bubbles: true });
+ searchEngineInput.dispatchEvent(event);
+ }).catch(error => {
+ console.error('Error refreshing search engines:', error);
+ if (icon) icon.className = 'fas fa-sync-alt';
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert('Failed to refresh search engines: ' + error.message, 'error');
+ }
+ });
+ });
+ }
+ }
}
/**
- * Setup a custom dropdown component
- * @param {HTMLElement} input - The input element
- * @param {HTMLElement} dropdownList - The dropdown list element
- * @param {Function} getOptions - Function that returns the current options array
- * @param {Function} onSelect - Callback when an item is selected
- * @param {boolean} allowCustomValues - Whether to allow values not in the options list
- * @param {string} noResultsText - Text to show when no results are found
+ * Setup event listeners
*/
- function setupCustomDropdown(input, dropdownList, getOptions, onSelect, allowCustomValues = false, noResultsText = 'No results found.') {
- let selectedIndex = -1;
- let isOpen = false;
- let showAllOptions = false; // Flag to track if we should show all options
-
- // Function to filter options
- function filterOptions(searchText, showAll = false) {
- const options = getOptions();
- if (showAll || !searchText.trim()) return options;
-
- return options.filter(item =>
- item.label.toLowerCase().includes(searchText.toLowerCase()) ||
- item.value.toLowerCase().includes(searchText.toLowerCase())
- );
- }
-
- // Function to highlight matched text
- function highlightText(text, search) {
- if (!search.trim() || showAllOptions) return text;
- const regex = new RegExp(`(${search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
- return text.replace(regex, '<span class="highlight">$1</span>');
- }
-
- // Function to show the dropdown
- function showDropdown() {
- dropdownList.style.display = 'block';
- input.setAttribute('aria-expanded', 'true');
- isOpen = true;
- }
-
- // Function to hide the dropdown
- function hideDropdown() {
- dropdownList.style.display = 'none';
- input.setAttribute('aria-expanded', 'false');
- selectedIndex = -1;
- isOpen = false;
- showAllOptions = false; // Reset the flag when closing dropdown
- }
-
- // Function to update the dropdown
- function updateDropdown() {
- const searchText = input.value;
- const filteredData = filterOptions(searchText, showAllOptions);
-
- dropdownList.innerHTML = '';
-
- if (filteredData.length === 0) {
- dropdownList.innerHTML = `<div class="custom-dropdown-no-results">${noResultsText}</div>`;
+ function setupEventListeners() {
+ if (!form || !startBtn) return;
- if (allowCustomValues && searchText.trim()) {
- const customOption = document.createElement('div');
- customOption.className = 'custom-dropdown-footer';
- customOption.textContent = `Press Enter to use "${searchText}"`;
- dropdownList.appendChild(customOption);
- }
+ // Form submission
+ form.addEventListener('submit', handleResearchSubmit);
- return;
- }
+ // Mode selection
+ modeOptions.forEach(mode => {
+ mode.addEventListener('click', function() {
+ modeOptions.forEach(m => m.classList.remove('active'));
+ this.classList.add('active');
+ });
+ });
- filteredData.forEach((item, index) => {
- const div = document.createElement('div');
- div.className = 'custom-dropdown-item';
- div.innerHTML = highlightText(item.label, searchText);
- div.setAttribute('data-value', item.value);
- div.addEventListener('click', () => {
- onSelect(item.value, item);
- hideDropdown();
- });
+ // Model provider change
+ if (modelProviderSelect) {
+ modelProviderSelect.addEventListener('change', function() {
+ const provider = this.value;
- if (index === selectedIndex) {
- div.classList.add('active');
+ // Show custom endpoint input if OpenAI endpoint is selected
+ if (endpointContainer) {
+ endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
}
- dropdownList.appendChild(div);
+ // Update model options based on provider
+ updateModelOptionsForProvider(provider, true);
});
}
- // Input event - filter as user types
- input.addEventListener('input', () => {
- showAllOptions = false; // Reset when typing
- showDropdown();
- updateDropdown();
- selectedIndex = -1;
- });
-
- // Click event - show all options when clicking in the input
- input.addEventListener('click', (e) => {
- if (!isOpen) {
- showAllOptions = true; // Show all options on click
- showDropdown();
- updateDropdown();
- }
- e.stopPropagation(); // Prevent immediate closing by document click handler
- });
-
- // Focus event - show dropdown when input is focused
- input.addEventListener('focus', () => {
- if (!isOpen) {
- showAllOptions = true; // Show all options on focus
- showDropdown();
- updateDropdown();
- }
- });
-
- // Keyboard navigation
- input.addEventListener('keydown', (e) => {
- const items = dropdownList.querySelectorAll('.custom-dropdown-item');
-
- // If dropdown is not open, only open on arrow down
- if (!isOpen && e.key === 'ArrowDown') {
- showAllOptions = true; // Show all options when opening with arrow down
- showDropdown();
- updateDropdown();
- return;
- }
-
- if (!isOpen) return;
-
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
- e.preventDefault();
-
- // Show all options when using arrow keys
- if (!showAllOptions) {
- showAllOptions = true;
- updateDropdown(); // Update to show all options
- }
+ // Advanced options toggle
+ if (advancedToggle && advancedPanel) {
+ // Set initial state
+ advancedToggle.classList.remove('open', 'expanded');
+ advancedPanel.style.display = 'none';
+ advancedPanel.style.maxHeight = '0';
- if (e.key === 'ArrowDown') {
- selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
- if (selectedIndex === -1 && items.length > 0) {
- selectedIndex = 0;
- }
- } else {
- selectedIndex = Math.max(selectedIndex - 1, -1);
- }
- } else if (e.key === 'Enter') {
- e.preventDefault();
-
- if (selectedIndex >= 0 && selectedIndex < items.length) {
- // Select the highlighted item
- const selectedItem = items[selectedIndex];
- const value = selectedItem.getAttribute('data-value');
- const item = getOptions().find(o => o.value === value);
- onSelect(value, item);
- } else if (allowCustomValues && input.value.trim()) {
- // Use the custom value
- onSelect(input.value.trim(), null);
+ advancedToggle.addEventListener('click', function() {
+ // Toggle classes for both approaches
+ const isOpen = advancedToggle.classList.toggle('open');
+ advancedToggle.classList.toggle('expanded', isOpen);
+
+ // Update icon
+ const icon = this.querySelector('i');
+ if (icon) {
+ icon.className = isOpen ? 'fas fa-chevron-up' : 'fas fa-chevron-down';
}
- hideDropdown();
- return;
- } else if (e.key === 'Escape') {
- e.preventDefault();
- hideDropdown();
- return;
- } else {
- // Any other key should reset the showAllOptions flag to let filtering work
- showAllOptions = false;
- return;
- }
-
- // Update active item styling
- items.forEach((item, idx) => {
- if (idx === selectedIndex) {
- item.classList.add('active');
- item.scrollIntoView({ block: 'nearest' });
+ // Support both styling approaches (for compatibility)
+ if (isOpen) {
+ // Show panel
+ advancedPanel.style.display = 'block';
+ // Need a small delay to allow the display:block to take effect before setting maxHeight
+ setTimeout(() => {
+ advancedPanel.style.maxHeight = advancedPanel.scrollHeight + 'px';
+ advancedPanel.classList.add('expanded');
+ }, 10);
} else {
- item.classList.remove('active');
+ // Hide panel with transition
+ advancedPanel.style.maxHeight = '0';
+ advancedPanel.classList.remove('expanded');
+ // Wait for transition to complete before setting display:none
+ setTimeout(() => {
+ advancedPanel.style.display = 'none';
+ }, 300); // Match the CSS transition time
}
});
- });
+ }
- // Click outside to close
- document.addEventListener('click', (e) => {
- const isClickInsideDropdown = input.contains(e.target) || dropdownList.contains(e.target);
- if (!isClickInsideDropdown && isOpen) {
- hideDropdown();
+ // Load options data from APIs
+ Promise.all([
+ loadModelOptions(false),
+ loadSearchEngineOptions(false)
+ ]).then(() => {
+ // After loading data, initialize dropdowns
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ updateModelOptionsForProvider(currentProvider, false);
+ }).catch(error => {
+ console.error('Failed to load options:', error);
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert('Failed to load model options. Please check your connection and try again.', 'error');
}
});
}
@@ -434,99 +381,176 @@
* @param {boolean} resetSelectedModel - Whether to reset the selected model
*/
function updateModelOptionsForProvider(provider, resetSelectedModel = false) {
- // Get models for this provider
- const models = availableModels[provider] || [];
-
- // Update model options
- modelOptions = models;
-
- // Reset model input if requested or if empty
- if (resetSelectedModel || !modelInput.value.trim()) {
- if (models.length > 0) {
- // Select the first model from the new provider
- modelInput.value = models[0].label;
- selectedModelValue = models[0].value;
- } else {
- // No models available for this provider
- modelInput.value = '';
- selectedModelValue = '';
- }
+ // Get models specifically for this provider
+ let models = [];
+
+ // If models aren't loaded yet, return early - they'll be loaded when available
+ const allModels = getCachedData(CACHE_KEYS.MODELS);
+ if (!allModels || !Array.isArray(allModels)) {
+ console.log('No model data loaded yet, will populate when available');
+ return;
}
- // Set placeholder text based on available models
- if (models.length === 0) {
- modelInput.placeholder = 'Enter custom model name';
- } else {
- modelInput.placeholder = 'Enter or select a model';
+ console.log('Filtering models for provider:', provider, 'from', allModels.length, 'models');
+
+ // Filter models based on the selected provider
+ models = allModels.filter(model => {
+ if (!model || typeof model !== 'object') return false;
+
+ // Skip provider options (they have value but no id)
+ if (model.value && !model.id) return false;
+
+ const modelProvider = model.provider ? model.provider.toUpperCase() : '';
+
+ if (provider === 'OLLAMA') {
+ return modelProvider === 'OLLAMA';
+ } else if (provider === 'OPENAI') {
+ return modelProvider === 'OPENAI';
+ } else if (provider === 'ANTHROPIC') {
+ return modelProvider === 'ANTHROPIC';
+ } else if (provider === 'OPENAI_ENDPOINT') {
+ // For custom endpoints, show OpenAI models as examples
+ return modelProvider === 'OPENAI' || modelProvider === 'ANTHROPIC';
+ } else if (provider === 'VLLM') {
+ return modelProvider === 'VLLM';
+ } else if (provider === 'LMSTUDIO') {
+ return modelProvider === 'LMSTUDIO';
+ } else if (provider === 'LLAMACPP') {
+ return modelProvider === 'LLAMACPP';
+ }
+
+ // If no provider selected or unrecognized, show all models
+ return true;
+ });
+
+ console.log('Filtered models for provider', provider, ':', models);
+
+ // Format models for dropdown
+ modelOptions = models.map(model => {
+ const label = model.name || model.id || 'Unknown model';
+ const value = model.id || '';
+ return { value, label };
+ });
+
+ console.log(`Updated model options for provider ${provider}: ${modelOptions.length} models`, modelOptions);
+
+ // Reset selected model if requested
+ if (resetSelectedModel && modelInput) {
+ modelInput.value = '';
+ selectedModelValue = '';
}
- // Update dropdown list if visible
+ // If we have available models and custom dropdown, update UI
+ if (window.setupCustomDropdown && modelInput && modelDropdownList) {
+ // Force dropdown list update if it's visible
if (modelDropdownList.style.display === 'block') {
- const event = new Event('input');
+ const event = new Event('input', { bubbles: true });
modelInput.dispatchEvent(event);
}
+ }
}
/**
- * Check if Ollama is running and model is available
- * @returns {Promise<Object>} Result with status and error message if any
+ * Check if Ollama is running and available
+ * @returns {Promise<boolean>} True if Ollama is running
*/
- async function checkOllamaModel() {
+ async function isOllamaRunning() {
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 };
- }
+ // Use the API endpoint with proper timeout handling
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
- const statusData = await statusResponse.json();
+ const response = await fetch('/research/settings/api/ollama-status', {
+ signal: controller.signal
+ });
- 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."
- };
- }
+ clearTimeout(timeoutId);
- // Then check if the model is available
- const modelResponse = await fetch('/research/api/check/ollama_model');
+ if (response.ok) {
+ const data = await response.json();
+ return data.running === true;
+ }
+ return false;
+ } catch (error) {
+ console.error('Ollama check failed:', error.name === 'AbortError' ? 'Request timed out' : error);
+ return false;
+ }
+ }
- // 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 };
- }
+ /**
+ * Get the currently selected model
+ * @returns {string} The model name
+ */
+ function getSelectedModel() {
+ // Get model value - could be a selected value or custom text
+ let model = selectedModelValue || (modelInput ? modelInput.value.trim() : "");
+ return model;
+ }
+
+ /**
+ * Check if Ollama is running and the selected model is available
+ * @returns {Promise<{success: boolean, error: string, solution: string}>} Result of the check
+ */
+ async function checkOllamaModel() {
+ const isRunning = await isOllamaRunning();
- const modelData = await modelResponse.json();
+ if (!isRunning) {
+ return {
+ success: false,
+ error: "Ollama service is not running.",
+ solution: "Please start Ollama and try again."
+ };
+ }
- 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 };
+ // Get the currently selected model
+ const model = getSelectedModel();
+
+ if (!model) {
+ return {
+ success: false,
+ error: "No model selected.",
+ solution: "Please select or enter a valid model name."
+ };
+ }
+
+ // Check if the model is available in Ollama
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
+
+ const response = await fetch(`/research/api/check/ollama_model?model=${encodeURIComponent(model)}`, {
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ return {
+ success: false,
+ error: "Error checking model availability.",
+ solution: "Please check your Ollama installation and try again."
+ };
}
- return { success: true };
+ const data = await response.json();
+
+ if (data.available) {
+ return {
+ success: true
+ };
+ } else {
+ return {
+ success: false,
+ error: data.message || "The selected model is not available in Ollama.",
+ solution: "Please pull the model first using 'ollama pull " + model + "' or select a different model."
+ };
+ }
} catch (error) {
- console.error('Error checking Ollama:', error);
+ console.error("Error checking Ollama model:", 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."
+ error: "Error checking model availability: " + error.message,
+ solution: "Please check your Ollama installation and try again."
};
}
}
@@ -549,8 +573,8 @@
? customEndpointInput.value.trim()
: '';
- // Get model value - could be a selected value or custom text
- let model = selectedModelValue || modelInput.value.trim();
+ // Get model value using helper function
+ let model = getSelectedModel();
// Use the specified search engine.
let searchEngine = selectedSearchEngineValue;
@@ -617,7 +641,8 @@
window.fetch('/research/api/start_research', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCsrfToken()
},
body: JSON.stringify(payload)
})
@@ -666,24 +691,29 @@
* @param {string} message - The error message to display
*/
function showFormError(message) {
- // Check if error element already exists
- let errorEl = form.querySelector('.form-error');
-
- if (!errorEl) {
- // Create error element
- errorEl = document.createElement('div');
- errorEl.className = 'form-error error-message';
- form.insertBefore(errorEl, form.querySelector('.form-actions'));
+ // Check if UI alert function is available
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert(message, 'error');
+ return;
}
- // Set error message
- errorEl.textContent = message;
- errorEl.style.display = 'block';
-
- // Hide error after 5 seconds
+ // Legacy implementation
+ const formError = document.getElementById('form-error');
+ if (formError) {
+ formError.textContent = message;
+ formError.style.display = 'block';
setTimeout(() => {
- errorEl.style.display = 'none';
+ formError.style.display = 'none';
}, 5000);
+ } else {
+ // Fallback to alert if no error container
+ alert(message);
+ }
+
+ if (startBtn) {
+ startBtn.disabled = false;
+ startBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
+ }
}
/**
@@ -721,115 +751,250 @@
}
/**
- * Load language model options from API
+ * Load model options from API or cache
+ * @param {boolean} forceRefresh - Whether to force refresh from API
+ * @returns {Promise} Promise that resolves when models are loaded
*/
- function loadModelOptions() {
- // Show loading state
- modelInput.placeholder = 'Loading models...';
- modelInput.disabled = true;
+ function loadModelOptions(forceRefresh = false) {
+ return new Promise((resolve, reject) => {
+ // Get cached data if available and not forcing refresh
+ const cachedData = getCachedData(CACHE_KEYS.MODELS);
+ if (!forceRefresh && cachedData && cachedData.length > 0) {
+ console.log('Using cached model data', cachedData.length, 'models');
+
+ // Update UI with cached data
+ try {
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ updateModelOptionsForProvider(currentProvider, false);
+ } catch (error) {
+ console.error('Error updating UI with cached model data:', error);
+ }
- // Fetch all data sources in parallel
- Promise.all([
- // Get available models from API - FIXED PATH
- fetch('/research/settings/api/available-models')
- .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`)),
-
- // Get current setting value - FIXED PATH
- fetch('/research/settings/api?type=llm')
- .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))
- .catch(() => ({ settings: {} })) // Fallback if API fails
- ])
- .then(([modelsData, settingsData]) => {
- // Process Ollama models
- if (modelsData.providers && modelsData.providers.ollama_models && modelsData.providers.ollama_models.length > 0) {
- console.log('Found Ollama models:', modelsData.providers.ollama_models);
- availableModels.OLLAMA = modelsData.providers.ollama_models;
- } else if (modelsData.ollama_models && modelsData.ollama_models.length > 0) {
- // Backward compatibility
- console.log('Found Ollama models (legacy format):', modelsData.ollama_models);
- availableModels.OLLAMA = modelsData.ollama_models;
- } else {
- // Fallback Ollama models
- availableModels.OLLAMA = [
- { value: 'gemma3:12b', label: 'Gemma 3 12B' },
- { value: 'mistral', label: 'Mistral' },
- { value: 'deepseek-r1', label: 'DeepSeek R1' }
- ];
+ resolve(cachedData);
+ return;
}
- // Check for current provider setting
- const currentProvider = settingsData?.settings?.['llm.provider'] || 'OLLAMA';
+ // Check for refresh button with both possible IDs
+ let refreshBtn = modelRefreshBtn;
+ if (!refreshBtn) {
+ refreshBtn = document.getElementById('llm-model-refresh');
+ }
- // Ensure provider is set to a valid value - default to OLLAMA if empty or invalid
- if (modelProviderSelect) {
- // Only update if it's a valid provider, otherwise use OLLAMA as default
- if (currentProvider && MODEL_PROVIDERS.some(p => p.value === currentProvider)) {
- modelProviderSelect.value = currentProvider;
- } else {
- modelProviderSelect.value = 'OLLAMA';
+ // Show loading spinner on refresh button if available
+ if (refreshBtn) {
+ refreshBtn.classList.add('loading');
+ const icon = refreshBtn.querySelector('i');
+ if (icon) icon.className = 'fas fa-spinner fa-spin';
+ }
+
+ console.log('Fetching models from API...');
+
+ // Fetch model providers from API
+ fetch('/research/settings/api/available-models')
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ return response.json();
+ })
+ .then(data => {
+ console.log('Received model data from API');
+
+ // Process and cache the data
+ const processedModels = processModelData(data);
+
+ // Update the UI
+ try {
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ updateModelOptionsForProvider(currentProvider, false);
+ } catch (error) {
+ console.error('Error updating dropdown after loading models:', error);
+ }
+
+ // Reset refresh button
+ if (refreshBtn) {
+ refreshBtn.classList.remove('loading');
+ const icon = refreshBtn.querySelector('i');
+ if (icon) icon.className = 'fas fa-sync-alt';
+ }
+
+ resolve(processedModels);
+ })
+ .catch(error => {
+ console.error('Error loading models:', error);
+
+ // Reset refresh button
+ if (refreshBtn) {
+ refreshBtn.classList.remove('loading');
+ const icon = refreshBtn.querySelector('i');
+ if (icon) icon.className = 'fas fa-sync-alt';
+ }
+
+ // Try to update UI with fallback data
+ try {
+ // Process empty data to get fallbacks
+ const fallbackModels = processModelData({});
+
+ // Update UI with fallbacks
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ updateModelOptionsForProvider(currentProvider, false);
+
+ // Resolve with fallbacks
+ resolve(fallbackModels);
+ } catch (fallbackError) {
+ console.error('Error applying fallback models:', fallbackError);
+ reject(error);
+ }
+ });
+ });
+ }
+
+ /**
+ * Process model data from API
+ * @param {Object} data - The model data from API
+ * @returns {Array} - Formatted model data
+ */
+ function processModelData(data) {
+ let formattedModels = [];
+
+ try {
+ console.log('Processing model data:', data);
+
+ // Debug the structure of the API response
+ if (data.providers) {
+ if (data.providers.ollama_models) {
+ console.log('Ollama models structure:',
+ data.providers.ollama_models.length > 0 ?
+ data.providers.ollama_models[0] : 'Empty array');
+ }
+ if (data.providers.openai_models) {
+ console.log('OpenAI models structure:',
+ data.providers.openai_models.length > 0 ?
+ data.providers.openai_models[0] : 'Empty array');
+ }
+ if (data.providers.anthropic_models) {
+ console.log('Anthropic models structure:',
+ data.providers.anthropic_models.length > 0 ?
+ data.providers.anthropic_models[0] : 'Empty array');
}
}
- // Check for endpoint setting
- const currentEndpoint = settingsData?.settings?.['llm.openai_endpoint'];
- if (currentEndpoint && customEndpointInput) {
- customEndpointInput.value = currentEndpoint;
+ // Check if data has provider_options
+ if (data.provider_options && Array.isArray(data.provider_options)) {
+ formattedModels = [...data.provider_options];
}
- // Show/hide endpoint input based on provider
- if (endpointContainer) {
- endpointContainer.style.display = modelProviderSelect.value === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ // Add Ollama models if available
+ if (data.providers && data.providers.ollama_models && Array.isArray(data.providers.ollama_models)) {
+ const ollamaModels = data.providers.ollama_models.map(model => {
+ // Check for different possible property names
+ const modelId = model.id || model.value || model.model_id || '';
+ const modelName = model.name || model.label || model.model_name || modelId;
+
+ console.log('Mapping Ollama model:', model, '→', { id: modelId, name: modelName });
+
+ return {
+ id: modelId,
+ name: modelName,
+ provider: 'OLLAMA'
+ };
+ });
+ formattedModels = [...formattedModels, ...ollamaModels];
}
- // Check for current model setting
- const currentModel = settingsData?.settings?.['llm.model'];
+ // Add OpenAI models if available
+ if (data.providers && data.providers.openai_models && Array.isArray(data.providers.openai_models)) {
+ const openaiModels = data.providers.openai_models.map(model => {
+ // Check for different possible property names
+ const modelId = model.id || model.value || model.model_id || '';
+ const modelName = model.name || model.label || model.model_name || modelId;
- // Update model options for the current provider
- updateModelOptionsForProvider(modelProviderSelect.value);
+ console.log('Mapping OpenAI model:', model, '→', { id: modelId, name: modelName });
- // Set default model if available
- if (currentModel) {
- // Try to find the model in the current provider's options
- const modelOption = modelOptions.find(m => m.value === currentModel);
- if (modelOption) {
- modelInput.value = modelOption.label;
- selectedModelValue = modelOption.value;
- } else {
- // If not found, set it as a custom value
- modelInput.value = currentModel;
- selectedModelValue = currentModel;
- }
- } else if (modelOptions.length > 0) {
- // Default to first model in the list
- modelInput.value = modelOptions[0].label;
- selectedModelValue = modelOptions[0].value;
+ return {
+ id: modelId,
+ name: modelName,
+ provider: 'OPENAI'
+ };
+ });
+ formattedModels = [...formattedModels, ...openaiModels];
}
- // Re-enable the input
- modelInput.disabled = false;
- })
- .catch(error => {
- console.error('Error loading LLM models:', error);
- // Use fallback options
- updateModelOptionsForProvider('OLLAMA');
- modelInput.disabled = false;
- });
+ // Add Anthropic models if available
+ if (data.providers && data.providers.anthropic_models && Array.isArray(data.providers.anthropic_models)) {
+ const anthropicModels = data.providers.anthropic_models.map(model => {
+ // Check for different possible property names
+ const modelId = model.id || model.value || model.model_id || '';
+ const modelName = model.name || model.label || model.model_name || modelId;
+
+ console.log('Mapping Anthropic model:', model, '→', { id: modelId, name: modelName });
+
+ return {
+ id: modelId,
+ name: modelName,
+ provider: 'ANTHROPIC'
+ };
+ });
+ formattedModels = [...formattedModels, ...anthropicModels];
+ }
+
+ console.log('Final formatted models:', formattedModels);
+ } catch (error) {
+ console.error('Error processing model data:', error);
+
+ // Add fallback models for each provider
+ formattedModels = [
+ ...availableModels.OLLAMA.map(model => ({
+ id: model.value,
+ name: model.label,
+ provider: 'OLLAMA'
+ })),
+ ...availableModels.OPENAI.map(model => ({
+ id: model.value,
+ name: model.label,
+ provider: 'OPENAI'
+ })),
+ ...availableModels.ANTHROPIC.map(model => ({
+ id: model.value,
+ name: model.label,
+ provider: 'ANTHROPIC'
+ }))
+ ];
+ }
+
+ // Cache the processed models
+ cacheData(CACHE_KEYS.MODELS, formattedModels);
+
+ return formattedModels;
}
/**
* Load search engine options from API
+ * @param {boolean} forceRefresh - Force refresh from API even if cached data exists
*/
- function loadSearchEngineOptions() {
+ function loadSearchEngineOptions(forceRefresh = false) {
// FORCE set default to Auto immediately
searchEngineInput.value = 'Auto (Default)';
selectedSearchEngineValue = 'auto';
- // Store this in localStorage to avoid any issues
- window.localStorage.setItem('defaultSearchEngine', 'auto');
+ // Try to load from cache first if not forcing refresh
+ if (!forceRefresh) {
+ const cachedEngines = getCachedData(CACHE_KEYS.SEARCH_ENGINES);
+ if (cachedEngines) {
+ console.log('Using cached search engine data');
+ processSearchEngineData(cachedEngines);
+ return;
+ }
+ }
// Show loading state
searchEngineInput.placeholder = 'Loading search engines...';
- searchEngineInput.disabled = true;
+
+ // Don't disable the input, allow interaction with cached data
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.add('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-spinner';
+ }
// Set default options in case API call fails
const defaultOptions = [
@@ -843,9 +1008,6 @@
// Start with default options
searchEngineOptions = defaultOptions;
- // Re-enable the input
- searchEngineInput.disabled = false;
-
// Try to get search engine options from API - FIXED PATH
fetch('/research/settings/api/available-search-engines')
.then(response => {
@@ -853,6 +1015,37 @@
return response.json();
})
.then(data => {
+ // Cache the search engine data
+ cacheData(CACHE_KEYS.SEARCH_ENGINES, data);
+
+ // Process the data
+ processSearchEngineData(data);
+
+ // Reset the refresh button
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.remove('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';
+ }
+ })
+ .catch(error => {
+ console.error('Error loading search settings:', error);
+ // Default to Auto on error
+ searchEngineInput.value = 'Auto (Default)';
+ selectedSearchEngineValue = 'auto';
+
+ // Reset the refresh button
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.remove('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';
+ }
+ });
+ }
+
+ /**
+ * Process search engine data from API or cache
+ * @param {Object} data - The search engine data from API or cache
+ */
+ function processSearchEngineData(data) {
if (data.engine_options && data.engine_options.length > 0) {
// Build options list with Auto first
let engineOptions = [];
@@ -871,23 +1064,60 @@
searchEngineOptions = engineOptions;
}
+ // Store this in localStorage to avoid any issues
+ window.localStorage.setItem('defaultSearchEngine', 'auto');
+
// FORCE set to Auto one more time to avoid issues
searchEngineInput.value = 'Auto (Default)';
selectedSearchEngineValue = 'auto';
+ }
- // Skip loading settings as we always want Auto
- return Promise.resolve({
- settings: {
- 'search.tool': 'auto'
- }
- });
- })
- .catch(error => {
- console.error('Error loading search settings:', error);
- // Default to Auto on error
- searchEngineInput.value = 'Auto (Default)';
- selectedSearchEngineValue = 'auto';
- });
+ /**
+ * Cache data in localStorage with timestamp
+ * @param {string} key - The key to store data under
+ * @param {any} data - The data to store
+ */
+ function cacheData(key, data) {
+ try {
+ // Don't cache null or undefined data
+ if (data === null || data === undefined) {
+ console.warn(`Not caching null or undefined data for key: ${key}`);
+ return;
+ }
+
+ // Store the data
+ localStorage.setItem(key, JSON.stringify(data));
+
+ // Store timestamp for cache expiration
+ const timestamps = JSON.parse(localStorage.getItem('cache_timestamps') || '{}');
+ timestamps[key] = Date.now();
+ localStorage.setItem('cache_timestamps', JSON.stringify(timestamps));
+
+ console.log(`Cached data for key: ${key}`);
+ } catch (error) {
+ console.error(`Error caching data for key ${key}:`, error);
+ }
+ }
+
+ /**
+ * Get cached data if it exists and is not expired
+ * @param {string} key - The cache key
+ * @returns {Object|null} The cached data or null if not found or expired
+ */
+ function getCachedData(key) {
+ try {
+ const cachedData = localStorage.getItem(key);
+
+ // Check if data exists before parsing
+ if (cachedData === null || cachedData === undefined || cachedData === 'undefined') {
+ return null;
+ }
+
+ return JSON.parse(cachedData);
+ } catch (error) {
+ console.error('Error getting cached data:', error);
+ return null;
+ }
}
/**
@@ -899,30 +1129,194 @@
if (questionsPerIterationInput) questionsPerIterationInput.value = 3;
if (notificationToggle) notificationToggle.checked = true;
- // Try to load app settings - FIXED PATH
- fetch('/research/settings/api?type=app')
+ // Check for localStorage settings (for backward compatibility)
+ const storedProvider = window.localStorage.getItem('lastUsedModelProvider');
+ const storedModel = window.localStorage.getItem('lastUsedModel');
+ const storedSearchEngine = window.localStorage.getItem('lastUsedSearchEngine');
+
+ // Try to load stored values
+ if (storedProvider && modelProviderSelect) {
+ modelProviderSelect.value = storedProvider;
+ }
+
+ // Try to load app settings from database
+ fetch('/research/settings/api/llm.provider')
.then(response => {
if (!response.ok) throw new Error(`API returned ${response.status}`);
return response.json();
})
.then(data => {
- if (data?.settings) {
- if (iterationsInput && data.settings['app.research_iterations'] !== undefined) {
- iterationsInput.value = data.settings['app.research_iterations'];
- }
+ if (data && data.setting && data.setting.value) {
+ const provider = data.setting.value;
+ console.log('Loaded provider from settings DB:', provider);
- if (questionsPerIterationInput && data.settings['app.questions_per_iteration'] !== undefined) {
- questionsPerIterationInput.value = data.settings['app.questions_per_iteration'];
- }
+ // Set the provider in the dropdown
+ if (modelProviderSelect) {
+ modelProviderSelect.value = provider;
+
+ // Show/hide custom endpoint based on provider
+ if (endpointContainer) {
+ endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ }
- if (notificationToggle && data.settings['app.enable_notifications'] !== undefined) {
- notificationToggle.checked = data.settings['app.enable_notifications'];
+ // Update model options for this provider
+ updateModelOptionsForProvider(provider, false);
}
+
+ // Now load the model
+ fetch('/research/settings/api/llm.model')
+ .then(response => {
+ if (!response.ok) throw new Error(`API returned ${response.status}`);
+ return response.json();
+ })
+ .then(modelData => {
+ if (modelData && modelData.setting && modelData.setting.value) {
+ const model = modelData.setting.value;
+ console.log('Loaded model from settings DB:', model);
+
+ // Set the model in the input
+ if (modelInput) {
+ modelInput.value = model;
+ selectedModelValue = model;
+
+ // Also update the hidden input if available
+ const hiddenInput = document.getElementById('model_hidden');
+ if (hiddenInput) {
+ hiddenInput.value = model;
+ }
+ }
+ } else if (storedModel && modelInput) {
+ // Fallback to localStorage
+ modelInput.value = storedModel;
+ selectedModelValue = storedModel;
+ }
+ })
+ .catch(error => {
+ console.error('Error loading model from settings:', error);
+ if (storedModel && modelInput) {
+ // Fallback to localStorage
+ modelInput.value = storedModel;
+ selectedModelValue = storedModel;
+ }
+ });
}
})
.catch(error => {
- console.error('Error loading app settings:', error);
+ console.error('Error loading settings:', error);
+ // Use localStorage fallback if available
+ if (storedProvider && modelProviderSelect) {
+ modelProviderSelect.value = storedProvider;
+
+ // Show/hide custom endpoint based on provider
+ if (endpointContainer) {
+ endpointContainer.style.display = storedProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ }
+
+ // Update model options for this provider
+ updateModelOptionsForProvider(storedProvider, false);
+ }
+
+ if (storedModel && modelInput) {
+ modelInput.value = storedModel;
+ selectedModelValue = storedModel;
+ }
+ });
+
+ // Also set search engine if available in localStorage
+ if (storedSearchEngine && searchEngineInput) {
+ // This will be updated when the search engine options are loaded
+ selectedSearchEngineValue = storedSearchEngine;
+ }
+ }
+
+ /**
+ * Populate the model dropdown with options filtered by provider
+ * @param {string} provider - The selected model provider
+ */
+ function populateModelDropdown(provider) {
+ // Find the input and dropdown elements
+ const modelInput = document.getElementById('model');
+ const modelDropdownList = document.getElementById('model-dropdown-list');
+
+ // If elements not found, try to look for them with llm- prefix (settings form uses this)
+ const inputElement = modelInput || document.getElementById('llm-model');
+ const dropdownElement = modelDropdownList || document.getElementById('llm-model-dropdown-list');
+
+ // If we still can't find them, exit
+ if (!inputElement || !dropdownElement) {
+ console.warn('Model dropdown elements not found');
+ return;
+ }
+
+ // Clear existing options
+ dropdownElement.innerHTML = '';
+
+ // Get all models from cache
+ const allModels = getCachedData('deepResearch.availableModels') || [];
+
+ console.log(`Populating model dropdown for provider: ${provider} with ${allModels.length} models`);
+
+ // Filter models by provider
+ let filteredModels = [];
+
+ if (Array.isArray(allModels)) {
+ filteredModels = allModels.filter(model => {
+ if (!model || typeof model !== 'object') return false;
+
+ const modelProvider = model.provider || '';
+
+ if (provider === 'OLLAMA') {
+ return modelProvider.toUpperCase() === 'OLLAMA';
+ } else if (provider === 'OPENAI') {
+ return modelProvider.toUpperCase() === 'OPENAI';
+ } else if (provider === 'ANTHROPIC') {
+ return modelProvider.toUpperCase() === 'ANTHROPIC';
+ } else if (provider === 'OPENAI_ENDPOINT') {
+ // For custom endpoints, show OpenAI models as examples
+ return modelProvider.toUpperCase() === 'OPENAI' || modelProvider.toUpperCase() === 'ANTHROPIC';
+ }
+
+ // If no provider selected or unrecognized, show all models
+ return true;
});
+ }
+
+ console.log(`Filtered to ${filteredModels.length} models for provider ${provider}`);
+
+ // Add models to dropdown
+ if (filteredModels.length === 0) {
+ // Add placeholder if no models available
+ const noOptions = document.createElement('div');
+ noOptions.className = 'custom-dropdown-item no-results';
+ noOptions.textContent = provider === 'OLLAMA' ?
+ 'No Ollama models found. Is Ollama running?' :
+ 'No models available. Type to enter a custom model name.';
+ dropdownElement.appendChild(noOptions);
+ } else {
+ // Add available models
+ filteredModels.forEach(model => {
+ const option = document.createElement('div');
+ option.className = 'custom-dropdown-item';
+ option.dataset.value = model.id || '';
+ option.textContent = model.name || model.id || '';
+
+ option.addEventListener('click', () => {
+ inputElement.value = model.id || '';
+ dropdownElement.style.display = 'none';
+ // Trigger change event
+ inputElement.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+
+ dropdownElement.appendChild(option);
+ });
+ }
+ }
+
+ /**
+ * Get CSRF token from meta tag
+ */
+ function getCsrfToken() {
+ return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
}
// Initialize on DOM content loaded
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index fef44865cb..cab892e347 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -28,6 +28,16 @@
let saveTimers = {};
let pendingSaveData = {};
+ // Cache keys - same as research.js for shared caching
+ const CACHE_KEYS = {
+ MODELS: 'deepResearch.availableModels',
+ SEARCH_ENGINES: 'deepResearch.searchEngines',
+ CACHE_TIMESTAMP: 'deepResearch.cacheTimestamp'
+ };
+
+ // Cache expiration time (24 hours in milliseconds)
+ const CACHE_EXPIRATION = 24 * 60 * 60 * 1000;
+
/**
* Initialize the settings component
*/
@@ -156,6 +166,77 @@
// Initialize specific settings page form handlers
initSpecificSettingsForm();
+
+ // Also add refresh button handlers
+ setupRefreshButtons();
+
+ // Initialize dropdown menus
+ initializeModelDropdowns();
+ initializeSearchEngineDropdowns();
+ }
+
+ /**
+ * Set up refresh button handlers
+ */
+ function setupRefreshButtons() {
+ // Look for any refresh buttons for model dropdowns
+ const modelRefreshBtn = document.getElementById('llm-model-refresh');
+ if (modelRefreshBtn) {
+ modelRefreshBtn.addEventListener('click', function() {
+ fetchModelProviders(true);
+ });
+ }
+
+ // Look for any refresh buttons for search engine dropdowns
+ const searchEngineRefreshBtn = document.getElementById('search-tool-refresh');
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.addEventListener('click', function() {
+ fetchSearchEngines(true);
+ });
+ }
+ }
+
+ /**
+ * Cache data in localStorage with timestamp
+ * @param {string} key - The cache key
+ * @param {Object} data - The data to cache
+ */
+ function cacheData(key, data) {
+ try {
+ // Store the data
+ localStorage.setItem(key, JSON.stringify(data));
+
+ // Update or set the timestamp
+ let timestamps = JSON.parse(localStorage.getItem(CACHE_KEYS.CACHE_TIMESTAMP) || '{}');
+ timestamps[key] = Date.now();
+ localStorage.setItem(CACHE_KEYS.CACHE_TIMESTAMP, JSON.stringify(timestamps));
+
+ console.log(`Cached data for ${key}`);
+ } catch (error) {
+ console.error('Error caching data:', error);
+ }
+ }
+
+ /**
+ * Get cached data if it exists and is not expired
+ * @param {string} key - The cache key
+ * @returns {Object|null} The cached data or null if not found or expired
+ */
+ function getCachedData(key) {
+ try {
+ // Get timestamps
+ const timestamps = JSON.parse(localStorage.getItem(CACHE_KEYS.CACHE_TIMESTAMP) || '{}');
+ const timestamp = timestamps[key];
+
+ // Check if data exists and is not expired
+ if (timestamp && (Date.now() - timestamp < CACHE_EXPIRATION)) {
+ const data = JSON.parse(localStorage.getItem(key));
+ return data;
+ }
+ } catch (error) {
+ console.error('Error getting cached data:', error);
+ }
+ return null;
}
/**
@@ -2444,156 +2525,258 @@
});
}
+ /**
+ * Check if Ollama service is running
+ * @returns {Promise<boolean>} True if Ollama is running
+ */
+ async function isOllamaRunning() {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
+
+ const response = await fetch('/research/settings/api/ollama-status', {
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ if (response.ok) {
+ const data = await response.json();
+ return data.running === true;
+ }
+ return false;
+ } catch (error) {
+ console.error('Ollama check failed:', error.name === 'AbortError' ? 'Request timed out' : error);
+ return false;
+ }
+ }
+
/**
* Fetch available model providers from API
+ * @param {boolean} forceRefresh - Force refresh even if cached data exists
*/
- function fetchModelProviders() {
- fetch('/research/settings/api/available-models')
- .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))
- .then(data => {
- // Process models from API
- if (data.provider_options) {
- modelOptions = data.provider_options;
+ function fetchModelProviders(forceRefresh = false) {
+ return new Promise((resolve, reject) => {
+ const cachedData = getCachedData('deepResearch.modelProviders');
+ if (!forceRefresh && cachedData) {
+ resolve(cachedData);
+ return;
+ }
- // Check for Ollama models
- if (data.providers && data.providers.ollama_models && data.providers.ollama_models.length > 0) {
- modelOptions = [...modelOptions, ...data.providers.ollama_models];
+ fetch('/research/settings/api/available-models')
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
}
- }
+ return response.json();
+ })
+ .then(data => {
+ if (data && data.providers) {
+ cacheData('deepResearch.modelProviders', data);
+ resolve(data);
+ } else {
+ reject(new Error('Invalid data format'));
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching model providers:', error);
+ // Return a default if we have cached data at least
+ if (cachedData) {
+ resolve(cachedData);
+ } else {
+ // Provide a fallback with common providers
+ const fallbackData = {
+ providers: [
+ { id: 'OLLAMA', name: 'Ollama (Local)', available: false },
+ { id: 'OPENAI', name: 'OpenAI API', available: true },
+ { id: 'ANTHROPIC', name: 'Anthropic API', available: true },
+ { id: 'OPENAI_ENDPOINT', name: 'OpenAI-compatible Endpoint', available: true }
+ ],
+ models: []
+ };
+ cacheData('deepResearch.modelProviders', fallbackData);
+ resolve(fallbackData);
+ }
+ });
+ });
+ }
- // Initialize model dropdowns if on the LLM tab
- if (activeTab === 'llm' || activeTab === 'all') {
- initializeModelDropdowns();
- }
- })
- .catch(error => console.error('Error loading models:', error));
+ /**
+ * Process model data from API or cache
+ * @param {Object} data - The model data
+ */
+ function processModelData(data) {
+ console.log('Processing model data:', data);
+
+ // Process models from API
+ if (data.provider_options) {
+ console.log('Found provider options:', data.provider_options);
+ modelOptions = data.provider_options;
+
+ // Check for Ollama models
+ if (data.providers && data.providers.ollama_models && data.providers.ollama_models.length > 0) {
+ // Add models with provider info
+ const ollama_models = data.providers.ollama_models;
+ console.log('Found Ollama models:', ollama_models);
+ modelOptions = [...modelOptions, ...ollama_models];
+ }
+
+ // Add OpenAI models if available
+ if (data.providers && data.providers.openai_models && data.providers.openai_models.length > 0) {
+ const openai_models = data.providers.openai_models;
+ console.log('Found OpenAI models:', openai_models);
+ modelOptions = [...modelOptions, ...openai_models];
+ }
+
+ // Add Anthropic models if available
+ if (data.providers && data.providers.anthropic_models && data.providers.anthropic_models.length > 0) {
+ const anthropic_models = data.providers.anthropic_models;
+ console.log('Found Anthropic models:', anthropic_models);
+ modelOptions = [...modelOptions, ...anthropic_models];
+ }
+ }
+
+ console.log('Final modelOptions:', modelOptions);
+
+ // Initialize model dropdowns if on the LLM tab
+ if (activeTab === 'llm' || activeTab === 'all') {
+ initializeModelDropdowns();
+ }
}
/**
* Fetch available search engines from API
+ * @param {boolean} forceRefresh - Force refresh even if cached data exists
*/
- function fetchSearchEngines() {
+ function fetchSearchEngines(forceRefresh = false) {
+ // Show loading state for any search engine refresh buttons
+ const searchEngineRefreshBtn = document.getElementById('search-tool-refresh');
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.add('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-spinner';
+ }
+
+ // Try to get from cache first if not forcing refresh
+ if (!forceRefresh) {
+ const cachedEngines = getCachedData(CACHE_KEYS.SEARCH_ENGINES);
+ if (cachedEngines) {
+ console.log('Using cached search engine data');
+ processSearchEngineData(cachedEngines);
+ return;
+ }
+ }
+
fetch('/research/settings/api/available-search-engines')
.then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))
.then(data => {
- if (data.engine_options && data.engine_options.length > 0) {
- searchEngineOptions = data.engine_options;
+ // Cache the data
+ cacheData(CACHE_KEYS.SEARCH_ENGINES, data);
- // Initialize search engine dropdowns if on the right tab
- if (activeTab === 'search' || activeTab === 'all') {
- initializeSearchEngineDropdowns();
- }
+ // Process the data
+ processSearchEngineData(data);
+
+ // Reset the refresh button
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.remove('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';
}
})
- .catch(error => console.error('Error loading search engines:', error));
+ .catch(error => {
+ console.error('Error loading search engines:', error);
+
+ // Reset the refresh button
+ if (searchEngineRefreshBtn) {
+ searchEngineRefreshBtn.classList.remove('loading');
+ searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';
+ }
+ });
}
/**
- * Initialize custom model dropdowns in the LLM section
+ * Process search engine data from API or cache
+ * @param {Object} data - The search engine data
*/
- function initializeModelDropdowns() {
- // Check for the model input field in the LLM section
- const modelInput = document.getElementById('llm-model');
- const providerInput = document.getElementById('llm-provider');
+ function processSearchEngineData(data) {
+ if (data.engine_options && data.engine_options.length > 0) {
+ searchEngineOptions = data.engine_options;
- if (modelInput) {
- // Create a dropdown for the model field
- const dropdownId = 'model-dropdown';
- const dropdownListId = `${dropdownId}-list`;
+ // Initialize search engine dropdowns if on the right tab
+ if (activeTab === 'search' || activeTab === 'all') {
+ initializeSearchEngineDropdowns();
+ }
+ }
+ }
- // Create dropdown container if it doesn't exist
- let dropdownContainer = modelInput.closest('.custom-dropdown');
- if (!dropdownContainer) {
- // Create custom dropdown container
- dropdownContainer = document.createElement('div');
- dropdownContainer.className = 'custom-dropdown';
- dropdownContainer.id = dropdownId;
+ /**
+ * Initialize custom model dropdowns in the LLM section
+ */
+ function initializeModelDropdowns() {
+ // Get all custom dropdowns for model providers and models
+ const providerDropdown = document.querySelector('#llm-provider');
+ const modelDropdown = document.querySelector('#llm-model');
+
+ if (!providerDropdown && !modelDropdown) {
+ // Check for settings form format with the correct name attributes
+ const settingsProviderInput = document.querySelector('input[data-setting-key="llm.provider"]');
+ const settingsModelInput = document.querySelector('input[data-setting-key="llm.model"]');
+
+ // Also check for the hidden inputs
+ const providerHiddenInput = document.querySelector('#llm-provider_hidden');
+ const modelHiddenInput = document.querySelector('#llm-model_hidden');
+
+ if (!settingsProviderInput && !settingsModelInput && !providerHiddenInput && !modelHiddenInput) {
+ // No dropdowns found at all
+ console.log('No model dropdowns found');
+ return;
+ }
+ }
- // Create dropdown list element
- const dropdownList = document.createElement('div');
- dropdownList.className = 'custom-dropdown-list';
- dropdownList.id = dropdownListId;
+ // Get settings for the current provider
+ let currentProvider = '';
+ let currentModel = '';
- // Replace the input with the dropdown
- const parent = modelInput.parentNode;
- parent.insertBefore(dropdownContainer, modelInput);
- dropdownContainer.appendChild(modelInput);
- dropdownContainer.appendChild(dropdownList);
+ // Get values from settings database
+ const providerSetting = allSettings.find(s => s.key === 'llm.provider');
+ const modelSetting = allSettings.find(s => s.key === 'llm.model');
- // Add custom-dropdown-input class to the input
- modelInput.classList.add('custom-dropdown-input');
+ if (providerSetting) {
+ currentProvider = providerSetting.value || 'ollama';
+ }
- // Set up the dropdown
- if (window.setupCustomDropdown) {
- window.setupCustomDropdown(
- modelInput,
- dropdownList,
- () => modelOptions,
- (value, item) => {
- // Update the modelInput value
- modelInput.value = value;
- // Trigger a change event so the form knows it's changed
- modelInput.dispatchEvent(new Event('change', { bubbles: true }));
- },
- true, // Allow custom values
- 'No models available. Type to enter a custom model name.'
- );
- }
- }
+ if (modelSetting) {
+ currentModel = modelSetting.value || '';
}
- // Also handle the provider dropdown if present
- if (providerInput) {
- // Create a dropdown for the provider field
- const dropdownId = 'provider-dropdown';
- const dropdownListId = `${dropdownId}-list`;
+ // Check for provider dropdown in settings page format
+ const settingsProviderInput = document.querySelector('input[data-setting-key="llm.provider"]');
+ const providerHiddenInput = document.querySelector('#llm-provider_hidden');
- // Create dropdown container if it doesn't exist
- let dropdownContainer = providerInput.closest('.custom-dropdown');
- if (!dropdownContainer) {
- // Create custom dropdown container
- dropdownContainer = document.createElement('div');
- dropdownContainer.className = 'custom-dropdown';
- dropdownContainer.id = dropdownId;
+ // Check for model dropdown in settings page format
+ const settingsModelInput = document.querySelector('input[data-setting-key="llm.model"]');
+ const modelHiddenInput = document.querySelector('#llm-model_hidden');
- // Create dropdown list element
- const dropdownList = document.createElement('div');
- dropdownList.className = 'custom-dropdown-list';
- dropdownList.id = dropdownListId;
+ // Initialize hidden inputs with current values if they exist
+ if (providerHiddenInput && currentProvider) {
+ providerHiddenInput.value = currentProvider;
+ }
- // Replace the input with the dropdown
- const parent = providerInput.parentNode;
- parent.insertBefore(dropdownContainer, providerInput);
- dropdownContainer.appendChild(providerInput);
- dropdownContainer.appendChild(dropdownList);
+ if (modelHiddenInput && currentModel) {
+ modelHiddenInput.value = currentModel;
+ }
- // Add custom-dropdown-input class to the input
- providerInput.classList.add('custom-dropdown-input');
+ // Add an event listener for the model refresh button if it exists
+ const refreshBtn = document.querySelector('#llm-model-refresh');
+ if (refreshBtn) {
+ refreshBtn.addEventListener('click', () => {
+ loadModelOptions(true);
+ });
+ }
- // Filter only provider options
- const providerOptions = modelOptions.filter(opt =>
- opt.value && typeof opt.value === 'string' &&
- !opt.value.includes(':') && !opt.value.includes('/')
- );
+ // Initialize the UI with model data
+ loadModelOptions();
- // Set up the dropdown
- if (window.setupCustomDropdown) {
- window.setupCustomDropdown(
- providerInput,
- dropdownList,
- () => providerOptions,
- (value, item) => {
- // Update the providerInput value
- providerInput.value = value;
- // Trigger a change event so the form knows it's changed
- providerInput.dispatchEvent(new Event('change', { bubbles: true }));
- },
- false, // Don't allow custom values
- 'No providers available.'
- );
- }
- }
- }
+ // For settings page - set up custom settings dropdowns
+ setupCustomDropdowns();
}
/**
@@ -2799,6 +2982,13 @@
* @param {boolean} skipIfToastShown - Whether to skip showing this alert if a toast was already shown
*/
function showAlert(message, type, skipIfToastShown = true) {
+ // If window.ui.showAlert exists, use it
+ if (window.ui && window.ui.showAlert) {
+ window.ui.showAlert(message, type, skipIfToastShown);
+ return;
+ }
+
+ // Otherwise fallback to old implementation (this shouldn't happen once ui.js is loaded)
// If we're showing a toast and we want to skip the regular alert, just return
if (skipIfToastShown && window.ui && window.ui.showMessage) {
return;
@@ -2845,4 +3035,155 @@
}
}, 5000);
}
+
+ /**
+ * Set up custom dropdowns for settings
+ */
+ function setupCustomDropdowns() {
+ // Find all custom dropdowns in the settings form
+ const customDropdowns = document.querySelectorAll('.custom-dropdown');
+
+ // Process each dropdown
+ customDropdowns.forEach(dropdown => {
+ const dropdownInput = dropdown.querySelector('.custom-dropdown-input');
+ const dropdownList = dropdown.querySelector('.custom-dropdown-list');
+
+ if (!dropdownInput || !dropdownList) return;
+
+ // Get the setting key from the data attribute
+ const settingKey = dropdownInput.getAttribute('data-setting-key');
+ if (!settingKey) return;
+
+ // Get current setting value from settings
+ const currentSetting = allSettings.find(s => s.key === settingKey);
+ const currentValue = currentSetting ? currentSetting.value : '';
+
+ // Get the hidden input
+ const hiddenInput = document.getElementById(`${settingKey}_hidden`);
+
+ // Set up options source based on setting key
+ let optionsSource = [];
+ let allowCustom = false;
+
+ if (settingKey === 'llm.model') {
+ optionsSource = modelOptions;
+ allowCustom = true;
+ } else if (settingKey === 'llm.provider') {
+ // Special handling for provider dropdown
+ const availableProviders = allSettings.find(s => s.key === 'llm.provider');
+ optionsSource = availableProviders && availableProviders.options
+ ? availableProviders.options.map(opt => ({ value: opt.value, label: opt.label }))
+ : [
+ { value: 'ollama', label: 'Ollama (Local)' },
+ { value: 'openai', label: 'OpenAI API' },
+ { value: 'anthropic', label: 'Anthropic API' },
+ { value: 'openai_endpoint', label: 'Custom OpenAI Endpoint' }
+ ];
+ } else if (settingKey === 'search.tool') {
+ optionsSource = searchEngineOptions;
+ }
+
+ // Initialize the dropdown
+ if (window.setupCustomDropdown) {
+ const dropdown = window.setupCustomDropdown(
+ dropdownInput,
+ dropdownList,
+ () => optionsSource,
+ (value, item) => {
+ // When a value is selected, update the hidden input
+ if (hiddenInput) {
+ hiddenInput.value = value;
+ // Trigger change event to save the setting
+ const changeEvent = new Event('change', { bubbles: true });
+ hiddenInput.dispatchEvent(changeEvent);
+ }
+ },
+ allowCustom
+ );
+
+ // Set initial value
+ if (currentValue && dropdown.setValue) {
+ dropdown.setValue(currentValue, false); // Don't fire event on init
+ // Also set the hidden input
+ if (hiddenInput) {
+ hiddenInput.value = currentValue;
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Load model options for the dropdown
+ * @param {boolean} forceRefresh - Force refresh of model options
+ * @returns {Promise} Promise that resolves with model options
+ */
+ function loadModelOptions(forceRefresh = false) {
+ return new Promise((resolve, reject) => {
+ fetchModelProviders(forceRefresh)
+ .then(data => {
+ if (data && data.providers) {
+ // Process the data to format for dropdowns
+ const ollama_models = data.providers.ollama_models || [];
+ const openai_models = data.providers.openai_models || [];
+ const anthropic_models = data.providers.anthropic_models || [];
+
+ // Format the models for dropdown
+ const formatted_models = [];
+
+ // Add Ollama models
+ ollama_models.forEach(model => {
+ formatted_models.push({
+ value: model.value,
+ label: model.label
+ });
+ });
+
+ // Add OpenAI models
+ openai_models.forEach(model => {
+ formatted_models.push({
+ value: model.value,
+ label: model.label
+ });
+ });
+
+ // Add Anthropic models
+ anthropic_models.forEach(model => {
+ formatted_models.push({
+ value: model.value,
+ label: model.label
+ });
+ });
+
+ // Update global modelOptions
+ modelOptions = formatted_models;
+
+ // Update any existing dropdowns
+ setupCustomDropdowns();
+
+ resolve(formatted_models);
+ } else {
+ // Use defaults if no data
+ modelOptions = [
+ { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo (OpenAI)' },
+ { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet (Anthropic)' }
+ ];
+ setupCustomDropdowns();
+ resolve(modelOptions);
+ }
+ })
+ .catch(error => {
+ console.error('Error loading model options:', error);
+ // Fallback to defaults
+ modelOptions = [
+ { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo (OpenAI)' },
+ { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet (Anthropic)' }
+ ];
+ setupCustomDropdowns();
+ resolve(modelOptions);
+ });
+ });
+ }
})();
diff --git a/src/local_deep_research/web/templates/components/custom_dropdown.html b/src/local_deep_research/web/templates/components/custom_dropdown.html
index 319f0d6c96..6905c7c8a6 100644
--- a/src/local_deep_research/web/templates/components/custom_dropdown.html
+++ b/src/local_deep_research/web/templates/components/custom_dropdown.html
@@ -1,18 +1,45 @@
-{% macro render_dropdown(input_id, dropdown_id, placeholder, label=None, help_text=None, allow_custom=False) %}
+{% macro render_dropdown(input_id, dropdown_id, placeholder, label=None, help_text=None, allow_custom=False, show_refresh=False, refresh_aria_label="Refresh options") %}
<div class="form-group">
{% if label %}
<label for="{{ input_id }}">{{ label }}</label>
{% endif %}
+
+ {% if show_refresh %}
+ <div class="custom-dropdown-with-refresh">
+ <div class="custom-dropdown" id="{{ dropdown_id }}">
+ <input type="text"
+ id="{{ input_id }}"
+ data-setting-key="{{ input_id }}"
+ class="custom-dropdown-input"
+ placeholder="{{ placeholder }}"
+ autocomplete="off"
+ aria-haspopup="listbox">
+ <!-- Hidden input that will be included in form submission -->
+ <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="">
+ <div class="custom-dropdown-list" id="{{ dropdown_id }}-list"></div>
+ </div>
+ <button type="button"
+ class="custom-dropdown-refresh-btn"
+ id="{{ input_id }}-refresh"
+ aria-label="{{ refresh_aria_label }}">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ </div>
+ {% else %}
<div class="custom-dropdown" id="{{ dropdown_id }}">
<input type="text"
id="{{ input_id }}"
- name="{{ input_id }}"
+ data-setting-key="{{ input_id }}"
class="custom-dropdown-input"
placeholder="{{ placeholder }}"
autocomplete="off"
aria-haspopup="listbox">
+ <!-- Hidden input that will be included in form submission -->
+ <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="">
<div class="custom-dropdown-list" id="{{ dropdown_id }}-list"></div>
</div>
+ {% endif %}
+
{% if help_text %}
<span class="input-help">{{ help_text }}</span>
{% endif %}
diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.html
index 6beaefd7c6..bb4a05f8f0 100644
--- a/src/local_deep_research/web/templates/components/settings_form.html
+++ b/src/local_deep_research/web/templates/components/settings_form.html
@@ -87,21 +87,33 @@
{% endif %}
{% elif setting.ui_element == "select" %}
- <select
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="settings-select form-control"
- {% if not setting.editable %}disabled{% endif %}
- >
- {% for option in setting.options %}
- <option
- value="{{ option.value }}"
- {% if option.value == setting.value %}selected{% endif %}
- >
- {{ option.label if option.label else option.value }}
- </option>
- {% endfor %}
- </select>
+ {% if setting.key == "llm.provider" %}
+ {% from "components/custom_dropdown.html" import render_dropdown %}
+ {{ render_dropdown(
+ input_id=setting.key,
+ dropdown_id=setting_id + "-dropdown",
+ placeholder="Select a provider",
+ help_text=setting.description if setting.description else None,
+ allow_custom=False,
+ show_refresh=False
+ ) }}
+ {% else %}
+ <select
+ id="{{ setting_id }}"
+ name="{{ setting.key }}"
+ class="settings-select form-control"
+ {% if not setting.editable %}disabled{% endif %}
+ >
+ {% for option in setting.options %}
+ <option
+ value="{{ option.value }}"
+ {% if option.value == setting.value %}selected{% endif %}
+ >
+ {{ option.label if option.label else option.value }}
+ </option>
+ {% endfor %}
+ </select>
+ {% endif %}
{% elif setting.ui_element == "checkbox" %}
<div class="checkbox-label">
@@ -162,6 +174,19 @@
{% if not setting.editable %}disabled{% endif %}
>
+ {% elif setting.key == "llm.model" or setting.key == "search.tool" %}
+ {% from "components/custom_dropdown.html" import render_dropdown %}
+ {{ render_dropdown(
+ input_id=setting.key,
+ dropdown_id=setting_id + "-dropdown",
+ placeholder="Select or enter a value",
+ help_text=setting.description if setting.description else None,
+ allow_custom=setting.key == "llm.model",
+ show_refresh=setting.key == "llm.model",
+ refresh_aria_label="Refresh model list"
+ ) }}
+ <!-- Debug info: setting.key = {{ setting.key }}, setting_id = {{ setting_id }} -->
+
{% else %}
{% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
<div class="json-expanded-controls">
@@ -229,7 +254,7 @@
{% endif %}
{% endif %}
- {% if setting.description %}
+ {% if setting.description and setting.key != "llm.model" and setting.key != "search.tool" %}
<div class="input-help">{{ setting.description }}</div>
{% endif %}
</div>
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 50b1585701..87fa7e6a19 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -6,6 +6,7 @@
{% block title %}New Research - Deep Research System{% endblock %}
{% block extra_head %}
+<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/custom_dropdown.css') }}">
{% endblock %}
@@ -14,6 +15,8 @@
<div class="page-header">
<h1>Start New Research</h1>
</div>
+ <!-- Add the alert container -->
+ <div id="research-alert" class="settings-alert-container" style="display:none"></div>
<div class="card research-card">
<div class="card-content">
<form id="research-form">
@@ -75,7 +78,9 @@
dropdown_id="model-dropdown",
placeholder="Enter or select a model",
label="Language Model",
- help_text="Select or enter a custom model name"
+ help_text="Select or enter a custom model name",
+ show_refresh=True,
+ refresh_aria_label="Refresh model list"
) }}
</div>
@@ -86,7 +91,9 @@
dropdown_id="search-engine-dropdown",
placeholder="Select a search engine",
label="Search Engine",
- help_text="Select the search engine to use for research"
+ help_text="Select the search engine to use for research",
+ show_refresh=True,
+ refresh_aria_label="Refresh search engine list"
) }}
</div>
</div>