~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Refactor settings system: Consolidate settings UI and improve management
hashedviking7e3e5e22bbc7
diff --git a/fix_indentation.py b/fix_indentation.pynew file mode 100644index 0000000000..138f53d0b8--- /dev/null+++ b/fix_indentation.py@@ -0,0 +1,30 @@+import re++# Read the file+file_path = "src/local_deep_research/web/routes/settings_routes.py"+with open(file_path, "r") as f:+ content = f.read()++# Fix common indentation issues in try-except blocks+# Pattern 1: Find db_session = get_db_session() with incorrect indentation after try:+pattern1 = r"try:\s+db_session = get_db_session\(\)"+replacement1 = r"try:\n db_session = get_db_session()"+content = re.sub(pattern1, replacement1, content)++# Pattern 2: Find incorrect indentation in except blocks+pattern2 = r'return jsonify\({"setting": setting_data}\)\s+except Exception as e:'+replacement2 = r'return jsonify({"setting": setting_data})\n except Exception as e:'+content = re.sub(pattern2, replacement2, content)++# Look for other common patterns+pattern3 = (+ r'category_list = \[.*\]\s+return jsonify\({"categories": category_list}\)\s+except'+)+replacement3 = r'category_list = [c[0] for c in categories if c[0] is not None]\n\n return jsonify({"categories": category_list})\n except'+content = re.sub(pattern3, replacement3, content)++# Write back to file+with open(file_path, "w") as f:+ f.write(content)++print("Fixed indentation issues in", file_path)diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex fa1964fb7b..0baa0ca541 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -57,12 +57,10 @@ class AdvancedSearchSystem:self.strategy.set_progress_callback(callback)def analyze_topic(self, query: str) -> Dict:-"""Analyze a topic using the current strategy."""# Use the strategy to analyze the topicresult = self.strategy.analyze_topic(query)-# Update our attributes for backward compatibilityif hasattr(self.strategy, "questions_by_iteration"):self.questions_by_iteration = self.strategy.questions_by_iterationdiff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex edb4fd7a96..12a09a3a29 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -12,6 +12,7 @@ from flask import (url_for,)from flask_socketio import SocketIO+from flask_wtf.csrf import CSRFProtectfrom .models.database import init_db@@ -52,6 +53,11 @@ def create_app():# App configurationapp.config["SECRET_KEY"] = "deep-research-secret-key"+ # Initialize CSRF protection+ csrf = CSRFProtect(app)+ # Exempt Socket.IO from CSRF protection+ csrf.exempt("research.socket_io")+# Database configurationdb_path = os.path.abspath(os.path.join(@@ -149,14 +155,12 @@ def register_blueprints(app):# Import blueprintsfrom .routes.history_routes import history_bpfrom .routes.research_routes import research_bp- from .routes.settings_api import settings_api_bpfrom .routes.settings_routes import settings_bp# Register blueprintsapp.register_blueprint(research_bp)app.register_blueprint(history_bp, url_prefix="/research/api")app.register_blueprint(settings_bp)- app.register_blueprint(settings_api_bp, url_prefix="/research/api")# Configure settings paths# Import config inside the function to avoid circular dependenciesdiff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.pyindex 09686131fd..ec23f19eb9 100644--- a/src/local_deep_research/web/database/migrations.py+++ b/src/local_deep_research/web/database/migrations.py@@ -225,30 +225,36 @@ def setup_predefined_settings(db_session):# Define standard UI settings for Appapp_settings = [{- "key": "app.research_iterations",- "name": "Research Iterations",- "description": "Number of research cycles to perform",- "category": "app_parameters",- "ui_element": "number",- "min_value": 1,- "max_value": 5,- "value": 2,+ "key": "app.debug",+ "name": "Debug Mode",+ "description": "Enable debug mode for the web application",+ "category": "app_interface",+ "ui_element": "checkbox",+ "value": True,+ },+ {+ "key": "app.host",+ "name": "Web Host",+ "description": "Host address to bind the web server",+ "category": "app_interface",+ "ui_element": "text",+ "value": "0.0.0.0",},{- "key": "app.questions_per_iteration",- "name": "Questions Per Iteration",- "description": "Number of questions to generate per research cycle",- "category": "app_parameters",+ "key": "app.port",+ "name": "Web Port",+ "description": "Port for the web server",+ "category": "app_interface","ui_element": "number","min_value": 1,- "max_value": 10,- "value": 3,+ "max_value": 65535,+ "value": 5000,},{"key": "app.enable_notifications","name": "Enable Notifications","description": "Enable browser notifications for research events",- "category": "app_parameters",+ "category": "app_interface","ui_element": "checkbox","value": True,},@@ -265,8 +271,93 @@ def setup_predefined_settings(db_session):],"value": "dark",},+ {+ "key": "app.web_interface",+ "name": "Web Interface",+ "description": "Enable the web interface",+ "category": "app_interface",+ "ui_element": "checkbox",+ "value": True,+ },+ {+ "key": "app.enable_web",+ "name": "Enable Web Server",+ "description": "Enable the web server",+ "category": "app_interface",+ "ui_element": "checkbox",+ "value": True,+ },]+ # Update search settings with research-specific settings+ search_settings.extend(+ [+ {+ "key": "search.research_iterations",+ "name": "Research Iterations",+ "description": "Number of research cycles to perform",+ "category": "search_parameters",+ "ui_element": "number",+ "min_value": 1,+ "max_value": 5,+ "value": 2,+ },+ {+ "key": "search.questions_per_iteration",+ "name": "Questions Per Iteration",+ "description": "Number of questions to generate per research cycle",+ "category": "search_parameters",+ "ui_element": "number",+ "min_value": 1,+ "max_value": 10,+ "value": 3,+ },+ {+ "key": "search.searches_per_section",+ "name": "Searches Per Section",+ "description": "Number of searches to run per report section",+ "category": "search_parameters",+ "ui_element": "number",+ "min_value": 1,+ "max_value": 5,+ "value": 2,+ },+ {+ "key": "search.skip_relevance_filter",+ "name": "Skip Relevance Filter",+ "description": "Skip filtering search results for relevance",+ "category": "search_parameters",+ "ui_element": "checkbox",+ "value": False,+ },+ {+ "key": "search.safe_search",+ "name": "Safe Search",+ "description": "Enable safe search filtering",+ "category": "search_parameters",+ "ui_element": "checkbox",+ "value": True,+ },+ {+ "key": "search.search_language",+ "name": "Search Language",+ "description": "Language for search results",+ "category": "search_parameters",+ "ui_element": "select",+ "options": [+ {"value": "English", "label": "English"},+ {"value": "French", "label": "French"},+ {"value": "German", "label": "German"},+ {"value": "Spanish", "label": "Spanish"},+ {"value": "Italian", "label": "Italian"},+ {"value": "Japanese", "label": "Japanese"},+ {"value": "Chinese", "label": "Chinese"},+ ],+ "value": "English",+ },+ ]+ )+# Ensure these predefined settings exist in the database# This will update existing settings with the same keyall_settings = llm_settings + search_settings + report_settings + app_settingsdiff --git a/src/local_deep_research/web/routes/settings_api.py b/src/local_deep_research/web/routes/settings_api.pydeleted file mode 100644index b62c7e1159..0000000000--- a/src/local_deep_research/web/routes/settings_api.py+++ /dev/null@@ -1,538 +0,0 @@-import logging-from pathlib import Path--import requests-import toml-from flask import Blueprint, current_app, jsonify, request-from sqlalchemy.orm import Session--from ...config.config_files import get_config_dir-from ...config.llm_config import (- VALID_PROVIDERS,- get_available_providers,- is_ollama_available,- settings,-)-from ...web_search_engines.search_engine_factory import (- get_available_engines,-)-from ..database.models import Setting, SettingType-from ..services.settings_manager import SettingsManager--# Initialize logger-logger = logging.getLogger(__name__)--# Create a Blueprint for settings API-settings_api_bp = Blueprint("settings_api", __name__, url_prefix="/")---def get_db_session() -> Session:- """Get the database session from the app context"""- if hasattr(current_app, "db_session"):- return current_app.db_session- else:- return current_app.extensions["sqlalchemy"].session()---@settings_api_bp.route("/", methods=["GET"])-def get_all_settings():- """Get all settings"""- try:- # Get query parameters- setting_type = request.args.get("type")- category = request.args.get("category")-- # Create settings manager- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Get settings- if setting_type:- try:- setting_type_enum = SettingType[setting_type.upper()]- settings = settings_manager.get_all_settings(setting_type_enum)- except KeyError:- return jsonify({"error": f"Invalid setting type: {setting_type}"}), 400- else:- settings = settings_manager.get_all_settings()-- # Filter by category if requested- if category:- filtered_settings = {}- # Need to get all setting details to check category- db_settings = db_session.query(Setting).all()- category_keys = [s.key for s in db_settings if s.category == category]-- # Filter settings by keys- for key, value in settings.items():- if key in category_keys:- filtered_settings[key] = value-- settings = filtered_settings-- return jsonify({"settings": settings})- except Exception as e:- logger.error(f"Error getting settings: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/<path:key>", methods=["GET"])-def get_setting(key):- """Get a specific setting by key"""- try:- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Get setting- value = settings_manager.get_setting(key)- if value is None:- return jsonify({"error": f"Setting not found: {key}"}), 404-- # Get additional metadata from database- db_setting = db_session.query(Setting).filter(Setting.key == key).first()-- if db_setting:- # Return full setting details- setting_data = {- "key": db_setting.key,- "value": db_setting.value,- "type": db_setting.type.value,- "name": db_setting.name,- "description": db_setting.description,- "category": db_setting.category,- "ui_element": db_setting.ui_element,- "options": db_setting.options,- "min_value": db_setting.min_value,- "max_value": db_setting.max_value,- "step": db_setting.step,- "visible": db_setting.visible,- "editable": db_setting.editable,- }- else:- # Return minimal info- setting_data = {"key": key, "value": value}-- return jsonify({"setting": setting_data})- except Exception as e:- logger.error(f"Error getting setting {key}: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/<path:key>", methods=["PUT"])-def update_setting(key):- """Update a setting"""- try:- # Get request data- data = request.get_json()- if not data:- return jsonify({"error": "No data provided"}), 400-- value = data.get("value")- if value is None:- return jsonify({"error": "No value provided"}), 400-- # Get DB session and settings manager- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Check if setting exists- db_setting = db_session.query(Setting).filter(Setting.key == key).first()-- if db_setting:- # Check if setting is editable- if not db_setting.editable:- return jsonify({"error": f"Setting {key} is not editable"}), 403-- # Update setting- success = settings_manager.set_setting(key, value)- if success:- return jsonify({"message": f"Setting {key} updated successfully"})- else:- return jsonify({"error": f"Failed to update setting {key}"}), 500- else:- # Create new setting with default metadata- setting_dict = {- "key": key,- "value": value,- "name": key.split(".")[-1].replace("_", " ").title(),- "description": f"Setting for {key}",- }-- # Add additional metadata if provided- for field in [- "type",- "name",- "description",- "category",- "ui_element",- "options",- "min_value",- "max_value",- "step",- "visible",- "editable",- ]:- if field in data:- setting_dict[field] = data[field]-- # Create setting- db_setting = settings_manager.create_or_update_setting(setting_dict)-- if db_setting:- return (- jsonify(- {- "message": f"Setting {key} created successfully",- "setting": {- "key": db_setting.key,- "value": db_setting.value,- "type": db_setting.type.value,- "name": db_setting.name,- },- }- ),- 201,- )- else:- return jsonify({"error": f"Failed to create setting {key}"}), 500- except Exception as e:- logger.error(f"Error updating setting {key}: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/<path:key>", methods=["DELETE"])-def delete_setting(key):- """Delete a setting"""- try:- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Check if setting exists- db_setting = db_session.query(Setting).filter(Setting.key == key).first()- if not db_setting:- return jsonify({"error": f"Setting not found: {key}"}), 404-- # Delete setting- success = settings_manager.delete_setting(key)- if success:- return jsonify({"message": f"Setting {key} deleted successfully"})- else:- return jsonify({"error": f"Failed to delete setting {key}"}), 500- except Exception as e:- logger.error(f"Error deleting setting {key}: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/export", methods=["POST"])-def export_settings():- """Export settings to file"""- try:- data = request.get_json() or {}- setting_type_str = data.get("type")-- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Export settings- if setting_type_str:- try:- setting_type = SettingType[setting_type_str.upper()]- success = settings_manager.export_to_file(setting_type)- except KeyError:- return (- jsonify({"error": f"Invalid setting type: {setting_type_str}"}),- 400,- )- else:- success = settings_manager.export_to_file()-- if success:- return jsonify({"message": "Settings exported successfully"})- else:- return jsonify({"error": "Failed to export settings"}), 500- except Exception as e:- logger.error(f"Error exporting settings: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/import", methods=["POST"])-def import_settings():- """Import settings from file"""- try:- data = request.get_json() or {}- setting_type_str = data.get("type")-- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)-- # Import settings- if setting_type_str:- try:- setting_type = SettingType[setting_type_str.upper()]- success = settings_manager.import_from_file(setting_type)- except KeyError:- return (- jsonify({"error": f"Invalid setting type: {setting_type_str}"}),- 400,- )- else:- success = settings_manager.import_from_file()-- if success:- return jsonify({"message": "Settings imported successfully"})- else:- return jsonify({"error": "Failed to import settings"}), 500- except Exception as e:- logger.error(f"Error importing settings: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/categories", methods=["GET"])-def get_categories():- """Get all setting categories"""- try:- db_session = get_db_session()-- # Get all distinct categories- categories = db_session.query(Setting.category).distinct().all()- category_list = [c[0] for c in categories if c[0] is not None]-- return jsonify({"categories": category_list})- except Exception as e:- logger.error(f"Error getting categories: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/types", methods=["GET"])-def get_types():- """Get all setting types"""- try:- # Get all setting types- types = [t.value for t in SettingType]- return jsonify({"types": types})- except Exception as e:- logger.error(f"Error getting types: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/ui_elements", methods=["GET"])-def get_ui_elements():- """Get all UI element types"""- try:- # Define supported UI element types- ui_elements = [- "text",- "select",- "checkbox",- "slider",- "number",- "textarea",- "color",- "date",- "file",- "password",- ]-- return jsonify({"ui_elements": ui_elements})- except Exception as e:- logger.error(f"Error getting UI elements: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/available-models", methods=["GET"])-def get_available_models():- """Get available language models"""- try:- # Get available providers- providers = get_available_providers()-- # Add more Ollama models if available- if "ollama" in providers:- # Try to get Ollama models directly from Ollama API- try:- # Get the Ollama base URL from settings- base_url = settings.get(- "OLLAMA_BASE_URL",- settings.llm.get("ollama_base_url", "http://localhost:11434"),- )-- # Try to fetch available models from Ollama- response = requests.get(f"{base_url}/api/tags", timeout=3.0)- if response.status_code == 200:- ollama_data = response.json()- if "models" in ollama_data:- ollama_models = ollama_data["models"]- else:- # Older Ollama API versions might return a simpler structure- ollama_models = [- {"name": m} for m in ollama_data.get("models", [])- ]-- # Create a list of Ollama model options- ollama_model_options = []- for model in ollama_models:- model_name = model.get("name")- if model_name:- # Format label to be more readable- if ":" in model_name:- base_name, variant = model_name.split(":", 1)- label = f"{base_name.title()} {variant} (Ollama)"- else:- label = f"{model_name.title()} (Ollama)"-- ollama_model_options.append(- {"value": model_name, "label": label}- )-- # Add additional context to the response- providers["ollama_models"] = ollama_model_options-- except Exception as e:- logger.error(f"Error fetching Ollama models: {e}")- # Don't fail if we can't get Ollama models- providers["ollama_models"] = []-- # Prepare response data- models_info = {- "providers": providers,- "valid_providers": VALID_PROVIDERS,- "provider_options": [- {"value": key, "label": value} for key, value in providers.items()- ],- "ollama_available": is_ollama_available(),- }-- return jsonify(models_info)- except Exception as e:- logger.error(f"Error getting available models: {e}")- return jsonify({"error": str(e)}), 500---@settings_api_bp.route("/available-search-engines", methods=["GET"])-def get_available_search_engines():- """Get available search engines"""- try:- # First try to get engines from search_engines.toml file- engines_dict = get_engines_from_file()-- # If we got engines from file, use those- if engines_dict:- # Make sure searxng is included if it should be- if "searxng" not in engines_dict:- engines_dict["searxng"] = {- "display_name": "SearXNG (Self-hosted)",- "description": "Self-hosted metasearch engine",- "strengths": ["privacy", "customization", "no API key needed"],- }-- # Format as options for dropdown- engine_options = [- {- "value": key,- "label": engines_dict.get(key, {}).get("display_name", key),- }- for key in engines_dict.keys()- ]-- return jsonify({"engines": engines_dict, "engine_options": engine_options})-- # Fallback to factory function if file method failed- try:- # Get available engines- search_engines = get_available_engines(include_api_key_services=True)-- # Handle if search_engines is a list (not a dict)- if isinstance(search_engines, list):- # Convert to dict with engine name as key and display name as value- engines_dict = {- engine: engine.replace("_", " ").title()- for engine in search_engines- }- else:- engines_dict = search_engines-- # Make sure searxng is included- if "searxng" not in engines_dict:- engines_dict["searxng"] = "SearXNG (Self-hosted)"-- # Format as options for dropdown- engine_options = [- {- "value": key,- "label": (- value- if isinstance(value, str)- else key.replace("_", " ").title()- ),- }- for key, value in engines_dict.items()- ]-- return jsonify({"engines": engines_dict, "engine_options": engine_options})- except Exception as e:- # If both methods fail, return default engines with searxng- logger.error(f"Error getting available search engines from factory: {e}")-- # Use hardcoded defaults from search_engines.toml- defaults = {- "wikipedia": "Wikipedia",- "arxiv": "ArXiv Papers",- "pubmed": "PubMed Medical",- "github": "GitHub Code",- "searxng": "SearXNG (Self-hosted)",- "serpapi": "SerpAPI (Google)",- "google_pse": "Google PSE",- "auto": "Auto-select",- }-- engine_options = [- {"value": key, "label": value} for key, value in defaults.items()- ]-- return jsonify({"engines": defaults, "engine_options": engine_options})-- except Exception as e:- logger.error(f"Error getting available search engines: {e}")- return jsonify({"error": str(e)}), 500---def get_engines_from_file():- """Get available search engines directly from the toml file"""- try:- # Try to load from the actual config directory- config_dir = get_config_dir()- search_engines_file = config_dir / "config" / "search_engines.toml"-- # If file doesn't exist in user config, try the defaults- if not search_engines_file.exists():- # Look in the defaults folder instead- import inspect-- from ...defaults import search_engines-- # Get the path to the search_engines.toml file- module_path = inspect.getfile(search_engines)- default_file = Path(module_path)-- if default_file.exists() and default_file.suffix == ".toml":- search_engines_file = default_file-- # If we found a file, load it- if search_engines_file.exists():- data = toml.load(search_engines_file)-- # Filter out the metadata entries (like DEFAULT_SEARCH_ENGINE)- engines = {k: v for k, v in data.items() if isinstance(v, dict)}-- # Add display names for each engine- for key, engine in engines.items():- if "display_name" not in engine:- # Create a display name from the key- engine["display_name"] = key.replace("_", " ").title()-- return engines-- return None- except Exception as e:- logger.error(f"Error loading search engines from file: {e}")- return Nonediff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 8aeca9d269..2d2934002b 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1,11 +1,17 @@+import jsonimport loggingimport osimport platformimport subprocess+from datetime import datetime+from pathlib import Path+from typing import Any, Dict, Optional, Tuple, Union+import requestsimport tomlfrom flask import (Blueprint,+ Response,current_app,flash,jsonify,@@ -14,9 +20,24 @@ from flask import (request,url_for,)-+from flask_wtf.csrf import generate_csrf+from sqlalchemy import func+from sqlalchemy.orm import Session++from ...config.config_files import get_config_dir+from ...config.config_files import settings as dynaconf_settings+from ...config.llm_config import (+ VALID_PROVIDERS,+ get_available_providers,+ is_ollama_available,+ settings,+)+from ...web_search_engines.search_engine_factory import (+ get_available_engines,+)from ..database.models import Setting, SettingTypefrom ..services.settings_manager import SettingsManager+from ..database.migrations import setup_predefined_settings# Initialize loggerlogger = logging.getLogger(__name__)@@ -42,7 +63,7 @@ def set_config_paths(LOCAL_COLLECTIONS_FILE = local_collections_file-def get_db_session():+def get_db_session() -> Session:"""Get the database session from the app context"""if hasattr(current_app, "db_session"):return current_app.db_session@@ -50,247 +71,1024 @@ def get_db_session():return current_app.extensions["sqlalchemy"].session()+def validate_setting(setting: Setting, value: Any) -> Tuple[bool, Optional[str]]:+ """+ Validate a setting value based on its type and constraints.++ Args:+ setting: The Setting object to validate against+ value: The value to validate++ Returns:+ Tuple of (is_valid, error_message)+ """+ # Convert value based on UI element type+ if setting.ui_element == "checkbox":+ # Convert string representations of boolean to actual boolean+ if isinstance(value, str):+ value = value.lower() in ("true", "on", "yes", "1")+ elif setting.ui_element == "number" or setting.ui_element == "slider":+ try:+ value = float(value)+ except (ValueError, TypeError):+ return False, f"Value must be a number"++ # Check min/max constraints if defined+ if setting.min_value is not None and value < setting.min_value:+ return False, f"Value must be at least {setting.min_value}"+ if setting.max_value is not None and value > setting.max_value:+ return False, f"Value must be at most {setting.max_value}"+ elif setting.ui_element == "select":+ # Check if value is in the allowed options+ if setting.options:+ allowed_values = [opt.get("value") for opt in setting.options]+ if value not in allowed_values:+ return (+ False,+ f"Value must be one of: {', '.join(str(v) for v in allowed_values)}",+ )++ # All checks passed+ return True, None+++def get_all_settings_json():+ """Get all settings as a JSON-serializable dictionary++ Returns:+ List of setting dictionaries+ """+ db_session = get_db_session()+ settings_list = []++ # Get all settings+ settings = (+ db_session.query(Setting)+ .order_by(Setting.type, Setting.category, Setting.name)+ .all()+ )++ # Convert to dictionaries+ for setting in settings:+ # Ensure objects are properly serialized+ value = setting.value++ # Convert objects to properly formatted JSON strings for display+ if isinstance(value, (dict, list)) and value:+ try:+ # For frontend display, we'll keep objects as they are+ # The javascript will handle formatting them+ pass+ except Exception as e:+ logger.error(f"Error serializing setting {setting.key}: {e}")++ setting_dict = {+ "key": setting.key,+ "value": value,+ "type": setting.type.value if setting.type else None,+ "name": setting.name,+ "description": setting.description,+ "category": setting.category,+ "ui_element": setting.ui_element,+ "options": setting.options,+ "min_value": setting.min_value,+ "max_value": setting.max_value,+ "step": setting.step,+ "visible": setting.visible,+ "editable": setting.editable,+ }+ settings_list.append(setting_dict)++ return settings_list++@settings_bp.route("/", methods=["GET"])def settings_page():"""Main settings dashboard with links to specialized config pages"""return render_template("settings_dashboard.html")-@settings_bp.route("/llm", methods=["GET", "POST"])-def llm_settings():- """LLM settings page"""+@settings_bp.route("/save_all_settings", methods=["POST"])+def save_all_settings():+ """Handle saving all settings at once from the unified settings page"""db_session = get_db_session()settings_manager = SettingsManager.get_instance(db_session)- if request.method == "POST":- # Process form submission- try:- # Get form data- form_data = request.form-- # Update each setting- for key, value in form_data.items():- if key.startswith("llm."):- # Convert checkboxes to boolean- if value == "on":- value = True+ try:+ # Process JSON data+ form_data = request.get_json()+ if not form_data:+ return (+ jsonify({"status": "error", "message": "No settings data provided"}),+ 400,+ )++ # Track validation errors+ validation_errors = []+ settings_by_type = {}++ # Track changes for logging+ updated_settings = []+ created_settings = []++ # Store original values for better messaging+ original_values = {}++ # Update each setting+ for key, value in form_data.items():+ # Skip corrupted keys or empty strings as keys+ if not key or not isinstance(key, str) or key.strip() == "":+ continue++ # Get the original value+ current_setting = (+ db_session.query(Setting).filter(Setting.key == key).first()+ )+ if current_setting:+ original_values[key] = current_setting.value++ # Determine setting type and category+ setting_type = None+ if key.startswith("llm."):+ setting_type = SettingType.LLM+ category = "llm_general"+ if (+ "temperature" in key+ or "max_tokens" in key+ or "batch" in key+ or "layers" in key+ ):+ category = "llm_parameters"+ elif key.startswith("search."):+ setting_type = SettingType.SEARCH+ category = "search_general"+ if (+ "iterations" in key+ or "results" in key+ or "region" in key+ or "questions" in key+ or "section" in key+ ):+ category = "search_parameters"+ elif key.startswith("report."):+ setting_type = SettingType.REPORT+ category = "report_parameters"+ elif key.startswith("app."):+ setting_type = SettingType.APP+ category = "app_interface"+ else:+ # Skip keys without a known prefix+ logger.warning(f"Skipping setting with unknown type: {key}")+ continue++ # Special handling for corrupted or empty values+ if value == "[object Object]" or (+ isinstance(value, str) and value.strip() in ["{}", "[]", "{", "["]+ ):+ if key.startswith("report."):+ value = {}+ else:+ # Use default or null for other types+ if key == "llm.model":+ value = "gpt-3.5-turbo"+ elif key == "llm.provider":+ value = "openai"+ elif key == "search.tool":+ value = "auto"+ elif key in ["app.theme", "app.default_theme"]:+ value = "dark"+ else:+ value = None++ logger.warning(f"Corrected corrupted value for {key}: {value}")++ # Handle JSON string values (already parsed by JavaScript)+ if isinstance(value, (dict, list)):+ # Keep as is, already parsed+ pass+ # Handle string values that might be JSON+ elif isinstance(value, str) and (+ value.startswith("{") or value.startswith("[")+ ):+ try:+ # Try to parse the string as JSON+ value = json.loads(value)+ except json.JSONDecodeError:+ # If it fails to parse, keep as string+ pass++ if current_setting:+ # Validate the setting+ is_valid, error_message = validate_setting(current_setting, value)++ if is_valid:+ # Update category if different from our determination+ if category and current_setting.category != category:+ current_setting.category = category# Save the setting- settings_manager.set_setting(key, value)+ success = settings_manager.set_setting(key, value)+ if success:+ updated_settings.append(key)++ # Track settings by type for exporting+ if current_setting.type not in settings_by_type:+ settings_by_type[current_setting.type] = []+ settings_by_type[current_setting.type].append(current_setting)+ else:+ # Add to validation errors+ validation_errors.append(+ {+ "key": key,+ "name": current_setting.name,+ "error": error_message,+ }+ )+ else:+ # Create a new setting+ new_setting = {+ "key": key,+ "value": value,+ "type": setting_type.value.lower(),+ "name": key.split(".")[-1].replace("_", " ").title(),+ "description": f"Setting for {key}",+ "category": category,+ "ui_element": "text", # Default UI element+ }++ # Determine better UI element based on value type+ if isinstance(value, bool):+ new_setting["ui_element"] = "checkbox"+ elif isinstance(value, (int, float)) and not isinstance(value, bool):+ new_setting["ui_element"] = "number"+ elif isinstance(value, (dict, list)):+ new_setting["ui_element"] = "textarea"++ # Create the setting+ db_setting = settings_manager.create_or_update_setting(new_setting)++ if db_setting:+ created_settings.append(key)+ # Track settings by type for exporting+ if db_setting.type not in settings_by_type:+ settings_by_type[db_setting.type] = []+ settings_by_type[db_setting.type].append(db_setting)+ else:+ validation_errors.append(+ {+ "key": key,+ "name": new_setting["name"],+ "error": "Failed to create setting",+ }+ )++ # Report validation errors if any+ if validation_errors:+ return (+ jsonify(+ {+ "status": "error",+ "message": "Validation errors",+ "errors": validation_errors,+ }+ ),+ 400,+ )++ # Export settings to file for each type+ for setting_type in settings_by_type:+ settings_manager.export_to_file(setting_type)++ # Get all settings to return to the client for proper state update+ all_settings = []+ for setting in db_session.query(Setting).all():+ # Convert enum to string if present+ setting_type = setting.type+ if hasattr(setting_type, "value"):+ setting_type = setting_type.value++ all_settings.append(+ {+ "key": setting.key,+ "value": setting.value,+ "name": setting.name,+ "description": setting.description,+ "type": setting_type,+ "category": setting.category,+ "ui_element": setting.ui_element,+ "editable": setting.editable,+ "options": setting.options,+ }+ )++ # Customize the success message based on what changed+ success_message = ""+ if len(updated_settings) == 1:+ # For a single update, provide more specific info about what changed+ key = updated_settings[0]+ updated_setting = (+ db_session.query(Setting).filter(Setting.key == key).first()+ )+ name = (+ updated_setting.name+ if updated_setting+ else key.split(".")[-1].replace("_", " ").title()+ )++ # Format the message+ if key in original_values:+ old_value = original_values[key]+ new_value = updated_setting.value if updated_setting else None++ # If it's a boolean, use "enabled/disabled" language+ if isinstance(new_value, bool):+ state = "enabled" if new_value else "disabled"+ success_message = f"{name} {state}"+ else:+ # For non-boolean values+ if isinstance(new_value, (dict, list)):+ success_message = f"{name} updated"+ else:+ success_message = f"{name} updated"+ else:+ success_message = f"{name} updated"+ else:+ # Multiple settings or generic message+ success_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"++ return jsonify(+ {+ "status": "success",+ "message": success_message,+ "updated": updated_settings,+ "created": created_settings,+ "settings": all_settings,+ }+ )++ except Exception as e:+ logger.error(f"Error saving settings: {e}")+ return (+ jsonify({"status": "error", "message": f"Error saving settings: {str(e)}"}),+ 500,+ )- # Export settings to file as well- settings_manager.export_to_file(SettingType.LLM)- flash("LLM settings saved successfully", "success")+@settings_bp.route("/reset_to_defaults", methods=["POST"])+def reset_to_defaults():+ """Reset all settings to their default values"""+ db_session = get_db_session()++ try:+ # First, delete all existing settings to ensure clean state+ try:+ # Get count before deletion+ settings_count = db_session.query(Setting).count()+ logger.info(f"Deleting {settings_count} existing settings before reset")++ # Delete all settings+ db_session.query(Setting).delete()+ db_session.commit()+ logger.info("Successfully deleted all existing settings")except Exception as e:- logger.error(f"Error saving LLM settings: {e}")- flash(f"Error saving settings: {str(e)}", "error")+ logger.error(f"Error deleting existing settings: {e}")+ db_session.rollback()+ return (+ jsonify(+ {+ "status": "error",+ "message": f"Error cleaning existing settings: {str(e)}",+ }+ ),+ 500,+ )++ # Import default settings from files+ try:+ # Import default config files from the defaults directory+ from importlib.resources import files- return redirect(url_for("settings.llm_settings"))+ try:+ defaults_dir = files("local_deep_research.defaults")+ except ImportError:+ # Fallback for older Python versions+ from pkg_resources import resource_filename- # Get all LLM settings- settings = (- db_session.query(Setting)- .filter(Setting.type == SettingType.LLM)- .order_by(Setting.category, Setting.name)- .all()- )+ defaults_dir = Path(+ resource_filename("local_deep_research", "defaults")+ )- # Group settings by category- settings_by_category = {}- for setting in settings:- category = setting.category or "general"- if category not in settings_by_category:- settings_by_category[category] = []- settings_by_category[category].append(setting)+ logger.info(f"Loading defaults from: {defaults_dir}")- return render_template(- "llm_settings.html", settings_by_category=settings_by_category- )+ # Get temporary path to default files+ import shutil+ import tempfile+ with tempfile.TemporaryDirectory() as temp_dir:+ # Copy default files to temp directory+ temp_main = Path(temp_dir) / "settings.toml"+ temp_search = Path(temp_dir) / "search_engines.toml"+ temp_collections = Path(temp_dir) / "local_collections.toml"-@settings_bp.route("/search", methods=["GET", "POST"])-def search_settings():- """Search settings page"""- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)+ # Copy default files (platform independent)+ import importlib.resources as pkg_resources- if request.method == "POST":- # Process form submission- try:- # Get form data- form_data = request.form+ from ... import defaults- # Update each setting- for key, value in form_data.items():- if key.startswith("search."):- # Convert checkboxes to boolean- if value == "on":- value = True+ with open(temp_main, "wb") as f:+ f.write(pkg_resources.read_binary(defaults, "main.toml"))- # Save the setting- settings_manager.set_setting(key, value)+ with open(temp_search, "wb") as f:+ f.write(pkg_resources.read_binary(defaults, "search_engines.toml"))++ with open(temp_collections, "wb") as f:+ f.write(+ pkg_resources.read_binary(defaults, "local_collections.toml")+ )- # Export settings to file as well- settings_manager.export_to_file(SettingType.SEARCH)+ # Create settings manager with temp files+ from ...config.config_files import get_config_dir- flash("Search settings saved successfully", "success")+ orig_config_dir = get_config_dir() / "config"++ # Create settings manager for the temporary config+ settings_manager = SettingsManager(db_session)++ # Import settings from default files+ settings_manager.import_default_settings(+ temp_main, temp_search, temp_collections+ )++ logger.info("Successfully imported settings from default files")except Exception as e:- logger.error(f"Error saving search settings: {e}")- flash(f"Error saving settings: {str(e)}", "error")+ logger.error(f"Error importing default settings: {e}")- return redirect(url_for("settings.search_settings"))+ # Fallback to predefined settings if file import fails+ logger.info("Falling back to predefined settings")+ from ..database.migrations import setup_predefined_settings- # Get all search settings- settings = (- db_session.query(Setting)- .filter(Setting.type == SettingType.SEARCH)- .order_by(Setting.category, Setting.name)- .all()- )+ setup_predefined_settings(db_session)- # Group settings by category- settings_by_category = {}- for setting in settings:- category = setting.category or "general"- if category not in settings_by_category:- settings_by_category[category] = []- settings_by_category[category].append(setting)+ # Also export the settings to file for consistency+ settings_manager = SettingsManager.get_instance(db_session)+ for setting_type in SettingType:+ settings_manager.export_to_file(setting_type)- return render_template(- "search_settings.html", settings_by_category=settings_by_category- )+ # Return success+ return jsonify(+ {+ "status": "success",+ "message": "All settings have been reset to default values",+ }+ )+ except Exception as e:+ logger.error(f"Error resetting settings to defaults: {e}")+ return (+ jsonify(+ {+ "status": "error",+ "message": f"Error resetting settings to defaults: {str(e)}",+ }+ ),+ 500,+ )+++@settings_bp.route("/all_settings", methods=["GET"])+def get_all_settings_route():+ """Get all settings for the unified dashboard"""+ settings_list = get_all_settings_json()+ return jsonify({"status": "success", "settings": settings_list})+++# API Routes+@settings_bp.route("/api", methods=["GET"])+def api_get_all_settings():+ """Get all settings"""+ try:+ # Get query parameters+ setting_type = request.args.get("type")+ category = request.args.get("category")++ # Create settings manager+ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Get settings+ if setting_type:+ try:+ setting_type_enum = SettingType[setting_type.upper()]+ settings = settings_manager.get_all_settings(setting_type_enum)+ except KeyError:+ return jsonify({"error": f"Invalid setting type: {setting_type}"}), 400+ else:+ settings = settings_manager.get_all_settings()++ # Filter by category if requested+ if category:+ filtered_settings = {}+ # Need to get all setting details to check category+ db_settings = db_session.query(Setting).all()+ category_keys = [s.key for s in db_settings if s.category == category]++ # Filter settings by keys+ for key, value in settings.items():+ if key in category_keys:+ filtered_settings[key] = value++ settings = filtered_settings++ return jsonify({"settings": settings})+ except Exception as e:+ logger.error(f"Error getting settings: {e}")+ return jsonify({"error": str(e)}), 500-@settings_bp.route("/app", methods=["GET", "POST"])-def app_settings():- """Application settings page"""- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)- if request.method == "POST":- # Process form submission- try:- # Get form data- form_data = request.form+@settings_bp.route("/api/<path:key>", methods=["GET"])+def api_get_setting(key):+ """Get a specific setting by key"""+ try:+ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Get setting+ value = settings_manager.get_setting(key)+ if value is None:+ return jsonify({"error": f"Setting not found: {key}"}), 404++ # Get additional metadata from database+ db_setting = db_session.query(Setting).filter(Setting.key == key).first()++ if db_setting:+ # Return full setting details+ setting_data = {+ "key": db_setting.key,+ "value": db_setting.value,+ "type": db_setting.type.value,+ "name": db_setting.name,+ "description": db_setting.description,+ "category": db_setting.category,+ "ui_element": db_setting.ui_element,+ "options": db_setting.options,+ "min_value": db_setting.min_value,+ "max_value": db_setting.max_value,+ "step": db_setting.step,+ "visible": db_setting.visible,+ "editable": db_setting.editable,+ }+ else:+ # Return minimal info+ setting_data = {"key": key, "value": value}++ return jsonify({"setting": setting_data})+ except Exception as e:+ logger.error(f"Error getting setting {key}: {e}")+ return jsonify({"error": str(e)}), 500- # Update each setting- for key, value in form_data.items():- if key.startswith("app."):- # Convert checkboxes to boolean- if value == "on":- value = True- # Save the setting- settings_manager.set_setting(key, value)+@settings_bp.route("/api/<path:key>", methods=["PUT"])+def api_update_setting(key):+ """Update a setting"""+ try:+ # Get request data+ data = request.get_json()+ if not data:+ return jsonify({"error": "No data provided"}), 400++ value = data.get("value")+ if value is None:+ return jsonify({"error": "No value provided"}), 400++ # Get DB session and settings manager+ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Check if setting exists+ db_setting = db_session.query(Setting).filter(Setting.key == key).first()++ if db_setting:+ # Check if setting is editable+ if not db_setting.editable:+ return jsonify({"error": f"Setting {key} is not editable"}), 403++ # Update setting+ success = settings_manager.set_setting(key, value)+ if success:+ return jsonify({"message": f"Setting {key} updated successfully"})+ else:+ return jsonify({"error": f"Failed to update setting {key}"}), 500+ else:+ # Create new setting with default metadata+ setting_dict = {+ "key": key,+ "value": value,+ "name": key.split(".")[-1].replace("_", " ").title(),+ "description": f"Setting for {key}",+ }++ # Add additional metadata if provided+ for field in [+ "type",+ "name",+ "description",+ "category",+ "ui_element",+ "options",+ "min_value",+ "max_value",+ "step",+ "visible",+ "editable",+ ]:+ if field in data:+ setting_dict[field] = data[field]++ # Create setting+ db_setting = settings_manager.create_or_update_setting(setting_dict)++ if db_setting:+ return (+ jsonify(+ {+ "message": f"Setting {key} created successfully",+ "setting": {+ "key": db_setting.key,+ "value": db_setting.value,+ "type": db_setting.type.value,+ "name": db_setting.name,+ },+ }+ ),+ 201,+ )+ else:+ return jsonify({"error": f"Failed to create setting {key}"}), 500+ except Exception as e:+ logger.error(f"Error updating setting {key}: {e}")+ return jsonify({"error": str(e)}), 500- # Export settings to file as well- settings_manager.export_to_file(SettingType.APP)- flash("Application settings saved successfully", "success")- except Exception as e:- logger.error(f"Error saving application settings: {e}")- flash(f"Error saving settings: {str(e)}", "error")+@settings_bp.route("/api/<path:key>", methods=["DELETE"])+def api_delete_setting(key):+ """Delete a setting"""+ try:+ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Check if setting exists+ db_setting = db_session.query(Setting).filter(Setting.key == key).first()+ if not db_setting:+ return jsonify({"error": f"Setting not found: {key}"}), 404++ # Delete setting+ success = settings_manager.delete_setting(key)+ if success:+ return jsonify({"message": f"Setting {key} deleted successfully"})+ else:+ return jsonify({"error": f"Failed to delete setting {key}"}), 500+ except Exception as e:+ logger.error(f"Error deleting setting {key}: {e}")+ return jsonify({"error": str(e)}), 500- return redirect(url_for("settings.app_settings"))- # Get all app settings- settings = (- db_session.query(Setting)- .filter(Setting.type == SettingType.APP)- .order_by(Setting.category, Setting.name)- .all()- )+@settings_bp.route("/api/export", methods=["POST"])+def api_export_settings():+ """Export settings to file"""+ try:+ data = request.get_json() or {}+ setting_type_str = data.get("type")++ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Export settings+ if setting_type_str:+ try:+ setting_type = SettingType[setting_type_str.upper()]+ success = settings_manager.export_to_file(setting_type)+ except KeyError:+ return (+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),+ 400,+ )+ else:+ success = settings_manager.export_to_file()++ if success:+ return jsonify({"message": "Settings exported successfully"})+ else:+ return jsonify({"error": "Failed to export settings"}), 500+ except Exception as e:+ logger.error(f"Error exporting settings: {e}")+ return jsonify({"error": str(e)}), 500- # Group settings by category- settings_by_category = {}- for setting in settings:- category = setting.category or "general"- if category not in settings_by_category:- settings_by_category[category] = []- settings_by_category[category].append(setting)- return render_template(- "app_settings.html", settings_by_category=settings_by_category- )+@settings_bp.route("/api/import", methods=["POST"])+def api_import_settings():+ """Import settings from file"""+ try:+ data = request.get_json() or {}+ setting_type_str = data.get("type")++ db_session = get_db_session()+ settings_manager = SettingsManager.get_instance(db_session)++ # Import settings+ if setting_type_str:+ try:+ setting_type = SettingType[setting_type_str.upper()]+ success = settings_manager.import_from_file(setting_type)+ except KeyError:+ return (+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),+ 400,+ )+ else:+ success = settings_manager.import_from_file()++ if success:+ return jsonify({"message": "Settings imported successfully"})+ else:+ return jsonify({"error": "Failed to import settings"}), 500+ except Exception as e:+ logger.error(f"Error importing settings: {e}")+ return jsonify({"error": str(e)}), 500-@settings_bp.route("/report", methods=["GET", "POST"])-def report_settings():- """Report generation settings page"""- db_session = get_db_session()- settings_manager = SettingsManager.get_instance(db_session)+@settings_bp.route("/api/categories", methods=["GET"])+def api_get_categories():+ """Get all setting categories"""+ try:+ db_session = get_db_session()- if request.method == "POST":- # Process form submission- try:- # Get form data- form_data = request.form+ # Get all distinct categories+ categories = db_session.query(Setting.category).distinct().all()+ category_list = [c[0] for c in categories if c[0] is not None]- # Update each setting- for key, value in form_data.items():- if key.startswith("report."):- # Convert checkboxes to boolean- if value == "on":- value = True+ return jsonify({"categories": category_list})+ except Exception as e:+ logger.error(f"Error getting categories: {e}")+ return jsonify({"error": str(e)}), 500- # Save the setting- settings_manager.set_setting(key, value)- # Export settings to file as well- settings_manager.export_to_file(SettingType.REPORT)+@settings_bp.route("/api/types", methods=["GET"])+def api_get_types():+ """Get all setting types"""+ try:+ # Get all setting types+ types = [t.value for t in SettingType]+ return jsonify({"types": types})+ except Exception as e:+ logger.error(f"Error getting types: {e}")+ return jsonify({"error": str(e)}), 500+- flash("Report settings saved successfully", "success")+@settings_bp.route("/api/ui_elements", methods=["GET"])+def api_get_ui_elements():+ """Get all UI element types"""+ try:+ # Define supported UI element types+ ui_elements = [+ "text",+ "select",+ "checkbox",+ "slider",+ "number",+ "textarea",+ "color",+ "date",+ "file",+ "password",+ ]++ return jsonify({"ui_elements": ui_elements})+ except Exception as e:+ logger.error(f"Error getting UI elements: {e}")+ return jsonify({"error": str(e)}), 500+++@settings_bp.route("/api/available-models", methods=["GET"])+def api_get_available_models():+ """Get available language models"""+ try:+ # Get available providers+ providers = get_available_providers()++ # Add more Ollama models if available+ if "ollama" in providers:+ # Try to get Ollama models directly from Ollama API+ try:+ # Get the Ollama base URL from settings+ base_url = settings.get(+ "OLLAMA_BASE_URL",+ settings.llm.get("ollama_base_url", "http://localhost:11434"),+ )++ # Try to fetch available models from Ollama+ response = requests.get(f"{base_url}/api/tags", timeout=3.0)+ if response.status_code == 200:+ ollama_data = response.json()+ if "models" in ollama_data:+ ollama_models = ollama_data["models"]+ else:+ # Older Ollama API versions might return a simpler structure+ ollama_models = [+ {"name": m} for m in ollama_data.get("models", [])+ ]++ # Create a list of Ollama model options+ ollama_model_options = []+ for model in ollama_models:+ model_name = model.get("name")+ if model_name:+ # Format label to be more readable+ if ":" in model_name:+ base_name, variant = model_name.split(":", 1)+ label = f"{base_name.title()} {variant} (Ollama)"+ else:+ label = f"{model_name.title()} (Ollama)"++ ollama_model_options.append(+ {"value": model_name, "label": label}+ )++ # Add additional context to the response+ providers["ollama_models"] = ollama_model_options++ except Exception as e:+ logger.error(f"Error fetching Ollama models: {e}")+ # Don't fail if we can't get Ollama models+ providers["ollama_models"] = []++ # Prepare response data+ models_info = {+ "providers": providers,+ "valid_providers": VALID_PROVIDERS,+ "provider_options": [+ {"value": key, "label": value} for key, value in providers.items()+ ],+ "ollama_available": is_ollama_available(),+ }++ return jsonify(models_info)+ except Exception as e:+ logger.error(f"Error getting available models: {e}")+ return jsonify({"error": str(e)}), 500+++@settings_bp.route("/api/available-search-engines", methods=["GET"])+def api_get_available_search_engines():+ """Get available search engines"""+ try:+ # First try to get engines from search_engines.toml file+ engines_dict = get_engines_from_file()++ # If we got engines from file, use those+ if engines_dict:+ # Make sure searxng is included if it should be+ if "searxng" not in engines_dict:+ engines_dict["searxng"] = {+ "display_name": "SearXNG (Self-hosted)",+ "description": "Self-hosted metasearch engine",+ "strengths": ["privacy", "customization", "no API key needed"],+ }++ # Format as options for dropdown+ engine_options = [+ {+ "value": key,+ "label": engines_dict.get(key, {}).get("display_name", key),+ }+ for key in engines_dict.keys()+ ]++ return jsonify({"engines": engines_dict, "engine_options": engine_options})++ # Fallback to factory function if file method failed+ try:+ # Get available engines+ search_engines = get_available_engines(include_api_key_services=True)++ # Handle if search_engines is a list (not a dict)+ if isinstance(search_engines, list):+ # Convert to dict with engine name as key and display name as value+ engines_dict = {+ engine: engine.replace("_", " ").title()+ for engine in search_engines+ }+ else:+ engines_dict = search_engines++ # Make sure searxng is included+ if "searxng" not in engines_dict:+ engines_dict["searxng"] = "SearXNG (Self-hosted)"++ # Format as options for dropdown+ engine_options = [+ {+ "value": key,+ "label": (+ value+ if isinstance(value, str)+ else key.replace("_", " ").title()+ ),+ }+ for key, value in engines_dict.items()+ ]++ return jsonify({"engines": engines_dict, "engine_options": engine_options})except Exception as e:- logger.error(f"Error saving report settings: {e}")- flash(f"Error saving settings: {str(e)}", "error")+ # If both methods fail, return default engines with searxng+ logger.error(f"Error getting available search engines from factory: {e}")++ # Use hardcoded defaults from search_engines.toml+ defaults = {+ "wikipedia": "Wikipedia",+ "arxiv": "ArXiv Papers",+ "pubmed": "PubMed Medical",+ "github": "GitHub Code",+ "searxng": "SearXNG (Self-hosted)",+ "serpapi": "SerpAPI (Google)",+ "google_pse": "Google PSE",+ "auto": "Auto-select",+ }++ engine_options = [+ {"value": key, "label": value} for key, value in defaults.items()+ ]++ return jsonify({"engines": defaults, "engine_options": engine_options})+ except Exception as e:+ logger.error(f"Error getting available search engines: {e}")+ return jsonify({"error": str(e)}), 500- return redirect(url_for("settings.report_settings"))- # Get all report settings- settings = (- db_session.query(Setting)- .filter(Setting.type == SettingType.REPORT)- .order_by(Setting.category, Setting.name)- .all()- )+def get_engines_from_file():+ """Get available search engines directly from the toml file"""+ try:+ # Try to load from the actual config directory+ config_dir = get_config_dir()+ search_engines_file = config_dir / "config" / "search_engines.toml"- # Group settings by category- settings_by_category = {}- for setting in settings:- category = setting.category or "general"- if category not in settings_by_category:- settings_by_category[category] = []- settings_by_category[category].append(setting)+ # If file doesn't exist in user config, try the defaults+ if not search_engines_file.exists():+ # Look in the defaults folder instead+ import inspect- return render_template(- "report_settings.html", settings_by_category=settings_by_category- )+ from ...defaults import search_engines++ # Get the path to the search_engines.toml file+ module_path = inspect.getfile(search_engines)+ default_file = Path(module_path)++ if default_file.exists() and default_file.suffix == ".toml":+ search_engines_file = default_file++ # If we found a file, load it+ if search_engines_file.exists():+ data = toml.load(search_engines_file)++ # Filter out the metadata entries (like DEFAULT_SEARCH_ENGINE)+ engines = {k: v for k, v in data.items() if isinstance(v, dict)}++ # Add display names for each engine+ for key, engine in engines.items():+ if "display_name" not in engine:+ # Create a display name from the key+ engine["display_name"] = key.replace("_", " ").title()++ return engines++ return None+ except Exception as e:+ logger.error(f"Error loading search engines from file: {e}")+ return None# Legacy routes for backward compatibility - these will redirect to the new routes@settings_bp.route("/main", methods=["GET"])def main_config_page():"""Redirect to app settings page"""- return redirect(url_for("settings.app_settings"))+ return redirect(url_for("settings.settings_page"))@settings_bp.route("/collections", methods=["GET"])def collections_config_page():"""Redirect to app settings page"""- return redirect(url_for("settings.app_settings"))+ return redirect(url_for("settings.settings_page"))@settings_bp.route("/api_keys", methods=["GET"])def api_keys_config_page():"""Redirect to LLM settings page"""- return redirect(url_for("settings.llm_settings"))+ return redirect(url_for("settings.settings_page"))@settings_bp.route("/search_engines", methods=["GET"])def search_engines_config_page():"""Redirect to search settings page"""- return redirect(url_for("settings.search_settings"))+ return redirect(url_for("settings.settings_page"))@settings_bp.route("/open_file_location", methods=["POST"])@@ -320,3 +1118,314 @@ def open_file_location():# Redirect back to the settings pagereturn redirect(url_for("settings.settings_page"))+++@settings_bp.context_processor+def inject_csrf_token():+ """Inject CSRF token into the template context for all settings routes."""+ return dict(csrf_token=generate_csrf)+++@settings_bp.route("/fix_corrupted_settings", methods=["POST"])+def fix_corrupted_settings():+ """Fix corrupted settings in the database"""+ db_session = get_db_session()++ try:+ # Track fixed and removed settings+ fixed_settings = []+ removed_duplicate_settings = []+ fixed_scoping_issues = []++ # First, find and remove duplicate settings with the same key+ # This happens because of errors in settings import/export+ from sqlalchemy import func++ # Find keys with duplicates+ duplicate_keys = (+ db_session.query(Setting.key)+ .group_by(Setting.key)+ .having(func.count(Setting.key) > 1)+ .all()+ )+ duplicate_keys = [key[0] for key in duplicate_keys]++ # For each duplicate key, keep the latest updated one and remove others+ for key in duplicate_keys:+ dupe_settings = (+ db_session.query(Setting)+ .filter(Setting.key == key)+ .order_by(Setting.updated_at.desc())+ .all()+ )++ # Keep the first one (most recently updated) and delete the rest+ for i, setting in enumerate(dupe_settings):+ if i > 0: # Skip the first one (keep it)+ db_session.delete(setting)+ removed_duplicate_settings.append(key)++ # Fix scoping issues - remove app.* settings that should be in other categories+ # Report settings+ for key in [+ "app.enable_fact_checking",+ "app.knowledge_accumulation",+ "app.knowledge_accumulation_context_limit",+ "app.output_dir",+ ]:+ setting = db_session.query(Setting).filter(Setting.key == key).first()+ if setting:+ # Move to proper category if not already there+ proper_key = key.replace("app.", "report.")+ existing_proper = (+ db_session.query(Setting).filter(Setting.key == proper_key).first()+ )++ if not existing_proper:+ # Create proper setting+ new_setting = Setting(+ key=proper_key,+ value=setting.value,+ type=SettingType.REPORT,+ name=setting.name,+ description=setting.description,+ category=(+ setting.category.replace("app", "report")+ if setting.category+ else "report_parameters"+ ),+ ui_element=setting.ui_element,+ options=setting.options,+ min_value=setting.min_value,+ max_value=setting.max_value,+ step=setting.step,+ visible=setting.visible,+ editable=setting.editable,+ )+ db_session.add(new_setting)++ # Delete the app one+ db_session.delete(setting)+ fixed_scoping_issues.append(key)++ # Search settings+ for key in [+ "app.research_iterations",+ "app.questions_per_iteration",+ "app.search_engine",+ "app.iterations",+ "app.max_results",+ "app.region",+ "app.safe_search",+ "app.search_language",+ "app.snippets_only",+ ]:+ setting = db_session.query(Setting).filter(Setting.key == key).first()+ if setting:+ # Move to proper category if not already there+ proper_key = key.replace("app.", "search.")+ existing_proper = (+ db_session.query(Setting).filter(Setting.key == proper_key).first()+ )++ if not existing_proper:+ # Create proper setting+ new_setting = Setting(+ key=proper_key,+ value=setting.value,+ type=SettingType.SEARCH,+ name=setting.name,+ description=setting.description,+ category=(+ setting.category.replace("app", "search")+ if setting.category+ else "search_parameters"+ ),+ ui_element=setting.ui_element,+ options=setting.options,+ min_value=setting.min_value,+ max_value=setting.max_value,+ step=setting.step,+ visible=setting.visible,+ editable=setting.editable,+ )+ db_session.add(new_setting)++ # Delete the app one+ db_session.delete(setting)+ fixed_scoping_issues.append(key)++ # LLM settings+ for key in [+ "app.model",+ "app.provider",+ "app.temperature",+ "app.max_tokens",+ "app.openai_endpoint_url",+ "app.lmstudio_url",+ "app.llamacpp_model_path",+ ]:+ setting = db_session.query(Setting).filter(Setting.key == key).first()+ if setting:+ # Move to proper category if not already there+ proper_key = key.replace("app.", "llm.")+ existing_proper = (+ db_session.query(Setting).filter(Setting.key == proper_key).first()+ )++ if not existing_proper:+ # Create proper setting+ new_setting = Setting(+ key=proper_key,+ value=setting.value,+ type=SettingType.LLM,+ name=setting.name,+ description=setting.description,+ category=(+ setting.category.replace("app", "llm")+ if setting.category+ else "llm_parameters"+ ),+ ui_element=setting.ui_element,+ options=setting.options,+ min_value=setting.min_value,+ max_value=setting.max_value,+ step=setting.step,+ visible=setting.visible,+ editable=setting.editable,+ )+ db_session.add(new_setting)++ # Delete the app one+ db_session.delete(setting)+ fixed_scoping_issues.append(key)++ # Check for settings with corrupted values+ all_settings = db_session.query(Setting).all()+ for setting in all_settings:+ # Check different types of corruption+ is_corrupted = False++ if setting.value is None:+ is_corrupted = True+ elif isinstance(setting.value, str) and setting.value in [+ "{",+ "[",+ "{}",+ "[]",+ "[object Object]",+ "null",+ "undefined",+ ]:+ is_corrupted = True+ elif isinstance(setting.value, dict) and len(setting.value) == 0:+ is_corrupted = True++ # Skip if not corrupted+ if not is_corrupted:+ continue++ # Get default value from migrations+ from ..database.migrations import setup_predefined_settings++ default_value = None++ # Try to find a matching default setting based on key+ if setting.key.startswith("llm."):+ if setting.key == "llm.model":+ default_value = "gpt-3.5-turbo"+ elif setting.key == "llm.provider":+ default_value = "openai"+ elif setting.key == "llm.temperature":+ default_value = 0.7+ elif setting.key == "llm.max_tokens":+ default_value = 1024+ elif setting.key.startswith("search."):+ if setting.key == "search.tool":+ default_value = "auto"+ elif setting.key == "search.max_results":+ default_value = 10+ elif setting.key == "search.region":+ default_value = "us"+ elif setting.key == "search.research_iterations":+ default_value = 2+ elif setting.key == "search.questions_per_iteration":+ default_value = 3+ elif setting.key == "search.searches_per_section":+ default_value = 2+ elif setting.key == "search.skip_relevance_filter":+ default_value = False+ elif setting.key == "search.safe_search":+ default_value = True+ elif setting.key == "search.search_language":+ default_value = "English"+ elif setting.key.startswith("report."):+ if setting.key == "report.searches_per_section":+ default_value = 2+ elif setting.key == "report.enable_fact_checking":+ default_value = True+ elif setting.key == "report.detailed_citations":+ default_value = True+ elif setting.key.startswith("app."):+ if setting.key == "app.theme" or setting.key == "app.default_theme":+ default_value = "dark"+ elif setting.key == "app.enable_notifications":+ default_value = True+ elif (+ setting.key == "app.enable_web"+ or setting.key == "app.web_interface"+ ):+ default_value = True+ elif setting.key == "app.host":+ default_value = "0.0.0.0"+ elif setting.key == "app.port":+ default_value = 5000+ elif setting.key == "app.debug":+ default_value = True++ # Update the setting with the default value if found+ if default_value is not None:+ setting.value = default_value+ fixed_settings.append(setting.key)+ else:+ # If no default found but it's a corrupted JSON, set to empty object+ if setting.key.startswith("report."):+ setting.value = {}+ fixed_settings.append(setting.key)++ # Commit changes+ if fixed_settings or removed_duplicate_settings or fixed_scoping_issues:+ db_session.commit()+ logger.info(+ f"Fixed {len(fixed_settings)} corrupted settings: {', '.join(fixed_settings)}"+ )+ if removed_duplicate_settings:+ logger.info(+ f"Removed {len(removed_duplicate_settings)} duplicate settings"+ )+ if fixed_scoping_issues:+ logger.info(f"Fixed {len(fixed_scoping_issues)} scoping issues")++ # Return success+ return jsonify(+ {+ "status": "success",+ "message": f"Fixed {len(fixed_settings)} corrupted settings, removed {len(removed_duplicate_settings)} duplicates, and fixed {len(fixed_scoping_issues)} scoping issues",+ "fixed_settings": fixed_settings,+ "removed_duplicates": removed_duplicate_settings,+ "fixed_scoping": fixed_scoping_issues,+ }+ )++ except Exception as e:+ logger.error(f"Error fixing corrupted settings: {e}")+ db_session.rollback()+ return (+ jsonify(+ {+ "status": "error",+ "message": f"Error fixing corrupted settings: {str(e)}",+ }+ ),+ 500,+ )diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 43ebb5441c..f12d400e4c 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -5,18 +5,14 @@ import threadingimport tracebackfrom datetime import datetime-from ...config.config_files import settingsfrom ...config.llm_config import get_llmfrom ...config.search_config import get_searchfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystem-from ...utilties.search_utilities import (- extract_links_from_search_results,-)-+from ...utilties.search_utilities import extract_links_from_search_resultsfrom ..models.database import add_log_to_db, calculate_duration, get_db_connection-from .socket_service import emit_to_subscribers # Keep if needed directly+from .socket_service import emit_to_subscribers# Initialize loggerlogger = logging.getLogger(__name__)@@ -267,12 +263,6 @@ def run_research_process(f"Overriding system settings with: provider={model_provider}, model={model}, search_engine={search_engine}")-- # Import configuration modules- from ...config.config_files import settings- from ...config.llm_config import get_llm- from ...config.search_config import get_search-# Override LLM if model or model_provider specifiedif model or model_provider:try:diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.pyindex 58cd98fdde..b8b57c3479 100644--- a/src/local_deep_research/web/services/settings_manager.py+++ b/src/local_deep_research/web/services/settings_manager.py@@ -545,3 +545,153 @@ class SettingsManager:cls._instance._load_settings_from_db()return cls._instance++ def import_default_settings(+ self, main_settings_file, search_engines_file, collections_file+ ):+ """+ Import settings directly from default files++ Args:+ main_settings_file: Path to the main settings.toml file+ search_engines_file: Path to the search_engines.toml file+ collections_file: Path to the local_collections.toml file++ Returns:+ True if successful, False otherwise+ """+ if not self.db_session:+ logger.warning(+ "No database session available, cannot import default settings"+ )+ return False++ try:+ # Import settings from main settings file+ if os.path.exists(main_settings_file):+ with open(main_settings_file, "r") as f:+ main_data = toml.load(f)++ # Process each section in the main settings file+ for section, values in main_data.items():+ if section in ["web", "llm", "general", "app"]:+ setting_type = None+ if section == "web" or section == "app":+ setting_type = SettingType.APP+ prefix = "app"+ elif section == "llm":+ setting_type = SettingType.LLM+ prefix = "llm"+ else: # general section+ # Map general settings to appropriate types+ prefix = None+ for key, value in values.items():+ if key in [+ "enable_fact_checking",+ "knowledge_accumulation",+ "knowledge_accumulation_context_limit",+ "output_dir",+ ]:+ self._create_setting(+ f"report.{key}", value, SettingType.REPORT+ )++ # Add settings with correct prefix+ if prefix:+ for key, value in values.items():+ self._create_setting(+ f"{prefix}.{key}", value, setting_type+ )++ elif section == "search":+ # Search settings go to search type+ for key, value in values.items():+ self._create_setting(+ f"search.{key}", value, SettingType.SEARCH+ )++ elif section == "report":+ # Report settings+ for key, value in values.items():+ self._create_setting(+ f"report.{key}", value, SettingType.REPORT+ )++ # Import settings from search engines file+ if os.path.exists(search_engines_file):+ with open(search_engines_file, "r") as f:+ search_data = toml.load(f)++ # Find search section in search engines file+ if "search" in search_data:+ for key, value in search_data["search"].items():+ # Skip complex sections that are nested+ if not isinstance(value, dict):+ self._create_setting(+ f"search.{key}", value, SettingType.SEARCH+ )++ # Commit changes+ self.db_session.commit()+ return True++ except Exception as e:+ logger.error(f"Error importing default settings: {e}")+ if self.db_session:+ self.db_session.rollback()+ return False++ def _create_setting(self, key, value, setting_type):+ """Create a setting with appropriate metadata"""++ # Determine appropriate category+ category = None+ ui_element = "text"++ # Determine category based on key pattern+ if key.startswith("app."):+ category = "app_interface"+ elif key.startswith("llm."):+ if any(+ param in key+ for param in ["temperature", "max_tokens", "n_batch", "n_gpu_layers"]+ ):+ category = "llm_parameters"+ else:+ category = "llm_general"+ elif key.startswith("search."):+ if any(+ param in key+ for param in ["iterations", "questions", "results", "region"]+ ):+ category = "search_parameters"+ else:+ category = "search_general"+ elif key.startswith("report."):+ category = "report_parameters"++ # Determine UI element type based on value+ if isinstance(value, bool):+ ui_element = "checkbox"+ elif isinstance(value, (int, float)) and not isinstance(value, bool):+ ui_element = "number"+ elif isinstance(value, (dict, list)):+ ui_element = "textarea"++ # Build setting object+ setting_dict = {+ "key": key,+ "value": value,+ "type": setting_type.value.lower(),+ "name": key.split(".")[-1].replace("_", " ").title(),+ "description": f"Setting for {key}",+ "category": category,+ "ui_element": ui_element,+ }++ # Create the setting in the database+ db_setting = self.create_or_update_setting(setting_dict, commit=False)++ # Also update cache+ if db_setting:+ self._settings_cache[key] = valuediff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.cssnew file mode 100644index 0000000000..358ca2ff1b--- /dev/null+++ b/src/local_deep_research/web/static/css/custom_dropdown.css@@ -0,0 +1,74 @@+/**+ * Custom Dropdown Component+ * Styling for reusable dropdown component+ */++.custom-dropdown {+ position: relative;+ width: 100%;+}++.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;+}++.custom-dropdown-input:focus {+ outline: none;+ border-color: var(--accent-color);+ box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.25);+}++.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;+ display: none;+}++.custom-dropdown-item {+ padding: 8px 12px;+ cursor: pointer;+ transition: background-color 0.2s;+}++.custom-dropdown-item:hover,+.custom-dropdown-item.active {+ background-color: var(--hover-bg);+}++.custom-dropdown-no-results {+ padding: 12px;+ color: var(--text-muted);+ text-align: center;+ 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;+}++.custom-dropdown-item .highlight {+ background-color: rgba(59, 130, 246, 0.2);+ font-weight: bold;+ border-radius: 2px;+}diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.cssnew file mode 100644index 0000000000..bdcf4287b7--- /dev/null+++ b/src/local_deep_research/web/static/css/settings.css@@ -0,0 +1,1227 @@+/* Settings Dashboard Styles */++/* Container */+.settings-container {+ max-width: 100%;+ margin: 0 auto;+ padding: 0;+}++.settings-header {+ margin-bottom: 1.5rem;+}++.settings-header h1 {+ margin-bottom: 0.5rem;+ font-size: 1.8rem;+ font-weight: 600;+}++.settings-description {+ color: var(--text-secondary);+ margin-bottom: 1.5rem;+ font-size: 0.95rem;+}++/* Card styling improvements */+.card {+ background-color: var(--bg-secondary);+ border-radius: 12px;+ box-shadow: var(--card-shadow);+ margin-bottom: 1.5rem;+ overflow: hidden;+ border: 1px solid var(--border-color);+}++.card-content {+ padding: 1.75rem;+}++/* Form */+.settings-form {+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid rgba(255, 255, 255, 0.05);+}++/* Tabs */+.settings-tabs {+ display: flex;+ margin: 0 0 1.5rem 0;+ overflow-x: auto;+ white-space: nowrap;+ gap: 0.75rem;+ padding-bottom: 1rem;+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);+}++.settings-tab {+ padding: 0.6rem 1.2rem;+ cursor: pointer;+ color: var(--text-secondary);+ font-weight: 500;+ background-color: var(--bg-tertiary);+ border-radius: 2rem;+ transition: all 0.2s;+ text-align: center;+ border: 1px solid var(--border-color);+}++.settings-tab:hover {+ color: var(--text-primary);+ background-color: rgba(110, 79, 246, 0.1);+}++.settings-tab.active {+ color: var(--text-primary);+ background-color: var(--accent-primary);+ box-shadow: 0 0 10px rgba(110, 79, 246, 0.3);+ border-color: var(--accent-primary);+}++/* Remove the underline since we're using background color */+.settings-tab.active::after {+ display: none;+}++/* Cards */+.settings-cards {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));+ gap: 1rem;+ margin-bottom: 1.5rem;+}++.settings-card {+ background-color: rgba(30, 35, 45, 0.7);+ border-radius: 8px;+ padding: 1.5rem;+ border: 1px solid rgba(255, 255, 255, 0.1);+ transition: transform 0.2s, box-shadow 0.2s;+}++.settings-card:hover {+ transform: translateY(-2px);+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);+ border-color: rgba(255, 255, 255, 0.2);+}++.settings-card-icon {+ width: 48px;+ height: 48px;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ margin-bottom: 1rem;+ font-size: 1.5rem;+ color: var(--text-primary);+ background-color: rgba(255, 255, 255, 0.1);+}++.settings-card h3 {+ font-size: 1.2rem;+ margin-bottom: 0.5rem;+ font-weight: 500;+}++.settings-card p {+ color: var(--text-secondary);+ font-size: 0.9rem;+ margin-bottom: 1rem;+}++.settings-card-footer {+ margin-top: auto;+ display: flex;+ justify-content: flex-end;+}++/* Sections */+.settings-section {+ margin-bottom: 1.5rem;+ background-color: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: 0.5rem;+ overflow: hidden;+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+}++.settings-section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 1rem 1.25rem;+ cursor: pointer;+ background-color: rgba(40, 45, 60, 0.5);+ border-bottom: 1px solid var(--border-color);+ transition: background-color 0.2s;+}++.settings-section-header:hover {+ background-color: rgba(50, 55, 70, 0.9);+}++.settings-section-title {+ font-weight: 600;+ font-size: 1rem;+ color: var(--text-primary);+ display: flex;+ align-items: center;+ max-width: 80%;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.settings-section-title i {+ margin-right: 0.5rem;+ color: var(--accent-primary);+ opacity: 0.8;+}++.settings-toggle-icon {+ transition: transform 0.3s;+ color: var(--accent-primary);+}++.settings-section-header.collapsed .settings-toggle-icon {+ transform: rotate(-90deg);+}++.settings-section-body {+ padding: 1.25rem;+ border-top: none;+}++.settings-group {+ margin-bottom: 1.5rem;+}++.settings-group-title {+ font-size: 1rem;+ font-weight: 500;+ margin-bottom: 1rem;+ color: var(--text-primary);+ display: flex;+ align-items: center;+}++.settings-group-title i {+ margin-right: 8px;+}++.settings-row {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: 1rem;+ margin-bottom: 1rem;+}++.settings-item {+ margin-bottom: 1.25rem;+ padding-bottom: 1.25rem;+ border-bottom: 1px solid var(--border-color);+}++.settings-item:last-child {+ margin-bottom: 0;+ padding-bottom: 0;+ border-bottom: none;+}++.settings-item-header {+ display: flex;+ align-items: flex-start;+ margin-bottom: 0.75rem;+ min-height: 28px;+}++.settings-item-header label {+ font-weight: 600;+ margin-right: 0.5rem;+ color: var(--text-primary);+ max-width: 400px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.settings-item-header label[title] {+ cursor: help;+}++.settings-item label {+ font-weight: 600;+ margin-right: 0.5rem;+ color: var(--text-primary);+}++.settings-tooltip {+ color: var(--text-secondary);+ cursor: help;+}++.settings-tooltip:hover::after {+ content: attr(title);+ position: absolute;+ top: 100%;+ right: 0;+ background-color: rgba(0, 0, 0, 0.9);+ color: #fff;+ padding: 6px 10px;+ border-radius: 4px;+ font-size: 0.8rem;+ width: 200px;+ white-space: normal;+ z-index: 10;+ margin-top: 5px;+}++.settings-tooltip:hover::before {+ content: '';+ position: absolute;+ top: 100%;+ right: 5px;+ border-width: 5px;+ border-style: solid;+ border-color: transparent transparent rgba(0, 0, 0, 0.9) transparent;+ z-index: 10;+}++/* Inputs */+.settings-input,+.settings-textarea,+.settings-select {+ width: 100%;+ padding: 0.75rem;+ font-size: 0.9rem;+ background-color: var(--bg-secondary);+ color: var(--text-primary);+ border: 1px solid var(--border-color);+ border-radius: 0.375rem;+ transition: border-color 0.2s, box-shadow 0.2s;+}++.settings-textarea {+ min-height: 120px;+ font-family: monospace;+ white-space: pre;+}++.settings-textarea.json-content {+ font-family: 'Courier New', Courier, monospace;+}++.settings-input:focus,+.settings-textarea:focus,+.settings-select:focus {+ outline: none;+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 2px rgba(110, 79, 246, 0.3);+}++.settings-select {+ appearance: none;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%236b7280' viewBox='0 0 16 16'%3E%3Cpath d='M8 11l-6-6 1.5-1.5L8 8l4.5-4.5L14 5l-6 6z'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 0.75rem center;+ background-size: 16px 12px;+ padding-right: 2.5rem;+}++.settings-checkbox-container {+ margin: 0.5rem 0;+}++.settings-checkbox-container .checkbox-label {+ margin-bottom: 0.25rem;+}++.json-property-item .checkbox-label {+ display: flex;+ align-items: center;+ margin: 0;+ padding: 0;+}++.settings-checkbox {+ width: 18px;+ height: 18px;+ background-color: rgba(20, 25, 35, 0.7);+ border: 1px solid rgba(255, 255, 255, 0.2);+}++.settings-range {+ flex: 1;+}++.settings-range-container {+ display: flex;+ align-items: center;+}++.settings-range-value {+ min-width: 40px;+ margin-left: 1rem;+ padding: 0.25rem 0.5rem;+ background-color: var(--accent-primary);+ color: white;+ border-radius: 0.25rem;+ text-align: center;+ font-size: 0.85rem;+}++.settings-help {+ margin-top: 0.5rem;+ font-size: 0.85rem;+ color: var(--text-secondary);+ padding-left: 24px;+}++.settings-error {+ border-color: var(--error-color) !important;+}++.settings-error-message {+ color: var(--error-color);+ font-size: 0.85rem;+ margin-top: 0.5rem;+}++/* Form Actions */+.form-actions {+ display: flex;+ justify-content: flex-end;+ gap: 1rem;+ margin-top: 1.5rem;+ padding-top: 1.5rem;+ border-top: 1px solid rgba(255, 255, 255, 0.05);+}++.settings-actions {+ margin-top: 20px;+ display: flex;+ justify-content: flex-end;+ gap: 1.5rem;+}++.settings-modified {+ position: relative;+}++.json-content {+ font-family: monospace;+ white-space: pre-wrap;+ overflow-x: auto;+ font-size: 0.9rem;+ background-color: rgba(20, 25, 35, 0.7);+}++.settings-json-editor {+ position: relative;+ display: flex;+ flex-direction: column;+}++.settings-json-toolbar {+ display: flex;+ justify-content: flex-end;+ gap: 5px;+ margin-bottom: 5px;+ background-color: rgba(40, 45, 55, 0.9);+ padding: 5px;+ border-radius: 4px;+}++.json-toolbar-btn {+ background-color: rgba(30, 35, 45, 0.7);+ border: none;+ color: var(--text-primary);+ padding: 2px 8px;+ border-radius: 4px;+ cursor: pointer;+ font-size: 0.8rem;+}++.json-toolbar-btn:hover {+ background-color: rgba(50, 55, 65, 0.9);+}++.json-format-btn {+ display: flex;+ align-items: center;+}++.json-copy-btn {+ display: flex;+ align-items: center;+}++/* Alert Messages */+.alert {+ padding: 0.75rem 1.25rem;+ margin-bottom: 1rem;+ border-radius: 0.375rem;+ display: flex;+ align-items: center;+}++.alert i {+ margin-right: 0.75rem;+}++.alert-success {+ background-color: rgba(10, 207, 151, 0.2);+ color: var(--success-color);+ border-left: 4px solid var(--success-color);+}++.alert-error, .alert-danger {+ background-color: rgba(250, 92, 124, 0.2);+ color: var(--error-color);+ border-left: 4px solid var(--error-color);+}++.alert-info {+ background-color: rgba(64, 191, 255, 0.2);+ color: var(--accent-tertiary);+ border-left: 4px solid var(--accent-tertiary);+}++.alert-warning {+ background-color: rgba(249, 188, 11, 0.2);+ color: var(--warning-color);+ border-left: 4px solid var(--warning-color);+}++/* Misc */+.empty-state {+ text-align: center;+ padding: 2rem;+ color: var(--text-secondary);+}++/* Loading indicator */+.loading-spinner {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 2rem 0;+}++.loading-spinner.centered {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ width: 100%;+}++.spinner {+ width: 40px;+ height: 40px;+ border: 3px solid rgba(255, 255, 255, 0.1);+ border-radius: 50%;+ border-top-color: var(--accent-primary);+ animation: spin 1s ease-in-out infinite;+ margin-bottom: 1rem;+ position: relative;+ left: 0;+ top: 0;+}++@keyframes spin {+ to { transform: rotate(360deg); }+}++/* Additional styles for main settings page */+.settings-section h2 {+ margin-bottom: 1rem;+ color: var(--accent-primary);+ font-size: 1.3rem;+}++.form-group {+ margin-bottom: 1rem;+}++.form-group label {+ display: block;+ margin-bottom: 0.5rem;+ font-weight: 500;+}++.form-control {+ width: 100%;+ padding: 0.5rem;+ border: 1px solid var(--border-color);+ border-radius: 4px;+ background-color: var(--bg-secondary);+ color: var(--text-primary);+}++.form-row {+ display: flex;+ gap: 1rem;+}++.form-group.half {+ flex: 1;+}++.input-help {+ font-size: 0.85rem;+ color: var(--text-secondary);+ margin-top: 0.3rem;+ line-height: 1.3;+}++.checkbox-group {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.checkbox-group input {+ margin: 0;+}++.checkbox-group label {+ margin: 0;+}++.range-value {+ display: inline-block;+ margin-left: 0.5rem;+}++.config-raw {+ margin-top: 2rem;+ background-color: var(--bg-quaternary);+ padding: 1rem;+ border-radius: 4px;+ overflow: auto;+ font-family: monospace;+ font-size: 0.9rem;+ color: var(--text-primary);+ white-space: pre;+ min-height: 200px;+ max-height: 600px;+ border: 1px solid var(--border-color);+}++.toggle-raw-config {+ cursor: pointer;+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-top: 2rem;+ margin-bottom: 1rem;+ color: var(--accent-primary);+ font-weight: 500;+ padding: 0.5rem 1rem;+ background-color: rgba(74, 108, 247, 0.1);+ border-radius: 4px;+ width: fit-content;+}++.toggle-raw-config:hover {+ background-color: rgba(74, 108, 247, 0.2);+}++.config-raw-editor {+ background-color: var(--bg-quaternary);+ color: var(--text-primary);+ font-family: monospace;+ font-size: 0.9rem;+ padding: 1rem;+ border: 1px solid var(--border-color);+ border-radius: 4px;+ width: 100%;+ min-height: 400px;+ resize: vertical;+ display: block !important;+}++.editor-header {+ background-color: var(--bg-tertiary);+ padding: 0.75rem 1rem;+ border-bottom: 1px solid var(--border-color);+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.editor-header h3 {+ margin: 0;+ font-size: 1rem;+ color: var(--text-primary);+}++.editor-lang {+ background-color: var(--accent-primary);+ font-size: 0.8rem;+ padding: 0.25rem 0.5rem;+ border-radius: 4px;+}++/* Search controls */+.search-controls {+ margin-bottom: 1.5rem;+}++.search-input {+ width: 100%;+ padding: 0.75rem 1rem;+ border-radius: 0.5rem;+ border: 1px solid var(--border-color);+ background-color: var(--bg-tertiary);+ color: var(--text-primary);+ font-size: 0.95rem;+ transition: all 0.2s;+}++.search-input:focus {+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 2px rgba(110, 79, 246, 0.2);+ outline: none;+}++/* Settings-specific colorful info boxes */+.provider-info,+.search-info,+.report-info,+.app-info {+ margin-bottom: 1.5rem;+ padding: 1rem;+ border-radius: 0.375rem;+ border-left-width: 4px;+ border-left-style: solid;+}++.provider-info {+ background-color: rgba(110, 79, 246, 0.1);+ border-left-color: var(--accent-primary);+}++.provider-info h3 {+ color: var(--accent-primary);+}++.search-info {+ background-color: rgba(249, 188, 11, 0.1);+ border-left-color: var(--warning-color);+}++.search-info h3 {+ color: var(--warning-color);+}++.report-info {+ background-color: rgba(10, 207, 151, 0.1);+ border-left-color: var(--success-color);+}++.report-info h3 {+ color: var(--success-color);+}++.app-info {+ background-color: rgba(110, 79, 246, 0.15);+ border-left-color: var(--accent-secondary);+}++.app-info h3 {+ color: var(--accent-secondary);+}++.provider-info h3,+.search-info h3,+.report-info h3,+.app-info h3 {+ margin-bottom: 0.5rem;+ font-size: 1.1rem;+}++.provider-info p,+.search-info p,+.report-info p,+.app-info p {+ margin-bottom: 0.5rem;+ font-size: 0.9rem;+}++.provider-info ul,+.search-info ul,+.report-info ul,+.app-info ul {+ margin-bottom: 0;+ padding-left: 1.5rem;+}++.provider-info li,+.search-info li,+.report-info li,+.app-info li {+ font-size: 0.9rem;+ margin-bottom: 0.25rem;+}++/* Collections config specific */+.file-path {+ background-color: var(--bg-secondary);+ padding: 0.75rem;+ border-radius: 4px;+ font-family: monospace;+ margin: 1rem 0;+ word-break: break-all;+ color: var(--text-primary);+}++.config-example {+ background-color: var(--bg-quaternary);+ color: var(--text-primary);+ font-family: monospace;+ font-size: 0.9rem;+ padding: 1rem;+ border-radius: 4px;+ overflow: auto;+ white-space: pre;+ margin: 1rem 0;+}++/* Button Styles */+.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.6rem 1.2rem;+ font-size: 0.9rem;+ font-weight: 500;+ border-radius: 2rem;+ cursor: pointer;+ transition: all 0.2s;+ border: 1px solid transparent;+ gap: 0.5rem;+}++.btn i {+ font-size: 1rem;+}++.btn-primary {+ background-color: var(--accent-primary);+ color: var(--text-primary);+ box-shadow: 0 0 10px rgba(110, 79, 246, 0.3);+}++.btn-primary:hover {+ background-color: var(--accent-secondary);+ transform: translateY(-1px);+ box-shadow: 0 4px 12px rgba(110, 79, 246, 0.4);+}++.btn-outline {+ background-color: transparent;+ color: var(--text-secondary);+ border: 1px solid var(--border-color);+}++.btn-outline:hover {+ color: var(--text-primary);+ border-color: var(--accent-primary);+ background-color: rgba(110, 79, 246, 0.1);+}++/* Raw JSON Configuration */+.raw-config-section {+ margin-top: 2rem;+ border-top: 1px solid rgba(255, 255, 255, 0.05);+ padding-top: 1.5rem;+}++.section-header {+ margin-bottom: 1.5rem;+}++.section-header h3 {+ font-size: 1.2rem;+ margin-bottom: 0.5rem;+ color: var(--text-primary);+ font-weight: 500;+}++.section-description {+ color: var(--text-secondary);+ font-size: 0.9rem;+}++.json-editor {+ width: 100%;+ min-height: 300px;+ padding: 1rem;+ background-color: var(--bg-tertiary);+ color: var(--text-primary);+ border: 1px solid var(--border-color);+ border-radius: 0.5rem;+ font-family: 'Courier New', monospace;+ font-size: 0.9rem;+ resize: vertical;+ white-space: pre;+ overflow-x: auto;+}++.json-editor:focus {+ outline: none;+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 2px rgba(110, 79, 246, 0.2);+}++.toggle-raw-config {+ display: inline-flex;+ align-items: center;+ padding: 0.6rem 1.2rem;+ margin-top: 2rem;+ background-color: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: 2rem;+ cursor: pointer;+ color: var(--text-secondary);+ font-weight: 500;+ transition: all 0.2s;+ gap: 0.5rem;+}++.toggle-raw-config:hover {+ color: var(--text-primary);+ background-color: rgba(110, 79, 246, 0.1);+ border-color: var(--accent-primary);+}++/* JSON Expanded Controls */+.json-expanded-controls {+ background-color: rgba(30, 35, 45, 0.5);+ border-radius: 8px;+ padding: 1rem;+ margin-bottom: 1rem;+ border: 1px solid var(--border-color);+}++.json-property-controls {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));+ gap: 1rem;+}++.json-property-item {+ margin-bottom: 0.5rem;+ padding: 1rem;+ background-color: rgba(25, 30, 40, 0.8);+ border-radius: 6px;+ border: 1px solid var(--border-color);+ transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s;+}++.json-property-item:hover {+ transform: translateY(-2px);+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);+ border-color: rgba(110, 79, 246, 0.4);+}++/* Property label with ellipsis for long text */+.json-property-item .property-label {+ display: block;+ margin-bottom: 0.75rem;+ font-weight: 500;+ color: var(--text-primary);+ font-size: 0.95rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 100%;+ cursor: pointer;+}++/* Add explicit title for hover tooltip on long labels */+.json-property-item .property-label:hover {+ color: var(--accent-primary);+}++/* Checkbox wrapper for clickable area */+.checkbox-wrapper {+ cursor: pointer;+ padding: 0.5rem;+ margin: -0.5rem;+ border-radius: 4px;+ transition: background-color 0.2s;+}++.checkbox-wrapper:hover {+ background-color: rgba(110, 79, 246, 0.1);+}++.json-property-item .checkbox-label {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ margin-top: 0.5rem;+ cursor: pointer;+}++.json-property-item .checkbox-text {+ font-size: 0.9rem;+ color: var(--text-primary);+ cursor: pointer;+}++.json-property-item .settings-input,+.json-property-item .settings-select {+ width: 100%;+ padding: 0.7rem;+ font-size: 0.9rem;+ background-color: var(--bg-secondary);+ border: 1px solid var(--border-color);+ color: var(--text-primary);+ border-radius: 4px;+}++.json-property-item .settings-input:focus,+.json-property-item .settings-select:focus {+ outline: none;+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 2px rgba(110, 79, 246, 0.3);+}++.json-property-item .settings-help {+ color: var(--text-secondary);+ font-size: 0.8rem;+ margin-top: 0.5rem;+ opacity: 0.8;+}++/* Animations for expanded controls */+.json-expanded-controls {+ animation: fadeIn 0.3s ease-in-out;+}++@keyframes fadeIn {+ from { opacity: 0; transform: translateY(-10px); }+ to { opacity: 1; transform: translateY(0); }+}++/* Checkbox styling */+.checkbox-label {+ display: flex;+ align-items: center;+ margin-bottom: 0.5rem;+ padding-left: 0;+ cursor: pointer;+ position: relative;+}++.checkbox-label input[type="checkbox"] {+ position: relative;+ width: 18px;+ height: 18px;+ appearance: none;+ -webkit-appearance: none;+ -moz-appearance: none;+ border: 2px solid var(--accent-primary);+ border-radius: 3px;+ background-color: var(--bg-surface);+ cursor: pointer;+ margin: 0 8px 0 0;+ padding: 0;+ vertical-align: middle;+ transition: all 0.2s;+}++.checkbox-label input[type="checkbox"]:checked {+ background-color: var(--accent-primary);+ border-color: var(--accent-primary);+}++.checkbox-label input[type="checkbox"]:checked::after {+ content: '✓';+ color: white;+ font-size: 12px;+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+}++.checkbox-label input[type="checkbox"]:focus {+ outline: none;+ box-shadow: 0 0 0 2px rgba(110, 79, 246, 0.3);+}++.checkbox-text {+ margin-left: 0;+ color: var(--text-primary);+ font-size: 14px;+ vertical-align: middle;+}++.settings-item .checkbox-label {+ margin-top: 0;+ padding-left: 0;+ display: flex;+ align-items: center;+}++/* Boolean property items */+.json-property-item.boolean-property {+ cursor: pointer;+ transition: background-color 0.2s, transform 0.2s, box-shadow 0.2s, border-color 0.2s;+ position: relative;+}++.json-property-item.boolean-property:hover {+ background-color: rgba(25, 35, 55, 0.9);+ border-color: var(--accent-primary);+ transform: translateY(-2px);+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.25);+}++.json-property-item.boolean-property:active {+ transform: translateY(0px);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);+}++.json-property-item.boolean-property:after {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ z-index: 1;+ cursor: pointer;+}++.json-property-item.boolean-property .checkbox-wrapper,+.json-property-item.boolean-property .checkbox-label {+ background-color: transparent;+ cursor: pointer;+ padding: 0;+ margin: 0;+ position: relative;+ z-index: 2;+}++.json-property-item.boolean-property .checkbox-wrapper:hover {+ background-color: transparent;+}++.json-property-item.boolean-property .checkbox-text {+ cursor: pointer;+ position: relative;+ z-index: 2;+}++.json-property-item.boolean-property .property-label {+ cursor: pointer;+ position: relative;+ z-index: 2;+}++.json-property-item.boolean-property input[type="checkbox"] {+ cursor: pointer;+ margin-right: 8px;+ position: relative;+ z-index: 3;+}++/* Add styling for Reset to Defaults button */+#reset-to-defaults-button {+ margin-left: 10px;+ background-color: #e74c3c;+ color: #fff;+ border: none;+}++#reset-to-defaults-button:hover {+ background-color: #c0392b;+}++/* Add styling for Fix Corrupted Settings button */+#fix-corrupted-button {+ margin-left: 10px;+ background-color: #3498db;+ color: #fff;+ border: none;+}++#fix-corrupted-button:hover {+ background-color: #2980b9;+}++.settings-item .checkbox-label {+ margin-top: 8px;+ padding-left: 0;+}++/* Saving indicator styles */+.saving {+ position: relative;+}++.saving:before {+ content: '';+ position: absolute;+ left: -20px;+ top: 50%;+ transform: translateY(-50%);+ width: 10px;+ height: 10px;+ border: 2px solid rgba(100, 100, 255, 0.3);+ border-radius: 50%;+ border-top-color: #6060ff;+ animation: spinner 0.8s linear infinite;+ z-index: 10;+}++.checkbox-label.saving:before {+ left: -20px;+ top: 50%;+}++.settings-item.saving:before {+ left: -20px;+}++.form-group.saving:before {+ left: -20px;+}++@keyframes spinner {+ to {transform: translateY(-50%) rotate(360deg);}+}++/* Add styles for alert container and close button */+.settings-alert-container {+ margin-bottom: 1rem;+ width: 100%;+}++.settings-alert-container .alert {+ position: relative;+ padding-right: 30px;+}++.alert-close {+ position: absolute;+ right: 10px;+ top: 8px;+ font-size: 1.2rem;+ font-weight: bold;+ cursor: pointer;+ opacity: 0.7;+}++.alert-close:hover {+ opacity: 1;+}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.jsnew file mode 100644index 0000000000..8516c32dc2--- /dev/null+++ b/src/local_deep_research/web/static/js/components/custom_dropdown.js@@ -0,0 +1,233 @@+/**+ * Custom Dropdown Component+ *+ * This module provides functionality for custom dropdown menus with filtering and keyboard navigation.+ * It can be used across the application for consistent dropdown behavior.+ */+(function() {+ 'use strict';++ // Make the setupCustomDropdown function available globally+ window.setupCustomDropdown = setupCustomDropdown;++ /**+ * 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 [{value: string, label: string}]+ * @param {Function} onSelect - Callback when an item is selected (value, item) => {}+ * @param {boolean} allowCustomValues - Whether to allow values not in the options list+ * @param {string} noResultsText - Text to show when no results are found+ */+ 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>`;++ if (allowCustomValues && searchText.trim()) {+ const customOption = document.createElement('div');+ customOption.className = 'custom-dropdown-footer';+ customOption.textContent = `Press Enter to use "${searchText}"`;+ dropdownList.appendChild(customOption);+ }++ return;+ }++ 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();+ });++ if (index === selectedIndex) {+ div.classList.add('active');+ }++ dropdownList.appendChild(div);+ });+ }++ // 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+ }++ 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);+ }+ hideDropdown();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ hideDropdown();+ }++ // Update selected item styling+ items.forEach((item, index) => {+ if (index === selectedIndex) {+ item.classList.add('active');+ // Scroll into view if necessary+ if (item.offsetTop < dropdownList.scrollTop) {+ dropdownList.scrollTop = item.offsetTop;+ } else if (item.offsetTop + item.offsetHeight > dropdownList.scrollTop + dropdownList.offsetHeight) {+ dropdownList.scrollTop = item.offsetTop + item.offsetHeight - dropdownList.offsetHeight;+ }+ } else {+ item.classList.remove('active');+ }+ });+ });++ // Close dropdown when clicking outside+ document.addEventListener('click', () => {+ if (isOpen) {+ hideDropdown();+ }+ });++ // Prevent clicks in the dropdown from closing it+ dropdownList.addEventListener('click', (e) => {+ e.stopPropagation();+ });++ // Initial state+ hideDropdown();++ // Return functions that might be needed externally+ return {+ updateOptions: updateDropdown,+ show: () => {+ showAllOptions = true;+ showDropdown();+ updateDropdown();+ },+ hide: hideDropdown,+ setValue: (value, fireEvent = true) => {+ const options = getOptions();+ const item = options.find(o => o.value === value);+ if (item) {+ input.value = item.label;+ if (fireEvent) {+ onSelect(value, item);+ }+ } else if (allowCustomValues) {+ input.value = 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.jsindex c9ae9986c7..54c961b09f 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -730,12 +730,12 @@// Fetch all data sources in parallelPromise.all([- // Get available models from API- fetch('/research/api/available-models')+ // 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- fetch('/research/api/?type=llm')+ // 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])@@ -846,8 +846,8 @@// Re-enable the inputsearchEngineInput.disabled = false;- // Try to get search engine options from API- fetch('/research/api/available-search-engines')+ // Try to get search engine options from API - FIXED PATH+ fetch('/research/settings/api/available-search-engines').then(response => {if (!response.ok) throw new Error(`API returned ${response.status}`);return response.json();@@ -899,8 +899,8 @@if (questionsPerIterationInput) questionsPerIterationInput.value = 3;if (notificationToggle) notificationToggle.checked = true;- // Try to load app settings- fetch('/research/api/?type=app')+ // Try to load app settings - FIXED PATH+ fetch('/research/settings/api?type=app').then(response => {if (!response.ok) throw new Error(`API returned ${response.status}`);return response.json();diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 757deeb99b..fef44865cb 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -4,167 +4,2845 @@(function() {'use strict';- // DOM elements- const settingsForm = document.querySelector('form');- const rawConfigToggle = document.getElementById('toggle-raw-config');- const rawConfigSection = document.getElementById('raw-config');- const rawConfigEditor = document.getElementById('raw-config-editor-container');- const rawConfigTextarea = document.getElementById('raw_config_editor');-- // Range input elements that need live value display- const rangeInputs = document.querySelectorAll('input[type="range"]');-+ // DOM elements and global variables+ let settingsForm;+ let settingsContent;+ let settingsSearch;+ let settingsTabs;+ let settingsAlert;+ let resetButton;+ let rawConfigToggle;+ let rawConfigSection;+ let rawConfigEditor;+ let originalSettings = {};+ let allSettings = [];+ let activeTab = 'all';+ let saveTimer = null;+ let pendingSaves = new Set();++ // Model and search engine dropdown variables+ let modelOptions = [];+ let searchEngineOptions = [];++ // Store save timers for each setting key+ let saveTimers = {};+ let pendingSaveData = {};++ /**+ * Initialize the settings component+ */+ function initializeSettings() {+ // Get DOM elements+ settingsForm = document.querySelector('form');+ settingsContent = document.getElementById('settings-content');+ settingsSearch = document.getElementById('settings-search');+ settingsTabs = document.querySelectorAll('.settings-tab');+ settingsAlert = document.getElementById('settings-alert');+ rawConfigToggle = document.getElementById('toggle-raw-config');+ rawConfigSection = document.getElementById('raw-config');+ rawConfigEditor = document.getElementById('raw_config_editor');++ // Add dynamic styles immediately+ addDynamicStyles();++ // Initialize range inputs to display their values+ initRangeInputs();++ // Initialize accordion behavior+ initAccordions();++ // Initialize JSON handling+ initJsonFormatting();++ // Initialize expanded JSON controls+ initExpandedJsonControls();++ // Initialize auto-save handlers+ initAutoSaveHandlers();++ // Set up event listeners for the settings dashboard+ if (settingsForm) {+ settingsForm.addEventListener('submit', handleSettingsSubmit);+ }++ // Now explicitly fix checkbox handling by modifying the checkbox event handler in initAutoSaveHandlers+ document.addEventListener('click', function(e) {+ // Check if this is a click inside a boolean property item+ const boolItem = e.target.closest('.boolean-property');+ if (boolItem) {+ const checkboxId = boolItem.dataset.checkboxid;+ if (checkboxId) {+ const checkbox = document.getElementById(checkboxId);+ // Only toggle if the click wasn't directly on the checkbox+ if (checkbox && !checkbox.disabled && e.target !== checkbox) {+ directToggleCheckbox(checkboxId);+ e.preventDefault();+ e.stopPropagation();+ }+ }+ }+ });++ // Add click handler for the logo to navigate home+ const logoLink = document.getElementById('logo-link');+ if (logoLink) {+ logoLink.addEventListener('click', () => {+ window.location.href = '/research/';+ });+ }++ // Handle tab switching+ if (settingsTabs) {+ settingsTabs.forEach(tab => {+ tab.addEventListener('click', () => {+ // Remove active class from all tabs+ settingsTabs.forEach(t => t.classList.remove('active'));++ // Add active class to clicked tab+ tab.classList.add('active');++ // Update active tab and re-render+ activeTab = tab.dataset.tab;+ renderSettingsByTab(activeTab);++ // Initialize auto-save handlers after rendering+ setTimeout(initAutoSaveHandlers, 300);++ // Initialize custom dropdowns after rendering+ if (activeTab === 'llm' || activeTab === 'all') {+ setTimeout(initializeModelDropdowns, 300);+ }+ });+ });+ }++ // Handle search filtering+ if (settingsSearch) {+ settingsSearch.addEventListener('input', handleSearchInput);+ }++ // Handle reset to defaults button+ const resetToDefaultsButton = document.getElementById('reset-to-defaults-button');+ if (resetToDefaultsButton) {+ resetToDefaultsButton.addEventListener('click', handleResetToDefaults);+ }++ // Add a fix corrupted settings button+ const fixCorruptedButton = document.createElement('button');+ fixCorruptedButton.setAttribute('type', 'button');+ fixCorruptedButton.setAttribute('id', 'fix-corrupted-button');+ fixCorruptedButton.className = 'btn btn-info';+ fixCorruptedButton.innerHTML = '<i class="fas fa-wrench"></i> Fix Corrupted Settings';+ fixCorruptedButton.addEventListener('click', handleFixCorruptedSettings);++ // Insert it after the reset to defaults button+ if (resetToDefaultsButton) {+ resetToDefaultsButton.insertAdjacentElement('afterend', fixCorruptedButton);+ }++ // Handle raw config toggle+ if (rawConfigToggle) {+ rawConfigToggle.addEventListener('click', toggleRawConfig);+ }++ // Load settings from API if on settings dashboard+ if (settingsContent) {+ loadSettings();++ // Fetch model providers and search engines+ fetchModelProviders();+ fetchSearchEngines();+ }++ // Initialize specific settings page form handlers+ initSpecificSettingsForm();+ }++ /**+ * Initialize auto-save handlers for settings inputs+ */+ function initAutoSaveHandlers() {+ // Only run this for the main settings dashboard+ if (!settingsContent) return;++ // Get all inputs in settings form+ const inputs = settingsForm.querySelectorAll('input, textarea, select');++ // Set up event handlers for each input+ inputs.forEach(input => {+ // Skip if this is a button or submit input+ if (input.type === 'button' || input.type === 'submit') return;++ // Set data-key attribute from name if not already set+ if (!input.getAttribute('data-key') && input.getAttribute('name')) {+ input.setAttribute('data-key', input.getAttribute('name'));+ }++ // Remove existing listeners to avoid duplicates+ input.removeEventListener('input', handleInputChange);+ input.removeEventListener('keydown', handleInputChange);+ input.removeEventListener('blur', handleInputChange);+ input.removeEventListener('change', handleInputChange);++ // For checkboxes, we use change event+ if (input.type === 'checkbox') {+ input.addEventListener('change', function(e) {+ // For checkboxes, pass custom event type parameter to avoid issues+ handleInputChange(e, 'change');+ });+ }+ // For selects, we use change event+ else if (input.tagName.toLowerCase() === 'select') {+ input.addEventListener('change', function(e) {+ // Create a custom parameter instead of modifying e.type+ handleInputChange(e, 'change');+ });++ // Also listen for blur to trigger saves+ input.addEventListener('blur', function(e) {+ // Create a custom parameter instead of modifying e.type+ handleInputChange(e, 'blur');+ });+ }+ // For text, number, etc. we monitor for changes but only save on blur or Enter+ else {+ // Listen for input events to track changes and validate in real-time+ input.addEventListener('input', function(e) {+ // Create a custom parameter instead of modifying e.type+ handleInputChange(e, 'input');+ });++ // Handle Enter key press for immediate saving+ input.addEventListener('keydown', function(e) {+ if (e.key === 'Enter') {+ // Create a custom parameter instead of modifying e.type+ handleInputChange(e, 'keydown');+ }+ });++ // Save on blur if changes were made+ input.addEventListener('blur', function(e) {+ // Create a custom parameter instead of modifying e.type+ handleInputChange(e, 'blur');+ });+ }+ });++ // Set up special handlers for JSON property controls+ const jsonPropertyControls = settingsForm.querySelectorAll('.json-property-control');++ jsonPropertyControls.forEach(control => {+ // Remove existing listeners+ control.removeEventListener('change', updateJsonFromControls);+ control.removeEventListener('input', updateJsonFromControls);+ control.removeEventListener('keydown', updateJsonFromControls);+ control.removeEventListener('blur', updateJsonFromControls);++ if (control.type === 'checkbox') {+ control.addEventListener('change', function(e) {+ updateJsonFromControls(control, true); // true = force save+ });+ } else {+ control.addEventListener('input', function(e) {+ updateJsonFromControls(control, false); // false = don't save yet+ });++ // Handle Enter key for JSON property controls+ control.addEventListener('keydown', function(e) {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ updateJsonFromControls(control, true); // true = force save+ control.blur();+ }+ });++ control.addEventListener('blur', function(e) {+ updateJsonFromControls(control, true); // true = force save+ });+ }+ });++ // If the raw JSON editor is visible, set up its event handlers+ if (rawConfigEditor) {+ rawConfigEditor.addEventListener('input', handleRawJsonInput);+ rawConfigEditor.addEventListener('blur', function(e) {+ if (rawConfigEditor.getAttribute('data-modified') === 'true') {+ handleRawJsonInput(e, true); // Force save on blur+ }+ });+ }+ }++ /**+ * Handle input change for autosave+ * @param {Event} e - The input change event+ * @param {string} [customEventType] - Optional event type parameter+ */+ function handleInputChange(e, customEventType) {+ const input = e.target;+ const eventType = customEventType || e.type; // Use custom type if provided, otherwise use event's type++ // Skip if disabled or not data-key attribute+ if (input.disabled || !input.getAttribute('data-key')) {+ return;+ }++ // Get the key and value+ const key = input.getAttribute('data-key') || input.getAttribute('name');++ // Skip if no key found+ if (!key) {+ console.error('No key found for input:', input);+ return;+ }++ // Get value based on input type+ let value;++ if (input.type === 'checkbox') {+ value = input.checked;++ // For checkboxes, we need to save immediately on change+ const formData = {};+ formData[key] = value;+ submitSettingsData(formData, input);+ return;+ } else if (input.type === 'number') {+ value = parseFloat(input.value);++ // Validate number against min/max if set+ const min = input.getAttribute('min');+ const max = input.getAttribute('max');++ if (min !== null && value < parseFloat(min)) {+ markInvalidInput(input, `Value must be at least ${min}`);+ return;+ }++ if (max !== null && value > parseFloat(max)) {+ markInvalidInput(input, `Value must be at most ${max}`);+ return;+ }+ } else {+ value = input.value;++ // If this is a raw JSON editor, validate the JSON+ if (input.classList.contains('json-editor')) {+ try {+ value = JSON.parse(input.value);+ } catch (e) {+ markInvalidInput(input, `Invalid JSON: ${e.message}`);+ return;+ }+ }++ // If this is part of an expanded JSON control, don't handle it here+ if (input.classList.contains('json-property-control')) {+ // This will be handled by updateJsonFromControls+ return;+ }+ }++ // Clear any previous error styling+ input.classList.remove('invalid-input');+ const errorMessage = input.parentNode.querySelector('.input-error-message');+ if (errorMessage) {+ errorMessage.remove();+ }++ // Get the original value to compare+ const settingObj = allSettings.find(s => s.key === key);+ const originalValue = settingObj ? settingObj.value : null;++ // Check if value actually changed before saving+ const hasChanged = !areValuesEqual(value, originalValue);++ // Don't mark as modified or save if nothing changed+ if (!hasChanged) {+ // If this is a blur event and we have no changes, just return+ if (eventType === 'blur') {+ return;+ }+ } else {+ // Only mark as modified if there's an actual change+ const item = input.closest('.settings-item');+ if (item) {+ item.classList.add('settings-modified');+ }+ }++ // Handle Enter key press - submit just this field immediately+ if (eventType === 'keydown' && e.key === 'Enter' && !e.shiftKey) {+ // Prevent default behavior (form submission)+ e.preventDefault();++ // Only if this is not a textarea or it is with Enter key and not Shift+Enter+ if (input.tagName.toLowerCase() !== 'textarea' || (e.key === 'Enter' && !e.shiftKey)) {+ // Only save if there's an actual change+ if (hasChanged) {+ // Create formData with just this field+ const formData = {};+ formData[key] = value;++ // Mark this input as being processed by Enter key to prevent double save+ input.setAttribute('data-enter-pressed', 'true');++ // Submit immediately+ submitSettingsData(formData, input);+ }++ // Blur the input without triggering another save+ setTimeout(() => {+ // Remove the focus without triggering blur events+ input.blur();+ }, 10);+ return;+ }+ }++ // For blur events, save immediately if value changed+ if (eventType === 'blur') {+ // Check if this was triggered right after an Enter key press+ if (input.getAttribute('data-enter-pressed') === 'true') {+ // Reset the flag and don't save again+ input.removeAttribute('data-enter-pressed');+ return;+ }++ if (hasChanged) {+ const formData = {};+ formData[key] = value;+ submitSettingsData(formData, input);+ }+ return;+ }++ // For 'input' events, we don't schedule a save - we'll save on blur or Enter+ // This way, we avoid saving while the user is still typing+ }++ /**+ * Compare two values for equality, handling different types+ * @param {any} value1 - First value+ * @param {any} value2 - Second value+ * @returns {boolean} - Whether the values are equal+ */+ function areValuesEqual(value1, value2) {+ // Handle null/undefined+ if (value1 === null && value2 === null) return true;+ if (value1 === undefined && value2 === undefined) return true;+ if (value1 === null && value2 === undefined) return true;+ if (value1 === undefined && value2 === null) return true;++ // If one is null/undefined but the other isn't+ if ((value1 === null || value1 === undefined) && (value2 !== null && value2 !== undefined)) return false;+ if ((value2 === null || value2 === undefined) && (value1 !== null && value1 !== undefined)) return false;++ // Handle different types+ const type1 = typeof value1;+ const type2 = typeof value2;++ // If types are different, they're not equal+ // Except for numbers and strings that might be equivalent+ if (type1 !== type2) {+ // Special case for numeric strings vs numbers+ if ((type1 === 'number' && type2 === 'string') || (type1 === 'string' && type2 === 'number')) {+ return String(value1) === String(value2);+ }+ return false;+ }++ // Handle objects (including arrays)+ if (type1 === 'object') {+ // Handle arrays+ if (Array.isArray(value1) && Array.isArray(value2)) {+ if (value1.length !== value2.length) return false;+ return JSON.stringify(value1) === JSON.stringify(value2);+ }++ // Handle objects+ return JSON.stringify(value1) === JSON.stringify(value2);+ }++ // Handle primitives+ return value1 === value2;+ }++ /**+ * Handle input to raw JSON fields for validation+ * @param {Event} e - The input event+ */+ function handleRawJsonInput(e) {+ const input = e.target;++ try {+ // Try to parse the JSON+ JSON.parse(input.value);++ // Valid JSON, remove any error styling+ const settingsItem = input.closest('.settings-item');+ if (settingsItem) {+ settingsItem.classList.remove('settings-error');++ // Remove any error message+ const errorMsg = settingsItem.querySelector('.settings-error-message');+ if (errorMsg) {+ errorMsg.remove();+ }+ }+ input.classList.remove('settings-error');+ } catch (e) {+ // Invalid JSON, mark as error but don't prevent typing+ input.classList.add('settings-error');++ // Don't show error message while actively typing, only on blur+ input.addEventListener('blur', function onBlur() {+ try {+ JSON.parse(input.value);+ // Valid JSON on blur, clear any error+ markInvalidInput(input, null);+ } catch (e) {+ // Still invalid on blur, show error+ markInvalidInput(input, 'Invalid JSON format: ' + e.message);+ }+ // Remove this blur handler after it runs once+ input.removeEventListener('blur', onBlur);+ }, { once: true });+ }+ }++ /**+ * Mark an input as invalid with error styling+ * @param {HTMLElement} input - The input element+ * @param {string|null} errorMessage - The error message or null to clear error+ */+ function markInvalidInput(input, errorMessage) {+ const settingsItem = input.closest('.settings-item');+ if (!settingsItem) return;++ // Clear existing error message+ const existingMsg = settingsItem.querySelector('.settings-error-message');+ if (existingMsg) {+ existingMsg.remove();+ }++ if (errorMessage) {+ // Add error class+ settingsItem.classList.add('settings-error');+ input.classList.add('settings-error');++ // Create error message+ const errorMsg = document.createElement('div');+ errorMsg.className = 'settings-error-message';+ errorMsg.textContent = errorMessage;+ settingsItem.appendChild(errorMsg);+ } else {+ // Remove error class+ settingsItem.classList.remove('settings-error');+ input.classList.remove('settings-error');+ }+ }++ /**+ * Schedule a debounced save operation+ * @param {Object} formData - The form data to save+ * @param {HTMLElement} sourceElement - The element that triggered the save+ */+ function scheduleSave(formData, sourceElement) {+ // Merge the form data with any existing pending save data+ Object.entries(formData).forEach(([key, value]) => {+ pendingSaveData[key] = value;++ // Clear any existing timer for this specific key+ if (saveTimers[key]) {+ clearTimeout(saveTimers[key]);+ }++ // Set loading state on the source element+ if (sourceElement) {+ sourceElement.classList.add('saving');+ }++ // Create a new timer for this specific key+ saveTimers[key] = setTimeout(() => {+ // Create a single-key form data object with just this setting+ const singleSettingData = { [key]: pendingSaveData[key] };++ // Submit just this setting's data+ submitSettingsData(singleSettingData, sourceElement);++ // Clear this key from pending saves+ delete pendingSaveData[key];+ delete saveTimers[key];+ }, 800); // 800ms debounce+ });+ }++ /**+ * Initialize expanded JSON controls+ * This sets up event listeners for the individual form controls that represent JSON properties+ */+ function initExpandedJsonControls() {+ // Find all JSON property controls+ document.querySelectorAll('.json-property-control').forEach(control => {+ // When the control changes, update the hidden JSON field+ control.addEventListener('change', function() {+ updateJsonFromControls(this);+ });++ // For text and number inputs, also listen for input events+ if (control.tagName === 'INPUT' && (control.type === 'text' || control.type === 'number')) {+ control.addEventListener('input', function() {+ updateJsonFromControls(this);+ });+ }+ });+ }++ /**+ * Update JSON data from individual controls+ * @param {HTMLElement} changedControl - The control that triggered the update+ * @param {boolean} forceSave - Whether to force an update to the server+ */+ function updateJsonFromControls(changedControl, forceSave = false) {+ const parentKey = changedControl.dataset.parentKey;+ const property = changedControl.dataset.property;++ if (!parentKey || !property) return;++ // Find all controls for this parent JSON+ const controls = document.querySelectorAll(`.json-property-control[data-parent-key="${parentKey}"]`);++ // Create an object to hold the JSON data+ const jsonData = {};++ // Populate the object with values from all controls+ controls.forEach(control => {+ const prop = control.dataset.property;+ let value = null;++ if (control.type === 'checkbox') {+ value = control.checked;+ } else if (control.type === 'number') {+ value = parseFloat(control.value);+ } else if (control.tagName === 'SELECT') {+ value = control.value;+ } else {+ value = control.value;+ // Try to convert to number if it's numeric+ if (!isNaN(value) && value !== '') {+ value = parseFloat(value);+ }+ }++ jsonData[prop] = value;+ });++ // Find the hidden input that stores the original JSON+ const originalInput = document.getElementById(`${parentKey.replace(/\./g, '-')}_original`);+ let originalJson = {};++ if (originalInput) {+ // Get the original JSON+ try {+ originalJson = JSON.parse(originalInput.value);+ } catch (e) {+ console.error('Error parsing original JSON:', e);+ // Create an empty object if parsing fails+ originalJson = {};+ }+ }++ // Check if there's actually a change before saving+ const hasChanged = !areObjectsEqual(jsonData, originalJson);++ // Mark the parent container as modified if there's a change+ const settingItem = changedControl.closest('.settings-item');+ if (settingItem && hasChanged) {+ settingItem.classList.add('settings-modified');+ }++ // Update the UI even if we're not saving to the server+ if (originalInput) {+ // Update the original JSON with new values+ Object.assign(originalJson, jsonData);+ originalInput.value = JSON.stringify(originalJson);+ }++ // Also update any textarea that might display this JSON+ const jsonTextarea = document.getElementById(parentKey.replace(/\./g, '-'));+ if (jsonTextarea && jsonTextarea.tagName === 'TEXTAREA') {+ jsonTextarea.value = JSON.stringify(jsonData, null, 2);+ }++ // If we have a raw config editor, update it as well+ if (rawConfigEditor) {+ try {+ const rawConfig = JSON.parse(rawConfigEditor.value);+ const parts = parentKey.split('.');+ const prefix = parts[0]; // app, llm, search, etc.++ if (rawConfig[prefix]) {+ const subKey = parentKey.substring(prefix.length + 1);+ rawConfig[prefix][subKey] = jsonData;+ rawConfigEditor.value = JSON.stringify(rawConfig, null, 2);+ }+ } catch (e) {+ console.log('Error updating raw config:', e);+ }+ }++ // Only save to the server if forced or there's a change+ if ((forceSave && hasChanged) || (changedControl.type === 'checkbox' && hasChanged)) {+ // Auto-save this setting+ const formData = {};+ formData[parentKey] = jsonData;+ submitSettingsData(formData, changedControl);+ }+ }++ /**+ * Compare two objects for equality+ * @param {Object} obj1 - First object+ * @param {Object} obj2 - Second object+ * @returns {boolean} - Whether the objects are equal+ */+ function areObjectsEqual(obj1, obj2) {+ // Get the keys of both objects+ const keys1 = Object.keys(obj1);+ const keys2 = Object.keys(obj2);++ // If the number of keys is different, they're not equal+ if (keys1.length !== keys2.length) return false;++ // Check each key/value pair+ for (const key of keys1) {+ // If the key doesn't exist in obj2, not equal+ if (!obj2.hasOwnProperty(key)) return false;++ // If the values are not equal, not equal+ if (!areValuesEqual(obj1[key], obj2[key])) return false;+ }++ // All keys/values match+ return true;+ }++ /**+ * Initialize specific settings page form handlers+ */+ function initSpecificSettingsForm() {+ // Get the form ID to determine which specific page we're on+ const specificForm = document.getElementById('report-settings-form') ||+ document.getElementById('llm-settings-form') ||+ document.getElementById('search-settings-form') ||+ document.getElementById('app-settings-form');++ if (specificForm) {+ // Add form submission handler+ specificForm.addEventListener('submit', function(e) {+ // Handle checkbox values+ const checkboxes = specificForm.querySelectorAll('input[type="checkbox"]');+ checkboxes.forEach(checkbox => {+ if (!checkbox.checked) {+ // Create a hidden input for unchecked boxes+ const hidden = document.createElement('input');+ hidden.type = 'hidden';+ hidden.name = checkbox.name;+ hidden.value = 'false';+ specificForm.appendChild(hidden);+ }+ });++ // Check for validation errors in JSON textareas+ let hasInvalidJson = false;++ document.querySelectorAll('.json-content').forEach(textarea => {+ try {+ // Try to parse JSON to validate+ JSON.parse(textarea.value);+ } catch (e) {+ // If it's not valid JSON, show an error+ e.preventDefault();+ hasInvalidJson = true;++ // Find the closest settings-item+ const settingsItem = textarea.closest('.settings-item');+ if (settingsItem) {+ settingsItem.classList.add('settings-error');++ // Add error message if it doesn't exist+ let errorMsg = settingsItem.querySelector('.settings-error-message');+ if (!errorMsg) {+ errorMsg = document.createElement('div');+ errorMsg.className = 'settings-error-message';+ settingsItem.appendChild(errorMsg);+ }+ errorMsg.textContent = 'Invalid JSON format';+ }+ }+ });++ // Handle JSON from expanded controls+ document.querySelectorAll('input[id$="_original"]').forEach(input => {+ if (input.name.endsWith('_original')) {+ const actualName = input.name.replace('_original', '');++ // Create a hidden input with the actual name+ const hiddenInput = document.createElement('input');+ hiddenInput.type = 'hidden';+ hiddenInput.name = actualName;+ hiddenInput.value = input.value;+ specificForm.appendChild(hiddenInput);+ }+ });++ if (hasInvalidJson) {+ e.preventDefault();+ return false;+ }+ });+ }+ }++ /**+ * Initialize range inputs to display their values+ */+ function initRangeInputs() {+ const rangeInputs = document.querySelectorAll('input[type="range"]');++ rangeInputs.forEach(range => {+ const valueDisplay = document.getElementById(`${range.id}-value`) || range.nextElementSibling;++ if (valueDisplay &&+ (valueDisplay.classList.contains('settings-range-value') ||+ valueDisplay.classList.contains('range-value'))) {+ // Set initial value+ valueDisplay.textContent = range.value;++ // Update on input change+ range.addEventListener('input', () => {+ valueDisplay.textContent = range.value;+ });+ }+ });+ }++ /**+ * Initialize accordion behavior+ */+ function initAccordions() {+ document.querySelectorAll('.settings-section-header').forEach(header => {+ const targetId = header.dataset.target;+ const target = document.getElementById(targetId);++ if (target) {+ // Set initial state - expanded+ header.classList.remove('collapsed');+ target.style.display = 'block';++ header.addEventListener('click', () => {+ header.classList.toggle('collapsed');+ target.style.display = header.classList.contains('collapsed') ? 'none' : 'block';++ // Rotate chevron icon+ const icon = header.querySelector('.settings-toggle-icon i');+ if (icon) {+ icon.style.transform = header.classList.contains('collapsed') ? 'rotate(-90deg)' : '';+ }+ });+ }+ });+ }++ /**+ * Format JSON in textareas+ */+ function initJsonFormatting() {+ document.querySelectorAll('.json-content').forEach(textarea => {+ const value = textarea.value.trim();++ if (value && (value.startsWith('{') || value.startsWith('['))) {+ try {+ const formatted = JSON.stringify(JSON.parse(value), null, 2);+ textarea.value = formatted;+ } catch (e) {+ // Not valid JSON, leave as is+ console.log('Error formatting JSON:', e);+ }+ }++ // Add event listener to format on input+ textarea.addEventListener('input', function() {+ if (this.value.trim() && (this.value.trim().startsWith('{') || this.value.trim().startsWith('['))) {+ try {+ const obj = JSON.parse(this.value);+ const formatted = JSON.stringify(obj, null, 2);++ // Only update if actually different (to avoid cursor jumping)+ if (this.value !== formatted) {+ // Remember cursor position+ const selectionStart = this.selectionStart;+ const selectionEnd = this.selectionEnd;++ this.value = formatted;++ // Try to restore cursor+ this.setSelectionRange(selectionStart, selectionEnd);+ }+ } catch (e) {+ // Invalid JSON, just leave it alone+ }+ }+ });+ });++ // Convert text inputs with JSON content to textareas+ document.querySelectorAll('.settings-input').forEach(input => {+ const value = input.value.trim();++ // Skip if the value is "[object Object]" which isn't valid JSON+ if (value === "[object Object]") {+ // Replace with an empty object+ input.value = "{}";+ console.log('Fixed [object Object] string in input:', input.name);+ return;+ }++ if (value && (value.startsWith('{') || value.startsWith('['))) {+ try {+ // Try to parse as JSON to validate+ JSON.parse(value);++ // Create a new textarea+ const textarea = document.createElement('textarea');+ textarea.id = input.id;+ textarea.name = input.name;+ textarea.className = 'settings-textarea json-content';+ textarea.disabled = input.disabled;++ try {+ textarea.value = JSON.stringify(JSON.parse(value), null, 2);+ } catch (e) {+ textarea.value = value;+ }++ // Replace the input with textarea+ input.parentNode.replaceChild(textarea, input);+ } catch (e) {+ // Not valid JSON, leave as is+ console.log('Error converting JSON input to textarea:', e);+ }+ }+ });+ }++ /**+ * Load settings from the API+ */+ function loadSettings() {+ // Only run this for the main settings dashboard+ if (!settingsContent) return;++ fetch('/research/settings/all_settings')+ .then(response => response.json())+ .then(data => {+ if (data.status === 'success') {+ // Process settings to handle object values and check for corruption+ allSettings = processSettings(data.settings);++ // Store original values+ allSettings.forEach(setting => {+ originalSettings[setting.key] = setting.value;+ });++ // Render settings by tab+ renderSettingsByTab(activeTab);++ // Initialize auto-save handlers+ setTimeout(initAutoSaveHandlers, 300);++ // Initialize the dropdowns after the settings are loaded+ if (activeTab === 'llm' || activeTab === 'all') {+ setTimeout(initializeModelDropdowns, 300);+ }+ if (activeTab === 'search' || activeTab === 'all') {+ setTimeout(initializeSearchEngineDropdowns, 300);+ }++ // Prepare the raw JSON editor if it exists+ prepareRawJsonEditor();++ // Initialize expanded JSON controls+ setTimeout(() => {+ initExpandedJsonControls();+ }, 100);+ } else {+ showAlert('Error loading settings: ' + data.message, 'error');+ }+ })+ .catch(error => {+ showAlert('Error loading settings: ' + error, 'error');+ });+ }++ /**+ * Format category names to be more user-friendly+ * @param {string} key - The setting key+ * @param {string} category - The category name+ * @returns {string} - The formatted category name+ */+ function formatCategoryName(key, category) {+ // Special cases for known categories+ if (category === 'app_interface') return 'App Interface';+ if (category === 'app_parameters') return 'App Parameters';+ if (category === 'llm_general') return 'LLM General';+ if (category === 'llm_parameters') return 'LLM Parameters';+ if (category === 'report_parameters') return 'Report Parameters';+ if (category === 'search_general') return 'Search General';+ if (category === 'search_parameters') return 'Search Parameters';++ // Remove any underscores and capitalize each word+ let formattedCategory = category.replace(/_/g, ' ');++ // Capitalize first letter of each word+ formattedCategory = formattedCategory.split(' ')+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');++ return formattedCategory;+ }++ /**+ * Organize settings to avoid duplicate group names and improve organization+ * @param {Array} settings - The settings array+ * @param {string} tab - The current tab+ * @returns {Object} - The organized settings+ */+ function organizeSettings(settings, tab) {+ // Create a mapping of types+ const typeMap = {+ 'app': 'Application',+ 'llm': 'Language Models',+ 'search': 'Search Engines',+ 'report': 'Reports'+ };++ // Define settings that should only appear in specific tabs+ const tabSpecificSettings = {+ 'llm': [+ 'llamacpp_f16_kv',+ 'provider',+ 'model',+ 'temperature',+ 'max_tokens',+ 'openai_endpoint_url',+ 'lmstudio_url',+ 'llamacpp_model_path',+ 'llamacpp_n_batch',+ 'llamacpp_n_gpu_layers',+ 'api_key'+ ],+ 'search': [+ 'iterations',+ 'max_filtered_results',+ 'max_results',+ 'quality_check_urls',+ 'questions_per_iteration',+ 'research_iterations',+ 'region',+ 'search_engine',+ 'searches_per_section',+ 'skip_relevance_filter',+ 'safe_search',+ 'search_language',+ 'time_period',+ 'tool',+ 'snippets_only'+ ],+ 'report': [+ 'enable_fact_checking',+ 'knowledge_accumulation',+ 'knowledge_accumulation_context_limit',+ 'output_dir',+ 'detailed_citations'+ ],+ 'app': [+ 'debug',+ 'host',+ 'port',+ 'enable_notifications',+ 'web_interface',+ 'enable_web',+ 'dark_mode',+ 'default_theme',+ 'theme'+ ]+ };++ // Priority settings that should appear at the top of each tab+ const prioritySettings = {+ 'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port'],+ 'llm': ['provider', 'model', 'temperature', 'max_tokens'],+ 'search': ['search_engine', 'tool', 'iterations', 'questions_per_iteration', 'research_iterations', 'max_results', 'region'],+ 'report': ['enable_fact_checking', 'knowledge_accumulation', 'output_dir', 'detailed_citations']+ };++ // Group by prefix and category+ const grouped = {};++ // Filter settings based on current tab+ const filteredSettings = settings.filter(setting => {+ const parts = setting.key.split('.');+ const prefix = parts[0]; // app, llm, search, etc.+ const subKey = parts[1]; // The actual key name without prefix++ // Filter out nested settings like app.llm, app.search, app.general, app.web, etc.+ if (prefix === 'app' && (subKey === 'llm' || subKey === 'search' || subKey === 'general' || subKey === 'web')) {+ return false;+ }++ // Filter out fact checking duplicates - only keep in report tab+ if (prefix !== 'report' && subKey === 'enable_fact_checking') {+ return false;+ }++ // Filter out knowledge_accumulation duplicates - only keep in report tab+ if (prefix !== 'report' && (subKey === 'knowledge_accumulation' || subKey === 'knowledge_accumulation_context_limit')) {+ return false;+ }++ // If we're on a specific tab, only show settings for that tab+ if (tab !== 'all') {+ // Only show settings in tab-specific lists for that tab+ if (tab === prefix) {+ // For tab-specific settings, make sure they're in the list+ if (tabSpecificSettings[tab] && tabSpecificSettings[tab].includes(subKey)) {+ return true;+ }+ // For settings not in any tab-specific list, allow showing them in their own tab+ for (const otherTab in tabSpecificSettings) {+ if (otherTab !== tab && tabSpecificSettings[otherTab].includes(subKey)) {+ return false;+ }+ }+ return true;+ }+ return false;+ }++ // For "all" tab, filter out duplicates and specialized settings+ // Check if this setting belongs exclusively to a specific tab+ for (const tabName in tabSpecificSettings) {+ if (tabSpecificSettings[tabName].includes(subKey) && prefix !== tabName) {+ // Don't show this setting if it belongs to a different tab+ return false;+ }+ }++ // Include all remaining settings in the "all" tab+ return true;+ });++ // First pass: group settings by prefix and category+ filteredSettings.forEach(setting => {+ const parts = setting.key.split('.');+ const prefix = parts[0]; // app, llm, search, etc.+ const subKey = parts[1]; // The setting key without prefix++ // Create namespace if needed+ if (!grouped[prefix]) {+ grouped[prefix] = {};+ }++ // Use category or create one based on subkey+ let category = setting.category || 'general';++ // Format the category name to be user-friendly+ category = formatCategoryName(prefix, category);++ // For duplicate "general" categories, prefix with the type+ if (category.toLowerCase() === 'general') {+ category = `${typeMap[prefix] || prefix.charAt(0).toUpperCase() + prefix.slice(1)} General`;+ }++ // Create category array if needed+ if (!grouped[prefix][category]) {+ grouped[prefix][category] = [];+ }++ // Add setting to category+ grouped[prefix][category].push(setting);+ });++ // Second pass: sort settings within each category by priority+ for (const prefix in grouped) {+ // Sort the categories themselves to ensure important ones come first+ const sortedCategories = {};+ const categoryOrder = ['General', 'Interface', 'Connection', 'Model', 'API', 'Parameters'];++ // Get existing categories for this prefix+ const categories = Object.keys(grouped[prefix]);++ // Sort categories+ categories.sort((a, b) => {+ // Check if either category contains a priority word+ const aIndex = categoryOrder.findIndex(word => a.includes(word));+ const bIndex = categoryOrder.findIndex(word => b.includes(word));++ // If both have priority words, sort by priority+ if (aIndex !== -1 && bIndex !== -1) {+ return aIndex - bIndex;+ }++ // If only one has a priority word, it comes first+ if (aIndex !== -1) return -1;+ if (bIndex !== -1) return 1;++ // Otherwise, alphabetical+ return a.localeCompare(b);+ });++ // Create new object with sorted categories+ categories.forEach(category => {+ sortedCategories[category] = grouped[prefix][category];++ // Sort settings within this category by priority+ sortedCategories[category].sort((a, b) => {+ const aKey = a.key.split('.')[1];+ const bKey = b.key.split('.')[1];++ // Get priority list for this prefix+ const priorities = prioritySettings[prefix] || [];++ // If both are in priorities, sort by priority order+ const aIndex = priorities.indexOf(aKey);+ const bIndex = priorities.indexOf(bKey);++ if (aIndex !== -1 && bIndex !== -1) {+ return aIndex - bIndex;+ }++ // If only one is in priorities, it comes first+ if (aIndex !== -1) return -1;+ if (bIndex !== -1) return 1;++ // Otherwise sort alphabetically+ return aKey.localeCompare(bKey);+ });+ });++ // Replace original categories with sorted ones+ grouped[prefix] = sortedCategories;+ }++ return grouped;+ }++ /**+ * Render settings based on active tab+ * @param {string} tab - The active tab+ */+ function renderSettingsByTab(tab) {+ // Only run this for the main settings dashboard+ if (!settingsContent) return;++ // Filter settings by tab+ let filteredSettings = allSettings;++ if (tab !== 'all') {+ filteredSettings = allSettings.filter(setting => setting.key.startsWith(tab + '.'));+ }++ // Organize settings to avoid duplicate groups+ const groupedSettings = organizeSettings(filteredSettings, tab);++ // Build HTML+ let html = '';++ // Define the order for the types in "all" tab+ const typeOrder = ['app', 'llm', 'search', 'report'];+ const prefixTypes = Object.keys(groupedSettings);++ // Sort prefixes by the defined order for the "all" tab+ if (tab === 'all') {+ prefixTypes.sort((a, b) => {+ const aIndex = typeOrder.indexOf(a);+ const bIndex = typeOrder.indexOf(b);++ // If both are in the ordered list, sort by that order+ if (aIndex !== -1 && bIndex !== -1) {+ return aIndex - bIndex;+ }++ // If only one is in the list, it comes first+ if (aIndex !== -1) return -1;+ if (bIndex !== -1) return 1;++ // Alphabetically for anything else+ return a.localeCompare(b);+ });+ }++ // For each type (app, llm, search, etc.)+ for (const type of prefixTypes) {+ if (tab !== 'all' && type !== tab) continue;++ // For each category in this type+ for (const category in groupedSettings[type]) {+ const sectionId = `section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`;++ html += `+ <div class="settings-section">+ <div class="settings-section-header" data-target="${sectionId}">+ <div class="settings-section-title" title="${category}">+ ${category}+ </div>+ <div class="settings-toggle-icon">+ <i class="fas fa-chevron-down"></i>+ </div>+ </div>+ <div id="${sectionId}" class="settings-section-body">+ `;++ // Add all settings in this category+ groupedSettings[type][category].forEach(setting => {+ html += renderSettingItem(setting);+ });++ html += `+ </div>+ </div>+ `;+ }+ }++ if (html === '') {+ html = '<div class="empty-state"><p>No settings found for this category</p></div>';+ }++ // Update the content+ settingsContent.innerHTML = html;++ // Initialize accordion behavior+ initAccordions();++ // Initialize JSON handling+ initJsonFormatting();++ // Initialize range inputs+ initRangeInputs();++ // Initialize expanded JSON controls+ setTimeout(() => {+ initExpandedJsonControls();+ }, 100);+ }++ /**+ * Render a single setting item+ * @param {Object} setting - The setting object+ * @returns {string} - The HTML for the setting item+ */+ function renderSettingItem(setting) {+ const settingId = `setting-${setting.key.replace(/\./g, '-')}`;+ let inputElement = '';++ // Generate the appropriate input element based on UI element type+ switch(setting.ui_element) {+ case 'textarea':+ // Check if it's JSON+ let isJson = false;+ let jsonClass = '';++ if (typeof setting.value === 'string' &&+ (setting.value.startsWith('{') || setting.value.startsWith('['))) {+ isJson = true;+ jsonClass = ' json-content';++ // Try to format the JSON for better display+ try {+ setting.value = JSON.stringify(JSON.parse(setting.value), null, 2);+ } catch (e) {+ // If parsing fails, keep the original value+ console.log('Error formatting JSON:', e);+ }++ // If it's an object (not an array), render individual controls+ if (setting.value.startsWith('{')) {+ try {+ const jsonObj = JSON.parse(setting.value);+ return renderExpandedJsonControls(setting, settingId, jsonObj);+ } catch (e) {+ console.log('Error parsing JSON for controls:', e);+ }+ }+ }++ inputElement = `+ <textarea id="${settingId}" name="${setting.key}"+ class="settings-textarea${jsonClass}"+ ${!setting.editable ? 'disabled' : ''}+ >${setting.value !== null ? setting.value : ''}</textarea>+ `;+ break;++ case 'select':+ inputElement = `+ <select id="${settingId}" name="${setting.key}"+ class="settings-select form-control"+ ${!setting.editable ? 'disabled' : ''}+ >+ `;++ if (setting.options) {+ setting.options.forEach(option => {+ const selected = option.value === setting.value ? 'selected' : '';+ inputElement += `<option value="${option.value}" ${selected}>${option.label || option.value}</option>`;+ });+ }++ inputElement += `</select>`;+ break;++ case 'checkbox':+ const checked = setting.value === true || setting.value === 'true' ? 'checked' : '';+ inputElement = `+ <div class="settings-checkbox-container">+ <label class="checkbox-label" for="${settingId}">+ <input type="checkbox" id="${settingId}" name="${setting.key}"+ class="settings-checkbox"+ ${checked}+ ${!setting.editable ? 'disabled' : ''}+ >+ <span class="checkbox-text">${setting.name}</span>+ </label>+ </div>+ `;+ break;++ case 'slider':+ case 'range':+ const min = setting.min_value !== null ? setting.min_value : 0;+ const max = setting.max_value !== null ? setting.max_value : 100;+ const step = setting.step !== null ? setting.step : 1;++ inputElement = `+ <div class="settings-range-container">+ <input type="range" id="${settingId}" name="${setting.key}"+ class="settings-range form-control"+ value="${setting.value !== null ? setting.value : min}"+ min="${min}" max="${max}" step="${step}"+ ${!setting.editable ? 'disabled' : ''}+ >+ <span class="settings-range-value">${setting.value !== null ? setting.value : min}</span>+ </div>+ `;+ break;++ case 'number':+ const numMin = setting.min_value !== null ? setting.min_value : '';+ const numMax = setting.max_value !== null ? setting.max_value : '';+ const numStep = setting.step !== null ? setting.step : 1;++ inputElement = `+ <input type="number" id="${settingId}" name="${setting.key}"+ class="settings-input form-control"+ value="${setting.value !== null ? setting.value : ''}"+ min="${numMin}" max="${numMax}" step="${numStep}"+ ${!setting.editable ? 'disabled' : ''}+ >+ `;+ break;++ default:+ // Handle JSON objects in text inputs+ if (typeof setting.value === 'string' &&+ (setting.value.startsWith('{') || setting.value.startsWith('['))) {++ // If it's an object (not an array), render individual controls+ if (setting.value.startsWith('{')) {+ try {+ const jsonObj = JSON.parse(setting.value);+ return renderExpandedJsonControls(setting, settingId, jsonObj);+ } catch (e) {+ console.log('Error parsing JSON for controls:', e);+ }+ }++ // It's a JSON string, use textarea instead+ inputElement = `+ <textarea id="${settingId}" name="${setting.key}"+ class="settings-textarea json-content"+ ${!setting.editable ? 'disabled' : ''}+ >${setting.value}</textarea>+ `;+ } else {+ // Default to text input+ inputElement = `+ <input type="${setting.ui_element === 'password' ? 'password' : 'text'}"+ id="${settingId}" name="${setting.key}"+ class="settings-input form-control"+ value="${setting.value !== null ? setting.value : ''}"+ ${!setting.editable ? 'disabled' : ''}+ >+ `;+ }+ break;+ }++ // Format the setting name to be more user-friendly if it contains underscores+ let settingName = setting.name;+ if (settingName.includes('_')) {+ settingName = formatCategoryName('', settingName);+ }++ // For checkboxes, we've already handled the label in the inputElement+ if (setting.ui_element === 'checkbox') {+ return `+ <div class="settings-item form-group" data-key="${setting.key}">+ ${inputElement}+ ${setting.description ? `+ <div class="input-help">+ ${setting.description}+ </div>+ ` : ''}+ </div>+ `;+ }++ // For non-checkbox elements, use the standard layout without info icons+ return `+ <div class="settings-item form-group" data-key="${setting.key}">+ <div class="settings-item-header">+ <label for="${settingId}" title="${settingName}">+ ${settingName}+ </label>+ </div>+ ${inputElement}+ ${setting.description ? `+ <div class="input-help">+ ${setting.description}+ </div>+ ` : ''}+ </div>+ `;+ }++ /**+ * Render expanded JSON controls for a JSON object setting+ * @param {Object} setting - The setting object+ * @param {string} settingId - The ID for the setting+ * @param {Object} jsonObj - The parsed JSON object+ * @returns {string} - The HTML for the expanded JSON controls+ */+ function renderExpandedJsonControls(setting, settingId, jsonObj) {+ let html = `+ <div class="settings-item form-group" data-key="${setting.key}">+ <div class="settings-item-header">+ <label for="${settingId}" title="${setting.name}">+ ${setting.name}+ </label>+ </div>+ <div class="json-expanded-controls">+ <input type="hidden" id="${settingId}_original" name="${setting.key}_original"+ value="${JSON.stringify(jsonObj)}">++ <div class="json-property-controls">+ `;++ // Create individual form controls for each JSON property+ for (const key in jsonObj) {+ const value = jsonObj[key];+ const controlId = `${settingId}_${key}`;+ const formattedName = formatPropertyName(key);+ let controlHtml = '';++ // Create appropriate control based on value type+ if (typeof value === 'boolean') {+ controlHtml = `+ <div class="json-property-item boolean-property" onclick="directToggleCheckbox('${controlId}')" data-checkboxid="${controlId}">+ <div class="checkbox-wrapper">+ <label class="checkbox-label" for="${controlId}">+ <input type="checkbox"+ id="${controlId}"+ name="${setting.key}_${key}"+ class="json-property-control"+ data-property="${key}"+ data-parent-key="${setting.key}"+ ${value ? 'checked' : ''}+ ${!setting.editable ? 'disabled' : ''}>+ <span class="checkbox-text">${formattedName}</span>+ </label>+ </div>+ </div>+ `;+ } else if (typeof value === 'number') {+ controlHtml = `+ <div class="json-property-item">+ <label for="${controlId}" class="property-label" title="${formattedName}">${formattedName}</label>+ <input type="number"+ id="${controlId}"+ name="${setting.key}_${key}"+ class="settings-input form-control json-property-control"+ data-property="${key}"+ data-parent-key="${setting.key}"+ value="${value}"+ ${!setting.editable ? 'disabled' : ''}>+ </div>+ `;+ } else if (typeof value === 'string' && (value === 'ITERATION' || value === 'NONE')) {+ controlHtml = `+ <div class="json-property-item">+ <label for="${controlId}" class="property-label" title="${formattedName}">${formattedName}</label>+ <select id="${controlId}"+ name="${setting.key}_${key}"+ class="settings-select form-control json-property-control"+ data-property="${key}"+ data-parent-key="${setting.key}"+ ${!setting.editable ? 'disabled' : ''}>+ <option value="ITERATION" ${value === 'ITERATION' ? 'selected' : ''}>Iteration</option>+ <option value="NONE" ${value === 'NONE' ? 'selected' : ''}>None</option>+ </select>+ </div>+ `;+ } else {+ controlHtml = `+ <div class="json-property-item">+ <label for="${controlId}" class="property-label" title="${formattedName}">${formattedName}</label>+ <input type="text"+ id="${controlId}"+ name="${setting.key}_${key}"+ class="settings-input form-control json-property-control"+ data-property="${key}"+ data-parent-key="${setting.key}"+ value="${value}"+ ${!setting.editable ? 'disabled' : ''}>+ </div>+ `;+ }++ html += controlHtml;+ }++ html += `+ </div>+ </div>+ ${setting.description ? `+ <div class="input-help">+ ${setting.description}+ </div>+ ` : ''}+ </div>+ `;++ return html;+ }++ /**+ * Format property name to be more user-friendly+ * @param {string} name - The property name+ * @returns {string} - The formatted property name+ */+ function formatPropertyName(name) {+ // Replace underscores with spaces and capitalize each word+ return name.split('_')+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');+ }++ /**+ * Handle settings form submission (for the entire form)+ * @param {Event} e - The submit event+ */+ function handleSettingsSubmit(e) {+ e.preventDefault();++ // Clear any previous errors+ document.querySelectorAll('.settings-error').forEach(element => {+ element.classList.remove('settings-error');+ });++ document.querySelectorAll('.settings-error-message').forEach(element => {+ element.remove();+ });++ // Collect form data+ const formData = {};++ // Get values from inputs+ document.querySelectorAll('.settings-input, .settings-textarea, .settings-select, .settings-range').forEach(input => {+ // Skip inputs that are part of expanded JSON controls+ if (input.classList.contains('json-property-control')) return;++ if (input.name) {+ // Check if value is a JSON object (textarea)+ if (input.tagName === 'TEXTAREA' && input.classList.contains('settings-textarea')) {+ try {+ const jsonValue = JSON.parse(input.value);+ formData[input.name] = jsonValue;+ } catch (e) {+ // Mark as invalid and don't include+ markInvalidInput(input, 'Invalid JSON format: ' + e.message);+ return;+ }+ } else {+ formData[input.name] = input.value;+ }+ }+ });++ // Get values from checkboxes+ document.querySelectorAll('.settings-checkbox').forEach(checkbox => {+ // Skip checkboxes that are part of expanded JSON controls+ if (checkbox.classList.contains('json-property-control')) return;++ if (checkbox.name) {+ formData[checkbox.name] = checkbox.checked;+ }+ });++ // Process expanded JSON controls+ document.querySelectorAll('input[id$="_original"]').forEach(input => {+ if (input.name && input.name.endsWith('_original')) {+ const actualName = input.name.replace('_original', '');++ // Get all controls for this setting+ const jsonData = {};+ const controls = document.querySelectorAll(`.json-property-control[data-parent-key="${actualName}"]`);++ controls.forEach(control => {+ const propName = control.dataset.property;++ if (propName) {+ if (control.type === 'checkbox') {+ jsonData[propName] = control.checked;+ } else if (control.tagName === 'SELECT') {+ jsonData[propName] = control.value;+ } else {+ // Attempt to convert to number if appropriate+ if (!isNaN(control.value) && control.value !== '') {+ // Check if it should be a float or int+ if (control.value.includes('.')) {+ jsonData[propName] = parseFloat(control.value);+ } else {+ jsonData[propName] = parseInt(control.value, 10);+ }+ } else {+ jsonData[propName] = control.value;+ }+ }+ }+ });++ // Special handling for corrupted JSON values (check for empty objects, single characters, etc.)+ if (Object.keys(jsonData).length === 0) {+ // Use the original JSON if it's non-empty and valid+ try {+ const originalJson = JSON.parse(input.value);+ if (originalJson && typeof originalJson === 'object' && Object.keys(originalJson).length > 0) {+ formData[actualName] = originalJson;+ } else {+ // Skip empty JSON+ console.log(`Skipping empty JSON object for ${actualName}`);+ }+ } catch (e) {+ console.log(`Error parsing original JSON for ${actualName}:`, e);+ }+ } else {+ // Use the collected data+ formData[actualName] = jsonData;+ }+ }+ });++ // For report nested values that might be corrupted, ensure they're proper objects+ Object.keys(formData).forEach(key => {+ // Check for various forms of corrupted data+ if (+ (typeof formData[key] === 'string' &&+ (formData[key] === '{' ||+ formData[key] === '[' ||+ formData[key] === '' ||+ formData[key] === null ||+ formData[key] === "[object Object]")) ||+ formData[key] === null+ ) {+ // This is likely a corrupted setting+ console.log(`Detected corrupted setting: ${key} with value: ${formData[key]}`);++ if (key.startsWith('report.')) {+ // For report settings, replace with empty object+ formData[key] = {};+ } else {+ // For other settings, delete to let defaults take over+ delete formData[key];+ }+ }+ });++ // Get raw config from editor if visible+ if (rawConfigSection.style.display !== 'none' && rawConfigEditor) {+ try {+ const rawConfig = JSON.parse(rawConfigEditor.value);++ // Process raw config and flatten the structure+ const flattenedConfig = {};++ // Process each namespace in the config (app, llm, search, report)+ Object.keys(rawConfig).forEach(namespace => {+ const section = rawConfig[namespace];++ // Each key in the section should be added to form data with namespace prefix+ Object.keys(section).forEach(key => {+ const fullKey = `${namespace}.${key}`;+ flattenedConfig[fullKey] = section[key];+ });+ });++ // Merge with form data, giving precedence to the raw JSON config+ Object.assign(formData, flattenedConfig);+ } catch (e) {+ showAlert('Invalid JSON in raw config editor: ' + e.message, 'error');+ return;+ }+ }++ // Show saving state for the form+ if (settingsForm) {+ settingsForm.classList.add('saving');+ }++ // Submit data to API+ submitSettingsData(formData, settingsForm);+ }++ /**+ * Show a success indicator on an input+ * @param {HTMLElement} element - The input element+ */+ function showSaveSuccess(element) {+ if (!element) return;++ // Add success class+ element.classList.add('save-success');++ // Remove it after a short delay+ setTimeout(() => {+ element.classList.remove('save-success');+ }, 1500);+ }++ /**+ * Submit settings data to the API+ * @param {Object} formData - The settings to save+ * @param {HTMLElement} sourceElement - The input element that triggered the save+ */+ function submitSettingsData(formData, sourceElement) {+ // Show loading indicator+ let loadingContainer = sourceElement;++ // If it's a specific input element, find its container to position the spinner correctly+ if (sourceElement && sourceElement.tagName) {+ if (sourceElement.type === 'checkbox') {+ // For checkboxes, use the checkbox label+ loadingContainer = sourceElement.closest('.checkbox-label') || sourceElement;+ } else if (sourceElement.classList.contains('json-property-control')) {+ // For JSON property controls, use the property item+ loadingContainer = sourceElement.closest('.json-property-item') || sourceElement;+ } else {+ // For other inputs, use the form-group or settings-item+ loadingContainer = sourceElement.closest('.form-group') ||+ sourceElement.closest('.settings-item') ||+ sourceElement;+ }+ }++ // Add the saving class to show the spinner+ if (loadingContainer) {+ loadingContainer.classList.add('saving');+ }++ // Get the keys being saved for reference+ const savingKeys = Object.keys(formData);++ // Store original values to show what changed+ const originalValues = {};+ savingKeys.forEach(key => {+ const settingObj = allSettings.find(s => s.key === key);+ originalValues[key] = settingObj ? settingObj.value : null;+ });++ fetch('/research/settings/save_all_settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCsrfToken()+ },+ body: JSON.stringify(formData),+ })+ .then(response => response.json())+ .then(data => {+ if (data.status === 'success') {+ // Show success indicator on the source element+ if (sourceElement) {+ showSaveSuccess(sourceElement);+ }++ // Remove loading state+ if (loadingContainer) {+ loadingContainer.classList.remove('saving');+ }++ // Update all settings data if it's a global change+ if (!sourceElement || savingKeys.length > 1) {+ // Update global state+ if (data.settings) {+ allSettings = processSettings(data.settings);+ }+ } else {+ // Update just the changed setting in our allSettings array+ if (savingKeys.length === 1) {+ const key = savingKeys[0];+ const settingIndex = allSettings.findIndex(s => s.key === key);++ if (settingIndex !== -1 && data.settings) {+ // Find the updated setting in the response+ const updatedSetting = data.settings.find(s => s.key === key);++ if (updatedSetting) {+ // Update the setting in our array+ allSettings[settingIndex] = processSettings([updatedSetting])[0];+ }+ }+ }+ }++ // Update the raw JSON editor if it's visible+ if (rawConfigSection && rawConfigSection.style.display === 'block') {+ prepareRawJsonEditor();+ }++ // Format a more informative message+ let successMessage = '';+ if (savingKeys.length === 1) {+ const key = savingKeys[0];+ const settingObj = allSettings.find(s => s.key === key);+ const oldValue = originalValues[key];+ const newValue = settingObj ? settingObj.value : formData[key];++ // Format the display name for better readability+ const displayName = key.split('.').pop().replace(/_/g, ' ');+ const capitalizedName = displayName.charAt(0).toUpperCase() + displayName.slice(1);++ // Format the values for display+ const oldDisplay = formatValueForDisplay(oldValue);+ const newDisplay = formatValueForDisplay(newValue);++ successMessage = `${capitalizedName}: ${oldDisplay} → ${newDisplay}`;+ } else {+ // If multiple settings were updated, use the original message+ successMessage = data.message || 'Settings saved successfully';+ }++ // Show toast notification if ui.showMessage is available+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(successMessage, 'success', 3000);+ // We're showing toast, so we pass true to skip showing the regular alert+ showAlert(successMessage, 'success', true);+ } else {+ // Fallback to regular alert, force showing it+ showAlert(successMessage, 'success', false);+ }+ } else {+ // Show error message+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(data.message || 'Error saving settings', 'error', 5000);+ showAlert(data.message || 'Error saving settings', 'error', true);+ } else {+ showAlert(data.message || 'Error saving settings', 'error', false);+ }++ // Remove loading state+ if (loadingContainer) {+ loadingContainer.classList.remove('saving');+ }+ }+ })+ .catch(error => {+ console.error('Error saving settings:', error);++ // Show error message+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage('Error saving settings: ' + error.message, 'error', 5000);+ showAlert('Error saving settings: ' + error.message, 'error', true);+ } else {+ showAlert('Error saving settings: ' + error.message, 'error', false);+ }++ // Remove loading state+ if (loadingContainer) {+ loadingContainer.classList.remove('saving');+ }+ });+ }+/**- * Initialize the settings component+ * Format a value for display in notifications+ * @param {any} value - The value to format+ * @returns {string} - Formatted value for display*/- function initializeSettings() {- // Set up event listeners- if (settingsForm) {- settingsForm.addEventListener('submit', handleSettingsSubmit);+ function formatValueForDisplay(value) {+ if (value === null || value === undefined) {+ return 'empty';+ } else if (typeof value === 'boolean') {+ return value ? 'enabled' : 'disabled';+ } else if (typeof value === 'object') {+ // For objects, show a simplified representation+ return '{...}';+ } else if (typeof value === 'string' && value.length > 20) {+ // Truncate long strings+ return `"${value.substring(0, 18)}..."`;+ } else if (typeof value === 'string') {+ return `"${value}"`;+ } else {+ return String(value);}-- // Initialize range inputs to display their values- rangeInputs.forEach(input => {- const valueDisplay = document.getElementById(`${input.id}-value`);- if (valueDisplay) {- // Update on input change- input.addEventListener('input', () => {- valueDisplay.textContent = input.value;- });+ }++ /**+ * Handle search input for filtering settings+ */+ function handleSearchInput() {+ // Only run this for the main settings dashboard+ if (!settingsContent || !settingsSearch) return;++ const searchValue = settingsSearch.value.toLowerCase();++ if (searchValue === '') {+ // If search is empty, just re-render based on active tab+ renderSettingsByTab(activeTab);+ return;+ }++ // Filter settings based on search+ const filteredSettings = allSettings.filter(setting => {+ return (+ setting.key.toLowerCase().includes(searchValue) ||+ setting.name.toLowerCase().includes(searchValue) ||+ (setting.description && setting.description.toLowerCase().includes(searchValue)) ||+ (setting.category && setting.category.toLowerCase().includes(searchValue))+ );+ });++ // Organize settings to avoid duplicate groups+ const groupedSettings = organizeSettings(filteredSettings, 'all');++ // Build HTML+ let html = '';++ // Define the order for the types+ const typeOrder = ['app', 'llm', 'search', 'report'];+ const prefixTypes = Object.keys(groupedSettings);++ // Sort prefixes by the defined order+ prefixTypes.sort((a, b) => {+ const aIndex = typeOrder.indexOf(a);+ const bIndex = typeOrder.indexOf(b);++ // If both are in the ordered list, sort by that order+ if (aIndex !== -1 && bIndex !== -1) {+ return aIndex - bIndex;}++ // If only one is in the list, it comes first+ if (aIndex !== -1) return -1;+ if (bIndex !== -1) return 1;++ // Alphabetically for anything else+ return a.localeCompare(b);});-- // Add click handler for the logo to navigate home- const logoLink = document.getElementById('logo-link');- if (logoLink) {- logoLink.addEventListener('click', () => {- window.location.href = '/research/';- });++ // For each type (app, llm, search, etc.)+ for (const type of prefixTypes) {+ // For each category in this type+ for (const category in groupedSettings[type]) {+ const sectionId = `section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`;++ html += `+ <div class="settings-section">+ <div class="settings-section-header" data-target="${sectionId}">+ <div class="settings-section-title" title="${category}">+ ${category}+ </div>+ <div class="settings-toggle-icon">+ <i class="fas fa-chevron-down"></i>+ </div>+ </div>+ <div id="${sectionId}" class="settings-section-body">+ `;++ // Add all settings in this category+ groupedSettings[type][category].forEach(setting => {+ html += renderSettingItem(setting);+ });++ html += `+ </div>+ </div>+ `;+ }}++ if (html === '') {+ html = '<div class="empty-state"><p>No settings found matching your search</p></div>';+ }++ // Add a container for alerts that will maintain proper positioning+ html = '<div id="filtered-settings-alert" class="settings-alert-container"></div>' + html;++ // Update the content+ settingsContent.innerHTML = html;++ // Initialize accordion behavior - all expanded for search results+ initAccordions();++ // Initialize JSON handling+ initJsonFormatting();++ // Initialize range inputs+ initRangeInputs();++ // Initialize auto-save handlers after re-rendering+ initAutoSaveHandlers();++ // Initialize expanded JSON controls+ setTimeout(() => {+ initExpandedJsonControls();+ }, 100);}-+/**- * Handle settings form submission- * @param {Event} e - The submit event+ * Handle the reset button click*/- function handleSettingsSubmit(e) {- e.preventDefault();-- // Show loading state- window.ui.showSpinner();-- // Get form data- const formData = new FormData(settingsForm);- const data = {};-- // Convert form data to JSON object- for (const [key, value] of formData.entries()) {- // Handle checkboxes separately (they're only included when checked)- if (settingsForm.elements[key].type === 'checkbox') {- data[key] = settingsForm.elements[key].checked;+ function handleReset() {+ // Reset to original values+ document.querySelectorAll('.settings-input, .settings-textarea, .settings-select').forEach(input => {+ // Skip inputs that are part of expanded JSON controls+ if (input.classList.contains('json-property-control')) return;++ const originalValue = originalSettings[input.name];++ if (typeof originalValue === 'object' && originalValue !== null) {+ input.value = JSON.stringify(originalValue, null, 2);} else {- data[key] = value;- }- }-- // Determine which settings form is being submitted based on form ID- let endpoint = '/research/api/save_main_config';-- if (settingsForm.id === 'search-engines-form') {- endpoint = '/research/api/save_search_engines_config';- } else if (settingsForm.id === 'collections-form') {- endpoint = '/research/api/save_collections_config';- } else if (settingsForm.id === 'api-keys-form') {- endpoint = '/research/api/save_api_keys_config';- } else if (settingsForm.id === 'llm-config-form') {- endpoint = '/research/api/save_llm_config';- }-- // Save the settings- window.api.postJSON(endpoint, data)- .then(response => {- if (response.success) {- window.ui.showNotification('Settings saved successfully');+ input.value = originalValue !== undefined ? originalValue : '';+ }+ });++ document.querySelectorAll('.settings-checkbox').forEach(checkbox => {+ // Skip checkboxes that are part of expanded JSON controls+ if (checkbox.classList.contains('json-property-control')) return;++ const originalValue = originalSettings[checkbox.name];+ checkbox.checked = originalValue === true || originalValue === 'true';+ });++ document.querySelectorAll('.settings-range').forEach(range => {+ const originalValue = originalSettings[range.name];+ range.value = originalValue !== undefined ? originalValue : range.min;++ // Update value display+ const valueDisplay = range.nextElementSibling;+ if (valueDisplay && valueDisplay.classList.contains('settings-range-value')) {+ valueDisplay.textContent = range.value;+ }+ });++ // Reset expanded JSON controls+ document.querySelectorAll('input[id$="_original"]').forEach(input => {+ if (input.name.endsWith('_original')) {+ const actualName = input.name.replace('_original', '');+ const originalValue = originalSettings[actualName];++ if (originalValue) {+ // Check for corrupted JSON (single character values like "{")+ if (typeof originalValue === 'string' && originalValue.length < 3) {+ console.log(`Skipping corrupted JSON value for ${actualName}`);+ return;+ }++ let jsonData = originalValue;+ if (typeof jsonData === 'string') {+ try {+ jsonData = JSON.parse(jsonData);+ } catch (e) {+ console.log('Error parsing JSON during reset:', e);+ return;+ }+ }++ // Update the hidden input+ input.value = JSON.stringify(jsonData);++ // Update individual controls+ for (const prop in jsonData) {+ const control = document.querySelector(`.json-property-control[data-parent-key="${actualName}"][data-property="${prop}"]`);+ if (control) {+ if (control.type === 'checkbox') {+ control.checked = !!jsonData[prop];+ } else if (control.tagName === 'SELECT') {+ control.value = jsonData[prop];+ } else {+ control.value = jsonData[prop];+ }+ }+ }+ }+ }+ });++ // Format JSON values+ initJsonFormatting();++ showAlert('Settings reset to last saved values', 'info');+ }++ /**+ * Handle the reset to defaults button click+ */+ function handleResetToDefaults() {+ // Show confirmation dialog+ if (confirm('Are you sure you want to reset ALL settings to their default values? This cannot be undone.')) {+ // Call the reset to defaults API+ fetch('/research/settings/reset_to_defaults', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCsrfToken()+ }+ })+ .then(response => response.json())+ .then(data => {+ if (data.status === 'success') {+ showAlert('Settings have been reset to defaults. Reloading page...', 'success');++ // Reload the page after a brief delay to show the success message+ setTimeout(() => {+ window.location.reload();+ }, 1500);} else {- window.ui.showErrorMessage('Failed to save settings: ' + (response.error || 'Unknown error'));+ showAlert('Error resetting settings: ' + data.message, 'error');}}).catch(error => {- window.ui.showErrorMessage('Error saving settings: ' + error.message);- })- .finally(() => {- window.ui.hideSpinner();+ showAlert('Error resetting settings: ' + error, 'error');});+ }}-+/*** Toggle the display of raw configuration*/function toggleRawConfig() {if (rawConfigSection && rawConfigEditor) {const isVisible = rawConfigSection.style.display !== 'none';-++ // If hiding the editor, try to apply changes+ if (isVisible) {+ try {+ // Parse the JSON to validate it+ const rawConfig = JSON.parse(rawConfigEditor.value);++ // Process and flatten the JSON+ const flattenedConfig = {};++ Object.keys(rawConfig).forEach(namespace => {+ const section = rawConfig[namespace];++ Object.keys(section).forEach(key => {+ const fullKey = `${namespace}.${key}`;+ flattenedConfig[fullKey] = section[key];+ });+ });++ // Save the changes to apply them to UI+ submitSettingsData(flattenedConfig, null);+ } catch (e) {+ // Show error but don't prevent hiding the editor+ showAlert('Invalid JSON in editor: ' + e.message, 'error');+ }+ }++ // Toggle visibilityrawConfigSection.style.display = isVisible ? 'none' : 'block';- rawConfigEditor.style.display = isVisible ? 'none' : 'block';-- if (rawConfigToggle) {- const toggleText = document.getElementById('toggle-text');- if (toggleText) {- toggleText.textContent = isVisible ? 'Show Raw Configuration' : 'Hide Raw Configuration';++ // Update toggle text+ const toggleText = document.getElementById('toggle-text');+ if (toggleText) {+ toggleText.textContent = isVisible ? 'Show JSON Configuration' : 'Hide JSON Configuration';+ }++ // If showing the config, prepare it+ if (!isVisible) {+ prepareRawJsonEditor();+ }+ }+ }++ /**+ * Prepare the raw JSON editor with all settings+ */+ function prepareRawJsonEditor() {+ if (rawConfigEditor && allSettings.length > 0) {+ // Try to parse existing JSON from editor if it exists+ let existingConfig = {};+ try {+ if (rawConfigEditor.value) {+ existingConfig = JSON.parse(rawConfigEditor.value);}+ } catch (e) {+ console.warn('Could not parse existing JSON config, starting fresh');+ existingConfig = {};}++ // Prepare settings as a JSON object+ const settingsObj = {};++ // Group by prefix (app, llm, search, report)+ allSettings.forEach(setting => {+ const key = setting.key;+ const parts = key.split('.');+ const prefix = parts[0];++ // Initialize namespace if needed+ if (!settingsObj[prefix]) {+ settingsObj[prefix] = {};+ }++ // Parse JSON values+ let value = setting.value;+ if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {+ try {+ value = JSON.parse(value);+ } catch (e) {+ // Leave as string if not valid JSON+ }+ }++ // Add to settings object+ settingsObj[prefix][key.substring(prefix.length + 1)] = value;+ });++ // Merge with existing config to preserve unknown parameters+ Object.keys(existingConfig).forEach(prefix => {+ if (!settingsObj[prefix]) {+ settingsObj[prefix] = {};+ }++ Object.keys(existingConfig[prefix]).forEach(key => {+ // Only keep parameters that don't exist in our known settings+ const fullKey = `${prefix}.${key}`;+ const exists = allSettings.some(s => s.key === fullKey);++ if (!exists) {+ settingsObj[prefix][key] = existingConfig[prefix][key];+ }+ });+ });++ // Format as pretty JSON+ rawConfigEditor.value = JSON.stringify(settingsObj, null, 2);+ }+ }++ /**+ * Function to open file location (for collections config)+ * @param {string} filePath - The file path to open+ */+ function openFileLocation(filePath) {+ // Create a hidden form and submit it to a route that will open the file location+ const form = document.createElement('form');+ form.method = 'POST';+ form.action = "/research/open_file_location";++ const input = document.createElement('input');+ input.type = 'hidden';+ input.name = 'file_path';+ input.value = filePath;++ form.appendChild(input);+ document.body.appendChild(form);+ form.submit();+ }++ /**+ * Initialize click handlers for checkbox wrappers+ */+ function initCheckboxWrappers() {+ // No longer needed - using direct onclick attribute instead+ }++ /**+ * Toggle checkbox directly from onclick event+ * Simple, direct function to toggle checkboxes+ * @param {string} checkboxId - The ID of the checkbox to toggle+ */+ function directToggleCheckbox(checkboxId) {+ const checkbox = document.getElementById(checkboxId);+ if (checkbox && !checkbox.disabled) {+ // Toggle the checkbox state+ checkbox.checked = !checkbox.checked;++ // Trigger change event for listeners+ const changeEvent = new Event('change', { bubbles: true });+ checkbox.dispatchEvent(changeEvent);++ // Stop event propagation+ event.stopPropagation();}}-++ /**+ * Get CSRF token from meta tag+ */+ function getCsrfToken() {+ return document.querySelector('meta[name="csrf-token"]').getAttribute('content');+ }+/**- * Save raw configuration+ * Handle the fix corrupted settings button click*/- function saveRawConfig() {- if (rawConfigTextarea) {- const rawConfig = rawConfigTextarea.value;-- window.ui.showSpinner();-- window.api.saveRawConfig(rawConfig)- .then(data => {- if (data.success) {- window.ui.showNotification('Configuration saved successfully');- // Reload the page to show updated values+ function handleFixCorruptedSettings() {+ // Call the fix corrupted settings API+ fetch('/research/settings/fix_corrupted_settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCsrfToken()+ }+ })+ .then(response => response.json())+ .then(data => {+ if (data.status === 'success') {+ if (data.fixed_settings && data.fixed_settings.length > 0) {+ showAlert(`Fixed ${data.fixed_settings.length} corrupted settings. Reloading page...`, 'success');++ // Reload the page after a brief delay to show the success message+ setTimeout(() => {window.location.reload();- } else {- window.ui.showErrorMessage('Error saving configuration: ' + (data.error || 'Unknown error'));+ }, 1500);+ } else {+ showAlert('No corrupted settings were found.', 'info');+ }+ } else {+ showAlert('Error fixing corrupted settings: ' + data.message, 'error');+ }+ })+ .catch(error => {+ showAlert('Error fixing corrupted settings: ' + error, 'error');+ });+ }++ /**+ * Fetch available model providers from API+ */+ 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;++ // Check for Ollama models+ if (data.providers && data.providers.ollama_models && data.providers.ollama_models.length > 0) {+ modelOptions = [...modelOptions, ...data.providers.ollama_models];}- })- .catch(error => {- window.ui.showErrorMessage('Error saving configuration: ' + error.message);- })- .finally(() => {- window.ui.hideSpinner();- });+ }++ // Initialize model dropdowns if on the LLM tab+ if (activeTab === 'llm' || activeTab === 'all') {+ initializeModelDropdowns();+ }+ })+ .catch(error => console.error('Error loading models:', error));+ }++ /**+ * Fetch available search engines from API+ */+ function fetchSearchEngines() {+ 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;++ // Initialize search engine dropdowns if on the right tab+ if (activeTab === 'search' || activeTab === 'all') {+ initializeSearchEngineDropdowns();+ }+ }+ })+ .catch(error => console.error('Error loading search engines:', error));+ }++ /**+ * Initialize custom model dropdowns in the LLM section+ */+ function initializeModelDropdowns() {+ // Check for the model input field in the LLM section+ const modelInput = document.getElementById('llm-model');+ const providerInput = document.getElementById('llm-provider');++ if (modelInput) {+ // Create a dropdown for the model field+ const dropdownId = 'model-dropdown';+ const dropdownListId = `${dropdownId}-list`;++ // 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;++ // Create dropdown list element+ const dropdownList = document.createElement('div');+ dropdownList.className = 'custom-dropdown-list';+ dropdownList.id = dropdownListId;++ // Replace the input with the dropdown+ const parent = modelInput.parentNode;+ parent.insertBefore(dropdownContainer, modelInput);+ dropdownContainer.appendChild(modelInput);+ dropdownContainer.appendChild(dropdownList);++ // Add custom-dropdown-input class to the input+ modelInput.classList.add('custom-dropdown-input');++ // 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.'+ );+ }+ }+ }++ // Also handle the provider dropdown if present+ if (providerInput) {+ // Create a dropdown for the provider field+ const dropdownId = 'provider-dropdown';+ const dropdownListId = `${dropdownId}-list`;++ // 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;++ // Create dropdown list element+ const dropdownList = document.createElement('div');+ dropdownList.className = 'custom-dropdown-list';+ dropdownList.id = dropdownListId;++ // Replace the input with the dropdown+ const parent = providerInput.parentNode;+ parent.insertBefore(dropdownContainer, providerInput);+ dropdownContainer.appendChild(providerInput);+ dropdownContainer.appendChild(dropdownList);++ // Add custom-dropdown-input class to the input+ providerInput.classList.add('custom-dropdown-input');++ // Filter only provider options+ const providerOptions = modelOptions.filter(opt =>+ opt.value && typeof opt.value === 'string' &&+ !opt.value.includes(':') && !opt.value.includes('/')+ );++ // 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.'+ );+ }+ }}}-+/**- * Cancel raw configuration editing+ * Initialize custom search engine dropdowns*/- function cancelRawEdit() {- if (rawConfigSection && rawConfigEditor && rawConfigToggle) {- rawConfigSection.style.display = 'none';- rawConfigEditor.style.display = 'none';-- const toggleText = document.getElementById('toggle-text');- if (toggleText) {- toggleText.textContent = 'Show Raw Configuration';+ function initializeSearchEngineDropdowns() {+ // Check for the search engine input field+ const searchEngineInput = document.getElementById('search-tool');++ if (searchEngineInput) {+ // Create a dropdown for the search engine field+ const dropdownId = 'search-engine-dropdown';+ const dropdownListId = `${dropdownId}-list`;++ // Create dropdown container if it doesn't exist+ let dropdownContainer = searchEngineInput.closest('.custom-dropdown');+ if (!dropdownContainer) {+ // Create custom dropdown container+ dropdownContainer = document.createElement('div');+ dropdownContainer.className = 'custom-dropdown';+ dropdownContainer.id = dropdownId;++ // Create dropdown list element+ const dropdownList = document.createElement('div');+ dropdownList.className = 'custom-dropdown-list';+ dropdownList.id = dropdownListId;++ // Replace the input with the dropdown+ const parent = searchEngineInput.parentNode;+ parent.insertBefore(dropdownContainer, searchEngineInput);+ dropdownContainer.appendChild(searchEngineInput);+ dropdownContainer.appendChild(dropdownList);++ // Add custom-dropdown-input class to the input+ searchEngineInput.classList.add('custom-dropdown-input');++ // Set up the dropdown+ if (window.setupCustomDropdown) {+ window.setupCustomDropdown(+ searchEngineInput,+ dropdownList,+ () => searchEngineOptions,+ (value, item) => {+ // Update the searchEngineInput value+ searchEngineInput.value = value;+ // Trigger a change event so the form knows it's changed+ searchEngineInput.dispatchEvent(new Event('change', { bubbles: true }));+ },+ false, // Don't allow custom values+ 'No search engines available.'+ );+ }+ }+ }+ }++ /**+ * Process settings to handle object values+ */+ function processSettings(settings) {+ return settings.map(setting => {+ const processedSetting = {...setting};++ // Convert object values to JSON strings for display+ if (typeof processedSetting.value === 'object' && processedSetting.value !== null) {+ processedSetting.value = JSON.stringify(processedSetting.value, null, 2);+ }++ // Handle corrupted JSON values (e.g., just "{" or "[" or "[object Object]")+ if (typeof processedSetting.value === 'string' &&+ (processedSetting.value === '{' ||+ processedSetting.value === '[' ||+ processedSetting.value === '{}' ||+ processedSetting.value === '[]' ||+ processedSetting.value === '[object Object]')) {++ console.log(`Detected corrupted JSON value for ${processedSetting.key}: ${processedSetting.value}`);++ // Initialize with empty object for corrupted JSON values+ if (processedSetting.key.startsWith('report.')) {+ processedSetting.value = '{}';+ }}++ return processedSetting;+ });+ }++ /**+ * Add CSS styles for loading indicators and saved state+ */+ function addDynamicStyles() {+ // Create a style element if it doesn't exist+ let styleEl = document.getElementById('settings-dynamic-styles');+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = 'settings-dynamic-styles';+ document.head.appendChild(styleEl);}++ // Add CSS for saving and success states+ styleEl.textContent = `+ .saving {+ opacity: 0.7;+ pointer-events: none;+ position: relative;+ }++ .saving::after {+ content: '';+ position: absolute;+ top: 50%;+ right: 10px;+ width: 16px;+ height: 16px;+ margin-top: -8px;+ border: 2px solid rgba(0, 123, 255, 0.1);+ border-top-color: #007bff;+ border-radius: 50%;+ animation: spinner 0.8s linear infinite;+ z-index: 10;+ }++ .save-success {+ border-color: #28a745 !important;+ transition: border-color 0.3s;+ }++ @keyframes spinner {+ to { transform: rotate(360deg); }+ }++ .spinner {+ width: 40px;+ height: 40px;+ border: 3px solid rgba(255, 255, 255, 0.1);+ border-radius: 50%;+ border-top-color: var(--accent-primary);+ animation: spin 1s ease-in-out infinite;+ margin: 0 auto 1rem auto;+ display: block;+ }++ .settings-item .checkbox-label {+ margin-top: 8px;+ padding-left: 0;+ }++ // Add styles for the loading spinner+ const spinnerStyles =+ '.saving {' ++ ' position: relative;' ++ '}' ++ '' ++ '.saving:before {' ++ ' content: \'\';' ++ ' position: absolute;' ++ ' left: -25px;' ++ ' top: 50%;' ++ ' transform: translateY(-50%);' ++ ' width: 16px;' ++ ' height: 16px;' ++ ' border: 2px solid rgba(255, 255, 255, 0.3);' ++ ' border-radius: 50%;' ++ ' border-top-color: #fff;' ++ ' animation: spinner .6s linear infinite;' ++ ' z-index: 10;' ++ '}' ++ '' ++ '.checkbox-label.saving:before {' ++ ' left: -25px;' ++ ' top: 50%;' ++ '}' ++ '' ++ '@keyframes spinner {' ++ ' to {transform: translateY(-50%) rotate(360deg);}' ++ '}';++ // Add the styles to the head+ const style = document.createElement('style');+ style.textContent = spinnerStyles;+ document.head.appendChild(style);+ `;}-- // Initialize when the DOM is ready++ // Initialize dynamic styles+ addDynamicStyles();++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', initializeSettings);-- // Expose functions to the global scope if they need to be called from HTML- window.toggleRawConfig = toggleRawConfig;- window.saveRawConfig = saveRawConfig;- window.cancelRawEdit = cancelRawEdit;--})();\ No newline at end of file+ } else {+ initializeSettings();+ }++ // Expose the setupCustomDropdowns function for other modules to use+ window.setupSettingsDropdowns = initializeModelDropdowns;++ /**+ * Show an alert message at the top of the settings form+ * @param {string} message - The message to display+ * @param {string} type - The alert type: success, error, warning, info+ * @param {boolean} skipIfToastShown - Whether to skip showing this alert if a toast was already shown+ */+ function showAlert(message, type, skipIfToastShown = true) {+ // If we're showing a toast and we want to skip the regular alert, just return+ if (skipIfToastShown && window.ui && window.ui.showMessage) {+ return;+ }++ // Find the alert container - look for filtered settings alert first+ let alertContainer = document.getElementById('filtered-settings-alert');++ // If not found, fall back to the regular alert+ if (!alertContainer) {+ alertContainer = document.getElementById('settings-alert');+ }++ if (!alertContainer) return;++ // Clear any existing alerts+ alertContainer.innerHTML = '';++ // Create alert element+ const alert = document.createElement('div');+ alert.className = `alert alert-${type}`;+ alert.innerHTML = `<i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${message}`;++ // Add a close button+ const closeBtn = document.createElement('span');+ closeBtn.className = 'alert-close';+ closeBtn.innerHTML = '×';+ closeBtn.addEventListener('click', () => {+ alert.remove();+ alertContainer.style.display = 'none';+ });++ alert.appendChild(closeBtn);++ // Add to container+ alertContainer.appendChild(alert);+ alertContainer.style.display = 'block';++ // Auto-hide after 5 seconds+ setTimeout(() => {+ alert.remove();+ if (alertContainer.children.length === 0) {+ alertContainer.style.display = 'none';+ }+ }, 5000);+ }+})();diff --git a/src/local_deep_research/web/templates/api_keys_config.html b/src/local_deep_research/web/templates/api_keys_config.htmldeleted file mode 100644index 24c5452746..0000000000--- a/src/local_deep_research/web/templates/api_keys_config.html+++ /dev/null@@ -1,82 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - API Keys</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <!-- Sidebar content (keep as is) -->- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="api-keys-settings">- <div class="page-header">- <div class="results-header">- <h1>API Keys Configuration</h1>- <div class="results-actions">- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-- <div class="card">- <div class="card-content">- <h2>API Keys Configuration File</h2>- <p>To edit your API keys configuration, open this file with your preferred text editor. Note that files beginning with a dot or located in configuration directories may be hidden by default in your file explorer. You may need to enable "Show Hidden Files" in your file explorer settings to view it.</p>- <div class="file-path">{{ secrets_file_path }}</div>-- <button onclick="openFileLocation('{{ secrets_file_path }}')" class="btn btn-primary">- <i class="fas fa-folder-open"></i> Open Containing Folder- </button>-- <h3 class="mt-4">Configuration Example</h3>- <pre class="config-example">-# API Keys for Deep Research System-# This file contains sensitive information and should not be shared.--# LLM Service API Keys-ANTHROPIC_API_KEY = "your-anthropic-api-key-here"-OPENAI_API_KEY = "your-openai-api-key-here"--# Search Service API Keys-GOOGLE_API_KEY = "your-google-api-key-here"-SERP_API_KEY = "your-serp-api-key-here"-GUARDIAN_API_KEY = "your-guardian-api-key-here"-GOOGLE_PSE_API_KEY = "your-google-pse-api-key-here"-GOOGLE_PSE_ENGINE_ID = "your-google-pse-engine-id-here"- </pre>- </div>- </div>- </div>- </main>- </div>-- <script>- function openFileLocation(filePath) {- // Create a hidden form and submit it to a route that will open the file location- const form = document.createElement('form');- form.method = 'POST';- form.action = "{{ url_for('research.open_file_location') }}";-- const input = document.createElement('input');- input.type = 'hidden';- input.name = 'file_path';- input.value = filePath;-- form.appendChild(input);- document.body.appendChild(form);- form.submit();- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/app_settings.html b/src/local_deep_research/web/templates/app_settings.htmldeleted file mode 100644index 24bcd3ebc3..0000000000--- a/src/local_deep_research/web/templates/app_settings.html+++ /dev/null@@ -1,76 +0,0 @@-{% extends "base.html" %}-{% from "components/settings_form.html" import render_settings_form, render_settings_section, render_setting %}--{% set active_page = 'settings' %}--{% block title %}Application Settings - Deep Research System{% endblock %}--{% block content %}-<div class="page active" id="settings">- <div class="page-header">- <h1>Application Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="card">- <div class="card-content">- {{ render_settings_form(settings_by_category, 'app-settings-form', url_for('settings.app_settings')) }}-- <div class="form-actions mt-4">- <a href="{{ url_for('settings.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- document.addEventListener('DOMContentLoaded', function() {- // Initialize sliders to display their values- const sliders = document.querySelectorAll('input[type="range"]');- sliders.forEach(slider => {- const valueDisplay = document.getElementById(`${slider.id}-value`);- if (valueDisplay) {- // Set initial value- valueDisplay.textContent = slider.value;-- // Update on input change- slider.addEventListener('input', () => {- valueDisplay.textContent = slider.value;- });- }- });-- // Add form submission handler- const form = document.getElementById('app-settings-form');- if (form) {- form.addEventListener('submit', function(e) {- // Handle checkbox values- const checkboxes = form.querySelectorAll('input[type="checkbox"]');- checkboxes.forEach(checkbox => {- if (!checkbox.checked) {- // Create a hidden input to send the false value- const hiddenInput = document.createElement('input');- hiddenInput.type = 'hidden';- hiddenInput.name = checkbox.name;- hiddenInput.value = 'false';- form.appendChild(hiddenInput);- }- });- });- }- });-</script>-{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/collections_config.html b/src/local_deep_research/web/templates/collections_config.htmldeleted file mode 100644index 1794b01ba4..0000000000--- a/src/local_deep_research/web/templates/collections_config.html+++ /dev/null@@ -1,90 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - Local Collections</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <!-- Sidebar content (keep as is) -->- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="collections-settings">- <div class="page-header">- <div class="results-header">- <h1>Local Document Collections</h1>- <div class="results-actions">- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-- <div class="card">- <div class="card-content">- <h2>Local Collections Configuration File</h2>- <p>To edit your local collections configuration, open this file with your preferred text editor:</p>- <div class="file-path">{{ collections_file_path }}</div>-- <button onclick="openFileLocation('{{ collections_file_path }}')" class="btn btn-primary">- <i class="fas fa-folder-open"></i> Open Containing Folder- </button>-- <h3 class="mt-4">Default Configuration Example</h3>- <pre class="config-example">-[project_docs]-name = "Project Documents"-description = "Project documentation and specifications"-paths = ["/path/to/project_documents"]-enabled = true-embedding_model = "all-MiniLM-L6-v2"-embedding_device = "cpu" # "cpu" or "cuda" for GPU-embedding_model_type = "sentence_transformers"-max_results = 20-max_filtered_results = 5-chunk_size = 1000-chunk_overlap = 200-cache_dir = ".cache/local_search/project_docs"--# Default embedding settings for all collections-[DEFAULT_EMBEDDING_SETTINGS]-DEFAULT_EMBEDDING_MODEL = "all-MiniLM-L6-v2"-DEFAULT_EMBEDDING_DEVICE = "cpu"-DEFAULT_EMBEDDING_MODEL_TYPE = "sentence_transformers"-FORCE_REINDEX = false-CACHE_DIR = ".cache/local_search"- </pre>- </div>- </div>- </div>- </main>- </div>-- <script>- function openFileLocation(filePath) {- // Create a hidden form and submit it to a route that will open the file location- const form = document.createElement('form');- form.method = 'POST';- form.action = "{{ url_for('research.open_file_location') }}";-- const input = document.createElement('input');- input.type = 'hidden';- input.name = 'file_path';- input.value = filePath;-- form.appendChild(input);- document.body.appendChild(form);- form.submit();- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/components/custom_dropdown.html b/src/local_deep_research/web/templates/components/custom_dropdown.htmlnew file mode 100644index 0000000000..319f0d6c96--- /dev/null+++ b/src/local_deep_research/web/templates/components/custom_dropdown.html@@ -0,0 +1,20 @@+{% macro render_dropdown(input_id, dropdown_id, placeholder, label=None, help_text=None, allow_custom=False) %}+<div class="form-group">+ {% if label %}+ <label for="{{ input_id }}">{{ label }}</label>+ {% endif %}+ <div class="custom-dropdown" id="{{ dropdown_id }}">+ <input type="text"+ id="{{ input_id }}"+ name="{{ input_id }}"+ class="custom-dropdown-input"+ placeholder="{{ placeholder }}"+ autocomplete="off"+ aria-haspopup="listbox">+ <div class="custom-dropdown-list" id="{{ dropdown_id }}-list"></div>+ </div>+ {% if help_text %}+ <span class="input-help">{{ help_text }}</span>+ {% endif %}+</div>+{% endmacro %}diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.htmlindex 836c0ad71d..6beaefd7c6 100644--- a/src/local_deep_research/web/templates/components/settings_form.html+++ b/src/local_deep_research/web/templates/components/settings_form.html@@ -1,107 +1,271 @@-{% macro render_setting(setting) %}- {% if setting.ui_element == 'text' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <input type="text" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>+{% macro render_setting(setting, id_prefix="") %}+ {% set setting_id = (id_prefix ~ "-" if id_prefix else "") ~ setting.key|replace(".", "-") %}++ <div class="settings-item form-group" data-key="{{ setting.key }}">+ <div class="settings-item-header">+ <label for="{{ setting_id }}">{{ setting.name }}</label>{% if setting.description %}- <span class="input-help">{{ setting.description }}</span>+ <span class="settings-tooltip" title="{{ setting.description }}">+ <i class="fas fa-info-circle"></i>+ </span>{% endif %}</div>- {% elif setting.ui_element == 'textarea' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <textarea class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" rows="3" {% if not setting.editable %}disabled{% endif %}>{{ setting.value }}</textarea>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>++ {% if setting.ui_element == "textarea" %}+ {# Check if this is JSON content that should be expanded into controls #}+ {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}+ <div class="json-expanded-controls">+ {% if setting.value is string %}+ {% set json_value = setting.value|tojson %}+ {% else %}+ {% set json_value = setting.value %}+ {% endif %}++ {# Store the original JSON in a hidden field #}+ <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">++ {# Create individual form controls for each JSON property #}+ <div class="json-property-controls">+ {% for key, value in json_value.items() %}+ <div class="json-property-item">+ <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>++ {% if value is boolean %}+ <div class="checkbox-label">+ <input type="checkbox"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ {% if value %}checked{% endif %}+ {% if not setting.editable %}disabled{% endif %}>+ <span class="checkbox-text">{{ key|replace("_", " ")|title }}</span>+ </div>+ {% elif value is number %}+ <input type="number"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="settings-input form-control json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ value="{{ value }}"+ {% if not setting.editable %}disabled{% endif %}>+ {% elif value is string and value in ["ITERATION", "NONE"] %}+ <select id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="settings-select form-control json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ {% if not setting.editable %}disabled{% endif %}>+ <option value="ITERATION" {% if value == "ITERATION" %}selected{% endif %}>Iteration</option>+ <option value="NONE" {% if value == "NONE" %}selected{% endif %}>None</option>+ </select>+ {% else %}+ <input type="text"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="settings-input form-control json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ value="{{ value }}"+ {% if not setting.editable %}disabled{% endif %}>+ {% endif %}++ <div class="input-help">{{ key|replace("_", " ")|title }}</div>+ </div>+ {% endfor %}+ </div>+ </div>+ {% else %}+ <textarea+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ class="settings-textarea form-control"+ {% if not setting.editable %}disabled{% endif %}+ >{{ setting.value if setting.value is not none else "" }}</textarea>{% endif %}- </div>- {% elif setting.ui_element == 'select' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <select class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" {% if not setting.editable %}disabled{% 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 }}</option>+ <option+ value="{{ option.value }}"+ {% if option.value == setting.value %}selected{% endif %}+ >+ {{ option.label if option.label else option.value }}+ </option>{% endfor %}</select>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% elif setting.ui_element == 'checkbox' %}- <div class="form-group checkbox-group">- <input type="checkbox" id="{{ setting.key }}" name="{{ setting.key }}" {% if setting.value %}checked{% endif %} {% if not setting.editable %}disabled{% endif %}>- <label for="{{ setting.key }}">{{ setting.name }}</label>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% elif setting.ui_element == 'slider' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <div class="slider-container">- <input type="range" class="slider" id="{{ setting.key }}" name="{{ setting.key }}" min="{{ setting.min_value }}" max="{{ setting.max_value }}" step="{{ setting.step }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>- <span class="range-value" id="{{ setting.key }}-value">{{ setting.value }}</span>++ {% elif setting.ui_element == "checkbox" %}+ <div class="checkbox-label">+ <input+ type="checkbox"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ {% if setting.value == true or setting.value == "true" %}checked{% endif %}+ {% if not setting.editable %}disabled{% endif %}+ >+ <span class="checkbox-text">{{ setting.name }}</span></div>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% elif setting.ui_element == 'number' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" min="{{ setting.min_value }}" max="{{ setting.max_value }}" step="{{ setting.step if setting.step else 1 }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% elif setting.ui_element == 'color' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <input type="color" class="form-control color-picker" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% elif setting.ui_element == 'password' %}- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <input type="password" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>- {% endif %}- </div>- {% else %}- <!-- Default to text input -->- <div class="form-group">- <label for="{{ setting.key }}">{{ setting.name }}</label>- <input type="text" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" {% if not setting.editable %}disabled{% endif %}>- {% if setting.description %}- <span class="input-help">{{ setting.description }}</span>++ {% elif setting.ui_element == "slider" or setting.ui_element == "range" %}+ {% set min_value = setting.min_value if setting.min_value is not none else 0 %}+ {% set max_value = setting.max_value if setting.max_value is not none else 100 %}+ {% set step = setting.step if setting.step is not none else 1 %}++ <div class="settings-range-container">+ <input+ type="range"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ class="settings-range form-control"+ value="{{ setting.value if setting.value is not none else min_value }}"+ min="{{ min_value }}"+ max="{{ max_value }}"+ step="{{ step }}"+ {% if not setting.editable %}disabled{% endif %}+ >+ <span class="settings-range-value" id="{{ setting_id }}-value">{{ setting.value if setting.value is not none else min_value }}</span>+ </div>++ {% elif setting.ui_element == "number" %}+ {% set min_value = setting.min_value if setting.min_value is not none else "" %}+ {% set max_value = setting.max_value if setting.max_value is not none else "" %}+ {% set step = setting.step if setting.step is not none else 1 %}++ <input+ type="number"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ class="settings-input form-control"+ value="{{ setting.value if setting.value is not none else '' }}"+ min="{{ min_value }}"+ max="{{ max_value }}"+ step="{{ step }}"+ {% if not setting.editable %}disabled{% endif %}+ >++ {% elif setting.ui_element == "password" %}+ <input+ type="password"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ class="settings-input form-control"+ value="{{ setting.value if setting.value is not none else '' }}"+ {% if not setting.editable %}disabled{% endif %}+ >++ {% else %}+ {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}+ <div class="json-expanded-controls">+ {% if setting.value is string %}+ {% set json_value = setting.value|tojson %}+ {% else %}+ {% set json_value = setting.value %}+ {% endif %}++ {# Store the original JSON in a hidden field #}+ <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">++ {# Create individual form controls for each JSON property #}+ <div class="json-property-controls">+ {% for key, value in json_value.items() %}+ <div class="json-property-item">+ <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>++ {% if value is boolean %}+ <div class="checkbox-label">+ <input type="checkbox"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ {% if value %}checked{% endif %}+ {% if not setting.editable %}disabled{% endif %}>+ <span class="checkbox-text">{{ key|replace("_", " ")|title }}</span>+ </div>+ {% elif value is number %}+ <input type="number"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="settings-input form-control json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ value="{{ value }}"+ {% if not setting.editable %}disabled{% endif %}>+ {% else %}+ <input type="text"+ id="{{ setting_id }}_{{ key }}"+ name="{{ setting.key }}_{{ key }}"+ class="settings-input form-control json-property-control"+ data-property="{{ key }}"+ data-parent-key="{{ setting.key }}"+ value="{{ value }}"+ {% if not setting.editable %}disabled{% endif %}>+ {% endif %}++ <div class="input-help">{{ key|replace("_", " ")|title }}</div>+ </div>+ {% endfor %}+ </div>+ </div>+ {% else %}+ <input+ type="text"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ class="settings-input form-control"+ value="{{ setting.value if setting.value is not none else '' }}"+ {% if not setting.editable %}disabled{% endif %}+ >{% endif %}- </div>- {% endif %}+ {% endif %}++ {% if setting.description %}+ <div class="input-help">{{ setting.description }}</div>+ {% endif %}+ </div>{% endmacro %}-{% macro render_settings_section(title, settings, icon=None) %}+{% macro render_settings_section(section_title, section_id, settings, form_id='settings-form') %}<div class="settings-section">- <h2>{% if icon %}<i class="{{ icon }}"></i> {% endif %}{{ title }}</h2>- {% for setting in settings %}- {% if setting.visible %}- {{ render_setting(setting) }}- {% endif %}- {% endfor %}+ <div class="settings-section-header" data-target="{{ section_id }}">+ <div class="settings-section-title">+ {{ section_title }}+ </div>+ <div class="settings-toggle-icon">+ <i class="fas fa-chevron-down"></i>+ </div>+ </div>+ <div id="{{ section_id }}" class="settings-section-body">+ {% for setting in settings %}+ {{ render_setting(setting, form_id) }}+ {% endfor %}+ </div></div>{% endmacro %}-{% macro render_settings_form(settings_by_category, form_id, submit_url) %}- <form id="{{ form_id }}" action="{{ submit_url }}" method="POST">+{% macro render_settings_form(settings_by_category, form_id, form_action) %}+ <form id="{{ form_id }}" action="{{ form_action }}" method="POST" class="settings-form">{% for category, settings in settings_by_category.items() %}- {{ render_settings_section(category.replace('_', ' ').title(), settings) }}+ {{ render_settings_section(category, category|lower|replace(' ', '-'), settings, form_id) }}{% endfor %}-+<div class="form-actions">- <button type="submit" class="btn btn-primary">Save Settings</button>- <button type="button" class="btn btn-outline" onclick="window.location.reload()">Cancel</button>+ <button type="reset" class="btn btn-outline">+ <i class="fas fa-undo"></i> Reset Changes+ </button>+ <button type="submit" class="btn btn-primary">+ <i class="fas fa-save"></i> Save Changes+ </button></div></form>-{% endmacro %}\ No newline at end of file+{% endmacro %}diff --git a/src/local_deep_research/web/templates/llm_config.html b/src/local_deep_research/web/templates/llm_config.htmldeleted file mode 100644index 15da90a8c1..0000000000--- a/src/local_deep_research/web/templates/llm_config.html+++ /dev/null@@ -1,120 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - LLM Settings</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <!-- Sidebar content (keep as is) -->- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="llm-settings">- <div class="page-header">- <div class="results-header">- <h1>Language Model Configuration</h1>- <div class="results-actions">- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-- <div class="card">- <div class="card-content">- <h2>LLM Configuration File</h2>- <p>To edit your LLM configuration, open this file with your preferred text editor:</p>- <div class="file-path">{{ llm_file_path }}</div>-- <button onclick="openFileLocation('{{ llm_file_path }}')" class="btn btn-primary">- <i class="fas fa-folder-open"></i> Open Containing Folder- </button>-- <h3 class="mt-4">Default Configuration Example</h3>- <pre class="config-example">-"""-LLM configuration for Local Deep Research.--This file is loaded as a Python module, allowing for complex-customization of LLM behavior.-"""--# Default model settings-DEFAULT_MODEL = "mistral"-DEFAULT_MODEL_TYPE = "ollama" # Options: ollama, openai, anthropic-DEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 30000--# API keys and endpoints (consider using environment variables instead)-USE_OPENAI_ENDPOINT = False-OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"-OPENAI_ENDPOINT_REQUIRES_MODEL = True--# Custom model loading function-def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):- """- Get a language model instance.-- Args:- model_name: Name of the model to use- model_type: Type of model provider- temperature: Model temperature- **kwargs: Additional parameters-- Returns:- A LangChain language model instance- """- # Use defaults if not provided- model_name = model_name or DEFAULT_MODEL- model_type = model_type or DEFAULT_MODEL_TYPE- temperature = temperature or DEFAULT_TEMPERATURE-- # If using Ollama- if model_type == "ollama":- from langchain_ollama import ChatOllama- return ChatOllama(- model=model_name,- temperature=temperature,- **kwargs- )-- # Default fallback- from langchain_ollama import ChatOllama- return ChatOllama(- model="mistral",- temperature=0.7,- **kwargs- )- </pre>- </div>- </div>- </div>- </main>- </div>-- <script>- function openFileLocation(path) {- fetch('/research/open_file_location', {- method: 'POST',- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: 'file_path=' + encodeURIComponent(path)- })- .then(response => {- // Handle response- })- .catch(error => console.error('Error:', error));- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/llm_settings.html b/src/local_deep_research/web/templates/llm_settings.htmldeleted file mode 100644index 742cc25335..0000000000--- a/src/local_deep_research/web/templates/llm_settings.html+++ /dev/null@@ -1,76 +0,0 @@-{% extends "base.html" %}-{% from "components/settings_form.html" import render_settings_form, render_settings_section, render_setting %}--{% set active_page = 'settings' %}--{% block title %}LLM Settings - Deep Research System{% endblock %}--{% block content %}-<div class="page active" id="settings">- <div class="page-header">- <h1>Language Model Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="card">- <div class="card-content">- {{ render_settings_form(settings_by_category, 'llm-settings-form', url_for('settings.llm_settings')) }}-- <div class="form-actions mt-4">- <a href="{{ url_for('settings.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- document.addEventListener('DOMContentLoaded', function() {- // Initialize sliders to display their values- const sliders = document.querySelectorAll('input[type="range"]');- sliders.forEach(slider => {- const valueDisplay = document.getElementById(`${slider.id}-value`);- if (valueDisplay) {- // Set initial value- valueDisplay.textContent = slider.value;-- // Update on input change- slider.addEventListener('input', () => {- valueDisplay.textContent = slider.value;- });- }- });-- // Add form submission handler- const form = document.getElementById('llm-settings-form');- if (form) {- form.addEventListener('submit', function(e) {- // Handle checkbox values- const checkboxes = form.querySelectorAll('input[type="checkbox"]');- checkboxes.forEach(checkbox => {- if (!checkbox.checked) {- // Create a hidden input to send the false value- const hiddenInput = document.createElement('input');- hiddenInput.type = 'hidden';- hiddenInput.name = checkbox.name;- hiddenInput.value = 'false';- form.appendChild(hiddenInput);- }- });- });- }- });-</script>-{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/main_config.html b/src/local_deep_research/web/templates/main_config.htmldeleted file mode 100644index 035b4cf651..0000000000--- a/src/local_deep_research/web/templates/main_config.html+++ /dev/null@@ -1,89 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - Search Settings</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <!-- Sidebar content (keep as is) -->- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="settings">- <div class="page-header">- <div class="results-header">- <h1>Search Settings</h1>- <div class="results-actions">- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-- <div class="card">- <div class="card-content">- <h2>Main Configuration File</h2>- <p>To edit your main configuration, open this file with your preferred text editor:</p>- <div class="file-path">{{ main_file_path }}</div>-- <button onclick="openFileLocation('{{ main_file_path }}')" class="btn btn-primary">- <i class="fas fa-folder-open"></i> Open Containing Folder- </button>-- <h3 class="mt-4">Default Configuration Example</h3>- <pre class="config-example">-[general]-output_dir = "research_outputs"-knowledge_accumulation = "ITERATION"-knowledge_accumulation_context_limit = 500000-enable_fact_checking = true--[search]-tool = "auto"-iterations = 3-questions_per_iteration = 3-searches_per_section = 2-max_results = 10-max_filtered_results = 5-region = "us"-time_period = "a"-search_language = "en"-safe_search = true-quality_check_urls = true-snippets_only = false-skip_relevance_filter = false- </pre>- </div>- </div>- </div>- </main>- </div>-- <script>- function openFileLocation(filePath) {- // Create a hidden form and submit it to a route that will open the file location- const form = document.createElement('form');- form.method = 'POST';- form.action = "{{ url_for('research.open_file_location') }}";-- const input = document.createElement('input');- input.type = 'hidden';- input.name = 'file_path';- input.value = filePath;-- form.appendChild(input);- document.body.appendChild(form);- form.submit();- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex af2d1f1314..50b1585701 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -1,9 +1,14 @@{% extends "base.html" %}+{% from "components/custom_dropdown.html" import render_dropdown %}{% set active_page = 'new-research' %}{% block title %}New Research - Deep Research System{% endblock %}+{% block extra_head %}+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/custom_dropdown.css') }}">+{% endblock %}+{% block content %}<div class="page active" id="new-research"><div class="page-header">@@ -65,34 +70,24 @@<div class="form-row"><!-- Model Selection --><div class="form-group half">- <label for="model">Language Model</label>- <div class="custom-dropdown" id="model-dropdown">- <input type="text"- id="model"- name="model"- class="custom-dropdown-input"- placeholder="Enter or select a model"- autocomplete="off"- aria-haspopup="listbox">- <div class="custom-dropdown-list" id="model-dropdown-list"></div>- </div>- <span class="input-help">Select or enter a custom model name</span>+ {{ render_dropdown(+ input_id="model",+ dropdown_id="model-dropdown",+ placeholder="Enter or select a model",+ label="Language Model",+ help_text="Select or enter a custom model name"+ ) }}</div><!-- Search Engine Selection --><div class="form-group half">- <label for="search_engine">Search Engine</label>- <div class="custom-dropdown" id="search-engine-dropdown">- <input type="text"- id="search_engine"- name="search_engine"- class="custom-dropdown-input"- placeholder="Select a search engine"- autocomplete="off"- aria-haspopup="listbox">- <div class="custom-dropdown-list" id="search-engine-dropdown-list"></div>- </div>- <span class="input-help">Select the search engine to use for research</span>+ {{ render_dropdown(+ input_id="search_engine",+ dropdown_id="search-engine-dropdown",+ placeholder="Select a search engine",+ label="Search Engine",+ help_text="Select the search engine to use for research"+ ) }}</div></div>@@ -132,5 +127,6 @@{% endblock %}{% block component_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/custom_dropdown.js') }}"></script><script src="{{ url_for('research.serve_static', path='js/components/research.js') }}"></script>{% endblock %}diff --git a/src/local_deep_research/web/templates/report_settings.html b/src/local_deep_research/web/templates/report_settings.htmldeleted file mode 100644index ea18416627..0000000000--- a/src/local_deep_research/web/templates/report_settings.html+++ /dev/null@@ -1,76 +0,0 @@-{% extends "base.html" %}-{% from "components/settings_form.html" import render_settings_form, render_settings_section, render_setting %}--{% set active_page = 'settings' %}--{% block title %}Report Settings - Deep Research System{% endblock %}--{% block content %}-<div class="page active" id="settings">- <div class="page-header">- <h1>Report Generation Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="card">- <div class="card-content">- {{ render_settings_form(settings_by_category, 'report-settings-form', url_for('settings.report_settings')) }}-- <div class="form-actions mt-4">- <a href="{{ url_for('settings.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- document.addEventListener('DOMContentLoaded', function() {- // Initialize sliders to display their values- const sliders = document.querySelectorAll('input[type="range"]');- sliders.forEach(slider => {- const valueDisplay = document.getElementById(`${slider.id}-value`);- if (valueDisplay) {- // Set initial value- valueDisplay.textContent = slider.value;-- // Update on input change- slider.addEventListener('input', () => {- valueDisplay.textContent = slider.value;- });- }- });-- // Add form submission handler- const form = document.getElementById('report-settings-form');- if (form) {- form.addEventListener('submit', function(e) {- // Handle checkbox values- const checkboxes = form.querySelectorAll('input[type="checkbox"]');- checkboxes.forEach(checkbox => {- if (!checkbox.checked) {- // Create a hidden input to send the false value- const hiddenInput = document.createElement('input');- hiddenInput.type = 'hidden';- hiddenInput.name = checkbox.name;- hiddenInput.value = 'false';- form.appendChild(hiddenInput);- }- });- });- }- });-</script>-{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/search_engines_config.html b/src/local_deep_research/web/templates/search_engines_config.htmldeleted file mode 100644index 4fc213dadd..0000000000--- a/src/local_deep_research/web/templates/search_engines_config.html+++ /dev/null@@ -1,154 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - Search Engines</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <!-- Sidebar content (keep as is) -->- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="search-engines-settings">- <div class="page-header">- <div class="results-header">- <h1>Search Engines Configuration</h1>- <div class="results-actions">- <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-- <div class="card">- <div class="card-content">- <h2>Search Engines Configuration File</h2>- <p>To edit your search engines configuration, open this file with your preferred text editor:</p>- <div class="file-path">{{ search_engines_file_path }}</div>-- <button onclick="openFileLocation('{{ search_engines_file_path }}')" class="btn btn-primary">- <i class="fas fa-folder-open"></i> Open Containing Folder- </button>-- <h3 class="mt-4">Edit Raw Configuration</h3>- <div id="editor-container">- <div class="editor-header">- <h3>Search Engines Configuration (TOML format)</h3>- <span class="editor-lang">TOML</span>- </div>- <textarea id="raw_config_editor" class="config-raw-editor" rows="25">{{ raw_config }}</textarea>- <div class="form-actions">- <button type="button" class="btn btn-primary" onclick="saveRawConfig()">- <i class="fas fa-save"></i> Save Configuration- </button>- <button type="button" class="btn btn-outline" onclick="resetEditor()">- <i class="fas fa-undo"></i> Reset Changes- </button>- </div>- </div>-- <h3 class="mt-4">Structure Reference</h3>- <p>Search engines are defined in TOML format with the following structure:</p>- <pre class="config-example">-# Define a search engine named "example_engine"-[example_engine]-module_path = "local_deep_research.web_search_engines.engines.search_engine_example"-class_name = "ExampleSearchEngine"-requires_api_key = false # or true if API key is required-reliability = 0.9 # Value between 0 and 1-strengths = ["strength1", "strength2"] # Array of strengths-weaknesses = ["weakness1", "weakness2"] # Array of weaknesses-supports_full_search = true # Whether this engine supports retrieving full content--# Optional: Define which API key environment variable to use-api_key_env = "EXAMPLE_API_KEY" # Only needed if requires_api_key is true--# Default parameters for this search engine-[example_engine.default_params]-max_results = 20-param1 = "value1"-param2 = true--# Special setting to define the default search engine-DEFAULT_SEARCH_ENGINE = "wikipedia"- </pre>-- <h3 class="mt-4">Available Search Engines</h3>- <p>The following search engines are currently defined:</p>- <ul id="available-engines">- {% for engine_name in engine_names %}- <li><strong>{{ engine_name }}</strong></li>- {% endfor %}- </ul>-- <div class="alert alert-info mt-4">- <i class="fas fa-info-circle"></i> Changes to search engines configuration will take effect after restarting the application.- </div>- </div>- </div>- </div>- </main>- </div>-- <script>- // Original config for reset functionality- const originalConfig = document.getElementById('raw_config_editor').value;-- function openFileLocation(filePath) {- // Create a hidden form and submit it to a route that will open the file location- const form = document.createElement('form');- form.method = 'POST';- form.action = "{{ url_for('research.open_file_location') }}";-- const input = document.createElement('input');- input.type = 'hidden';- input.name = 'file_path';- input.value = filePath;-- form.appendChild(input);- document.body.appendChild(form);- form.submit();- }-- function resetEditor() {- if (confirm('Are you sure you want to reset all changes?')) {- document.getElementById('raw_config_editor').value = originalConfig;- }- }-- function saveRawConfig() {- const rawConfig = document.getElementById('raw_config_editor').value;-- fetch('{{ url_for("research.save_search_engines_config") }}', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({ raw_config: rawConfig }),- })- .then(response => response.json())- .then(data => {- if (data.success) {- alert('Configuration saved successfully. Changes will take effect after restarting the application.');- // Reload the page to refresh the content- window.location.reload();- } else {- alert('Error saving configuration: ' + data.error);- }- })- .catch(error => {- alert('Error saving configuration: ' + error);- });- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/search_settings.html b/src/local_deep_research/web/templates/search_settings.htmldeleted file mode 100644index 56a09cf681..0000000000--- a/src/local_deep_research/web/templates/search_settings.html+++ /dev/null@@ -1,76 +0,0 @@-{% extends "base.html" %}-{% from "components/settings_form.html" import render_settings_form, render_settings_section, render_setting %}--{% set active_page = 'settings' %}--{% block title %}Search Settings - Deep Research System{% endblock %}--{% block content %}-<div class="page active" id="settings">- <div class="page-header">- <h1>Search Engine Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="card">- <div class="card-content">- {{ render_settings_form(settings_by_category, 'search-settings-form', url_for('settings.search_settings')) }}-- <div class="form-actions mt-4">- <a href="{{ url_for('settings.settings_page') }}" class="btn btn-outline">- <i class="fas fa-arrow-left"></i> Back to Settings- </a>- </div>- </div>- </div>-</div>-{% endblock %}--{% block scripts %}-<script>- document.addEventListener('DOMContentLoaded', function() {- // Initialize sliders to display their values- const sliders = document.querySelectorAll('input[type="range"]');- sliders.forEach(slider => {- const valueDisplay = document.getElementById(`${slider.id}-value`);- if (valueDisplay) {- // Set initial value- valueDisplay.textContent = slider.value;-- // Update on input change- slider.addEventListener('input', () => {- valueDisplay.textContent = slider.value;- });- }- });-- // Add form submission handler- const form = document.getElementById('search-settings-form');- if (form) {- form.addEventListener('submit', function(e) {- // Handle checkbox values- const checkboxes = form.querySelectorAll('input[type="checkbox"]');- checkboxes.forEach(checkbox => {- if (!checkbox.checked) {- // Create a hidden input to send the false value- const hiddenInput = document.createElement('input');- hiddenInput.type = 'hidden';- hiddenInput.name = checkbox.name;- hiddenInput.value = 'false';- form.appendChild(hiddenInput);- }- });- });- }- });-</script>-{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/settings.html b/src/local_deep_research/web/templates/settings.htmldeleted file mode 100644index e084103e45..0000000000--- a/src/local_deep_research/web/templates/settings.html+++ /dev/null@@ -1,519 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - Settings</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">- <style>- .settings-section {- margin-bottom: 2rem;- padding-bottom: 1.5rem;- border-bottom: 1px solid #333;- }- .settings-section h2 {- margin-bottom: 1rem;- color: #4a6cf7;- font-size: 1.3rem;- }- .form-group {- margin-bottom: 1rem;- }- .form-group label {- display: block;- margin-bottom: 0.5rem;- font-weight: 500;- }- .form-control {- width: 100%;- padding: 0.5rem;- border: 1px solid #333;- border-radius: 4px;- background-color: #1a1a1a;- color: #f8f9fa;- }- .form-row {- display: flex;- gap: 1rem;- }- .form-group.half {- flex: 1;- }- .input-help {- display: block;- font-size: 0.8rem;- color: #8a8a8a;- margin-top: 0.25rem;- }- .checkbox-group {- display: flex;- align-items: center;- gap: 0.5rem;- }- .checkbox-group input {- margin: 0;- }- .checkbox-group label {- margin: 0;- }- .form-actions {- margin-top: 2rem;- display: flex;- gap: 1rem;- }- .range-value {- display: inline-block;- margin-left: 0.5rem;- }- .config-raw {- margin-top: 2rem;- background-color: #0a0a0a;- padding: 1rem;- border-radius: 4px;- overflow: auto;- font-family: monospace;- font-size: 0.9rem;- color: #e6e6e6;- white-space: pre;- min-height: 200px;- max-height: 600px;- border: 1px solid #333;- }- .toggle-raw-config {- cursor: pointer;- display: flex;- align-items: center;- gap: 0.5rem;- margin-top: 2rem;- margin-bottom: 1rem;- color: #4a6cf7;- font-weight: 500;- padding: 0.5rem 1rem;- background-color: rgba(74, 108, 247, 0.1);- border-radius: 4px;- width: fit-content;- }- .toggle-raw-config:hover {- background-color: rgba(74, 108, 247, 0.2);- }- .config-raw-editor {- background-color: #0a0a0a;- color: #e6e6e6;- font-family: monospace;- font-size: 0.9rem;- padding: 1rem;- border: 1px solid #333;- border-radius: 4px;- width: 100%;- min-height: 400px;- resize: vertical;- display: block !important;- }- .alert {- padding: 0.75rem 1.25rem;- margin-bottom: 1rem;- border: 1px solid transparent;- border-radius: 0.25rem;- }- .alert-success {- color: #d4edda;- background-color: #1e462e;- border-color: #c3e6cb;- }- .alert-error {- color: #f8d7da;- background-color: #462c2e;- border-color: #f5c6cb;- }- .editor-header {- background-color: var(--bg-tertiary);- padding: 0.75rem 1rem;- border-bottom: 1px solid var(--border-color);- display: flex;- justify-content: space-between;- align-items: center;- }- .editor-header h3 {- margin: 0;- font-size: 1rem;- color: var(--text-primary);- }- .editor-lang {- background-color: var(--accent-primary);- font-size: 0.8rem;- padding: 0.25rem 0.5rem;- border-radius: 4px;- }- </style>-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <div class="sidebar-header">- <h2 id="logo-link" style="cursor: pointer;"><i class="fas fa-atom"></i> Deep Research</h2>- </div>- <nav class="sidebar-nav">- <ul>- <li data-page="new-research"><i class="fas fa-search"></i> <a href="{{ url_for('research.index') }}">New Research</a></li>- <li data-page="history"><i class="fas fa-history"></i> <a href="{{ url_for('research.index') }}#history">History</a></li>- <li class="active" data-page="settings"><i class="fas fa-cog"></i> Settings</li>- </ul>- </nav>- <div class="sidebar-footer">- <p>v0.0.1 | <i class="fas fa-brain"></i></p>- </div>- </aside>-- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="settings">- <div class="page-header">- <h1>Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="card">- <div class="card-content">- <form method="POST" action="{{ url_for('research.settings_page') }}">- <!-- LLM Settings Section -->- <div class="settings-section">- <h2><i class="fas fa-brain"></i> LLM Settings</h2>- <div class="form-group">- <label for="DEFAULT_MODEL">Default Model</label>- <select id="DEFAULT_MODEL" name="DEFAULT_MODEL" class="form-control">- <option value="mistral" {% if config.DEFAULT_MODEL == "mistral" %}selected{% endif %}>Mistral (Default)</option>- <option value="llama3" {% if config.DEFAULT_MODEL == "llama3" %}selected{% endif %}>Llama3</option>- <option value="mixtral" {% if config.DEFAULT_MODEL == "mixtral" %}selected{% endif %}>Mixtral</option>- <option value="mpt-7b" {% if config.DEFAULT_MODEL == "mpt-7b" %}selected{% endif %}>MPT-7B</option>- <option value="gpt-4o" {% if config.DEFAULT_MODEL == "gpt-4o" %}selected{% endif %}>GPT-4o (requires API key)</option>- <option value="gpt-3.5-turbo" {% if config.DEFAULT_MODEL == "gpt-3.5-turbo" %}selected{% endif %}>GPT-3.5 Turbo (requires API key)</option>- <option value="claude-3-5-sonnet-latest" {% if config.DEFAULT_MODEL == "claude-3-5-sonnet-latest" %}selected{% endif %}>Claude (requires API key)</option>- </select>- <span class="input-help">Select the default language model to use for analysis</span>- </div>- <div class="form-group">- <label for="DEFAULT_TEMPERATURE">Temperature</label>- <input type="range" min="0" max="1" step="0.1" class="form-control" id="DEFAULT_TEMPERATURE" name="DEFAULT_TEMPERATURE" value="{{ config.DEFAULT_TEMPERATURE }}">- <span class="range-value" id="temp-value">{{ config.DEFAULT_TEMPERATURE }}</span>- <span class="input-help">Higher values = more creative, lower values = more deterministic</span>- </div>- <div class="form-group">- <label for="MAX_TOKENS">Max Tokens</label>- <input type="number" min="1000" max="100000" step="1000" class="form-control" id="MAX_TOKENS" name="MAX_TOKENS" value="{{ config.MAX_TOKENS }}">- <span class="input-help">Maximum tokens for model output</span>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="OPENAIENDPOINT" name="OPENAIENDPOINT" {% if config.OPENAIENDPOINT %}checked{% endif %}>- <label for="OPENAIENDPOINT">Use OpenAI endpoint</label>- </div>-- <div class="form-group">- <label for="OPENROUTER_BASE_URL">OpenRouter Base URL</label>- <input type="text" class="form-control" id="OPENROUTER_BASE_URL" name="OPENROUTER_BASE_URL" value="{{ config.OPENROUTER_BASE_URL }}">- <span class="input-help">Base URL for OpenRouter API</span>- </div>- </div>-- <!-- VLLM Settings Section -->- <div class="settings-section">- <h2><i class="fas fa-server"></i> VLLM Configuration</h2>- <div class="form-row">- <div class="form-group half">- <label for="VLLM_MAX_NEW_TOKENS">Max New Tokens</label>- <input type="number" min="1" max="1000" class="form-control" id="VLLM_MAX_NEW_TOKENS" name="VLLM_MAX_NEW_TOKENS" value="{{ config.VLLM_MAX_NEW_TOKENS }}">- <span class="input-help">Maximum new tokens for VLLM models</span>- </div>- <div class="form-group half">- <label for="VLLM_TOP_K">Top K</label>- <input type="number" min="1" max="100" class="form-control" id="VLLM_TOP_K" name="VLLM_TOP_K" value="{{ config.VLLM_TOP_K }}">- <span class="input-help">Top K sampling parameter</span>- </div>- </div>- <div class="form-row">- <div class="form-group half">- <label for="VLLM_TOP_P">Top P</label>- <input type="range" min="0" max="1" step="0.01" class="form-control" id="VLLM_TOP_P" name="VLLM_TOP_P" value="{{ config.VLLM_TOP_P }}">- <span class="range-value" id="top-p-value">{{ config.VLLM_TOP_P }}</span>- <span class="input-help">Top P sampling parameter</span>- </div>- <div class="form-group half">- <label for="VLLM_TEMPERATURE">VLLM Temperature</label>- <input type="range" min="0" max="1" step="0.1" class="form-control" id="VLLM_TEMPERATURE" name="VLLM_TEMPERATURE" value="{{ config.VLLM_TEMPERATURE }}">- <span class="range-value" id="vllm-temp-value">{{ config.VLLM_TEMPERATURE }}</span>- <span class="input-help">Temperature for VLLM models</span>- </div>- </div>- </div>-- <!-- Search Settings Section -->- <div class="settings-section">- <h2><i class="fas fa-search"></i> Search Settings</h2>- <div class="form-group">- <label for="search_tool">Default Search Engine</label>- <select id="search_tool" name="search_tool" class="form-control">- <option value="auto" {% if config.search_tool == "auto" %}selected{% endif %}>Auto (Intelligent selection)</option>- <option value="wikipedia" {% if config.search_tool == "wikipedia" %}selected{% endif %}>Wikipedia</option>- <option value="arxiv" {% if config.search_tool == "arxiv" %}selected{% endif %}>arXiv (scientific papers)</option>- <option value="pubmed" {% if config.search_tool == "pubmed" %}selected{% endif %}>PubMed (medical research)</option>- <option value="duckduckgo" {% if config.search_tool == "duckduckgo" %}selected{% endif %}>DuckDuckGo (web search)</option>- <option value="serp" {% if config.search_tool == "serp" %}selected{% endif %}>SerpAPI (Google, requires API key)</option>- <option value="google_pse" {% if config.search_tool == "google_pse" %}selected{% endif %}>Google PSE (requires API key)</option>- <option value="guardian" {% if config.search_tool == "guardian" %}selected{% endif %}>Guardian (news, requires API key)</option>- <option value="local_all" {% if config.search_tool == "local_all" %}selected{% endif %}>Local Documents</option>- </select>- <span class="input-help">Choose your primary search and research source</span>- </div>-- <div class="form-row">- <div class="form-group half">- <label for="SEARCH_ITERATIONS">Search Iterations</label>- <input type="number" min="1" max="5" class="form-control" id="SEARCH_ITERATIONS" name="SEARCH_ITERATIONS" value="{{ config.SEARCH_ITERATIONS }}">- <span class="input-help">Number of research cycles to perform</span>- </div>- <div class="form-group half">- <label for="QUESTIONS_PER_ITERATION">Questions Per Iteration</label>- <input type="number" min="1" max="10" class="form-control" id="QUESTIONS_PER_ITERATION" name="QUESTIONS_PER_ITERATION" value="{{ config.QUESTIONS_PER_ITERATION }}">- <span class="input-help">Follow-up questions in each cycle</span>- </div>- </div>-- <div class="form-row">- <div class="form-group half">- <label for="MAX_SEARCH_RESULTS">Maximum Search Results</label>- <input type="number" min="5" max="100" class="form-control" id="MAX_SEARCH_RESULTS" name="MAX_SEARCH_RESULTS" value="{{ config.MAX_SEARCH_RESULTS }}">- <span class="input-help">Higher values give more comprehensive research but take longer</span>- </div>-- <div class="form-group half">- <label for="MAX_FILTERED_RESULTS">Maximum Filtered Results</label>- <input type="number" min="1" max="20" class="form-control" id="MAX_FILTERED_RESULTS" name="MAX_FILTERED_RESULTS" value="{{ config.MAX_FILTERED_RESULTS }}">- <span class="input-help">Results kept after relevance filtering</span>- </div>- </div>-- <div class="form-group">- <label for="KNOWLEDGE_ACCUMULATION">Knowledge Accumulation</label>- <select id="KNOWLEDGE_ACCUMULATION" name="KNOWLEDGE_ACCUMULATION" class="form-control">- <option value="ITERATION" {% if config.KNOWLEDGE_ACCUMULATION == "ITERATION" %}selected{% endif %}>Iteration-based</option>- <option value="NONE" {% if config.KNOWLEDGE_ACCUMULATION == "NONE" %}selected{% endif %}>None</option>- </select>- <span class="input-help">How to accumulate knowledge during research</span>- </div>-- <div class="form-group">- <label for="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT">Knowledge Accumulation Context Limit</label>- <input type="number" class="form-control" id="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" name="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" value="{{ config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT }}">- <span class="input-help">Maximum context size for knowledge accumulation</span>- </div>-- <div class="form-row">- <div class="form-group half">- <label for="SEARCH_REGION">Search Region</label>- <input type="text" class="form-control" id="SEARCH_REGION" name="SEARCH_REGION" value="{{ config.SEARCH_REGION }}">- <span class="input-help">Region code for search (e.g., us, uk, de)</span>- </div>- <div class="form-group half">- <label for="TIME_PERIOD">Time Period</label>- <select id="TIME_PERIOD" name="TIME_PERIOD" class="form-control">- <option value="d" {% if config.TIME_PERIOD == "d" %}selected{% endif %}>Past day</option>- <option value="w" {% if config.TIME_PERIOD == "w" %}selected{% endif %}>Past week</option>- <option value="m" {% if config.TIME_PERIOD == "m" %}selected{% endif %}>Past month</option>- <option value="y" {% if config.TIME_PERIOD == "y" %}selected{% endif %}>Past year</option>- <option value="a" {% if config.TIME_PERIOD == "a" %}selected{% endif %}>All time</option>- </select>- <span class="input-help">Time period for search results</span>- </div>- </div>-- <div class="form-group">- <label for="SEARCH_LANGUAGE">Search Language</label>- <input type="text" class="form-control" id="SEARCH_LANGUAGE" name="SEARCH_LANGUAGE" value="{{ config.SEARCH_LANGUAGE }}">- <span class="input-help">Language for search results</span>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="SAFE_SEARCH" name="SAFE_SEARCH" {% if config.SAFE_SEARCH %}checked{% endif %}>- <label for="SAFE_SEARCH">Safe Search</label>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="QUALITY_CHECK_DDG_URLS" name="QUALITY_CHECK_DDG_URLS" {% if config.QUALITY_CHECK_DDG_URLS %}checked{% endif %}>- <label for="QUALITY_CHECK_DDG_URLS">Quality check URLs</label>- <span class="input-help">Enable quality filtering for search results</span>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="SEARCH_SNIPPETS_ONLY" name="SEARCH_SNIPPETS_ONLY" {% if config.SEARCH_SNIPPETS_ONLY %}checked{% endif %}>- <label for="SEARCH_SNIPPETS_ONLY">Use search snippets only (faster but less detailed)</label>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="SKIP_RELEVANCE_FILTER" name="SKIP_RELEVANCE_FILTER" {% if config.SKIP_RELEVANCE_FILTER %}checked{% endif %}>- <label for="SKIP_RELEVANCE_FILTER">Skip relevance filtering (return all results)</label>- </div>- </div>-- <!-- Report Settings Section -->- <div class="settings-section">- <h2><i class="fas fa-file-alt"></i> Report Settings</h2>- <div class="form-group">- <label for="SEARCHES_PER_SECTION">Searches Per Report Section</label>- <input type="number" min="1" max="5" class="form-control" id="SEARCHES_PER_SECTION" name="SEARCHES_PER_SECTION" value="{{ config.SEARCHES_PER_SECTION }}">- <span class="input-help">Number of searches to run per report section</span>- </div>-- <div class="form-group checkbox-group">- <input type="checkbox" id="ENABLE_FACT_CHECKING" name="ENABLE_FACT_CHECKING" {% if config.ENABLE_FACT_CHECKING %}checked{% endif %}>- <label for="ENABLE_FACT_CHECKING">Enable fact checking (may work better with large LLMs)</label>- </div>-- <div class="form-group">- <label for="OUTPUT_DIR">Output Directory</label>- <input type="text" class="form-control" id="OUTPUT_DIR" name="OUTPUT_DIR" value="{{ config.OUTPUT_DIR }}">- <span class="input-help">Directory to save research outputs</span>- </div>- </div>-- <div class="form-actions">- <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Settings</button>- <a href="{{ url_for('research.index') }}" class="btn btn-outline"><i class="fas fa-times"></i> Cancel</a>- </div>- </form>-- <div class="toggle-raw-config" onclick="toggleRawConfig()">- <i class="fas fa-code"></i> <span id="toggle-text">Show Raw Configuration</span>- </div>-- <div id="raw-config" class="config-raw" style="display: none;">- {{ raw_config|safe }}- </div>-- <!-- Raw Configuration Editing -->- <div id="raw-config-editor-container" style="display: none; margin-top: 1rem;">- <div class="editor-header">- <h3>Edit Raw Configuration</h3>- <span class="editor-lang">TOML</span>- </div>- <textarea id="raw_config_editor" name="raw_config_editor" class="config-raw-editor" rows="20">{{ raw_config|safe }}</textarea>- <div class="form-actions">- <button type="button" class="btn btn-primary" onclick="saveRawConfig()"><i class="fas fa-save"></i> Save Raw Configuration</button>- <button type="button" class="btn btn-outline" onclick="cancelRawEdit()"><i class="fas fa-times"></i> Cancel</button>- </div>- </div>- </div>- </div>- </div>- </main>- </div>-- <!-- Mobile Tab Bar -->- <nav class="mobile-tab-bar">- <ul>- <li data-page="new-research">- <a href="{{ url_for('research.index') }}">- <i class="fas fa-search"></i>- <span>Research</span>- </a>- </li>- <li data-page="history">- <a href="{{ url_for('research.index') }}#history">- <i class="fas fa-history"></i>- <span>History</span>- </a>- </li>- <li class="active" data-page="settings">- <i class="fas fa-cog"></i>- <span>Settings</span>- </li>- </ul>- </nav>-- <script>- // Update temperature display value- document.getElementById('DEFAULT_TEMPERATURE').addEventListener('input', function() {- document.getElementById('temp-value').textContent = this.value;- });-- // Update VLLM temperature display value- document.getElementById('VLLM_TEMPERATURE').addEventListener('input', function() {- document.getElementById('vllm-temp-value').textContent = this.value;- });-- // Update Top P display value- document.getElementById('VLLM_TOP_P').addEventListener('input', function() {- document.getElementById('top-p-value').textContent = this.value;- });-- // Make the logo clickable to go back to home- document.getElementById('logo-link').addEventListener('click', function() {- window.location.href = "{{ url_for('research.index') }}";- });-- // Toggle raw configuration display- function toggleRawConfig() {- const rawConfig = document.getElementById('raw-config');- const editorContainer = document.getElementById('raw-config-editor-container');- const toggleText = document.getElementById('toggle-text');-- if (rawConfig.style.display === 'none') {- rawConfig.style.display = 'block';- editorContainer.style.display = 'block';- toggleText.textContent = 'Hide Raw Configuration';- } else {- rawConfig.style.display = 'none';- editorContainer.style.display = 'none';- toggleText.textContent = 'Show Raw Configuration';- }- }-- function cancelRawEdit() {- const rawConfig = document.getElementById('raw-config');- const editorContainer = document.getElementById('raw-config-editor-container');- const toggleText = document.getElementById('toggle-text');-- rawConfig.style.display = 'none';- editorContainer.style.display = 'none';- toggleText.textContent = 'Show Raw Configuration';- }-- function saveRawConfig() {- const rawConfig = document.getElementById('raw_config_editor').value;-- fetch('{{ url_for("research.save_raw_config") }}', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({ raw_config: rawConfig }),- })- .then(response => response.json())- .then(data => {- if (data.success) {- alert('Configuration saved successfully. You may need to restart the application for changes to take effect.');- // Reload the page to show updated values- window.location.reload();- } else {- alert('Error saving configuration: ' + data.error);- }- })- .catch(error => {- alert('Error saving configuration: ' + error);- });- }- </script>-</body>-</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.htmlindex e08cad4237..4c5e646111 100644--- a/src/local_deep_research/web/templates/settings_dashboard.html+++ b/src/local_deep_research/web/templates/settings_dashboard.html@@ -1,245 +1,93 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Deep Research System - Settings</title>- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">- <style>- .settings-cards {- display: grid;- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));- gap: 1.5rem;- margin-top: 1.5rem;- }- .settings-card {- display: flex;- flex-direction: column;- height: 100%;- }- .settings-card .card-content {- display: flex;- flex-direction: column;- flex: 1;- }- .settings-icon {- font-size: 2rem;- color: var(--accent-primary);- margin-bottom: 1rem;- text-align: center;- }- .settings-title {- font-size: 1.25rem;- font-weight: 600;- margin-bottom: 0.75rem;- color: var(--text-primary);- }- .settings-description {- color: var(--text-secondary);- margin-bottom: 1.5rem;- flex: 1;- }- .card-actions {- margin-top: auto;- text-align: center;- }- </style>-</head>-<body>- <div class="app-container">- <!-- Sidebar -->- <aside class="sidebar">- <div class="sidebar-header">- <h2 id="logo-link" style="cursor: pointer;"><i class="fas fa-atom"></i> Deep Research</h2>- </div>- <nav class="sidebar-nav">- <ul>- <li data-page="new-research"><i class="fas fa-search"></i> <a href="{{ url_for('research.index') }}">New Research</a></li>- <li data-page="history"><i class="fas fa-history"></i> <a href="{{ url_for('research.index') }}#history">History</a></li>- <li class="active" data-page="settings"><i class="fas fa-cog"></i> Settings</li>- </ul>- </nav>- <div class="sidebar-footer">- <p>v0.1.0 | <i class="fas fa-brain"></i></p>- </div>- </aside>+{% extends "base.html" %}+{% from "components/settings_form.html" import render_setting %}+{% from "components/custom_dropdown.html" import render_dropdown %}- <!-- Main Content -->- <main class="main-content">- <div class="page active" id="settings">- <div class="page-header">- <h1>Settings</h1>- </div>-- {% with messages = get_flashed_messages(with_categories=true) %}- {% if messages %}- {% for category, message in messages %}- <div class="alert alert-{{ category }}">- {{ message }}- </div>- {% endfor %}- {% endif %}- {% endwith %}-- <div class="settings-cards">- <!-- Main Configuration Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-search"></i>- </div>- <h3 class="settings-title">Search Settings</h3>- <p class="settings-description">- Configure search parameters, results limits, general behavior, and output settings for the research system.- </p>- <div class="card-actions">- <a href="{{ url_for('research.main_config_page') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>- </div>- </div>+{% set active_page = 'settings' %}- <!-- LLM Configuration Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-brain"></i>- </div>- <h3 class="settings-title">Language Model Settings</h3>- <p class="settings-description">- Set up the language models used for research, including model selection, parameters, and API settings.- </p>- <div class="card-actions">- <a href="{{ url_for('settings.llm_settings') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>- </div>- </div>+{% block title %}Settings - Deep Research System{% endblock %}- <!-- Search Settings Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-search"></i>- </div>- <h3 class="settings-title">Search Engine Settings</h3>- <p class="settings-description">- Configure search engines, their parameters, and specify which search engines to use for different types of queries.- </p>- <div class="card-actions">- <a href="{{ url_for('settings.search_settings') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>- </div>+{% block extra_head %}+<meta name="csrf-token" content="{{ csrf_token() }}">+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/settings.css') }}">+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/custom_dropdown.css') }}">+{% endblock %}++{% block content %}+<div class="page active" id="settings">+ <div class="settings-container">+ <div class="page-header">+ <h1>Settings</h1>+ <p class="settings-description">+ Configure your research environment by adjusting the settings below. All settings are automatically saved when you make changes.+ </p>+ </div>++ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ {% for category, message in messages %}+ <div class="alert alert-{{ category }}">+ <i class="fas {% if category == 'success' %}fa-check-circle{% else %}fa-exclamation-circle{% endif %}"></i> {{ message }}</div>+ {% endfor %}+ {% endif %}+ {% endwith %}- <!-- Report Settings Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-file-alt"></i>- </div>- <h3 class="settings-title">Report Settings</h3>- <p class="settings-description">- Configure how research reports are generated, including formatting, citation style, and content organization.- </p>- <div class="card-actions">- <a href="{{ url_for('settings.report_settings') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>+ <div id="settings-alert" style="display:none"></div>++ <div class="card">+ <div class="card-content">+ <div class="search-controls">+ <input type="text" id="settings-search" class="search-input" placeholder="Search settings by name, description or category...">+ </div>++ <div class="settings-tabs">+ <div class="settings-tab active" data-tab="all">All Settings</div>+ <div class="settings-tab" data-tab="llm">Language Models</div>+ <div class="settings-tab" data-tab="search">Search Engines</div>+ <div class="settings-tab" data-tab="report">Reports</div>+ <div class="settings-tab" data-tab="app">Application</div>+ </div>++ <form id="settings-form" class="settings-form">+ <div id="settings-content">+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ <p>Loading settings...</p></div></div>- <!-- Application Settings Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-cogs"></i>- </div>- <h3 class="settings-title">Application Settings</h3>- <p class="settings-description">- Configure general application settings like notifications, UI preferences, and default research parameters.- </p>- <div class="card-actions">- <a href="{{ url_for('settings.app_settings') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>- </div>+ <div class="toggle-raw-config" id="toggle-raw-config">+ <i class="fas fa-code"></i> <span id="toggle-text">Show JSON Configuration</span></div>- <!-- Local Collections Card -->- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-folder"></i>- </div>- <h3 class="settings-title">Local Document Collections</h3>- <p class="settings-description">- Configure local document collections to search through your own files, papers, and research materials.+ <div id="raw-config" class="raw-config-section" style="display: none;">+ <div class="section-header">+ <h3>Advanced JSON Configuration</h3>+ <p class="section-description">+ Use this editor to directly modify configuration values. You can add new parameters not shown in the UI, and they will be preserved across saves. Changes here override the UI settings.</p>- <div class="card-actions">- <a href="{{ url_for('research.collections_config_page') }}" class="btn btn-primary">- <i class="fas fa-code"></i> Edit Configuration- </a>- </div>+ </div>+ <div id="json-editor-container">+ <textarea id="raw_config_editor" class="json-editor"></textarea></div></div>- <div class="card settings-card">- <div class="card-content">- <div class="settings-icon">- <i class="fas fa-key"></i>- </div>- <h3 class="settings-title">API Keys</h3>- <p class="settings-description">- Configure API keys for external services like OpenAI, Anthropic, and search providers.- </p>- <div class="card-actions">- <a href="{{ url_for('research.api_keys_config_page') }}" class="btn btn-primary">- <i class="fas fa-cog"></i> Configure- </a>- </div>- </div>+ <div class="form-actions">+ <button type="button" id="reset-to-defaults-button" class="btn btn-warning">+ <i class="fas fa-sync-alt"></i> Reset to Defaults+ </button>+ <button type="submit" class="btn btn-primary">+ <i class="fas fa-save"></i> Save All Settings+ </button></div>- </div>+ </form></div>- </main>+ </div></div>+</div>+{% endblock %}- <!-- Mobile Tab Bar -->- <nav class="mobile-tab-bar">- <ul>- <li data-page="new-research">- <a href="{{ url_for('research.index') }}">- <i class="fas fa-search"></i>- <span>Research</span>- </a>- </li>- <li data-page="history">- <a href="{{ url_for('research.index') }}#history">- <i class="fas fa-history"></i>- <span>History</span>- </a>- </li>- <li class="active" data-page="settings">- <i class="fas fa-cog"></i>- <span>Settings</span>- </li>- </ul>- </nav>-- <script>- // Make the logo clickable to go back to home- document.getElementById('logo-link').addEventListener('click', function() {- window.location.href = "{{ url_for('research.index') }}";- });- </script>-</body>-</html>+{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/custom_dropdown.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/components/settings.js') }}"></script>+{% endblock %}